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.
9 "cmd/compile/internal/syntax"
14 func (err *error_) recordAltDecl(obj Object) {
15 if pos := obj.Pos(); pos.IsKnown() {
16 // We use "other" rather than "previous" here because
17 // the first declaration seen may not be textually
18 // earlier in the source.
19 err.errorf(pos, "other declaration of %s", obj.Name())
23 func (check *Checker) declare(scope *Scope, id *syntax.Name, obj Object, pos syntax.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
28 if obj.Name() != "_" {
29 if alt := scope.Insert(obj); alt != nil {
31 err.errorf(obj, "%s redeclared in this block", obj.Name())
32 err.recordAltDecl(alt)
39 check.recordDef(id, obj)
43 // pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
44 func pathString(path []Object) string {
46 for i, p := range path {
55 // objDecl type-checks the declaration of obj in its respective (file) environment.
56 // For the meaning of def, see Checker.definedType, in typexpr.go.
57 func (check *Checker) objDecl(obj Object, def *Named) {
58 if check.conf.Trace && obj.Type() == nil {
59 if check.indent == 0 {
60 fmt.Println() // empty line between top-level objects for readability
62 check.trace(obj.Pos(), "-- checking %s (%s, objPath = %s)", obj, obj.color(), pathString(check.objPath))
66 check.trace(obj.Pos(), "=> %s (%s)", obj, obj.color())
70 // Checking the declaration of obj means inferring its type
71 // (and possibly its value, for constants).
72 // An object's type (and thus the object) may be in one of
73 // three states which are expressed by colors:
75 // - an object whose type is not yet known is painted white (initial color)
76 // - an object whose type is in the process of being inferred is painted grey
77 // - an object whose type is fully inferred is painted black
79 // During type inference, an object's color changes from white to grey
80 // to black (pre-declared objects are painted black from the start).
81 // A black object (i.e., its type) can only depend on (refer to) other black
82 // ones. White and grey objects may depend on white and black objects.
83 // A dependency on a grey object indicates a cycle which may or may not be
86 // When objects turn grey, they are pushed on the object path (a stack);
87 // they are popped again when they turn black. Thus, if a grey object (a
88 // cycle) is encountered, it is on the object path, and all the objects
89 // it depends on are the remaining objects on that path. Color encoding
90 // is such that the color value of a grey object indicates the index of
91 // that object in the object path.
93 // During type-checking, white objects may be assigned a type without
94 // traversing through objDecl; e.g., when initializing constants and
95 // variables. Update the colors of those objects here (rather than
96 // everywhere where we set the type) to satisfy the color invariants.
97 if obj.color() == white && obj.Type() != nil {
104 assert(obj.Type() == nil)
105 // All color values other than white and black are considered grey.
106 // Because black and white are < grey, all values >= grey are grey.
107 // Use those values to encode the object's index into the object path.
108 obj.setColor(grey + color(check.push(obj)))
110 check.pop().setColor(black)
114 assert(obj.Type() != nil)
118 // Color values other than white or black are considered grey.
122 // We have a (possibly invalid) cycle.
123 // In the existing code, this is marked by a non-nil type
124 // for the object except for constants and variables whose
125 // type may be non-nil (known), or nil if it depends on the
126 // not-yet known initialization value.
127 // In the former case, set the type to Typ[Invalid] because
128 // we have an initialization cycle. The cycle error will be
129 // reported later, when determining initialization order.
130 // TODO(gri) Report cycle here and simplify initialization
132 switch obj := obj.(type) {
134 if !check.validCycle(obj) || obj.typ == nil {
135 obj.typ = Typ[Invalid]
139 if !check.validCycle(obj) || obj.typ == nil {
140 obj.typ = Typ[Invalid]
144 if !check.validCycle(obj) {
146 // (without this, calling underlying()
147 // below may lead to an endless loop
148 // if we have a cycle for a defined
150 obj.typ = Typ[Invalid]
154 if !check.validCycle(obj) {
155 // Don't set obj.typ to Typ[Invalid] here
156 // because plenty of code type-asserts that
157 // functions have a *Signature type. Grey
158 // functions have their type set to an empty
159 // signature which makes it impossible to
160 // initialize a variable with the function.
166 assert(obj.Type() != nil)
170 d := check.objMap[obj]
172 check.dump("%v: %s should have been declared", obj.Pos(), obj)
176 // save/restore current environment and set up object environment
177 defer func(env environment) {
178 check.environment = env
180 check.environment = environment{
184 // Const and var declarations must not have initialization
185 // cycles. We track them by remembering the current declaration
186 // in check.decl. Initialization expressions depending on other
187 // consts, vars, or functions, add dependencies to the current
189 switch obj := obj.(type) {
191 check.decl = d // new package-level const decl
192 check.constDecl(obj, d.vtyp, d.init, d.inherited)
194 check.decl = d // new package-level var decl
195 check.varDecl(obj, d.lhs, d.vtyp, d.init)
197 // invalid recursive types are detected via path
198 check.typeDecl(obj, d.tdecl, def)
199 check.collectMethods(obj) // methods can only be added to top-level types
201 // functions may be recursive - no need to track dependencies
202 check.funcDecl(obj, d)
208 // validCycle reports whether the cycle starting with obj is valid and
209 // reports an error if it is not.
210 func (check *Checker) validCycle(obj Object) (valid bool) {
211 // The object map contains the package scope objects and the non-interface methods.
213 info := check.objMap[obj]
214 inObjMap := info != nil && (info.fdecl == nil || info.fdecl.Recv == nil) // exclude methods
215 isPkgObj := obj.Parent() == check.pkg.scope
216 if isPkgObj != inObjMap {
217 check.dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", obj.Pos(), obj, isPkgObj, inObjMap)
222 // Count cycle objects.
223 assert(obj.color() >= grey)
224 start := obj.color() - grey // index of obj in objPath
225 cycle := check.objPath[start:]
226 tparCycle := false // if set, the cycle is through a type parameter list
227 nval := 0 // number of (constant or variable) values in the cycle; valid if !generic
228 ndef := 0 // number of type definitions in the cycle; valid if !generic
230 for _, obj := range cycle {
231 switch obj := obj.(type) {
235 // If we reach a generic type that is part of a cycle
236 // and we are in a type parameter list, we have a cycle
237 // through a type parameter list, which is invalid.
238 if check.inTParamList && isGeneric(obj.typ) {
243 // Determine if the type name is an alias or not. For
244 // package-level objects, use the object map which
245 // provides syntactic information (which doesn't rely
246 // on the order in which the objects are set up). For
247 // local objects, we can rely on the order, so use
248 // the object's predicate.
249 // TODO(gri) It would be less fragile to always access
250 // the syntactic information. We should consider storing
251 // this information explicitly in the object.
253 if d := check.objMap[obj]; d != nil {
254 alias = d.tdecl.Alias // package-level object
256 alias = obj.IsAlias() // function local object
268 if check.conf.Trace {
269 check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
271 check.trace(obj.Pos(), "## cycle contains: generic type in a type parameter list")
273 check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
277 check.trace(obj.Pos(), "=> cycle is valid")
279 check.trace(obj.Pos(), "=> error: cycle is invalid")
285 // A cycle involving only constants and variables is invalid but we
286 // ignore them here because they are reported via the initialization
288 if nval == len(cycle) {
292 // A cycle involving only types (and possibly functions) must have at least
293 // one type definition to be permitted: If there is no type definition, we
294 // have a sequence of alias type names which will expand ad infinitum.
295 if nval == 0 && ndef > 0 {
300 check.cycleError(cycle)
304 // cycleError reports a declaration cycle starting with
305 // the object in cycle that is "first" in the source.
306 func (check *Checker) cycleError(cycle []Object) {
307 // name returns the (possibly qualified) object name.
308 // This is needed because with generic types, cycles
309 // may refer to imported types. See issue #50788.
310 // TODO(gri) Thus functionality is used elsewhere. Factor it out.
311 name := func(obj Object) string {
313 writePackage(&buf, obj.Pkg(), check.qualifier)
314 buf.WriteString(obj.Name())
318 // TODO(gri) Should we start with the last (rather than the first) object in the cycle
319 // since that is the earliest point in the source where we start seeing the
320 // cycle? That would be more consistent with other error messages.
321 i := firstInSrc(cycle)
324 // If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors.
325 tname, _ := obj.(*TypeName)
326 if tname != nil && tname.IsAlias() {
327 check.validAlias(tname, Typ[Invalid])
330 if tname != nil && check.conf.CompilerErrorMessages {
331 err.errorf(obj, "invalid recursive type %s", objName)
333 err.errorf(obj, "illegal cycle in declaration of %s", objName)
336 err.errorf(obj, "%s refers to", objName)
344 err.errorf(obj, "%s", objName)
348 // firstInSrc reports the index of the object with the "smallest"
349 // source position in path. path must not be empty.
350 func firstInSrc(path []Object) int {
351 fst, pos := 0, path[0].Pos()
352 for i, t := range path[1:] {
353 if t.Pos().Cmp(pos) < 0 {
354 fst, pos = i+1, t.Pos()
360 func (check *Checker) constDecl(obj *Const, typ, init syntax.Expr, inherited bool) {
361 assert(obj.typ == nil)
363 // use the correct value of iota and errpos
364 defer func(iota constant.Value, errpos syntax.Pos) {
366 check.errpos = errpos
367 }(check.iota, check.errpos)
371 // provide valid constant value under all circumstances
372 obj.val = constant.MakeUnknown()
374 // determine type, if any
378 // don't report an error if the type is an invalid C (defined) type
380 if under(t) != Typ[Invalid] {
381 check.errorf(typ, "invalid constant type %s", t)
383 obj.typ = Typ[Invalid]
389 // check initialization
393 // The initialization expression is inherited from a previous
394 // constant declaration, and (error) positions refer to that
395 // expression and not the current constant declaration. Use
396 // the constant identifier position for any errors during
397 // init expression evaluation since that is all we have
398 // (see issues #42991, #42992).
399 check.errpos = obj.pos
403 check.initConst(obj, &x)
406 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init syntax.Expr) {
407 assert(obj.typ == nil)
409 // If we have undefined variable types due to errors,
410 // mark variables as used to avoid follow-on errors.
411 // Matches compiler behavior.
413 if obj.typ == Typ[Invalid] {
416 for _, lhs := range lhs {
417 if lhs.typ == Typ[Invalid] {
423 // determine type, if any
425 obj.typ = check.varType(typ)
426 // We cannot spread the type to all lhs variables if there
427 // are more than one since that would mark them as checked
428 // (see Checker.objDecl) and the assignment of init exprs,
429 // if any, would not be checked.
431 // TODO(gri) If we have no init expr, we should distribute
432 // a given type otherwise we need to re-evalate the type
433 // expr for each lhs variable, leading to duplicate work.
436 // check initialization
439 // error reported before by arityMatch
440 obj.typ = Typ[Invalid]
445 if lhs == nil || len(lhs) == 1 {
446 assert(lhs == nil || lhs[0] == obj)
449 check.initVar(obj, &x, "variable declaration")
454 // obj must be one of lhs
456 for _, lhs := range lhs {
463 panic("inconsistent lhs")
467 // We have multiple variables on the lhs and one init expr.
468 // Make sure all variables have been given the same type if
469 // one was specified, otherwise they assume the type of the
470 // init expression values (was issue #15755).
472 for _, lhs := range lhs {
477 check.initVars(lhs, []syntax.Expr{init}, nil)
480 // isImportedConstraint reports whether typ is an imported type constraint.
481 func (check *Checker) isImportedConstraint(typ Type) bool {
482 named, _ := typ.(*Named)
483 if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
486 u, _ := named.under().(*Interface)
487 return u != nil && !u.IsMethodSet()
490 func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *Named) {
491 assert(obj.typ == nil)
495 if t, _ := obj.typ.(*Named); t != nil { // type may be invalid
498 // If typ is local, an error was already reported where typ is specified/defined.
499 if check.isImportedConstraint(rhs) && !check.allowVersion(check.pkg, 1, 18) {
500 check.versionErrorf(tdecl.Type, "go1.18", "using type constraint %s", rhs)
502 }).describef(obj, "validType(%s)", obj.Name())
505 if alias && tdecl.TParamList != nil {
506 // The parser will ensure this but we may still get an invalid AST.
507 // Complain and continue as regular type definition.
508 check.error(tdecl, "generic type cannot be alias")
514 if !check.allowVersion(check.pkg, 1, 9) {
515 check.versionErrorf(tdecl, "go1.9", "type aliases")
518 check.brokenAlias(obj)
519 rhs = check.typ(tdecl.Type)
520 check.validAlias(obj, rhs)
524 // type definition or generic type declaration
525 named := check.newNamed(obj, nil, nil)
526 def.setUnderlying(named)
528 if tdecl.TParamList != nil {
529 check.openScope(tdecl, "type parameters")
530 defer check.closeScope()
531 check.collectTypeParams(&named.tparams, tdecl.TParamList)
534 // determine underlying type of named
535 rhs = check.definedType(tdecl.Type, named)
539 // If the underlying type was not set while type-checking the right-hand
540 // side, it is invalid and an error should have been reported elsewhere.
541 if named.underlying == nil {
542 named.underlying = Typ[Invalid]
545 // Disallow a lone type parameter as the RHS of a type declaration (issue #45639).
546 // We don't need this restriction anymore if we make the underlying type of a type
547 // parameter its constraint interface: if the RHS is a lone type parameter, we will
548 // use its underlying type (like we do for any RHS in a type declaration), and its
549 // underlying type is an interface and the type declaration is well defined.
550 if isTypeParam(rhs) {
551 check.error(tdecl.Type, "cannot use a type parameter as RHS in type declaration")
552 named.underlying = Typ[Invalid]
556 func (check *Checker) collectTypeParams(dst **TypeParamList, list []*syntax.Field) {
557 tparams := make([]*TypeParam, len(list))
559 // Declare type parameters up-front.
560 // The scope of type parameters starts at the beginning of the type parameter
561 // list (so we can have mutually recursive parameterized type bounds).
562 for i, f := range list {
563 tparams[i] = check.declareTypeParam(f.Name)
566 // Set the type parameters before collecting the type constraints because
567 // the parameterized type may be used by the constraints (issue #47887).
568 // Example: type T[P T[P]] interface{}
569 *dst = bindTParams(tparams)
571 // Signal to cycle detection that we are in a type parameter list.
572 // We can only be inside one type parameter list at any given time:
573 // function closures may appear inside a type parameter list but they
574 // cannot be generic, and their bodies are processed in delayed and
575 // sequential fashion. Note that with each new declaration, we save
576 // the existing environment and restore it when done; thus inTParamList
577 // is true exactly only when we are in a specific type parameter list.
578 assert(!check.inTParamList)
579 check.inTParamList = true
581 check.inTParamList = false
584 // Keep track of bounds for later validation.
586 for i, f := range list {
587 // Optimization: Re-use the previous type bound if it hasn't changed.
588 // This also preserves the grouped output of type parameter lists
589 // when printing type strings.
590 if i == 0 || f.Type != list[i-1].Type {
591 bound = check.bound(f.Type)
592 if isTypeParam(bound) {
593 // We may be able to allow this since it is now well-defined what
594 // the underlying type and thus type set of a type parameter is.
595 // But we may need some additional form of cycle detection within
596 // type parameter lists.
597 check.error(f.Type, "cannot use a type parameter as constraint")
601 tparams[i].bound = bound
605 func (check *Checker) bound(x syntax.Expr) Type {
606 // A type set literal of the form ~T and A|B may only appear as constraint;
607 // embed it in an implicit interface so that only interface type-checking
608 // needs to take care of such type expressions.
609 if op, _ := x.(*syntax.Operation); op != nil && (op.Op == syntax.Tilde || op.Op == syntax.Or) {
610 t := check.typ(&syntax.InterfaceType{MethodList: []*syntax.Field{{Type: x}}})
611 // mark t as implicit interface if all went well
612 if t, _ := t.(*Interface); t != nil {
620 func (check *Checker) declareTypeParam(name *syntax.Name) *TypeParam {
621 // Use Typ[Invalid] for the type constraint to ensure that a type
622 // is present even if the actual constraint has not been assigned
624 // TODO(gri) Need to systematically review all uses of type parameter
625 // constraints to make sure we don't rely on them if they
626 // are not properly set yet.
627 tname := NewTypeName(name.Pos(), check.pkg, name.Value, nil)
628 tpar := check.newTypeParam(tname, Typ[Invalid]) // assigns type to tname as a side-effect
629 check.declare(check.scope, name, tname, check.scope.pos) // TODO(gri) check scope position
633 func (check *Checker) collectMethods(obj *TypeName) {
634 // get associated methods
635 // (Checker.collectObjects only collects methods with non-blank names;
636 // Checker.resolveBaseTypeName ensures that obj is not an alias name
637 // if it has attached methods.)
638 methods := check.methods[obj]
642 delete(check.methods, obj)
643 assert(!check.objMap[obj].tdecl.Alias) // don't use TypeName.IsAlias (requires fully set up object)
645 // use an objset to check for name conflicts
648 // spec: "If the base type is a struct type, the non-blank method
649 // and field names must be distinct."
650 base, _ := obj.typ.(*Named) // shouldn't fail but be conservative
652 assert(base.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type
654 // See issue #52529: we must delay the expansion of underlying here, as
655 // base may not be fully set-up.
657 check.checkFieldUniqueness(base)
658 }).describef(obj, "verifying field uniqueness for %v", base)
660 // Checker.Files may be called multiple times; additional package files
661 // may add methods to already type-checked types. Add pre-existing methods
662 // so that we can detect redeclarations.
663 for i := 0; i < base.NumMethods(); i++ {
665 assert(m.name != "_")
666 assert(mset.insert(m) == nil)
671 for _, m := range methods {
672 // spec: "For a base type, the non-blank names of methods bound
673 // to it must be unique."
674 assert(m.name != "_")
675 if alt := mset.insert(m); alt != nil {
677 if check.conf.CompilerErrorMessages {
678 err.errorf(m.pos, "%s.%s redeclared in this block", obj.Name(), m.name)
680 err.errorf(m.pos, "method %s already declared for %s", m.name, obj)
682 err.recordAltDecl(alt)
693 func (check *Checker) checkFieldUniqueness(base *Named) {
694 if t, _ := base.under().(*Struct); t != nil {
696 for i := 0; i < base.NumMethods(); i++ {
698 assert(m.name != "_")
699 assert(mset.insert(m) == nil)
702 // Check that any non-blank field names of base are distinct from its
704 for _, fld := range t.fields {
706 if alt := mset.insert(fld); alt != nil {
707 // Struct fields should already be unique, so we should only
708 // encounter an alternate via collision with a method name.
711 // For historical consistency, we report the primary error on the
712 // method, and the alt decl on the field.
714 err.errorf(alt, "field and method with the same name %s", fld.name)
715 err.recordAltDecl(fld)
723 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
724 assert(obj.typ == nil)
726 // func declarations cannot use iota
727 assert(check.iota == nil)
729 sig := new(Signature)
730 obj.typ = sig // guard against cycles
732 // Avoid cycle error when referring to method while type-checking the signature.
733 // This avoids a nuisance in the best case (non-parameterized receiver type) and
734 // since the method is not a type, we get an error. If we have a parameterized
735 // receiver type, instantiating the receiver type leads to the instantiation of
736 // its methods, and we don't want a cycle error in that case.
737 // TODO(gri) review if this is correct and/or whether we still need this?
741 check.funcType(sig, fdecl.Recv, fdecl.TParamList, fdecl.Type)
744 if len(fdecl.TParamList) > 0 && fdecl.Body == nil {
745 check.softErrorf(fdecl, "parameterized function is missing function body")
748 // function body must be type-checked after global declarations
749 // (functions implemented elsewhere have no body)
750 if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
752 check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
753 }).describef(obj, "func %s", obj.name)
757 func (check *Checker) declStmt(list []syntax.Decl) {
760 first := -1 // index of first ConstDecl in the current group, or -1
761 var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
762 for index, decl := range list {
763 if _, ok := decl.(*syntax.ConstDecl); !ok {
764 first = -1 // we're not in a constant declaration
767 switch s := decl.(type) {
768 case *syntax.ConstDecl:
769 top := len(check.delayed)
771 // iota is the index of the current constDecl within the group
772 if first < 0 || s.Group == nil || list[index-1].(*syntax.ConstDecl).Group != s.Group {
776 iota := constant.MakeInt64(int64(index - first))
778 // determine which initialization expressions to use
781 case s.Type != nil || s.Values != nil:
785 last = new(syntax.ConstDecl) // make sure last exists
789 // declare all constants
790 lhs := make([]*Const, len(s.NameList))
791 values := unpackExpr(last.Values)
792 for i, name := range s.NameList {
793 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
801 check.constDecl(obj, last.Type, init, inherited)
804 // Constants must always have init values.
805 check.arity(s.Pos(), s.NameList, values, true, inherited)
807 // process function literals in init expressions before scope changes
808 check.processDelayed(top)
810 // spec: "The scope of a constant or variable identifier declared
811 // inside a function begins at the end of the ConstSpec or VarSpec
812 // (ShortVarDecl for short variable declarations) and ends at the
813 // end of the innermost containing block."
814 scopePos := syntax.EndPos(s)
815 for i, name := range s.NameList {
816 check.declare(check.scope, name, lhs[i], scopePos)
819 case *syntax.VarDecl:
820 top := len(check.delayed)
822 lhs0 := make([]*Var, len(s.NameList))
823 for i, name := range s.NameList {
824 lhs0[i] = NewVar(name.Pos(), pkg, name.Value, nil)
827 // initialize all variables
828 values := unpackExpr(s.Values)
829 for i, obj := range lhs0 {
833 case len(s.NameList):
837 // rhs is expected to be a multi-valued expression
845 check.varDecl(obj, lhs, s.Type, init)
846 if len(values) == 1 {
847 // If we have a single lhs variable we are done either way.
848 // If we have a single rhs expression, it must be a multi-
849 // valued expression, in which case handling the first lhs
850 // variable will cause all lhs variables to have a type
851 // assigned, and we are done as well.
853 for _, obj := range lhs0 {
854 assert(obj.typ != nil)
861 // If we have no type, we must have values.
862 if s.Type == nil || values != nil {
863 check.arity(s.Pos(), s.NameList, values, false, false)
866 // process function literals in init expressions before scope changes
867 check.processDelayed(top)
869 // declare all variables
870 // (only at this point are the variable scopes (parents) set)
871 scopePos := syntax.EndPos(s) // see constant declarations
872 for i, name := range s.NameList {
873 // see constant declarations
874 check.declare(check.scope, name, lhs0[i], scopePos)
877 case *syntax.TypeDecl:
878 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
879 // spec: "The scope of a type identifier declared inside a function
880 // begins at the identifier in the TypeSpec and ends at the end of
881 // the innermost containing block."
882 scopePos := s.Name.Pos()
883 check.declare(check.scope, s.Name, obj, scopePos)
884 // mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
885 obj.setColor(grey + color(check.push(obj)))
886 check.typeDecl(obj, s, nil)
887 check.pop().setColor(black)
890 check.errorf(s, invalidAST+"unknown syntax.Decl node %T", s)