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