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"
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 syntax.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 syntax.Pos // if valid, 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[*syntax.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 poser, format string, args ...interface{}) {
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
97 version version // accepted language version
98 nextID uint64 // unique Id for type parameters (first valid Id is 1)
99 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
100 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
101 infoMap map[*Named]typeInfo // maps named types to their associated type info (for cycle detection)
103 // pkgPathMap maps package names to the set of distinct import paths we've
104 // seen for that name, anywhere in the import graph. It is used for
105 // disambiguating package names in error messages.
107 // pkgPathMap is allocated lazily, so that we don't pay the price of building
108 // it on the happy path. seenPkgMap tracks the packages that we've already
110 pkgPathMap map[string]map[string]bool
111 seenPkgMap map[*Package]bool
113 // information collected during type-checking of a set of package files
114 // (initialized by Files, valid only for the duration of check.Files;
115 // maps and lists are allocated on demand)
116 files []*syntax.File // list of package files
117 imports []*PkgName // list of imported packages
118 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
119 recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
120 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
121 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
122 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
124 firstErr error // first error encountered
125 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
126 untyped map[syntax.Expr]exprInfo // map of expressions without final type
127 delayed []action // stack of delayed action segments; segments are processed in FIFO order
128 objPath []Object // path of object dependencies during type inference (for cycle reporting)
129 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
131 // environment within which the current object is type-checked (valid only
132 // for the duration of type-checking a specific object)
136 indent int // indentation for tracing
139 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
140 func (check *Checker) addDeclDep(to Object) {
143 return // not in a package-level init expression
145 if _, found := check.objMap[to]; !found {
146 return // to is not a package-level object
151 // brokenAlias records that alias doesn't have a determined type yet.
152 // It also sets alias.typ to Typ[Invalid].
153 func (check *Checker) brokenAlias(alias *TypeName) {
154 if check.brokenAliases == nil {
155 check.brokenAliases = make(map[*TypeName]bool)
157 check.brokenAliases[alias] = true
158 alias.typ = Typ[Invalid]
161 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
162 func (check *Checker) validAlias(alias *TypeName, typ Type) {
163 delete(check.brokenAliases, alias)
167 // isBrokenAlias reports whether alias doesn't have a determined type yet.
168 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
169 return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
172 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
175 m = make(map[syntax.Expr]exprInfo)
178 m[e] = exprInfo{lhs, mode, typ, val}
181 // later pushes f on to the stack of actions that will be processed later;
182 // either at the end of the current statement, or in case of a local constant
183 // or variable declaration, before the constant or variable is in scope
184 // (so that f still sees the scope before any new declarations).
185 // later returns the pushed action so one can provide a description
186 // via action.describef for debugging, if desired.
187 func (check *Checker) later(f func()) *action {
188 i := len(check.delayed)
189 check.delayed = append(check.delayed, action{f: f})
190 return &check.delayed[i]
193 // push pushes obj onto the object path and returns its index in the path.
194 func (check *Checker) push(obj Object) int {
195 check.objPath = append(check.objPath, obj)
196 return len(check.objPath) - 1
199 // pop pops and returns the topmost object from the object path.
200 func (check *Checker) pop() Object {
201 i := len(check.objPath) - 1
202 obj := check.objPath[i]
203 check.objPath[i] = nil
204 check.objPath = check.objPath[:i]
208 type cleaner interface {
212 // needsCleanup records objects/types that implement the cleanup method
213 // which will be called at the end of type-checking.
214 func (check *Checker) needsCleanup(c cleaner) {
215 check.cleaners = append(check.cleaners, c)
218 // NewChecker returns a new Checker instance for a given package.
219 // Package files may be added incrementally via checker.Files.
220 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
221 // make sure we have a configuration
226 // make sure we have an info struct
231 version, err := parseGoVersion(conf.GoVersion)
233 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
242 objMap: make(map[Object]*declInfo),
243 impMap: make(map[importKey]*Package),
244 infoMap: make(map[*Named]typeInfo),
248 // initFiles initializes the files-specific portion of checker.
249 // The provided files must all belong to the same package.
250 func (check *Checker) initFiles(files []*syntax.File) {
251 // start with a clean slate (check.Files may be called multiple times)
254 check.dotImportMap = nil
263 // determine package name and collect valid files
265 for _, file := range files {
266 switch name := file.PkgName.Value; pkg.name {
271 check.error(file.PkgName, "invalid package name _")
276 check.files = append(check.files, file)
279 check.errorf(file, "package %s; expected %s", name, pkg.name)
285 // A bailout panic is used for early termination.
286 type bailout struct{}
288 func (check *Checker) handleBailout(err *error) {
289 switch p := recover().(type) {
291 // normal return or early exit
292 *err = check.firstErr
299 // Files checks the provided files as part of the checker's package.
300 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
302 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
304 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
305 if check.conf.FakeImportC && check.conf.go115UsesCgo {
309 defer check.handleBailout(&err)
311 print := func(msg string) {
312 if check.conf.Trace {
318 print("== initFiles ==")
319 check.initFiles(files)
321 print("== collectObjects ==")
322 check.collectObjects()
324 print("== packageObjects ==")
325 check.packageObjects()
327 print("== processDelayed ==")
328 check.processDelayed(0) // incl. all functions
330 print("== cleanup ==")
333 print("== initOrder ==")
336 if !check.conf.DisableUnusedImportCheck {
337 print("== unusedImports ==")
338 check.unusedImports()
341 print("== recordUntyped ==")
342 check.recordUntyped()
344 if check.firstErr == nil {
345 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
349 check.pkg.complete = true
351 // no longer needed - release memory
353 check.dotImportMap = nil
354 check.pkgPathMap = nil
355 check.seenPkgMap = nil
356 check.recvTParamMap = nil
357 check.brokenAliases = nil
358 check.unionTypeSets = nil
361 // TODO(gri) There's more memory we should release at this point.
366 // processDelayed processes all delayed actions pushed after top.
367 func (check *Checker) processDelayed(top int) {
368 // If each delayed action pushes a new action, the
369 // stack will continue to grow during this loop.
370 // However, it is only processing functions (which
371 // are processed in a delayed fashion) that may
372 // add more actions (such as nested functions), so
373 // this is a sufficiently bounded process.
374 for i := top; i < len(check.delayed); i++ {
375 a := &check.delayed[i]
376 if check.conf.Trace && a.desc != nil {
378 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
380 a.f() // may append to check.delayed
382 assert(top <= len(check.delayed)) // stack must not have shrunk
383 check.delayed = check.delayed[:top]
386 // cleanup runs cleanup for all collected cleaners.
387 func (check *Checker) cleanup() {
388 // Don't use a range clause since Named.cleanup may add more cleaners.
389 for i := 0; i < len(check.cleaners); i++ {
390 check.cleaners[i].cleanup()
395 func (check *Checker) record(x *operand) {
396 // convert x into a user-friendly set of values
397 // TODO(gri) this code can be simplified
399 var val constant.Value
411 assert(x.expr != nil && typ != nil)
414 // delay type and value recording until we know the type
415 // or until the end of type checking
416 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
418 check.recordTypeAndValue(x.expr, x.mode, typ, val)
422 func (check *Checker) recordUntyped() {
423 if !debug && check.Types == nil {
424 return // nothing to do
427 for x, info := range check.untyped {
428 if debug && isTyped(info.typ) {
429 check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
432 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
436 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
442 if mode == constant_ {
444 // We check allBasic(typ, IsConstType) here as constant expressions may be
445 // recorded as type parameters.
446 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
448 if m := check.Types; m != nil {
449 m[x] = TypeAndValue{mode, typ, val}
453 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
454 // f must be a (possibly parenthesized, possibly qualified)
455 // identifier denoting a built-in (including unsafe's non-constant
456 // functions Add and Slice): record the signature for f and possible
459 check.recordTypeAndValue(f, builtin, sig, nil)
460 switch p := f.(type) {
461 case *syntax.Name, *syntax.SelectorExpr:
463 case *syntax.ParenExpr:
471 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
473 if a[0] == nil || a[1] == nil {
476 assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
477 if m := check.Types; m != nil {
480 assert(tv.Type != nil) // should have been recorded already
483 NewVar(pos, check.pkg, "", a[0]),
484 NewVar(pos, check.pkg, "", a[1]),
487 // if x is a parenthesized expression (p.X), update p.X
488 p, _ := x.(*syntax.ParenExpr)
497 // recordInstance records instantiation information into check.Info, if the
498 // Instances map is non-nil. The given expr must be an ident, selector, or
499 // index (list) expr with ident or selector operand.
501 // TODO(rfindley): the expr parameter is fragile. See if we can access the
502 // instantiated identifier in some other way.
503 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
504 ident := instantiatedIdent(expr)
507 if m := check.Instances; m != nil {
508 m[ident] = Instance{newTypeList(targs), typ}
512 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
513 var selOrIdent syntax.Expr
514 switch e := expr.(type) {
515 case *syntax.IndexExpr:
517 case *syntax.SelectorExpr, *syntax.Name:
520 switch x := selOrIdent.(type) {
523 case *syntax.SelectorExpr:
526 panic("instantiated ident not found")
529 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
531 if m := check.Defs; m != nil {
536 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
539 if m := check.Uses; m != nil {
544 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
547 if m := check.Implicits; m != nil {
552 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
553 assert(obj != nil && (recv == nil || len(index) > 0))
554 check.recordUse(x.Sel, obj)
555 if m := check.Selections; m != nil {
556 m[x] = &Selection{kind, recv, obj, index, indirect}
560 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
563 if m := check.Scopes; m != nil {