]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/decl.go
go/types, types2: use zero error code to indicate unset error code
[gostls13.git] / src / cmd / compile / internal / types2 / decl.go
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package types2
6
7 import (
8         "bytes"
9         "cmd/compile/internal/syntax"
10         "fmt"
11         "go/constant"
12         . "internal/types/errors"
13 )
14
15 func (err *error_) recordAltDecl(obj Object) {
16         if pos := obj.Pos(); pos.IsKnown() {
17                 // We use "other" rather than "previous" here because
18                 // the first declaration seen may not be textually
19                 // earlier in the source.
20                 err.errorf(pos, "other declaration of %s", obj.Name())
21         }
22 }
23
24 func (check *Checker) declare(scope *Scope, id *syntax.Name, obj Object, pos syntax.Pos) {
25         // spec: "The blank identifier, represented by the underscore
26         // character _, may be used in a declaration like any other
27         // identifier but the declaration does not introduce a new
28         // binding."
29         if obj.Name() != "_" {
30                 if alt := scope.Insert(obj); alt != nil {
31                         var err error_
32                         err.code = DuplicateDecl
33                         err.errorf(obj, "%s redeclared in this block", obj.Name())
34                         err.recordAltDecl(alt)
35                         check.report(&err)
36                         return
37                 }
38                 obj.setScopePos(pos)
39         }
40         if id != nil {
41                 check.recordDef(id, obj)
42         }
43 }
44
45 // pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
46 func pathString(path []Object) string {
47         var s string
48         for i, p := range path {
49                 if i > 0 {
50                         s += "->"
51                 }
52                 s += p.Name()
53         }
54         return s
55 }
56
57 // objDecl type-checks the declaration of obj in its respective (file) environment.
58 // For the meaning of def, see Checker.definedType, in typexpr.go.
59 func (check *Checker) objDecl(obj Object, def *Named) {
60         if check.conf.Trace && obj.Type() == nil {
61                 if check.indent == 0 {
62                         fmt.Println() // empty line between top-level objects for readability
63                 }
64                 check.trace(obj.Pos(), "-- checking %s (%s, objPath = %s)", obj, obj.color(), pathString(check.objPath))
65                 check.indent++
66                 defer func() {
67                         check.indent--
68                         check.trace(obj.Pos(), "=> %s (%s)", obj, obj.color())
69                 }()
70         }
71
72         // Checking the declaration of obj means inferring its type
73         // (and possibly its value, for constants).
74         // An object's type (and thus the object) may be in one of
75         // three states which are expressed by colors:
76         //
77         // - an object whose type is not yet known is painted white (initial color)
78         // - an object whose type is in the process of being inferred is painted grey
79         // - an object whose type is fully inferred is painted black
80         //
81         // During type inference, an object's color changes from white to grey
82         // to black (pre-declared objects are painted black from the start).
83         // A black object (i.e., its type) can only depend on (refer to) other black
84         // ones. White and grey objects may depend on white and black objects.
85         // A dependency on a grey object indicates a cycle which may or may not be
86         // valid.
87         //
88         // When objects turn grey, they are pushed on the object path (a stack);
89         // they are popped again when they turn black. Thus, if a grey object (a
90         // cycle) is encountered, it is on the object path, and all the objects
91         // it depends on are the remaining objects on that path. Color encoding
92         // is such that the color value of a grey object indicates the index of
93         // that object in the object path.
94
95         // During type-checking, white objects may be assigned a type without
96         // traversing through objDecl; e.g., when initializing constants and
97         // variables. Update the colors of those objects here (rather than
98         // everywhere where we set the type) to satisfy the color invariants.
99         if obj.color() == white && obj.Type() != nil {
100                 obj.setColor(black)
101                 return
102         }
103
104         switch obj.color() {
105         case white:
106                 assert(obj.Type() == nil)
107                 // All color values other than white and black are considered grey.
108                 // Because black and white are < grey, all values >= grey are grey.
109                 // Use those values to encode the object's index into the object path.
110                 obj.setColor(grey + color(check.push(obj)))
111                 defer func() {
112                         check.pop().setColor(black)
113                 }()
114
115         case black:
116                 assert(obj.Type() != nil)
117                 return
118
119         default:
120                 // Color values other than white or black are considered grey.
121                 fallthrough
122
123         case grey:
124                 // We have a (possibly invalid) cycle.
125                 // In the existing code, this is marked by a non-nil type
126                 // for the object except for constants and variables whose
127                 // type may be non-nil (known), or nil if it depends on the
128                 // not-yet known initialization value.
129                 // In the former case, set the type to Typ[Invalid] because
130                 // we have an initialization cycle. The cycle error will be
131                 // reported later, when determining initialization order.
132                 // TODO(gri) Report cycle here and simplify initialization
133                 // order code.
134                 switch obj := obj.(type) {
135                 case *Const:
136                         if !check.validCycle(obj) || obj.typ == nil {
137                                 obj.typ = Typ[Invalid]
138                         }
139
140                 case *Var:
141                         if !check.validCycle(obj) || obj.typ == nil {
142                                 obj.typ = Typ[Invalid]
143                         }
144
145                 case *TypeName:
146                         if !check.validCycle(obj) {
147                                 // break cycle
148                                 // (without this, calling underlying()
149                                 // below may lead to an endless loop
150                                 // if we have a cycle for a defined
151                                 // (*Named) type)
152                                 obj.typ = Typ[Invalid]
153                         }
154
155                 case *Func:
156                         if !check.validCycle(obj) {
157                                 // Don't set obj.typ to Typ[Invalid] here
158                                 // because plenty of code type-asserts that
159                                 // functions have a *Signature type. Grey
160                                 // functions have their type set to an empty
161                                 // signature which makes it impossible to
162                                 // initialize a variable with the function.
163                         }
164
165                 default:
166                         unreachable()
167                 }
168                 assert(obj.Type() != nil)
169                 return
170         }
171
172         d := check.objMap[obj]
173         if d == nil {
174                 check.dump("%v: %s should have been declared", obj.Pos(), obj)
175                 unreachable()
176         }
177
178         // save/restore current environment and set up object environment
179         defer func(env environment) {
180                 check.environment = env
181         }(check.environment)
182         check.environment = environment{
183                 scope: d.file,
184         }
185
186         // Const and var declarations must not have initialization
187         // cycles. We track them by remembering the current declaration
188         // in check.decl. Initialization expressions depending on other
189         // consts, vars, or functions, add dependencies to the current
190         // check.decl.
191         switch obj := obj.(type) {
192         case *Const:
193                 check.decl = d // new package-level const decl
194                 check.constDecl(obj, d.vtyp, d.init, d.inherited)
195         case *Var:
196                 check.decl = d // new package-level var decl
197                 check.varDecl(obj, d.lhs, d.vtyp, d.init)
198         case *TypeName:
199                 // invalid recursive types are detected via path
200                 check.typeDecl(obj, d.tdecl, def)
201                 check.collectMethods(obj) // methods can only be added to top-level types
202         case *Func:
203                 // functions may be recursive - no need to track dependencies
204                 check.funcDecl(obj, d)
205         default:
206                 unreachable()
207         }
208 }
209
210 // validCycle reports whether the cycle starting with obj is valid and
211 // reports an error if it is not.
212 func (check *Checker) validCycle(obj Object) (valid bool) {
213         // The object map contains the package scope objects and the non-interface methods.
214         if debug {
215                 info := check.objMap[obj]
216                 inObjMap := info != nil && (info.fdecl == nil || info.fdecl.Recv == nil) // exclude methods
217                 isPkgObj := obj.Parent() == check.pkg.scope
218                 if isPkgObj != inObjMap {
219                         check.dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", obj.Pos(), obj, isPkgObj, inObjMap)
220                         unreachable()
221                 }
222         }
223
224         // Count cycle objects.
225         assert(obj.color() >= grey)
226         start := obj.color() - grey // index of obj in objPath
227         cycle := check.objPath[start:]
228         tparCycle := false // if set, the cycle is through a type parameter list
229         nval := 0          // number of (constant or variable) values in the cycle; valid if !generic
230         ndef := 0          // number of type definitions in the cycle; valid if !generic
231 loop:
232         for _, obj := range cycle {
233                 switch obj := obj.(type) {
234                 case *Const, *Var:
235                         nval++
236                 case *TypeName:
237                         // If we reach a generic type that is part of a cycle
238                         // and we are in a type parameter list, we have a cycle
239                         // through a type parameter list, which is invalid.
240                         if check.inTParamList && isGeneric(obj.typ) {
241                                 tparCycle = true
242                                 break loop
243                         }
244
245                         // Determine if the type name is an alias or not. For
246                         // package-level objects, use the object map which
247                         // provides syntactic information (which doesn't rely
248                         // on the order in which the objects are set up). For
249                         // local objects, we can rely on the order, so use
250                         // the object's predicate.
251                         // TODO(gri) It would be less fragile to always access
252                         // the syntactic information. We should consider storing
253                         // this information explicitly in the object.
254                         var alias bool
255                         if d := check.objMap[obj]; d != nil {
256                                 alias = d.tdecl.Alias // package-level object
257                         } else {
258                                 alias = obj.IsAlias() // function local object
259                         }
260                         if !alias {
261                                 ndef++
262                         }
263                 case *Func:
264                         // ignored for now
265                 default:
266                         unreachable()
267                 }
268         }
269
270         if check.conf.Trace {
271                 check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
272                 if tparCycle {
273                         check.trace(obj.Pos(), "## cycle contains: generic type in a type parameter list")
274                 } else {
275                         check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
276                 }
277                 defer func() {
278                         if valid {
279                                 check.trace(obj.Pos(), "=> cycle is valid")
280                         } else {
281                                 check.trace(obj.Pos(), "=> error: cycle is invalid")
282                         }
283                 }()
284         }
285
286         if !tparCycle {
287                 // A cycle involving only constants and variables is invalid but we
288                 // ignore them here because they are reported via the initialization
289                 // cycle check.
290                 if nval == len(cycle) {
291                         return true
292                 }
293
294                 // A cycle involving only types (and possibly functions) must have at least
295                 // one type definition to be permitted: If there is no type definition, we
296                 // have a sequence of alias type names which will expand ad infinitum.
297                 if nval == 0 && ndef > 0 {
298                         return true
299                 }
300         }
301
302         check.cycleError(cycle)
303         return false
304 }
305
306 // cycleError reports a declaration cycle starting with
307 // the object in cycle that is "first" in the source.
308 func (check *Checker) cycleError(cycle []Object) {
309         // name returns the (possibly qualified) object name.
310         // This is needed because with generic types, cycles
311         // may refer to imported types. See issue #50788.
312         // TODO(gri) This functionality is used elsewhere. Factor it out.
313         name := func(obj Object) string {
314                 var buf bytes.Buffer
315                 writePackage(&buf, obj.Pkg(), check.qualifier)
316                 buf.WriteString(obj.Name())
317                 return buf.String()
318         }
319
320         // TODO(gri) Should we start with the last (rather than the first) object in the cycle
321         //           since that is the earliest point in the source where we start seeing the
322         //           cycle? That would be more consistent with other error messages.
323         i := firstInSrc(cycle)
324         obj := cycle[i]
325         objName := name(obj)
326         // If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors.
327         tname, _ := obj.(*TypeName)
328         if tname != nil && tname.IsAlias() {
329                 check.validAlias(tname, Typ[Invalid])
330         }
331
332         // report a more concise error for self references
333         if len(cycle) == 1 {
334                 if tname != nil {
335                         check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", objName)
336                 } else {
337                         check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", objName)
338                 }
339                 return
340         }
341
342         var err error_
343         err.code = InvalidDeclCycle
344         if tname != nil {
345                 err.errorf(obj, "invalid recursive type %s", objName)
346         } else {
347                 err.errorf(obj, "invalid cycle in declaration of %s", objName)
348         }
349         for range cycle {
350                 err.errorf(obj, "%s refers to", objName)
351                 i++
352                 if i >= len(cycle) {
353                         i = 0
354                 }
355                 obj = cycle[i]
356                 objName = name(obj)
357         }
358         err.errorf(obj, "%s", objName)
359         check.report(&err)
360 }
361
362 // firstInSrc reports the index of the object with the "smallest"
363 // source position in path. path must not be empty.
364 func firstInSrc(path []Object) int {
365         fst, pos := 0, path[0].Pos()
366         for i, t := range path[1:] {
367                 if t.Pos().Cmp(pos) < 0 {
368                         fst, pos = i+1, t.Pos()
369                 }
370         }
371         return fst
372 }
373
374 func (check *Checker) constDecl(obj *Const, typ, init syntax.Expr, inherited bool) {
375         assert(obj.typ == nil)
376
377         // use the correct value of iota and errpos
378         defer func(iota constant.Value, errpos syntax.Pos) {
379                 check.iota = iota
380                 check.errpos = errpos
381         }(check.iota, check.errpos)
382         check.iota = obj.val
383         check.errpos = nopos
384
385         // provide valid constant value under all circumstances
386         obj.val = constant.MakeUnknown()
387
388         // determine type, if any
389         if typ != nil {
390                 t := check.typ(typ)
391                 if !isConstType(t) {
392                         // don't report an error if the type is an invalid C (defined) type
393                         // (issue #22090)
394                         if under(t) != Typ[Invalid] {
395                                 check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
396                         }
397                         obj.typ = Typ[Invalid]
398                         return
399                 }
400                 obj.typ = t
401         }
402
403         // check initialization
404         var x operand
405         if init != nil {
406                 if inherited {
407                         // The initialization expression is inherited from a previous
408                         // constant declaration, and (error) positions refer to that
409                         // expression and not the current constant declaration. Use
410                         // the constant identifier position for any errors during
411                         // init expression evaluation since that is all we have
412                         // (see issues #42991, #42992).
413                         check.errpos = obj.pos
414                 }
415                 check.expr(&x, init)
416         }
417         check.initConst(obj, &x)
418 }
419
420 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init syntax.Expr) {
421         assert(obj.typ == nil)
422
423         // If we have undefined variable types due to errors,
424         // mark variables as used to avoid follow-on errors.
425         // Matches compiler behavior.
426         defer func() {
427                 if obj.typ == Typ[Invalid] {
428                         obj.used = true
429                 }
430                 for _, lhs := range lhs {
431                         if lhs.typ == Typ[Invalid] {
432                                 lhs.used = true
433                         }
434                 }
435         }()
436
437         // determine type, if any
438         if typ != nil {
439                 obj.typ = check.varType(typ)
440                 // We cannot spread the type to all lhs variables if there
441                 // are more than one since that would mark them as checked
442                 // (see Checker.objDecl) and the assignment of init exprs,
443                 // if any, would not be checked.
444                 //
445                 // TODO(gri) If we have no init expr, we should distribute
446                 // a given type otherwise we need to re-evalate the type
447                 // expr for each lhs variable, leading to duplicate work.
448         }
449
450         // check initialization
451         if init == nil {
452                 if typ == nil {
453                         // error reported before by arityMatch
454                         obj.typ = Typ[Invalid]
455                 }
456                 return
457         }
458
459         if lhs == nil || len(lhs) == 1 {
460                 assert(lhs == nil || lhs[0] == obj)
461                 var x operand
462                 check.expr(&x, init)
463                 check.initVar(obj, &x, "variable declaration")
464                 return
465         }
466
467         if debug {
468                 // obj must be one of lhs
469                 found := false
470                 for _, lhs := range lhs {
471                         if obj == lhs {
472                                 found = true
473                                 break
474                         }
475                 }
476                 if !found {
477                         panic("inconsistent lhs")
478                 }
479         }
480
481         // We have multiple variables on the lhs and one init expr.
482         // Make sure all variables have been given the same type if
483         // one was specified, otherwise they assume the type of the
484         // init expression values (was issue #15755).
485         if typ != nil {
486                 for _, lhs := range lhs {
487                         lhs.typ = obj.typ
488                 }
489         }
490
491         check.initVars(lhs, []syntax.Expr{init}, nil)
492 }
493
494 // isImportedConstraint reports whether typ is an imported type constraint.
495 func (check *Checker) isImportedConstraint(typ Type) bool {
496         named, _ := typ.(*Named)
497         if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
498                 return false
499         }
500         u, _ := named.under().(*Interface)
501         return u != nil && !u.IsMethodSet()
502 }
503
504 func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *Named) {
505         assert(obj.typ == nil)
506
507         var rhs Type
508         check.later(func() {
509                 if t, _ := obj.typ.(*Named); t != nil { // type may be invalid
510                         check.validType(t)
511                 }
512                 // If typ is local, an error was already reported where typ is specified/defined.
513                 if check.isImportedConstraint(rhs) && !check.allowVersion(check.pkg, 1, 18) {
514                         check.versionErrorf(tdecl.Type, "go1.18", "using type constraint %s", rhs)
515                 }
516         }).describef(obj, "validType(%s)", obj.Name())
517
518         alias := tdecl.Alias
519         if alias && tdecl.TParamList != nil {
520                 // The parser will ensure this but we may still get an invalid AST.
521                 // Complain and continue as regular type definition.
522                 check.error(tdecl, BadDecl, "generic type cannot be alias")
523                 alias = false
524         }
525
526         // alias declaration
527         if alias {
528                 if !check.allowVersion(check.pkg, 1, 9) {
529                         check.versionErrorf(tdecl, "go1.9", "type aliases")
530                 }
531
532                 check.brokenAlias(obj)
533                 rhs = check.typ(tdecl.Type)
534                 check.validAlias(obj, rhs)
535                 return
536         }
537
538         // type definition or generic type declaration
539         named := check.newNamed(obj, nil, nil)
540         def.setUnderlying(named)
541
542         if tdecl.TParamList != nil {
543                 check.openScope(tdecl, "type parameters")
544                 defer check.closeScope()
545                 check.collectTypeParams(&named.tparams, tdecl.TParamList)
546         }
547
548         // determine underlying type of named
549         rhs = check.definedType(tdecl.Type, named)
550         assert(rhs != nil)
551         named.fromRHS = rhs
552
553         // If the underlying type was not set while type-checking the right-hand
554         // side, it is invalid and an error should have been reported elsewhere.
555         if named.underlying == nil {
556                 named.underlying = Typ[Invalid]
557         }
558
559         // Disallow a lone type parameter as the RHS of a type declaration (issue #45639).
560         // We don't need this restriction anymore if we make the underlying type of a type
561         // parameter its constraint interface: if the RHS is a lone type parameter, we will
562         // use its underlying type (like we do for any RHS in a type declaration), and its
563         // underlying type is an interface and the type declaration is well defined.
564         if isTypeParam(rhs) {
565                 check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
566                 named.underlying = Typ[Invalid]
567         }
568 }
569
570 func (check *Checker) collectTypeParams(dst **TypeParamList, list []*syntax.Field) {
571         tparams := make([]*TypeParam, len(list))
572
573         // Declare type parameters up-front.
574         // The scope of type parameters starts at the beginning of the type parameter
575         // list (so we can have mutually recursive parameterized type bounds).
576         for i, f := range list {
577                 tparams[i] = check.declareTypeParam(f.Name)
578         }
579
580         // Set the type parameters before collecting the type constraints because
581         // the parameterized type may be used by the constraints (issue #47887).
582         // Example: type T[P T[P]] interface{}
583         *dst = bindTParams(tparams)
584
585         // Signal to cycle detection that we are in a type parameter list.
586         // We can only be inside one type parameter list at any given time:
587         // function closures may appear inside a type parameter list but they
588         // cannot be generic, and their bodies are processed in delayed and
589         // sequential fashion. Note that with each new declaration, we save
590         // the existing environment and restore it when done; thus inTParamList
591         // is true exactly only when we are in a specific type parameter list.
592         assert(!check.inTParamList)
593         check.inTParamList = true
594         defer func() {
595                 check.inTParamList = false
596         }()
597
598         // Keep track of bounds for later validation.
599         var bound Type
600         for i, f := range list {
601                 // Optimization: Re-use the previous type bound if it hasn't changed.
602                 // This also preserves the grouped output of type parameter lists
603                 // when printing type strings.
604                 if i == 0 || f.Type != list[i-1].Type {
605                         bound = check.bound(f.Type)
606                         if isTypeParam(bound) {
607                                 // We may be able to allow this since it is now well-defined what
608                                 // the underlying type and thus type set of a type parameter is.
609                                 // But we may need some additional form of cycle detection within
610                                 // type parameter lists.
611                                 check.error(f.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
612                                 bound = Typ[Invalid]
613                         }
614                 }
615                 tparams[i].bound = bound
616         }
617 }
618
619 func (check *Checker) bound(x syntax.Expr) Type {
620         // A type set literal of the form ~T and A|B may only appear as constraint;
621         // embed it in an implicit interface so that only interface type-checking
622         // needs to take care of such type expressions.
623         if op, _ := x.(*syntax.Operation); op != nil && (op.Op == syntax.Tilde || op.Op == syntax.Or) {
624                 t := check.typ(&syntax.InterfaceType{MethodList: []*syntax.Field{{Type: x}}})
625                 // mark t as implicit interface if all went well
626                 if t, _ := t.(*Interface); t != nil {
627                         t.implicit = true
628                 }
629                 return t
630         }
631         return check.typ(x)
632 }
633
634 func (check *Checker) declareTypeParam(name *syntax.Name) *TypeParam {
635         // Use Typ[Invalid] for the type constraint to ensure that a type
636         // is present even if the actual constraint has not been assigned
637         // yet.
638         // TODO(gri) Need to systematically review all uses of type parameter
639         //           constraints to make sure we don't rely on them if they
640         //           are not properly set yet.
641         tname := NewTypeName(name.Pos(), check.pkg, name.Value, nil)
642         tpar := check.newTypeParam(tname, Typ[Invalid])          // assigns type to tname as a side-effect
643         check.declare(check.scope, name, tname, check.scope.pos) // TODO(gri) check scope position
644         return tpar
645 }
646
647 func (check *Checker) collectMethods(obj *TypeName) {
648         // get associated methods
649         // (Checker.collectObjects only collects methods with non-blank names;
650         // Checker.resolveBaseTypeName ensures that obj is not an alias name
651         // if it has attached methods.)
652         methods := check.methods[obj]
653         if methods == nil {
654                 return
655         }
656         delete(check.methods, obj)
657         assert(!check.objMap[obj].tdecl.Alias) // don't use TypeName.IsAlias (requires fully set up object)
658
659         // use an objset to check for name conflicts
660         var mset objset
661
662         // spec: "If the base type is a struct type, the non-blank method
663         // and field names must be distinct."
664         base, _ := obj.typ.(*Named) // shouldn't fail but be conservative
665         if base != nil {
666                 assert(base.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type
667
668                 // See issue #52529: we must delay the expansion of underlying here, as
669                 // base may not be fully set-up.
670                 check.later(func() {
671                         check.checkFieldUniqueness(base)
672                 }).describef(obj, "verifying field uniqueness for %v", base)
673
674                 // Checker.Files may be called multiple times; additional package files
675                 // may add methods to already type-checked types. Add pre-existing methods
676                 // so that we can detect redeclarations.
677                 for i := 0; i < base.NumMethods(); i++ {
678                         m := base.Method(i)
679                         assert(m.name != "_")
680                         assert(mset.insert(m) == nil)
681                 }
682         }
683
684         // add valid methods
685         for _, m := range methods {
686                 // spec: "For a base type, the non-blank names of methods bound
687                 // to it must be unique."
688                 assert(m.name != "_")
689                 if alt := mset.insert(m); alt != nil {
690                         if alt.Pos().IsKnown() {
691                                 check.errorf(m.pos, DuplicateMethod, "method %s.%s already declared at %s", obj.Name(), m.name, alt.Pos())
692                         } else {
693                                 check.errorf(m.pos, DuplicateMethod, "method %s.%s already declared", obj.Name(), m.name)
694                         }
695                         continue
696                 }
697
698                 if base != nil {
699                         base.AddMethod(m)
700                 }
701         }
702 }
703
704 func (check *Checker) checkFieldUniqueness(base *Named) {
705         if t, _ := base.under().(*Struct); t != nil {
706                 var mset objset
707                 for i := 0; i < base.NumMethods(); i++ {
708                         m := base.Method(i)
709                         assert(m.name != "_")
710                         assert(mset.insert(m) == nil)
711                 }
712
713                 // Check that any non-blank field names of base are distinct from its
714                 // method names.
715                 for _, fld := range t.fields {
716                         if fld.name != "_" {
717                                 if alt := mset.insert(fld); alt != nil {
718                                         // Struct fields should already be unique, so we should only
719                                         // encounter an alternate via collision with a method name.
720                                         _ = alt.(*Func)
721
722                                         // For historical consistency, we report the primary error on the
723                                         // method, and the alt decl on the field.
724                                         var err error_
725                                         err.code = DuplicateFieldAndMethod
726                                         err.errorf(alt, "field and method with the same name %s", fld.name)
727                                         err.recordAltDecl(fld)
728                                         check.report(&err)
729                                 }
730                         }
731                 }
732         }
733 }
734
735 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
736         assert(obj.typ == nil)
737
738         // func declarations cannot use iota
739         assert(check.iota == nil)
740
741         sig := new(Signature)
742         obj.typ = sig // guard against cycles
743
744         // Avoid cycle error when referring to method while type-checking the signature.
745         // This avoids a nuisance in the best case (non-parameterized receiver type) and
746         // since the method is not a type, we get an error. If we have a parameterized
747         // receiver type, instantiating the receiver type leads to the instantiation of
748         // its methods, and we don't want a cycle error in that case.
749         // TODO(gri) review if this is correct and/or whether we still need this?
750         saved := obj.color_
751         obj.color_ = black
752         fdecl := decl.fdecl
753         check.funcType(sig, fdecl.Recv, fdecl.TParamList, fdecl.Type)
754         obj.color_ = saved
755
756         if len(fdecl.TParamList) > 0 && fdecl.Body == nil {
757                 check.softErrorf(fdecl, BadDecl, "generic function is missing function body")
758         }
759
760         // function body must be type-checked after global declarations
761         // (functions implemented elsewhere have no body)
762         if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
763                 check.later(func() {
764                         check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
765                 }).describef(obj, "func %s", obj.name)
766         }
767 }
768
769 func (check *Checker) declStmt(list []syntax.Decl) {
770         pkg := check.pkg
771
772         first := -1                // index of first ConstDecl in the current group, or -1
773         var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
774         for index, decl := range list {
775                 if _, ok := decl.(*syntax.ConstDecl); !ok {
776                         first = -1 // we're not in a constant declaration
777                 }
778
779                 switch s := decl.(type) {
780                 case *syntax.ConstDecl:
781                         top := len(check.delayed)
782
783                         // iota is the index of the current constDecl within the group
784                         if first < 0 || s.Group == nil || list[index-1].(*syntax.ConstDecl).Group != s.Group {
785                                 first = index
786                                 last = nil
787                         }
788                         iota := constant.MakeInt64(int64(index - first))
789
790                         // determine which initialization expressions to use
791                         inherited := true
792                         switch {
793                         case s.Type != nil || s.Values != nil:
794                                 last = s
795                                 inherited = false
796                         case last == nil:
797                                 last = new(syntax.ConstDecl) // make sure last exists
798                                 inherited = false
799                         }
800
801                         // declare all constants
802                         lhs := make([]*Const, len(s.NameList))
803                         values := unpackExpr(last.Values)
804                         for i, name := range s.NameList {
805                                 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
806                                 lhs[i] = obj
807
808                                 var init syntax.Expr
809                                 if i < len(values) {
810                                         init = values[i]
811                                 }
812
813                                 check.constDecl(obj, last.Type, init, inherited)
814                         }
815
816                         // Constants must always have init values.
817                         check.arity(s.Pos(), s.NameList, values, true, inherited)
818
819                         // process function literals in init expressions before scope changes
820                         check.processDelayed(top)
821
822                         // spec: "The scope of a constant or variable identifier declared
823                         // inside a function begins at the end of the ConstSpec or VarSpec
824                         // (ShortVarDecl for short variable declarations) and ends at the
825                         // end of the innermost containing block."
826                         scopePos := syntax.EndPos(s)
827                         for i, name := range s.NameList {
828                                 check.declare(check.scope, name, lhs[i], scopePos)
829                         }
830
831                 case *syntax.VarDecl:
832                         top := len(check.delayed)
833
834                         lhs0 := make([]*Var, len(s.NameList))
835                         for i, name := range s.NameList {
836                                 lhs0[i] = NewVar(name.Pos(), pkg, name.Value, nil)
837                         }
838
839                         // initialize all variables
840                         values := unpackExpr(s.Values)
841                         for i, obj := range lhs0 {
842                                 var lhs []*Var
843                                 var init syntax.Expr
844                                 switch len(values) {
845                                 case len(s.NameList):
846                                         // lhs and rhs match
847                                         init = values[i]
848                                 case 1:
849                                         // rhs is expected to be a multi-valued expression
850                                         lhs = lhs0
851                                         init = values[0]
852                                 default:
853                                         if i < len(values) {
854                                                 init = values[i]
855                                         }
856                                 }
857                                 check.varDecl(obj, lhs, s.Type, init)
858                                 if len(values) == 1 {
859                                         // If we have a single lhs variable we are done either way.
860                                         // If we have a single rhs expression, it must be a multi-
861                                         // valued expression, in which case handling the first lhs
862                                         // variable will cause all lhs variables to have a type
863                                         // assigned, and we are done as well.
864                                         if debug {
865                                                 for _, obj := range lhs0 {
866                                                         assert(obj.typ != nil)
867                                                 }
868                                         }
869                                         break
870                                 }
871                         }
872
873                         // If we have no type, we must have values.
874                         if s.Type == nil || values != nil {
875                                 check.arity(s.Pos(), s.NameList, values, false, false)
876                         }
877
878                         // process function literals in init expressions before scope changes
879                         check.processDelayed(top)
880
881                         // declare all variables
882                         // (only at this point are the variable scopes (parents) set)
883                         scopePos := syntax.EndPos(s) // see constant declarations
884                         for i, name := range s.NameList {
885                                 // see constant declarations
886                                 check.declare(check.scope, name, lhs0[i], scopePos)
887                         }
888
889                 case *syntax.TypeDecl:
890                         obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
891                         // spec: "The scope of a type identifier declared inside a function
892                         // begins at the identifier in the TypeSpec and ends at the end of
893                         // the innermost containing block."
894                         scopePos := s.Name.Pos()
895                         check.declare(check.scope, s.Name, obj, scopePos)
896                         // mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
897                         obj.setColor(grey + color(check.push(obj)))
898                         check.typeDecl(obj, s, nil)
899                         check.pop().setColor(black)
900
901                 default:
902                         check.errorf(s, InvalidSyntaxTree, invalidAST+"unknown syntax.Decl node %T", s)
903                 }
904         }
905 }