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 // If forceStrict is set, the type-checker enforces additional
22 // rules not specified by the Go 1 spec, but which will
23 // catch guaranteed run-time errors if the respective
24 // code is executed. In other words, programs passing in
25 // strict mode are Go 1 compliant, but not all Go 1 programs
26 // will pass in strict mode. The additional rules are:
28 // - A type assertion x.(T) where T is an interface type
29 // is invalid if any (statically known) method that exists
30 // for both x and T have different signatures.
32 const forceStrict = false
34 // If methodTypeParamsOk is set, type parameters are
35 // permitted in method declarations (in interfaces, too).
36 // Generalization and experimental feature.
37 const methodTypeParamsOk = true
39 // exprInfo stores information about an untyped expression.
40 type exprInfo struct {
41 isLhs bool // expression is lhs operand of a shift with delayed type-check
44 val constant.Value // constant value; or nil (if not a constant)
47 // A context represents the context within which an object is type-checked.
49 decl *declInfo // package-level declaration whose init expression/function body is checked
50 scope *Scope // top-most scope for lookups
51 pos syntax.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
52 iota constant.Value // value of iota in a constant declaration; nil otherwise
53 errpos syntax.Pos // if valid, identifier position of a constant with inherited initializer
54 sig *Signature // function signature if inside a function; nil otherwise
55 isPanic map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
56 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
57 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
60 // lookup looks up name in the current context and returns the matching object, or nil.
61 func (ctxt *context) lookup(name string) Object {
62 _, obj := ctxt.scope.LookupParent(name, ctxt.pos)
66 // An importKey identifies an imported package by import path and source directory
67 // (directory containing the file containing the import). In practice, the directory
68 // may always be the same, or may not matter. Given an (import path, directory), an
69 // importer must always return the same package (but given two different import paths,
70 // an importer may still return the same package by mapping them to the same package
72 type importKey struct {
76 // A dotImportKey describes a dot-imported object in the given scope.
77 type dotImportKey struct {
82 // A Checker maintains the state of the type checker.
83 // It must be created with NewChecker.
85 // package information
86 // (initialized by NewChecker, valid for the life-time of checker)
90 version version // accepted language version
91 nextId uint64 // unique Id for type parameters (first valid Id is 1)
92 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
93 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
94 posMap map[*Interface][]syntax.Pos // maps interface types to lists of embedded interface positions
95 typMap map[string]*Named // maps an instantiated named type hash to a *Named type
96 pkgCnt map[string]int // counts number of imported packages with a given name (for better error messages)
98 // information collected during type-checking of a set of package files
99 // (initialized by Files, valid only for the duration of check.Files;
100 // maps and lists are allocated on demand)
101 files []*syntax.File // list of package files
102 imports []*PkgName // list of imported packages
103 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
105 firstErr error // first error encountered
106 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
107 untyped map[syntax.Expr]exprInfo // map of expressions without final type
108 delayed []func() // stack of delayed action segments; segments are processed in FIFO order
109 objPath []Object // path of object dependencies during type inference (for cycle reporting)
111 // context within which the current object is type-checked
112 // (valid only for the duration of type-checking a specific object)
116 indent int // indentation for tracing
119 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
120 func (check *Checker) addDeclDep(to Object) {
123 return // not in a package-level init expression
125 if _, found := check.objMap[to]; !found {
126 return // to is not a package-level object
131 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
134 m = make(map[syntax.Expr]exprInfo)
137 m[e] = exprInfo{lhs, mode, typ, val}
140 // later pushes f on to the stack of actions that will be processed later;
141 // either at the end of the current statement, or in case of a local constant
142 // or variable declaration, before the constant or variable is in scope
143 // (so that f still sees the scope before any new declarations).
144 func (check *Checker) later(f func()) {
145 check.delayed = append(check.delayed, f)
148 // push pushes obj onto the object path and returns its index in the path.
149 func (check *Checker) push(obj Object) int {
150 check.objPath = append(check.objPath, obj)
151 return len(check.objPath) - 1
154 // pop pops and returns the topmost object from the object path.
155 func (check *Checker) pop() Object {
156 i := len(check.objPath) - 1
157 obj := check.objPath[i]
158 check.objPath[i] = nil
159 check.objPath = check.objPath[:i]
163 // NewChecker returns a new Checker instance for a given package.
164 // Package files may be added incrementally via checker.Files.
165 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
166 // make sure we have a configuration
171 // make sure we have an info struct
176 version, err := parseGoVersion(conf.GoVersion)
178 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
187 objMap: make(map[Object]*declInfo),
188 impMap: make(map[importKey]*Package),
189 posMap: make(map[*Interface][]syntax.Pos),
190 typMap: make(map[string]*Named),
191 pkgCnt: make(map[string]int),
195 // initFiles initializes the files-specific portion of checker.
196 // The provided files must all belong to the same package.
197 func (check *Checker) initFiles(files []*syntax.File) {
198 // start with a clean slate (check.Files may be called multiple times)
201 check.dotImportMap = nil
208 // determine package name and collect valid files
210 for _, file := range files {
211 switch name := file.PkgName.Value; pkg.name {
216 check.error(file.PkgName, "invalid package name _")
221 check.files = append(check.files, file)
224 check.errorf(file, "package %s; expected %s", name, pkg.name)
230 // A bailout panic is used for early termination.
231 type bailout struct{}
233 func (check *Checker) handleBailout(err *error) {
234 switch p := recover().(type) {
236 // normal return or early exit
237 *err = check.firstErr
244 // Files checks the provided files as part of the checker's package.
245 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
247 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
249 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
250 if check.conf.FakeImportC && check.conf.go115UsesCgo {
254 defer check.handleBailout(&err)
256 print := func(msg string) {
257 if check.conf.Trace {
262 print("== initFiles ==")
263 check.initFiles(files)
265 print("== collectObjects ==")
266 check.collectObjects()
268 print("== packageObjects ==")
269 check.packageObjects()
271 print("== processDelayed ==")
272 check.processDelayed(0) // incl. all functions
274 print("== initOrder ==")
277 if !check.conf.DisableUnusedImportCheck {
278 print("== unusedImports ==")
279 check.unusedImports()
281 // no longer needed - release memory
283 check.dotImportMap = nil
285 print("== recordUntyped ==")
286 check.recordUntyped()
288 if check.Info != nil {
289 print("== sanitizeInfo ==")
290 sanitizeInfo(check.Info)
293 check.pkg.complete = true
295 // TODO(gri) There's more memory we should release at this point.
300 // processDelayed processes all delayed actions pushed after top.
301 func (check *Checker) processDelayed(top int) {
302 // If each delayed action pushes a new action, the
303 // stack will continue to grow during this loop.
304 // However, it is only processing functions (which
305 // are processed in a delayed fashion) that may
306 // add more actions (such as nested functions), so
307 // this is a sufficiently bounded process.
308 for i := top; i < len(check.delayed); i++ {
309 check.delayed[i]() // may append to check.delayed
311 assert(top <= len(check.delayed)) // stack must not have shrunk
312 check.delayed = check.delayed[:top]
315 func (check *Checker) recordUntyped() {
316 if !debug && check.Types == nil {
317 return // nothing to do
320 for x, info := range check.untyped {
321 if debug && isTyped(info.typ) {
322 check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
325 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
329 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
335 if mode == constant_ {
337 // We check is(typ, IsConstType) here as constant expressions may be
338 // recorded as type parameters.
339 assert(typ == Typ[Invalid] || is(typ, IsConstType))
341 if m := check.Types; m != nil {
342 m[x] = TypeAndValue{mode, typ, val}
346 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
347 // f must be a (possibly parenthesized) identifier denoting a built-in
348 // (built-ins in package unsafe always produce a constant result and
349 // we don't record their signatures, so we don't see qualified idents
350 // here): record the signature for f and possible children.
352 check.recordTypeAndValue(f, builtin, sig, nil)
353 switch p := f.(type) {
356 case *syntax.ParenExpr:
364 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
366 if a[0] == nil || a[1] == nil {
369 assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
370 if m := check.Types; m != nil {
373 assert(tv.Type != nil) // should have been recorded already
376 NewVar(pos, check.pkg, "", a[0]),
377 NewVar(pos, check.pkg, "", a[1]),
380 // if x is a parenthesized expression (p.X), update p.X
381 p, _ := x.(*syntax.ParenExpr)
390 func (check *Checker) recordInferred(call syntax.Expr, targs []Type, sig *Signature) {
393 if m := check.Inferred; m != nil {
394 m[call] = Inferred{targs, sig}
398 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
400 if m := check.Defs; m != nil {
405 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
408 if m := check.Uses; m != nil {
413 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
416 if m := check.Implicits; m != nil {
421 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
422 assert(obj != nil && (recv == nil || len(index) > 0))
423 check.recordUse(x.Sel, obj)
424 if m := check.Selections; m != nil {
425 m[x] = &Selection{kind, recv, obj, index, indirect}
429 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
432 if m := check.Scopes; m != nil {