]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check.go
go/types, types2: move posVers field into group of package-specific fields (cleanup)
[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/goversion"
15         . "internal/types/errors"
16 )
17
18 // nopos indicates an unknown position
19 var nopos syntax.Pos
20
21 // debugging/development support
22 const debug = false // leave on during development
23
24 // exprInfo stores information about an untyped expression.
25 type exprInfo struct {
26         isLhs bool // expression is lhs operand of a shift with delayed type-check
27         mode  operandMode
28         typ   *Basic
29         val   constant.Value // constant value; or nil (if not a constant)
30 }
31
32 // An environment represents the environment within which an object is
33 // type-checked.
34 type environment struct {
35         decl          *declInfo                 // package-level declaration whose init expression/function body is checked
36         scope         *Scope                    // top-most scope for lookups
37         pos           syntax.Pos                // if valid, identifiers are looked up as if at position pos (used by Eval)
38         iota          constant.Value            // value of iota in a constant declaration; nil otherwise
39         errpos        syntax.Pos                // if valid, identifier position of a constant with inherited initializer
40         inTParamList  bool                      // set if inside a type parameter list
41         sig           *Signature                // function signature if inside a function; nil otherwise
42         isPanic       map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
43         hasLabel      bool                      // set if a function makes use of labels (only ~1% of functions); unused outside functions
44         hasCallOrRecv bool                      // set if an expression contains a function call or channel receive operation
45 }
46
47 // lookup looks up name in the current environment and returns the matching object, or nil.
48 func (env *environment) lookup(name string) Object {
49         _, obj := env.scope.LookupParent(name, env.pos)
50         return obj
51 }
52
53 // An importKey identifies an imported package by import path and source directory
54 // (directory containing the file containing the import). In practice, the directory
55 // may always be the same, or may not matter. Given an (import path, directory), an
56 // importer must always return the same package (but given two different import paths,
57 // an importer may still return the same package by mapping them to the same package
58 // paths).
59 type importKey struct {
60         path, dir string
61 }
62
63 // A dotImportKey describes a dot-imported object in the given scope.
64 type dotImportKey struct {
65         scope *Scope
66         name  string
67 }
68
69 // An action describes a (delayed) action.
70 type action struct {
71         f    func()      // action to be executed
72         desc *actionDesc // action description; may be nil, requires debug to be set
73 }
74
75 // If debug is set, describef sets a printf-formatted description for action a.
76 // Otherwise, it is a no-op.
77 func (a *action) describef(pos poser, format string, args ...interface{}) {
78         if debug {
79                 a.desc = &actionDesc{pos, format, args}
80         }
81 }
82
83 // An actionDesc provides information on an action.
84 // For debugging only.
85 type actionDesc struct {
86         pos    poser
87         format string
88         args   []interface{}
89 }
90
91 // A Checker maintains the state of the type checker.
92 // It must be created with NewChecker.
93 type Checker struct {
94         // package information
95         // (initialized by NewChecker, valid for the life-time of checker)
96         conf *Config
97         ctxt *Context // context for de-duplicating instances
98         pkg  *Package
99         *Info
100         version version                     // accepted language version
101         posVers map[*syntax.PosBase]version // maps file PosBases to versions (may be nil)
102         nextID  uint64                      // unique Id for type parameters (first valid Id is 1)
103         objMap  map[Object]*declInfo        // maps package-level objects and (non-interface) methods to declaration info
104         impMap  map[importKey]*Package      // maps (import path, source directory) to (complete or fake) package
105         valids  instanceLookup              // valid *Named (incl. instantiated) types per the validType check
106
107         // pkgPathMap maps package names to the set of distinct import paths we've
108         // seen for that name, anywhere in the import graph. It is used for
109         // disambiguating package names in error messages.
110         //
111         // pkgPathMap is allocated lazily, so that we don't pay the price of building
112         // it on the happy path. seenPkgMap tracks the packages that we've already
113         // walked.
114         pkgPathMap map[string]map[string]bool
115         seenPkgMap map[*Package]bool
116
117         // information collected during type-checking of a set of package files
118         // (initialized by Files, valid only for the duration of check.Files;
119         // maps and lists are allocated on demand)
120         files         []*syntax.File              // list of package files
121         imports       []*PkgName                  // list of imported packages
122         dotImportMap  map[dotImportKey]*PkgName   // maps dot-imported objects to the package they were dot-imported through
123         recvTParamMap map[*syntax.Name]*TypeParam // maps blank receiver type parameters to their type
124         brokenAliases map[*TypeName]bool          // set of aliases with broken (not yet determined) types
125         unionTypeSets map[*Union]*_TypeSet        // computed type sets for union types
126         mono          monoGraph                   // graph for detecting non-monomorphizable instantiation loops
127
128         firstErr error                    // first error encountered
129         methods  map[*TypeName][]*Func    // maps package scope type names to associated non-blank (non-interface) methods
130         untyped  map[syntax.Expr]exprInfo // map of expressions without final type
131         delayed  []action                 // stack of delayed action segments; segments are processed in FIFO order
132         objPath  []Object                 // path of object dependencies during type inference (for cycle reporting)
133         cleaners []cleaner                // list of types that may need a final cleanup at the end of type-checking
134
135         // environment within which the current object is type-checked (valid only
136         // for the duration of type-checking a specific object)
137         environment
138
139         // debugging
140         indent int // indentation for tracing
141 }
142
143 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
144 func (check *Checker) addDeclDep(to Object) {
145         from := check.decl
146         if from == nil {
147                 return // not in a package-level init expression
148         }
149         if _, found := check.objMap[to]; !found {
150                 return // to is not a package-level object
151         }
152         from.addDep(to)
153 }
154
155 // brokenAlias records that alias doesn't have a determined type yet.
156 // It also sets alias.typ to Typ[Invalid].
157 func (check *Checker) brokenAlias(alias *TypeName) {
158         if check.brokenAliases == nil {
159                 check.brokenAliases = make(map[*TypeName]bool)
160         }
161         check.brokenAliases[alias] = true
162         alias.typ = Typ[Invalid]
163 }
164
165 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
166 func (check *Checker) validAlias(alias *TypeName, typ Type) {
167         delete(check.brokenAliases, alias)
168         alias.typ = typ
169 }
170
171 // isBrokenAlias reports whether alias doesn't have a determined type yet.
172 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
173         return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
174 }
175
176 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
177         m := check.untyped
178         if m == nil {
179                 m = make(map[syntax.Expr]exprInfo)
180                 check.untyped = m
181         }
182         m[e] = exprInfo{lhs, mode, typ, val}
183 }
184
185 // later pushes f on to the stack of actions that will be processed later;
186 // either at the end of the current statement, or in case of a local constant
187 // or variable declaration, before the constant or variable is in scope
188 // (so that f still sees the scope before any new declarations).
189 // later returns the pushed action so one can provide a description
190 // via action.describef for debugging, if desired.
191 func (check *Checker) later(f func()) *action {
192         i := len(check.delayed)
193         check.delayed = append(check.delayed, action{f: f})
194         return &check.delayed[i]
195 }
196
197 // push pushes obj onto the object path and returns its index in the path.
198 func (check *Checker) push(obj Object) int {
199         check.objPath = append(check.objPath, obj)
200         return len(check.objPath) - 1
201 }
202
203 // pop pops and returns the topmost object from the object path.
204 func (check *Checker) pop() Object {
205         i := len(check.objPath) - 1
206         obj := check.objPath[i]
207         check.objPath[i] = nil
208         check.objPath = check.objPath[:i]
209         return obj
210 }
211
212 type cleaner interface {
213         cleanup()
214 }
215
216 // needsCleanup records objects/types that implement the cleanup method
217 // which will be called at the end of type-checking.
218 func (check *Checker) needsCleanup(c cleaner) {
219         check.cleaners = append(check.cleaners, c)
220 }
221
222 // NewChecker returns a new Checker instance for a given package.
223 // Package files may be added incrementally via checker.Files.
224 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
225         // make sure we have a configuration
226         if conf == nil {
227                 conf = new(Config)
228         }
229
230         // make sure we have an info struct
231         if info == nil {
232                 info = new(Info)
233         }
234
235         // Note: clients may call NewChecker with the Unsafe package, which is
236         // globally shared and must not be mutated. Therefore NewChecker must not
237         // mutate *pkg.
238         //
239         // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
240
241         return &Checker{
242                 conf:   conf,
243                 ctxt:   conf.Context,
244                 pkg:    pkg,
245                 Info:   info,
246                 objMap: make(map[Object]*declInfo),
247                 impMap: make(map[importKey]*Package),
248         }
249 }
250
251 // initFiles initializes the files-specific portion of checker.
252 // The provided files must all belong to the same package.
253 func (check *Checker) initFiles(files []*syntax.File) {
254         // start with a clean slate (check.Files may be called multiple times)
255         check.files = nil
256         check.imports = nil
257         check.dotImportMap = nil
258
259         check.firstErr = nil
260         check.methods = nil
261         check.untyped = nil
262         check.delayed = nil
263         check.objPath = nil
264         check.cleaners = nil
265
266         // determine package name and collect valid files
267         pkg := check.pkg
268         for _, file := range files {
269                 switch name := file.PkgName.Value; pkg.name {
270                 case "":
271                         if name != "_" {
272                                 pkg.name = name
273                         } else {
274                                 check.error(file.PkgName, BlankPkgName, "invalid package name _")
275                         }
276                         fallthrough
277
278                 case name:
279                         check.files = append(check.files, file)
280
281                 default:
282                         check.errorf(file, MismatchedPkgName, "package %s; expected %s", name, pkg.name)
283                         // ignore this file
284                 }
285         }
286
287         for _, file := range check.files {
288                 v, _ := parseGoVersion(file.GoVersion)
289                 if v.major > 0 {
290                         if v.equal(check.version) {
291                                 continue
292                         }
293                         // Go 1.21 introduced the feature of setting the go.mod
294                         // go line to an early version of Go and allowing //go:build lines
295                         // to “upgrade” the Go version in a given file.
296                         // We can do that backwards compatibly.
297                         // Go 1.21 also introduced the feature of allowing //go:build lines
298                         // to “downgrade” the Go version in a given file.
299                         // That can't be done compatibly in general, since before the
300                         // build lines were ignored and code got the module's Go version.
301                         // To work around this, downgrades are only allowed when the
302                         // module's Go version is Go 1.21 or later.
303                         // If there is no check.version, then we don't really know what Go version to apply.
304                         // Legacy tools may do this, and they historically have accepted everything.
305                         // Preserve that behavior by ignoring //go:build constraints entirely in that case.
306                         if (v.before(check.version) && check.version.before(go1_21)) || check.version.equal(go0_0) {
307                                 continue
308                         }
309                         if check.posVers == nil {
310                                 check.posVers = make(map[*syntax.PosBase]version)
311                         }
312                         check.posVers[base(file.Pos())] = v
313                 }
314         }
315 }
316
317 // A bailout panic is used for early termination.
318 type bailout struct{}
319
320 func (check *Checker) handleBailout(err *error) {
321         switch p := recover().(type) {
322         case nil, bailout:
323                 // normal return or early exit
324                 *err = check.firstErr
325         default:
326                 // re-panic
327                 panic(p)
328         }
329 }
330
331 // Files checks the provided files as part of the checker's package.
332 func (check *Checker) Files(files []*syntax.File) error { return check.checkFiles(files) }
333
334 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
335
336 func (check *Checker) checkFiles(files []*syntax.File) (err error) {
337         if check.pkg == Unsafe {
338                 // Defensive handling for Unsafe, which cannot be type checked, and must
339                 // not be mutated. See https://go.dev/issue/61212 for an example of where
340                 // Unsafe is passed to NewChecker.
341                 return nil
342         }
343
344         // Note: parseGoVersion and the subsequent checks should happen once,
345         //       when we create a new Checker, not for each batch of files.
346         //       We can't change it at this point because NewChecker doesn't
347         //       return an error.
348         check.version, err = parseGoVersion(check.conf.GoVersion)
349         if err != nil {
350                 return err
351         }
352         if check.version.after(version{1, goversion.Version}) {
353                 return fmt.Errorf("package requires newer Go version %v", check.version)
354         }
355         if check.conf.FakeImportC && check.conf.go115UsesCgo {
356                 return errBadCgo
357         }
358
359         defer check.handleBailout(&err)
360
361         print := func(msg string) {
362                 if check.conf.Trace {
363                         fmt.Println()
364                         fmt.Println(msg)
365                 }
366         }
367
368         print("== initFiles ==")
369         check.initFiles(files)
370
371         print("== collectObjects ==")
372         check.collectObjects()
373
374         print("== packageObjects ==")
375         check.packageObjects()
376
377         print("== processDelayed ==")
378         check.processDelayed(0) // incl. all functions
379
380         print("== cleanup ==")
381         check.cleanup()
382
383         print("== initOrder ==")
384         check.initOrder()
385
386         if !check.conf.DisableUnusedImportCheck {
387                 print("== unusedImports ==")
388                 check.unusedImports()
389         }
390
391         print("== recordUntyped ==")
392         check.recordUntyped()
393
394         if check.firstErr == nil {
395                 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
396                 check.monomorph()
397         }
398
399         check.pkg.goVersion = check.conf.GoVersion
400         check.pkg.complete = true
401
402         // no longer needed - release memory
403         check.imports = nil
404         check.dotImportMap = nil
405         check.pkgPathMap = nil
406         check.seenPkgMap = nil
407         check.recvTParamMap = nil
408         check.brokenAliases = nil
409         check.unionTypeSets = nil
410         check.ctxt = nil
411
412         // TODO(gri) There's more memory we should release at this point.
413
414         return
415 }
416
417 // processDelayed processes all delayed actions pushed after top.
418 func (check *Checker) processDelayed(top int) {
419         // If each delayed action pushes a new action, the
420         // stack will continue to grow during this loop.
421         // However, it is only processing functions (which
422         // are processed in a delayed fashion) that may
423         // add more actions (such as nested functions), so
424         // this is a sufficiently bounded process.
425         for i := top; i < len(check.delayed); i++ {
426                 a := &check.delayed[i]
427                 if check.conf.Trace {
428                         if a.desc != nil {
429                                 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
430                         } else {
431                                 check.trace(nopos, "-- delayed %p", a.f)
432                         }
433                 }
434                 a.f() // may append to check.delayed
435                 if check.conf.Trace {
436                         fmt.Println()
437                 }
438         }
439         assert(top <= len(check.delayed)) // stack must not have shrunk
440         check.delayed = check.delayed[:top]
441 }
442
443 // cleanup runs cleanup for all collected cleaners.
444 func (check *Checker) cleanup() {
445         // Don't use a range clause since Named.cleanup may add more cleaners.
446         for i := 0; i < len(check.cleaners); i++ {
447                 check.cleaners[i].cleanup()
448         }
449         check.cleaners = nil
450 }
451
452 func (check *Checker) record(x *operand) {
453         // convert x into a user-friendly set of values
454         // TODO(gri) this code can be simplified
455         var typ Type
456         var val constant.Value
457         switch x.mode {
458         case invalid:
459                 typ = Typ[Invalid]
460         case novalue:
461                 typ = (*Tuple)(nil)
462         case constant_:
463                 typ = x.typ
464                 val = x.val
465         default:
466                 typ = x.typ
467         }
468         assert(x.expr != nil && typ != nil)
469
470         if isUntyped(typ) {
471                 // delay type and value recording until we know the type
472                 // or until the end of type checking
473                 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
474         } else {
475                 check.recordTypeAndValue(x.expr, x.mode, typ, val)
476         }
477 }
478
479 func (check *Checker) recordUntyped() {
480         if !debug && !check.recordTypes() {
481                 return // nothing to do
482         }
483
484         for x, info := range check.untyped {
485                 if debug && isTyped(info.typ) {
486                         check.dump("%v: %s (type %s) is typed", atPos(x), x, info.typ)
487                         unreachable()
488                 }
489                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
490         }
491 }
492
493 func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
494         assert(x != nil)
495         assert(typ != nil)
496         if mode == invalid {
497                 return // omit
498         }
499         if mode == constant_ {
500                 assert(val != nil)
501                 // We check allBasic(typ, IsConstType) here as constant expressions may be
502                 // recorded as type parameters.
503                 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
504         }
505         if m := check.Types; m != nil {
506                 m[x] = TypeAndValue{mode, typ, val}
507         }
508         if check.StoreTypesInSyntax {
509                 tv := TypeAndValue{mode, typ, val}
510                 stv := syntax.TypeAndValue{Type: typ, Value: val}
511                 if tv.IsVoid() {
512                         stv.SetIsVoid()
513                 }
514                 if tv.IsType() {
515                         stv.SetIsType()
516                 }
517                 if tv.IsBuiltin() {
518                         stv.SetIsBuiltin()
519                 }
520                 if tv.IsValue() {
521                         stv.SetIsValue()
522                 }
523                 if tv.IsNil() {
524                         stv.SetIsNil()
525                 }
526                 if tv.Addressable() {
527                         stv.SetAddressable()
528                 }
529                 if tv.Assignable() {
530                         stv.SetAssignable()
531                 }
532                 if tv.HasOk() {
533                         stv.SetHasOk()
534                 }
535                 x.SetTypeInfo(stv)
536         }
537 }
538
539 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
540         // f must be a (possibly parenthesized, possibly qualified)
541         // identifier denoting a built-in (including unsafe's non-constant
542         // functions Add and Slice): record the signature for f and possible
543         // children.
544         for {
545                 check.recordTypeAndValue(f, builtin, sig, nil)
546                 switch p := f.(type) {
547                 case *syntax.Name, *syntax.SelectorExpr:
548                         return // we're done
549                 case *syntax.ParenExpr:
550                         f = p.X
551                 default:
552                         unreachable()
553                 }
554         }
555 }
556
557 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
558 // (and therefore has tuple type).
559 func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand) {
560         assert(x != nil)
561         assert(len(a) == 2)
562         if a[0].mode == invalid {
563                 return
564         }
565         t0, t1 := a[0].typ, a[1].typ
566         assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
567         if m := check.Types; m != nil {
568                 for {
569                         tv := m[x]
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                         m[x] = tv
577                         // if x is a parenthesized expression (p.X), update p.X
578                         p, _ := x.(*syntax.ParenExpr)
579                         if p == nil {
580                                 break
581                         }
582                         x = p.X
583                 }
584         }
585         if check.StoreTypesInSyntax {
586                 // Note: this loop is duplicated because the type of tv is different.
587                 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
588                 for {
589                         tv := x.GetTypeInfo()
590                         assert(tv.Type != nil) // should have been recorded already
591                         pos := x.Pos()
592                         tv.Type = NewTuple(
593                                 NewVar(pos, check.pkg, "", t0),
594                                 NewVar(pos, check.pkg, "", t1),
595                         )
596                         x.SetTypeInfo(tv)
597                         p, _ := x.(*syntax.ParenExpr)
598                         if p == nil {
599                                 break
600                         }
601                         x = p.X
602                 }
603         }
604 }
605
606 // recordInstance records instantiation information into check.Info, if the
607 // Instances map is non-nil. The given expr must be an ident, selector, or
608 // index (list) expr with ident or selector operand.
609 //
610 // TODO(rfindley): the expr parameter is fragile. See if we can access the
611 // instantiated identifier in some other way.
612 func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type) {
613         ident := instantiatedIdent(expr)
614         assert(ident != nil)
615         assert(typ != nil)
616         if m := check.Instances; m != nil {
617                 m[ident] = Instance{newTypeList(targs), typ}
618         }
619 }
620
621 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
622         var selOrIdent syntax.Expr
623         switch e := expr.(type) {
624         case *syntax.IndexExpr:
625                 selOrIdent = e.X
626         case *syntax.SelectorExpr, *syntax.Name:
627                 selOrIdent = e
628         }
629         switch x := selOrIdent.(type) {
630         case *syntax.Name:
631                 return x
632         case *syntax.SelectorExpr:
633                 return x.Sel
634         }
635         panic("instantiated ident not found")
636 }
637
638 func (check *Checker) recordDef(id *syntax.Name, obj Object) {
639         assert(id != nil)
640         if m := check.Defs; m != nil {
641                 m[id] = obj
642         }
643 }
644
645 func (check *Checker) recordUse(id *syntax.Name, obj Object) {
646         assert(id != nil)
647         assert(obj != nil)
648         if m := check.Uses; m != nil {
649                 m[id] = obj
650         }
651 }
652
653 func (check *Checker) recordImplicit(node syntax.Node, obj Object) {
654         assert(node != nil)
655         assert(obj != nil)
656         if m := check.Implicits; m != nil {
657                 m[node] = obj
658         }
659 }
660
661 func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
662         assert(obj != nil && (recv == nil || len(index) > 0))
663         check.recordUse(x.Sel, obj)
664         if m := check.Selections; m != nil {
665                 m[x] = &Selection{kind, recv, obj, index, indirect}
666         }
667 }
668
669 func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
670         assert(node != nil)
671         assert(scope != nil)
672         if m := check.Scopes; m != nil {
673                 m[node] = scope
674         }
675 }