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.
17 // debugging/development support
19 debug = false // leave on during development
20 trace = false // turn on for detailed type resolution traces
23 // If forceStrict is set, the type-checker enforces additional
24 // rules not specified by the Go 1 spec, but which will
25 // catch guaranteed run-time errors if the respective
26 // code is executed. In other words, programs passing in
27 // strict mode are Go 1 compliant, but not all Go 1 programs
28 // will pass in strict mode. The additional rules are:
30 // - A type assertion x.(T) where T is an interface type
31 // is invalid if any (statically known) method that exists
32 // for both x and T have different signatures.
34 const forceStrict = false
36 // exprInfo stores information about an untyped expression.
37 type exprInfo struct {
38 isLhs bool // expression is lhs operand of a shift with delayed type-check
41 val constant.Value // constant value; or nil (if not a constant)
44 // A context represents the context within which an object is type-checked.
46 decl *declInfo // package-level declaration whose init expression/function body is checked
47 scope *Scope // top-most scope for lookups
48 pos token.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
49 iota constant.Value // value of iota in a constant declaration; nil otherwise
50 errpos positioner // if set, identifier position of a constant with inherited initializer
51 inTParamList bool // set if inside a type parameter list
52 sig *Signature // function signature if inside a function; nil otherwise
53 isPanic map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
54 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
55 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
58 // lookup looks up name in the current context and returns the matching object, or nil.
59 func (ctxt *context) lookup(name string) Object {
60 _, obj := ctxt.scope.LookupParent(name, ctxt.pos)
64 // An importKey identifies an imported package by import path and source directory
65 // (directory containing the file containing the import). In practice, the directory
66 // may always be the same, or may not matter. Given an (import path, directory), an
67 // importer must always return the same package (but given two different import paths,
68 // an importer may still return the same package by mapping them to the same package
70 type importKey struct {
74 // A dotImportKey describes a dot-imported object in the given scope.
75 type dotImportKey struct {
80 // An action describes a (delayed) action.
82 f func() // action to be executed
83 desc *actionDesc // action description; may be nil, requires debug to be set
86 // If debug is set, describef sets a printf-formatted description for action a.
87 // Otherwise, it is a no-op.
88 func (a *action) describef(pos positioner, format string, args ...interface{}) {
90 a.desc = &actionDesc{pos, format, args}
94 // An actionDesc provides information on an action.
95 // For debugging only.
96 type actionDesc struct {
102 // A Checker maintains the state of the type checker.
103 // It must be created with NewChecker.
104 type Checker struct {
105 // package information
106 // (initialized by NewChecker, valid for the life-time of checker)
108 ctxt *Context // context for de-duplicating instances
112 version version // accepted language version
113 nextID uint64 // unique Id for type parameters (first valid Id is 1)
114 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
115 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
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 []*ast.File // 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[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
134 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
136 firstErr error // first error encountered
137 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
138 untyped map[ast.Expr]exprInfo // map of expressions without final type
139 delayed []action // stack of delayed action segments; segments are processed in FIFO order
140 objPath []Object // path of object dependencies during type inference (for cycle reporting)
141 defTypes []*Named // defined types created during type checking, for final validation.
143 // context within which the current object is type-checked
144 // (valid only for the duration of type-checking a specific object)
148 indent int // indentation for tracing
151 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
152 func (check *Checker) addDeclDep(to Object) {
155 return // not in a package-level init expression
157 if _, found := check.objMap[to]; !found {
158 return // to is not a package-level object
163 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
166 m = make(map[ast.Expr]exprInfo)
169 m[e] = exprInfo{lhs, mode, typ, val}
172 // later pushes f on to the stack of actions that will be processed later;
173 // either at the end of the current statement, or in case of a local constant
174 // or variable declaration, before the constant or variable is in scope
175 // (so that f still sees the scope before any new declarations).
176 // later returns the pushed action so one can provide a description
177 // via action.describef for debugging, if desired.
178 func (check *Checker) later(f func()) *action {
179 i := len(check.delayed)
180 check.delayed = append(check.delayed, action{f: f})
181 return &check.delayed[i]
184 // push pushes obj onto the object path and returns its index in the path.
185 func (check *Checker) push(obj Object) int {
186 check.objPath = append(check.objPath, obj)
187 return len(check.objPath) - 1
190 // pop pops and returns the topmost object from the object path.
191 func (check *Checker) pop() Object {
192 i := len(check.objPath) - 1
193 obj := check.objPath[i]
194 check.objPath[i] = nil
195 check.objPath = check.objPath[:i]
199 // NewChecker returns a new Checker instance for a given package.
200 // Package files may be added incrementally via checker.Files.
201 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
202 // make sure we have a configuration
207 // make sure we have an info struct
212 version, err := parseGoVersion(conf.GoVersion)
214 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
224 objMap: make(map[Object]*declInfo),
225 impMap: make(map[importKey]*Package),
229 // initFiles initializes the files-specific portion of checker.
230 // The provided files must all belong to the same package.
231 func (check *Checker) initFiles(files []*ast.File) {
232 // start with a clean slate (check.Files may be called multiple times)
235 check.dotImportMap = nil
242 // determine package name and collect valid files
244 for _, file := range files {
245 switch name := file.Name.Name; pkg.name {
250 check.errorf(file.Name, _BlankPkgName, "invalid package name _")
255 check.files = append(check.files, file)
258 check.errorf(atPos(file.Package), _MismatchedPkgName, "package %s; expected %s", name, pkg.name)
264 // A bailout panic is used for early termination.
265 type bailout struct{}
267 func (check *Checker) handleBailout(err *error) {
268 switch p := recover().(type) {
270 // normal return or early exit
271 *err = check.firstErr
278 // Files checks the provided files as part of the checker's package.
279 func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
281 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
283 func (check *Checker) checkFiles(files []*ast.File) (err error) {
284 if check.conf.FakeImportC && check.conf.go115UsesCgo {
288 defer check.handleBailout(&err)
290 check.initFiles(files)
292 check.collectObjects()
294 check.packageObjects()
296 check.processDelayed(0) // incl. all functions
298 check.expandDefTypes()
302 if !check.conf.DisableUnusedImportCheck {
303 check.unusedImports()
306 check.recordUntyped()
308 if check.firstErr == nil {
309 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
313 check.pkg.complete = true
315 // no longer needed - release memory
317 check.dotImportMap = nil
318 check.pkgPathMap = nil
319 check.seenPkgMap = nil
320 check.recvTParamMap = nil
324 // TODO(rFindley) There's more memory we should release at this point.
329 // processDelayed processes all delayed actions pushed after top.
330 func (check *Checker) processDelayed(top int) {
331 // If each delayed action pushes a new action, the
332 // stack will continue to grow during this loop.
333 // However, it is only processing functions (which
334 // are processed in a delayed fashion) that may
335 // add more actions (such as nested functions), so
336 // this is a sufficiently bounded process.
337 for i := top; i < len(check.delayed); i++ {
338 a := &check.delayed[i]
339 if trace && a.desc != nil {
341 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
343 a.f() // may append to check.delayed
345 assert(top <= len(check.delayed)) // stack must not have shrunk
346 check.delayed = check.delayed[:top]
349 func (check *Checker) expandDefTypes() {
350 // Ensure that every defined type created in the course of type-checking has
351 // either non-*Named underlying, or is unresolved.
353 // This guarantees that we don't leak any types whose underlying is *Named,
354 // because any unresolved instances will lazily compute their underlying by
355 // substituting in the underlying of their origin. The origin must have
356 // either been imported or type-checked and expanded here, and in either case
357 // its underlying will be fully expanded.
358 for i := 0; i < len(check.defTypes); i++ {
359 n := check.defTypes[i]
360 switch n.underlying.(type) {
362 if n.resolver == nil {
363 panic("nil underlying")
366 n.under() // n.under may add entries to check.defTypes
372 func (check *Checker) record(x *operand) {
373 // convert x into a user-friendly set of values
374 // TODO(gri) this code can be simplified
376 var val constant.Value
388 assert(x.expr != nil && typ != nil)
391 // delay type and value recording until we know the type
392 // or until the end of type checking
393 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
395 check.recordTypeAndValue(x.expr, x.mode, typ, val)
399 func (check *Checker) recordUntyped() {
400 if !debug && check.Types == nil {
401 return // nothing to do
404 for x, info := range check.untyped {
405 if debug && isTyped(info.typ) {
406 check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
409 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
413 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
419 if mode == constant_ {
421 // We check allBasic(typ, IsConstType) here as constant expressions may be
422 // recorded as type parameters.
423 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
425 if m := check.Types; m != nil {
426 m[x] = TypeAndValue{mode, typ, val}
430 func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
431 // f must be a (possibly parenthesized, possibly qualified)
432 // identifier denoting a built-in (including unsafe's non-constant
433 // functions Add and Slice): record the signature for f and possible
436 check.recordTypeAndValue(f, builtin, sig, nil)
437 switch p := f.(type) {
438 case *ast.Ident, *ast.SelectorExpr:
448 func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
450 if a[0] == nil || a[1] == nil {
453 assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
454 if m := check.Types; m != nil {
457 assert(tv.Type != nil) // should have been recorded already
460 NewVar(pos, check.pkg, "", a[0]),
461 NewVar(pos, check.pkg, "", a[1]),
464 // if x is a parenthesized expression (p.X), update p.X
465 p, _ := x.(*ast.ParenExpr)
474 // recordInstance records instantiation information into check.Info, if the
475 // Instances map is non-nil. The given expr must be an ident, selector, or
476 // index (list) expr with ident or selector operand.
478 // TODO(rfindley): the expr parameter is fragile. See if we can access the
479 // instantiated identifier in some other way.
480 func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
481 ident := instantiatedIdent(expr)
484 if m := check.Instances; m != nil {
485 m[ident] = Instance{NewTypeList(targs), typ}
489 func instantiatedIdent(expr ast.Expr) *ast.Ident {
490 var selOrIdent ast.Expr
491 switch e := expr.(type) {
494 case *ast.IndexListExpr:
496 case *ast.SelectorExpr, *ast.Ident:
499 switch x := selOrIdent.(type) {
502 case *ast.SelectorExpr:
505 panic("instantiated ident not found")
508 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
510 if m := check.Defs; m != nil {
515 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
518 if m := check.Uses; m != nil {
523 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
526 if m := check.Implicits; m != nil {
531 func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
532 assert(obj != nil && (recv == nil || len(index) > 0))
533 check.recordUse(x.Sel, obj)
534 if m := check.Selections; m != nil {
535 m[x] = &Selection{kind, recv, obj, index, indirect}
539 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
542 if m := check.Scopes; m != nil {