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.
10 "cmd/compile/internal/syntax"
15 . "internal/types/errors"
18 // nopos indicates an unknown position
21 // debugging/development support
22 const debug = false // leave on during development
24 // exprInfo stores information about an untyped expression.
25 type exprInfo struct {
26 isLhs bool // expression is lhs operand of a shift with delayed type-check
29 val constant.Value // constant value; or nil (if not a constant)
32 // An environment represents the environment within which an object is
34 type environment struct {
35 decl *declInfo // package-level declaration whose init expression/function body is checked
36 scope *Scope // top-most scope for lookups
37 pos syntax.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
38 iota constant.Value // value of iota in a constant declaration; nil otherwise
39 errpos syntax.Pos // if valid, identifier position of a constant with inherited initializer
40 inTParamList bool // set if inside a type parameter list
41 sig *Signature // function signature if inside a function; nil otherwise
42 isPanic map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
43 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
44 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
47 // lookup looks up name in the current environment and returns the matching object, or nil.
48 func (env *environment) lookup(name string) Object {
49 _, obj := env.scope.LookupParent(name, env.pos)
53 // An importKey identifies an imported package by import path and source directory
54 // (directory containing the file containing the import). In practice, the directory
55 // may always be the same, or may not matter. Given an (import path, directory), an
56 // importer must always return the same package (but given two different import paths,
57 // an importer may still return the same package by mapping them to the same package
59 type importKey struct {
63 // A dotImportKey describes a dot-imported object in the given scope.
64 type dotImportKey struct {
69 // An action describes a (delayed) action.
71 f func() // action to be executed
72 desc *actionDesc // action description; may be nil, requires debug to be set
75 // If debug is set, describef sets a printf-formatted description for action a.
76 // Otherwise, it is a no-op.
77 func (a *action) describef(pos poser, format string, args ...interface{}) {
79 a.desc = &actionDesc{pos, format, args}
83 // An actionDesc provides information on an action.
84 // For debugging only.
85 type actionDesc struct {
91 // A Checker maintains the state of the type checker.
92 // It must be created with NewChecker.
94 // package information
95 // (initialized by NewChecker, valid for the life-time of checker)
97 ctxt *Context // context for de-duplicating instances
100 version version // accepted language version
101 posVers map[*syntax.PosBase]version // maps file PosBases to versions (may be nil)
102 nextID uint64 // unique Id for type parameters (first valid Id is 1)
103 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
104 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
105 valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
107 // pkgPathMap maps package names to the set of distinct import paths we've
108 // seen for that name, anywhere in the import graph. It is used for
109 // disambiguating package names in error messages.
111 // pkgPathMap is allocated lazily, so that we don't pay the price of building
112 // it on the happy path. seenPkgMap tracks the packages that we've already
114 pkgPathMap map[string]map[string]bool
115 seenPkgMap map[*Package]bool
117 // information collected during type-checking of a set of package files
118 // (initialized by Files, valid only for the duration of check.Files;
119 // maps and lists are allocated on demand)
120 files []*syntax.File // list of package files
121 imports []*PkgName // list of imported packages
122 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
123 recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
124 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
125 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
126 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
128 firstErr error // first error encountered
129 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
130 untyped map[syntax.Expr]exprInfo // map of expressions without final type
131 delayed []action // stack of delayed action segments; segments are processed in FIFO order
132 objPath []Object // path of object dependencies during type inference (for cycle reporting)
133 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
135 // environment within which the current object is type-checked (valid only
136 // for the duration of type-checking a specific object)
140 indent int // indentation for tracing
143 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
144 func (check *Checker) addDeclDep(to Object) {
147 return // not in a package-level init expression
149 if _, found := check.objMap[to]; !found {
150 return // to is not a package-level object
155 // brokenAlias records that alias doesn't have a determined type yet.
156 // It also sets alias.typ to Typ[Invalid].
157 func (check *Checker) brokenAlias(alias *TypeName) {
158 if check.brokenAliases == nil {
159 check.brokenAliases = make(map[*TypeName]bool)
161 check.brokenAliases[alias] = true
162 alias.typ = Typ[Invalid]
165 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
166 func (check *Checker) validAlias(alias *TypeName, typ Type) {
167 delete(check.brokenAliases, alias)
171 // isBrokenAlias reports whether alias doesn't have a determined type yet.
172 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
173 return !isValid(alias.typ) && check.brokenAliases[alias]
176 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
179 m = make(map[syntax.Expr]exprInfo)
182 m[e] = exprInfo{lhs, mode, typ, val}
185 // later pushes f on to the stack of actions that will be processed later;
186 // either at the end of the current statement, or in case of a local constant
187 // or variable declaration, before the constant or variable is in scope
188 // (so that f still sees the scope before any new declarations).
189 // later returns the pushed action so one can provide a description
190 // via action.describef for debugging, if desired.
191 func (check *Checker) later(f func()) *action {
192 i := len(check.delayed)
193 check.delayed = append(check.delayed, action{f: f})
194 return &check.delayed[i]
197 // push pushes obj onto the object path and returns its index in the path.
198 func (check *Checker) push(obj Object) int {
199 check.objPath = append(check.objPath, obj)
200 return len(check.objPath) - 1
203 // pop pops and returns the topmost object from the object path.
204 func (check *Checker) pop() Object {
205 i := len(check.objPath) - 1
206 obj := check.objPath[i]
207 check.objPath[i] = nil
208 check.objPath = check.objPath[:i]
212 type cleaner interface {
216 // needsCleanup records objects/types that implement the cleanup method
217 // which will be called at the end of type-checking.
218 func (check *Checker) needsCleanup(c cleaner) {
219 check.cleaners = append(check.cleaners, c)
222 // NewChecker returns a new Checker instance for a given package.
223 // Package files may be added incrementally via checker.Files.
224 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
225 // make sure we have a configuration
230 // make sure we have an info struct
235 // Note: clients may call NewChecker with the Unsafe package, which is
236 // globally shared and must not be mutated. Therefore NewChecker must not
239 // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
246 objMap: make(map[Object]*declInfo),
247 impMap: make(map[importKey]*Package),
251 // initFiles initializes the files-specific portion of checker.
252 // The provided files must all belong to the same package.
253 func (check *Checker) initFiles(files []*syntax.File) {
254 // start with a clean slate (check.Files may be called multiple times)
257 check.dotImportMap = nil
266 // determine package name and collect valid files
268 for _, file := range files {
269 switch name := file.PkgName.Value; pkg.name {
274 check.error(file.PkgName, BlankPkgName, "invalid package name _")
279 check.files = append(check.files, file)
282 check.errorf(file, MismatchedPkgName, "package %s; expected %s", name, pkg.name)
287 for _, file := range check.files {
288 fbase := base(file.Pos()) // fbase may be nil for tests
289 check.recordFileVersion(fbase, check.version) // record package version (possibly zero version)
290 v, _ := parseGoVersion(file.GoVersion)
292 if v.equal(check.version) {
295 // Go 1.21 introduced the feature of setting the go.mod
296 // go line to an early version of Go and allowing //go:build lines
297 // to “upgrade” the Go version in a given file.
298 // We can do that backwards compatibly.
299 // Go 1.21 also introduced the feature of allowing //go:build lines
300 // to “downgrade” the Go version in a given file.
301 // That can't be done compatibly in general, since before the
302 // build lines were ignored and code got the module's Go version.
303 // To work around this, downgrades are only allowed when the
304 // module's Go version is Go 1.21 or later.
305 // If there is no check.version, then we don't really know what Go version to apply.
306 // Legacy tools may do this, and they historically have accepted everything.
307 // Preserve that behavior by ignoring //go:build constraints entirely in that case.
308 if (v.before(check.version) && check.version.before(go1_21)) || check.version.equal(go0_0) {
311 if check.posVers == nil {
312 check.posVers = make(map[*syntax.PosBase]version)
314 check.posVers[fbase] = v
315 check.recordFileVersion(fbase, v) // overwrite package version
320 // A bailout panic is used for early termination.
321 type bailout struct{}
323 func (check *Checker) handleBailout(err *error) {
324 switch p := recover().(type) {
326 // normal return or early exit
327 *err = check.firstErr
334 // Files checks the provided files as part of the checker's package.
335 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
337 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
339 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
340 if check.pkg == Unsafe {
341 // Defensive handling for Unsafe, which cannot be type checked, and must
342 // not be mutated. See https://go.dev/issue/61212 for an example of where
343 // Unsafe is passed to NewChecker.
347 // Note: parseGoVersion and the subsequent checks should happen once,
348 // when we create a new Checker, not for each batch of files.
349 // We can't change it at this point because NewChecker doesn't
351 check.version, err = parseGoVersion(check.conf.GoVersion)
355 if check.version.after(version{1, goversion.Version}) {
356 return fmt.Errorf("package requires newer Go version %v", check.version)
358 if check.conf.FakeImportC && check.conf.go115UsesCgo {
362 defer check.handleBailout(&err)
364 print := func(msg string) {
365 if check.conf.Trace {
371 print("== initFiles ==")
372 check.initFiles(files)
374 print("== collectObjects ==")
375 check.collectObjects()
377 print("== packageObjects ==")
378 check.packageObjects()
380 print("== processDelayed ==")
381 check.processDelayed(0) // incl. all functions
383 print("== cleanup ==")
386 print("== initOrder ==")
389 if !check.conf.DisableUnusedImportCheck {
390 print("== unusedImports ==")
391 check.unusedImports()
394 print("== recordUntyped ==")
395 check.recordUntyped()
397 if check.firstErr == nil {
398 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
402 check.pkg.goVersion = check.conf.GoVersion
403 check.pkg.complete = true
405 // no longer needed - release memory
407 check.dotImportMap = nil
408 check.pkgPathMap = nil
409 check.seenPkgMap = nil
410 check.recvTParamMap = nil
411 check.brokenAliases = nil
412 check.unionTypeSets = nil
415 // TODO(gri) There's more memory we should release at this point.
420 // processDelayed processes all delayed actions pushed after top.
421 func (check *Checker) processDelayed(top int) {
422 // If each delayed action pushes a new action, the
423 // stack will continue to grow during this loop.
424 // However, it is only processing functions (which
425 // are processed in a delayed fashion) that may
426 // add more actions (such as nested functions), so
427 // this is a sufficiently bounded process.
428 for i := top; i < len(check.delayed); i++ {
429 a := &check.delayed[i]
430 if check.conf.Trace {
432 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
434 check.trace(nopos, "-- delayed %p", a.f)
437 a.f() // may append to check.delayed
438 if check.conf.Trace {
442 assert(top <= len(check.delayed)) // stack must not have shrunk
443 check.delayed = check.delayed[:top]
446 // cleanup runs cleanup for all collected cleaners.
447 func (check *Checker) cleanup() {
448 // Don't use a range clause since Named.cleanup may add more cleaners.
449 for i := 0; i < len(check.cleaners); i++ {
450 check.cleaners[i].cleanup()
455 func (check *Checker) record(x *operand) {
456 // convert x into a user-friendly set of values
457 // TODO(gri) this code can be simplified
459 var val constant.Value
471 assert(x.expr != nil && typ != nil)
474 // delay type and value recording until we know the type
475 // or until the end of type checking
476 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
478 check.recordTypeAndValue(x.expr, x.mode, typ, val)
482 func (check *Checker) recordUntyped() {
483 if !debug && !check.recordTypes() {
484 return // nothing to do
487 for x, info := range check.untyped {
488 if debug && isTyped(info.typ) {
489 check.dump("%v: %s (type %s) is typed", atPos(x), x, info.typ)
492 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
496 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
502 if mode == constant_ {
504 // We check allBasic(typ, IsConstType) here as constant expressions may be
505 // recorded as type parameters.
506 assert(!isValid(typ) || allBasic(typ, IsConstType))
508 if m := check.Types; m != nil {
509 m[x] = TypeAndValue{mode, typ, val}
511 if check.StoreTypesInSyntax {
512 tv := TypeAndValue{mode, typ, val}
513 stv := syntax.TypeAndValue{Type: typ, Value: val}
529 if tv.Addressable() {
542 func (check *Checker) recordBuiltinType(f syntax.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 *syntax.Name, *syntax.SelectorExpr:
552 case *syntax.ParenExpr:
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 syntax.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.(*syntax.ParenExpr)
588 if check.StoreTypesInSyntax {
589 // Note: this loop is duplicated because the type of tv is different.
590 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
592 tv := x.GetTypeInfo()
593 assert(tv.Type != nil) // should have been recorded already
596 NewVar(pos, check.pkg, "", t0),
597 NewVar(pos, check.pkg, "", t1),
600 p, _ := x.(*syntax.ParenExpr)
609 // recordInstance records instantiation information into check.Info, if the
610 // Instances map is non-nil. The given expr must be an ident, selector, or
611 // index (list) expr with ident or selector operand.
613 // TODO(rfindley): the expr parameter is fragile. See if we can access the
614 // instantiated identifier in some other way.
615 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
616 ident := instantiatedIdent(expr)
619 if m := check.Instances; m != nil {
620 m[ident] = Instance{newTypeList(targs), typ}
624 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
625 var selOrIdent syntax.Expr
626 switch e := expr.(type) {
627 case *syntax.IndexExpr:
629 case *syntax.SelectorExpr, *syntax.Name:
632 switch x := selOrIdent.(type) {
635 case *syntax.SelectorExpr:
638 panic("instantiated ident not found")
641 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
643 if m := check.Defs; m != nil {
648 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
651 if m := check.Uses; m != nil {
656 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
659 if m := check.Implicits; m != nil {
664 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
665 assert(obj != nil && (recv == nil || len(index) > 0))
666 check.recordUse(x.Sel, obj)
667 if m := check.Selections; m != nil {
668 m[x] = &Selection{kind, recv, obj, index, indirect}
672 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
675 if m := check.Scopes; m != nil {
680 func (check *Checker) recordFileVersion(fbase *syntax.PosBase, v version) {
681 if m := check.FileVersions; m != nil {
682 m[fbase] = Version{v.major, v.minor}