]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/decl.go
[dev.typeparams] merge master (2f0da6d) into dev.typeparams
[gostls13.git] / src / go / types / 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 types
6
7 import (
8         "fmt"
9         "go/ast"
10         "go/constant"
11         "go/token"
12 )
13
14 func (check *Checker) reportAltDecl(obj Object) {
15         if pos := obj.Pos(); pos.IsValid() {
16                 // We use "other" rather than "previous" here because
17                 // the first declaration seen may not be textually
18                 // earlier in the source.
19                 check.errorf(obj, _DuplicateDecl, "\tother declaration of %s", obj.Name()) // secondary error, \t indented
20         }
21 }
22
23 func (check *Checker) declare(scope *Scope, id *ast.Ident, obj Object, pos token.Pos) {
24         // spec: "The blank identifier, represented by the underscore
25         // character _, may be used in a declaration like any other
26         // identifier but the declaration does not introduce a new
27         // binding."
28         if obj.Name() != "_" {
29                 if alt := scope.Insert(obj); alt != nil {
30                         check.errorf(obj, _DuplicateDecl, "%s redeclared in this block", obj.Name())
31                         check.reportAltDecl(alt)
32                         return
33                 }
34                 obj.setScopePos(pos)
35         }
36         if id != nil {
37                 check.recordDef(id, obj)
38         }
39 }
40
41 // pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
42 func pathString(path []Object) string {
43         var s string
44         for i, p := range path {
45                 if i > 0 {
46                         s += "->"
47                 }
48                 s += p.Name()
49         }
50         return s
51 }
52
53 // objDecl type-checks the declaration of obj in its respective (file) context.
54 // For the meaning of def, see Checker.definedType, in typexpr.go.
55 func (check *Checker) objDecl(obj Object, def *Named) {
56         if trace && obj.Type() == nil {
57                 if check.indent == 0 {
58                         fmt.Println() // empty line between top-level objects for readability
59                 }
60                 check.trace(obj.Pos(), "-- checking %s (%s, objPath = %s)", obj, obj.color(), pathString(check.objPath))
61                 check.indent++
62                 defer func() {
63                         check.indent--
64                         check.trace(obj.Pos(), "=> %s (%s)", obj, obj.color())
65                 }()
66         }
67
68         // Checking the declaration of obj means inferring its type
69         // (and possibly its value, for constants).
70         // An object's type (and thus the object) may be in one of
71         // three states which are expressed by colors:
72         //
73         // - an object whose type is not yet known is painted white (initial color)
74         // - an object whose type is in the process of being inferred is painted grey
75         // - an object whose type is fully inferred is painted black
76         //
77         // During type inference, an object's color changes from white to grey
78         // to black (pre-declared objects are painted black from the start).
79         // A black object (i.e., its type) can only depend on (refer to) other black
80         // ones. White and grey objects may depend on white and black objects.
81         // A dependency on a grey object indicates a cycle which may or may not be
82         // valid.
83         //
84         // When objects turn grey, they are pushed on the object path (a stack);
85         // they are popped again when they turn black. Thus, if a grey object (a
86         // cycle) is encountered, it is on the object path, and all the objects
87         // it depends on are the remaining objects on that path. Color encoding
88         // is such that the color value of a grey object indicates the index of
89         // that object in the object path.
90
91         // During type-checking, white objects may be assigned a type without
92         // traversing through objDecl; e.g., when initializing constants and
93         // variables. Update the colors of those objects here (rather than
94         // everywhere where we set the type) to satisfy the color invariants.
95         if obj.color() == white && obj.Type() != nil {
96                 obj.setColor(black)
97                 return
98         }
99
100         switch obj.color() {
101         case white:
102                 assert(obj.Type() == nil)
103                 // All color values other than white and black are considered grey.
104                 // Because black and white are < grey, all values >= grey are grey.
105                 // Use those values to encode the object's index into the object path.
106                 obj.setColor(grey + color(check.push(obj)))
107                 defer func() {
108                         check.pop().setColor(black)
109                 }()
110
111         case black:
112                 assert(obj.Type() != nil)
113                 return
114
115         default:
116                 // Color values other than white or black are considered grey.
117                 fallthrough
118
119         case grey:
120                 // We have a cycle.
121                 // In the existing code, this is marked by a non-nil type
122                 // for the object except for constants and variables whose
123                 // type may be non-nil (known), or nil if it depends on the
124                 // not-yet known initialization value.
125                 // In the former case, set the type to Typ[Invalid] because
126                 // we have an initialization cycle. The cycle error will be
127                 // reported later, when determining initialization order.
128                 // TODO(gri) Report cycle here and simplify initialization
129                 // order code.
130                 switch obj := obj.(type) {
131                 case *Const:
132                         if check.cycle(obj) || obj.typ == nil {
133                                 obj.typ = Typ[Invalid]
134                         }
135
136                 case *Var:
137                         if check.cycle(obj) || obj.typ == nil {
138                                 obj.typ = Typ[Invalid]
139                         }
140
141                 case *TypeName:
142                         if check.cycle(obj) {
143                                 // break cycle
144                                 // (without this, calling underlying()
145                                 // below may lead to an endless loop
146                                 // if we have a cycle for a defined
147                                 // (*Named) type)
148                                 obj.typ = Typ[Invalid]
149                         }
150
151                 case *Func:
152                         if check.cycle(obj) {
153                                 // Don't set obj.typ to Typ[Invalid] here
154                                 // because plenty of code type-asserts that
155                                 // functions have a *Signature type. Grey
156                                 // functions have their type set to an empty
157                                 // signature which makes it impossible to
158                                 // initialize a variable with the function.
159                         }
160
161                 default:
162                         unreachable()
163                 }
164                 assert(obj.Type() != nil)
165                 return
166         }
167
168         d := check.objMap[obj]
169         if d == nil {
170                 check.dump("%v: %s should have been declared", obj.Pos(), obj)
171                 unreachable()
172         }
173
174         // save/restore current context and setup object context
175         defer func(ctxt context) {
176                 check.context = ctxt
177         }(check.context)
178         check.context = context{
179                 scope: d.file,
180         }
181
182         // Const and var declarations must not have initialization
183         // cycles. We track them by remembering the current declaration
184         // in check.decl. Initialization expressions depending on other
185         // consts, vars, or functions, add dependencies to the current
186         // check.decl.
187         switch obj := obj.(type) {
188         case *Const:
189                 check.decl = d // new package-level const decl
190                 check.constDecl(obj, d.vtyp, d.init, d.inherited)
191         case *Var:
192                 check.decl = d // new package-level var decl
193                 check.varDecl(obj, d.lhs, d.vtyp, d.init)
194         case *TypeName:
195                 // invalid recursive types are detected via path
196                 check.typeDecl(obj, d.tdecl, def)
197                 check.collectMethods(obj) // methods can only be added to top-level types
198         case *Func:
199                 // functions may be recursive - no need to track dependencies
200                 check.funcDecl(obj, d)
201         default:
202                 unreachable()
203         }
204 }
205
206 // cycle checks if the cycle starting with obj is valid and
207 // reports an error if it is not.
208 func (check *Checker) cycle(obj Object) (isCycle bool) {
209         // The object map contains the package scope objects and the non-interface methods.
210         if debug {
211                 info := check.objMap[obj]
212                 inObjMap := info != nil && (info.fdecl == nil || info.fdecl.Recv == nil) // exclude methods
213                 isPkgObj := obj.Parent() == check.pkg.scope
214                 if isPkgObj != inObjMap {
215                         check.dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", obj.Pos(), obj, isPkgObj, inObjMap)
216                         unreachable()
217                 }
218         }
219
220         // Count cycle objects.
221         assert(obj.color() >= grey)
222         start := obj.color() - grey // index of obj in objPath
223         cycle := check.objPath[start:]
224         nval := 0 // number of (constant or variable) values in the cycle
225         ndef := 0 // number of type definitions in the cycle
226         for _, obj := range cycle {
227                 switch obj := obj.(type) {
228                 case *Const, *Var:
229                         nval++
230                 case *TypeName:
231                         // Determine if the type name is an alias or not. For
232                         // package-level objects, use the object map which
233                         // provides syntactic information (which doesn't rely
234                         // on the order in which the objects are set up). For
235                         // local objects, we can rely on the order, so use
236                         // the object's predicate.
237                         // TODO(gri) It would be less fragile to always access
238                         // the syntactic information. We should consider storing
239                         // this information explicitly in the object.
240                         var alias bool
241                         if d := check.objMap[obj]; d != nil {
242                                 alias = d.tdecl.Assign.IsValid() // package-level object
243                         } else {
244                                 alias = obj.IsAlias() // function local object
245                         }
246                         if !alias {
247                                 ndef++
248                         }
249                 case *Func:
250                         // ignored for now
251                 default:
252                         unreachable()
253                 }
254         }
255
256         if trace {
257                 check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
258                 check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
259                 defer func() {
260                         if isCycle {
261                                 check.trace(obj.Pos(), "=> error: cycle is invalid")
262                         }
263                 }()
264         }
265
266         // A cycle involving only constants and variables is invalid but we
267         // ignore them here because they are reported via the initialization
268         // cycle check.
269         if nval == len(cycle) {
270                 return false
271         }
272
273         // A cycle involving only types (and possibly functions) must have at least
274         // one type definition to be permitted: If there is no type definition, we
275         // have a sequence of alias type names which will expand ad infinitum.
276         if nval == 0 && ndef > 0 {
277                 return false // cycle is permitted
278         }
279
280         check.cycleError(cycle)
281
282         return true
283 }
284
285 type typeInfo uint
286
287 // validType verifies that the given type does not "expand" infinitely
288 // producing a cycle in the type graph. Cycles are detected by marking
289 // defined types.
290 // (Cycles involving alias types, as in "type A = [10]A" are detected
291 // earlier, via the objDecl cycle detection mechanism.)
292 func (check *Checker) validType(typ Type, path []Object) typeInfo {
293         const (
294                 unknown typeInfo = iota
295                 marked
296                 valid
297                 invalid
298         )
299
300         switch t := typ.(type) {
301         case *Array:
302                 return check.validType(t.elem, path)
303
304         case *Struct:
305                 for _, f := range t.fields {
306                         if check.validType(f.typ, path) == invalid {
307                                 return invalid
308                         }
309                 }
310
311         case *Interface:
312                 for _, etyp := range t.embeddeds {
313                         if check.validType(etyp, path) == invalid {
314                                 return invalid
315                         }
316                 }
317
318         case *Named:
319                 // don't touch the type if it is from a different package or the Universe scope
320                 // (doing so would lead to a race condition - was issue #35049)
321                 if t.obj.pkg != check.pkg {
322                         return valid
323                 }
324
325                 // don't report a 2nd error if we already know the type is invalid
326                 // (e.g., if a cycle was detected earlier, via under).
327                 if t.underlying == Typ[Invalid] {
328                         t.info = invalid
329                         return invalid
330                 }
331
332                 switch t.info {
333                 case unknown:
334                         t.info = marked
335                         t.info = check.validType(t.orig, append(path, t.obj)) // only types of current package added to path
336                 case marked:
337                         // cycle detected
338                         for i, tn := range path {
339                                 if t.obj.pkg != check.pkg {
340                                         panic("internal error: type cycle via package-external type")
341                                 }
342                                 if tn == t.obj {
343                                         check.cycleError(path[i:])
344                                         t.info = invalid
345                                         return t.info
346                                 }
347                         }
348                         panic("internal error: cycle start not found")
349                 }
350                 return t.info
351
352         case *instance:
353                 return check.validType(t.expand(), path)
354         }
355
356         return valid
357 }
358
359 // cycleError reports a declaration cycle starting with
360 // the object in cycle that is "first" in the source.
361 func (check *Checker) cycleError(cycle []Object) {
362         // TODO(gri) Should we start with the last (rather than the first) object in the cycle
363         //           since that is the earliest point in the source where we start seeing the
364         //           cycle? That would be more consistent with other error messages.
365         i := firstInSrc(cycle)
366         obj := cycle[i]
367         check.errorf(obj, _InvalidDeclCycle, "illegal cycle in declaration of %s", obj.Name())
368         for range cycle {
369                 check.errorf(obj, _InvalidDeclCycle, "\t%s refers to", obj.Name()) // secondary error, \t indented
370                 i++
371                 if i >= len(cycle) {
372                         i = 0
373                 }
374                 obj = cycle[i]
375         }
376         check.errorf(obj, _InvalidDeclCycle, "\t%s", obj.Name())
377 }
378
379 // firstInSrc reports the index of the object with the "smallest"
380 // source position in path. path must not be empty.
381 func firstInSrc(path []Object) int {
382         fst, pos := 0, path[0].Pos()
383         for i, t := range path[1:] {
384                 if t.Pos() < pos {
385                         fst, pos = i+1, t.Pos()
386                 }
387         }
388         return fst
389 }
390
391 type (
392         decl interface {
393                 node() ast.Node
394         }
395
396         importDecl struct{ spec *ast.ImportSpec }
397         constDecl  struct {
398                 spec      *ast.ValueSpec
399                 iota      int
400                 typ       ast.Expr
401                 init      []ast.Expr
402                 inherited bool
403         }
404         varDecl  struct{ spec *ast.ValueSpec }
405         typeDecl struct{ spec *ast.TypeSpec }
406         funcDecl struct{ decl *ast.FuncDecl }
407 )
408
409 func (d importDecl) node() ast.Node { return d.spec }
410 func (d constDecl) node() ast.Node  { return d.spec }
411 func (d varDecl) node() ast.Node    { return d.spec }
412 func (d typeDecl) node() ast.Node   { return d.spec }
413 func (d funcDecl) node() ast.Node   { return d.decl }
414
415 func (check *Checker) walkDecls(decls []ast.Decl, f func(decl)) {
416         for _, d := range decls {
417                 check.walkDecl(d, f)
418         }
419 }
420
421 func (check *Checker) walkDecl(d ast.Decl, f func(decl)) {
422         switch d := d.(type) {
423         case *ast.BadDecl:
424                 // ignore
425         case *ast.GenDecl:
426                 var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
427                 for iota, s := range d.Specs {
428                         switch s := s.(type) {
429                         case *ast.ImportSpec:
430                                 f(importDecl{s})
431                         case *ast.ValueSpec:
432                                 switch d.Tok {
433                                 case token.CONST:
434                                         // determine which initialization expressions to use
435                                         inherited := true
436                                         switch {
437                                         case s.Type != nil || len(s.Values) > 0:
438                                                 last = s
439                                                 inherited = false
440                                         case last == nil:
441                                                 last = new(ast.ValueSpec) // make sure last exists
442                                                 inherited = false
443                                         }
444                                         check.arityMatch(s, last)
445                                         f(constDecl{spec: s, iota: iota, typ: last.Type, init: last.Values, inherited: inherited})
446                                 case token.VAR:
447                                         check.arityMatch(s, nil)
448                                         f(varDecl{s})
449                                 default:
450                                         check.invalidAST(s, "invalid token %s", d.Tok)
451                                 }
452                         case *ast.TypeSpec:
453                                 f(typeDecl{s})
454                         default:
455                                 check.invalidAST(s, "unknown ast.Spec node %T", s)
456                         }
457                 }
458         case *ast.FuncDecl:
459                 f(funcDecl{d})
460         default:
461                 check.invalidAST(d, "unknown ast.Decl node %T", d)
462         }
463 }
464
465 func (check *Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool) {
466         assert(obj.typ == nil)
467
468         // use the correct value of iota
469         defer func(iota constant.Value, errpos positioner) {
470                 check.iota = iota
471                 check.errpos = errpos
472         }(check.iota, check.errpos)
473         check.iota = obj.val
474         check.errpos = nil
475
476         // provide valid constant value under all circumstances
477         obj.val = constant.MakeUnknown()
478
479         // determine type, if any
480         if typ != nil {
481                 t := check.typ(typ)
482                 if !isConstType(t) {
483                         // don't report an error if the type is an invalid C (defined) type
484                         // (issue #22090)
485                         if under(t) != Typ[Invalid] {
486                                 check.errorf(typ, _InvalidConstType, "invalid constant type %s", t)
487                         }
488                         obj.typ = Typ[Invalid]
489                         return
490                 }
491                 obj.typ = t
492         }
493
494         // check initialization
495         var x operand
496         if init != nil {
497                 if inherited {
498                         // The initialization expression is inherited from a previous
499                         // constant declaration, and (error) positions refer to that
500                         // expression and not the current constant declaration. Use
501                         // the constant identifier position for any errors during
502                         // init expression evaluation since that is all we have
503                         // (see issues #42991, #42992).
504                         check.errpos = atPos(obj.pos)
505                 }
506                 check.expr(&x, init)
507         }
508         check.initConst(obj, &x)
509 }
510
511 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) {
512         assert(obj.typ == nil)
513
514         // determine type, if any
515         if typ != nil {
516                 obj.typ = check.varType(typ)
517                 // We cannot spread the type to all lhs variables if there
518                 // are more than one since that would mark them as checked
519                 // (see Checker.objDecl) and the assignment of init exprs,
520                 // if any, would not be checked.
521                 //
522                 // TODO(gri) If we have no init expr, we should distribute
523                 // a given type otherwise we need to re-evalate the type
524                 // expr for each lhs variable, leading to duplicate work.
525         }
526
527         // check initialization
528         if init == nil {
529                 if typ == nil {
530                         // error reported before by arityMatch
531                         obj.typ = Typ[Invalid]
532                 }
533                 return
534         }
535
536         if lhs == nil || len(lhs) == 1 {
537                 assert(lhs == nil || lhs[0] == obj)
538                 var x operand
539                 check.expr(&x, init)
540                 check.initVar(obj, &x, "variable declaration")
541                 return
542         }
543
544         if debug {
545                 // obj must be one of lhs
546                 found := false
547                 for _, lhs := range lhs {
548                         if obj == lhs {
549                                 found = true
550                                 break
551                         }
552                 }
553                 if !found {
554                         panic("inconsistent lhs")
555                 }
556         }
557
558         // We have multiple variables on the lhs and one init expr.
559         // Make sure all variables have been given the same type if
560         // one was specified, otherwise they assume the type of the
561         // init expression values (was issue #15755).
562         if typ != nil {
563                 for _, lhs := range lhs {
564                         lhs.typ = obj.typ
565                 }
566         }
567
568         check.initVars(lhs, []ast.Expr{init}, token.NoPos)
569 }
570
571 // under returns the expanded underlying type of n0; possibly by following
572 // forward chains of named types. If an underlying type is found, resolve
573 // the chain by setting the underlying type for each defined type in the
574 // chain before returning it. If no underlying type is found or a cycle
575 // is detected, the result is Typ[Invalid]. If a cycle is detected and
576 // n0.check != nil, the cycle is reported.
577 func (n0 *Named) under() Type {
578         u := n0.underlying
579         if u == nil {
580                 return Typ[Invalid]
581         }
582
583         // If the underlying type of a defined type is not a defined
584         // type, then that is the desired underlying type.
585         n := asNamed(u)
586         if n == nil {
587                 return u // common case
588         }
589
590         // Otherwise, follow the forward chain.
591         seen := map[*Named]int{n0: 0}
592         path := []Object{n0.obj}
593         for {
594                 u = n.underlying
595                 if u == nil {
596                         u = Typ[Invalid]
597                         break
598                 }
599                 n1 := asNamed(u)
600                 if n1 == nil {
601                         break // end of chain
602                 }
603
604                 seen[n] = len(seen)
605                 path = append(path, n.obj)
606                 n = n1
607
608                 if i, ok := seen[n]; ok {
609                         // cycle
610                         // TODO(rFindley) revert this to a method on Checker. Having a possibly
611                         // nil Checker on Named and TypeParam is too subtle.
612                         if n0.check != nil {
613                                 n0.check.cycleError(path[i:])
614                         }
615                         u = Typ[Invalid]
616                         break
617                 }
618         }
619
620         for n := range seen {
621                 // We should never have to update the underlying type of an imported type;
622                 // those underlying types should have been resolved during the import.
623                 // Also, doing so would lead to a race condition (was issue #31749).
624                 // Do this check always, not just in debug more (it's cheap).
625                 if n0.check != nil && n.obj.pkg != n0.check.pkg {
626                         panic("internal error: imported type with unresolved underlying type")
627                 }
628                 n.underlying = u
629         }
630
631         return u
632 }
633
634 func (n *Named) setUnderlying(typ Type) {
635         if n != nil {
636                 n.underlying = typ
637         }
638 }
639
640 func (check *Checker) typeDecl(obj *TypeName, tdecl *ast.TypeSpec, def *Named) {
641         assert(obj.typ == nil)
642
643         check.later(func() {
644                 check.validType(obj.typ, nil)
645         })
646
647         alias := tdecl.Assign.IsValid()
648         if alias && tdecl.TParams != nil {
649                 // The parser will ensure this but we may still get an invalid AST.
650                 // Complain and continue as regular type definition.
651                 check.error(atPos(tdecl.Assign), 0, "generic type cannot be alias")
652                 alias = false
653         }
654
655         if alias {
656                 // type alias declaration
657                 if !check.allowVersion(obj.pkg, 1, 9) {
658                         check.errorf(atPos(tdecl.Assign), _BadDecl, "type aliases requires go1.9 or later")
659                 }
660
661                 obj.typ = Typ[Invalid]
662                 obj.typ = check.anyType(tdecl.Type)
663
664         } else {
665                 // defined type declaration
666
667                 named := &Named{check: check, obj: obj}
668                 def.setUnderlying(named)
669                 obj.typ = named // make sure recursive type declarations terminate
670
671                 if tdecl.TParams != nil {
672                         check.openScope(tdecl, "type parameters")
673                         defer check.closeScope()
674                         named.tparams = check.collectTypeParams(tdecl.TParams)
675                 }
676
677                 // determine underlying type of named
678                 named.orig = check.definedType(tdecl.Type, named)
679
680                 // The underlying type of named may be itself a named type that is
681                 // incomplete:
682                 //
683                 //      type (
684                 //              A B
685                 //              B *C
686                 //              C A
687                 //      )
688                 //
689                 // The type of C is the (named) type of A which is incomplete,
690                 // and which has as its underlying type the named type B.
691                 // Determine the (final, unnamed) underlying type by resolving
692                 // any forward chain.
693                 // TODO(gri) Investigate if we can just use named.origin here
694                 //           and rely on lazy computation of the underlying type.
695                 named.underlying = under(named)
696         }
697
698 }
699
700 func (check *Checker) collectTypeParams(list *ast.FieldList) (tparams []*TypeName) {
701         // Type parameter lists should not be empty. The parser will
702         // complain but we still may get an incorrect AST: ignore it.
703         if list.NumFields() == 0 {
704                 return
705         }
706
707         // Declare type parameters up-front, with empty interface as type bound.
708         // The scope of type parameters starts at the beginning of the type parameter
709         // list (so we can have mutually recursive parameterized interfaces).
710         for _, f := range list.List {
711                 tparams = check.declareTypeParams(tparams, f.Names)
712         }
713
714         setBoundAt := func(at int, bound Type) {
715                 assert(IsInterface(bound))
716                 tparams[at].typ.(*TypeParam).bound = bound
717         }
718
719         index := 0
720         var bound Type
721         for _, f := range list.List {
722                 if f.Type == nil {
723                         goto next
724                 }
725
726                 // The predeclared identifier "any" is visible only as a constraint
727                 // in a type parameter list. Look for it before general constraint
728                 // resolution.
729                 if tident, _ := f.Type.(*ast.Ident); tident != nil && tident.Name == "any" && check.lookup("any") == nil {
730                         bound = universeAny
731                 } else {
732                         bound = check.typ(f.Type)
733                 }
734
735                 // type bound must be an interface
736                 // TODO(gri) We should delay the interface check because
737                 //           we may not have a complete interface yet:
738                 //           type C(type T C) interface {}
739                 //           (issue #39724).
740                 if _, ok := under(bound).(*Interface); ok {
741                         // Otherwise, set the bound for each type parameter.
742                         for i := range f.Names {
743                                 setBoundAt(index+i, bound)
744                         }
745                 } else if bound != Typ[Invalid] {
746                         check.errorf(f.Type, _Todo, "%s is not an interface", bound)
747                 }
748
749         next:
750                 index += len(f.Names)
751         }
752
753         return
754 }
755
756 func (check *Checker) declareTypeParams(tparams []*TypeName, names []*ast.Ident) []*TypeName {
757         for _, name := range names {
758                 tpar := NewTypeName(name.Pos(), check.pkg, name.Name, nil)
759                 check.NewTypeParam(tpar, len(tparams), &emptyInterface) // assigns type to tpar as a side-effect
760                 check.declare(check.scope, name, tpar, check.scope.pos) // TODO(gri) check scope position
761                 tparams = append(tparams, tpar)
762         }
763
764         if trace && len(names) > 0 {
765                 check.trace(names[0].Pos(), "type params = %v", tparams[len(tparams)-len(names):])
766         }
767
768         return tparams
769 }
770
771 func (check *Checker) collectMethods(obj *TypeName) {
772         // get associated methods
773         // (Checker.collectObjects only collects methods with non-blank names;
774         // Checker.resolveBaseTypeName ensures that obj is not an alias name
775         // if it has attached methods.)
776         methods := check.methods[obj]
777         if methods == nil {
778                 return
779         }
780         delete(check.methods, obj)
781         assert(!check.objMap[obj].tdecl.Assign.IsValid()) // don't use TypeName.IsAlias (requires fully set up object)
782
783         // use an objset to check for name conflicts
784         var mset objset
785
786         // spec: "If the base type is a struct type, the non-blank method
787         // and field names must be distinct."
788         base := asNamed(obj.typ) // shouldn't fail but be conservative
789         if base != nil {
790                 if t, _ := base.underlying.(*Struct); t != nil {
791                         for _, fld := range t.fields {
792                                 if fld.name != "_" {
793                                         assert(mset.insert(fld) == nil)
794                                 }
795                         }
796                 }
797
798                 // Checker.Files may be called multiple times; additional package files
799                 // may add methods to already type-checked types. Add pre-existing methods
800                 // so that we can detect redeclarations.
801                 for _, m := range base.methods {
802                         assert(m.name != "_")
803                         assert(mset.insert(m) == nil)
804                 }
805         }
806
807         // add valid methods
808         for _, m := range methods {
809                 // spec: "For a base type, the non-blank names of methods bound
810                 // to it must be unique."
811                 assert(m.name != "_")
812                 if alt := mset.insert(m); alt != nil {
813                         switch alt.(type) {
814                         case *Var:
815                                 check.errorf(m, _DuplicateFieldAndMethod, "field and method with the same name %s", m.name)
816                         case *Func:
817                                 check.errorf(m, _DuplicateMethod, "method %s already declared for %s", m.name, obj)
818                         default:
819                                 unreachable()
820                         }
821                         check.reportAltDecl(alt)
822                         continue
823                 }
824
825                 if base != nil {
826                         base.methods = append(base.methods, m)
827                 }
828         }
829 }
830
831 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
832         assert(obj.typ == nil)
833
834         // func declarations cannot use iota
835         assert(check.iota == nil)
836
837         sig := new(Signature)
838         obj.typ = sig // guard against cycles
839
840         // Avoid cycle error when referring to method while type-checking the signature.
841         // This avoids a nuisance in the best case (non-parameterized receiver type) and
842         // since the method is not a type, we get an error. If we have a parameterized
843         // receiver type, instantiating the receiver type leads to the instantiation of
844         // its methods, and we don't want a cycle error in that case.
845         // TODO(gri) review if this is correct and/or whether we still need this?
846         saved := obj.color_
847         obj.color_ = black
848         fdecl := decl.fdecl
849         check.funcType(sig, fdecl.Recv, fdecl.Type)
850         obj.color_ = saved
851
852         // function body must be type-checked after global declarations
853         // (functions implemented elsewhere have no body)
854         if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
855                 check.later(func() {
856                         check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
857                 })
858         }
859 }
860
861 func (check *Checker) declStmt(d ast.Decl) {
862         pkg := check.pkg
863
864         check.walkDecl(d, func(d decl) {
865                 switch d := d.(type) {
866                 case constDecl:
867                         top := len(check.delayed)
868
869                         // declare all constants
870                         lhs := make([]*Const, len(d.spec.Names))
871                         for i, name := range d.spec.Names {
872                                 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
873                                 lhs[i] = obj
874
875                                 var init ast.Expr
876                                 if i < len(d.init) {
877                                         init = d.init[i]
878                                 }
879
880                                 check.constDecl(obj, d.typ, init, d.inherited)
881                         }
882
883                         // process function literals in init expressions before scope changes
884                         check.processDelayed(top)
885
886                         // spec: "The scope of a constant or variable identifier declared
887                         // inside a function begins at the end of the ConstSpec or VarSpec
888                         // (ShortVarDecl for short variable declarations) and ends at the
889                         // end of the innermost containing block."
890                         scopePos := d.spec.End()
891                         for i, name := range d.spec.Names {
892                                 check.declare(check.scope, name, lhs[i], scopePos)
893                         }
894
895                 case varDecl:
896                         top := len(check.delayed)
897
898                         lhs0 := make([]*Var, len(d.spec.Names))
899                         for i, name := range d.spec.Names {
900                                 lhs0[i] = NewVar(name.Pos(), pkg, name.Name, nil)
901                         }
902
903                         // initialize all variables
904                         for i, obj := range lhs0 {
905                                 var lhs []*Var
906                                 var init ast.Expr
907                                 switch len(d.spec.Values) {
908                                 case len(d.spec.Names):
909                                         // lhs and rhs match
910                                         init = d.spec.Values[i]
911                                 case 1:
912                                         // rhs is expected to be a multi-valued expression
913                                         lhs = lhs0
914                                         init = d.spec.Values[0]
915                                 default:
916                                         if i < len(d.spec.Values) {
917                                                 init = d.spec.Values[i]
918                                         }
919                                 }
920                                 check.varDecl(obj, lhs, d.spec.Type, init)
921                                 if len(d.spec.Values) == 1 {
922                                         // If we have a single lhs variable we are done either way.
923                                         // If we have a single rhs expression, it must be a multi-
924                                         // valued expression, in which case handling the first lhs
925                                         // variable will cause all lhs variables to have a type
926                                         // assigned, and we are done as well.
927                                         if debug {
928                                                 for _, obj := range lhs0 {
929                                                         assert(obj.typ != nil)
930                                                 }
931                                         }
932                                         break
933                                 }
934                         }
935
936                         // process function literals in init expressions before scope changes
937                         check.processDelayed(top)
938
939                         // declare all variables
940                         // (only at this point are the variable scopes (parents) set)
941                         scopePos := d.spec.End() // see constant declarations
942                         for i, name := range d.spec.Names {
943                                 // see constant declarations
944                                 check.declare(check.scope, name, lhs0[i], scopePos)
945                         }
946
947                 case typeDecl:
948                         obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
949                         // spec: "The scope of a type identifier declared inside a function
950                         // begins at the identifier in the TypeSpec and ends at the end of
951                         // the innermost containing block."
952                         scopePos := d.spec.Name.Pos()
953                         check.declare(check.scope, d.spec.Name, obj, scopePos)
954                         // mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
955                         obj.setColor(grey + color(check.push(obj)))
956                         check.typeDecl(obj, d.spec, nil)
957                         check.pop().setColor(black)
958                 default:
959                         check.invalidAST(d.node(), "unknown ast.Decl node %T", d.node())
960                 }
961         })
962 }