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.
16 // debugging/development support
18 debug = false // leave on during development
19 trace = false // turn on for detailed type resolution traces
22 // If Strict is set, the type-checker enforces additional
23 // rules not specified by the Go 1 spec, but which will
24 // catch guaranteed run-time errors if the respective
25 // code is executed. In other words, programs passing in
26 // Strict mode are Go 1 compliant, but not all Go 1 programs
27 // will pass in Strict mode. The additional rules are:
29 // - A type assertion x.(T) where T is an interface type
30 // is invalid if any (statically known) method that exists
31 // for both x and T have different signatures.
35 // exprInfo stores information about an untyped expression.
36 type exprInfo struct {
37 isLhs bool // expression is lhs operand of a shift with delayed type-check
40 val constant.Value // constant value; or nil (if not a constant)
43 // A context represents the context within which an object is type-checked.
45 decl *declInfo // package-level declaration whose init expression/function body is checked
46 scope *Scope // top-most scope for lookups
47 pos token.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
48 iota constant.Value // value of iota in a constant declaration; nil otherwise
49 errpos positioner // if set, identifier position of a constant with inherited initializer
50 sig *Signature // function signature if inside a function; nil otherwise
51 isPanic map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
52 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
53 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
56 // lookup looks up name in the current context and returns the matching object, or nil.
57 func (ctxt *context) lookup(name string) Object {
58 _, obj := ctxt.scope.LookupParent(name, ctxt.pos)
62 // An importKey identifies an imported package by import path and source directory
63 // (directory containing the file containing the import). In practice, the directory
64 // may always be the same, or may not matter. Given an (import path, directory), an
65 // importer must always return the same package (but given two different import paths,
66 // an importer may still return the same package by mapping them to the same package
68 type importKey struct {
72 // A dotImportKey describes a dot-imported object in the given scope.
73 type dotImportKey struct {
78 // A Checker maintains the state of the type checker.
79 // It must be created with NewChecker.
81 // package information
82 // (initialized by NewChecker, valid for the life-time of checker)
87 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
88 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
89 posMap map[*Interface][]token.Pos // maps interface types to lists of embedded interface positions
90 pkgCnt map[string]int // counts number of imported packages with a given name (for better error messages)
92 // information collected during type-checking of a set of package files
93 // (initialized by Files, valid only for the duration of check.Files;
94 // maps and lists are allocated on demand)
95 files []*ast.File // package files
96 imports []*PkgName // list of imported packages
97 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
99 firstErr error // first error encountered
100 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
101 untyped map[ast.Expr]exprInfo // map of expressions without final type
102 delayed []func() // stack of delayed action segments; segments are processed in FIFO order
103 finals []func() // list of final actions; processed at the end of type-checking the current set of files
104 objPath []Object // path of object dependencies during type inference (for cycle reporting)
106 // context within which the current object is type-checked
107 // (valid only for the duration of type-checking a specific object)
111 indent int // indentation for tracing
114 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
115 func (check *Checker) addDeclDep(to Object) {
118 return // not in a package-level init expression
120 if _, found := check.objMap[to]; !found {
121 return // to is not a package-level object
126 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
129 m = make(map[ast.Expr]exprInfo)
132 m[e] = exprInfo{lhs, mode, typ, val}
135 // later pushes f on to the stack of actions that will be processed later;
136 // either at the end of the current statement, or in case of a local constant
137 // or variable declaration, before the constant or variable is in scope
138 // (so that f still sees the scope before any new declarations).
139 func (check *Checker) later(f func()) {
140 check.delayed = append(check.delayed, f)
143 // atEnd adds f to the list of actions processed at the end
144 // of type-checking, before initialization order computation.
145 // Actions added by atEnd are processed after any actions
147 func (check *Checker) atEnd(f func()) {
148 check.finals = append(check.finals, f)
151 // push pushes obj onto the object path and returns its index in the path.
152 func (check *Checker) push(obj Object) int {
153 check.objPath = append(check.objPath, obj)
154 return len(check.objPath) - 1
157 // pop pops and returns the topmost object from the object path.
158 func (check *Checker) pop() Object {
159 i := len(check.objPath) - 1
160 obj := check.objPath[i]
161 check.objPath[i] = nil
162 check.objPath = check.objPath[:i]
166 // NewChecker returns a new Checker instance for a given package.
167 // Package files may be added incrementally via checker.Files.
168 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
169 // make sure we have a configuration
174 // make sure we have an info struct
184 objMap: make(map[Object]*declInfo),
185 impMap: make(map[importKey]*Package),
186 posMap: make(map[*Interface][]token.Pos),
187 pkgCnt: make(map[string]int),
191 // initFiles initializes the files-specific portion of checker.
192 // The provided files must all belong to the same package.
193 func (check *Checker) initFiles(files []*ast.File) {
194 // start with a clean slate (check.Files may be called multiple times)
197 check.dotImportMap = nil
205 // determine package name and collect valid files
207 for _, file := range files {
208 switch name := file.Name.Name; pkg.name {
213 check.errorf(file.Name, _BlankPkgName, "invalid package name _")
218 check.files = append(check.files, file)
221 check.errorf(atPos(file.Package), _MismatchedPkgName, "package %s; expected %s", name, pkg.name)
227 // A bailout panic is used for early termination.
228 type bailout struct{}
230 func (check *Checker) handleBailout(err *error) {
231 switch p := recover().(type) {
233 // normal return or early exit
234 *err = check.firstErr
241 // Files checks the provided files as part of the checker's package.
242 func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
244 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
246 func (check *Checker) checkFiles(files []*ast.File) (err error) {
247 if check.conf.FakeImportC && check.conf.go115UsesCgo {
251 defer check.handleBailout(&err)
253 check.initFiles(files)
255 check.collectObjects()
257 check.packageObjects()
259 check.processDelayed(0) // incl. all functions
260 check.processFinals()
264 if !check.conf.DisableUnusedImportCheck {
265 check.unusedImports()
267 // no longer needed - release memory
269 check.dotImportMap = nil
271 check.recordUntyped()
273 check.pkg.complete = true
275 // TODO(rFindley) There's more memory we should release at this point.
280 // processDelayed processes all delayed actions pushed after top.
281 func (check *Checker) processDelayed(top int) {
282 // If each delayed action pushes a new action, the
283 // stack will continue to grow during this loop.
284 // However, it is only processing functions (which
285 // are processed in a delayed fashion) that may
286 // add more actions (such as nested functions), so
287 // this is a sufficiently bounded process.
288 for i := top; i < len(check.delayed); i++ {
289 check.delayed[i]() // may append to check.delayed
291 assert(top <= len(check.delayed)) // stack must not have shrunk
292 check.delayed = check.delayed[:top]
295 func (check *Checker) processFinals() {
296 n := len(check.finals)
297 for _, f := range check.finals {
298 f() // must not append to check.finals
300 if len(check.finals) != n {
301 panic("internal error: final action list grew")
305 func (check *Checker) recordUntyped() {
306 if !debug && check.Types == nil {
307 return // nothing to do
310 for x, info := range check.untyped {
311 if debug && isTyped(info.typ) {
312 check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
315 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
319 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
325 if mode == constant_ {
327 assert(typ == Typ[Invalid] || isConstType(typ))
329 if m := check.Types; m != nil {
330 m[x] = TypeAndValue{mode, typ, val}
334 func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
335 // f must be a (possibly parenthesized) identifier denoting a built-in
336 // (built-ins in package unsafe always produce a constant result and
337 // we don't record their signatures, so we don't see qualified idents
338 // here): record the signature for f and possible children.
340 check.recordTypeAndValue(f, builtin, sig, nil)
341 switch p := f.(type) {
352 func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
354 if a[0] == nil || a[1] == nil {
357 assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
358 if m := check.Types; m != nil {
361 assert(tv.Type != nil) // should have been recorded already
364 NewVar(pos, check.pkg, "", a[0]),
365 NewVar(pos, check.pkg, "", a[1]),
368 // if x is a parenthesized expression (p.X), update p.X
369 p, _ := x.(*ast.ParenExpr)
378 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
380 if m := check.Defs; m != nil {
385 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
388 if m := check.Uses; m != nil {
393 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
396 if m := check.Implicits; m != nil {
401 func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
402 assert(obj != nil && (recv == nil || len(index) > 0))
403 check.recordUse(x.Sel, obj)
404 if m := check.Selections; m != nil {
405 m[x] = &Selection{kind, recv, obj, index, indirect}
409 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
412 if m := check.Scopes; m != nil {