]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
go/types, types2: generalize cleanup phase after type checking
[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 // exprInfo stores information about an untyped expression.
22 type exprInfo struct {
23         isLhs bool // expression is lhs operand of a shift with delayed type-check
24         mode  operandMode
25         typ   *Basic
26         val   constant.Value // constant value; or nil (if not a constant)
27 }
28
29 // An environment represents the environment within which an object is
30 // type-checked.
31 type environment struct {
32         decl          *declInfo                 // package-level declaration whose init expression/function body is checked
33         scope         *Scope                    // top-most scope for lookups
34         pos           syntax.Pos                // if valid, identifiers are looked up as if at position pos (used by Eval)
35         iota          constant.Value            // value of iota in a constant declaration; nil otherwise
36         errpos        syntax.Pos                // if valid, identifier position of a constant with inherited initializer
37         inTParamList  bool                      // set if inside a type parameter list
38         sig           *Signature                // function signature if inside a function; nil otherwise
39         isPanic       map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
40         hasLabel      bool                      // set if a function makes use of labels (only ~1% of functions); unused outside functions
41         hasCallOrRecv bool                      // set if an expression contains a function call or channel receive operation
42 }
43
44 // lookup looks up name in the current environment and returns the matching object, or nil.
45 func (env *environment) lookup(name string) Object {
46         _, obj := env.scope.LookupParent(name, env.pos)
47         return obj
48 }
49
50 // An importKey identifies an imported package by import path and source directory
51 // (directory containing the file containing the import). In practice, the directory
52 // may always be the same, or may not matter. Given an (import path, directory), an
53 // importer must always return the same package (but given two different import paths,
54 // an importer may still return the same package by mapping them to the same package
55 // paths).
56 type importKey struct {
57         path, dir string
58 }
59
60 // A dotImportKey describes a dot-imported object in the given scope.
61 type dotImportKey struct {
62         scope *Scope
63         name  string
64 }
65
66 // An action describes a (delayed) action.
67 type action struct {
68         f    func()      // action to be executed
69         desc *actionDesc // action description; may be nil, requires debug to be set
70 }
71
72 // If debug is set, describef sets a printf-formatted description for action a.
73 // Otherwise, it is a no-op.
74 func (a *action) describef(pos poser, format string, args ...interface{}) {
75         if debug {
76                 a.desc = &actionDesc{pos, format, args}
77         }
78 }
79
80 // An actionDesc provides information on an action.
81 // For debugging only.
82 type actionDesc struct {
83         pos    poser
84         format string
85         args   []interface{}
86 }
87
88 // A Checker maintains the state of the type checker.
89 // It must be created with NewChecker.
90 type Checker struct {
91         // package information
92         // (initialized by NewChecker, valid for the life-time of checker)
93         conf *Config
94         ctxt *Context // context for de-duplicating instances
95         pkg  *Package
96         *Info
97         version version                // accepted language version
98         nextID  uint64                 // unique Id for type parameters (first valid Id is 1)
99         objMap  map[Object]*declInfo   // maps package-level objects and (non-interface) methods to declaration info
100         impMap  map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
101         infoMap map[*Named]typeInfo    // maps named types to their associated type info (for cycle detection)
102
103         // pkgPathMap maps package names to the set of distinct import paths we've
104         // seen for that name, anywhere in the import graph. It is used for
105         // disambiguating package names in error messages.
106         //
107         // pkgPathMap is allocated lazily, so that we don't pay the price of building
108         // it on the happy path. seenPkgMap tracks the packages that we've already
109         // walked.
110         pkgPathMap map[string]map[string]bool
111         seenPkgMap map[*Package]bool
112
113         // information collected during type-checking of a set of package files
114         // (initialized by Files, valid only for the duration of check.Files;
115         // maps and lists are allocated on demand)
116         files         []*syntax.File              // list of package files
117         imports       []*PkgName                  // list of imported packages
118         dotImportMap  map[dotImportKey]*PkgName   // maps dot-imported objects to the package they were dot-imported through
119         recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
120         brokenAliases map[*TypeName]bool          // set of aliases with broken (not yet determined) types
121         unionTypeSets map[*Union]*_TypeSet        // computed type sets for union types
122         mono          monoGraph                   // graph for detecting non-monomorphizable instantiation loops
123
124         firstErr error                    // first error encountered
125         methods  map[*TypeName][]*Func    // maps package scope type names to associated non-blank (non-interface) methods
126         untyped  map[syntax.Expr]exprInfo // map of expressions without final type
127         delayed  []action                 // stack of delayed action segments; segments are processed in FIFO order
128         objPath  []Object                 // path of object dependencies during type inference (for cycle reporting)
129         cleaners []cleaner                // list of types that may need a final cleanup at the end of type-checking
130
131         // environment within which the current object is type-checked (valid only
132         // for the duration of type-checking a specific object)
133         environment
134
135         // debugging
136         indent int // indentation for tracing
137 }
138
139 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
140 func (check *Checker) addDeclDep(to Object) {
141         from := check.decl
142         if from == nil {
143                 return // not in a package-level init expression
144         }
145         if _, found := check.objMap[to]; !found {
146                 return // to is not a package-level object
147         }
148         from.addDep(to)
149 }
150
151 // brokenAlias records that alias doesn't have a determined type yet.
152 // It also sets alias.typ to Typ[Invalid].
153 func (check *Checker) brokenAlias(alias *TypeName) {
154         if check.brokenAliases == nil {
155                 check.brokenAliases = make(map[*TypeName]bool)
156         }
157         check.brokenAliases[alias] = true
158         alias.typ = Typ[Invalid]
159 }
160
161 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
162 func (check *Checker) validAlias(alias *TypeName, typ Type) {
163         delete(check.brokenAliases, alias)
164         alias.typ = typ
165 }
166
167 // isBrokenAlias reports whether alias doesn't have a determined type yet.
168 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
169         return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
170 }
171
172 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
173         m := check.untyped
174         if m == nil {
175                 m = make(map[syntax.Expr]exprInfo)
176                 check.untyped = m
177         }
178         m[e] = exprInfo{lhs, mode, typ, val}
179 }
180
181 // later pushes f on to the stack of actions that will be processed later;
182 // either at the end of the current statement, or in case of a local constant
183 // or variable declaration, before the constant or variable is in scope
184 // (so that f still sees the scope before any new declarations).
185 // later returns the pushed action so one can provide a description
186 // via action.describef for debugging, if desired.
187 func (check *Checker) later(f func()) *action {
188         i := len(check.delayed)
189         check.delayed = append(check.delayed, action{f: f})
190         return &check.delayed[i]
191 }
192
193 // push pushes obj onto the object path and returns its index in the path.
194 func (check *Checker) push(obj Object) int {
195         check.objPath = append(check.objPath, obj)
196         return len(check.objPath) - 1
197 }
198
199 // pop pops and returns the topmost object from the object path.
200 func (check *Checker) pop() Object {
201         i := len(check.objPath) - 1
202         obj := check.objPath[i]
203         check.objPath[i] = nil
204         check.objPath = check.objPath[:i]
205         return obj
206 }
207
208 type cleaner interface {
209         cleanup()
210 }
211
212 // needsCleanup records objects/types that implement the cleanup method
213 // which will be called at the end of type-checking.
214 func (check *Checker) needsCleanup(c cleaner) {
215         check.cleaners = append(check.cleaners, c)
216 }
217
218 // NewChecker returns a new Checker instance for a given package.
219 // Package files may be added incrementally via checker.Files.
220 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
221         // make sure we have a configuration
222         if conf == nil {
223                 conf = new(Config)
224         }
225
226         // make sure we have an info struct
227         if info == nil {
228                 info = new(Info)
229         }
230
231         version, err := parseGoVersion(conf.GoVersion)
232         if err != nil {
233                 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
234         }
235
236         return &Checker{
237                 conf:    conf,
238                 ctxt:    conf.Context,
239                 pkg:     pkg,
240                 Info:    info,
241                 version: version,
242                 objMap:  make(map[Object]*declInfo),
243                 impMap:  make(map[importKey]*Package),
244                 infoMap: make(map[*Named]typeInfo),
245         }
246 }
247
248 // initFiles initializes the files-specific portion of checker.
249 // The provided files must all belong to the same package.
250 func (check *Checker) initFiles(files []*syntax.File) {
251         // start with a clean slate (check.Files may be called multiple times)
252         check.files = nil
253         check.imports = nil
254         check.dotImportMap = nil
255
256         check.firstErr = nil
257         check.methods = nil
258         check.untyped = nil
259         check.delayed = nil
260         check.objPath = nil
261         check.cleaners = nil
262
263         // determine package name and collect valid files
264         pkg := check.pkg
265         for _, file := range files {
266                 switch name := file.PkgName.Value; pkg.name {
267                 case "":
268                         if name != "_" {
269                                 pkg.name = name
270                         } else {
271                                 check.error(file.PkgName, "invalid package name _")
272                         }
273                         fallthrough
274
275                 case name:
276                         check.files = append(check.files, file)
277
278                 default:
279                         check.errorf(file, "package %s; expected %s", name, pkg.name)
280                         // ignore this file
281                 }
282         }
283 }
284
285 // A bailout panic is used for early termination.
286 type bailout struct{}
287
288 func (check *Checker) handleBailout(err *error) {
289         switch p := recover().(type) {
290         case nil, bailout:
291                 // normal return or early exit
292                 *err = check.firstErr
293         default:
294                 // re-panic
295                 panic(p)
296         }
297 }
298
299 // Files checks the provided files as part of the checker's package.
300 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
301
302 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
303
304 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
305         if check.conf.FakeImportC && check.conf.go115UsesCgo {
306                 return errBadCgo
307         }
308
309         defer check.handleBailout(&err)
310
311         print := func(msg string) {
312                 if check.conf.Trace {
313                         fmt.Println()
314                         fmt.Println(msg)
315                 }
316         }
317
318         print("== initFiles ==")
319         check.initFiles(files)
320
321         print("== collectObjects ==")
322         check.collectObjects()
323
324         print("== packageObjects ==")
325         check.packageObjects()
326
327         print("== processDelayed ==")
328         check.processDelayed(0) // incl. all functions
329
330         print("== cleanup ==")
331         check.cleanup()
332
333         print("== initOrder ==")
334         check.initOrder()
335
336         if !check.conf.DisableUnusedImportCheck {
337                 print("== unusedImports ==")
338                 check.unusedImports()
339         }
340
341         print("== recordUntyped ==")
342         check.recordUntyped()
343
344         if check.firstErr == nil {
345                 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
346                 check.monomorph()
347         }
348
349         check.pkg.complete = true
350
351         // no longer needed - release memory
352         check.imports = nil
353         check.dotImportMap = nil
354         check.pkgPathMap = nil
355         check.seenPkgMap = nil
356         check.recvTParamMap = nil
357         check.brokenAliases = nil
358         check.unionTypeSets = nil
359         check.ctxt = nil
360
361         // TODO(gri) There's more memory we should release at this point.
362
363         return
364 }
365
366 // processDelayed processes all delayed actions pushed after top.
367 func (check *Checker) processDelayed(top int) {
368         // If each delayed action pushes a new action, the
369         // stack will continue to grow during this loop.
370         // However, it is only processing functions (which
371         // are processed in a delayed fashion) that may
372         // add more actions (such as nested functions), so
373         // this is a sufficiently bounded process.
374         for i := top; i < len(check.delayed); i++ {
375                 a := &check.delayed[i]
376                 if check.conf.Trace && a.desc != nil {
377                         fmt.Println()
378                         check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
379                 }
380                 a.f() // may append to check.delayed
381         }
382         assert(top <= len(check.delayed)) // stack must not have shrunk
383         check.delayed = check.delayed[:top]
384 }
385
386 // cleanup runs cleanup for all collected cleaners.
387 func (check *Checker) cleanup() {
388         // Don't use a range clause since Named.cleanup may add more cleaners.
389         for i := 0; i < len(check.cleaners); i++ {
390                 check.cleaners[i].cleanup()
391         }
392         check.cleaners = nil
393 }
394
395 func (check *Checker) record(x *operand) {
396         // convert x into a user-friendly set of values
397         // TODO(gri) this code can be simplified
398         var typ Type
399         var val constant.Value
400         switch x.mode {
401         case invalid:
402                 typ = Typ[Invalid]
403         case novalue:
404                 typ = (*Tuple)(nil)
405         case constant_:
406                 typ = x.typ
407                 val = x.val
408         default:
409                 typ = x.typ
410         }
411         assert(x.expr != nil && typ != nil)
412
413         if isUntyped(typ) {
414                 // delay type and value recording until we know the type
415                 // or until the end of type checking
416                 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
417         } else {
418                 check.recordTypeAndValue(x.expr, x.mode, typ, val)
419         }
420 }
421
422 func (check *Checker) recordUntyped() {
423         if !debug && check.Types == nil {
424                 return // nothing to do
425         }
426
427         for x, info := range check.untyped {
428                 if debug && isTyped(info.typ) {
429                         check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
430                         unreachable()
431                 }
432                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
433         }
434 }
435
436 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
437         assert(x != nil)
438         assert(typ != nil)
439         if mode == invalid {
440                 return // omit
441         }
442         if mode == constant_ {
443                 assert(val != nil)
444                 // We check allBasic(typ, IsConstType) here as constant expressions may be
445                 // recorded as type parameters.
446                 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
447         }
448         if m := check.Types; m != nil {
449                 m[x] = TypeAndValue{mode, typ, val}
450         }
451 }
452
453 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
454         // f must be a (possibly parenthesized, possibly qualified)
455         // identifier denoting a built-in (including unsafe's non-constant
456         // functions Add and Slice): record the signature for f and possible
457         // children.
458         for {
459                 check.recordTypeAndValue(f, builtin, sig, nil)
460                 switch p := f.(type) {
461                 case *syntax.Name, *syntax.SelectorExpr:
462                         return // we're done
463                 case *syntax.ParenExpr:
464                         f = p.X
465                 default:
466                         unreachable()
467                 }
468         }
469 }
470
471 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
472         assert(x != nil)
473         if a[0] == nil || a[1] == nil {
474                 return
475         }
476         assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
477         if m := check.Types; m != nil {
478                 for {
479                         tv := m[x]
480                         assert(tv.Type != nil) // should have been recorded already
481                         pos := x.Pos()
482                         tv.Type = NewTuple(
483                                 NewVar(pos, check.pkg, "", a[0]),
484                                 NewVar(pos, check.pkg, "", a[1]),
485                         )
486                         m[x] = tv
487                         // if x is a parenthesized expression (p.X), update p.X
488                         p, _ := x.(*syntax.ParenExpr)
489                         if p == nil {
490                                 break
491                         }
492                         x = p.X
493                 }
494         }
495 }
496
497 // recordInstance records instantiation information into check.Info, if the
498 // Instances map is non-nil. The given expr must be an ident, selector, or
499 // index (list) expr with ident or selector operand.
500 //
501 // TODO(rfindley): the expr parameter is fragile. See if we can access the
502 // instantiated identifier in some other way.
503 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
504         ident := instantiatedIdent(expr)
505         assert(ident != nil)
506         assert(typ != nil)
507         if m := check.Instances; m != nil {
508                 m[ident] = Instance{newTypeList(targs), typ}
509         }
510 }
511
512 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
513         var selOrIdent syntax.Expr
514         switch e := expr.(type) {
515         case *syntax.IndexExpr:
516                 selOrIdent = e.X
517         case *syntax.SelectorExpr, *syntax.Name:
518                 selOrIdent = e
519         }
520         switch x := selOrIdent.(type) {
521         case *syntax.Name:
522                 return x
523         case *syntax.SelectorExpr:
524                 return x.Sel
525         }
526         panic("instantiated ident not found")
527 }
528
529 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
530         assert(id != nil)
531         if m := check.Defs; m != nil {
532                 m[id] = obj
533         }
534 }
535
536 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
537         assert(id != nil)
538         assert(obj != nil)
539         if m := check.Uses; m != nil {
540                 m[id] = obj
541         }
542 }
543
544 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
545         assert(node != nil)
546         assert(obj != nil)
547         if m := check.Implicits; m != nil {
548                 m[node] = obj
549         }
550 }
551
552 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
553         assert(obj != nil && (recv == nil || len(index) > 0))
554         check.recordUse(x.Sel, obj)
555         if m := check.Selections; m != nil {
556                 m[x] = &Selection{kind, recv, obj, index, indirect}
557         }
558 }
559
560 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
561         assert(node != nil)
562         assert(scope != nil)
563         if m := check.Scopes; m != nil {
564                 m[node] = scope
565         }
566 }