// Copyright 2011 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.// This file implements the Check function, which drives type-checking.package typesimport (.)// nopos indicates an unknown positionvar nopos token.Pos// debugging/development supportconst debug = false// leave on during development// exprInfo stores information about an untyped expression.type exprInfo struct { isLhs bool// expression is lhs operand of a shift with delayed type-check mode operandMode typ *Basic val constant.Value// constant value; or nil (if not a constant)}// An environment represents the environment within which an object is// type-checked.type environment struct { decl *declInfo// package-level declaration whose init expression/function body is checked scope *Scope// top-most scope for lookups pos token.Pos// if valid, identifiers are looked up as if at position pos (used by Eval) iota constant.Value// value of iota in a constant declaration; nil otherwise errpos positioner// if set, identifier position of a constant with inherited initializer inTParamList bool// set if inside a type parameter list sig *Signature// function signature if inside a function; nil otherwise isPanic map[*ast.CallExpr]bool// set of panic call expressions (used for termination check) hasLabel bool// set if a function makes use of labels (only ~1% of functions); unused outside functions hasCallOrRecv bool// set if an expression contains a function call or channel receive operation}// lookup looks up name in the current environment and returns the matching object, or nil.func ( *environment) ( string) Object { , := .scope.LookupParent(, .pos)return}// An importKey identifies an imported package by import path and source directory// (directory containing the file containing the import). In practice, the directory// may always be the same, or may not matter. Given an (import path, directory), an// importer must always return the same package (but given two different import paths,// an importer may still return the same package by mapping them to the same package// paths).type importKey struct { path, dir string}// A dotImportKey describes a dot-imported object in the given scope.type dotImportKey struct { scope *Scope name string}// An action describes a (delayed) action.type action struct { f func() // action to be executed desc *actionDesc// action description; may be nil, requires debug to be set}// If debug is set, describef sets a printf-formatted description for action a.// Otherwise, it is a no-op.func ( *action) ( positioner, string, ...any) {ifdebug { .desc = &actionDesc{, , } }}// An actionDesc provides information on an action.// For debugging only.type actionDesc struct { pos positioner format string args []any}// A Checker maintains the state of the type checker.// It must be created with NewChecker.typeCheckerstruct {// package information // (initialized by NewChecker, valid for the life-time of checker) conf *Config ctxt *Context// context for de-duplicating instances fset *token.FileSet pkg *Package *Info version version// accepted language version nextID uint64// unique Id for type parameters (first valid Id is 1) objMap map[Object]*declInfo// maps package-level objects and (non-interface) methods to declaration info impMap map[importKey]*Package// maps (import path, source directory) to (complete or fake) package valids instanceLookup// valid *Named (incl. instantiated) types per the validType check// pkgPathMap maps package names to the set of distinct import paths we've // seen for that name, anywhere in the import graph. It is used for // disambiguating package names in error messages. // // pkgPathMap is allocated lazily, so that we don't pay the price of building // it on the happy path. seenPkgMap tracks the packages that we've already // walked. pkgPathMap map[string]map[string]bool seenPkgMap map[*Package]bool// information collected during type-checking of a set of package files // (initialized by Files, valid only for the duration of check.Files; // maps and lists are allocated on demand) files []*ast.File// package files posVers map[*token.File]version// Pos -> Go version mapping imports []*PkgName// list of imported packages dotImportMap map[dotImportKey]*PkgName// maps dot-imported objects to the package they were dot-imported through recvTParamMap map[*ast.Ident]*TypeParam// maps blank receiver type parameters to their type brokenAliases map[*TypeName]bool// set of aliases with broken (not yet determined) types unionTypeSets map[*Union]*_TypeSet// computed type sets for union types mono monoGraph// graph for detecting non-monomorphizable instantiation loops firstErr error// first error encountered methods map[*TypeName][]*Func// maps package scope type names to associated non-blank (non-interface) methods untyped map[ast.Expr]exprInfo// map of expressions without final type delayed []action// stack of delayed action segments; segments are processed in FIFO order objPath []Object// path of object dependencies during type inference (for cycle reporting) cleaners []cleaner// list of types that may need a final cleanup at the end of type-checking// environment within which the current object is type-checked (valid only // for the duration of type-checking a specific object)environment// debugging indent int// indentation for tracing}// addDeclDep adds the dependency edge (check.decl -> to) if check.decl existsfunc ( *Checker) ( Object) { := .declif == nil {return// not in a package-level init expression }if , := .objMap[]; ! {return// to is not a package-level object } .addDep()}// brokenAlias records that alias doesn't have a determined type yet.// It also sets alias.typ to Typ[Invalid].func ( *Checker) ( *TypeName) {if .brokenAliases == nil { .brokenAliases = make(map[*TypeName]bool) } .brokenAliases[] = true .typ = Typ[Invalid]}// validAlias records that alias has the valid type typ (possibly Typ[Invalid]).func ( *Checker) ( *TypeName, Type) {delete(.brokenAliases, ) .typ = }// isBrokenAlias reports whether alias doesn't have a determined type yet.func ( *Checker) ( *TypeName) bool {return .typ == Typ[Invalid] && .brokenAliases[]}func ( *Checker) ( ast.Expr, bool, operandMode, *Basic, constant.Value) { := .untypedif == nil { = make(map[ast.Expr]exprInfo) .untyped = } [] = exprInfo{, , , }}// later pushes f on to the stack of actions that will be processed later;// either at the end of the current statement, or in case of a local constant// or variable declaration, before the constant or variable is in scope// (so that f still sees the scope before any new declarations).// later returns the pushed action so one can provide a description// via action.describef for debugging, if desired.func ( *Checker) ( func()) *action { := len(.delayed) .delayed = append(.delayed, action{f: })return &.delayed[]}// push pushes obj onto the object path and returns its index in the path.func ( *Checker) ( Object) int { .objPath = append(.objPath, )returnlen(.objPath) - 1}// pop pops and returns the topmost object from the object path.func ( *Checker) () Object { := len(.objPath) - 1 := .objPath[] .objPath[] = nil .objPath = .objPath[:]return}type cleaner interface { cleanup()}// needsCleanup records objects/types that implement the cleanup method// which will be called at the end of type-checking.func ( *Checker) ( cleaner) { .cleaners = append(.cleaners, )}// NewChecker returns a new Checker instance for a given package.// Package files may be added incrementally via checker.Files.func ( *Config, *token.FileSet, *Package, *Info) *Checker {// make sure we have a configurationif == nil { = new(Config) }// make sure we have an info structif == nil { = new(Info) }// Note: clients may call NewChecker with the Unsafe package, which is // globally shared and must not be mutated. Therefore NewChecker must not // mutate *pkg. // // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)return &Checker{conf: ,ctxt: .Context,fset: ,pkg: ,Info: ,objMap: make(map[Object]*declInfo),impMap: make(map[importKey]*Package), }}// initFiles initializes the files-specific portion of checker.// The provided files must all belong to the same package.func ( *Checker) ( []*ast.File) {// start with a clean slate (check.Files may be called multiple times) .files = nil .imports = nil .dotImportMap = nil .firstErr = nil .methods = nil .untyped = nil .delayed = nil .objPath = nil .cleaners = nil// determine package name and collect valid files := .pkgfor , := range {switch := .Name.Name; .name {case"":if != "_" { .name = } else { .error(.Name, BlankPkgName, "invalid package name _") }fallthroughcase : .files = append(.files, )default: .errorf(atPos(.Package), MismatchedPkgName, "package %s; expected %s", , .name)// ignore this file } }for , := range .files { , := parseGoVersion(.GoVersion)if .major > 0 {if .equal(.version) {continue }// Go 1.21 introduced the feature of setting the go.mod // go line to an early version of Go and allowing //go:build lines // to “upgrade” the Go version in a given file. // We can do that backwards compatibly. // Go 1.21 also introduced the feature of allowing //go:build lines // to “downgrade” the Go version in a given file. // That can't be done compatibly in general, since before the // build lines were ignored and code got the module's Go version. // To work around this, downgrades are only allowed when the // module's Go version is Go 1.21 or later. // If there is no check.version, then we don't really know what Go version to apply. // Legacy tools may do this, and they historically have accepted everything. // Preserve that behavior by ignoring //go:build constraints entirely in that case.if (.before(.version) && .version.before(version{1, 21})) || .version.equal(version{0, 0}) {continue }if .posVers == nil { .posVers = make(map[*token.File]version) } .posVers[.fset.File(.FileStart)] = } }}// A posVers records that the file starting at pos declares the Go version vers.type posVers struct { pos token.Pos vers version}// A bailout panic is used for early termination.type bailout struct{}func ( *Checker) ( *error) {switch p := recover().(type) {casenil, bailout:// normal return or early exit * = .firstErrdefault:// re-panicpanic() }}// Files checks the provided files as part of the checker's package.func ( *Checker) ( []*ast.File) error { return .checkFiles() }var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")func ( *Checker) ( []*ast.File) ( error) {if .pkg == Unsafe {// Defensive handling for Unsafe, which cannot be type checked, and must // not be mutated. See https://go.dev/issue/61212 for an example of where // Unsafe is passed to NewChecker.returnnil } .version, = parseGoVersion(.conf.GoVersion)if != nil {return }if .version.after(version{1, goversion.Version}) {returnfmt.Errorf("package requires newer Go version %v", .version) }if .conf.FakeImportC && .conf.go115UsesCgo {returnerrBadCgo }defer .handleBailout(&) := func( string) {if .conf._Trace {fmt.Println()fmt.Println() } } ("== initFiles ==") .initFiles() ("== collectObjects ==") .collectObjects() ("== packageObjects ==") .packageObjects() ("== processDelayed ==") .processDelayed(0) // incl. all functions ("== cleanup ==") .cleanup() ("== initOrder ==") .initOrder()if !.conf.DisableUnusedImportCheck { ("== unusedImports ==") .unusedImports() } ("== recordUntyped ==") .recordUntyped()if .firstErr == nil {// TODO(mdempsky): Ensure monomorph is safe when errors exist. .monomorph() } .pkg.goVersion = .conf.GoVersion .pkg.complete = true// no longer needed - release memory .imports = nil .dotImportMap = nil .pkgPathMap = nil .seenPkgMap = nil .recvTParamMap = nil .brokenAliases = nil .unionTypeSets = nil .ctxt = nil// TODO(rFindley) There's more memory we should release at this point.return}// processDelayed processes all delayed actions pushed after top.func ( *Checker) ( int) {// If each delayed action pushes a new action, the // stack will continue to grow during this loop. // However, it is only processing functions (which // are processed in a delayed fashion) that may // add more actions (such as nested functions), so // this is a sufficiently bounded process.for := ; < len(.delayed); ++ { := &.delayed[]if .conf._Trace {if .desc != nil { .trace(.desc.pos.Pos(), "-- "+.desc.format, .desc.args...) } else { .trace(nopos, "-- delayed %p", .f) } } .f() // may append to check.delayedif .conf._Trace {fmt.Println() } }assert( <= len(.delayed)) // stack must not have shrunk .delayed = .delayed[:]}// cleanup runs cleanup for all collected cleaners.func ( *Checker) () {// Don't use a range clause since Named.cleanup may add more cleaners.for := 0; < len(.cleaners); ++ { .cleaners[].cleanup() } .cleaners = nil}func ( *Checker) ( *operand) {// convert x into a user-friendly set of values // TODO(gri) this code can be simplifiedvarTypevarconstant.Valueswitch .mode {caseinvalid: = Typ[Invalid]casenovalue: = (*Tuple)(nil)caseconstant_: = .typ = .valdefault: = .typ }assert(.expr != nil && != nil)ifisUntyped() {// delay type and value recording until we know the type // or until the end of type checking .rememberUntyped(.expr, false, .mode, .(*Basic), ) } else { .recordTypeAndValue(.expr, .mode, , ) }}func ( *Checker) () {if !debug && .Types == nil {return// nothing to do }for , := range .untyped {ifdebug && isTyped(.typ) { .dump("%v: %s (type %s) is typed", .Pos(), , .typ)unreachable() } .recordTypeAndValue(, .mode, .typ, .val) }}func ( *Checker) ( ast.Expr, operandMode, Type, constant.Value) {assert( != nil)assert( != nil)if == invalid {return// omit }if == constant_ {assert( != nil)// We check allBasic(typ, IsConstType) here as constant expressions may be // recorded as type parameters.assert( == Typ[Invalid] || allBasic(, IsConstType)) }if := .Types; != nil { [] = TypeAndValue{, , } }}func ( *Checker) ( ast.Expr, *Signature) {// f must be a (possibly parenthesized, possibly qualified) // identifier denoting a built-in (including unsafe's non-constant // functions Add and Slice): record the signature for f and possible // children.for { .recordTypeAndValue(, builtin, , nil)switch p := .(type) {case *ast.Ident, *ast.SelectorExpr:return// we're donecase *ast.ParenExpr: = .Xdefault:unreachable() } }}// recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context// (and therefore has tuple type).func ( *Checker) ( ast.Expr, []*operand) {assert( != nil)assert(len() == 2)if [0].mode == invalid {return } , := [0].typ, [1].typassert(isTyped() && isTyped() && (isBoolean() || == universeError))if := .Types; != nil {for { := []assert(.Type != nil) // should have been recorded already := .Pos() .Type = NewTuple(NewVar(, .pkg, "", ),NewVar(, .pkg, "", ), ) [] = // if x is a parenthesized expression (p.X), update p.X , := .(*ast.ParenExpr)if == nil {break } = .X } }}// recordInstance records instantiation information into check.Info, if the// Instances map is non-nil. The given expr must be an ident, selector, or// index (list) expr with ident or selector operand.//// TODO(rfindley): the expr parameter is fragile. See if we can access the// instantiated identifier in some other way.func ( *Checker) ( ast.Expr, []Type, Type) { := instantiatedIdent()assert( != nil)assert( != nil)if := .Instances; != nil { [] = Instance{newTypeList(), } }}func instantiatedIdent( ast.Expr) *ast.Ident {varast.Exprswitch e := .(type) {case *ast.IndexExpr: = .Xcase *ast.IndexListExpr: = .Xcase *ast.SelectorExpr, *ast.Ident: = }switch x := .(type) {case *ast.Ident:returncase *ast.SelectorExpr:return .Sel }panic("instantiated ident not found")}func ( *Checker) ( *ast.Ident, Object) {assert( != nil)if := .Defs; != nil { [] = }}func ( *Checker) ( *ast.Ident, Object) {assert( != nil)assert( != nil)if := .Uses; != nil { [] = }}func ( *Checker) ( ast.Node, Object) {assert( != nil)assert( != nil)if := .Implicits; != nil { [] = }}func ( *Checker) ( *ast.SelectorExpr, SelectionKind, Type, Object, []int, bool) {assert( != nil && ( == nil || len() > 0)) .recordUse(.Sel, )if := .Selections; != nil { [] = &Selection{, , , , } }}func ( *Checker) ( ast.Node, *Scope) {assert( != nil)assert( != nil)if := .Scopes; != nil { [] = }}
The pages are generated with Goldsv0.6.6. (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 @Go100and1 (reachable from the left QR code) to get the latest news of Golds.