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.
15 . "internal/types/errors"
18 // debugging/development support
19 const debug = false // leave on during development
21 // exprInfo stores information about an untyped expression.
22 type exprInfo struct {
23 isLhs bool // expression is lhs operand of a shift with delayed type-check
26 val constant.Value // constant value; or nil (if not a constant)
29 // An environment represents the environment within which an object is
31 type environment struct {
32 decl *declInfo // package-level declaration whose init expression/function body is checked
33 scope *Scope // top-most scope for lookups
34 pos token.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
35 iota constant.Value // value of iota in a constant declaration; nil otherwise
36 errpos positioner // if set, identifier position of a constant with inherited initializer
37 inTParamList bool // set if inside a type parameter list
38 sig *Signature // function signature if inside a function; nil otherwise
39 isPanic map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
40 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
41 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
44 // lookup looks up name in the current environment and returns the matching object, or nil.
45 func (env *environment) lookup(name string) Object {
46 _, obj := env.scope.LookupParent(name, env.pos)
50 // An importKey identifies an imported package by import path and source directory
51 // (directory containing the file containing the import). In practice, the directory
52 // may always be the same, or may not matter. Given an (import path, directory), an
53 // importer must always return the same package (but given two different import paths,
54 // an importer may still return the same package by mapping them to the same package
56 type importKey struct {
60 // A dotImportKey describes a dot-imported object in the given scope.
61 type dotImportKey struct {
66 // An action describes a (delayed) action.
68 f func() // action to be executed
69 desc *actionDesc // action description; may be nil, requires debug to be set
72 // If debug is set, describef sets a printf-formatted description for action a.
73 // Otherwise, it is a no-op.
74 func (a *action) describef(pos positioner, format string, args ...any) {
76 a.desc = &actionDesc{pos, format, args}
80 // An actionDesc provides information on an action.
81 // For debugging only.
82 type actionDesc struct {
88 // A Checker maintains the state of the type checker.
89 // It must be created with NewChecker.
91 // package information
92 // (initialized by NewChecker, valid for the life-time of checker)
94 ctxt *Context // context for de-duplicating instances
98 version version // accepted language version
99 nextID uint64 // unique Id for type parameters (first valid Id is 1)
100 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
101 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
102 valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
104 // pkgPathMap maps package names to the set of distinct import paths we've
105 // seen for that name, anywhere in the import graph. It is used for
106 // disambiguating package names in error messages.
108 // pkgPathMap is allocated lazily, so that we don't pay the price of building
109 // it on the happy path. seenPkgMap tracks the packages that we've already
111 pkgPathMap map[string]map[string]bool
112 seenPkgMap map[*Package]bool
114 // information collected during type-checking of a set of package files
115 // (initialized by Files, valid only for the duration of check.Files;
116 // maps and lists are allocated on demand)
117 files []*ast.File // package files
118 imports []*PkgName // list of imported packages
119 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
120 recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
121 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
122 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
123 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
125 firstErr error // first error encountered
126 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
127 untyped map[ast.Expr]exprInfo // map of expressions without final type
128 delayed []action // stack of delayed action segments; segments are processed in FIFO order
129 objPath []Object // path of object dependencies during type inference (for cycle reporting)
130 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
132 // environment within which the current object is type-checked (valid only
133 // for the duration of type-checking a specific object)
137 indent int // indentation for tracing
140 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
141 func (check *Checker) addDeclDep(to Object) {
144 return // not in a package-level init expression
146 if _, found := check.objMap[to]; !found {
147 return // to is not a package-level object
152 // brokenAlias records that alias doesn't have a determined type yet.
153 // It also sets alias.typ to Typ[Invalid].
154 func (check *Checker) brokenAlias(alias *TypeName) {
155 if check.brokenAliases == nil {
156 check.brokenAliases = make(map[*TypeName]bool)
158 check.brokenAliases[alias] = true
159 alias.typ = Typ[Invalid]
162 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
163 func (check *Checker) validAlias(alias *TypeName, typ Type) {
164 delete(check.brokenAliases, alias)
168 // isBrokenAlias reports whether alias doesn't have a determined type yet.
169 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
170 return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
173 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
176 m = make(map[ast.Expr]exprInfo)
179 m[e] = exprInfo{lhs, mode, typ, val}
182 // later pushes f on to the stack of actions that will be processed later;
183 // either at the end of the current statement, or in case of a local constant
184 // or variable declaration, before the constant or variable is in scope
185 // (so that f still sees the scope before any new declarations).
186 // later returns the pushed action so one can provide a description
187 // via action.describef for debugging, if desired.
188 func (check *Checker) later(f func()) *action {
189 i := len(check.delayed)
190 check.delayed = append(check.delayed, action{f: f})
191 return &check.delayed[i]
194 // push pushes obj onto the object path and returns its index in the path.
195 func (check *Checker) push(obj Object) int {
196 check.objPath = append(check.objPath, obj)
197 return len(check.objPath) - 1
200 // pop pops and returns the topmost object from the object path.
201 func (check *Checker) pop() Object {
202 i := len(check.objPath) - 1
203 obj := check.objPath[i]
204 check.objPath[i] = nil
205 check.objPath = check.objPath[:i]
209 type cleaner interface {
213 // needsCleanup records objects/types that implement the cleanup method
214 // which will be called at the end of type-checking.
215 func (check *Checker) needsCleanup(c cleaner) {
216 check.cleaners = append(check.cleaners, c)
219 // NewChecker returns a new Checker instance for a given package.
220 // Package files may be added incrementally via checker.Files.
221 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
222 // make sure we have a configuration
227 // make sure we have an info struct
232 version, err := parseGoVersion(conf.GoVersion)
234 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
244 objMap: make(map[Object]*declInfo),
245 impMap: make(map[importKey]*Package),
249 // initFiles initializes the files-specific portion of checker.
250 // The provided files must all belong to the same package.
251 func (check *Checker) initFiles(files []*ast.File) {
252 // start with a clean slate (check.Files may be called multiple times)
255 check.dotImportMap = nil
264 // determine package name and collect valid files
266 for _, file := range files {
267 switch name := file.Name.Name; pkg.name {
272 check.error(file.Name, BlankPkgName, "invalid package name _")
277 check.files = append(check.files, file)
280 check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected %s", name, pkg.name)
286 // A bailout panic is used for early termination.
287 type bailout struct{}
289 func (check *Checker) handleBailout(err *error) {
290 switch p := recover().(type) {
292 // normal return or early exit
293 *err = check.firstErr
300 // Files checks the provided files as part of the checker's package.
301 func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
303 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
305 func (check *Checker) checkFiles(files []*ast.File) (err error) {
306 if check.conf.FakeImportC && check.conf.go115UsesCgo {
310 defer check.handleBailout(&err)
312 print := func(msg string) {
313 if check.conf.trace {
319 print("== initFiles ==")
320 check.initFiles(files)
322 print("== collectObjects ==")
323 check.collectObjects()
325 print("== packageObjects ==")
326 check.packageObjects()
328 print("== processDelayed ==")
329 check.processDelayed(0) // incl. all functions
331 print("== cleanup ==")
334 print("== initOrder ==")
337 if !check.conf.DisableUnusedImportCheck {
338 print("== unusedImports ==")
339 check.unusedImports()
342 print("== recordUntyped ==")
343 check.recordUntyped()
345 if check.firstErr == nil {
346 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
350 check.pkg.complete = true
352 // no longer needed - release memory
354 check.dotImportMap = nil
355 check.pkgPathMap = nil
356 check.seenPkgMap = nil
357 check.recvTParamMap = nil
358 check.brokenAliases = nil
359 check.unionTypeSets = nil
362 // TODO(rFindley) There's more memory we should release at this point.
367 // processDelayed processes all delayed actions pushed after top.
368 func (check *Checker) processDelayed(top int) {
369 // If each delayed action pushes a new action, the
370 // stack will continue to grow during this loop.
371 // However, it is only processing functions (which
372 // are processed in a delayed fashion) that may
373 // add more actions (such as nested functions), so
374 // this is a sufficiently bounded process.
375 for i := top; i < len(check.delayed); i++ {
376 a := &check.delayed[i]
377 if check.conf.trace {
379 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
381 check.trace(token.NoPos, "-- delayed %p", a.f)
384 a.f() // may append to check.delayed
385 if check.conf.trace {
389 assert(top <= len(check.delayed)) // stack must not have shrunk
390 check.delayed = check.delayed[:top]
393 // cleanup runs cleanup for all collected cleaners.
394 func (check *Checker) cleanup() {
395 // Don't use a range clause since Named.cleanup may add more cleaners.
396 for i := 0; i < len(check.cleaners); i++ {
397 check.cleaners[i].cleanup()
402 func (check *Checker) record(x *operand) {
403 // convert x into a user-friendly set of values
404 // TODO(gri) this code can be simplified
406 var val constant.Value
418 assert(x.expr != nil && typ != nil)
421 // delay type and value recording until we know the type
422 // or until the end of type checking
423 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
425 check.recordTypeAndValue(x.expr, x.mode, typ, val)
429 func (check *Checker) recordUntyped() {
430 if !debug && check.Types == nil {
431 return // nothing to do
434 for x, info := range check.untyped {
435 if debug && isTyped(info.typ) {
436 check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
439 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
443 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
449 if mode == constant_ {
451 // We check allBasic(typ, IsConstType) here as constant expressions may be
452 // recorded as type parameters.
453 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
455 if m := check.Types; m != nil {
456 m[x] = TypeAndValue{mode, typ, val}
460 func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
461 // f must be a (possibly parenthesized, possibly qualified)
462 // identifier denoting a built-in (including unsafe's non-constant
463 // functions Add and Slice): record the signature for f and possible
466 check.recordTypeAndValue(f, builtin, sig, nil)
467 switch p := f.(type) {
468 case *ast.Ident, *ast.SelectorExpr:
478 func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
480 if a[0] == nil || a[1] == nil {
483 assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
484 if m := check.Types; m != nil {
487 assert(tv.Type != nil) // should have been recorded already
490 NewVar(pos, check.pkg, "", a[0]),
491 NewVar(pos, check.pkg, "", a[1]),
494 // if x is a parenthesized expression (p.X), update p.X
495 p, _ := x.(*ast.ParenExpr)
504 // recordInstance records instantiation information into check.Info, if the
505 // Instances map is non-nil. The given expr must be an ident, selector, or
506 // index (list) expr with ident or selector operand.
508 // TODO(rfindley): the expr parameter is fragile. See if we can access the
509 // instantiated identifier in some other way.
510 func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
511 ident := instantiatedIdent(expr)
514 if m := check.Instances; m != nil {
515 m[ident] = Instance{newTypeList(targs), typ}
519 func instantiatedIdent(expr ast.Expr) *ast.Ident {
520 var selOrIdent ast.Expr
521 switch e := expr.(type) {
524 case *ast.IndexListExpr:
526 case *ast.SelectorExpr, *ast.Ident:
529 switch x := selOrIdent.(type) {
532 case *ast.SelectorExpr:
535 panic("instantiated ident not found")
538 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
540 if m := check.Defs; m != nil {
545 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
548 if m := check.Uses; m != nil {
553 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
556 if m := check.Implicits; m != nil {
561 func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
562 assert(obj != nil && (recv == nil || len(index) > 0))
563 check.recordUse(x.Sel, obj)
564 if m := check.Selections; m != nil {
565 m[x] = &Selection{kind, recv, obj, index, indirect}
569 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
572 if m := check.Scopes; m != nil {