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"
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 syntax.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 syntax.Pos // if valid, 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[*syntax.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 poser, format string, args ...interface{}) {
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
110 version version // accepted language version
111 posVers map[*syntax.PosBase]version // maps file PosBases to versions (may be nil)
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 []*syntax.File // list of package files
131 imports []*PkgName // list of imported packages
132 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
133 recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
134 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
135 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
136 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
138 firstErr error // first error encountered
139 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
140 untyped map[syntax.Expr]exprInfo // map of expressions without final type
141 delayed []action // stack of delayed action segments; segments are processed in FIFO order
142 objPath []Object // path of object dependencies during type inference (for cycle reporting)
143 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
145 // environment within which the current object is type-checked (valid only
146 // for the duration of type-checking a specific object)
150 indent int // indentation for tracing
153 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
154 func (check *Checker) addDeclDep(to Object) {
157 return // not in a package-level init expression
159 if _, found := check.objMap[to]; !found {
160 return // to is not a package-level object
165 // Note: The following three alias-related functions are only used
166 // when Alias types are not enabled.
168 // brokenAlias records that alias doesn't have a determined type yet.
169 // It also sets alias.typ to Typ[Invalid].
170 // Not used if check.enableAlias is set.
171 func (check *Checker) brokenAlias(alias *TypeName) {
172 assert(!check.enableAlias)
173 if check.brokenAliases == nil {
174 check.brokenAliases = make(map[*TypeName]bool)
176 check.brokenAliases[alias] = true
177 alias.typ = Typ[Invalid]
180 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
181 func (check *Checker) validAlias(alias *TypeName, typ Type) {
182 assert(!check.enableAlias)
183 delete(check.brokenAliases, alias)
187 // isBrokenAlias reports whether alias doesn't have a determined type yet.
188 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
189 assert(!check.enableAlias)
190 return check.brokenAliases[alias]
193 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
196 m = make(map[syntax.Expr]exprInfo)
199 m[e] = exprInfo{lhs, mode, typ, val}
202 // later pushes f on to the stack of actions that will be processed later;
203 // either at the end of the current statement, or in case of a local constant
204 // or variable declaration, before the constant or variable is in scope
205 // (so that f still sees the scope before any new declarations).
206 // later returns the pushed action so one can provide a description
207 // via action.describef for debugging, if desired.
208 func (check *Checker) later(f func()) *action {
209 i := len(check.delayed)
210 check.delayed = append(check.delayed, action{f: f})
211 return &check.delayed[i]
214 // push pushes obj onto the object path and returns its index in the path.
215 func (check *Checker) push(obj Object) int {
216 check.objPath = append(check.objPath, obj)
217 return len(check.objPath) - 1
220 // pop pops and returns the topmost object from the object path.
221 func (check *Checker) pop() Object {
222 i := len(check.objPath) - 1
223 obj := check.objPath[i]
224 check.objPath[i] = nil
225 check.objPath = check.objPath[:i]
229 type cleaner interface {
233 // needsCleanup records objects/types that implement the cleanup method
234 // which will be called at the end of type-checking.
235 func (check *Checker) needsCleanup(c cleaner) {
236 check.cleaners = append(check.cleaners, c)
239 // NewChecker returns a new Checker instance for a given package.
240 // Package files may be added incrementally via checker.Files.
241 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
242 // make sure we have a configuration
247 // make sure we have an info struct
252 // Note: clients may call NewChecker with the Unsafe package, which is
253 // globally shared and must not be mutated. Therefore NewChecker must not
256 // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
259 enableAlias: gotypesalias.Value() == "1",
264 objMap: make(map[Object]*declInfo),
265 impMap: make(map[importKey]*Package),
269 // initFiles initializes the files-specific portion of checker.
270 // The provided files must all belong to the same package.
271 func (check *Checker) initFiles(files []*syntax.File) {
272 // start with a clean slate (check.Files may be called multiple times)
275 check.dotImportMap = nil
284 // determine package name and collect valid files
286 for _, file := range files {
287 switch name := file.PkgName.Value; pkg.name {
292 check.error(file.PkgName, BlankPkgName, "invalid package name _")
297 check.files = append(check.files, file)
300 check.errorf(file, MismatchedPkgName, "package %s; expected %s", name, pkg.name)
305 for _, file := range check.files {
306 fbase := base(file.Pos()) // fbase may be nil for tests
307 check.recordFileVersion(fbase, check.conf.GoVersion) // record package version (possibly zero version)
308 v, _ := parseGoVersion(file.GoVersion)
310 if v.equal(check.version) {
313 // Go 1.21 introduced the feature of setting the go.mod
314 // go line to an early version of Go and allowing //go:build lines
315 // to “upgrade” the Go version in a given file.
316 // We can do that backwards compatibly.
317 // Go 1.21 also introduced the feature of allowing //go:build lines
318 // to “downgrade” the Go version in a given file.
319 // That can't be done compatibly in general, since before the
320 // build lines were ignored and code got the module's Go version.
321 // To work around this, downgrades are only allowed when the
322 // module's Go version is Go 1.21 or later.
323 // If there is no check.version, then we don't really know what Go version to apply.
324 // Legacy tools may do this, and they historically have accepted everything.
325 // Preserve that behavior by ignoring //go:build constraints entirely in that case.
326 if (v.before(check.version) && check.version.before(go1_21)) || check.version.equal(go0_0) {
329 if check.posVers == nil {
330 check.posVers = make(map[*syntax.PosBase]version)
332 check.posVers[fbase] = v
333 check.recordFileVersion(fbase, file.GoVersion) // overwrite package version
338 // A bailout panic is used for early termination.
339 type bailout struct{}
341 func (check *Checker) handleBailout(err *error) {
342 switch p := recover().(type) {
344 // normal return or early exit
345 *err = check.firstErr
352 // Files checks the provided files as part of the checker's package.
353 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
355 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
357 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
358 if check.pkg == Unsafe {
359 // Defensive handling for Unsafe, which cannot be type checked, and must
360 // not be mutated. See https://go.dev/issue/61212 for an example of where
361 // Unsafe is passed to NewChecker.
365 // Note: parseGoVersion and the subsequent checks should happen once,
366 // when we create a new Checker, not for each batch of files.
367 // We can't change it at this point because NewChecker doesn't
369 check.version, err = parseGoVersion(check.conf.GoVersion)
373 if check.version.after(version{1, goversion.Version}) {
374 return fmt.Errorf("package requires newer Go version %v", check.version)
376 if check.conf.FakeImportC && check.conf.go115UsesCgo {
380 defer check.handleBailout(&err)
382 print := func(msg string) {
383 if check.conf.Trace {
389 print("== initFiles ==")
390 check.initFiles(files)
392 print("== collectObjects ==")
393 check.collectObjects()
395 print("== packageObjects ==")
396 check.packageObjects()
398 print("== processDelayed ==")
399 check.processDelayed(0) // incl. all functions
401 print("== cleanup ==")
404 print("== initOrder ==")
407 if !check.conf.DisableUnusedImportCheck {
408 print("== unusedImports ==")
409 check.unusedImports()
412 print("== recordUntyped ==")
413 check.recordUntyped()
415 if check.firstErr == nil {
416 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
420 check.pkg.goVersion = check.conf.GoVersion
421 check.pkg.complete = true
423 // no longer needed - release memory
425 check.dotImportMap = nil
426 check.pkgPathMap = nil
427 check.seenPkgMap = nil
428 check.recvTParamMap = nil
429 check.brokenAliases = nil
430 check.unionTypeSets = nil
433 // TODO(gri) There's more memory we should release at this point.
438 // processDelayed processes all delayed actions pushed after top.
439 func (check *Checker) processDelayed(top int) {
440 // If each delayed action pushes a new action, the
441 // stack will continue to grow during this loop.
442 // However, it is only processing functions (which
443 // are processed in a delayed fashion) that may
444 // add more actions (such as nested functions), so
445 // this is a sufficiently bounded process.
446 for i := top; i < len(check.delayed); i++ {
447 a := &check.delayed[i]
448 if check.conf.Trace {
450 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
452 check.trace(nopos, "-- delayed %p", a.f)
455 a.f() // may append to check.delayed
456 if check.conf.Trace {
460 assert(top <= len(check.delayed)) // stack must not have shrunk
461 check.delayed = check.delayed[:top]
464 // cleanup runs cleanup for all collected cleaners.
465 func (check *Checker) cleanup() {
466 // Don't use a range clause since Named.cleanup may add more cleaners.
467 for i := 0; i < len(check.cleaners); i++ {
468 check.cleaners[i].cleanup()
473 func (check *Checker) record(x *operand) {
474 // convert x into a user-friendly set of values
475 // TODO(gri) this code can be simplified
477 var val constant.Value
489 assert(x.expr != nil && typ != nil)
492 // delay type and value recording until we know the type
493 // or until the end of type checking
494 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
496 check.recordTypeAndValue(x.expr, x.mode, typ, val)
500 func (check *Checker) recordUntyped() {
501 if !debug && !check.recordTypes() {
502 return // nothing to do
505 for x, info := range check.untyped {
506 if debug && isTyped(info.typ) {
507 check.dump("%v: %s (type %s) is typed", atPos(x), x, info.typ)
510 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
514 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
520 if mode == constant_ {
522 // We check allBasic(typ, IsConstType) here as constant expressions may be
523 // recorded as type parameters.
524 assert(!isValid(typ) || allBasic(typ, IsConstType))
526 if m := check.Types; m != nil {
527 m[x] = TypeAndValue{mode, typ, val}
529 if check.StoreTypesInSyntax {
530 tv := TypeAndValue{mode, typ, val}
531 stv := syntax.TypeAndValue{Type: typ, Value: val}
547 if tv.Addressable() {
560 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
561 // f must be a (possibly parenthesized, possibly qualified)
562 // identifier denoting a built-in (including unsafe's non-constant
563 // functions Add and Slice): record the signature for f and possible
566 check.recordTypeAndValue(f, builtin, sig, nil)
567 switch p := f.(type) {
568 case *syntax.Name, *syntax.SelectorExpr:
570 case *syntax.ParenExpr:
578 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
579 // (and therefore has tuple type).
580 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand) {
583 if a[0].mode == invalid {
586 t0, t1 := a[0].typ, a[1].typ
587 assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
588 if m := check.Types; m != nil {
591 assert(tv.Type != nil) // should have been recorded already
594 NewVar(pos, check.pkg, "", t0),
595 NewVar(pos, check.pkg, "", t1),
598 // if x is a parenthesized expression (p.X), update p.X
599 p, _ := x.(*syntax.ParenExpr)
606 if check.StoreTypesInSyntax {
607 // Note: this loop is duplicated because the type of tv is different.
608 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
610 tv := x.GetTypeInfo()
611 assert(tv.Type != nil) // should have been recorded already
614 NewVar(pos, check.pkg, "", t0),
615 NewVar(pos, check.pkg, "", t1),
618 p, _ := x.(*syntax.ParenExpr)
627 // recordInstance records instantiation information into check.Info, if the
628 // Instances map is non-nil. The given expr must be an ident, selector, or
629 // index (list) expr with ident or selector operand.
631 // TODO(rfindley): the expr parameter is fragile. See if we can access the
632 // instantiated identifier in some other way.
633 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
634 ident := instantiatedIdent(expr)
637 if m := check.Instances; m != nil {
638 m[ident] = Instance{newTypeList(targs), typ}
642 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
643 var selOrIdent syntax.Expr
644 switch e := expr.(type) {
645 case *syntax.IndexExpr:
647 case *syntax.SelectorExpr, *syntax.Name:
650 switch x := selOrIdent.(type) {
653 case *syntax.SelectorExpr:
656 panic("instantiated ident not found")
659 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
661 if m := check.Defs; m != nil {
666 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
669 if m := check.Uses; m != nil {
674 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
677 if m := check.Implicits; m != nil {
682 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
683 assert(obj != nil && (recv == nil || len(index) > 0))
684 check.recordUse(x.Sel, obj)
685 if m := check.Selections; m != nil {
686 m[x] = &Selection{kind, recv, obj, index, indirect}
690 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
693 if m := check.Scopes; m != nil {
698 func (check *Checker) recordFileVersion(fbase *syntax.PosBase, version string) {
699 if m := check.FileVersions; m != nil {