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