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