]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/check.go
[dev.regabi] all: merge master (ff0e93e) into dev.regabi
[gostls13.git] / src / go / types / check.go
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.
4
5 // This file implements the Check function, which drives type-checking.
6
7 package types
8
9 import (
10         "errors"
11         "go/ast"
12         "go/constant"
13         "go/token"
14 )
15
16 // debugging/development support
17 const (
18         debug = false // leave on during development
19         trace = false // turn on for detailed type resolution traces
20 )
21
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:
28 //
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.
32 //
33 const strict = false
34
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
38         mode  operandMode
39         typ   *Basic
40         val   constant.Value // constant value; or nil (if not a constant)
41 }
42
43 // A context represents the context within which an object is type-checked.
44 type context struct {
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
54 }
55
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)
59         return obj
60 }
61
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
67 // paths).
68 type importKey struct {
69         path, dir string
70 }
71
72 // A dotImportKey describes a dot-imported object in the given scope.
73 type dotImportKey struct {
74         scope *Scope
75         obj   Object
76 }
77
78 // A Checker maintains the state of the type checker.
79 // It must be created with NewChecker.
80 type Checker struct {
81         // package information
82         // (initialized by NewChecker, valid for the life-time of checker)
83         conf *Config
84         fset *token.FileSet
85         pkg  *Package
86         *Info
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)
91
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
98
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)
105
106         // context within which the current object is type-checked
107         // (valid only for the duration of type-checking a specific object)
108         context
109
110         // debugging
111         indent int // indentation for tracing
112 }
113
114 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
115 func (check *Checker) addDeclDep(to Object) {
116         from := check.decl
117         if from == nil {
118                 return // not in a package-level init expression
119         }
120         if _, found := check.objMap[to]; !found {
121                 return // to is not a package-level object
122         }
123         from.addDep(to)
124 }
125
126 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
127         m := check.untyped
128         if m == nil {
129                 m = make(map[ast.Expr]exprInfo)
130                 check.untyped = m
131         }
132         m[e] = exprInfo{lhs, mode, typ, val}
133 }
134
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)
141 }
142
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
146 // added by later.
147 func (check *Checker) atEnd(f func()) {
148         check.finals = append(check.finals, f)
149 }
150
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
155 }
156
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]
163         return obj
164 }
165
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
170         if conf == nil {
171                 conf = new(Config)
172         }
173
174         // make sure we have an info struct
175         if info == nil {
176                 info = new(Info)
177         }
178
179         return &Checker{
180                 conf:   conf,
181                 fset:   fset,
182                 pkg:    pkg,
183                 Info:   info,
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),
188         }
189 }
190
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)
195         check.files = nil
196         check.imports = nil
197         check.dotImportMap = nil
198
199         check.firstErr = nil
200         check.methods = nil
201         check.untyped = nil
202         check.delayed = nil
203         check.finals = nil
204
205         // determine package name and collect valid files
206         pkg := check.pkg
207         for _, file := range files {
208                 switch name := file.Name.Name; pkg.name {
209                 case "":
210                         if name != "_" {
211                                 pkg.name = name
212                         } else {
213                                 check.errorf(file.Name, _BlankPkgName, "invalid package name _")
214                         }
215                         fallthrough
216
217                 case name:
218                         check.files = append(check.files, file)
219
220                 default:
221                         check.errorf(atPos(file.Package), _MismatchedPkgName, "package %s; expected %s", name, pkg.name)
222                         // ignore this file
223                 }
224         }
225 }
226
227 // A bailout panic is used for early termination.
228 type bailout struct{}
229
230 func (check *Checker) handleBailout(err *error) {
231         switch p := recover().(type) {
232         case nil, bailout:
233                 // normal return or early exit
234                 *err = check.firstErr
235         default:
236                 // re-panic
237                 panic(p)
238         }
239 }
240
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) }
243
244 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
245
246 func (check *Checker) checkFiles(files []*ast.File) (err error) {
247         if check.conf.FakeImportC && check.conf.go115UsesCgo {
248                 return errBadCgo
249         }
250
251         defer check.handleBailout(&err)
252
253         check.initFiles(files)
254
255         check.collectObjects()
256
257         check.packageObjects()
258
259         check.processDelayed(0) // incl. all functions
260         check.processFinals()
261
262         check.initOrder()
263
264         if !check.conf.DisableUnusedImportCheck {
265                 check.unusedImports()
266         }
267         // no longer needed - release memory
268         check.imports = nil
269         check.dotImportMap = nil
270
271         check.recordUntyped()
272
273         check.pkg.complete = true
274
275         // TODO(rFindley) There's more memory we should release at this point.
276
277         return
278 }
279
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
290         }
291         assert(top <= len(check.delayed)) // stack must not have shrunk
292         check.delayed = check.delayed[:top]
293 }
294
295 func (check *Checker) processFinals() {
296         n := len(check.finals)
297         for _, f := range check.finals {
298                 f() // must not append to check.finals
299         }
300         if len(check.finals) != n {
301                 panic("internal error: final action list grew")
302         }
303 }
304
305 func (check *Checker) recordUntyped() {
306         if !debug && check.Types == nil {
307                 return // nothing to do
308         }
309
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)
313                         unreachable()
314                 }
315                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
316         }
317 }
318
319 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
320         assert(x != nil)
321         assert(typ != nil)
322         if mode == invalid {
323                 return // omit
324         }
325         if mode == constant_ {
326                 assert(val != nil)
327                 assert(typ == Typ[Invalid] || isConstType(typ))
328         }
329         if m := check.Types; m != nil {
330                 m[x] = TypeAndValue{mode, typ, val}
331         }
332 }
333
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.
339         for {
340                 check.recordTypeAndValue(f, builtin, sig, nil)
341                 switch p := f.(type) {
342                 case *ast.Ident:
343                         return // we're done
344                 case *ast.ParenExpr:
345                         f = p.X
346                 default:
347                         unreachable()
348                 }
349         }
350 }
351
352 func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
353         assert(x != nil)
354         if a[0] == nil || a[1] == nil {
355                 return
356         }
357         assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
358         if m := check.Types; m != nil {
359                 for {
360                         tv := m[x]
361                         assert(tv.Type != nil) // should have been recorded already
362                         pos := x.Pos()
363                         tv.Type = NewTuple(
364                                 NewVar(pos, check.pkg, "", a[0]),
365                                 NewVar(pos, check.pkg, "", a[1]),
366                         )
367                         m[x] = tv
368                         // if x is a parenthesized expression (p.X), update p.X
369                         p, _ := x.(*ast.ParenExpr)
370                         if p == nil {
371                                 break
372                         }
373                         x = p.X
374                 }
375         }
376 }
377
378 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
379         assert(id != nil)
380         if m := check.Defs; m != nil {
381                 m[id] = obj
382         }
383 }
384
385 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
386         assert(id != nil)
387         assert(obj != nil)
388         if m := check.Uses; m != nil {
389                 m[id] = obj
390         }
391 }
392
393 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
394         assert(node != nil)
395         assert(obj != nil)
396         if m := check.Implicits; m != nil {
397                 m[node] = obj
398         }
399 }
400
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}
406         }
407 }
408
409 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
410         assert(node != nil)
411         assert(scope != nil)
412         if m := check.Scopes; m != nil {
413                 m[node] = scope
414         }
415 }