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