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.
8 "cmd/compile/internal/syntax"
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())
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
27 if obj.Name() != "_" {
28 if alt := scope.Insert(obj); alt != nil {
30 err.errorf(obj, "%s redeclared in this block", obj.Name())
31 err.recordAltDecl(alt)
38 check.recordDef(id, obj)
42 // pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
43 func pathString(path []Object) string {
45 for i, p := range path {
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
61 check.trace(obj.Pos(), "-- checking %s (%s, objPath = %s)", obj, obj.color(), pathString(check.objPath))
65 check.trace(obj.Pos(), "=> %s (%s)", obj, obj.color())
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)
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:
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
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
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.
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 {
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)))
115 check.pop().setColor(black)
119 assert(obj.Type() != nil)
123 // Color values other than white or black are considered grey.
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
137 switch obj := obj.(type) {
139 if check.cycle(obj) || obj.typ == nil {
140 obj.typ = Typ[Invalid]
144 if check.cycle(obj) || obj.typ == nil {
145 obj.typ = Typ[Invalid]
149 if check.cycle(obj) {
151 // (without this, calling underlying()
152 // below may lead to an endless loop
153 // if we have a cycle for a defined
155 obj.typ = Typ[Invalid]
159 if check.cycle(obj) {
160 // Don't set obj.typ to Typ[Invalid] here
161 // because plenty of code type-asserts that
162 // functions have a *Signature type. Grey
163 // functions have their type set to an empty
164 // signature which makes it impossible to
165 // initialize a variable with the function.
171 assert(obj.Type() != nil)
175 d := check.objMap[obj]
177 check.dump("%v: %s should have been declared", obj.Pos(), obj)
181 // save/restore current context and setup object context
182 defer func(ctxt context) {
185 check.context = context{
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
194 switch obj := obj.(type) {
196 check.decl = d // new package-level const decl
197 check.constDecl(obj, d.vtyp, d.init, d.inherited)
199 check.decl = d // new package-level var decl
200 check.varDecl(obj, d.lhs, d.vtyp, d.init)
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
206 // functions may be recursive - no need to track dependencies
207 check.funcDecl(obj, d)
213 // cycle checks if the cycle starting with obj is valid and
214 // reports an error if it is not.
215 func (check *Checker) cycle(obj Object) (isCycle bool) {
216 // The object map contains the package scope objects and the non-interface methods.
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)
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) {
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.
248 if d := check.objMap[obj]; d != nil {
249 alias = d.tdecl.Alias // package-level object
251 alias = obj.IsAlias() // function local object
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)
268 check.trace(obj.Pos(), "=> error: cycle is invalid")
273 // A cycle involving only constants and variables is invalid but we
274 // ignore them here because they are reported via the initialization
276 if nval == len(cycle) {
280 // A cycle involving only types (and possibly functions) must have at least
281 // one type definition to be permitted: If there is no type definition, we
282 // have a sequence of alias type names which will expand ad infinitum.
283 if nval == 0 && ndef > 0 {
284 return false // cycle is permitted
287 check.cycleError(cycle)
294 // validType verifies that the given type does not "expand" infinitely
295 // producing a cycle in the type graph. Cycles are detected by marking
297 // (Cycles involving alias types, as in "type A = [10]A" are detected
298 // earlier, via the objDecl cycle detection mechanism.)
299 func (check *Checker) validType(typ Type, path []Object) typeInfo {
301 unknown typeInfo = iota
307 switch t := typ.(type) {
309 return check.validType(t.elem, path)
312 for _, f := range t.fields {
313 if check.validType(f.typ, path) == invalid {
319 for _, t := range t.terms {
320 if check.validType(t.typ, path) == invalid {
326 for _, etyp := range t.embeddeds {
327 if check.validType(etyp, path) == invalid {
333 t.resolve(check.conf.Context)
335 // don't touch the type if it is from a different package or the Universe scope
336 // (doing so would lead to a race condition - was issue #35049)
337 if t.obj.pkg != check.pkg {
341 // don't report a 2nd error if we already know the type is invalid
342 // (e.g., if a cycle was detected earlier, via under).
343 if t.underlying == Typ[Invalid] {
351 t.info = check.validType(t.fromRHS, append(path, t.obj)) // only types of current package added to path
354 for i, tn := range path {
355 if t.obj.pkg != check.pkg {
356 panic("type cycle via package-external type")
359 check.cycleError(path[i:])
361 t.underlying = Typ[Invalid]
365 panic("cycle start not found")
373 // cycleError reports a declaration cycle starting with
374 // the object in cycle that is "first" in the source.
375 func (check *Checker) cycleError(cycle []Object) {
376 // TODO(gri) Should we start with the last (rather than the first) object in the cycle
377 // since that is the earliest point in the source where we start seeing the
378 // cycle? That would be more consistent with other error messages.
379 i := firstInSrc(cycle)
382 if check.conf.CompilerErrorMessages {
383 err.errorf(obj, "invalid recursive type %s", obj.Name())
385 err.errorf(obj, "illegal cycle in declaration of %s", obj.Name())
388 err.errorf(obj, "%s refers to", obj.Name())
395 err.errorf(obj, "%s", obj.Name())
399 // firstInSrc reports the index of the object with the "smallest"
400 // source position in path. path must not be empty.
401 func firstInSrc(path []Object) int {
402 fst, pos := 0, path[0].Pos()
403 for i, t := range path[1:] {
404 if t.Pos().Cmp(pos) < 0 {
405 fst, pos = i+1, t.Pos()
411 func (check *Checker) constDecl(obj *Const, typ, init syntax.Expr, inherited bool) {
412 assert(obj.typ == nil)
414 // use the correct value of iota and errpos
415 defer func(iota constant.Value, errpos syntax.Pos) {
417 check.errpos = errpos
418 }(check.iota, check.errpos)
422 // provide valid constant value under all circumstances
423 obj.val = constant.MakeUnknown()
425 // determine type, if any
429 // don't report an error if the type is an invalid C (defined) type
431 if under(t) != Typ[Invalid] {
432 check.errorf(typ, "invalid constant type %s", t)
434 obj.typ = Typ[Invalid]
440 // check initialization
444 // The initialization expression is inherited from a previous
445 // constant declaration, and (error) positions refer to that
446 // expression and not the current constant declaration. Use
447 // the constant identifier position for any errors during
448 // init expression evaluation since that is all we have
449 // (see issues #42991, #42992).
450 check.errpos = obj.pos
454 check.initConst(obj, &x)
457 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init syntax.Expr) {
458 assert(obj.typ == nil)
460 // If we have undefined variable types due to errors,
461 // mark variables as used to avoid follow-on errors.
462 // Matches compiler behavior.
464 if obj.typ == Typ[Invalid] {
467 for _, lhs := range lhs {
468 if lhs.typ == Typ[Invalid] {
474 // determine type, if any
476 obj.typ = check.varType(typ)
477 // We cannot spread the type to all lhs variables if there
478 // are more than one since that would mark them as checked
479 // (see Checker.objDecl) and the assignment of init exprs,
480 // if any, would not be checked.
482 // TODO(gri) If we have no init expr, we should distribute
483 // a given type otherwise we need to re-evalate the type
484 // expr for each lhs variable, leading to duplicate work.
487 // check initialization
490 // error reported before by arityMatch
491 obj.typ = Typ[Invalid]
496 if lhs == nil || len(lhs) == 1 {
497 assert(lhs == nil || lhs[0] == obj)
500 check.initVar(obj, &x, "variable declaration")
505 // obj must be one of lhs
507 for _, lhs := range lhs {
514 panic("inconsistent lhs")
518 // We have multiple variables on the lhs and one init expr.
519 // Make sure all variables have been given the same type if
520 // one was specified, otherwise they assume the type of the
521 // init expression values (was issue #15755).
523 for _, lhs := range lhs {
528 check.initVars(lhs, []syntax.Expr{init}, nopos)
531 // isImportedConstraint reports whether typ is an imported type constraint.
532 func (check *Checker) isImportedConstraint(typ Type) bool {
533 named, _ := typ.(*Named)
534 if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
537 u, _ := named.under().(*Interface)
538 return u != nil && !u.IsMethodSet()
541 func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *Named) {
542 assert(obj.typ == nil)
546 check.validType(obj.typ, nil)
547 // If typ is local, an error was already reported where typ is specified/defined.
548 if check.isImportedConstraint(rhs) && !check.allowVersion(check.pkg, 1, 18) {
549 check.errorf(tdecl.Type.Pos(), "using type constraint %s requires go1.18 or later", rhs)
554 if alias && tdecl.TParamList != nil {
555 // The parser will ensure this but we may still get an invalid AST.
556 // Complain and continue as regular type definition.
557 check.error(tdecl, "generic type cannot be alias")
563 if !check.allowVersion(check.pkg, 1, 9) {
564 if check.conf.CompilerErrorMessages {
565 check.error(tdecl, "type aliases only supported as of -lang=go1.9")
567 check.error(tdecl, "type aliases requires go1.9 or later")
571 obj.typ = Typ[Invalid]
572 rhs = check.varType(tdecl.Type)
577 // type definition or generic type declaration
578 named := check.newNamed(obj, nil, nil, nil, nil)
579 def.setUnderlying(named)
581 if tdecl.TParamList != nil {
582 check.openScope(tdecl, "type parameters")
583 defer check.closeScope()
584 check.collectTypeParams(&named.tparams, tdecl.TParamList)
587 // determine underlying type of named
588 rhs = check.definedType(tdecl.Type, named)
591 // The underlying type of named may be itself a named type that is
600 // The type of C is the (named) type of A which is incomplete,
601 // and which has as its underlying type the named type B.
602 // Determine the (final, unnamed) underlying type by resolving
603 // any forward chain.
604 // TODO(gri) Investigate if we can just use named.fromRHS here
605 // and rely on lazy computation of the underlying type.
606 named.underlying = under(named)
608 // If the RHS is a type parameter, it must be from this type declaration.
609 if tpar, _ := named.underlying.(*TypeParam); tpar != nil && tparamIndex(named.TypeParams().list(), tpar) < 0 {
610 check.errorf(tdecl.Type, "cannot use function type parameter %s as RHS in type declaration", tpar)
611 named.underlying = Typ[Invalid]
615 func (check *Checker) collectTypeParams(dst **TypeParamList, list []*syntax.Field) {
616 tparams := make([]*TypeParam, len(list))
618 // Declare type parameters up-front.
619 // The scope of type parameters starts at the beginning of the type parameter
620 // list (so we can have mutually recursive parameterized type bounds).
621 for i, f := range list {
622 tparams[i] = check.declareTypeParam(f.Name)
625 // Set the type parameters before collecting the type constraints because
626 // the parameterized type may be used by the constraints (issue #47887).
627 // Example: type T[P T[P]] interface{}
628 *dst = bindTParams(tparams)
630 // Keep track of bounds for later validation.
634 for i, f := range list {
635 // Optimization: Re-use the previous type bound if it hasn't changed.
636 // This also preserves the grouped output of type parameter lists
637 // when printing type strings.
638 if i == 0 || f.Type != list[i-1].Type {
639 bound = check.bound(f.Type)
640 bounds = append(bounds, bound)
641 posers = append(posers, f.Type)
643 tparams[i].bound = bound
647 for i, bound := range bounds {
648 if _, ok := under(bound).(*TypeParam); ok {
649 check.error(posers[i], "cannot use a type parameter as constraint")
652 for _, tpar := range tparams {
653 tpar.iface() // compute type set
658 func (check *Checker) bound(x syntax.Expr) Type {
659 // A type set literal of the form ~T and A|B may only appear as constraint;
660 // embed it in an implicit interface so that only interface type-checking
661 // needs to take care of such type expressions.
662 if op, _ := x.(*syntax.Operation); op != nil && (op.Op == syntax.Tilde || op.Op == syntax.Or) {
663 t := check.typ(&syntax.InterfaceType{MethodList: []*syntax.Field{{Type: x}}})
664 // mark t as implicit interface if all went well
665 if t, _ := t.(*Interface); t != nil {
673 func (check *Checker) declareTypeParam(name *syntax.Name) *TypeParam {
674 // Use Typ[Invalid] for the type constraint to ensure that a type
675 // is present even if the actual constraint has not been assigned
677 // TODO(gri) Need to systematically review all uses of type parameter
678 // constraints to make sure we don't rely on them if they
679 // are not properly set yet.
680 tname := NewTypeName(name.Pos(), check.pkg, name.Value, nil)
681 tpar := check.newTypeParam(tname, Typ[Invalid]) // assigns type to tname as a side-effect
682 check.declare(check.scope, name, tname, check.scope.pos) // TODO(gri) check scope position
686 func (check *Checker) collectMethods(obj *TypeName) {
687 // get associated methods
688 // (Checker.collectObjects only collects methods with non-blank names;
689 // Checker.resolveBaseTypeName ensures that obj is not an alias name
690 // if it has attached methods.)
691 methods := check.methods[obj]
695 delete(check.methods, obj)
696 assert(!check.objMap[obj].tdecl.Alias) // don't use TypeName.IsAlias (requires fully set up object)
698 // use an objset to check for name conflicts
701 // spec: "If the base type is a struct type, the non-blank method
702 // and field names must be distinct."
703 base := asNamed(obj.typ) // shouldn't fail but be conservative
705 u := safeUnderlying(base) // base should be expanded, but use safeUnderlying to be conservative
706 if t, _ := u.(*Struct); t != nil {
707 for _, fld := range t.fields {
709 assert(mset.insert(fld) == nil)
714 // Checker.Files may be called multiple times; additional package files
715 // may add methods to already type-checked types. Add pre-existing methods
716 // so that we can detect redeclarations.
717 for _, m := range base.methods {
718 assert(m.name != "_")
719 assert(mset.insert(m) == nil)
724 for _, m := range methods {
725 // spec: "For a base type, the non-blank names of methods bound
726 // to it must be unique."
727 assert(m.name != "_")
728 if alt := mset.insert(m); alt != nil {
732 err.errorf(m.pos, "field and method with the same name %s", m.name)
734 if check.conf.CompilerErrorMessages {
735 err.errorf(m.pos, "%s.%s redeclared in this block", obj.Name(), m.name)
737 err.errorf(m.pos, "method %s already declared for %s", m.name, obj)
742 err.recordAltDecl(alt)
748 base.resolve(nil) // TODO(mdempsky): Probably unnecessary.
749 base.methods = append(base.methods, m)
754 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
755 assert(obj.typ == nil)
757 // func declarations cannot use iota
758 assert(check.iota == nil)
760 sig := new(Signature)
761 obj.typ = sig // guard against cycles
763 // Avoid cycle error when referring to method while type-checking the signature.
764 // This avoids a nuisance in the best case (non-parameterized receiver type) and
765 // since the method is not a type, we get an error. If we have a parameterized
766 // receiver type, instantiating the receiver type leads to the instantiation of
767 // its methods, and we don't want a cycle error in that case.
768 // TODO(gri) review if this is correct and/or whether we still need this?
772 check.funcType(sig, fdecl.Recv, fdecl.TParamList, fdecl.Type)
775 if len(fdecl.TParamList) > 0 && fdecl.Body == nil {
776 check.softErrorf(fdecl, "parameterized function is missing function body")
779 // function body must be type-checked after global declarations
780 // (functions implemented elsewhere have no body)
781 if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
783 check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
788 func (check *Checker) declStmt(list []syntax.Decl) {
791 first := -1 // index of first ConstDecl in the current group, or -1
792 var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
793 for index, decl := range list {
794 if _, ok := decl.(*syntax.ConstDecl); !ok {
795 first = -1 // we're not in a constant declaration
798 switch s := decl.(type) {
799 case *syntax.ConstDecl:
800 top := len(check.delayed)
802 // iota is the index of the current constDecl within the group
803 if first < 0 || list[index-1].(*syntax.ConstDecl).Group != s.Group {
807 iota := constant.MakeInt64(int64(index - first))
809 // determine which initialization expressions to use
812 case s.Type != nil || s.Values != nil:
816 last = new(syntax.ConstDecl) // make sure last exists
820 // declare all constants
821 lhs := make([]*Const, len(s.NameList))
822 values := unpackExpr(last.Values)
823 for i, name := range s.NameList {
824 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
832 check.constDecl(obj, last.Type, init, inherited)
835 // Constants must always have init values.
836 check.arity(s.Pos(), s.NameList, values, true, inherited)
838 // process function literals in init expressions before scope changes
839 check.processDelayed(top)
841 // spec: "The scope of a constant or variable identifier declared
842 // inside a function begins at the end of the ConstSpec or VarSpec
843 // (ShortVarDecl for short variable declarations) and ends at the
844 // end of the innermost containing block."
845 scopePos := syntax.EndPos(s)
846 for i, name := range s.NameList {
847 check.declare(check.scope, name, lhs[i], scopePos)
850 case *syntax.VarDecl:
851 top := len(check.delayed)
853 lhs0 := make([]*Var, len(s.NameList))
854 for i, name := range s.NameList {
855 lhs0[i] = NewVar(name.Pos(), pkg, name.Value, nil)
858 // initialize all variables
859 values := unpackExpr(s.Values)
860 for i, obj := range lhs0 {
864 case len(s.NameList):
868 // rhs is expected to be a multi-valued expression
876 check.varDecl(obj, lhs, s.Type, init)
877 if len(values) == 1 {
878 // If we have a single lhs variable we are done either way.
879 // If we have a single rhs expression, it must be a multi-
880 // valued expression, in which case handling the first lhs
881 // variable will cause all lhs variables to have a type
882 // assigned, and we are done as well.
884 for _, obj := range lhs0 {
885 assert(obj.typ != nil)
892 // If we have no type, we must have values.
893 if s.Type == nil || values != nil {
894 check.arity(s.Pos(), s.NameList, values, false, false)
897 // process function literals in init expressions before scope changes
898 check.processDelayed(top)
900 // declare all variables
901 // (only at this point are the variable scopes (parents) set)
902 scopePos := syntax.EndPos(s) // see constant declarations
903 for i, name := range s.NameList {
904 // see constant declarations
905 check.declare(check.scope, name, lhs0[i], scopePos)
908 case *syntax.TypeDecl:
909 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
910 // spec: "The scope of a type identifier declared inside a function
911 // begins at the identifier in the TypeSpec and ends at the end of
912 // the innermost containing block."
913 scopePos := s.Name.Pos()
914 check.declare(check.scope, s.Name, obj, scopePos)
915 // mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
916 obj.setColor(grey + color(check.push(obj)))
917 check.typeDecl(obj, s, nil)
918 check.pop().setColor(black)
921 check.errorf(s, invalidAST+"unknown syntax.Decl node %T", s)