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 imports []*PkgName // list of imported packages
120 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
121 recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
122 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
123 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
124 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
126 firstErr error // first error encountered
127 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
128 untyped map[syntax.Expr]exprInfo // map of expressions without final type
129 delayed []action // stack of delayed action segments; segments are processed in FIFO order
130 objPath []Object // path of object dependencies during type inference (for cycle reporting)
131 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
133 // environment within which the current object is type-checked (valid only
134 // for the duration of type-checking a specific object)
138 indent int // indentation for tracing
141 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
142 func (check *Checker) addDeclDep(to Object) {
145 return // not in a package-level init expression
147 if _, found := check.objMap[to]; !found {
148 return // to is not a package-level object
153 // brokenAlias records that alias doesn't have a determined type yet.
154 // It also sets alias.typ to Typ[Invalid].
155 func (check *Checker) brokenAlias(alias *TypeName) {
156 if check.brokenAliases == nil {
157 check.brokenAliases = make(map[*TypeName]bool)
159 check.brokenAliases[alias] = true
160 alias.typ = Typ[Invalid]
163 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
164 func (check *Checker) validAlias(alias *TypeName, typ Type) {
165 delete(check.brokenAliases, alias)
169 // isBrokenAlias reports whether alias doesn't have a determined type yet.
170 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
171 return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
174 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
177 m = make(map[syntax.Expr]exprInfo)
180 m[e] = exprInfo{lhs, mode, typ, val}
183 // later pushes f on to the stack of actions that will be processed later;
184 // either at the end of the current statement, or in case of a local constant
185 // or variable declaration, before the constant or variable is in scope
186 // (so that f still sees the scope before any new declarations).
187 // later returns the pushed action so one can provide a description
188 // via action.describef for debugging, if desired.
189 func (check *Checker) later(f func()) *action {
190 i := len(check.delayed)
191 check.delayed = append(check.delayed, action{f: f})
192 return &check.delayed[i]
195 // push pushes obj onto the object path and returns its index in the path.
196 func (check *Checker) push(obj Object) int {
197 check.objPath = append(check.objPath, obj)
198 return len(check.objPath) - 1
201 // pop pops and returns the topmost object from the object path.
202 func (check *Checker) pop() Object {
203 i := len(check.objPath) - 1
204 obj := check.objPath[i]
205 check.objPath[i] = nil
206 check.objPath = check.objPath[:i]
210 type cleaner interface {
214 // needsCleanup records objects/types that implement the cleanup method
215 // which will be called at the end of type-checking.
216 func (check *Checker) needsCleanup(c cleaner) {
217 check.cleaners = append(check.cleaners, c)
220 // NewChecker returns a new Checker instance for a given package.
221 // Package files may be added incrementally via checker.Files.
222 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
223 // make sure we have a configuration
228 // make sure we have an info struct
233 version, err := parseGoVersion(conf.GoVersion)
235 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 []*syntax.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.PkgName.Value; pkg.name {
272 check.error(file.PkgName, BlankPkgName, "invalid package name _")
277 check.files = append(check.files, file)
280 check.errorf(file, 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 []*syntax.File) error { return check.checkFiles(files) }
303 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
305 func (check *Checker) checkFiles(files []*syntax.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(gri) 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(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.recordTypes() {
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", posFor(x), x, info.typ)
439 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
443 func (check *Checker) recordTypeAndValue(x syntax.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}
458 if check.StoreTypesInSyntax {
459 tv := TypeAndValue{mode, typ, val}
460 stv := syntax.TypeAndValue{Type: typ, Value: val}
476 if tv.Addressable() {
489 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
490 // f must be a (possibly parenthesized, possibly qualified)
491 // identifier denoting a built-in (including unsafe's non-constant
492 // functions Add and Slice): record the signature for f and possible
495 check.recordTypeAndValue(f, builtin, sig, nil)
496 switch p := f.(type) {
497 case *syntax.Name, *syntax.SelectorExpr:
499 case *syntax.ParenExpr:
507 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
509 if a[0] == nil || a[1] == nil {
512 assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
513 if m := check.Types; m != nil {
516 assert(tv.Type != nil) // should have been recorded already
519 NewVar(pos, check.pkg, "", a[0]),
520 NewVar(pos, check.pkg, "", a[1]),
523 p, _ := x.(*syntax.ParenExpr)
530 if check.StoreTypesInSyntax {
531 // Note: this loop is duplicated because the type of tv is different.
532 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
534 tv := x.GetTypeInfo()
535 assert(tv.Type != nil) // should have been recorded already
538 NewVar(pos, check.pkg, "", a[0]),
539 NewVar(pos, check.pkg, "", a[1]),
542 p, _ := x.(*syntax.ParenExpr)
551 // recordInstance records instantiation information into check.Info, if the
552 // Instances map is non-nil. The given expr must be an ident, selector, or
553 // index (list) expr with ident or selector operand.
555 // TODO(rfindley): the expr parameter is fragile. See if we can access the
556 // instantiated identifier in some other way.
557 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
558 ident := instantiatedIdent(expr)
561 if m := check.Instances; m != nil {
562 m[ident] = Instance{newTypeList(targs), typ}
566 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
567 var selOrIdent syntax.Expr
568 switch e := expr.(type) {
569 case *syntax.IndexExpr:
571 case *syntax.SelectorExpr, *syntax.Name:
574 switch x := selOrIdent.(type) {
577 case *syntax.SelectorExpr:
580 panic("instantiated ident not found")
583 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
585 if m := check.Defs; m != nil {
590 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
593 if m := check.Uses; m != nil {
598 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
601 if m := check.Implicits; m != nil {
606 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
607 assert(obj != nil && (recv == nil || len(index) > 0))
608 check.recordUse(x.Sel, obj)
609 if m := check.Selections; m != nil {
610 m[x] = &Selection{kind, recv, obj, index, indirect}
614 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
617 if m := check.Scopes; m != nil {