]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
[dev.typeparams] all: merge dev.regabi (07569da) into dev.typeparams
[gostls13.git] / src / cmd / compile / internal / types2 / check.go
1 // UNREVIEWED
2 // Copyright 2011 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 // This file implements the Check function, which drives type-checking.
7
8 package types2
9
10 import (
11         "cmd/compile/internal/syntax"
12         "errors"
13         "fmt"
14         "go/constant"
15 )
16
17 var nopos syntax.Pos
18
19 // debugging/development support
20 const debug = true // leave on during development
21
22 // If forceStrict 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 forceStrict = false
34
35 // If methodTypeParamsOk is set, type parameters are
36 // permitted in method declarations (in interfaces, too).
37 // Generalization and experimental feature.
38 const methodTypeParamsOk = true
39
40 // exprInfo stores information about an untyped expression.
41 type exprInfo struct {
42         isLhs bool // expression is lhs operand of a shift with delayed type-check
43         mode  operandMode
44         typ   *Basic
45         val   constant.Value // constant value; or nil (if not a constant)
46 }
47
48 // A context represents the context within which an object is type-checked.
49 type context struct {
50         decl          *declInfo                 // package-level declaration whose init expression/function body is checked
51         scope         *Scope                    // top-most scope for lookups
52         pos           syntax.Pos                // if valid, identifiers are looked up as if at position pos (used by Eval)
53         iota          constant.Value            // value of iota in a constant declaration; nil otherwise
54         errpos        syntax.Pos                // if valid, identifier position of a constant with inherited initializer
55         sig           *Signature                // function signature if inside a function; nil otherwise
56         isPanic       map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
57         hasLabel      bool                      // set if a function makes use of labels (only ~1% of functions); unused outside functions
58         hasCallOrRecv bool                      // set if an expression contains a function call or channel receive operation
59 }
60
61 // lookup looks up name in the current context and returns the matching object, or nil.
62 func (ctxt *context) lookup(name string) Object {
63         _, obj := ctxt.scope.LookupParent(name, ctxt.pos)
64         return obj
65 }
66
67 // An importKey identifies an imported package by import path and source directory
68 // (directory containing the file containing the import). In practice, the directory
69 // may always be the same, or may not matter. Given an (import path, directory), an
70 // importer must always return the same package (but given two different import paths,
71 // an importer may still return the same package by mapping them to the same package
72 // paths).
73 type importKey struct {
74         path, dir 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         nextId uint64                      // unique Id for type parameters (first valid Id is 1)
86         objMap map[Object]*declInfo        // maps package-level objects and (non-interface) methods to declaration info
87         impMap map[importKey]*Package      // maps (import path, source directory) to (complete or fake) package
88         posMap map[*Interface][]syntax.Pos // maps interface types to lists of embedded interface positions
89         typMap map[string]*Named           // maps an instantiated named type hash to a *Named type
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            []*syntax.File                     // package files
96         unusedDotImports map[*Scope]map[*Package]syntax.Pos // positions of unused dot-imported packages for each file scope
97
98         firstErr error                    // first error encountered
99         methods  map[*TypeName][]*Func    // maps package scope type names to associated non-blank (non-interface) methods
100         untyped  map[syntax.Expr]exprInfo // map of expressions without final type
101         delayed  []func()                 // stack of delayed action segments; segments are processed in FIFO order
102         finals   []func()                 // list of final actions; processed at the end of type-checking the current set of files
103         objPath  []Object                 // path of object dependencies during type inference (for cycle reporting)
104
105         // context within which the current object is type-checked
106         // (valid only for the duration of type-checking a specific object)
107         context
108
109         // debugging
110         indent int // indentation for tracing
111 }
112
113 // addUnusedImport adds the position of a dot-imported package
114 // pkg to the map of dot imports for the given file scope.
115 func (check *Checker) addUnusedDotImport(scope *Scope, pkg *Package, pos syntax.Pos) {
116         mm := check.unusedDotImports
117         if mm == nil {
118                 mm = make(map[*Scope]map[*Package]syntax.Pos)
119                 check.unusedDotImports = mm
120         }
121         m := mm[scope]
122         if m == nil {
123                 m = make(map[*Package]syntax.Pos)
124                 mm[scope] = m
125         }
126         m[pkg] = pos
127 }
128
129 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
130 func (check *Checker) addDeclDep(to Object) {
131         from := check.decl
132         if from == nil {
133                 return // not in a package-level init expression
134         }
135         if _, found := check.objMap[to]; !found {
136                 return // to is not a package-level object
137         }
138         from.addDep(to)
139 }
140
141 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
142         m := check.untyped
143         if m == nil {
144                 m = make(map[syntax.Expr]exprInfo)
145                 check.untyped = m
146         }
147         m[e] = exprInfo{lhs, mode, typ, val}
148 }
149
150 // later pushes f on to the stack of actions that will be processed later;
151 // either at the end of the current statement, or in case of a local constant
152 // or variable declaration, before the constant or variable is in scope
153 // (so that f still sees the scope before any new declarations).
154 func (check *Checker) later(f func()) {
155         check.delayed = append(check.delayed, f)
156 }
157
158 // atEnd adds f to the list of actions processed at the end
159 // of type-checking, before initialization order computation.
160 // Actions added by atEnd are processed after any actions
161 // added by later.
162 func (check *Checker) atEnd(f func()) {
163         check.finals = append(check.finals, f)
164 }
165
166 // push pushes obj onto the object path and returns its index in the path.
167 func (check *Checker) push(obj Object) int {
168         check.objPath = append(check.objPath, obj)
169         return len(check.objPath) - 1
170 }
171
172 // pop pops and returns the topmost object from the object path.
173 func (check *Checker) pop() Object {
174         i := len(check.objPath) - 1
175         obj := check.objPath[i]
176         check.objPath[i] = nil
177         check.objPath = check.objPath[:i]
178         return obj
179 }
180
181 // NewChecker returns a new Checker instance for a given package.
182 // Package files may be added incrementally via checker.Files.
183 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
184         // make sure we have a configuration
185         if conf == nil {
186                 conf = new(Config)
187         }
188
189         // make sure we have an info struct
190         if info == nil {
191                 info = new(Info)
192         }
193
194         return &Checker{
195                 conf:   conf,
196                 pkg:    pkg,
197                 Info:   info,
198                 nextId: 1,
199                 objMap: make(map[Object]*declInfo),
200                 impMap: make(map[importKey]*Package),
201                 posMap: make(map[*Interface][]syntax.Pos),
202                 typMap: make(map[string]*Named),
203                 pkgCnt: make(map[string]int),
204         }
205 }
206
207 // initFiles initializes the files-specific portion of checker.
208 // The provided files must all belong to the same package.
209 func (check *Checker) initFiles(files []*syntax.File) {
210         // start with a clean slate (check.Files may be called multiple times)
211         check.files = nil
212         check.unusedDotImports = nil
213
214         check.firstErr = nil
215         check.methods = nil
216         check.untyped = nil
217         check.delayed = nil
218         check.finals = nil
219
220         // determine package name and collect valid files
221         pkg := check.pkg
222         for _, file := range files {
223                 switch name := file.PkgName.Value; pkg.name {
224                 case "":
225                         if name != "_" {
226                                 pkg.name = name
227                         } else {
228                                 check.errorf(file.PkgName, "invalid package name _")
229                         }
230                         fallthrough
231
232                 case name:
233                         check.files = append(check.files, file)
234
235                 default:
236                         check.errorf(file, "package %s; expected %s", name, pkg.name)
237                         // ignore this file
238                 }
239         }
240 }
241
242 // A bailout panic is used for early termination.
243 type bailout struct{}
244
245 func (check *Checker) handleBailout(err *error) {
246         switch p := recover().(type) {
247         case nil, bailout:
248                 // normal return or early exit
249                 *err = check.firstErr
250         default:
251                 // re-panic
252                 panic(p)
253         }
254 }
255
256 // Files checks the provided files as part of the checker's package.
257 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
258
259 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
260
261 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
262         if check.conf.FakeImportC && check.conf.go115UsesCgo {
263                 return errBadCgo
264         }
265
266         defer check.handleBailout(&err)
267
268         print := func(msg string) {
269                 if check.conf.Trace {
270                         fmt.Println(msg)
271                 }
272         }
273
274         print("== initFiles ==")
275         check.initFiles(files)
276
277         print("== collectObjects ==")
278         check.collectObjects()
279
280         print("== packageObjects ==")
281         check.packageObjects()
282
283         print("== processDelayed ==")
284         check.processDelayed(0) // incl. all functions
285         check.processFinals()
286
287         print("== initOrder ==")
288         check.initOrder()
289
290         if !check.conf.DisableUnusedImportCheck {
291                 print("== unusedImports ==")
292                 check.unusedImports()
293         }
294
295         print("== recordUntyped ==")
296         check.recordUntyped()
297
298         if check.Info != nil {
299                 print("== sanitizeInfo ==")
300                 sanitizeInfo(check.Info)
301         }
302
303         check.pkg.complete = true
304         return
305 }
306
307 // processDelayed processes all delayed actions pushed after top.
308 func (check *Checker) processDelayed(top int) {
309         // If each delayed action pushes a new action, the
310         // stack will continue to grow during this loop.
311         // However, it is only processing functions (which
312         // are processed in a delayed fashion) that may
313         // add more actions (such as nested functions), so
314         // this is a sufficiently bounded process.
315         for i := top; i < len(check.delayed); i++ {
316                 check.delayed[i]() // may append to check.delayed
317         }
318         assert(top <= len(check.delayed)) // stack must not have shrunk
319         check.delayed = check.delayed[:top]
320 }
321
322 func (check *Checker) processFinals() {
323         n := len(check.finals)
324         for _, f := range check.finals {
325                 f() // must not append to check.finals
326         }
327         if len(check.finals) != n {
328                 panic("internal error: final action list grew")
329         }
330 }
331
332 func (check *Checker) recordUntyped() {
333         if !debug && check.Types == nil {
334                 return // nothing to do
335         }
336
337         for x, info := range check.untyped {
338                 if debug && isTyped(info.typ) {
339                         check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
340                         unreachable()
341                 }
342                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
343         }
344 }
345
346 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
347         assert(x != nil)
348         assert(typ != nil)
349         if mode == invalid {
350                 return // omit
351         }
352         if mode == constant_ {
353                 assert(val != nil)
354                 assert(typ == Typ[Invalid] || isConstType(typ))
355         }
356         if m := check.Types; m != nil {
357                 m[x] = TypeAndValue{mode, typ, val}
358         }
359 }
360
361 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
362         // f must be a (possibly parenthesized) identifier denoting a built-in
363         // (built-ins in package unsafe always produce a constant result and
364         // we don't record their signatures, so we don't see qualified idents
365         // here): record the signature for f and possible children.
366         for {
367                 check.recordTypeAndValue(f, builtin, sig, nil)
368                 switch p := f.(type) {
369                 case *syntax.Name:
370                         return // we're done
371                 case *syntax.ParenExpr:
372                         f = p.X
373                 default:
374                         unreachable()
375                 }
376         }
377 }
378
379 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
380         assert(x != nil)
381         if a[0] == nil || a[1] == nil {
382                 return
383         }
384         assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
385         if m := check.Types; m != nil {
386                 for {
387                         tv := m[x]
388                         assert(tv.Type != nil) // should have been recorded already
389                         pos := x.Pos()
390                         tv.Type = NewTuple(
391                                 NewVar(pos, check.pkg, "", a[0]),
392                                 NewVar(pos, check.pkg, "", a[1]),
393                         )
394                         m[x] = tv
395                         // if x is a parenthesized expression (p.X), update p.X
396                         p, _ := x.(*syntax.ParenExpr)
397                         if p == nil {
398                                 break
399                         }
400                         x = p.X
401                 }
402         }
403 }
404
405 func (check *Checker) recordInferred(call syntax.Expr, targs []Type, sig *Signature) {
406         assert(call != nil)
407         assert(sig != nil)
408         if m := check.Inferred; m != nil {
409                 m[call] = Inferred{targs, sig}
410         }
411 }
412
413 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
414         assert(id != nil)
415         if m := check.Defs; m != nil {
416                 m[id] = obj
417         }
418 }
419
420 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
421         assert(id != nil)
422         assert(obj != nil)
423         if m := check.Uses; m != nil {
424                 m[id] = obj
425         }
426 }
427
428 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
429         assert(node != nil)
430         assert(obj != nil)
431         if m := check.Implicits; m != nil {
432                 m[node] = obj
433         }
434 }
435
436 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
437         assert(obj != nil && (recv == nil || len(index) > 0))
438         check.recordUse(x.Sel, obj)
439         if m := check.Selections; m != nil {
440                 m[x] = &Selection{kind, recv, obj, index, indirect}
441         }
442 }
443
444 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
445         assert(node != nil)
446         assert(scope != nil)
447         if m := check.Scopes; m != nil {
448                 m[node] = scope
449         }
450 }