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 // Checking the declaration of obj means inferring its type
70 // (and possibly its value, for constants).
71 // An object's type (and thus the object) may be in one of
72 // three states which are expressed by colors:
74 // - an object whose type is not yet known is painted white (initial color)
75 // - an object whose type is in the process of being inferred is painted grey
76 // - an object whose type is fully inferred is painted black
78 // During type inference, an object's color changes from white to grey
79 // to black (pre-declared objects are painted black from the start).
80 // A black object (i.e., its type) can only depend on (refer to) other black
81 // ones. White and grey objects may depend on white and black objects.
82 // A dependency on a grey object indicates a cycle which may or may not be
85 // When objects turn grey, they are pushed on the object path (a stack);
86 // they are popped again when they turn black. Thus, if a grey object (a
87 // cycle) is encountered, it is on the object path, and all the objects
88 // it depends on are the remaining objects on that path. Color encoding
89 // is such that the color value of a grey object indicates the index of
90 // that object in the object path.
92 // During type-checking, white objects may be assigned a type without
93 // traversing through objDecl; e.g., when initializing constants and
94 // variables. Update the colors of those objects here (rather than
95 // everywhere where we set the type) to satisfy the color invariants.
96 if obj.color() == white && obj.Type() != nil {
103 assert(obj.Type() == nil)
104 // All color values other than white and black are considered grey.
105 // Because black and white are < grey, all values >= grey are grey.
106 // Use those values to encode the object's index into the object path.
107 obj.setColor(grey + color(check.push(obj)))
109 check.pop().setColor(black)
113 assert(obj.Type() != nil)
117 // Color values other than white or black are considered grey.
122 // In the existing code, this is marked by a non-nil type
123 // for the object except for constants and variables whose
124 // type may be non-nil (known), or nil if it depends on the
125 // not-yet known initialization value.
126 // In the former case, set the type to Typ[Invalid] because
127 // we have an initialization cycle. The cycle error will be
128 // reported later, when determining initialization order.
129 // TODO(gri) Report cycle here and simplify initialization
131 switch obj := obj.(type) {
133 if check.cycle(obj) || obj.typ == nil {
134 obj.typ = Typ[Invalid]
138 if check.cycle(obj) || obj.typ == nil {
139 obj.typ = Typ[Invalid]
143 if check.cycle(obj) {
145 // (without this, calling underlying()
146 // below may lead to an endless loop
147 // if we have a cycle for a defined
149 obj.typ = Typ[Invalid]
153 if check.cycle(obj) {
154 // Don't set obj.typ to Typ[Invalid] here
155 // because plenty of code type-asserts that
156 // functions have a *Signature type. Grey
157 // functions have their type set to an empty
158 // signature which makes it impossible to
159 // initialize a variable with the function.
165 assert(obj.Type() != nil)
169 d := check.objMap[obj]
171 check.dump("%v: %s should have been declared", obj.Pos(), obj)
175 // save/restore current context and setup object context
176 defer func(ctxt context) {
179 check.context = context{
183 // Const and var declarations must not have initialization
184 // cycles. We track them by remembering the current declaration
185 // in check.decl. Initialization expressions depending on other
186 // consts, vars, or functions, add dependencies to the current
188 switch obj := obj.(type) {
190 check.decl = d // new package-level const decl
191 check.constDecl(obj, d.vtyp, d.init, d.inherited)
193 check.decl = d // new package-level var decl
194 check.varDecl(obj, d.lhs, d.vtyp, d.init)
196 // invalid recursive types are detected via path
197 check.typeDecl(obj, d.tdecl, def)
198 check.collectMethods(obj) // methods can only be added to top-level types
200 // functions may be recursive - no need to track dependencies
201 check.funcDecl(obj, d)
207 // cycle checks if the cycle starting with obj is valid and
208 // reports an error if it is not.
209 func (check *Checker) cycle(obj Object) (isCycle bool) {
210 // The object map contains the package scope objects and the non-interface methods.
212 info := check.objMap[obj]
213 inObjMap := info != nil && (info.fdecl == nil || info.fdecl.Recv == nil) // exclude methods
214 isPkgObj := obj.Parent() == check.pkg.scope
215 if isPkgObj != inObjMap {
216 check.dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", obj.Pos(), obj, isPkgObj, inObjMap)
221 // Count cycle objects.
222 assert(obj.color() >= grey)
223 start := obj.color() - grey // index of obj in objPath
224 cycle := check.objPath[start:]
225 nval := 0 // number of (constant or variable) values in the cycle
226 ndef := 0 // number of type definitions in the cycle
227 for _, obj := range cycle {
228 switch obj := obj.(type) {
232 // Determine if the type name is an alias or not. For
233 // package-level objects, use the object map which
234 // provides syntactic information (which doesn't rely
235 // on the order in which the objects are set up). For
236 // local objects, we can rely on the order, so use
237 // the object's predicate.
238 // TODO(gri) It would be less fragile to always access
239 // the syntactic information. We should consider storing
240 // this information explicitly in the object.
242 if d := check.objMap[obj]; d != nil {
243 alias = d.tdecl.Alias // package-level object
245 alias = obj.IsAlias() // function local object
257 if check.conf.Trace {
258 check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
259 check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
262 check.trace(obj.Pos(), "=> error: cycle is invalid")
267 // A cycle involving only constants and variables is invalid but we
268 // ignore them here because they are reported via the initialization
270 if nval == len(cycle) {
274 // A cycle involving only types (and possibly functions) must have at least
275 // one type definition to be permitted: If there is no type definition, we
276 // have a sequence of alias type names which will expand ad infinitum.
277 if nval == 0 && ndef > 0 {
278 return false // cycle is permitted
281 check.cycleError(cycle)
288 // validType verifies that the given type does not "expand" infinitely
289 // producing a cycle in the type graph. Cycles are detected by marking
291 // (Cycles involving alias types, as in "type A = [10]A" are detected
292 // earlier, via the objDecl cycle detection mechanism.)
293 func (check *Checker) validType(typ Type, path []Object) typeInfo {
295 unknown typeInfo = iota
301 switch t := typ.(type) {
303 return check.validType(t.elem, path)
306 for _, f := range t.fields {
307 if check.validType(f.typ, path) == invalid {
313 for _, etyp := range t.embeddeds {
314 if check.validType(etyp, path) == invalid {
320 t.expand(check.typMap)
322 // don't touch the type if it is from a different package or the Universe scope
323 // (doing so would lead to a race condition - was issue #35049)
324 if t.obj.pkg != check.pkg {
328 // don't report a 2nd error if we already know the type is invalid
329 // (e.g., if a cycle was detected earlier, via under).
330 if t.underlying == Typ[Invalid] {
338 t.info = check.validType(t.fromRHS, append(path, t.obj)) // only types of current package added to path
341 for i, tn := range path {
342 if t.obj.pkg != check.pkg {
343 panic("type cycle via package-external type")
346 check.cycleError(path[i:])
351 panic("cycle start not found")
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)
368 if check.conf.CompilerErrorMessages {
369 err.errorf(obj, "invalid recursive type %s", obj.Name())
371 err.errorf(obj, "illegal cycle in declaration of %s", obj.Name())
374 err.errorf(obj, "%s refers to", obj.Name())
381 err.errorf(obj, "%s", obj.Name())
385 // firstInSrc reports the index of the object with the "smallest"
386 // source position in path. path must not be empty.
387 func firstInSrc(path []Object) int {
388 fst, pos := 0, path[0].Pos()
389 for i, t := range path[1:] {
390 if t.Pos().Cmp(pos) < 0 {
391 fst, pos = i+1, t.Pos()
397 func (check *Checker) constDecl(obj *Const, typ, init syntax.Expr, inherited bool) {
398 assert(obj.typ == nil)
400 // use the correct value of iota and errpos
401 defer func(iota constant.Value, errpos syntax.Pos) {
403 check.errpos = errpos
404 }(check.iota, check.errpos)
408 // provide valid constant value under all circumstances
409 obj.val = constant.MakeUnknown()
411 // determine type, if any
415 // don't report an error if the type is an invalid C (defined) type
417 if under(t) != Typ[Invalid] {
418 check.errorf(typ, "invalid constant type %s", t)
420 obj.typ = Typ[Invalid]
426 // check initialization
430 // The initialization expression is inherited from a previous
431 // constant declaration, and (error) positions refer to that
432 // expression and not the current constant declaration. Use
433 // the constant identifier position for any errors during
434 // init expression evaluation since that is all we have
435 // (see issues #42991, #42992).
436 check.errpos = obj.pos
440 check.initConst(obj, &x)
443 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init syntax.Expr) {
444 assert(obj.typ == nil)
446 // If we have undefined variable types due to errors,
447 // mark variables as used to avoid follow-on errors.
448 // Matches compiler behavior.
450 if obj.typ == Typ[Invalid] {
453 for _, lhs := range lhs {
454 if lhs.typ == Typ[Invalid] {
460 // determine type, if any
462 obj.typ = check.varType(typ)
463 // We cannot spread the type to all lhs variables if there
464 // are more than one since that would mark them as checked
465 // (see Checker.objDecl) and the assignment of init exprs,
466 // if any, would not be checked.
468 // TODO(gri) If we have no init expr, we should distribute
469 // a given type otherwise we need to re-evalate the type
470 // expr for each lhs variable, leading to duplicate work.
473 // check initialization
476 // error reported before by arityMatch
477 obj.typ = Typ[Invalid]
482 if lhs == nil || len(lhs) == 1 {
483 assert(lhs == nil || lhs[0] == obj)
486 check.initVar(obj, &x, "variable declaration")
491 // obj must be one of lhs
493 for _, lhs := range lhs {
500 panic("inconsistent lhs")
504 // We have multiple variables on the lhs and one init expr.
505 // Make sure all variables have been given the same type if
506 // one was specified, otherwise they assume the type of the
507 // init expression values (was issue #15755).
509 for _, lhs := range lhs {
514 check.initVars(lhs, []syntax.Expr{init}, nopos)
517 // isImportedConstraint reports whether typ is an imported type constraint.
518 func (check *Checker) isImportedConstraint(typ Type) bool {
519 named, _ := typ.(*Named)
520 if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
523 u, _ := named.under().(*Interface)
524 return u != nil && u.IsConstraint()
527 func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *Named) {
528 assert(obj.typ == nil)
532 check.validType(obj.typ, nil)
533 // If typ is local, an error was already reported where typ is specified/defined.
534 if check.isImportedConstraint(rhs) && !check.allowVersion(check.pkg, 1, 18) {
535 check.errorf(tdecl.Type.Pos(), "using type constraint %s requires go1.18 or later", rhs)
540 if alias && tdecl.TParamList != nil {
541 // The parser will ensure this but we may still get an invalid AST.
542 // Complain and continue as regular type definition.
543 check.error(tdecl, "generic type cannot be alias")
549 if !check.allowVersion(check.pkg, 1, 9) {
550 if check.conf.CompilerErrorMessages {
551 check.error(tdecl, "type aliases only supported as of -lang=go1.9")
553 check.error(tdecl, "type aliases requires go1.9 or later")
557 obj.typ = Typ[Invalid]
558 rhs = check.anyType(tdecl.Type)
563 // type definition or generic type declaration
564 named := check.newNamed(obj, nil, nil, nil, nil)
565 def.setUnderlying(named)
567 if tdecl.TParamList != nil {
568 check.openScope(tdecl, "type parameters")
569 defer check.closeScope()
570 named.tparams = check.collectTypeParams(tdecl.TParamList)
573 // determine underlying type of named
574 rhs = check.definedType(tdecl.Type, named)
577 // The underlying type of named may be itself a named type that is
586 // The type of C is the (named) type of A which is incomplete,
587 // and which has as its underlying type the named type B.
588 // Determine the (final, unnamed) underlying type by resolving
589 // any forward chain.
590 // TODO(gri) Investigate if we can just use named.fromRHS here
591 // and rely on lazy computation of the underlying type.
592 named.underlying = under(named)
594 // If the RHS is a type parameter, it must be from this type declaration.
595 if tpar, _ := named.underlying.(*TypeParam); tpar != nil && tparamIndex(named.TParams().list(), tpar) < 0 {
596 check.errorf(tdecl.Type, "cannot use function type parameter %s as RHS in type declaration", tpar)
597 named.underlying = Typ[Invalid]
601 func (check *Checker) collectTypeParams(list []*syntax.Field) *TParamList {
602 tparams := make([]*TypeParam, len(list))
604 // Declare type parameters up-front.
605 // The scope of type parameters starts at the beginning of the type parameter
606 // list (so we can have mutually recursive parameterized type bounds).
607 for i, f := range list {
608 tparams[i] = check.declareTypeParam(f.Name)
612 for i, f := range list {
613 // Optimization: Re-use the previous type bound if it hasn't changed.
614 // This also preserves the grouped output of type parameter lists
615 // when printing type strings.
616 if i == 0 || f.Type != list[i-1].Type {
617 bound = check.boundType(f.Type)
619 tparams[i].bound = bound
622 return bindTParams(tparams)
625 func (check *Checker) declareTypeParam(name *syntax.Name) *TypeParam {
626 tname := NewTypeName(name.Pos(), check.pkg, name.Value, nil)
627 tpar := check.NewTypeParam(tname, nil) // assigns type to tname as a side-effect
628 check.declare(check.scope, name, tname, check.scope.pos) // TODO(gri) check scope position
632 // boundType type-checks the type expression e and returns its type, or Typ[Invalid].
633 // The type must be an interface, including the predeclared type "any".
634 func (check *Checker) boundType(e syntax.Expr) Type {
635 // The predeclared identifier "any" is visible only as a type bound in a type parameter list.
636 // If we allow "any" for general use, this if-statement can be removed (issue #33232).
637 if name, _ := unparen(e).(*syntax.Name); name != nil && name.Value == "any" && check.lookup("any") == universeAny {
638 return universeAny.Type()
641 bound := check.typ(e)
644 if _, ok := u.(*Interface); !ok && u != Typ[Invalid] {
645 check.errorf(e, "%s is not an interface", bound)
651 func (check *Checker) collectMethods(obj *TypeName) {
652 // get associated methods
653 // (Checker.collectObjects only collects methods with non-blank names;
654 // Checker.resolveBaseTypeName ensures that obj is not an alias name
655 // if it has attached methods.)
656 methods := check.methods[obj]
660 delete(check.methods, obj)
661 assert(!check.objMap[obj].tdecl.Alias) // don't use TypeName.IsAlias (requires fully set up object)
663 // use an objset to check for name conflicts
666 // spec: "If the base type is a struct type, the non-blank method
667 // and field names must be distinct."
668 base := asNamed(obj.typ) // shouldn't fail but be conservative
670 u := safeUnderlying(base) // base should be expanded, but use safeUnderlying to be conservative
671 if t, _ := u.(*Struct); t != nil {
672 for _, fld := range t.fields {
674 assert(mset.insert(fld) == nil)
679 // Checker.Files may be called multiple times; additional package files
680 // may add methods to already type-checked types. Add pre-existing methods
681 // so that we can detect redeclarations.
682 for _, m := range base.methods {
683 assert(m.name != "_")
684 assert(mset.insert(m) == nil)
689 for _, m := range methods {
690 // spec: "For a base type, the non-blank names of methods bound
691 // to it must be unique."
692 assert(m.name != "_")
693 if alt := mset.insert(m); alt != nil {
697 err.errorf(m.pos, "field and method with the same name %s", m.name)
699 if check.conf.CompilerErrorMessages {
700 err.errorf(m.pos, "%s.%s redeclared in this block", obj.Name(), m.name)
702 err.errorf(m.pos, "method %s already declared for %s", m.name, obj)
707 err.recordAltDecl(alt)
713 base.load() // TODO(mdempsky): Probably unnecessary.
714 base.methods = append(base.methods, m)
719 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
720 assert(obj.typ == nil)
722 // func declarations cannot use iota
723 assert(check.iota == nil)
725 sig := new(Signature)
726 obj.typ = sig // guard against cycles
728 // Avoid cycle error when referring to method while type-checking the signature.
729 // This avoids a nuisance in the best case (non-parameterized receiver type) and
730 // since the method is not a type, we get an error. If we have a parameterized
731 // receiver type, instantiating the receiver type leads to the instantiation of
732 // its methods, and we don't want a cycle error in that case.
733 // TODO(gri) review if this is correct and/or whether we still need this?
737 check.funcType(sig, fdecl.Recv, fdecl.TParamList, fdecl.Type)
740 if len(fdecl.TParamList) > 0 && fdecl.Body == nil {
741 check.softErrorf(fdecl, "parameterized function is missing function body")
744 // function body must be type-checked after global declarations
745 // (functions implemented elsewhere have no body)
746 if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
748 check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
753 func (check *Checker) declStmt(list []syntax.Decl) {
756 first := -1 // index of first ConstDecl in the current group, or -1
757 var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
758 for index, decl := range list {
759 if _, ok := decl.(*syntax.ConstDecl); !ok {
760 first = -1 // we're not in a constant declaration
763 switch s := decl.(type) {
764 case *syntax.ConstDecl:
765 top := len(check.delayed)
767 // iota is the index of the current constDecl within the group
768 if first < 0 || list[index-1].(*syntax.ConstDecl).Group != s.Group {
772 iota := constant.MakeInt64(int64(index - first))
774 // determine which initialization expressions to use
777 case s.Type != nil || s.Values != nil:
781 last = new(syntax.ConstDecl) // make sure last exists
785 // declare all constants
786 lhs := make([]*Const, len(s.NameList))
787 values := unpackExpr(last.Values)
788 for i, name := range s.NameList {
789 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
797 check.constDecl(obj, last.Type, init, inherited)
800 // Constants must always have init values.
801 check.arity(s.Pos(), s.NameList, values, true, inherited)
803 // process function literals in init expressions before scope changes
804 check.processDelayed(top)
806 // spec: "The scope of a constant or variable identifier declared
807 // inside a function begins at the end of the ConstSpec or VarSpec
808 // (ShortVarDecl for short variable declarations) and ends at the
809 // end of the innermost containing block."
810 scopePos := syntax.EndPos(s)
811 for i, name := range s.NameList {
812 check.declare(check.scope, name, lhs[i], scopePos)
815 case *syntax.VarDecl:
816 top := len(check.delayed)
818 lhs0 := make([]*Var, len(s.NameList))
819 for i, name := range s.NameList {
820 lhs0[i] = NewVar(name.Pos(), pkg, name.Value, nil)
823 // initialize all variables
824 values := unpackExpr(s.Values)
825 for i, obj := range lhs0 {
829 case len(s.NameList):
833 // rhs is expected to be a multi-valued expression
841 check.varDecl(obj, lhs, s.Type, init)
842 if len(values) == 1 {
843 // If we have a single lhs variable we are done either way.
844 // If we have a single rhs expression, it must be a multi-
845 // valued expression, in which case handling the first lhs
846 // variable will cause all lhs variables to have a type
847 // assigned, and we are done as well.
849 for _, obj := range lhs0 {
850 assert(obj.typ != nil)
857 // If we have no type, we must have values.
858 if s.Type == nil || values != nil {
859 check.arity(s.Pos(), s.NameList, values, false, false)
862 // process function literals in init expressions before scope changes
863 check.processDelayed(top)
865 // declare all variables
866 // (only at this point are the variable scopes (parents) set)
867 scopePos := syntax.EndPos(s) // see constant declarations
868 for i, name := range s.NameList {
869 // see constant declarations
870 check.declare(check.scope, name, lhs0[i], scopePos)
873 case *syntax.TypeDecl:
874 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
875 // spec: "The scope of a type identifier declared inside a function
876 // begins at the identifier in the TypeSpec and ends at the end of
877 // the innermost containing block."
878 scopePos := s.Name.Pos()
879 check.declare(check.scope, s.Name, obj, scopePos)
880 // mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
881 obj.setColor(grey + color(check.push(obj)))
882 check.typeDecl(obj, s, nil)
883 check.pop().setColor(black)
886 check.errorf(s, invalidAST+"unknown syntax.Decl node %T", s)