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