]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/decl.go
go/types, types2: implement Alias proposal (export API)
[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         "cmd/compile/internal/syntax"
9         "fmt"
10         "go/constant"
11         . "internal/types/errors"
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 *TypeName) {
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 check.enableAlias {
255                                 alias = obj.IsAlias()
256                         } else {
257                                 if d := check.objMap[obj]; d != nil {
258                                         alias = d.tdecl.Alias // package-level object
259                                 } else {
260                                         alias = obj.IsAlias() // function local object
261                                 }
262                         }
263                         if !alias {
264                                 ndef++
265                         }
266                 case *Func:
267                         // ignored for now
268                 default:
269                         unreachable()
270                 }
271         }
272
273         if check.conf.Trace {
274                 check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
275                 if tparCycle {
276                         check.trace(obj.Pos(), "## cycle contains: generic type in a type parameter list")
277                 } else {
278                         check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
279                 }
280                 defer func() {
281                         if valid {
282                                 check.trace(obj.Pos(), "=> cycle is valid")
283                         } else {
284                                 check.trace(obj.Pos(), "=> error: cycle is invalid")
285                         }
286                 }()
287         }
288
289         if !tparCycle {
290                 // A cycle involving only constants and variables is invalid but we
291                 // ignore them here because they are reported via the initialization
292                 // cycle check.
293                 if nval == len(cycle) {
294                         return true
295                 }
296
297                 // A cycle involving only types (and possibly functions) must have at least
298                 // one type definition to be permitted: If there is no type definition, we
299                 // have a sequence of alias type names which will expand ad infinitum.
300                 if nval == 0 && ndef > 0 {
301                         return true
302                 }
303         }
304
305         check.cycleError(cycle)
306         return false
307 }
308
309 // cycleError reports a declaration cycle starting with
310 // the object in cycle that is "first" in the source.
311 func (check *Checker) cycleError(cycle []Object) {
312         // name returns the (possibly qualified) object name.
313         // This is needed because with generic types, cycles
314         // may refer to imported types. See go.dev/issue/50788.
315         // TODO(gri) This functionality is used elsewhere. Factor it out.
316         name := func(obj Object) string {
317                 return packagePrefix(obj.Pkg(), check.qualifier) + obj.Name()
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                 // If we use Alias nodes, it is initialized with Typ[Invalid].
330                 // TODO(gri) Adjust this code if we initialize with nil.
331                 if !check.enableAlias {
332                         check.validAlias(tname, Typ[Invalid])
333                 }
334         }
335
336         // report a more concise error for self references
337         if len(cycle) == 1 {
338                 if tname != nil {
339                         check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", objName)
340                 } else {
341                         check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", objName)
342                 }
343                 return
344         }
345
346         var err error_
347         err.code = InvalidDeclCycle
348         if tname != nil {
349                 err.errorf(obj, "invalid recursive type %s", objName)
350         } else {
351                 err.errorf(obj, "invalid cycle in declaration of %s", objName)
352         }
353         for range cycle {
354                 err.errorf(obj, "%s refers to", objName)
355                 i++
356                 if i >= len(cycle) {
357                         i = 0
358                 }
359                 obj = cycle[i]
360                 objName = name(obj)
361         }
362         err.errorf(obj, "%s", objName)
363         check.report(&err)
364 }
365
366 // firstInSrc reports the index of the object with the "smallest"
367 // source position in path. path must not be empty.
368 func firstInSrc(path []Object) int {
369         fst, pos := 0, path[0].Pos()
370         for i, t := range path[1:] {
371                 if cmpPos(t.Pos(), pos) < 0 {
372                         fst, pos = i+1, t.Pos()
373                 }
374         }
375         return fst
376 }
377
378 func (check *Checker) constDecl(obj *Const, typ, init syntax.Expr, inherited bool) {
379         assert(obj.typ == nil)
380
381         // use the correct value of iota and errpos
382         defer func(iota constant.Value, errpos syntax.Pos) {
383                 check.iota = iota
384                 check.errpos = errpos
385         }(check.iota, check.errpos)
386         check.iota = obj.val
387         check.errpos = nopos
388
389         // provide valid constant value under all circumstances
390         obj.val = constant.MakeUnknown()
391
392         // determine type, if any
393         if typ != nil {
394                 t := check.typ(typ)
395                 if !isConstType(t) {
396                         // don't report an error if the type is an invalid C (defined) type
397                         // (go.dev/issue/22090)
398                         if isValid(under(t)) {
399                                 check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
400                         }
401                         obj.typ = Typ[Invalid]
402                         return
403                 }
404                 obj.typ = t
405         }
406
407         // check initialization
408         var x operand
409         if init != nil {
410                 if inherited {
411                         // The initialization expression is inherited from a previous
412                         // constant declaration, and (error) positions refer to that
413                         // expression and not the current constant declaration. Use
414                         // the constant identifier position for any errors during
415                         // init expression evaluation since that is all we have
416                         // (see issues go.dev/issue/42991, go.dev/issue/42992).
417                         check.errpos = obj.pos
418                 }
419                 check.expr(nil, &x, init)
420         }
421         check.initConst(obj, &x)
422 }
423
424 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init syntax.Expr) {
425         assert(obj.typ == nil)
426
427         // determine type, if any
428         if typ != nil {
429                 obj.typ = check.varType(typ)
430                 // We cannot spread the type to all lhs variables if there
431                 // are more than one since that would mark them as checked
432                 // (see Checker.objDecl) and the assignment of init exprs,
433                 // if any, would not be checked.
434                 //
435                 // TODO(gri) If we have no init expr, we should distribute
436                 // a given type otherwise we need to re-evalate the type
437                 // expr for each lhs variable, leading to duplicate work.
438         }
439
440         // check initialization
441         if init == nil {
442                 if typ == nil {
443                         // error reported before by arityMatch
444                         obj.typ = Typ[Invalid]
445                 }
446                 return
447         }
448
449         if lhs == nil || len(lhs) == 1 {
450                 assert(lhs == nil || lhs[0] == obj)
451                 var x operand
452                 check.expr(obj.typ, &x, init)
453                 check.initVar(obj, &x, "variable declaration")
454                 return
455         }
456
457         if debug {
458                 // obj must be one of lhs
459                 found := false
460                 for _, lhs := range lhs {
461                         if obj == lhs {
462                                 found = true
463                                 break
464                         }
465                 }
466                 if !found {
467                         panic("inconsistent lhs")
468                 }
469         }
470
471         // We have multiple variables on the lhs and one init expr.
472         // Make sure all variables have been given the same type if
473         // one was specified, otherwise they assume the type of the
474         // init expression values (was go.dev/issue/15755).
475         if typ != nil {
476                 for _, lhs := range lhs {
477                         lhs.typ = obj.typ
478                 }
479         }
480
481         check.initVars(lhs, []syntax.Expr{init}, nil)
482 }
483
484 // isImportedConstraint reports whether typ is an imported type constraint.
485 func (check *Checker) isImportedConstraint(typ Type) bool {
486         named := asNamed(typ)
487         if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
488                 return false
489         }
490         u, _ := named.under().(*Interface)
491         return u != nil && !u.IsMethodSet()
492 }
493
494 func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *TypeName) {
495         assert(obj.typ == nil)
496
497         var rhs Type
498         check.later(func() {
499                 if t := asNamed(obj.typ); t != nil { // type may be invalid
500                         check.validType(t)
501                 }
502                 // If typ is local, an error was already reported where typ is specified/defined.
503                 _ = check.isImportedConstraint(rhs) && check.verifyVersionf(tdecl.Type, go1_18, "using type constraint %s", rhs)
504         }).describef(obj, "validType(%s)", obj.Name())
505
506         aliasDecl := tdecl.Alias
507         if aliasDecl && tdecl.TParamList != nil {
508                 // The parser will ensure this but we may still get an invalid AST.
509                 // Complain and continue as regular type definition.
510                 check.error(tdecl, BadDecl, "generic type cannot be alias")
511                 aliasDecl = false
512         }
513
514         // alias declaration
515         if aliasDecl {
516                 check.verifyVersionf(tdecl, go1_9, "type aliases")
517                 if check.enableAlias {
518                         // TODO(gri) Should be able to use nil instead of Typ[Invalid] to mark
519                         //           the alias as incomplete. Currently this causes problems
520                         //           with certain cycles. Investigate.
521                         alias := check.newAlias(obj, Typ[Invalid])
522                         setDefType(def, alias)
523                         rhs = check.definedType(tdecl.Type, obj)
524                         assert(rhs != nil)
525                         alias.fromRHS = rhs
526                         Unalias(alias) // resolve alias.actual
527                 } else {
528                         check.brokenAlias(obj)
529                         rhs = check.typ(tdecl.Type)
530                         check.validAlias(obj, rhs)
531                 }
532                 return
533         }
534
535         // type definition or generic type declaration
536         named := check.newNamed(obj, nil, nil)
537         setDefType(def, named)
538
539         if tdecl.TParamList != nil {
540                 check.openScope(tdecl, "type parameters")
541                 defer check.closeScope()
542                 check.collectTypeParams(&named.tparams, tdecl.TParamList)
543         }
544
545         // determine underlying type of named
546         rhs = check.definedType(tdecl.Type, obj)
547         assert(rhs != nil)
548         named.fromRHS = rhs
549
550         // If the underlying type was not set while type-checking the right-hand
551         // side, it is invalid and an error should have been reported elsewhere.
552         if named.underlying == nil {
553                 named.underlying = Typ[Invalid]
554         }
555
556         // Disallow a lone type parameter as the RHS of a type declaration (go.dev/issue/45639).
557         // We don't need this restriction anymore if we make the underlying type of a type
558         // parameter its constraint interface: if the RHS is a lone type parameter, we will
559         // use its underlying type (like we do for any RHS in a type declaration), and its
560         // underlying type is an interface and the type declaration is well defined.
561         if isTypeParam(rhs) {
562                 check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
563                 named.underlying = Typ[Invalid]
564         }
565 }
566
567 func (check *Checker) collectTypeParams(dst **TypeParamList, list []*syntax.Field) {
568         tparams := make([]*TypeParam, len(list))
569
570         // Declare type parameters up-front.
571         // The scope of type parameters starts at the beginning of the type parameter
572         // list (so we can have mutually recursive parameterized type bounds).
573         for i, f := range list {
574                 tparams[i] = check.declareTypeParam(f.Name)
575         }
576
577         // Set the type parameters before collecting the type constraints because
578         // the parameterized type may be used by the constraints (go.dev/issue/47887).
579         // Example: type T[P T[P]] interface{}
580         *dst = bindTParams(tparams)
581
582         // Signal to cycle detection that we are in a type parameter list.
583         // We can only be inside one type parameter list at any given time:
584         // function closures may appear inside a type parameter list but they
585         // cannot be generic, and their bodies are processed in delayed and
586         // sequential fashion. Note that with each new declaration, we save
587         // the existing environment and restore it when done; thus inTParamList
588         // is true exactly only when we are in a specific type parameter list.
589         assert(!check.inTParamList)
590         check.inTParamList = true
591         defer func() {
592                 check.inTParamList = false
593         }()
594
595         // Keep track of bounds for later validation.
596         var bound Type
597         for i, f := range list {
598                 // Optimization: Re-use the previous type bound if it hasn't changed.
599                 // This also preserves the grouped output of type parameter lists
600                 // when printing type strings.
601                 if i == 0 || f.Type != list[i-1].Type {
602                         bound = check.bound(f.Type)
603                         if isTypeParam(bound) {
604                                 // We may be able to allow this since it is now well-defined what
605                                 // the underlying type and thus type set of a type parameter is.
606                                 // But we may need some additional form of cycle detection within
607                                 // type parameter lists.
608                                 check.error(f.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
609                                 bound = Typ[Invalid]
610                         }
611                 }
612                 tparams[i].bound = bound
613         }
614 }
615
616 func (check *Checker) bound(x syntax.Expr) Type {
617         // A type set literal of the form ~T and A|B may only appear as constraint;
618         // embed it in an implicit interface so that only interface type-checking
619         // needs to take care of such type expressions.
620         if op, _ := x.(*syntax.Operation); op != nil && (op.Op == syntax.Tilde || op.Op == syntax.Or) {
621                 t := check.typ(&syntax.InterfaceType{MethodList: []*syntax.Field{{Type: x}}})
622                 // mark t as implicit interface if all went well
623                 if t, _ := t.(*Interface); t != nil {
624                         t.implicit = true
625                 }
626                 return t
627         }
628         return check.typ(x)
629 }
630
631 func (check *Checker) declareTypeParam(name *syntax.Name) *TypeParam {
632         // Use Typ[Invalid] for the type constraint to ensure that a type
633         // is present even if the actual constraint has not been assigned
634         // yet.
635         // TODO(gri) Need to systematically review all uses of type parameter
636         //           constraints to make sure we don't rely on them if they
637         //           are not properly set yet.
638         tname := NewTypeName(name.Pos(), check.pkg, name.Value, nil)
639         tpar := check.newTypeParam(tname, Typ[Invalid])          // assigns type to tname as a side-effect
640         check.declare(check.scope, name, tname, check.scope.pos) // TODO(gri) check scope position
641         return tpar
642 }
643
644 func (check *Checker) collectMethods(obj *TypeName) {
645         // get associated methods
646         // (Checker.collectObjects only collects methods with non-blank names;
647         // Checker.resolveBaseTypeName ensures that obj is not an alias name
648         // if it has attached methods.)
649         methods := check.methods[obj]
650         if methods == nil {
651                 return
652         }
653         delete(check.methods, obj)
654         assert(!check.objMap[obj].tdecl.Alias) // don't use TypeName.IsAlias (requires fully set up object)
655
656         // use an objset to check for name conflicts
657         var mset objset
658
659         // spec: "If the base type is a struct type, the non-blank method
660         // and field names must be distinct."
661         base := asNamed(obj.typ) // shouldn't fail but be conservative
662         if base != nil {
663                 assert(base.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type
664
665                 // See go.dev/issue/52529: we must delay the expansion of underlying here, as
666                 // base may not be fully set-up.
667                 check.later(func() {
668                         check.checkFieldUniqueness(base)
669                 }).describef(obj, "verifying field uniqueness for %v", base)
670
671                 // Checker.Files may be called multiple times; additional package files
672                 // may add methods to already type-checked types. Add pre-existing methods
673                 // so that we can detect redeclarations.
674                 for i := 0; i < base.NumMethods(); i++ {
675                         m := base.Method(i)
676                         assert(m.name != "_")
677                         assert(mset.insert(m) == nil)
678                 }
679         }
680
681         // add valid methods
682         for _, m := range methods {
683                 // spec: "For a base type, the non-blank names of methods bound
684                 // to it must be unique."
685                 assert(m.name != "_")
686                 if alt := mset.insert(m); alt != nil {
687                         if alt.Pos().IsKnown() {
688                                 check.errorf(m.pos, DuplicateMethod, "method %s.%s already declared at %s", obj.Name(), m.name, alt.Pos())
689                         } else {
690                                 check.errorf(m.pos, DuplicateMethod, "method %s.%s already declared", obj.Name(), m.name)
691                         }
692                         continue
693                 }
694
695                 if base != nil {
696                         base.AddMethod(m)
697                 }
698         }
699 }
700
701 func (check *Checker) checkFieldUniqueness(base *Named) {
702         if t, _ := base.under().(*Struct); t != nil {
703                 var mset objset
704                 for i := 0; i < base.NumMethods(); i++ {
705                         m := base.Method(i)
706                         assert(m.name != "_")
707                         assert(mset.insert(m) == nil)
708                 }
709
710                 // Check that any non-blank field names of base are distinct from its
711                 // method names.
712                 for _, fld := range t.fields {
713                         if fld.name != "_" {
714                                 if alt := mset.insert(fld); alt != nil {
715                                         // Struct fields should already be unique, so we should only
716                                         // encounter an alternate via collision with a method name.
717                                         _ = alt.(*Func)
718
719                                         // For historical consistency, we report the primary error on the
720                                         // method, and the alt decl on the field.
721                                         var err error_
722                                         err.code = DuplicateFieldAndMethod
723                                         err.errorf(alt, "field and method with the same name %s", fld.name)
724                                         err.recordAltDecl(fld)
725                                         check.report(&err)
726                                 }
727                         }
728                 }
729         }
730 }
731
732 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
733         assert(obj.typ == nil)
734
735         // func declarations cannot use iota
736         assert(check.iota == nil)
737
738         sig := new(Signature)
739         obj.typ = sig // guard against cycles
740
741         // Avoid cycle error when referring to method while type-checking the signature.
742         // This avoids a nuisance in the best case (non-parameterized receiver type) and
743         // since the method is not a type, we get an error. If we have a parameterized
744         // receiver type, instantiating the receiver type leads to the instantiation of
745         // its methods, and we don't want a cycle error in that case.
746         // TODO(gri) review if this is correct and/or whether we still need this?
747         saved := obj.color_
748         obj.color_ = black
749         fdecl := decl.fdecl
750         check.funcType(sig, fdecl.Recv, fdecl.TParamList, fdecl.Type)
751         obj.color_ = saved
752
753         if len(fdecl.TParamList) > 0 && fdecl.Body == nil {
754                 check.softErrorf(fdecl, BadDecl, "generic function is missing function body")
755         }
756
757         // function body must be type-checked after global declarations
758         // (functions implemented elsewhere have no body)
759         if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
760                 check.later(func() {
761                         check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
762                 }).describef(obj, "func %s", obj.name)
763         }
764 }
765
766 func (check *Checker) declStmt(list []syntax.Decl) {
767         pkg := check.pkg
768
769         first := -1                // index of first ConstDecl in the current group, or -1
770         var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
771         for index, decl := range list {
772                 if _, ok := decl.(*syntax.ConstDecl); !ok {
773                         first = -1 // we're not in a constant declaration
774                 }
775
776                 switch s := decl.(type) {
777                 case *syntax.ConstDecl:
778                         top := len(check.delayed)
779
780                         // iota is the index of the current constDecl within the group
781                         if first < 0 || s.Group == nil || list[index-1].(*syntax.ConstDecl).Group != s.Group {
782                                 first = index
783                                 last = nil
784                         }
785                         iota := constant.MakeInt64(int64(index - first))
786
787                         // determine which initialization expressions to use
788                         inherited := true
789                         switch {
790                         case s.Type != nil || s.Values != nil:
791                                 last = s
792                                 inherited = false
793                         case last == nil:
794                                 last = new(syntax.ConstDecl) // make sure last exists
795                                 inherited = false
796                         }
797
798                         // declare all constants
799                         lhs := make([]*Const, len(s.NameList))
800                         values := syntax.UnpackListExpr(last.Values)
801                         for i, name := range s.NameList {
802                                 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
803                                 lhs[i] = obj
804
805                                 var init syntax.Expr
806                                 if i < len(values) {
807                                         init = values[i]
808                                 }
809
810                                 check.constDecl(obj, last.Type, init, inherited)
811                         }
812
813                         // Constants must always have init values.
814                         check.arity(s.Pos(), s.NameList, values, true, inherited)
815
816                         // process function literals in init expressions before scope changes
817                         check.processDelayed(top)
818
819                         // spec: "The scope of a constant or variable identifier declared
820                         // inside a function begins at the end of the ConstSpec or VarSpec
821                         // (ShortVarDecl for short variable declarations) and ends at the
822                         // end of the innermost containing block."
823                         scopePos := syntax.EndPos(s)
824                         for i, name := range s.NameList {
825                                 check.declare(check.scope, name, lhs[i], scopePos)
826                         }
827
828                 case *syntax.VarDecl:
829                         top := len(check.delayed)
830
831                         lhs0 := make([]*Var, len(s.NameList))
832                         for i, name := range s.NameList {
833                                 lhs0[i] = NewVar(name.Pos(), pkg, name.Value, nil)
834                         }
835
836                         // initialize all variables
837                         values := syntax.UnpackListExpr(s.Values)
838                         for i, obj := range lhs0 {
839                                 var lhs []*Var
840                                 var init syntax.Expr
841                                 switch len(values) {
842                                 case len(s.NameList):
843                                         // lhs and rhs match
844                                         init = values[i]
845                                 case 1:
846                                         // rhs is expected to be a multi-valued expression
847                                         lhs = lhs0
848                                         init = values[0]
849                                 default:
850                                         if i < len(values) {
851                                                 init = values[i]
852                                         }
853                                 }
854                                 check.varDecl(obj, lhs, s.Type, init)
855                                 if len(values) == 1 {
856                                         // If we have a single lhs variable we are done either way.
857                                         // If we have a single rhs expression, it must be a multi-
858                                         // valued expression, in which case handling the first lhs
859                                         // variable will cause all lhs variables to have a type
860                                         // assigned, and we are done as well.
861                                         if debug {
862                                                 for _, obj := range lhs0 {
863                                                         assert(obj.typ != nil)
864                                                 }
865                                         }
866                                         break
867                                 }
868                         }
869
870                         // If we have no type, we must have values.
871                         if s.Type == nil || values != nil {
872                                 check.arity(s.Pos(), s.NameList, values, false, false)
873                         }
874
875                         // process function literals in init expressions before scope changes
876                         check.processDelayed(top)
877
878                         // declare all variables
879                         // (only at this point are the variable scopes (parents) set)
880                         scopePos := syntax.EndPos(s) // see constant declarations
881                         for i, name := range s.NameList {
882                                 // see constant declarations
883                                 check.declare(check.scope, name, lhs0[i], scopePos)
884                         }
885
886                 case *syntax.TypeDecl:
887                         obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
888                         // spec: "The scope of a type identifier declared inside a function
889                         // begins at the identifier in the TypeSpec and ends at the end of
890                         // the innermost containing block."
891                         scopePos := s.Name.Pos()
892                         check.declare(check.scope, s.Name, obj, scopePos)
893                         // mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
894                         obj.setColor(grey + color(check.push(obj)))
895                         check.typeDecl(obj, s, nil)
896                         check.pop().setColor(black)
897
898                 default:
899                         check.errorf(s, InvalidSyntaxTree, "unknown syntax.Decl node %T", s)
900                 }
901         }
902 }