]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
cmd/compile: keep typecheck results in syntax tree
[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         valids  instanceLookup         // valid *Named (incl. instantiated) types per the validType check
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         }
245 }
246
247 // initFiles initializes the files-specific portion of checker.
248 // The provided files must all belong to the same package.
249 func (check *Checker) initFiles(files []*syntax.File) {
250         // start with a clean slate (check.Files may be called multiple times)
251         check.files = nil
252         check.imports = nil
253         check.dotImportMap = nil
254
255         check.firstErr = nil
256         check.methods = nil
257         check.untyped = nil
258         check.delayed = nil
259         check.objPath = nil
260         check.cleaners = nil
261
262         // determine package name and collect valid files
263         pkg := check.pkg
264         for _, file := range files {
265                 switch name := file.PkgName.Value; pkg.name {
266                 case "":
267                         if name != "_" {
268                                 pkg.name = name
269                         } else {
270                                 check.error(file.PkgName, _BlankPkgName, "invalid package name _")
271                         }
272                         fallthrough
273
274                 case name:
275                         check.files = append(check.files, file)
276
277                 default:
278                         check.errorf(file, _MismatchedPkgName, "package %s; expected %s", name, pkg.name)
279                         // ignore this file
280                 }
281         }
282 }
283
284 // A bailout panic is used for early termination.
285 type bailout struct{}
286
287 func (check *Checker) handleBailout(err *error) {
288         switch p := recover().(type) {
289         case nil, bailout:
290                 // normal return or early exit
291                 *err = check.firstErr
292         default:
293                 // re-panic
294                 panic(p)
295         }
296 }
297
298 // Files checks the provided files as part of the checker's package.
299 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
300
301 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
302
303 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
304         if check.conf.FakeImportC && check.conf.go115UsesCgo {
305                 return errBadCgo
306         }
307
308         defer check.handleBailout(&err)
309
310         print := func(msg string) {
311                 if check.conf.Trace {
312                         fmt.Println()
313                         fmt.Println(msg)
314                 }
315         }
316
317         print("== initFiles ==")
318         check.initFiles(files)
319
320         print("== collectObjects ==")
321         check.collectObjects()
322
323         print("== packageObjects ==")
324         check.packageObjects()
325
326         print("== processDelayed ==")
327         check.processDelayed(0) // incl. all functions
328
329         print("== cleanup ==")
330         check.cleanup()
331
332         print("== initOrder ==")
333         check.initOrder()
334
335         if !check.conf.DisableUnusedImportCheck {
336                 print("== unusedImports ==")
337                 check.unusedImports()
338         }
339
340         print("== recordUntyped ==")
341         check.recordUntyped()
342
343         if check.firstErr == nil {
344                 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
345                 check.monomorph()
346         }
347
348         check.pkg.complete = true
349
350         // no longer needed - release memory
351         check.imports = nil
352         check.dotImportMap = nil
353         check.pkgPathMap = nil
354         check.seenPkgMap = nil
355         check.recvTParamMap = nil
356         check.brokenAliases = nil
357         check.unionTypeSets = nil
358         check.ctxt = nil
359
360         // TODO(gri) There's more memory we should release at this point.
361
362         return
363 }
364
365 // processDelayed processes all delayed actions pushed after top.
366 func (check *Checker) processDelayed(top int) {
367         // If each delayed action pushes a new action, the
368         // stack will continue to grow during this loop.
369         // However, it is only processing functions (which
370         // are processed in a delayed fashion) that may
371         // add more actions (such as nested functions), so
372         // this is a sufficiently bounded process.
373         for i := top; i < len(check.delayed); i++ {
374                 a := &check.delayed[i]
375                 if check.conf.Trace {
376                         if a.desc != nil {
377                                 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
378                         } else {
379                                 check.trace(nopos, "-- delayed %p", a.f)
380                         }
381                 }
382                 a.f() // may append to check.delayed
383                 if check.conf.Trace {
384                         fmt.Println()
385                 }
386         }
387         assert(top <= len(check.delayed)) // stack must not have shrunk
388         check.delayed = check.delayed[:top]
389 }
390
391 // cleanup runs cleanup for all collected cleaners.
392 func (check *Checker) cleanup() {
393         // Don't use a range clause since Named.cleanup may add more cleaners.
394         for i := 0; i < len(check.cleaners); i++ {
395                 check.cleaners[i].cleanup()
396         }
397         check.cleaners = nil
398 }
399
400 func (check *Checker) record(x *operand) {
401         // convert x into a user-friendly set of values
402         // TODO(gri) this code can be simplified
403         var typ Type
404         var val constant.Value
405         switch x.mode {
406         case invalid:
407                 typ = Typ[Invalid]
408         case novalue:
409                 typ = (*Tuple)(nil)
410         case constant_:
411                 typ = x.typ
412                 val = x.val
413         default:
414                 typ = x.typ
415         }
416         assert(x.expr != nil && typ != nil)
417
418         if isUntyped(typ) {
419                 // delay type and value recording until we know the type
420                 // or until the end of type checking
421                 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
422         } else {
423                 check.recordTypeAndValue(x.expr, x.mode, typ, val)
424         }
425 }
426
427 func (check *Checker) recordUntyped() {
428         if !debug && !check.recordTypes() {
429                 return // nothing to do
430         }
431
432         for x, info := range check.untyped {
433                 if debug && isTyped(info.typ) {
434                         check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
435                         unreachable()
436                 }
437                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
438         }
439 }
440
441 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
442         assert(x != nil)
443         assert(typ != nil)
444         if mode == invalid {
445                 return // omit
446         }
447         if mode == constant_ {
448                 assert(val != nil)
449                 // We check allBasic(typ, IsConstType) here as constant expressions may be
450                 // recorded as type parameters.
451                 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
452         }
453         if m := check.Types; m != nil {
454                 m[x] = TypeAndValue{mode, typ, val}
455         }
456         if check.StoreTypesInSyntax {
457                 tv := TypeAndValue{mode, typ, val}
458                 stv := syntax.TypeAndValue{Type: typ, Value: val}
459                 if tv.IsVoid() {
460                         stv.SetIsVoid()
461                 }
462                 if tv.IsType() {
463                         stv.SetIsType()
464                 }
465                 if tv.IsBuiltin() {
466                         stv.SetIsBuiltin()
467                 }
468                 if tv.IsValue() {
469                         stv.SetIsValue()
470                 }
471                 if tv.IsNil() {
472                         stv.SetIsNil()
473                 }
474                 if tv.Addressable() {
475                         stv.SetAddressable()
476                 }
477                 if tv.Assignable() {
478                         stv.SetAssignable()
479                 }
480                 if tv.HasOk() {
481                         stv.SetHasOk()
482                 }
483                 x.SetTypeInfo(stv)
484         }
485 }
486
487 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
488         // f must be a (possibly parenthesized, possibly qualified)
489         // identifier denoting a built-in (including unsafe's non-constant
490         // functions Add and Slice): record the signature for f and possible
491         // children.
492         for {
493                 check.recordTypeAndValue(f, builtin, sig, nil)
494                 switch p := f.(type) {
495                 case *syntax.Name, *syntax.SelectorExpr:
496                         return // we're done
497                 case *syntax.ParenExpr:
498                         f = p.X
499                 default:
500                         unreachable()
501                 }
502         }
503 }
504
505 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
506         assert(x != nil)
507         if a[0] == nil || a[1] == nil {
508                 return
509         }
510         assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
511         if m := check.Types; m != nil {
512                 for {
513                         tv := m[x]
514                         assert(tv.Type != nil) // should have been recorded already
515                         pos := x.Pos()
516                         tv.Type = NewTuple(
517                                 NewVar(pos, check.pkg, "", a[0]),
518                                 NewVar(pos, check.pkg, "", a[1]),
519                         )
520                         m[x] = tv
521                         p, _ := x.(*syntax.ParenExpr)
522                         if p == nil {
523                                 break
524                         }
525                         x = p.X
526                 }
527         }
528         if check.StoreTypesInSyntax {
529                 // Note: this loop is duplicated because the type of tv is different.
530                 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
531                 for {
532                         tv := x.GetTypeInfo()
533                         assert(tv.Type != nil) // should have been recorded already
534                         pos := x.Pos()
535                         tv.Type = NewTuple(
536                                 NewVar(pos, check.pkg, "", a[0]),
537                                 NewVar(pos, check.pkg, "", a[1]),
538                         )
539                         x.SetTypeInfo(tv)
540                         p, _ := x.(*syntax.ParenExpr)
541                         if p == nil {
542                                 break
543                         }
544                         x = p.X
545                 }
546         }
547 }
548
549 // recordInstance records instantiation information into check.Info, if the
550 // Instances map is non-nil. The given expr must be an ident, selector, or
551 // index (list) expr with ident or selector operand.
552 //
553 // TODO(rfindley): the expr parameter is fragile. See if we can access the
554 // instantiated identifier in some other way.
555 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
556         ident := instantiatedIdent(expr)
557         assert(ident != nil)
558         assert(typ != nil)
559         if m := check.Instances; m != nil {
560                 m[ident] = Instance{newTypeList(targs), typ}
561         }
562 }
563
564 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
565         var selOrIdent syntax.Expr
566         switch e := expr.(type) {
567         case *syntax.IndexExpr:
568                 selOrIdent = e.X
569         case *syntax.SelectorExpr, *syntax.Name:
570                 selOrIdent = e
571         }
572         switch x := selOrIdent.(type) {
573         case *syntax.Name:
574                 return x
575         case *syntax.SelectorExpr:
576                 return x.Sel
577         }
578         panic("instantiated ident not found")
579 }
580
581 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
582         assert(id != nil)
583         if m := check.Defs; m != nil {
584                 m[id] = obj
585         }
586 }
587
588 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
589         assert(id != nil)
590         assert(obj != nil)
591         if m := check.Uses; m != nil {
592                 m[id] = obj
593         }
594 }
595
596 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
597         assert(node != nil)
598         assert(obj != nil)
599         if m := check.Implicits; m != nil {
600                 m[node] = obj
601         }
602 }
603
604 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
605         assert(obj != nil && (recv == nil || len(index) > 0))
606         check.recordUse(x.Sel, obj)
607         if m := check.Selections; m != nil {
608                 m[x] = &Selection{kind, recv, obj, index, indirect}
609         }
610 }
611
612 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
613         assert(node != nil)
614         assert(scope != nil)
615         if m := check.Scopes; m != nil {
616                 m[node] = scope
617         }
618 }