2 // Copyright 2011 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
6 // This file implements the Check function, which drives type-checking.
11 "cmd/compile/internal/syntax"
19 // debugging/development support
20 const debug = true // leave on during development
22 // If forceStrict 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.
33 const forceStrict = false
35 // If methodTypeParamsOk is set, type parameters are
36 // permitted in method declarations (in interfaces, too).
37 // Generalization and experimental feature.
38 const methodTypeParamsOk = true
40 // exprInfo stores information about an untyped expression.
41 type exprInfo struct {
42 isLhs bool // expression is lhs operand of a shift with delayed type-check
45 val constant.Value // constant value; or nil (if not a constant)
48 // A context represents the context within which an object is type-checked.
50 decl *declInfo // package-level declaration whose init expression/function body is checked
51 scope *Scope // top-most scope for lookups
52 pos syntax.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
53 iota constant.Value // value of iota in a constant declaration; nil otherwise
54 errpos syntax.Pos // if valid, identifier position of a constant with inherited initializer
55 sig *Signature // function signature if inside a function; nil otherwise
56 isPanic map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
57 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
58 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
61 // lookup looks up name in the current context and returns the matching object, or nil.
62 func (ctxt *context) lookup(name string) Object {
63 _, obj := ctxt.scope.LookupParent(name, ctxt.pos)
67 // An importKey identifies an imported package by import path and source directory
68 // (directory containing the file containing the import). In practice, the directory
69 // may always be the same, or may not matter. Given an (import path, directory), an
70 // importer must always return the same package (but given two different import paths,
71 // an importer may still return the same package by mapping them to the same package
73 type importKey struct {
77 // A dotImportKey describes a dot-imported object in the given scope.
78 type dotImportKey struct {
83 // A Checker maintains the state of the type checker.
84 // It must be created with NewChecker.
86 // package information
87 // (initialized by NewChecker, valid for the life-time of checker)
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 finals []func() // list of final actions; processed at the end of type-checking the current set of files
110 objPath []Object // path of object dependencies during type inference (for cycle reporting)
112 // context within which the current object is type-checked
113 // (valid only for the duration of type-checking a specific object)
117 indent int // indentation for tracing
120 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
121 func (check *Checker) addDeclDep(to Object) {
124 return // not in a package-level init expression
126 if _, found := check.objMap[to]; !found {
127 return // to is not a package-level object
132 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
135 m = make(map[syntax.Expr]exprInfo)
138 m[e] = exprInfo{lhs, mode, typ, val}
141 // later pushes f on to the stack of actions that will be processed later;
142 // either at the end of the current statement, or in case of a local constant
143 // or variable declaration, before the constant or variable is in scope
144 // (so that f still sees the scope before any new declarations).
145 func (check *Checker) later(f func()) {
146 check.delayed = append(check.delayed, f)
149 // atEnd adds f to the list of actions processed at the end
150 // of type-checking, before initialization order computation.
151 // Actions added by atEnd are processed after any actions
153 func (check *Checker) atEnd(f func()) {
154 check.finals = append(check.finals, f)
157 // push pushes obj onto the object path and returns its index in the path.
158 func (check *Checker) push(obj Object) int {
159 check.objPath = append(check.objPath, obj)
160 return len(check.objPath) - 1
163 // pop pops and returns the topmost object from the object path.
164 func (check *Checker) pop() Object {
165 i := len(check.objPath) - 1
166 obj := check.objPath[i]
167 check.objPath[i] = nil
168 check.objPath = check.objPath[:i]
172 // NewChecker returns a new Checker instance for a given package.
173 // Package files may be added incrementally via checker.Files.
174 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
175 // make sure we have a configuration
180 // make sure we have an info struct
190 objMap: make(map[Object]*declInfo),
191 impMap: make(map[importKey]*Package),
192 posMap: make(map[*Interface][]syntax.Pos),
193 typMap: make(map[string]*Named),
194 pkgCnt: make(map[string]int),
198 // initFiles initializes the files-specific portion of checker.
199 // The provided files must all belong to the same package.
200 func (check *Checker) initFiles(files []*syntax.File) {
201 // start with a clean slate (check.Files may be called multiple times)
204 check.dotImportMap = nil
212 // determine package name and collect valid files
214 for _, file := range files {
215 switch name := file.PkgName.Value; pkg.name {
220 check.errorf(file.PkgName, "invalid package name _")
225 check.files = append(check.files, file)
228 check.errorf(file, "package %s; expected %s", name, pkg.name)
234 // A bailout panic is used for early termination.
235 type bailout struct{}
237 func (check *Checker) handleBailout(err *error) {
238 switch p := recover().(type) {
240 // normal return or early exit
241 *err = check.firstErr
248 // Files checks the provided files as part of the checker's package.
249 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
251 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
253 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
254 if check.conf.FakeImportC && check.conf.go115UsesCgo {
258 defer check.handleBailout(&err)
260 print := func(msg string) {
261 if check.conf.Trace {
266 print("== initFiles ==")
267 check.initFiles(files)
269 print("== collectObjects ==")
270 check.collectObjects()
272 print("== packageObjects ==")
273 check.packageObjects()
275 print("== processDelayed ==")
276 check.processDelayed(0) // incl. all functions
277 check.processFinals()
279 print("== initOrder ==")
282 if !check.conf.DisableUnusedImportCheck {
283 print("== unusedImports ==")
284 check.unusedImports()
286 // no longer needed - release memory
288 check.dotImportMap = nil
290 print("== recordUntyped ==")
291 check.recordUntyped()
293 if check.Info != nil {
294 print("== sanitizeInfo ==")
295 sanitizeInfo(check.Info)
298 check.pkg.complete = true
300 // TODO(gri) There's more memory we should release at this point.
305 // processDelayed processes all delayed actions pushed after top.
306 func (check *Checker) processDelayed(top int) {
307 // If each delayed action pushes a new action, the
308 // stack will continue to grow during this loop.
309 // However, it is only processing functions (which
310 // are processed in a delayed fashion) that may
311 // add more actions (such as nested functions), so
312 // this is a sufficiently bounded process.
313 for i := top; i < len(check.delayed); i++ {
314 check.delayed[i]() // may append to check.delayed
316 assert(top <= len(check.delayed)) // stack must not have shrunk
317 check.delayed = check.delayed[:top]
320 func (check *Checker) processFinals() {
321 n := len(check.finals)
322 for _, f := range check.finals {
323 f() // must not append to check.finals
325 if len(check.finals) != n {
326 panic("internal error: final action list grew")
330 func (check *Checker) recordUntyped() {
331 if !debug && check.Types == nil {
332 return // nothing to do
335 for x, info := range check.untyped {
336 if debug && isTyped(info.typ) {
337 check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
340 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
344 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
350 if mode == constant_ {
352 assert(typ == Typ[Invalid] || isConstType(typ))
354 if m := check.Types; m != nil {
355 m[x] = TypeAndValue{mode, typ, val}
359 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
360 // f must be a (possibly parenthesized) identifier denoting a built-in
361 // (built-ins in package unsafe always produce a constant result and
362 // we don't record their signatures, so we don't see qualified idents
363 // here): record the signature for f and possible children.
365 check.recordTypeAndValue(f, builtin, sig, nil)
366 switch p := f.(type) {
369 case *syntax.ParenExpr:
377 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
379 if a[0] == nil || a[1] == nil {
382 assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
383 if m := check.Types; m != nil {
386 assert(tv.Type != nil) // should have been recorded already
389 NewVar(pos, check.pkg, "", a[0]),
390 NewVar(pos, check.pkg, "", a[1]),
393 // if x is a parenthesized expression (p.X), update p.X
394 p, _ := x.(*syntax.ParenExpr)
403 func (check *Checker) recordInferred(call syntax.Expr, targs []Type, sig *Signature) {
406 if m := check.Inferred; m != nil {
407 m[call] = Inferred{targs, sig}
411 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
413 if m := check.Defs; m != nil {
418 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
421 if m := check.Uses; m != nil {
426 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
429 if m := check.Implicits; m != nil {
434 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
435 assert(obj != nil && (recv == nil || len(index) > 0))
436 check.recordUse(x.Sel, obj)
437 if m := check.Selections; m != nil {
438 m[x] = &Selection{kind, recv, obj, index, indirect}
442 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
445 if m := check.Scopes; m != nil {