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