]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
cmd/compile/internal/types2: implement deduplication of instances using the Environment
[gostls13.git] / src / cmd / compile / internal / types2 / 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 types2
8
9 import (
10         "cmd/compile/internal/syntax"
11         "errors"
12         "fmt"
13         "go/constant"
14 )
15
16 var nopos syntax.Pos
17
18 // debugging/development support
19 const debug = false // leave on during development
20
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:
27 //
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.
31 //
32 const forceStrict = false
33
34 // exprInfo stores information about an untyped expression.
35 type exprInfo struct {
36         isLhs bool // expression is lhs operand of a shift with delayed type-check
37         mode  operandMode
38         typ   *Basic
39         val   constant.Value // constant value; or nil (if not a constant)
40 }
41
42 // A context represents the context within which an object is type-checked.
43 type context struct {
44         decl          *declInfo                 // package-level declaration whose init expression/function body is checked
45         scope         *Scope                    // top-most scope for lookups
46         pos           syntax.Pos                // if valid, identifiers are looked up as if at position pos (used by Eval)
47         iota          constant.Value            // value of iota in a constant declaration; nil otherwise
48         errpos        syntax.Pos                // if valid, identifier position of a constant with inherited initializer
49         sig           *Signature                // function signature if inside a function; nil otherwise
50         isPanic       map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
51         hasLabel      bool                      // set if a function makes use of labels (only ~1% of functions); unused outside functions
52         hasCallOrRecv bool                      // set if an expression contains a function call or channel receive operation
53 }
54
55 // lookup looks up name in the current context and returns the matching object, or nil.
56 func (ctxt *context) lookup(name string) Object {
57         _, obj := ctxt.scope.LookupParent(name, ctxt.pos)
58         return obj
59 }
60
61 // An importKey identifies an imported package by import path and source directory
62 // (directory containing the file containing the import). In practice, the directory
63 // may always be the same, or may not matter. Given an (import path, directory), an
64 // importer must always return the same package (but given two different import paths,
65 // an importer may still return the same package by mapping them to the same package
66 // paths).
67 type importKey struct {
68         path, dir string
69 }
70
71 // A dotImportKey describes a dot-imported object in the given scope.
72 type dotImportKey struct {
73         scope *Scope
74         name  string
75 }
76
77 // A Checker maintains the state of the type checker.
78 // It must be created with NewChecker.
79 type Checker struct {
80         // package information
81         // (initialized by NewChecker, valid for the life-time of checker)
82         conf *Config
83         pkg  *Package
84         *Info
85         version version                // accepted language version
86         nextID  uint64                 // unique Id for type parameters (first valid Id is 1)
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         env     *Environment           // for deduplicating identical instances
90
91         // pkgPathMap maps package names to the set of distinct import paths we've
92         // seen for that name, anywhere in the import graph. It is used for
93         // disambiguating package names in error messages.
94         //
95         // pkgPathMap is allocated lazily, so that we don't pay the price of building
96         // it on the happy path. seenPkgMap tracks the packages that we've already
97         // walked.
98         pkgPathMap map[string]map[string]bool
99         seenPkgMap map[*Package]bool
100
101         // information collected during type-checking of a set of package files
102         // (initialized by Files, valid only for the duration of check.Files;
103         // maps and lists are allocated on demand)
104         files        []*syntax.File            // list of package files
105         imports      []*PkgName                // list of imported packages
106         dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
107
108         firstErr error                    // first error encountered
109         methods  map[*TypeName][]*Func    // maps package scope type names to associated non-blank (non-interface) methods
110         untyped  map[syntax.Expr]exprInfo // map of expressions without final type
111         delayed  []func()                 // stack of delayed action segments; segments are processed in FIFO order
112         objPath  []Object                 // path of object dependencies during type inference (for cycle reporting)
113
114         // context within which the current object is type-checked
115         // (valid only for the duration of type-checking a specific object)
116         context
117
118         // debugging
119         indent int // indentation for tracing
120 }
121
122 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
123 func (check *Checker) addDeclDep(to Object) {
124         from := check.decl
125         if from == nil {
126                 return // not in a package-level init expression
127         }
128         if _, found := check.objMap[to]; !found {
129                 return // to is not a package-level object
130         }
131         from.addDep(to)
132 }
133
134 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
135         m := check.untyped
136         if m == nil {
137                 m = make(map[syntax.Expr]exprInfo)
138                 check.untyped = m
139         }
140         m[e] = exprInfo{lhs, mode, typ, val}
141 }
142
143 // later pushes f on to the stack of actions that will be processed later;
144 // either at the end of the current statement, or in case of a local constant
145 // or variable declaration, before the constant or variable is in scope
146 // (so that f still sees the scope before any new declarations).
147 func (check *Checker) later(f func()) {
148         check.delayed = append(check.delayed, 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, 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         version, err := parseGoVersion(conf.GoVersion)
180         if err != nil {
181                 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
182         }
183
184         return &Checker{
185                 conf:    conf,
186                 pkg:     pkg,
187                 Info:    info,
188                 version: version,
189                 objMap:  make(map[Object]*declInfo),
190                 impMap:  make(map[importKey]*Package),
191                 env:     NewEnvironment(),
192         }
193 }
194
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)
199         check.files = nil
200         check.imports = nil
201         check.dotImportMap = nil
202
203         check.firstErr = nil
204         check.methods = nil
205         check.untyped = nil
206         check.delayed = nil
207
208         // determine package name and collect valid files
209         pkg := check.pkg
210         for _, file := range files {
211                 switch name := file.PkgName.Value; pkg.name {
212                 case "":
213                         if name != "_" {
214                                 pkg.name = name
215                         } else {
216                                 check.error(file.PkgName, "invalid package name _")
217                         }
218                         fallthrough
219
220                 case name:
221                         check.files = append(check.files, file)
222
223                 default:
224                         check.errorf(file, "package %s; expected %s", name, pkg.name)
225                         // ignore this file
226                 }
227         }
228 }
229
230 // A bailout panic is used for early termination.
231 type bailout struct{}
232
233 func (check *Checker) handleBailout(err *error) {
234         switch p := recover().(type) {
235         case nil, bailout:
236                 // normal return or early exit
237                 *err = check.firstErr
238         default:
239                 // re-panic
240                 panic(p)
241         }
242 }
243
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) }
246
247 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
248
249 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
250         if check.conf.FakeImportC && check.conf.go115UsesCgo {
251                 return errBadCgo
252         }
253
254         defer check.handleBailout(&err)
255
256         print := func(msg string) {
257                 if check.conf.Trace {
258                         fmt.Println(msg)
259                 }
260         }
261
262         print("== initFiles ==")
263         check.initFiles(files)
264
265         print("== collectObjects ==")
266         check.collectObjects()
267
268         print("== packageObjects ==")
269         check.packageObjects()
270
271         print("== processDelayed ==")
272         check.processDelayed(0) // incl. all functions
273
274         print("== initOrder ==")
275         check.initOrder()
276
277         if !check.conf.DisableUnusedImportCheck {
278                 print("== unusedImports ==")
279                 check.unusedImports()
280         }
281
282         print("== recordUntyped ==")
283         check.recordUntyped()
284
285         check.pkg.complete = true
286
287         // no longer needed - release memory
288         check.imports = nil
289         check.dotImportMap = nil
290         check.pkgPathMap = nil
291         check.seenPkgMap = nil
292
293         // TODO(gri) There's more memory we should release at this point.
294
295         return
296 }
297
298 // processDelayed processes all delayed actions pushed after top.
299 func (check *Checker) processDelayed(top int) {
300         // If each delayed action pushes a new action, the
301         // stack will continue to grow during this loop.
302         // However, it is only processing functions (which
303         // are processed in a delayed fashion) that may
304         // add more actions (such as nested functions), so
305         // this is a sufficiently bounded process.
306         for i := top; i < len(check.delayed); i++ {
307                 check.delayed[i]() // may append to check.delayed
308         }
309         assert(top <= len(check.delayed)) // stack must not have shrunk
310         check.delayed = check.delayed[:top]
311 }
312
313 func (check *Checker) record(x *operand) {
314         // convert x into a user-friendly set of values
315         // TODO(gri) this code can be simplified
316         var typ Type
317         var val constant.Value
318         switch x.mode {
319         case invalid:
320                 typ = Typ[Invalid]
321         case novalue:
322                 typ = (*Tuple)(nil)
323         case constant_:
324                 typ = x.typ
325                 val = x.val
326         default:
327                 typ = x.typ
328         }
329         assert(x.expr != nil && typ != nil)
330
331         if isUntyped(typ) {
332                 // delay type and value recording until we know the type
333                 // or until the end of type checking
334                 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
335         } else {
336                 check.recordTypeAndValue(x.expr, x.mode, typ, val)
337         }
338 }
339
340 func (check *Checker) recordUntyped() {
341         if !debug && check.Types == nil {
342                 return // nothing to do
343         }
344
345         for x, info := range check.untyped {
346                 if debug && isTyped(info.typ) {
347                         check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
348                         unreachable()
349                 }
350                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
351         }
352 }
353
354 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
355         assert(x != nil)
356         assert(typ != nil)
357         if mode == invalid {
358                 return // omit
359         }
360         if mode == constant_ {
361                 assert(val != nil)
362                 // We check is(typ, IsConstType) here as constant expressions may be
363                 // recorded as type parameters.
364                 assert(typ == Typ[Invalid] || is(typ, IsConstType))
365         }
366         if m := check.Types; m != nil {
367                 m[x] = TypeAndValue{mode, typ, val}
368         }
369 }
370
371 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
372         // f must be a (possibly parenthesized, possibly qualified)
373         // identifier denoting a built-in (including unsafe's non-constant
374         // functions Add and Slice): record the signature for f and possible
375         // children.
376         for {
377                 check.recordTypeAndValue(f, builtin, sig, nil)
378                 switch p := f.(type) {
379                 case *syntax.Name, *syntax.SelectorExpr:
380                         return // we're done
381                 case *syntax.ParenExpr:
382                         f = p.X
383                 default:
384                         unreachable()
385                 }
386         }
387 }
388
389 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
390         assert(x != nil)
391         if a[0] == nil || a[1] == nil {
392                 return
393         }
394         assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
395         if m := check.Types; m != nil {
396                 for {
397                         tv := m[x]
398                         assert(tv.Type != nil) // should have been recorded already
399                         pos := x.Pos()
400                         tv.Type = NewTuple(
401                                 NewVar(pos, check.pkg, "", a[0]),
402                                 NewVar(pos, check.pkg, "", a[1]),
403                         )
404                         m[x] = tv
405                         // if x is a parenthesized expression (p.X), update p.X
406                         p, _ := x.(*syntax.ParenExpr)
407                         if p == nil {
408                                 break
409                         }
410                         x = p.X
411                 }
412         }
413 }
414
415 func (check *Checker) recordInferred(call syntax.Expr, targs []Type, sig *Signature) {
416         assert(call != nil)
417         assert(sig != nil)
418         if m := check.Inferred; m != nil {
419                 m[call] = Inferred{NewTypeList(targs), sig}
420         }
421 }
422
423 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
424         assert(id != nil)
425         if m := check.Defs; m != nil {
426                 m[id] = obj
427         }
428 }
429
430 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
431         assert(id != nil)
432         assert(obj != nil)
433         if m := check.Uses; m != nil {
434                 m[id] = obj
435         }
436 }
437
438 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
439         assert(node != nil)
440         assert(obj != nil)
441         if m := check.Implicits; m != nil {
442                 m[node] = obj
443         }
444 }
445
446 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
447         assert(obj != nil && (recv == nil || len(index) > 0))
448         check.recordUse(x.Sel, obj)
449         if m := check.Selections; m != nil {
450                 m[x] = &Selection{kind, recv, obj, index, indirect}
451         }
452 }
453
454 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
455         assert(node != nil)
456         assert(scope != nil)
457         if m := check.Scopes; m != nil {
458                 m[node] = scope
459         }
460 }