// 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.func ( *Checker) ( Object) {iftracePos { .pushPos(atPos(.Pos()))deferfunc() {// If we're panicking, keep stack of source positions.if := recover(); != nil {panic() } .popPos() }() }if .conf._Trace && .Type() == nil {if .indent == 0 {fmt.Println() // empty line between top-level objects for readability } .trace(.Pos(), "-- checking %s (objPath = %s)", , pathString(.objPath)) .indent++deferfunc() { .indent-- .trace(.Pos(), "=> %s", ) }() }// Checking the declaration of an object means determining its type // (and also its value for constants). An object (and thus its type) // may be in 1 of 3 states: // // - not in Checker.objPathIdx and type == nil : type is not yet known (white) // - in Checker.objPathIdx : type is pending (grey) // - not in Checker.objPathIdx and type != nil : type is known (black) // // During type-checking, an object changes from white to grey to black. // Predeclared objects start as black (their type is known without checking). // // A black object may only depend on (refer to) to other black objects. White // and grey objects may depend on white or black objects. A dependency on a // grey object indicates a (possibly invalid) cycle. // // When an object is marked grey, it is pushed onto the object path (a stack) // and its index in the path is recorded in the path index map. It is popped // and removed from the map when its type is determined (and marked black).// If this object is grey, we have a (possibly invalid) cycle. This is signaled // 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 a 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.if , := .objPathIdx[]; {switch obj := .(type) {case *Const, *Var:if !.validCycle() || .Type() == nil { .setType(Typ[Invalid]) }case *TypeName:if !.validCycle() { .setType(Typ[Invalid]) }case *Func:if !.validCycle() {// Don't set type to Typ[Invalid]; plenty of code asserts that // functions have a *Signature type. Instead, leave the type // as an empty signature, which makes it impossible to // initialize a variable with the function. }default:panic("unreachable") }assert(.Type() != nil)return }if .Type() != nil { // black, meaning it's already type-checkedreturn }// white, meaning it must be type-checked .push() // mark as greydefer .pop() , := .objMap[]assert()// save/restore current environment and set up object environmentdeferfunc( environment) { .environment = }(.environment) .environment = environment{scope: .file, version: .version}// 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. , := .objPathIdx[]assert() := .objPath[:] := false// if set, the cycle is through a type parameter list := 0// number of (constant or variable) values in the cycle := 0// number of type definitions in the cycle: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.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") } }() }// Cycles through type parameter lists are ok (go.dev/issue/68162).if {returntrue }// 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) This 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 {if .conf._EnableAlias {if , := .Type().(*Alias); { .fromRHS = Typ[Invalid] } } else {if .IsAlias() { .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", ()) }// "cycle[i] refers to cycle[j]" for (i,j) = (s,s+1), (s+1,s+2), ..., (n-1,0), (0,1), ..., (s-1,s) for len(cycle) = n, s = start.for := range { := [(++1)%len()] .addf(, "%s refers to %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(.Underlying()) { .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 lhsif !slices.Contains(, ) {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 } , := .Underlying().(*Interface)return != nil && !.IsMethodSet()}func ( *Checker) ( *TypeName, *ast.TypeSpec) {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 { := .newAlias(, nil)// If we could not type the RHS, set it to invalid. This should // only ever happen if we panic before setting.deferfunc() {if .fromRHS == nil { .fromRHS = Typ[Invalid]unalias() } }()// handle type parameters even if not allowed (Alias type is supported)if != nil { .openScope(, "type parameters")defer .closeScope() .collectTypeParams(&.tparams, .TypeParams) } = .declaredType(.Type, )assert( != nil) .fromRHS = // spec: In an alias declaration the given type cannot be a type parameter declared in the same declaration." // (see also go.dev/issue/75884, go.dev/issue/#75885)if , := .(*TypeParam); && .tparams != nil && slices.Index(.tparams.list(), ) >= 0 { .error(.Type, MisplacedTypeParam, "cannot use type parameter declared in alias declaration as RHS") .fromRHS = Typ[Invalid] } } 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)// The RHS of a named N can be nil if, for example, N is defined as a cycle of aliases with // gotypesalias=0. Consider: // // type D N // N.unpack() will panic // type N A // type A = N // N.fromRHS is not set before N.unpack(), since A does not call setDefType // // There is likely a better way to detect such cases, but it may not be worth the effort. // Instead, we briefly permit a nil N.fromRHS while type-checking D. .allowNilRHS = truedefer (func() { .allowNilRHS = false })()if .TypeParams != nil { .openScope(, "type parameters")defer .closeScope() .collectTypeParams(&.tparams, .TypeParams) } = .declaredType(.Type, )assert( != nil) .fromRHS = // spec: "In a type definition the given type cannot be a type parameter." // (See also go.dev/issue/45639.)ifisTypeParam() { .error(.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration") .fromRHS = 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 {for , := range .Names { = append(, .declareTypeParam(, )) } }// 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) ( *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. := NewTypeName(.Pos(), .pkg, .Name, nil) := .newTypeParam(, Typ[Invalid]) // assigns type to tname as a side-effect .declare(.scope, , , )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 , := .Underlying().(*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 := .fdecl .funcType(, .Recv, .Type)// 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(LocalVar, .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, , ) .push() // mark as grey .typeDecl(, .spec) .pop()default: .errorf(.node(), InvalidSyntaxTree, "unknown ast.Decl node %T", .node()) } })}
The pages are generated with Goldsv0.8.3-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.