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