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