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"
14 . "internal/types/errors"
17 // nopos indicates an unknown position
20 // debugging/development support
21 const debug = false // leave on during development
23 // exprInfo stores information about an untyped expression.
24 type exprInfo struct {
25 isLhs bool // expression is lhs operand of a shift with delayed type-check
28 val constant.Value // constant value; or nil (if not a constant)
31 // An environment represents the environment within which an object is
33 type environment struct {
34 decl *declInfo // package-level declaration whose init expression/function body is checked
35 scope *Scope // top-most scope for lookups
36 pos syntax.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
37 iota constant.Value // value of iota in a constant declaration; nil otherwise
38 errpos syntax.Pos // if valid, identifier position of a constant with inherited initializer
39 inTParamList bool // set if inside a type parameter list
40 sig *Signature // function signature if inside a function; nil otherwise
41 isPanic map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
42 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
43 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
46 // lookup looks up name in the current environment and returns the matching object, or nil.
47 func (env *environment) lookup(name string) Object {
48 _, obj := env.scope.LookupParent(name, env.pos)
52 // An importKey identifies an imported package by import path and source directory
53 // (directory containing the file containing the import). In practice, the directory
54 // may always be the same, or may not matter. Given an (import path, directory), an
55 // importer must always return the same package (but given two different import paths,
56 // an importer may still return the same package by mapping them to the same package
58 type importKey struct {
62 // A dotImportKey describes a dot-imported object in the given scope.
63 type dotImportKey struct {
68 // An action describes a (delayed) action.
70 f func() // action to be executed
71 desc *actionDesc // action description; may be nil, requires debug to be set
74 // If debug is set, describef sets a printf-formatted description for action a.
75 // Otherwise, it is a no-op.
76 func (a *action) describef(pos poser, format string, args ...interface{}) {
78 a.desc = &actionDesc{pos, format, args}
82 // An actionDesc provides information on an action.
83 // For debugging only.
84 type actionDesc struct {
90 // A Checker maintains the state of the type checker.
91 // It must be created with NewChecker.
93 // package information
94 // (initialized by NewChecker, valid for the life-time of checker)
96 ctxt *Context // context for de-duplicating instances
99 version version // accepted language version
100 nextID uint64 // unique Id for type parameters (first valid Id is 1)
101 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
102 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
103 valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
105 // pkgPathMap maps package names to the set of distinct import paths we've
106 // seen for that name, anywhere in the import graph. It is used for
107 // disambiguating package names in error messages.
109 // pkgPathMap is allocated lazily, so that we don't pay the price of building
110 // it on the happy path. seenPkgMap tracks the packages that we've already
112 pkgPathMap map[string]map[string]bool
113 seenPkgMap map[*Package]bool
115 // information collected during type-checking of a set of package files
116 // (initialized by Files, valid only for the duration of check.Files;
117 // maps and lists are allocated on demand)
118 files []*syntax.File // list of package files
119 posVers map[*syntax.PosBase]version // Pos -> Go version mapping
120 imports []*PkgName // list of imported packages
121 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
122 recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
123 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
124 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
125 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
127 firstErr error // first error encountered
128 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
129 untyped map[syntax.Expr]exprInfo // map of expressions without final type
130 delayed []action // stack of delayed action segments; segments are processed in FIFO order
131 objPath []Object // path of object dependencies during type inference (for cycle reporting)
132 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
134 // environment within which the current object is type-checked (valid only
135 // for the duration of type-checking a specific object)
139 indent int // indentation for tracing
142 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
143 func (check *Checker) addDeclDep(to Object) {
146 return // not in a package-level init expression
148 if _, found := check.objMap[to]; !found {
149 return // to is not a package-level object
154 // brokenAlias records that alias doesn't have a determined type yet.
155 // It also sets alias.typ to Typ[Invalid].
156 func (check *Checker) brokenAlias(alias *TypeName) {
157 if check.brokenAliases == nil {
158 check.brokenAliases = make(map[*TypeName]bool)
160 check.brokenAliases[alias] = true
161 alias.typ = Typ[Invalid]
164 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
165 func (check *Checker) validAlias(alias *TypeName, typ Type) {
166 delete(check.brokenAliases, alias)
170 // isBrokenAlias reports whether alias doesn't have a determined type yet.
171 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
172 return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
175 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
178 m = make(map[syntax.Expr]exprInfo)
181 m[e] = exprInfo{lhs, mode, typ, val}
184 // later pushes f on to the stack of actions that will be processed later;
185 // either at the end of the current statement, or in case of a local constant
186 // or variable declaration, before the constant or variable is in scope
187 // (so that f still sees the scope before any new declarations).
188 // later returns the pushed action so one can provide a description
189 // via action.describef for debugging, if desired.
190 func (check *Checker) later(f func()) *action {
191 i := len(check.delayed)
192 check.delayed = append(check.delayed, action{f: f})
193 return &check.delayed[i]
196 // push pushes obj onto the object path and returns its index in the path.
197 func (check *Checker) push(obj Object) int {
198 check.objPath = append(check.objPath, obj)
199 return len(check.objPath) - 1
202 // pop pops and returns the topmost object from the object path.
203 func (check *Checker) pop() Object {
204 i := len(check.objPath) - 1
205 obj := check.objPath[i]
206 check.objPath[i] = nil
207 check.objPath = check.objPath[:i]
211 type cleaner interface {
215 // needsCleanup records objects/types that implement the cleanup method
216 // which will be called at the end of type-checking.
217 func (check *Checker) needsCleanup(c cleaner) {
218 check.cleaners = append(check.cleaners, c)
221 // NewChecker returns a new Checker instance for a given package.
222 // Package files may be added incrementally via checker.Files.
223 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
224 // make sure we have a configuration
229 // make sure we have an info struct
234 version, err := parseGoVersion(conf.GoVersion)
236 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
245 objMap: make(map[Object]*declInfo),
246 impMap: make(map[importKey]*Package),
250 // initFiles initializes the files-specific portion of checker.
251 // The provided files must all belong to the same package.
252 func (check *Checker) initFiles(files []*syntax.File) {
253 // start with a clean slate (check.Files may be called multiple times)
256 check.dotImportMap = nil
265 // determine package name and collect valid files
267 for _, file := range files {
268 switch name := file.PkgName.Value; pkg.name {
273 check.error(file.PkgName, BlankPkgName, "invalid package name _")
278 check.files = append(check.files, file)
281 check.errorf(file, MismatchedPkgName, "package %s; expected %s", name, pkg.name)
286 for _, file := range check.files {
287 v, _ := parseGoVersion(file.GoVersion)
289 if v.equal(check.version) {
292 // Go 1.21 introduced the feature of setting the go.mod
293 // go line to an early version of Go and allowing //go:build lines
294 // to “upgrade” the Go version in a given file.
295 // We can do that backwards compatibly.
296 // Go 1.21 also introduced the feature of allowing //go:build lines
297 // to “downgrade” the Go version in a given file.
298 // That can't be done compatibly in general, since before the
299 // build lines were ignored and code got the module's Go version.
300 // To work around this, downgrades are only allowed when the
301 // module's Go version is Go 1.21 or later.
302 // If there is no check.version, then we don't really know what Go version to apply.
303 // Legacy tools may do this, and they historically have accepted everything.
304 // Preserve that behavior by ignoring //go:build constraints entirely in that case.
305 if (v.before(check.version) && check.version.before(version{1, 21})) || check.version.equal(version{0, 0}) {
308 if check.posVers == nil {
309 check.posVers = make(map[*syntax.PosBase]version)
311 check.posVers[base(file.Pos())] = v
316 // A bailout panic is used for early termination.
317 type bailout struct{}
319 func (check *Checker) handleBailout(err *error) {
320 switch p := recover().(type) {
322 // normal return or early exit
323 *err = check.firstErr
330 // Files checks the provided files as part of the checker's package.
331 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
333 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
335 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
336 if check.conf.FakeImportC && check.conf.go115UsesCgo {
340 defer check.handleBailout(&err)
342 print := func(msg string) {
343 if check.conf.Trace {
349 print("== initFiles ==")
350 check.initFiles(files)
352 print("== collectObjects ==")
353 check.collectObjects()
355 print("== packageObjects ==")
356 check.packageObjects()
358 print("== processDelayed ==")
359 check.processDelayed(0) // incl. all functions
361 print("== cleanup ==")
364 print("== initOrder ==")
367 if !check.conf.DisableUnusedImportCheck {
368 print("== unusedImports ==")
369 check.unusedImports()
372 print("== recordUntyped ==")
373 check.recordUntyped()
375 if check.firstErr == nil {
376 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
380 check.pkg.complete = true
382 // no longer needed - release memory
384 check.dotImportMap = nil
385 check.pkgPathMap = nil
386 check.seenPkgMap = nil
387 check.recvTParamMap = nil
388 check.brokenAliases = nil
389 check.unionTypeSets = nil
392 // TODO(gri) There's more memory we should release at this point.
397 // processDelayed processes all delayed actions pushed after top.
398 func (check *Checker) processDelayed(top int) {
399 // If each delayed action pushes a new action, the
400 // stack will continue to grow during this loop.
401 // However, it is only processing functions (which
402 // are processed in a delayed fashion) that may
403 // add more actions (such as nested functions), so
404 // this is a sufficiently bounded process.
405 for i := top; i < len(check.delayed); i++ {
406 a := &check.delayed[i]
407 if check.conf.Trace {
409 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
411 check.trace(nopos, "-- delayed %p", a.f)
414 a.f() // may append to check.delayed
415 if check.conf.Trace {
419 assert(top <= len(check.delayed)) // stack must not have shrunk
420 check.delayed = check.delayed[:top]
423 // cleanup runs cleanup for all collected cleaners.
424 func (check *Checker) cleanup() {
425 // Don't use a range clause since Named.cleanup may add more cleaners.
426 for i := 0; i < len(check.cleaners); i++ {
427 check.cleaners[i].cleanup()
432 func (check *Checker) record(x *operand) {
433 // convert x into a user-friendly set of values
434 // TODO(gri) this code can be simplified
436 var val constant.Value
448 assert(x.expr != nil && typ != nil)
451 // delay type and value recording until we know the type
452 // or until the end of type checking
453 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
455 check.recordTypeAndValue(x.expr, x.mode, typ, val)
459 func (check *Checker) recordUntyped() {
460 if !debug && !check.recordTypes() {
461 return // nothing to do
464 for x, info := range check.untyped {
465 if debug && isTyped(info.typ) {
466 check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
469 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
473 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
479 if mode == constant_ {
481 // We check allBasic(typ, IsConstType) here as constant expressions may be
482 // recorded as type parameters.
483 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
485 if m := check.Types; m != nil {
486 m[x] = TypeAndValue{mode, typ, val}
488 if check.StoreTypesInSyntax {
489 tv := TypeAndValue{mode, typ, val}
490 stv := syntax.TypeAndValue{Type: typ, Value: val}
506 if tv.Addressable() {
519 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
520 // f must be a (possibly parenthesized, possibly qualified)
521 // identifier denoting a built-in (including unsafe's non-constant
522 // functions Add and Slice): record the signature for f and possible
525 check.recordTypeAndValue(f, builtin, sig, nil)
526 switch p := f.(type) {
527 case *syntax.Name, *syntax.SelectorExpr:
529 case *syntax.ParenExpr:
537 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
538 // (and therefore has tuple type).
539 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand) {
542 if a[0].mode == invalid {
545 t0, t1 := a[0].typ, a[1].typ
546 assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
547 if m := check.Types; m != nil {
550 assert(tv.Type != nil) // should have been recorded already
553 NewVar(pos, check.pkg, "", t0),
554 NewVar(pos, check.pkg, "", t1),
557 // if x is a parenthesized expression (p.X), update p.X
558 p, _ := x.(*syntax.ParenExpr)
565 if check.StoreTypesInSyntax {
566 // Note: this loop is duplicated because the type of tv is different.
567 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
569 tv := x.GetTypeInfo()
570 assert(tv.Type != nil) // should have been recorded already
573 NewVar(pos, check.pkg, "", t0),
574 NewVar(pos, check.pkg, "", t1),
577 p, _ := x.(*syntax.ParenExpr)
586 // recordInstance records instantiation information into check.Info, if the
587 // Instances map is non-nil. The given expr must be an ident, selector, or
588 // index (list) expr with ident or selector operand.
590 // TODO(rfindley): the expr parameter is fragile. See if we can access the
591 // instantiated identifier in some other way.
592 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
593 ident := instantiatedIdent(expr)
596 if m := check.Instances; m != nil {
597 m[ident] = Instance{newTypeList(targs), typ}
601 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
602 var selOrIdent syntax.Expr
603 switch e := expr.(type) {
604 case *syntax.IndexExpr:
606 case *syntax.SelectorExpr, *syntax.Name:
609 switch x := selOrIdent.(type) {
612 case *syntax.SelectorExpr:
615 panic("instantiated ident not found")
618 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
620 if m := check.Defs; m != nil {
625 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
628 if m := check.Uses; m != nil {
633 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
636 if m := check.Implicits; m != nil {
641 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
642 assert(obj != nil && (recv == nil || len(index) > 0))
643 check.recordUse(x.Sel, obj)
644 if m := check.Selections; m != nil {
645 m[x] = &Selection{kind, recv, obj, index, indirect}
649 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
652 if m := check.Scopes; m != nil {