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