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 // gotypesalias controls the use of Alias types.
25 var gotypesalias = godebug.New("#gotypesalias")
27 // exprInfo stores information about an untyped expression.
28 type exprInfo struct {
29 isLhs bool // expression is lhs operand of a shift with delayed type-check
32 val constant.Value // constant value; or nil (if not a constant)
35 // An environment represents the environment within which an object is
37 type environment struct {
38 decl *declInfo // package-level declaration whose init expression/function body is checked
39 scope *Scope // top-most scope for lookups
40 pos syntax.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
41 iota constant.Value // value of iota in a constant declaration; nil otherwise
42 errpos syntax.Pos // if valid, identifier position of a constant with inherited initializer
43 inTParamList bool // set if inside a type parameter list
44 sig *Signature // function signature if inside a function; nil otherwise
45 isPanic map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
46 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
47 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
50 // lookup looks up name in the current environment and returns the matching object, or nil.
51 func (env *environment) lookup(name string) Object {
52 _, obj := env.scope.LookupParent(name, env.pos)
56 // An importKey identifies an imported package by import path and source directory
57 // (directory containing the file containing the import). In practice, the directory
58 // may always be the same, or may not matter. Given an (import path, directory), an
59 // importer must always return the same package (but given two different import paths,
60 // an importer may still return the same package by mapping them to the same package
62 type importKey struct {
66 // A dotImportKey describes a dot-imported object in the given scope.
67 type dotImportKey struct {
72 // An action describes a (delayed) action.
74 f func() // action to be executed
75 desc *actionDesc // action description; may be nil, requires debug to be set
78 // If debug is set, describef sets a printf-formatted description for action a.
79 // Otherwise, it is a no-op.
80 func (a *action) describef(pos poser, format string, args ...interface{}) {
82 a.desc = &actionDesc{pos, format, args}
86 // An actionDesc provides information on an action.
87 // For debugging only.
88 type actionDesc struct {
94 // A Checker maintains the state of the type checker.
95 // It must be created with NewChecker.
97 // package information
98 // (initialized by NewChecker, valid for the life-time of checker)
100 // If enableAlias is set, alias declarations produce an Alias type.
101 // Otherwise the alias information is only in the type name, which
102 // points directly to the actual (aliased) type.
106 ctxt *Context // context for de-duplicating instances
109 version goVersion // accepted language version
110 nextID uint64 // unique Id for type parameters (first valid Id is 1)
111 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
112 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
113 valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
115 // pkgPathMap maps package names to the set of distinct import paths we've
116 // seen for that name, anywhere in the import graph. It is used for
117 // disambiguating package names in error messages.
119 // pkgPathMap is allocated lazily, so that we don't pay the price of building
120 // it on the happy path. seenPkgMap tracks the packages that we've already
122 pkgPathMap map[string]map[string]bool
123 seenPkgMap map[*Package]bool
125 // information collected during type-checking of a set of package files
126 // (initialized by Files, valid only for the duration of check.Files;
127 // maps and lists are allocated on demand)
128 files []*syntax.File // list of package files
129 versions map[*syntax.PosBase]string // maps file bases to version strings (each file has an entry)
130 imports []*PkgName // list of imported packages
131 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
132 recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
133 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
134 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
135 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
137 firstErr error // first error encountered
138 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
139 untyped map[syntax.Expr]exprInfo // map of expressions without final type
140 delayed []action // stack of delayed action segments; segments are processed in FIFO order
141 objPath []Object // path of object dependencies during type inference (for cycle reporting)
142 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
144 // environment within which the current object is type-checked (valid only
145 // for the duration of type-checking a specific object)
149 indent int // indentation for tracing
152 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
153 func (check *Checker) addDeclDep(to Object) {
156 return // not in a package-level init expression
158 if _, found := check.objMap[to]; !found {
159 return // to is not a package-level object
164 // Note: The following three alias-related functions are only used
165 // when Alias types are not enabled.
167 // brokenAlias records that alias doesn't have a determined type yet.
168 // It also sets alias.typ to Typ[Invalid].
169 // Not used if check.enableAlias is set.
170 func (check *Checker) brokenAlias(alias *TypeName) {
171 assert(!check.enableAlias)
172 if check.brokenAliases == nil {
173 check.brokenAliases = make(map[*TypeName]bool)
175 check.brokenAliases[alias] = true
176 alias.typ = Typ[Invalid]
179 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
180 func (check *Checker) validAlias(alias *TypeName, typ Type) {
181 assert(!check.enableAlias)
182 delete(check.brokenAliases, alias)
186 // isBrokenAlias reports whether alias doesn't have a determined type yet.
187 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
188 assert(!check.enableAlias)
189 return check.brokenAliases[alias]
192 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
195 m = make(map[syntax.Expr]exprInfo)
198 m[e] = exprInfo{lhs, mode, typ, val}
201 // later pushes f on to the stack of actions that will be processed later;
202 // either at the end of the current statement, or in case of a local constant
203 // or variable declaration, before the constant or variable is in scope
204 // (so that f still sees the scope before any new declarations).
205 // later returns the pushed action so one can provide a description
206 // via action.describef for debugging, if desired.
207 func (check *Checker) later(f func()) *action {
208 i := len(check.delayed)
209 check.delayed = append(check.delayed, action{f: f})
210 return &check.delayed[i]
213 // push pushes obj onto the object path and returns its index in the path.
214 func (check *Checker) push(obj Object) int {
215 check.objPath = append(check.objPath, obj)
216 return len(check.objPath) - 1
219 // pop pops and returns the topmost object from the object path.
220 func (check *Checker) pop() Object {
221 i := len(check.objPath) - 1
222 obj := check.objPath[i]
223 check.objPath[i] = nil
224 check.objPath = check.objPath[:i]
228 type cleaner interface {
232 // needsCleanup records objects/types that implement the cleanup method
233 // which will be called at the end of type-checking.
234 func (check *Checker) needsCleanup(c cleaner) {
235 check.cleaners = append(check.cleaners, c)
238 // NewChecker returns a new Checker instance for a given package.
239 // Package files may be added incrementally via checker.Files.
240 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
241 // make sure we have a configuration
246 // make sure we have an info struct
251 // Note: clients may call NewChecker with the Unsafe package, which is
252 // globally shared and must not be mutated. Therefore NewChecker must not
255 // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
258 enableAlias: gotypesalias.Value() == "1",
263 version: asGoVersion(conf.GoVersion),
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 // reuse Info.FileVersions if provided
306 versions := check.Info.FileVersions
308 versions = make(map[*syntax.PosBase]string)
310 check.versions = versions
312 pkgVersionOk := check.version.isValid()
313 downgradeOk := check.version.cmp(go1_21) >= 0
315 // determine Go version for each file
316 for _, file := range check.files {
317 // use unaltered Config.GoVersion by default
318 // (This version string may contain dot-release numbers as in go1.20.1,
319 // unlike file versions which are Go language versions only, if valid.)
320 v := check.conf.GoVersion
321 // use the file version, if applicable
322 // (file versions are either the empty string or of the form go1.dd)
324 fileVersion := asGoVersion(file.GoVersion)
325 if fileVersion.isValid() {
326 cmp := fileVersion.cmp(check.version)
327 // Go 1.21 introduced the feature of setting the go.mod
328 // go line to an early version of Go and allowing //go:build lines
329 // to “upgrade” (cmp > 0) the Go version in a given file.
330 // We can do that backwards compatibly.
332 // Go 1.21 also introduced the feature of allowing //go:build lines
333 // to “downgrade” (cmp < 0) the Go version in a given file.
334 // That can't be done compatibly in general, since before the
335 // build lines were ignored and code got the module's Go version.
336 // To work around this, downgrades are only allowed when the
337 // module's Go version is Go 1.21 or later.
339 // If there is no valid check.version, then we don't really know what
340 // Go version to apply.
341 // Legacy tools may do this, and they historically have accepted everything.
342 // Preserve that behavior by ignoring //go:build constraints entirely in that
343 // case (!pkgVersionOk).
344 if cmp > 0 || cmp < 0 && downgradeOk {
349 versions[base(file.Pos())] = v // base(file.Pos()) may be nil for tests
353 // A bailout panic is used for early termination.
354 type bailout struct{}
356 func (check *Checker) handleBailout(err *error) {
357 switch p := recover().(type) {
359 // normal return or early exit
360 *err = check.firstErr
367 // Files checks the provided files as part of the checker's package.
368 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
370 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
372 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
373 if check.pkg == Unsafe {
374 // Defensive handling for Unsafe, which cannot be type checked, and must
375 // not be mutated. See https://go.dev/issue/61212 for an example of where
376 // Unsafe is passed to NewChecker.
380 // Note: NewChecker doesn't return an error, so we need to check the version here.
381 if check.version.cmp(go_current) > 0 {
382 return fmt.Errorf("package requires newer Go version %v", check.version)
384 if check.conf.FakeImportC && check.conf.go115UsesCgo {
388 defer check.handleBailout(&err)
390 print := func(msg string) {
391 if check.conf.Trace {
397 print("== initFiles ==")
398 check.initFiles(files)
400 print("== collectObjects ==")
401 check.collectObjects()
403 print("== packageObjects ==")
404 check.packageObjects()
406 print("== processDelayed ==")
407 check.processDelayed(0) // incl. all functions
409 print("== cleanup ==")
412 print("== initOrder ==")
415 if !check.conf.DisableUnusedImportCheck {
416 print("== unusedImports ==")
417 check.unusedImports()
420 print("== recordUntyped ==")
421 check.recordUntyped()
423 if check.firstErr == nil {
424 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
428 check.pkg.goVersion = check.conf.GoVersion
429 check.pkg.complete = true
431 // no longer needed - release memory
433 check.dotImportMap = nil
434 check.pkgPathMap = nil
435 check.seenPkgMap = nil
436 check.recvTParamMap = nil
437 check.brokenAliases = nil
438 check.unionTypeSets = nil
441 // TODO(gri) There's more memory we should release at this point.
446 // processDelayed processes all delayed actions pushed after top.
447 func (check *Checker) processDelayed(top int) {
448 // If each delayed action pushes a new action, the
449 // stack will continue to grow during this loop.
450 // However, it is only processing functions (which
451 // are processed in a delayed fashion) that may
452 // add more actions (such as nested functions), so
453 // this is a sufficiently bounded process.
454 for i := top; i < len(check.delayed); i++ {
455 a := &check.delayed[i]
456 if check.conf.Trace {
458 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
460 check.trace(nopos, "-- delayed %p", a.f)
463 a.f() // may append to check.delayed
464 if check.conf.Trace {
468 assert(top <= len(check.delayed)) // stack must not have shrunk
469 check.delayed = check.delayed[:top]
472 // cleanup runs cleanup for all collected cleaners.
473 func (check *Checker) cleanup() {
474 // Don't use a range clause since Named.cleanup may add more cleaners.
475 for i := 0; i < len(check.cleaners); i++ {
476 check.cleaners[i].cleanup()
481 func (check *Checker) record(x *operand) {
482 // convert x into a user-friendly set of values
483 // TODO(gri) this code can be simplified
485 var val constant.Value
497 assert(x.expr != nil && typ != nil)
500 // delay type and value recording until we know the type
501 // or until the end of type checking
502 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
504 check.recordTypeAndValue(x.expr, x.mode, typ, val)
508 func (check *Checker) recordUntyped() {
509 if !debug && !check.recordTypes() {
510 return // nothing to do
513 for x, info := range check.untyped {
514 if debug && isTyped(info.typ) {
515 check.dump("%v: %s (type %s) is typed", atPos(x), x, info.typ)
518 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
522 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
528 if mode == constant_ {
530 // We check allBasic(typ, IsConstType) here as constant expressions may be
531 // recorded as type parameters.
532 assert(!isValid(typ) || allBasic(typ, IsConstType))
534 if m := check.Types; m != nil {
535 m[x] = TypeAndValue{mode, typ, val}
537 if check.StoreTypesInSyntax {
538 tv := TypeAndValue{mode, typ, val}
539 stv := syntax.TypeAndValue{Type: typ, Value: val}
555 if tv.Addressable() {
568 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
569 // f must be a (possibly parenthesized, possibly qualified)
570 // identifier denoting a built-in (including unsafe's non-constant
571 // functions Add and Slice): record the signature for f and possible
574 check.recordTypeAndValue(f, builtin, sig, nil)
575 switch p := f.(type) {
576 case *syntax.Name, *syntax.SelectorExpr:
578 case *syntax.ParenExpr:
586 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
587 // (and therefore has tuple type).
588 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand) {
591 if a[0].mode == invalid {
594 t0, t1 := a[0].typ, a[1].typ
595 assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
596 if m := check.Types; m != nil {
599 assert(tv.Type != nil) // should have been recorded already
602 NewVar(pos, check.pkg, "", t0),
603 NewVar(pos, check.pkg, "", t1),
606 // if x is a parenthesized expression (p.X), update p.X
607 p, _ := x.(*syntax.ParenExpr)
614 if check.StoreTypesInSyntax {
615 // Note: this loop is duplicated because the type of tv is different.
616 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
618 tv := x.GetTypeInfo()
619 assert(tv.Type != nil) // should have been recorded already
622 NewVar(pos, check.pkg, "", t0),
623 NewVar(pos, check.pkg, "", t1),
626 p, _ := x.(*syntax.ParenExpr)
635 // recordInstance records instantiation information into check.Info, if the
636 // Instances map is non-nil. The given expr must be an ident, selector, or
637 // index (list) expr with ident or selector operand.
639 // TODO(rfindley): the expr parameter is fragile. See if we can access the
640 // instantiated identifier in some other way.
641 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
642 ident := instantiatedIdent(expr)
645 if m := check.Instances; m != nil {
646 m[ident] = Instance{newTypeList(targs), typ}
650 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
651 var selOrIdent syntax.Expr
652 switch e := expr.(type) {
653 case *syntax.IndexExpr:
655 case *syntax.SelectorExpr, *syntax.Name:
658 switch x := selOrIdent.(type) {
661 case *syntax.SelectorExpr:
664 panic("instantiated ident not found")
667 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
669 if m := check.Defs; m != nil {
674 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
677 if m := check.Uses; m != nil {
682 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
685 if m := check.Implicits; m != nil {
690 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
691 assert(obj != nil && (recv == nil || len(index) > 0))
692 check.recordUse(x.Sel, obj)
693 if m := check.Selections; m != nil {
694 m[x] = &Selection{kind, recv, obj, index, indirect}
698 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
701 if m := check.Scopes; m != nil {