]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
go/types: use nopos instead of token.NoPos to match types2
[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         . "internal/types/errors"
15 )
16
17 // nopos indicates an unknown position
18 var nopos syntax.Pos
19
20 // debugging/development support
21 const debug = false // leave on during development
22
23 // exprInfo stores information about an untyped expression.
24 type exprInfo struct {
25         isLhs bool // expression is lhs operand of a shift with delayed type-check
26         mode  operandMode
27         typ   *Basic
28         val   constant.Value // constant value; or nil (if not a constant)
29 }
30
31 // An environment represents the environment within which an object is
32 // type-checked.
33 type environment struct {
34         decl          *declInfo                 // package-level declaration whose init expression/function body is checked
35         scope         *Scope                    // top-most scope for lookups
36         pos           syntax.Pos                // if valid, identifiers are looked up as if at position pos (used by Eval)
37         iota          constant.Value            // value of iota in a constant declaration; nil otherwise
38         errpos        syntax.Pos                // if valid, identifier position of a constant with inherited initializer
39         inTParamList  bool                      // set if inside a type parameter list
40         sig           *Signature                // function signature if inside a function; nil otherwise
41         isPanic       map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
42         hasLabel      bool                      // set if a function makes use of labels (only ~1% of functions); unused outside functions
43         hasCallOrRecv bool                      // set if an expression contains a function call or channel receive operation
44 }
45
46 // lookup looks up name in the current environment and returns the matching object, or nil.
47 func (env *environment) lookup(name string) Object {
48         _, obj := env.scope.LookupParent(name, env.pos)
49         return obj
50 }
51
52 // An importKey identifies an imported package by import path and source directory
53 // (directory containing the file containing the import). In practice, the directory
54 // may always be the same, or may not matter. Given an (import path, directory), an
55 // importer must always return the same package (but given two different import paths,
56 // an importer may still return the same package by mapping them to the same package
57 // paths).
58 type importKey struct {
59         path, dir string
60 }
61
62 // A dotImportKey describes a dot-imported object in the given scope.
63 type dotImportKey struct {
64         scope *Scope
65         name  string
66 }
67
68 // An action describes a (delayed) action.
69 type action struct {
70         f    func()      // action to be executed
71         desc *actionDesc // action description; may be nil, requires debug to be set
72 }
73
74 // If debug is set, describef sets a printf-formatted description for action a.
75 // Otherwise, it is a no-op.
76 func (a *action) describef(pos poser, format string, args ...interface{}) {
77         if debug {
78                 a.desc = &actionDesc{pos, format, args}
79         }
80 }
81
82 // An actionDesc provides information on an action.
83 // For debugging only.
84 type actionDesc struct {
85         pos    poser
86         format string
87         args   []interface{}
88 }
89
90 // A Checker maintains the state of the type checker.
91 // It must be created with NewChecker.
92 type Checker struct {
93         // package information
94         // (initialized by NewChecker, valid for the life-time of checker)
95         conf *Config
96         ctxt *Context // context for de-duplicating instances
97         pkg  *Package
98         *Info
99         version version                // accepted language version
100         nextID  uint64                 // unique Id for type parameters (first valid Id is 1)
101         objMap  map[Object]*declInfo   // maps package-level objects and (non-interface) methods to declaration info
102         impMap  map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
103         valids  instanceLookup         // valid *Named (incl. instantiated) types per the validType check
104
105         // pkgPathMap maps package names to the set of distinct import paths we've
106         // seen for that name, anywhere in the import graph. It is used for
107         // disambiguating package names in error messages.
108         //
109         // pkgPathMap is allocated lazily, so that we don't pay the price of building
110         // it on the happy path. seenPkgMap tracks the packages that we've already
111         // walked.
112         pkgPathMap map[string]map[string]bool
113         seenPkgMap map[*Package]bool
114
115         // information collected during type-checking of a set of package files
116         // (initialized by Files, valid only for the duration of check.Files;
117         // maps and lists are allocated on demand)
118         files         []*syntax.File              // list of package files
119         imports       []*PkgName                  // list of imported packages
120         dotImportMap  map[dotImportKey]*PkgName   // maps dot-imported objects to the package they were dot-imported through
121         recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
122         brokenAliases map[*TypeName]bool          // set of aliases with broken (not yet determined) types
123         unionTypeSets map[*Union]*_TypeSet        // computed type sets for union types
124         mono          monoGraph                   // graph for detecting non-monomorphizable instantiation loops
125
126         firstErr error                    // first error encountered
127         methods  map[*TypeName][]*Func    // maps package scope type names to associated non-blank (non-interface) methods
128         untyped  map[syntax.Expr]exprInfo // map of expressions without final type
129         delayed  []action                 // stack of delayed action segments; segments are processed in FIFO order
130         objPath  []Object                 // path of object dependencies during type inference (for cycle reporting)
131         cleaners []cleaner                // list of types that may need a final cleanup at the end of type-checking
132
133         // environment within which the current object is type-checked (valid only
134         // for the duration of type-checking a specific object)
135         environment
136
137         // debugging
138         indent int // indentation for tracing
139 }
140
141 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
142 func (check *Checker) addDeclDep(to Object) {
143         from := check.decl
144         if from == nil {
145                 return // not in a package-level init expression
146         }
147         if _, found := check.objMap[to]; !found {
148                 return // to is not a package-level object
149         }
150         from.addDep(to)
151 }
152
153 // brokenAlias records that alias doesn't have a determined type yet.
154 // It also sets alias.typ to Typ[Invalid].
155 func (check *Checker) brokenAlias(alias *TypeName) {
156         if check.brokenAliases == nil {
157                 check.brokenAliases = make(map[*TypeName]bool)
158         }
159         check.brokenAliases[alias] = true
160         alias.typ = Typ[Invalid]
161 }
162
163 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
164 func (check *Checker) validAlias(alias *TypeName, typ Type) {
165         delete(check.brokenAliases, alias)
166         alias.typ = typ
167 }
168
169 // isBrokenAlias reports whether alias doesn't have a determined type yet.
170 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
171         return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
172 }
173
174 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
175         m := check.untyped
176         if m == nil {
177                 m = make(map[syntax.Expr]exprInfo)
178                 check.untyped = m
179         }
180         m[e] = exprInfo{lhs, mode, typ, val}
181 }
182
183 // later pushes f on to the stack of actions that will be processed later;
184 // either at the end of the current statement, or in case of a local constant
185 // or variable declaration, before the constant or variable is in scope
186 // (so that f still sees the scope before any new declarations).
187 // later returns the pushed action so one can provide a description
188 // via action.describef for debugging, if desired.
189 func (check *Checker) later(f func()) *action {
190         i := len(check.delayed)
191         check.delayed = append(check.delayed, action{f: f})
192         return &check.delayed[i]
193 }
194
195 // push pushes obj onto the object path and returns its index in the path.
196 func (check *Checker) push(obj Object) int {
197         check.objPath = append(check.objPath, obj)
198         return len(check.objPath) - 1
199 }
200
201 // pop pops and returns the topmost object from the object path.
202 func (check *Checker) pop() Object {
203         i := len(check.objPath) - 1
204         obj := check.objPath[i]
205         check.objPath[i] = nil
206         check.objPath = check.objPath[:i]
207         return obj
208 }
209
210 type cleaner interface {
211         cleanup()
212 }
213
214 // needsCleanup records objects/types that implement the cleanup method
215 // which will be called at the end of type-checking.
216 func (check *Checker) needsCleanup(c cleaner) {
217         check.cleaners = append(check.cleaners, c)
218 }
219
220 // NewChecker returns a new Checker instance for a given package.
221 // Package files may be added incrementally via checker.Files.
222 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
223         // make sure we have a configuration
224         if conf == nil {
225                 conf = new(Config)
226         }
227
228         // make sure we have an info struct
229         if info == nil {
230                 info = new(Info)
231         }
232
233         version, err := parseGoVersion(conf.GoVersion)
234         if err != nil {
235                 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
236         }
237
238         return &Checker{
239                 conf:    conf,
240                 ctxt:    conf.Context,
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 []*syntax.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.PkgName.Value; pkg.name {
268                 case "":
269                         if name != "_" {
270                                 pkg.name = name
271                         } else {
272                                 check.error(file.PkgName, BlankPkgName, "invalid package name _")
273                         }
274                         fallthrough
275
276                 case name:
277                         check.files = append(check.files, file)
278
279                 default:
280                         check.errorf(file, 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 []*syntax.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 []*syntax.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(gri) 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(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.recordTypes() {
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", posFor(x), 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 syntax.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         if check.StoreTypesInSyntax {
459                 tv := TypeAndValue{mode, typ, val}
460                 stv := syntax.TypeAndValue{Type: typ, Value: val}
461                 if tv.IsVoid() {
462                         stv.SetIsVoid()
463                 }
464                 if tv.IsType() {
465                         stv.SetIsType()
466                 }
467                 if tv.IsBuiltin() {
468                         stv.SetIsBuiltin()
469                 }
470                 if tv.IsValue() {
471                         stv.SetIsValue()
472                 }
473                 if tv.IsNil() {
474                         stv.SetIsNil()
475                 }
476                 if tv.Addressable() {
477                         stv.SetAddressable()
478                 }
479                 if tv.Assignable() {
480                         stv.SetAssignable()
481                 }
482                 if tv.HasOk() {
483                         stv.SetHasOk()
484                 }
485                 x.SetTypeInfo(stv)
486         }
487 }
488
489 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
490         // f must be a (possibly parenthesized, possibly qualified)
491         // identifier denoting a built-in (including unsafe's non-constant
492         // functions Add and Slice): record the signature for f and possible
493         // children.
494         for {
495                 check.recordTypeAndValue(f, builtin, sig, nil)
496                 switch p := f.(type) {
497                 case *syntax.Name, *syntax.SelectorExpr:
498                         return // we're done
499                 case *syntax.ParenExpr:
500                         f = p.X
501                 default:
502                         unreachable()
503                 }
504         }
505 }
506
507 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
508         assert(x != nil)
509         if a[0] == nil || a[1] == nil {
510                 return
511         }
512         assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
513         if m := check.Types; m != nil {
514                 for {
515                         tv := m[x]
516                         assert(tv.Type != nil) // should have been recorded already
517                         pos := x.Pos()
518                         tv.Type = NewTuple(
519                                 NewVar(pos, check.pkg, "", a[0]),
520                                 NewVar(pos, check.pkg, "", a[1]),
521                         )
522                         m[x] = tv
523                         p, _ := x.(*syntax.ParenExpr)
524                         if p == nil {
525                                 break
526                         }
527                         x = p.X
528                 }
529         }
530         if check.StoreTypesInSyntax {
531                 // Note: this loop is duplicated because the type of tv is different.
532                 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
533                 for {
534                         tv := x.GetTypeInfo()
535                         assert(tv.Type != nil) // should have been recorded already
536                         pos := x.Pos()
537                         tv.Type = NewTuple(
538                                 NewVar(pos, check.pkg, "", a[0]),
539                                 NewVar(pos, check.pkg, "", a[1]),
540                         )
541                         x.SetTypeInfo(tv)
542                         p, _ := x.(*syntax.ParenExpr)
543                         if p == nil {
544                                 break
545                         }
546                         x = p.X
547                 }
548         }
549 }
550
551 // recordInstance records instantiation information into check.Info, if the
552 // Instances map is non-nil. The given expr must be an ident, selector, or
553 // index (list) expr with ident or selector operand.
554 //
555 // TODO(rfindley): the expr parameter is fragile. See if we can access the
556 // instantiated identifier in some other way.
557 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
558         ident := instantiatedIdent(expr)
559         assert(ident != nil)
560         assert(typ != nil)
561         if m := check.Instances; m != nil {
562                 m[ident] = Instance{newTypeList(targs), typ}
563         }
564 }
565
566 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
567         var selOrIdent syntax.Expr
568         switch e := expr.(type) {
569         case *syntax.IndexExpr:
570                 selOrIdent = e.X
571         case *syntax.SelectorExpr, *syntax.Name:
572                 selOrIdent = e
573         }
574         switch x := selOrIdent.(type) {
575         case *syntax.Name:
576                 return x
577         case *syntax.SelectorExpr:
578                 return x.Sel
579         }
580         panic("instantiated ident not found")
581 }
582
583 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
584         assert(id != nil)
585         if m := check.Defs; m != nil {
586                 m[id] = obj
587         }
588 }
589
590 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
591         assert(id != nil)
592         assert(obj != nil)
593         if m := check.Uses; m != nil {
594                 m[id] = obj
595         }
596 }
597
598 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
599         assert(node != nil)
600         assert(obj != nil)
601         if m := check.Implicits; m != nil {
602                 m[node] = obj
603         }
604 }
605
606 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
607         assert(obj != nil && (recv == nil || len(index) > 0))
608         check.recordUse(x.Sel, obj)
609         if m := check.Selections; m != nil {
610                 m[x] = &Selection{kind, recv, obj, index, indirect}
611         }
612 }
613
614 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
615         assert(node != nil)
616         assert(scope != nil)
617         if m := check.Scopes; m != nil {
618                 m[node] = scope
619         }
620 }