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