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 // exprInfo stores information about an untyped expression.
26 type exprInfo struct {
27 isLhs bool // expression is lhs operand of a shift with delayed type-check
30 val constant.Value // constant value; or nil (if not a constant)
33 // An environment represents the environment within which an object is
35 type environment struct {
36 decl *declInfo // package-level declaration whose init expression/function body is checked
37 scope *Scope // top-most scope for lookups
38 pos token.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
39 iota constant.Value // value of iota in a constant declaration; nil otherwise
40 errpos positioner // if set, identifier position of a constant with inherited initializer
41 inTParamList bool // set if inside a type parameter list
42 sig *Signature // function signature if inside a function; nil otherwise
43 isPanic map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
44 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
45 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
48 // lookup looks up name in the current environment and returns the matching object, or nil.
49 func (env *environment) lookup(name string) Object {
50 _, obj := env.scope.LookupParent(name, env.pos)
54 // An importKey identifies an imported package by import path and source directory
55 // (directory containing the file containing the import). In practice, the directory
56 // may always be the same, or may not matter. Given an (import path, directory), an
57 // importer must always return the same package (but given two different import paths,
58 // an importer may still return the same package by mapping them to the same package
60 type importKey struct {
64 // A dotImportKey describes a dot-imported object in the given scope.
65 type dotImportKey struct {
70 // An action describes a (delayed) action.
72 f func() // action to be executed
73 desc *actionDesc // action description; may be nil, requires debug to be set
76 // If debug is set, describef sets a printf-formatted description for action a.
77 // Otherwise, it is a no-op.
78 func (a *action) describef(pos positioner, format string, args ...any) {
80 a.desc = &actionDesc{pos, format, args}
84 // An actionDesc provides information on an action.
85 // For debugging only.
86 type actionDesc struct {
92 // A Checker maintains the state of the type checker.
93 // It must be created with NewChecker.
95 // package information
96 // (initialized by NewChecker, valid for the life-time of checker)
98 ctxt *Context // context for de-duplicating instances
102 version version // accepted language version
103 versionErr error // version error, delayed from NewChecker
104 nextID uint64 // unique Id for type parameters (first valid Id is 1)
105 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
106 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
107 valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
109 // pkgPathMap maps package names to the set of distinct import paths we've
110 // seen for that name, anywhere in the import graph. It is used for
111 // disambiguating package names in error messages.
113 // pkgPathMap is allocated lazily, so that we don't pay the price of building
114 // it on the happy path. seenPkgMap tracks the packages that we've already
116 pkgPathMap map[string]map[string]bool
117 seenPkgMap map[*Package]bool
119 // information collected during type-checking of a set of package files
120 // (initialized by Files, valid only for the duration of check.Files;
121 // maps and lists are allocated on demand)
122 files []*ast.File // package files
123 posVers map[*token.File]version // Pos -> Go version mapping
124 imports []*PkgName // list of imported packages
125 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
126 recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
127 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
128 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
129 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
131 firstErr error // first error encountered
132 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
133 untyped map[ast.Expr]exprInfo // map of expressions without final type
134 delayed []action // stack of delayed action segments; segments are processed in FIFO order
135 objPath []Object // path of object dependencies during type inference (for cycle reporting)
136 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
138 // environment within which the current object is type-checked (valid only
139 // for the duration of type-checking a specific object)
143 indent int // indentation for tracing
146 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
147 func (check *Checker) addDeclDep(to Object) {
150 return // not in a package-level init expression
152 if _, found := check.objMap[to]; !found {
153 return // to is not a package-level object
158 // brokenAlias records that alias doesn't have a determined type yet.
159 // It also sets alias.typ to Typ[Invalid].
160 func (check *Checker) brokenAlias(alias *TypeName) {
161 if check.brokenAliases == nil {
162 check.brokenAliases = make(map[*TypeName]bool)
164 check.brokenAliases[alias] = true
165 alias.typ = Typ[Invalid]
168 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
169 func (check *Checker) validAlias(alias *TypeName, typ Type) {
170 delete(check.brokenAliases, alias)
174 // isBrokenAlias reports whether alias doesn't have a determined type yet.
175 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
176 return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
179 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
182 m = make(map[ast.Expr]exprInfo)
185 m[e] = exprInfo{lhs, mode, typ, val}
188 // later pushes f on to the stack of actions that will be processed later;
189 // either at the end of the current statement, or in case of a local constant
190 // or variable declaration, before the constant or variable is in scope
191 // (so that f still sees the scope before any new declarations).
192 // later returns the pushed action so one can provide a description
193 // via action.describef for debugging, if desired.
194 func (check *Checker) later(f func()) *action {
195 i := len(check.delayed)
196 check.delayed = append(check.delayed, action{f: f})
197 return &check.delayed[i]
200 // push pushes obj onto the object path and returns its index in the path.
201 func (check *Checker) push(obj Object) int {
202 check.objPath = append(check.objPath, obj)
203 return len(check.objPath) - 1
206 // pop pops and returns the topmost object from the object path.
207 func (check *Checker) pop() Object {
208 i := len(check.objPath) - 1
209 obj := check.objPath[i]
210 check.objPath[i] = nil
211 check.objPath = check.objPath[:i]
215 type cleaner interface {
219 // needsCleanup records objects/types that implement the cleanup method
220 // which will be called at the end of type-checking.
221 func (check *Checker) needsCleanup(c cleaner) {
222 check.cleaners = append(check.cleaners, c)
225 // NewChecker returns a new Checker instance for a given package.
226 // Package files may be added incrementally via checker.Files.
227 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
228 // make sure we have a configuration
233 // make sure we have an info struct
238 version, versionErr := parseGoVersion(conf.GoVersion)
240 pkg.goVersion = conf.GoVersion
250 versionErr: versionErr,
251 objMap: make(map[Object]*declInfo),
252 impMap: make(map[importKey]*Package),
256 // initFiles initializes the files-specific portion of checker.
257 // The provided files must all belong to the same package.
258 func (check *Checker) initFiles(files []*ast.File) {
259 // start with a clean slate (check.Files may be called multiple times)
262 check.dotImportMap = nil
271 // determine package name and collect valid files
273 for _, file := range files {
274 switch name := file.Name.Name; pkg.name {
279 check.error(file.Name, BlankPkgName, "invalid package name _")
284 check.files = append(check.files, file)
287 check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected %s", name, pkg.name)
292 for _, file := range check.files {
293 v, _ := parseGoVersion(file.GoVersion)
295 if v.equal(check.version) {
298 // Go 1.21 introduced the feature of setting the go.mod
299 // go line to an early version of Go and allowing //go:build lines
300 // to “upgrade” the Go version in a given file.
301 // We can do that backwards compatibly.
302 // Go 1.21 also introduced the feature of allowing //go:build lines
303 // to “downgrade” the Go version in a given file.
304 // That can't be done compatibly in general, since before the
305 // build lines were ignored and code got the module's Go version.
306 // To work around this, downgrades are only allowed when the
307 // module's Go version is Go 1.21 or later.
308 // If there is no check.version, then we don't really know what Go version to apply.
309 // Legacy tools may do this, and they historically have accepted everything.
310 // Preserve that behavior by ignoring //go:build constraints entirely in that case.
311 if (v.before(check.version) && check.version.before(version{1, 21})) || check.version.equal(version{0, 0}) {
314 if check.posVers == nil {
315 check.posVers = make(map[*token.File]version)
317 check.posVers[check.fset.File(file.FileStart)] = v
322 // A posVers records that the file starting at pos declares the Go version vers.
323 type posVers struct {
328 // A bailout panic is used for early termination.
329 type bailout struct{}
331 func (check *Checker) handleBailout(err *error) {
332 switch p := recover().(type) {
334 // normal return or early exit
335 *err = check.firstErr
342 // Files checks the provided files as part of the checker's package.
343 func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
345 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
347 func (check *Checker) checkFiles(files []*ast.File) (err error) {
348 if check.versionErr != nil {
349 return check.versionErr
351 if check.version.after(version{1, goversion.Version}) {
352 return fmt.Errorf("package requires newer Go version %v", check.version)
354 if check.conf.FakeImportC && check.conf.go115UsesCgo {
358 defer check.handleBailout(&err)
360 print := func(msg string) {
361 if check.conf._Trace {
367 print("== initFiles ==")
368 check.initFiles(files)
370 print("== collectObjects ==")
371 check.collectObjects()
373 print("== packageObjects ==")
374 check.packageObjects()
376 print("== processDelayed ==")
377 check.processDelayed(0) // incl. all functions
379 print("== cleanup ==")
382 print("== initOrder ==")
385 if !check.conf.DisableUnusedImportCheck {
386 print("== unusedImports ==")
387 check.unusedImports()
390 print("== recordUntyped ==")
391 check.recordUntyped()
393 if check.firstErr == nil {
394 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
398 check.pkg.complete = true
400 // no longer needed - release memory
402 check.dotImportMap = nil
403 check.pkgPathMap = nil
404 check.seenPkgMap = nil
405 check.recvTParamMap = nil
406 check.brokenAliases = nil
407 check.unionTypeSets = nil
410 // TODO(rFindley) There's more memory we should release at this point.
415 // processDelayed processes all delayed actions pushed after top.
416 func (check *Checker) processDelayed(top int) {
417 // If each delayed action pushes a new action, the
418 // stack will continue to grow during this loop.
419 // However, it is only processing functions (which
420 // are processed in a delayed fashion) that may
421 // add more actions (such as nested functions), so
422 // this is a sufficiently bounded process.
423 for i := top; i < len(check.delayed); i++ {
424 a := &check.delayed[i]
425 if check.conf._Trace {
427 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
429 check.trace(nopos, "-- delayed %p", a.f)
432 a.f() // may append to check.delayed
433 if check.conf._Trace {
437 assert(top <= len(check.delayed)) // stack must not have shrunk
438 check.delayed = check.delayed[:top]
441 // cleanup runs cleanup for all collected cleaners.
442 func (check *Checker) cleanup() {
443 // Don't use a range clause since Named.cleanup may add more cleaners.
444 for i := 0; i < len(check.cleaners); i++ {
445 check.cleaners[i].cleanup()
450 func (check *Checker) record(x *operand) {
451 // convert x into a user-friendly set of values
452 // TODO(gri) this code can be simplified
454 var val constant.Value
466 assert(x.expr != nil && typ != nil)
469 // delay type and value recording until we know the type
470 // or until the end of type checking
471 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
473 check.recordTypeAndValue(x.expr, x.mode, typ, val)
477 func (check *Checker) recordUntyped() {
478 if !debug && check.Types == nil {
479 return // nothing to do
482 for x, info := range check.untyped {
483 if debug && isTyped(info.typ) {
484 check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
487 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
491 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
497 if mode == constant_ {
499 // We check allBasic(typ, IsConstType) here as constant expressions may be
500 // recorded as type parameters.
501 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
503 if m := check.Types; m != nil {
504 m[x] = TypeAndValue{mode, typ, val}
508 func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
509 // f must be a (possibly parenthesized, possibly qualified)
510 // identifier denoting a built-in (including unsafe's non-constant
511 // functions Add and Slice): record the signature for f and possible
514 check.recordTypeAndValue(f, builtin, sig, nil)
515 switch p := f.(type) {
516 case *ast.Ident, *ast.SelectorExpr:
526 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
527 // (and therefore has tuple type).
528 func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
531 if a[0].mode == invalid {
534 t0, t1 := a[0].typ, a[1].typ
535 assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
536 if m := check.Types; m != nil {
539 assert(tv.Type != nil) // should have been recorded already
542 NewVar(pos, check.pkg, "", t0),
543 NewVar(pos, check.pkg, "", t1),
546 // if x is a parenthesized expression (p.X), update p.X
547 p, _ := x.(*ast.ParenExpr)
556 // recordInstance records instantiation information into check.Info, if the
557 // Instances map is non-nil. The given expr must be an ident, selector, or
558 // index (list) expr with ident or selector operand.
560 // TODO(rfindley): the expr parameter is fragile. See if we can access the
561 // instantiated identifier in some other way.
562 func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
563 ident := instantiatedIdent(expr)
566 if m := check.Instances; m != nil {
567 m[ident] = Instance{newTypeList(targs), typ}
571 func instantiatedIdent(expr ast.Expr) *ast.Ident {
572 var selOrIdent ast.Expr
573 switch e := expr.(type) {
576 case *ast.IndexListExpr:
578 case *ast.SelectorExpr, *ast.Ident:
581 switch x := selOrIdent.(type) {
584 case *ast.SelectorExpr:
587 panic("instantiated ident not found")
590 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
592 if m := check.Defs; m != nil {
597 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
600 if m := check.Uses; m != nil {
605 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
608 if m := check.Implicits; m != nil {
613 func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
614 assert(obj != nil && (recv == nil || len(index) > 0))
615 check.recordUse(x.Sel, obj)
616 if m := check.Selections; m != nil {
617 m[x] = &Selection{kind, recv, obj, index, indirect}
621 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
624 if m := check.Scopes; m != nil {