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