// 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) ( *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 { := .newError(DuplicateDecl) .addf(, "%s redeclared in this block", .Name()) .addAltDecl() .report()return } .setScopePos() }if != nil { .recordDef(, ) }}// pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].func pathString( []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, *TypeName) {if .conf._Trace && .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:panic("unreachable") }assert(.Type() != nil)return } := .objMap[]if == nil { .dump("%v: %s should have been declared", .Pos(), )panic("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:panic("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(), , , )panic("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 .conf._EnableAlias { = .IsAlias() } else {if := .objMap[]; != nil { = .tdecl.Assign.IsValid() // package-level object } else { = .IsAlias() // function local object } }if ! { ++ }case *Func:// ignored for nowdefault:panic("unreachable") } }if .conf._Trace { .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(, firstInSrc())returnfalse}// cycleError reports a declaration cycle starting with the object at cycle[start].func ( *Checker) ( []Object, int) {// name returns the (possibly qualified) object name. // This is needed because with generic types, cycles // may refer to imported types. See go.dev/issue/50788. // TODO(gri) Thus functionality is used elsewhere. Factor it out. := func( Object) string {returnpackagePrefix(.Pkg(), .qualifier) + .Name() } := [] := ()// If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors. , := .(*TypeName)if != nil && .IsAlias() {// If we use Alias nodes, it is initialized with Typ[Invalid]. // TODO(gri) Adjust this code if we initialize with nil.if !.conf._EnableAlias { .validAlias(, Typ[Invalid]) } }// report a more concise error for self referencesiflen() == 1 {if != nil { .errorf(, InvalidDeclCycle, "invalid recursive type: %s refers to itself", ) } else { .errorf(, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", ) }return } := .newError(InvalidDeclCycle)if != nil { .addf(, "invalid recursive type %s", ) } else { .addf(, "invalid cycle in declaration of %s", ) } := forrange { .addf(, "%s refers to", ) ++if >= len() { = 0 } = [] = () } .addf(, "%s", ) .report()}// firstInSrc reports the index of the object with the "smallest"// source position in path. path must not be empty.func firstInSrc( []Object) int { , := 0, [0].Pos()for , := range [1:] {ifcmpPos(.Pos(), ) < 0 { , = +1, .Pos() } }return}type ( decl interface { node() ast.Node } importDecl struct{ spec *ast.ImportSpec } constDecl struct { spec *ast.ValueSpec iota int typ ast.Expr init []ast.Expr inherited bool } varDecl struct{ spec *ast.ValueSpec } typeDecl struct{ spec *ast.TypeSpec } funcDecl struct{ 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: .errorf(, InvalidSyntaxTree, "invalid token %s", .Tok) }case *ast.TypeSpec: (typeDecl{})default: .errorf(, InvalidSyntaxTree, "unknown ast.Spec node %T", ) } }case *ast.FuncDecl: (funcDecl{})default: .errorf(, InvalidSyntaxTree, "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 // (go.dev/issue/22090)ifisValid(under()) { .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 go.dev/issue/42991, go.dev/issue/42992). .errpos = atPos(.pos) } .expr(nil, &, ) } .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-evaluate 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(newTarget(.typ, .name), &, ) .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 go.dev/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 { := asNamed()if == nil || .obj.pkg == .pkg || .obj.pkg == nil {returnfalse } , := .under().(*Interface)return != nil && !.IsMethodSet()}func ( *Checker) ( *TypeName, *ast.TypeSpec, *TypeName) {assert(.typ == nil)// Only report a version error if we have not reported one already. := falsevarType .later(func() {if := asNamed(.typ); != nil { // type may be invalid .validType() }// If typ is local, an error was already reported where typ is specified/defined. _ = ! && .isImportedConstraint() && .verifyVersionf(.Type, go1_18, "using type constraint %s", ) }).describef(, "validType(%s)", .Name())// First type parameter, or nil.var *ast.Fieldif .TypeParams.NumFields() > 0 { = .TypeParams.List[0] }// alias declarationif .Assign.IsValid() {// Report highest version requirement first so that fixing a version issue // avoids possibly two -lang changes (first to Go 1.9 and then to Go 1.23).if ! && != nil && !.verifyVersionf(, go1_23, "generic type alias") { = true }if ! && !.verifyVersionf(atPos(.Assign), go1_9, "type alias") { = true }if .conf._EnableAlias {// TODO(gri) Should be able to use nil instead of Typ[Invalid] to mark // the alias as incomplete. Currently this causes problems // with certain cycles. Investigate. // // NOTE(adonovan): to avoid the Invalid being prematurely observed // by (e.g.) a var whose type is an unfinished cycle, // Unalias does not memoize if Invalid. Perhaps we should use a // special sentinel distinct from Invalid. := .newAlias(, Typ[Invalid])setDefType(, )// handle type parameters even if not allowed (Alias type is supported)if != nil {if ! && !buildcfg.Experiment.AliasTypeParams { .error(, UnsupportedFeature, "generic type alias requires GOEXPERIMENT=aliastypeparams") = true } .openScope(, "type parameters")defer .closeScope() .collectTypeParams(&.tparams, .TypeParams) } = .definedType(.Type, )assert( != nil) .fromRHS = Unalias() // resolve alias.actual } else {// With Go1.23, the default behavior is to use Alias nodes, // reflected by check.enableAlias. Signal non-default behavior. // // TODO(gri) Testing runs tests in both modes. Do we need to exclude // tracking of non-default behavior for tests?gotypesalias.IncNonDefault()if ! && != nil { .error(, UnsupportedFeature, "generic type alias requires GODEBUG=gotypesalias=1 or unset") = true } .brokenAlias() = .typ(.Type) .validAlias(, ) }return }// type definition or generic type declarationif ! && != nil && !.verifyVersionf(, go1_18, "type parameter") { = true } := .newNamed(, nil, nil)setDefType(, )if .TypeParams != nil { .openScope(, "type parameters")defer .closeScope() .collectTypeParams(&.tparams, .TypeParams) }// determine underlying type of named = .definedType(.Type, )assert( != nil) .fromRHS = // If the underlying type 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 (go.dev/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). := .Pos()for , := range .List { = .declareTypeParams(, .Names, ) }// Set the type parameters before collecting the type constraints because // the parameterized type may be used by the constraints (go.dev/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, token.Pos) []*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, , , ) = append(, ) }if .conf._Trace && 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." := asNamed(.typ) // shouldn't fail but be conservativeif != nil {assert(.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type// See go.dev/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; < .NumMethods(); ++ { := .Method()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 {if .Pos().IsValid() { .errorf(, DuplicateMethod, "method %s.%s already declared at %v", .Name(), .name, .Pos()) } else { .errorf(, DuplicateMethod, "method %s.%s already declared", .Name(), .name) }continue }if != nil { .AddMethod() } }}func ( *Checker) ( *Named) {if , := .under().(*Struct); != nil {varobjsetfor := 0; < .NumMethods(); ++ { := .Method()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. := .newError(DuplicateFieldAndMethod) .addf(, "field and method with the same name %s", .name) .addAltDecl() .report() } } } }}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_ = // Set the scope's extent to the complete "func (...) { ... }" // so that Scope.Innermost works correctly. .scope.pos = .Pos() .scope.end = .End()if .Type.TypeParams.NumFields() > 0 && .Body == nil { .softErrorf(.Name, BadDecl, "generic 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) }).describef(, "func %s", .name) }}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: .errorf(.node(), InvalidSyntaxTree, "unknown ast.Decl node %T", .node()) } })}
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.