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