]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
go/types: fix version downgrade bug without Config.GoVersion
[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         posVers       map[*syntax.PosBase]version // Pos -> Go version mapping
120         imports       []*PkgName                  // list of imported packages
121         dotImportMap  map[dotImportKey]*PkgName   // maps dot-imported objects to the package they were dot-imported through
122         recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
123         brokenAliases map[*TypeName]bool          // set of aliases with broken (not yet determined) types
124         unionTypeSets map[*Union]*_TypeSet        // computed type sets for union types
125         mono          monoGraph                   // graph for detecting non-monomorphizable instantiation loops
126
127         firstErr error                    // first error encountered
128         methods  map[*TypeName][]*Func    // maps package scope type names to associated non-blank (non-interface) methods
129         untyped  map[syntax.Expr]exprInfo // map of expressions without final type
130         delayed  []action                 // stack of delayed action segments; segments are processed in FIFO order
131         objPath  []Object                 // path of object dependencies during type inference (for cycle reporting)
132         cleaners []cleaner                // list of types that may need a final cleanup at the end of type-checking
133
134         // environment within which the current object is type-checked (valid only
135         // for the duration of type-checking a specific object)
136         environment
137
138         // debugging
139         indent int // indentation for tracing
140 }
141
142 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
143 func (check *Checker) addDeclDep(to Object) {
144         from := check.decl
145         if from == nil {
146                 return // not in a package-level init expression
147         }
148         if _, found := check.objMap[to]; !found {
149                 return // to is not a package-level object
150         }
151         from.addDep(to)
152 }
153
154 // brokenAlias records that alias doesn't have a determined type yet.
155 // It also sets alias.typ to Typ[Invalid].
156 func (check *Checker) brokenAlias(alias *TypeName) {
157         if check.brokenAliases == nil {
158                 check.brokenAliases = make(map[*TypeName]bool)
159         }
160         check.brokenAliases[alias] = true
161         alias.typ = Typ[Invalid]
162 }
163
164 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
165 func (check *Checker) validAlias(alias *TypeName, typ Type) {
166         delete(check.brokenAliases, alias)
167         alias.typ = typ
168 }
169
170 // isBrokenAlias reports whether alias doesn't have a determined type yet.
171 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
172         return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
173 }
174
175 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
176         m := check.untyped
177         if m == nil {
178                 m = make(map[syntax.Expr]exprInfo)
179                 check.untyped = m
180         }
181         m[e] = exprInfo{lhs, mode, typ, val}
182 }
183
184 // later pushes f on to the stack of actions that will be processed later;
185 // either at the end of the current statement, or in case of a local constant
186 // or variable declaration, before the constant or variable is in scope
187 // (so that f still sees the scope before any new declarations).
188 // later returns the pushed action so one can provide a description
189 // via action.describef for debugging, if desired.
190 func (check *Checker) later(f func()) *action {
191         i := len(check.delayed)
192         check.delayed = append(check.delayed, action{f: f})
193         return &check.delayed[i]
194 }
195
196 // push pushes obj onto the object path and returns its index in the path.
197 func (check *Checker) push(obj Object) int {
198         check.objPath = append(check.objPath, obj)
199         return len(check.objPath) - 1
200 }
201
202 // pop pops and returns the topmost object from the object path.
203 func (check *Checker) pop() Object {
204         i := len(check.objPath) - 1
205         obj := check.objPath[i]
206         check.objPath[i] = nil
207         check.objPath = check.objPath[:i]
208         return obj
209 }
210
211 type cleaner interface {
212         cleanup()
213 }
214
215 // needsCleanup records objects/types that implement the cleanup method
216 // which will be called at the end of type-checking.
217 func (check *Checker) needsCleanup(c cleaner) {
218         check.cleaners = append(check.cleaners, c)
219 }
220
221 // NewChecker returns a new Checker instance for a given package.
222 // Package files may be added incrementally via checker.Files.
223 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
224         // make sure we have a configuration
225         if conf == nil {
226                 conf = new(Config)
227         }
228
229         // make sure we have an info struct
230         if info == nil {
231                 info = new(Info)
232         }
233
234         version, err := parseGoVersion(conf.GoVersion)
235         if err != nil {
236                 panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
237         }
238
239         return &Checker{
240                 conf:    conf,
241                 ctxt:    conf.Context,
242                 pkg:     pkg,
243                 Info:    info,
244                 version: version,
245                 objMap:  make(map[Object]*declInfo),
246                 impMap:  make(map[importKey]*Package),
247         }
248 }
249
250 // initFiles initializes the files-specific portion of checker.
251 // The provided files must all belong to the same package.
252 func (check *Checker) initFiles(files []*syntax.File) {
253         // start with a clean slate (check.Files may be called multiple times)
254         check.files = nil
255         check.imports = nil
256         check.dotImportMap = nil
257
258         check.firstErr = nil
259         check.methods = nil
260         check.untyped = nil
261         check.delayed = nil
262         check.objPath = nil
263         check.cleaners = nil
264
265         // determine package name and collect valid files
266         pkg := check.pkg
267         for _, file := range files {
268                 switch name := file.PkgName.Value; pkg.name {
269                 case "":
270                         if name != "_" {
271                                 pkg.name = name
272                         } else {
273                                 check.error(file.PkgName, BlankPkgName, "invalid package name _")
274                         }
275                         fallthrough
276
277                 case name:
278                         check.files = append(check.files, file)
279
280                 default:
281                         check.errorf(file, MismatchedPkgName, "package %s; expected %s", name, pkg.name)
282                         // ignore this file
283                 }
284         }
285
286         for _, file := range check.files {
287                 v, _ := parseGoVersion(file.GoVersion)
288                 if v.major > 0 {
289                         if v.equal(check.version) {
290                                 continue
291                         }
292                         // Go 1.21 introduced the feature of setting the go.mod
293                         // go line to an early version of Go and allowing //go:build lines
294                         // to “upgrade” the Go version in a given file.
295                         // We can do that backwards compatibly.
296                         // Go 1.21 also introduced the feature of allowing //go:build lines
297                         // to “downgrade” the Go version in a given file.
298                         // That can't be done compatibly in general, since before the
299                         // build lines were ignored and code got the module's Go version.
300                         // To work around this, downgrades are only allowed when the
301                         // module's Go version is Go 1.21 or later.
302                         // If there is no check.version, then we don't really know what Go version to apply.
303                         // Legacy tools may do this, and they historically have accepted everything.
304                         // Preserve that behavior by ignoring //go:build constraints entirely in that case.
305                         if (v.before(check.version) && check.version.before(version{1, 21})) || check.version.equal(version{0, 0}) {
306                                 continue
307                         }
308                         if check.posVers == nil {
309                                 check.posVers = make(map[*syntax.PosBase]version)
310                         }
311                         check.posVers[base(file.Pos())] = v
312                 }
313         }
314 }
315
316 // A bailout panic is used for early termination.
317 type bailout struct{}
318
319 func (check *Checker) handleBailout(err *error) {
320         switch p := recover().(type) {
321         case nil, bailout:
322                 // normal return or early exit
323                 *err = check.firstErr
324         default:
325                 // re-panic
326                 panic(p)
327         }
328 }
329
330 // Files checks the provided files as part of the checker's package.
331 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
332
333 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
334
335 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
336         if check.conf.FakeImportC && check.conf.go115UsesCgo {
337                 return errBadCgo
338         }
339
340         defer check.handleBailout(&err)
341
342         print := func(msg string) {
343                 if check.conf.Trace {
344                         fmt.Println()
345                         fmt.Println(msg)
346                 }
347         }
348
349         print("== initFiles ==")
350         check.initFiles(files)
351
352         print("== collectObjects ==")
353         check.collectObjects()
354
355         print("== packageObjects ==")
356         check.packageObjects()
357
358         print("== processDelayed ==")
359         check.processDelayed(0) // incl. all functions
360
361         print("== cleanup ==")
362         check.cleanup()
363
364         print("== initOrder ==")
365         check.initOrder()
366
367         if !check.conf.DisableUnusedImportCheck {
368                 print("== unusedImports ==")
369                 check.unusedImports()
370         }
371
372         print("== recordUntyped ==")
373         check.recordUntyped()
374
375         if check.firstErr == nil {
376                 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
377                 check.monomorph()
378         }
379
380         check.pkg.complete = true
381
382         // no longer needed - release memory
383         check.imports = nil
384         check.dotImportMap = nil
385         check.pkgPathMap = nil
386         check.seenPkgMap = nil
387         check.recvTParamMap = nil
388         check.brokenAliases = nil
389         check.unionTypeSets = nil
390         check.ctxt = nil
391
392         // TODO(gri) There's more memory we should release at this point.
393
394         return
395 }
396
397 // processDelayed processes all delayed actions pushed after top.
398 func (check *Checker) processDelayed(top int) {
399         // If each delayed action pushes a new action, the
400         // stack will continue to grow during this loop.
401         // However, it is only processing functions (which
402         // are processed in a delayed fashion) that may
403         // add more actions (such as nested functions), so
404         // this is a sufficiently bounded process.
405         for i := top; i < len(check.delayed); i++ {
406                 a := &check.delayed[i]
407                 if check.conf.Trace {
408                         if a.desc != nil {
409                                 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
410                         } else {
411                                 check.trace(nopos, "-- delayed %p", a.f)
412                         }
413                 }
414                 a.f() // may append to check.delayed
415                 if check.conf.Trace {
416                         fmt.Println()
417                 }
418         }
419         assert(top <= len(check.delayed)) // stack must not have shrunk
420         check.delayed = check.delayed[:top]
421 }
422
423 // cleanup runs cleanup for all collected cleaners.
424 func (check *Checker) cleanup() {
425         // Don't use a range clause since Named.cleanup may add more cleaners.
426         for i := 0; i < len(check.cleaners); i++ {
427                 check.cleaners[i].cleanup()
428         }
429         check.cleaners = nil
430 }
431
432 func (check *Checker) record(x *operand) {
433         // convert x into a user-friendly set of values
434         // TODO(gri) this code can be simplified
435         var typ Type
436         var val constant.Value
437         switch x.mode {
438         case invalid:
439                 typ = Typ[Invalid]
440         case novalue:
441                 typ = (*Tuple)(nil)
442         case constant_:
443                 typ = x.typ
444                 val = x.val
445         default:
446                 typ = x.typ
447         }
448         assert(x.expr != nil && typ != nil)
449
450         if isUntyped(typ) {
451                 // delay type and value recording until we know the type
452                 // or until the end of type checking
453                 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
454         } else {
455                 check.recordTypeAndValue(x.expr, x.mode, typ, val)
456         }
457 }
458
459 func (check *Checker) recordUntyped() {
460         if !debug && !check.recordTypes() {
461                 return // nothing to do
462         }
463
464         for x, info := range check.untyped {
465                 if debug && isTyped(info.typ) {
466                         check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
467                         unreachable()
468                 }
469                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
470         }
471 }
472
473 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
474         assert(x != nil)
475         assert(typ != nil)
476         if mode == invalid {
477                 return // omit
478         }
479         if mode == constant_ {
480                 assert(val != nil)
481                 // We check allBasic(typ, IsConstType) here as constant expressions may be
482                 // recorded as type parameters.
483                 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
484         }
485         if m := check.Types; m != nil {
486                 m[x] = TypeAndValue{mode, typ, val}
487         }
488         if check.StoreTypesInSyntax {
489                 tv := TypeAndValue{mode, typ, val}
490                 stv := syntax.TypeAndValue{Type: typ, Value: val}
491                 if tv.IsVoid() {
492                         stv.SetIsVoid()
493                 }
494                 if tv.IsType() {
495                         stv.SetIsType()
496                 }
497                 if tv.IsBuiltin() {
498                         stv.SetIsBuiltin()
499                 }
500                 if tv.IsValue() {
501                         stv.SetIsValue()
502                 }
503                 if tv.IsNil() {
504                         stv.SetIsNil()
505                 }
506                 if tv.Addressable() {
507                         stv.SetAddressable()
508                 }
509                 if tv.Assignable() {
510                         stv.SetAssignable()
511                 }
512                 if tv.HasOk() {
513                         stv.SetHasOk()
514                 }
515                 x.SetTypeInfo(stv)
516         }
517 }
518
519 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
520         // f must be a (possibly parenthesized, possibly qualified)
521         // identifier denoting a built-in (including unsafe's non-constant
522         // functions Add and Slice): record the signature for f and possible
523         // children.
524         for {
525                 check.recordTypeAndValue(f, builtin, sig, nil)
526                 switch p := f.(type) {
527                 case *syntax.Name, *syntax.SelectorExpr:
528                         return // we're done
529                 case *syntax.ParenExpr:
530                         f = p.X
531                 default:
532                         unreachable()
533                 }
534         }
535 }
536
537 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
538 // (and therefore has tuple type).
539 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand) {
540         assert(x != nil)
541         assert(len(a) == 2)
542         if a[0].mode == invalid {
543                 return
544         }
545         t0, t1 := a[0].typ, a[1].typ
546         assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
547         if m := check.Types; m != nil {
548                 for {
549                         tv := m[x]
550                         assert(tv.Type != nil) // should have been recorded already
551                         pos := x.Pos()
552                         tv.Type = NewTuple(
553                                 NewVar(pos, check.pkg, "", t0),
554                                 NewVar(pos, check.pkg, "", t1),
555                         )
556                         m[x] = tv
557                         // if x is a parenthesized expression (p.X), update p.X
558                         p, _ := x.(*syntax.ParenExpr)
559                         if p == nil {
560                                 break
561                         }
562                         x = p.X
563                 }
564         }
565         if check.StoreTypesInSyntax {
566                 // Note: this loop is duplicated because the type of tv is different.
567                 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
568                 for {
569                         tv := x.GetTypeInfo()
570                         assert(tv.Type != nil) // should have been recorded already
571                         pos := x.Pos()
572                         tv.Type = NewTuple(
573                                 NewVar(pos, check.pkg, "", t0),
574                                 NewVar(pos, check.pkg, "", t1),
575                         )
576                         x.SetTypeInfo(tv)
577                         p, _ := x.(*syntax.ParenExpr)
578                         if p == nil {
579                                 break
580                         }
581                         x = p.X
582                 }
583         }
584 }
585
586 // recordInstance records instantiation information into check.Info, if the
587 // Instances map is non-nil. The given expr must be an ident, selector, or
588 // index (list) expr with ident or selector operand.
589 //
590 // TODO(rfindley): the expr parameter is fragile. See if we can access the
591 // instantiated identifier in some other way.
592 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
593         ident := instantiatedIdent(expr)
594         assert(ident != nil)
595         assert(typ != nil)
596         if m := check.Instances; m != nil {
597                 m[ident] = Instance{newTypeList(targs), typ}
598         }
599 }
600
601 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
602         var selOrIdent syntax.Expr
603         switch e := expr.(type) {
604         case *syntax.IndexExpr:
605                 selOrIdent = e.X
606         case *syntax.SelectorExpr, *syntax.Name:
607                 selOrIdent = e
608         }
609         switch x := selOrIdent.(type) {
610         case *syntax.Name:
611                 return x
612         case *syntax.SelectorExpr:
613                 return x.Sel
614         }
615         panic("instantiated ident not found")
616 }
617
618 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
619         assert(id != nil)
620         if m := check.Defs; m != nil {
621                 m[id] = obj
622         }
623 }
624
625 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
626         assert(id != nil)
627         assert(obj != nil)
628         if m := check.Uses; m != nil {
629                 m[id] = obj
630         }
631 }
632
633 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
634         assert(node != nil)
635         assert(obj != nil)
636         if m := check.Implicits; m != nil {
637                 m[node] = obj
638         }
639 }
640
641 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
642         assert(obj != nil && (recv == nil || len(index) > 0))
643         check.recordUse(x.Sel, obj)
644         if m := check.Selections; m != nil {
645                 m[x] = &Selection{kind, recv, obj, index, indirect}
646         }
647 }
648
649 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
650         assert(node != nil)
651         assert(scope != nil)
652         if m := check.Scopes; m != nil {
653                 m[node] = scope
654         }
655 }