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.
17 . "internal/types/errors"
20 // nopos indicates an unknown position
23 // debugging/development support
24 const debug = false // leave on during development
26 // gotypesalias controls the use of Alias types
27 var gotypesalias = godebug.New("gotypesalias")
29 // exprInfo stores information about an untyped expression.
30 type exprInfo struct {
31 isLhs bool // expression is lhs operand of a shift with delayed type-check
34 val constant.Value // constant value; or nil (if not a constant)
37 // An environment represents the environment within which an object is
39 type environment struct {
40 decl *declInfo // package-level declaration whose init expression/function body is checked
41 scope *Scope // top-most scope for lookups
42 pos token.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
43 iota constant.Value // value of iota in a constant declaration; nil otherwise
44 errpos positioner // if set, identifier position of a constant with inherited initializer
45 inTParamList bool // set if inside a type parameter list
46 sig *Signature // function signature if inside a function; nil otherwise
47 isPanic map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
48 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
49 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
52 // lookup looks up name in the current environment and returns the matching object, or nil.
53 func (env *environment) lookup(name string) Object {
54 _, obj := env.scope.LookupParent(name, env.pos)
58 // An importKey identifies an imported package by import path and source directory
59 // (directory containing the file containing the import). In practice, the directory
60 // may always be the same, or may not matter. Given an (import path, directory), an
61 // importer must always return the same package (but given two different import paths,
62 // an importer may still return the same package by mapping them to the same package
64 type importKey struct {
68 // A dotImportKey describes a dot-imported object in the given scope.
69 type dotImportKey struct {
74 // An action describes a (delayed) action.
76 f func() // action to be executed
77 desc *actionDesc // action description; may be nil, requires debug to be set
80 // If debug is set, describef sets a printf-formatted description for action a.
81 // Otherwise, it is a no-op.
82 func (a *action) describef(pos positioner, format string, args ...any) {
84 a.desc = &actionDesc{pos, format, args}
88 // An actionDesc provides information on an action.
89 // For debugging only.
90 type actionDesc struct {
96 // A Checker maintains the state of the type checker.
97 // It must be created with [NewChecker].
99 // package information
100 // (initialized by NewChecker, valid for the life-time of checker)
102 // If EnableAlias is set, alias declarations produce an Alias type.
103 // Otherwise the alias information is only in the type name, which
104 // points directly to the actual (aliased) type.
108 ctxt *Context // context for de-duplicating instances
112 version version // accepted language version
113 posVers map[token.Pos]version // maps file start positions to versions (may be nil)
114 nextID uint64 // unique Id for type parameters (first valid Id is 1)
115 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
116 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
117 valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
119 // pkgPathMap maps package names to the set of distinct import paths we've
120 // seen for that name, anywhere in the import graph. It is used for
121 // disambiguating package names in error messages.
123 // pkgPathMap is allocated lazily, so that we don't pay the price of building
124 // it on the happy path. seenPkgMap tracks the packages that we've already
126 pkgPathMap map[string]map[string]bool
127 seenPkgMap map[*Package]bool
129 // information collected during type-checking of a set of package files
130 // (initialized by Files, valid only for the duration of check.Files;
131 // maps and lists are allocated on demand)
132 files []*ast.File // package files
133 imports []*PkgName // list of imported packages
134 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
135 recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
136 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
137 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
138 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
140 firstErr error // first error encountered
141 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
142 untyped map[ast.Expr]exprInfo // map of expressions without final type
143 delayed []action // stack of delayed action segments; segments are processed in FIFO order
144 objPath []Object // path of object dependencies during type inference (for cycle reporting)
145 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
147 // environment within which the current object is type-checked (valid only
148 // for the duration of type-checking a specific object)
152 indent int // indentation for tracing
155 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
156 func (check *Checker) addDeclDep(to Object) {
159 return // not in a package-level init expression
161 if _, found := check.objMap[to]; !found {
162 return // to is not a package-level object
167 // Note: The following three alias-related functions are only used
168 // when Alias types are not enabled.
170 // brokenAlias records that alias doesn't have a determined type yet.
171 // It also sets alias.typ to Typ[Invalid].
172 // Not used if check.enableAlias is set.
173 func (check *Checker) brokenAlias(alias *TypeName) {
174 assert(!check.enableAlias)
175 if check.brokenAliases == nil {
176 check.brokenAliases = make(map[*TypeName]bool)
178 check.brokenAliases[alias] = true
179 alias.typ = Typ[Invalid]
182 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
183 func (check *Checker) validAlias(alias *TypeName, typ Type) {
184 assert(!check.enableAlias)
185 delete(check.brokenAliases, alias)
189 // isBrokenAlias reports whether alias doesn't have a determined type yet.
190 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
191 assert(!check.enableAlias)
192 return check.brokenAliases[alias]
195 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
198 m = make(map[ast.Expr]exprInfo)
201 m[e] = exprInfo{lhs, mode, typ, val}
204 // later pushes f on to the stack of actions that will be processed later;
205 // either at the end of the current statement, or in case of a local constant
206 // or variable declaration, before the constant or variable is in scope
207 // (so that f still sees the scope before any new declarations).
208 // later returns the pushed action so one can provide a description
209 // via action.describef for debugging, if desired.
210 func (check *Checker) later(f func()) *action {
211 i := len(check.delayed)
212 check.delayed = append(check.delayed, action{f: f})
213 return &check.delayed[i]
216 // push pushes obj onto the object path and returns its index in the path.
217 func (check *Checker) push(obj Object) int {
218 check.objPath = append(check.objPath, obj)
219 return len(check.objPath) - 1
222 // pop pops and returns the topmost object from the object path.
223 func (check *Checker) pop() Object {
224 i := len(check.objPath) - 1
225 obj := check.objPath[i]
226 check.objPath[i] = nil
227 check.objPath = check.objPath[:i]
231 type cleaner interface {
235 // needsCleanup records objects/types that implement the cleanup method
236 // which will be called at the end of type-checking.
237 func (check *Checker) needsCleanup(c cleaner) {
238 check.cleaners = append(check.cleaners, c)
241 // NewChecker returns a new [Checker] instance for a given package.
242 // [Package] files may be added incrementally via checker.Files.
243 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
244 // make sure we have a configuration
249 // make sure we have an info struct
254 // Note: clients may call NewChecker with the Unsafe package, which is
255 // globally shared and must not be mutated. Therefore NewChecker must not
258 // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
261 enableAlias: gotypesalias.Value() == "1",
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 // collect file versions
309 for _, file := range check.files {
310 check.recordFileVersion(file, check.conf.GoVersion) // record package version (possibly zero version)
311 if v, _ := parseGoVersion(file.GoVersion); v.major > 0 {
312 if v.equal(check.version) {
315 // Go 1.21 introduced the feature of setting the go.mod
316 // go line to an early version of Go and allowing //go:build lines
317 // to “upgrade” the Go version in a given file.
318 // We can do that backwards compatibly.
319 // Go 1.21 also introduced the feature of allowing //go:build lines
320 // to “downgrade” the Go version in a given file.
321 // That can't be done compatibly in general, since before the
322 // build lines were ignored and code got the module's Go version.
323 // To work around this, downgrades are only allowed when the
324 // module's Go version is Go 1.21 or later.
325 // If there is no check.version, then we don't really know what Go version to apply.
326 // Legacy tools may do this, and they historically have accepted everything.
327 // Preserve that behavior by ignoring //go:build constraints entirely in that case.
328 if (v.before(check.version) && check.version.before(go1_21)) || check.version.equal(go0_0) {
331 if check.posVers == nil {
332 check.posVers = make(map[token.Pos]version)
334 check.posVers[file.FileStart] = v
335 check.recordFileVersion(file, file.GoVersion) // overwrite package version
340 // A bailout panic is used for early termination.
341 type bailout struct{}
343 func (check *Checker) handleBailout(err *error) {
344 switch p := recover().(type) {
346 // normal return or early exit
347 *err = check.firstErr
354 // Files checks the provided files as part of the checker's package.
355 func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
357 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
359 func (check *Checker) checkFiles(files []*ast.File) (err error) {
360 if check.pkg == Unsafe {
361 // Defensive handling for Unsafe, which cannot be type checked, and must
362 // not be mutated. See https://go.dev/issue/61212 for an example of where
363 // Unsafe is passed to NewChecker.
367 // Note: parseGoVersion and the subsequent checks should happen once,
368 // when we create a new Checker, not for each batch of files.
369 // We can't change it at this point because NewChecker doesn't
371 check.version, err = parseGoVersion(check.conf.GoVersion)
375 if check.version.after(version{1, goversion.Version}) {
376 return fmt.Errorf("package requires newer Go version %v", check.version)
378 if check.conf.FakeImportC && check.conf.go115UsesCgo {
382 defer check.handleBailout(&err)
384 print := func(msg string) {
385 if check.conf._Trace {
391 print("== initFiles ==")
392 check.initFiles(files)
394 print("== collectObjects ==")
395 check.collectObjects()
397 print("== packageObjects ==")
398 check.packageObjects()
400 print("== processDelayed ==")
401 check.processDelayed(0) // incl. all functions
403 print("== cleanup ==")
406 print("== initOrder ==")
409 if !check.conf.DisableUnusedImportCheck {
410 print("== unusedImports ==")
411 check.unusedImports()
414 print("== recordUntyped ==")
415 check.recordUntyped()
417 if check.firstErr == nil {
418 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
422 check.pkg.goVersion = check.conf.GoVersion
423 check.pkg.complete = true
425 // no longer needed - release memory
427 check.dotImportMap = nil
428 check.pkgPathMap = nil
429 check.seenPkgMap = nil
430 check.recvTParamMap = nil
431 check.brokenAliases = nil
432 check.unionTypeSets = nil
435 // TODO(rFindley) There's more memory we should release at this point.
440 // processDelayed processes all delayed actions pushed after top.
441 func (check *Checker) processDelayed(top int) {
442 // If each delayed action pushes a new action, the
443 // stack will continue to grow during this loop.
444 // However, it is only processing functions (which
445 // are processed in a delayed fashion) that may
446 // add more actions (such as nested functions), so
447 // this is a sufficiently bounded process.
448 for i := top; i < len(check.delayed); i++ {
449 a := &check.delayed[i]
450 if check.conf._Trace {
452 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
454 check.trace(nopos, "-- delayed %p", a.f)
457 a.f() // may append to check.delayed
458 if check.conf._Trace {
462 assert(top <= len(check.delayed)) // stack must not have shrunk
463 check.delayed = check.delayed[:top]
466 // cleanup runs cleanup for all collected cleaners.
467 func (check *Checker) cleanup() {
468 // Don't use a range clause since Named.cleanup may add more cleaners.
469 for i := 0; i < len(check.cleaners); i++ {
470 check.cleaners[i].cleanup()
475 func (check *Checker) record(x *operand) {
476 // convert x into a user-friendly set of values
477 // TODO(gri) this code can be simplified
479 var val constant.Value
491 assert(x.expr != nil && typ != nil)
494 // delay type and value recording until we know the type
495 // or until the end of type checking
496 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
498 check.recordTypeAndValue(x.expr, x.mode, typ, val)
502 func (check *Checker) recordUntyped() {
503 if !debug && check.Types == nil {
504 return // nothing to do
507 for x, info := range check.untyped {
508 if debug && isTyped(info.typ) {
509 check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
512 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
516 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
522 if mode == constant_ {
524 // We check allBasic(typ, IsConstType) here as constant expressions may be
525 // recorded as type parameters.
526 assert(!isValid(typ) || allBasic(typ, IsConstType))
528 if m := check.Types; m != nil {
529 m[x] = TypeAndValue{mode, typ, val}
533 func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
534 // f must be a (possibly parenthesized, possibly qualified)
535 // identifier denoting a built-in (including unsafe's non-constant
536 // functions Add and Slice): record the signature for f and possible
539 check.recordTypeAndValue(f, builtin, sig, nil)
540 switch p := f.(type) {
541 case *ast.Ident, *ast.SelectorExpr:
551 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
552 // (and therefore has tuple type).
553 func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
556 if a[0].mode == invalid {
559 t0, t1 := a[0].typ, a[1].typ
560 assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
561 if m := check.Types; m != nil {
564 assert(tv.Type != nil) // should have been recorded already
567 NewVar(pos, check.pkg, "", t0),
568 NewVar(pos, check.pkg, "", t1),
571 // if x is a parenthesized expression (p.X), update p.X
572 p, _ := x.(*ast.ParenExpr)
581 // recordInstance records instantiation information into check.Info, if the
582 // Instances map is non-nil. The given expr must be an ident, selector, or
583 // index (list) expr with ident or selector operand.
585 // TODO(rfindley): the expr parameter is fragile. See if we can access the
586 // instantiated identifier in some other way.
587 func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
588 ident := instantiatedIdent(expr)
591 if m := check.Instances; m != nil {
592 m[ident] = Instance{newTypeList(targs), typ}
596 func instantiatedIdent(expr ast.Expr) *ast.Ident {
597 var selOrIdent ast.Expr
598 switch e := expr.(type) {
601 case *ast.IndexListExpr:
603 case *ast.SelectorExpr, *ast.Ident:
606 switch x := selOrIdent.(type) {
609 case *ast.SelectorExpr:
612 panic("instantiated ident not found")
615 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
617 if m := check.Defs; m != nil {
622 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
625 if m := check.Uses; m != nil {
630 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
633 if m := check.Implicits; m != nil {
638 func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
639 assert(obj != nil && (recv == nil || len(index) > 0))
640 check.recordUse(x.Sel, obj)
641 if m := check.Selections; m != nil {
642 m[x] = &Selection{kind, recv, obj, index, indirect}
646 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
649 if m := check.Scopes; m != nil {
654 func (check *Checker) recordFileVersion(file *ast.File, version string) {
655 if m := check.FileVersions; m != nil {