// Copyright 2014 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package typesimport ()func ( *Checker) ( Object) {if := .Pos(); .IsValid() {// We use "other" rather than "previous" here because // the first declaration seen may not be textually // earlier in the source. .errorf(, _DuplicateDecl, "\tother declaration of %s", .Name()) // secondary error, \t indented }}func ( *Checker) ( *Scope, *ast.Ident, Object, token.Pos) {// spec: "The blank identifier, represented by the underscore // character _, may be used in a declaration like any other // identifier but the declaration does not introduce a new // binding."if .Name() != "_" {if := .Insert(); != nil { .errorf(, _DuplicateDecl, "%s redeclared in this block", .Name()) .reportAltDecl()return } .setScopePos() }if != nil { .recordDef(, ) }}// pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].func ( []Object) string {varstringfor , := range {if > 0 { += "->" } += .Name() }return}// objDecl type-checks the declaration of obj in its respective (file) environment.// For the meaning of def, see Checker.definedType, in typexpr.go.func ( *Checker) ( Object, *Named) {iftrace && .Type() == nil {if .indent == 0 {fmt.Println() // empty line between top-level objects for readability } .trace(.Pos(), "-- checking %s (%s, objPath = %s)", , .color(), pathString(.objPath)) .indent++deferfunc() { .indent-- .trace(.Pos(), "=> %s (%s)", , .color()) }() }// Checking the declaration of obj means inferring its type // (and possibly its value, for constants). // An object's type (and thus the object) may be in one of // three states which are expressed by colors: // // - an object whose type is not yet known is painted white (initial color) // - an object whose type is in the process of being inferred is painted grey // - an object whose type is fully inferred is painted black // // During type inference, an object's color changes from white to grey // to black (pre-declared objects are painted black from the start). // A black object (i.e., its type) can only depend on (refer to) other black // ones. White and grey objects may depend on white and black objects. // A dependency on a grey object indicates a cycle which may or may not be // valid. // // When objects turn grey, they are pushed on the object path (a stack); // they are popped again when they turn black. Thus, if a grey object (a // cycle) is encountered, it is on the object path, and all the objects // it depends on are the remaining objects on that path. Color encoding // is such that the color value of a grey object indicates the index of // that object in the object path.// During type-checking, white objects may be assigned a type without // traversing through objDecl; e.g., when initializing constants and // variables. Update the colors of those objects here (rather than // everywhere where we set the type) to satisfy the color invariants.if .color() == white && .Type() != nil { .setColor(black)return }switch .color() {casewhite:assert(.Type() == nil)// All color values other than white and black are considered grey. // Because black and white are < grey, all values >= grey are grey. // Use those values to encode the object's index into the object path. .setColor(grey + color(.push()))deferfunc() { .pop().setColor(black) }()caseblack:assert(.Type() != nil)returndefault:// Color values other than white or black are considered grey.fallthroughcasegrey:// We have a (possibly invalid) cycle. // In the existing code, this is marked by a non-nil type // for the object except for constants and variables whose // type may be non-nil (known), or nil if it depends on the // not-yet known initialization value. // In the former case, set the type to Typ[Invalid] because // we have an initialization cycle. The cycle error will be // reported later, when determining initialization order. // TODO(gri) Report cycle here and simplify initialization // order code.switch obj := .(type) {case *Const:if !.validCycle() || .typ == nil { .typ = Typ[Invalid] }case *Var:if !.validCycle() || .typ == nil { .typ = Typ[Invalid] }case *TypeName:if !.validCycle() {// break cycle // (without this, calling underlying() // below may lead to an endless loop // if we have a cycle for a defined // (*Named) type) .typ = Typ[Invalid] }case *Func:if !.validCycle() {// Don't set obj.typ to Typ[Invalid] here // because plenty of code type-asserts that // functions have a *Signature type. Grey // functions have their type set to an empty // signature which makes it impossible to // initialize a variable with the function. }default:unreachable() }assert(.Type() != nil)return } := .objMap[]if == nil { .dump("%v: %s should have been declared", .Pos(), )unreachable() }// save/restore current environment and set up object environmentdeferfunc( environment) { .environment = }(.environment) .environment = environment{scope: .file, }// Const and var declarations must not have initialization // cycles. We track them by remembering the current declaration // in check.decl. Initialization expressions depending on other // consts, vars, or functions, add dependencies to the current // check.decl.switch obj := .(type) {case *Const: .decl = // new package-level const decl .constDecl(, .vtyp, .init, .inherited)case *Var: .decl = // new package-level var decl .varDecl(, .lhs, .vtyp, .init)case *TypeName:// invalid recursive types are detected via path .typeDecl(, .tdecl, ) .collectMethods() // methods can only be added to top-level typescase *Func:// functions may be recursive - no need to track dependencies .funcDecl(, )default:unreachable() }}// validCycle checks if the cycle starting with obj is valid and// reports an error if it is not.func ( *Checker) ( Object) ( bool) {// The object map contains the package scope objects and the non-interface methods.ifdebug { := .objMap[] := != nil && (.fdecl == nil || .fdecl.Recv == nil) // exclude methods := .Parent() == .pkg.scopeif != { .dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", .Pos(), , , )unreachable() } }// Count cycle objects.assert(.color() >= grey) := .color() - grey// index of obj in objPath := .objPath[:] := false// if set, the cycle is through a type parameter list := 0// number of (constant or variable) values in the cycle; valid if !generic := 0// number of type definitions in the cycle; valid if !generic:for , := range {switch obj := .(type) {case *Const, *Var: ++case *TypeName:// If we reach a generic type that is part of a cycle // and we are in a type parameter list, we have a cycle // through a type parameter list, which is invalid.if .inTParamList && isGeneric(.typ) { = truebreak }// Determine if the type name is an alias or not. For // package-level objects, use the object map which // provides syntactic information (which doesn't rely // on the order in which the objects are set up). For // local objects, we can rely on the order, so use // the object's predicate. // TODO(gri) It would be less fragile to always access // the syntactic information. We should consider storing // this information explicitly in the object.varboolif := .objMap[]; != nil { = .tdecl.Assign.IsValid() // package-level object } else { = .IsAlias() // function local object }if ! { ++ }case *Func:// ignored for nowdefault:unreachable() } }iftrace { .trace(.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(), .Name(), len())if { .trace(.Pos(), "## cycle contains: generic type in a type parameter list") } else { .trace(.Pos(), "## cycle contains: %d values, %d type definitions", , ) }deferfunc() {if { .trace(.Pos(), "=> cycle is valid") } else { .trace(.Pos(), "=> error: cycle is invalid") } }() }if ! {// A cycle involving only constants and variables is invalid but we // ignore them here because they are reported via the initialization // cycle check.if == len() {returntrue }// A cycle involving only types (and possibly functions) must have at least // one type definition to be permitted: If there is no type definition, we // have a sequence of alias type names which will expand ad infinitum.if == 0 && > 0 {returntrue } } .cycleError()returnfalse}// cycleError reports a declaration cycle starting with// the object in cycle that is "first" in the source.func ( *Checker) ( []Object) {// TODO(gri) Should we start with the last (rather than the first) object in the cycle // since that is the earliest point in the source where we start seeing the // cycle? That would be more consistent with other error messages. := firstInSrc() := []// If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors. , := .(*TypeName)if != nil && .IsAlias() { .validAlias(, Typ[Invalid]) }if != nil && compilerErrorMessages { .errorf(, _InvalidDeclCycle, "invalid recursive type %s", .Name()) } else { .errorf(, _InvalidDeclCycle, "illegal cycle in declaration of %s", .Name()) }forrange { .errorf(, _InvalidDeclCycle, "\t%s refers to", .Name()) // secondary error, \t indented ++if >= len() { = 0 } = [] } .errorf(, _InvalidDeclCycle, "\t%s", .Name())}// firstInSrc reports the index of the object with the "smallest"// source position in path. path must not be empty.func ( []Object) int { , := 0, [0].Pos()for , := range [1:] {if .Pos() < { , = +1, .Pos() } }return}type (declinterface {node() ast.Node }importDeclstruct{ spec *ast.ImportSpec }constDeclstruct {spec *ast.ValueSpeciotainttypast.Exprinit []ast.Exprinheritedbool }varDeclstruct{ spec *ast.ValueSpec }typeDeclstruct{ spec *ast.TypeSpec }funcDeclstruct{ decl *ast.FuncDecl })func ( importDecl) () ast.Node { return .spec }func ( constDecl) () ast.Node { return .spec }func ( varDecl) () ast.Node { return .spec }func ( typeDecl) () ast.Node { return .spec }func ( funcDecl) () ast.Node { return .decl }func ( *Checker) ( []ast.Decl, func(decl)) {for , := range { .walkDecl(, ) }}func ( *Checker) ( ast.Decl, func(decl)) {switch d := .(type) {case *ast.BadDecl:// ignorecase *ast.GenDecl:var *ast.ValueSpec// last ValueSpec with type or init exprs seenfor , := range .Specs {switch s := .(type) {case *ast.ImportSpec: (importDecl{})case *ast.ValueSpec:switch .Tok {casetoken.CONST:// determine which initialization expressions to use := trueswitch {case .Type != nil || len(.Values) > 0: = = falsecase == nil: = new(ast.ValueSpec) // make sure last exists = false } .arityMatch(, ) (constDecl{spec: , iota: , typ: .Type, init: .Values, inherited: })casetoken.VAR: .arityMatch(, nil) (varDecl{})default: .invalidAST(, "invalid token %s", .Tok) }case *ast.TypeSpec: (typeDecl{})default: .invalidAST(, "unknown ast.Spec node %T", ) } }case *ast.FuncDecl: (funcDecl{})default: .invalidAST(, "unknown ast.Decl node %T", ) }}func ( *Checker) ( *Const, , ast.Expr, bool) {assert(.typ == nil)// use the correct value of iotadeferfunc( constant.Value, positioner) { .iota = .errpos = }(.iota, .errpos) .iota = .val .errpos = nil// provide valid constant value under all circumstances .val = constant.MakeUnknown()// determine type, if anyif != nil { := .typ()if !isConstType() {// don't report an error if the type is an invalid C (defined) type // (issue #22090)ifunder() != Typ[Invalid] { .errorf(, _InvalidConstType, "invalid constant type %s", ) } .typ = Typ[Invalid]return } .typ = }// check initializationvaroperandif != nil {if {// The initialization expression is inherited from a previous // constant declaration, and (error) positions refer to that // expression and not the current constant declaration. Use // the constant identifier position for any errors during // init expression evaluation since that is all we have // (see issues #42991, #42992). .errpos = atPos(.pos) } .expr(&, ) } .initConst(, &)}func ( *Checker) ( *Var, []*Var, , ast.Expr) {assert(.typ == nil)// determine type, if anyif != nil { .typ = .varType()// We cannot spread the type to all lhs variables if there // are more than one since that would mark them as checked // (see Checker.objDecl) and the assignment of init exprs, // if any, would not be checked. // // TODO(gri) If we have no init expr, we should distribute // a given type otherwise we need to re-evalate the type // expr for each lhs variable, leading to duplicate work. }// check initializationif == nil {if == nil {// error reported before by arityMatch .typ = Typ[Invalid] }return }if == nil || len() == 1 {assert( == nil || [0] == )varoperand .expr(&, ) .initVar(, &, "variable declaration")return }ifdebug {// obj must be one of lhs := falsefor , := range {if == { = truebreak } }if ! {panic("inconsistent lhs") } }// We have multiple variables on the lhs and one init expr. // Make sure all variables have been given the same type if // one was specified, otherwise they assume the type of the // init expression values (was issue #15755).if != nil {for , := range { .typ = .typ } } .initVars(, []ast.Expr{}, nil)}// isImportedConstraint reports whether typ is an imported type constraint.func ( *Checker) ( Type) bool { , := .(*Named)if == nil || .obj.pkg == .pkg || .obj.pkg == nil {returnfalse } , := .under().(*Interface)return != nil && !.IsMethodSet()}func ( *Checker) ( *TypeName, *ast.TypeSpec, *Named) {assert(.typ == nil)varType .later(func() {if , := .typ.(*Named); != nil { // type may be invalid .validType() }// If typ is local, an error was already reported where typ is specified/defined.if .isImportedConstraint() && !.allowVersion(.pkg, 1, 18) { .errorf(.Type, _UnsupportedFeature, "using type constraint %s requires go1.18 or later", ) } }).describef(, "validType(%s)", .Name()) := .Assign.IsValid()if && .TypeParams.NumFields() != 0 {// The parser will ensure this but we may still get an invalid AST. // Complain and continue as regular type definition. .error(atPos(.Assign), _BadDecl, "generic type cannot be alias") = false }// alias declarationif {if !.allowVersion(.pkg, 1, 9) { .errorf(atPos(.Assign), _BadDecl, "type aliases requires go1.9 or later") } .brokenAlias() = .varType(.Type) .validAlias(, )return }// type definition or generic type declaration := .newNamed(, nil, nil, nil, nil) .setUnderlying()if .TypeParams != nil { .openScope(, "type parameters")defer .closeScope() .collectTypeParams(&.tparams, .TypeParams) }// determine underlying type of named = .definedType(.Type, )assert( != nil) .fromRHS = // If the underlying was not set while type-checking the right-hand side, it // is invalid and an error should have been reported elsewhere.if .underlying == nil { .underlying = Typ[Invalid] }// Disallow a lone type parameter as the RHS of a type declaration (issue #45639). // We don't need this restriction anymore if we make the underlying type of a type // parameter its constraint interface: if the RHS is a lone type parameter, we will // use its underlying type (like we do for any RHS in a type declaration), and its // underlying type is an interface and the type declaration is well defined.ifisTypeParam() { .error(.Type, _MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration") .underlying = Typ[Invalid] }}func ( *Checker) ( **TypeParamList, *ast.FieldList) {var []*TypeParam// Declare type parameters up-front, with empty interface as type bound. // The scope of type parameters starts at the beginning of the type parameter // list (so we can have mutually recursive parameterized interfaces).for , := range .List { = .declareTypeParams(, .Names) }// Set the type parameters before collecting the type constraints because // the parameterized type may be used by the constraints (issue #47887). // Example: type T[P T[P]] interface{} * = bindTParams()// Signal to cycle detection that we are in a type parameter list. // We can only be inside one type parameter list at any given time: // function closures may appear inside a type parameter list but they // cannot be generic, and their bodies are processed in delayed and // sequential fashion. Note that with each new declaration, we save // the existing environment and restore it when done; thus inTPList is // true exactly only when we are in a specific type parameter list.assert(!.inTParamList) .inTParamList = truedeferfunc() { .inTParamList = false }() := 0for , := range .List {varType// NOTE: we may be able to assert that f.Type != nil here, but this is not // an invariant of the AST, so we are cautious.if .Type != nil { = .bound(.Type)ifisTypeParam() {// We may be able to allow this since it is now well-defined what // the underlying type and thus type set of a type parameter is. // But we may need some additional form of cycle detection within // type parameter lists. .error(.Type, _MisplacedTypeParam, "cannot use a type parameter as constraint") = Typ[Invalid] } } else { = Typ[Invalid] }for := range .Names { [+].bound = } += len(.Names) }}func ( *Checker) ( ast.Expr) Type {// A type set literal of the form ~T and A|B may only appear as constraint; // embed it in an implicit interface so that only interface type-checking // needs to take care of such type expressions. := falseswitch op := .(type) {case *ast.UnaryExpr: = .Op == token.TILDEcase *ast.BinaryExpr: = .Op == token.OR }if { = &ast.InterfaceType{Methods: &ast.FieldList{List: []*ast.Field{{Type: }}}} := .typ()// mark t as implicit interface if all went wellif , := .(*Interface); != nil { .implicit = true }return }return .typ()}func ( *Checker) ( []*TypeParam, []*ast.Ident) []*TypeParam {// Use Typ[Invalid] for the type constraint to ensure that a type // is present even if the actual constraint has not been assigned // yet. // TODO(gri) Need to systematically review all uses of type parameter // constraints to make sure we don't rely on them if they // are not properly set yet.for , := range { := NewTypeName(.Pos(), .pkg, .Name, nil) := .newTypeParam(, Typ[Invalid]) // assigns type to tpar as a side-effect .declare(.scope, , , .scope.pos) // TODO(gri) check scope position = append(, ) }iftrace && len() > 0 { .trace([0].Pos(), "type params = %v", [len()-len():]) }return}func ( *Checker) ( *TypeName) {// get associated methods // (Checker.collectObjects only collects methods with non-blank names; // Checker.resolveBaseTypeName ensures that obj is not an alias name // if it has attached methods.) := .methods[]if == nil {return }delete(.methods, )assert(!.objMap[].tdecl.Assign.IsValid()) // don't use TypeName.IsAlias (requires fully set up object)// use an objset to check for name conflictsvarobjset// spec: "If the base type is a struct type, the non-blank method // and field names must be distinct." , := .typ.(*Named) // shouldn't fail but be conservativeif != nil {assert(.targs.Len() == 0) // collectMethods should not be called on an instantiated type// See issue #52529: we must delay the expansion of underlying here, as // base may not be fully set-up. .later(func() { .checkFieldUniqueness() }).describef(, "verifying field uniqueness for %v", )// Checker.Files may be called multiple times; additional package files // may add methods to already type-checked types. Add pre-existing methods // so that we can detect redeclarations.for := 0; < .methods.Len(); ++ { := .methods.At(, nil)assert(.name != "_")assert(.insert() == nil) } }// add valid methodsfor , := range {// spec: "For a base type, the non-blank names of methods bound // to it must be unique."assert(.name != "_")if := .insert(); != nil { .errorf(, _DuplicateMethod, "method %s already declared for %s", .name, ) .reportAltDecl()continue }if != nil { .resolve(nil) // TODO(mdempsky): Probably unnecessary. .AddMethod() } }}func ( *Checker) ( *Named) {if , := .under().(*Struct); != nil {varobjsetfor := 0; < .methods.Len(); ++ { := .methods.At(, nil)assert(.name != "_")assert(.insert() == nil) }// Check that any non-blank field names of base are distinct from its // method names.for , := range .fields {if .name != "_" {if := .insert(); != nil {// Struct fields should already be unique, so we should only // encounter an alternate via collision with a method name. _ = .(*Func)// For historical consistency, we report the primary error on the // method, and the alt decl on the field. .errorf(, _DuplicateFieldAndMethod, "field and method with the same name %s", .name) .reportAltDecl() } } } }}func ( *Checker) ( *Func, *declInfo) {assert(.typ == nil)// func declarations cannot use iotaassert(.iota == nil) := new(Signature) .typ = // guard against cycles// Avoid cycle error when referring to method while type-checking the signature. // This avoids a nuisance in the best case (non-parameterized receiver type) and // since the method is not a type, we get an error. If we have a parameterized // receiver type, instantiating the receiver type leads to the instantiation of // its methods, and we don't want a cycle error in that case. // TODO(gri) review if this is correct and/or whether we still need this? := .color_ .color_ = black := .fdecl .funcType(, .Recv, .Type) .color_ = if .Type.TypeParams.NumFields() > 0 && .Body == nil { .softErrorf(.Name, _BadDecl, "parameterized function is missing function body") }// function body must be type-checked after global declarations // (functions implemented elsewhere have no body)if !.conf.IgnoreFuncBodies && .Body != nil { .later(func() { .funcBody(, .name, , .Body, nil) }) }}func ( *Checker) ( ast.Decl) { := .pkg .walkDecl(, func( decl) {switch d := .(type) {caseconstDecl: := len(.delayed)// declare all constants := make([]*Const, len(.spec.Names))for , := range .spec.Names { := NewConst(.Pos(), , .Name, nil, constant.MakeInt64(int64(.iota))) [] = varast.Exprif < len(.init) { = .init[] } .constDecl(, .typ, , .inherited) }// process function literals in init expressions before scope changes .processDelayed()// spec: "The scope of a constant or variable identifier declared // inside a function begins at the end of the ConstSpec or VarSpec // (ShortVarDecl for short variable declarations) and ends at the // end of the innermost containing block." := .spec.End()for , := range .spec.Names { .declare(.scope, , [], ) }casevarDecl: := len(.delayed) := make([]*Var, len(.spec.Names))for , := range .spec.Names { [] = NewVar(.Pos(), , .Name, nil) }// initialize all variablesfor , := range {var []*Varvarast.Exprswitchlen(.spec.Values) {caselen(.spec.Names):// lhs and rhs match = .spec.Values[]case1:// rhs is expected to be a multi-valued expression = = .spec.Values[0]default:if < len(.spec.Values) { = .spec.Values[] } } .varDecl(, , .spec.Type, )iflen(.spec.Values) == 1 {// If we have a single lhs variable we are done either way. // If we have a single rhs expression, it must be a multi- // valued expression, in which case handling the first lhs // variable will cause all lhs variables to have a type // assigned, and we are done as well.ifdebug {for , := range {assert(.typ != nil) } }break } }// process function literals in init expressions before scope changes .processDelayed()// declare all variables // (only at this point are the variable scopes (parents) set) := .spec.End() // see constant declarationsfor , := range .spec.Names {// see constant declarations .declare(.scope, , [], ) }casetypeDecl: := NewTypeName(.spec.Name.Pos(), , .spec.Name.Name, nil)// spec: "The scope of a type identifier declared inside a function // begins at the identifier in the TypeSpec and ends at the end of // the innermost containing block." := .spec.Name.Pos() .declare(.scope, .spec.Name, , )// mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl) .setColor(grey + color(.push())) .typeDecl(, .spec, nil) .pop().setColor(black)default: .invalidAST(.node(), "unknown ast.Decl node %T", .node()) } })}
The pages are generated with Goldsv0.4.9. (GOOS=linux GOARCH=amd64)