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