1 // Copyright 2011 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.
5 // This file implements the Check function, which drives type-checking.
16 . "internal/types/errors"
19 // nopos indicates an unknown position
22 // debugging/development support
23 const debug = false // leave on during development
25 // gotypesalias controls the use of Alias types
26 var gotypesalias = godebug.New("gotypesalias")
28 // exprInfo stores information about an untyped expression.
29 type exprInfo struct {
30 isLhs bool // expression is lhs operand of a shift with delayed type-check
33 val constant.Value // constant value; or nil (if not a constant)
36 // An environment represents the environment within which an object is
38 type environment struct {
39 decl *declInfo // package-level declaration whose init expression/function body is checked
40 scope *Scope // top-most scope for lookups
41 pos token.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
42 iota constant.Value // value of iota in a constant declaration; nil otherwise
43 errpos positioner // if set, identifier position of a constant with inherited initializer
44 inTParamList bool // set if inside a type parameter list
45 sig *Signature // function signature if inside a function; nil otherwise
46 isPanic map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
47 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
48 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
51 // lookup looks up name in the current environment and returns the matching object, or nil.
52 func (env *environment) lookup(name string) Object {
53 _, obj := env.scope.LookupParent(name, env.pos)
57 // An importKey identifies an imported package by import path and source directory
58 // (directory containing the file containing the import). In practice, the directory
59 // may always be the same, or may not matter. Given an (import path, directory), an
60 // importer must always return the same package (but given two different import paths,
61 // an importer may still return the same package by mapping them to the same package
63 type importKey struct {
67 // A dotImportKey describes a dot-imported object in the given scope.
68 type dotImportKey struct {
73 // An action describes a (delayed) action.
75 f func() // action to be executed
76 desc *actionDesc // action description; may be nil, requires debug to be set
79 // If debug is set, describef sets a printf-formatted description for action a.
80 // Otherwise, it is a no-op.
81 func (a *action) describef(pos positioner, format string, args ...any) {
83 a.desc = &actionDesc{pos, format, args}
87 // An actionDesc provides information on an action.
88 // For debugging only.
89 type actionDesc struct {
95 // A Checker maintains the state of the type checker.
96 // It must be created with [NewChecker].
98 // package information
99 // (initialized by NewChecker, valid for the life-time of checker)
101 // If EnableAlias is set, alias declarations produce an Alias type.
102 // Otherwise the alias information is only in the type name, which
103 // points directly to the actual (aliased) type.
107 ctxt *Context // context for de-duplicating instances
111 version goVersion // accepted language version
112 nextID uint64 // unique Id for type parameters (first valid Id is 1)
113 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
114 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
115 valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
117 // pkgPathMap maps package names to the set of distinct import paths we've
118 // seen for that name, anywhere in the import graph. It is used for
119 // disambiguating package names in error messages.
121 // pkgPathMap is allocated lazily, so that we don't pay the price of building
122 // it on the happy path. seenPkgMap tracks the packages that we've already
124 pkgPathMap map[string]map[string]bool
125 seenPkgMap map[*Package]bool
127 // information collected during type-checking of a set of package files
128 // (initialized by Files, valid only for the duration of check.Files;
129 // maps and lists are allocated on demand)
130 files []*ast.File // package files
131 versions map[*ast.File]string // maps files to version strings (each file has an entry)
132 imports []*PkgName // list of imported packages
133 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
134 recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
135 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
136 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
137 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
139 firstErr error // first error encountered
140 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
141 untyped map[ast.Expr]exprInfo // map of expressions without final type
142 delayed []action // stack of delayed action segments; segments are processed in FIFO order
143 objPath []Object // path of object dependencies during type inference (for cycle reporting)
144 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
146 // environment within which the current object is type-checked (valid only
147 // for the duration of type-checking a specific object)
151 indent int // indentation for tracing
154 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
155 func (check *Checker) addDeclDep(to Object) {
158 return // not in a package-level init expression
160 if _, found := check.objMap[to]; !found {
161 return // to is not a package-level object
166 // Note: The following three alias-related functions are only used
167 // when Alias types are not enabled.
169 // brokenAlias records that alias doesn't have a determined type yet.
170 // It also sets alias.typ to Typ[Invalid].
171 // Not used if check.enableAlias is set.
172 func (check *Checker) brokenAlias(alias *TypeName) {
173 assert(!check.enableAlias)
174 if check.brokenAliases == nil {
175 check.brokenAliases = make(map[*TypeName]bool)
177 check.brokenAliases[alias] = true
178 alias.typ = Typ[Invalid]
181 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
182 func (check *Checker) validAlias(alias *TypeName, typ Type) {
183 assert(!check.enableAlias)
184 delete(check.brokenAliases, alias)
188 // isBrokenAlias reports whether alias doesn't have a determined type yet.
189 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
190 assert(!check.enableAlias)
191 return check.brokenAliases[alias]
194 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
197 m = make(map[ast.Expr]exprInfo)
200 m[e] = exprInfo{lhs, mode, typ, val}
203 // later pushes f on to the stack of actions that will be processed later;
204 // either at the end of the current statement, or in case of a local constant
205 // or variable declaration, before the constant or variable is in scope
206 // (so that f still sees the scope before any new declarations).
207 // later returns the pushed action so one can provide a description
208 // via action.describef for debugging, if desired.
209 func (check *Checker) later(f func()) *action {
210 i := len(check.delayed)
211 check.delayed = append(check.delayed, action{f: f})
212 return &check.delayed[i]
215 // push pushes obj onto the object path and returns its index in the path.
216 func (check *Checker) push(obj Object) int {
217 check.objPath = append(check.objPath, obj)
218 return len(check.objPath) - 1
221 // pop pops and returns the topmost object from the object path.
222 func (check *Checker) pop() Object {
223 i := len(check.objPath) - 1
224 obj := check.objPath[i]
225 check.objPath[i] = nil
226 check.objPath = check.objPath[:i]
230 type cleaner interface {
234 // needsCleanup records objects/types that implement the cleanup method
235 // which will be called at the end of type-checking.
236 func (check *Checker) needsCleanup(c cleaner) {
237 check.cleaners = append(check.cleaners, c)
240 // NewChecker returns a new [Checker] instance for a given package.
241 // [Package] files may be added incrementally via checker.Files.
242 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
243 // make sure we have a configuration
248 // make sure we have an info struct
253 // Note: clients may call NewChecker with the Unsafe package, which is
254 // globally shared and must not be mutated. Therefore NewChecker must not
257 // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
260 enableAlias: gotypesalias.Value() == "1",
266 version: asGoVersion(conf.GoVersion),
267 objMap: make(map[Object]*declInfo),
268 impMap: make(map[importKey]*Package),
272 // initFiles initializes the files-specific portion of checker.
273 // The provided files must all belong to the same package.
274 func (check *Checker) initFiles(files []*ast.File) {
275 // start with a clean slate (check.Files may be called multiple times)
278 check.dotImportMap = nil
287 // determine package name and collect valid files
289 for _, file := range files {
290 switch name := file.Name.Name; pkg.name {
295 check.error(file.Name, BlankPkgName, "invalid package name _")
300 check.files = append(check.files, file)
303 check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected %s", name, pkg.name)
308 // reuse Info.FileVersions if provided
309 versions := check.Info.FileVersions
311 versions = make(map[*ast.File]string)
313 check.versions = versions
315 pkgVersionOk := check.version.isValid()
316 downgradeOk := check.version.cmp(go1_21) >= 0
318 // determine Go version for each file
319 for _, file := range check.files {
320 // use unaltered Config.GoVersion by default
321 // (This version string may contain dot-release numbers as in go1.20.1,
322 // unlike file versions which are Go language versions only, if valid.)
323 v := check.conf.GoVersion
324 // use the file version, if applicable
325 // (file versions are either the empty string or of the form go1.dd)
327 fileVersion := asGoVersion(file.GoVersion)
328 if fileVersion.isValid() {
329 cmp := fileVersion.cmp(check.version)
330 // Go 1.21 introduced the feature of setting the go.mod
331 // go line to an early version of Go and allowing //go:build lines
332 // to “upgrade” (cmp > 0) the Go version in a given file.
333 // We can do that backwards compatibly.
335 // Go 1.21 also introduced the feature of allowing //go:build lines
336 // to “downgrade” (cmp < 0) the Go version in a given file.
337 // That can't be done compatibly in general, since before the
338 // build lines were ignored and code got the module's Go version.
339 // To work around this, downgrades are only allowed when the
340 // module's Go version is Go 1.21 or later.
342 // If there is no valid check.version, then we don't really know what
343 // Go version to apply.
344 // Legacy tools may do this, and they historically have accepted everything.
345 // Preserve that behavior by ignoring //go:build constraints entirely in that
346 // case (!pkgVersionOk).
347 if cmp > 0 || cmp < 0 && downgradeOk {
356 // A bailout panic is used for early termination.
357 type bailout struct{}
359 func (check *Checker) handleBailout(err *error) {
360 switch p := recover().(type) {
362 // normal return or early exit
363 *err = check.firstErr
370 // Files checks the provided files as part of the checker's package.
371 func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
373 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
375 func (check *Checker) checkFiles(files []*ast.File) (err error) {
376 if check.pkg == Unsafe {
377 // Defensive handling for Unsafe, which cannot be type checked, and must
378 // not be mutated. See https://go.dev/issue/61212 for an example of where
379 // Unsafe is passed to NewChecker.
383 // Note: NewChecker doesn't return an error, so we need to check the version here.
384 if check.version.cmp(go_current) > 0 {
385 return fmt.Errorf("package requires newer Go version %v", check.version)
387 if check.conf.FakeImportC && check.conf.go115UsesCgo {
391 defer check.handleBailout(&err)
393 print := func(msg string) {
394 if check.conf._Trace {
400 print("== initFiles ==")
401 check.initFiles(files)
403 print("== collectObjects ==")
404 check.collectObjects()
406 print("== packageObjects ==")
407 check.packageObjects()
409 print("== processDelayed ==")
410 check.processDelayed(0) // incl. all functions
412 print("== cleanup ==")
415 print("== initOrder ==")
418 if !check.conf.DisableUnusedImportCheck {
419 print("== unusedImports ==")
420 check.unusedImports()
423 print("== recordUntyped ==")
424 check.recordUntyped()
426 if check.firstErr == nil {
427 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
431 check.pkg.goVersion = check.conf.GoVersion
432 check.pkg.complete = true
434 // no longer needed - release memory
436 check.dotImportMap = nil
437 check.pkgPathMap = nil
438 check.seenPkgMap = nil
439 check.recvTParamMap = nil
440 check.brokenAliases = nil
441 check.unionTypeSets = nil
444 // TODO(rFindley) There's more memory we should release at this point.
449 // processDelayed processes all delayed actions pushed after top.
450 func (check *Checker) processDelayed(top int) {
451 // If each delayed action pushes a new action, the
452 // stack will continue to grow during this loop.
453 // However, it is only processing functions (which
454 // are processed in a delayed fashion) that may
455 // add more actions (such as nested functions), so
456 // this is a sufficiently bounded process.
457 for i := top; i < len(check.delayed); i++ {
458 a := &check.delayed[i]
459 if check.conf._Trace {
461 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
463 check.trace(nopos, "-- delayed %p", a.f)
466 a.f() // may append to check.delayed
467 if check.conf._Trace {
471 assert(top <= len(check.delayed)) // stack must not have shrunk
472 check.delayed = check.delayed[:top]
475 // cleanup runs cleanup for all collected cleaners.
476 func (check *Checker) cleanup() {
477 // Don't use a range clause since Named.cleanup may add more cleaners.
478 for i := 0; i < len(check.cleaners); i++ {
479 check.cleaners[i].cleanup()
484 func (check *Checker) record(x *operand) {
485 // convert x into a user-friendly set of values
486 // TODO(gri) this code can be simplified
488 var val constant.Value
500 assert(x.expr != nil && typ != nil)
503 // delay type and value recording until we know the type
504 // or until the end of type checking
505 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
507 check.recordTypeAndValue(x.expr, x.mode, typ, val)
511 func (check *Checker) recordUntyped() {
512 if !debug && check.Types == nil {
513 return // nothing to do
516 for x, info := range check.untyped {
517 if debug && isTyped(info.typ) {
518 check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
521 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
525 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
531 if mode == constant_ {
533 // We check allBasic(typ, IsConstType) here as constant expressions may be
534 // recorded as type parameters.
535 assert(!isValid(typ) || allBasic(typ, IsConstType))
537 if m := check.Types; m != nil {
538 m[x] = TypeAndValue{mode, typ, val}
542 func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
543 // f must be a (possibly parenthesized, possibly qualified)
544 // identifier denoting a built-in (including unsafe's non-constant
545 // functions Add and Slice): record the signature for f and possible
548 check.recordTypeAndValue(f, builtin, sig, nil)
549 switch p := f.(type) {
550 case *ast.Ident, *ast.SelectorExpr:
560 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
561 // (and therefore has tuple type).
562 func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
565 if a[0].mode == invalid {
568 t0, t1 := a[0].typ, a[1].typ
569 assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
570 if m := check.Types; m != nil {
573 assert(tv.Type != nil) // should have been recorded already
576 NewVar(pos, check.pkg, "", t0),
577 NewVar(pos, check.pkg, "", t1),
580 // if x is a parenthesized expression (p.X), update p.X
581 p, _ := x.(*ast.ParenExpr)
590 // recordInstance records instantiation information into check.Info, if the
591 // Instances map is non-nil. The given expr must be an ident, selector, or
592 // index (list) expr with ident or selector operand.
594 // TODO(rfindley): the expr parameter is fragile. See if we can access the
595 // instantiated identifier in some other way.
596 func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
597 ident := instantiatedIdent(expr)
600 if m := check.Instances; m != nil {
601 m[ident] = Instance{newTypeList(targs), typ}
605 func instantiatedIdent(expr ast.Expr) *ast.Ident {
606 var selOrIdent ast.Expr
607 switch e := expr.(type) {
610 case *ast.IndexListExpr:
612 case *ast.SelectorExpr, *ast.Ident:
615 switch x := selOrIdent.(type) {
618 case *ast.SelectorExpr:
621 panic("instantiated ident not found")
624 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
626 if m := check.Defs; m != nil {
631 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
634 if m := check.Uses; m != nil {
639 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
642 if m := check.Implicits; m != nil {
647 func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
648 assert(obj != nil && (recv == nil || len(index) > 0))
649 check.recordUse(x.Sel, obj)
650 if m := check.Selections; m != nil {
651 m[x] = &Selection{kind, recv, obj, index, indirect}
655 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
658 if m := check.Scopes; m != nil {