]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
all: REVERSE MERGE dev.typeparams (7cdfa49) into master
[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 dotImportKey describes a dot-imported object in the given scope.
78 type dotImportKey struct {
79         scope *Scope
80         obj   Object
81 }
82
83 // A Checker maintains the state of the type checker.
84 // It must be created with NewChecker.
85 type Checker struct {
86         // package information
87         // (initialized by NewChecker, valid for the life-time of checker)
88         conf *Config
89         pkg  *Package
90         *Info
91         version version                     // accepted language version
92         nextId  uint64                      // unique Id for type parameters (first valid Id is 1)
93         objMap  map[Object]*declInfo        // maps package-level objects and (non-interface) methods to declaration info
94         impMap  map[importKey]*Package      // maps (import path, source directory) to (complete or fake) package
95         posMap  map[*Interface][]syntax.Pos // maps interface types to lists of embedded interface positions
96         typMap  map[string]*Named           // maps an instantiated named type hash to a *Named type
97         pkgCnt  map[string]int              // counts number of imported packages with a given name (for better error messages)
98
99         // information collected during type-checking of a set of package files
100         // (initialized by Files, valid only for the duration of check.Files;
101         // maps and lists are allocated on demand)
102         files        []*syntax.File            // list of package files
103         imports      []*PkgName                // list of imported packages
104         dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
105
106         firstErr error                    // first error encountered
107         methods  map[*TypeName][]*Func    // maps package scope type names to associated non-blank (non-interface) methods
108         untyped  map[syntax.Expr]exprInfo // map of expressions without final type
109         delayed  []func()                 // stack of delayed action segments; segments are processed in FIFO order
110         finals   []func()                 // list of final actions; processed at the end of type-checking the current set of files
111         objPath  []Object                 // path of object dependencies during type inference (for cycle reporting)
112
113         // context within which the current object is type-checked
114         // (valid only for the duration of type-checking a specific object)
115         context
116
117         // debugging
118         indent int // indentation for tracing
119 }
120
121 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
122 func (check *Checker) addDeclDep(to Object) {
123         from := check.decl
124         if from == nil {
125                 return // not in a package-level init expression
126         }
127         if _, found := check.objMap[to]; !found {
128                 return // to is not a package-level object
129         }
130         from.addDep(to)
131 }
132
133 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
134         m := check.untyped
135         if m == nil {
136                 m = make(map[syntax.Expr]exprInfo)
137                 check.untyped = m
138         }
139         m[e] = exprInfo{lhs, mode, typ, val}
140 }
141
142 // later pushes f on to the stack of actions that will be processed later;
143 // either at the end of the current statement, or in case of a local constant
144 // or variable declaration, before the constant or variable is in scope
145 // (so that f still sees the scope before any new declarations).
146 func (check *Checker) later(f func()) {
147         check.delayed = append(check.delayed, f)
148 }
149
150 // atEnd adds f to the list of actions processed at the end
151 // of type-checking, before initialization order computation.
152 // Actions added by atEnd are processed after any actions
153 // added by later.
154 func (check *Checker) atEnd(f func()) {
155         check.finals = append(check.finals, f)
156 }
157
158 // push pushes obj onto the object path and returns its index in the path.
159 func (check *Checker) push(obj Object) int {
160         check.objPath = append(check.objPath, obj)
161         return len(check.objPath) - 1
162 }
163
164 // pop pops and returns the topmost object from the object path.
165 func (check *Checker) pop() Object {
166         i := len(check.objPath) - 1
167         obj := check.objPath[i]
168         check.objPath[i] = nil
169         check.objPath = check.objPath[:i]
170         return obj
171 }
172
173 // NewChecker returns a new Checker instance for a given package.
174 // Package files may be added incrementally via checker.Files.
175 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
176         // make sure we have a configuration
177         if conf == nil {
178                 conf = new(Config)
179         }
180
181         // make sure we have an info struct
182         if info == nil {
183                 info = new(Info)
184         }
185
186         version, err := parseGoVersion(conf.GoVersion)
187         if err != nil {
188                 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
189         }
190
191         return &Checker{
192                 conf:    conf,
193                 pkg:     pkg,
194                 Info:    info,
195                 version: version,
196                 nextId:  1,
197                 objMap:  make(map[Object]*declInfo),
198                 impMap:  make(map[importKey]*Package),
199                 posMap:  make(map[*Interface][]syntax.Pos),
200                 typMap:  make(map[string]*Named),
201                 pkgCnt:  make(map[string]int),
202         }
203 }
204
205 // initFiles initializes the files-specific portion of checker.
206 // The provided files must all belong to the same package.
207 func (check *Checker) initFiles(files []*syntax.File) {
208         // start with a clean slate (check.Files may be called multiple times)
209         check.files = nil
210         check.imports = nil
211         check.dotImportMap = nil
212
213         check.firstErr = nil
214         check.methods = nil
215         check.untyped = nil
216         check.delayed = nil
217         check.finals = nil
218
219         // determine package name and collect valid files
220         pkg := check.pkg
221         for _, file := range files {
222                 switch name := file.PkgName.Value; pkg.name {
223                 case "":
224                         if name != "_" {
225                                 pkg.name = name
226                         } else {
227                                 check.errorf(file.PkgName, "invalid package name _")
228                         }
229                         fallthrough
230
231                 case name:
232                         check.files = append(check.files, file)
233
234                 default:
235                         check.errorf(file, "package %s; expected %s", name, pkg.name)
236                         // ignore this file
237                 }
238         }
239 }
240
241 // A bailout panic is used for early termination.
242 type bailout struct{}
243
244 func (check *Checker) handleBailout(err *error) {
245         switch p := recover().(type) {
246         case nil, bailout:
247                 // normal return or early exit
248                 *err = check.firstErr
249         default:
250                 // re-panic
251                 panic(p)
252         }
253 }
254
255 // Files checks the provided files as part of the checker's package.
256 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
257
258 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
259
260 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
261         if check.conf.FakeImportC && check.conf.go115UsesCgo {
262                 return errBadCgo
263         }
264
265         defer check.handleBailout(&err)
266
267         print := func(msg string) {
268                 if check.conf.Trace {
269                         fmt.Println(msg)
270                 }
271         }
272
273         print("== initFiles ==")
274         check.initFiles(files)
275
276         print("== collectObjects ==")
277         check.collectObjects()
278
279         print("== packageObjects ==")
280         check.packageObjects()
281
282         print("== processDelayed ==")
283         check.processDelayed(0) // incl. all functions
284         check.processFinals()
285
286         print("== initOrder ==")
287         check.initOrder()
288
289         if !check.conf.DisableUnusedImportCheck {
290                 print("== unusedImports ==")
291                 check.unusedImports()
292         }
293         // no longer needed - release memory
294         check.imports = nil
295         check.dotImportMap = nil
296
297         print("== recordUntyped ==")
298         check.recordUntyped()
299
300         if check.Info != nil {
301                 print("== sanitizeInfo ==")
302                 sanitizeInfo(check.Info)
303         }
304
305         check.pkg.complete = true
306
307         // TODO(gri) There's more memory we should release at this point.
308
309         return
310 }
311
312 // processDelayed processes all delayed actions pushed after top.
313 func (check *Checker) processDelayed(top int) {
314         // If each delayed action pushes a new action, the
315         // stack will continue to grow during this loop.
316         // However, it is only processing functions (which
317         // are processed in a delayed fashion) that may
318         // add more actions (such as nested functions), so
319         // this is a sufficiently bounded process.
320         for i := top; i < len(check.delayed); i++ {
321                 check.delayed[i]() // may append to check.delayed
322         }
323         assert(top <= len(check.delayed)) // stack must not have shrunk
324         check.delayed = check.delayed[:top]
325 }
326
327 func (check *Checker) processFinals() {
328         n := len(check.finals)
329         for _, f := range check.finals {
330                 f() // must not append to check.finals
331         }
332         if len(check.finals) != n {
333                 panic("internal error: final action list grew")
334         }
335 }
336
337 func (check *Checker) recordUntyped() {
338         if !debug && check.Types == nil {
339                 return // nothing to do
340         }
341
342         for x, info := range check.untyped {
343                 if debug && isTyped(info.typ) {
344                         check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
345                         unreachable()
346                 }
347                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
348         }
349 }
350
351 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
352         assert(x != nil)
353         assert(typ != nil)
354         if mode == invalid {
355                 return // omit
356         }
357         if mode == constant_ {
358                 assert(val != nil)
359                 assert(typ == Typ[Invalid] || isConstType(typ))
360         }
361         if m := check.Types; m != nil {
362                 m[x] = TypeAndValue{mode, typ, val}
363         }
364 }
365
366 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
367         // f must be a (possibly parenthesized) identifier denoting a built-in
368         // (built-ins in package unsafe always produce a constant result and
369         // we don't record their signatures, so we don't see qualified idents
370         // here): record the signature for f and possible children.
371         for {
372                 check.recordTypeAndValue(f, builtin, sig, nil)
373                 switch p := f.(type) {
374                 case *syntax.Name:
375                         return // we're done
376                 case *syntax.ParenExpr:
377                         f = p.X
378                 default:
379                         unreachable()
380                 }
381         }
382 }
383
384 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
385         assert(x != nil)
386         if a[0] == nil || a[1] == nil {
387                 return
388         }
389         assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
390         if m := check.Types; m != nil {
391                 for {
392                         tv := m[x]
393                         assert(tv.Type != nil) // should have been recorded already
394                         pos := x.Pos()
395                         tv.Type = NewTuple(
396                                 NewVar(pos, check.pkg, "", a[0]),
397                                 NewVar(pos, check.pkg, "", a[1]),
398                         )
399                         m[x] = tv
400                         // if x is a parenthesized expression (p.X), update p.X
401                         p, _ := x.(*syntax.ParenExpr)
402                         if p == nil {
403                                 break
404                         }
405                         x = p.X
406                 }
407         }
408 }
409
410 func (check *Checker) recordInferred(call syntax.Expr, targs []Type, sig *Signature) {
411         assert(call != nil)
412         assert(sig != nil)
413         if m := check.Inferred; m != nil {
414                 m[call] = Inferred{targs, sig}
415         }
416 }
417
418 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
419         assert(id != nil)
420         if m := check.Defs; m != nil {
421                 m[id] = obj
422         }
423 }
424
425 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
426         assert(id != nil)
427         assert(obj != nil)
428         if m := check.Uses; m != nil {
429                 m[id] = obj
430         }
431 }
432
433 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
434         assert(node != nil)
435         assert(obj != nil)
436         if m := check.Implicits; m != nil {
437                 m[node] = obj
438         }
439 }
440
441 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
442         assert(obj != nil && (recv == nil || len(index) > 0))
443         check.recordUse(x.Sel, obj)
444         if m := check.Selections; m != nil {
445                 m[x] = &Selection{kind, recv, obj, index, indirect}
446         }
447 }
448
449 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
450         assert(node != nil)
451         assert(scope != nil)
452         if m := check.Scopes; m != nil {
453                 m[node] = scope
454         }
455 }