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