Debian Codegraph @

src/cmd/compile/internal/types2/check.go

raw
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 "fmt"
12 "go/constant"
13 . "internal/types/errors"
14 "os"
15 "sync/atomic"
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 // position tracing for panics during type checking
25 const tracePos = true
26
27 // _aliasAny changes the behavior of [Scope.Lookup] for "any" in the
28 // [Universe] scope.
29 //
30 // This is necessary because while Alias creation is controlled by
31 // [Config.EnableAlias], the representation of "any" is a global. In
32 // [Scope.Lookup], we select this global representation based on the result of
33 // [aliasAny], but as a result need to guard against this behavior changing
34 // during the type checking pass. Therefore we implement the following rule:
35 // any number of goroutines can type check concurrently with the same
36 // EnableAlias value, but if any goroutine tries to type check concurrently
37 // with a different EnableAlias value, we panic.
38 //
39 // To achieve this, _aliasAny is a state machine:
40 //
41 // 0: no type checking is occurring
42 // negative: type checking is occurring without EnableAlias set
43 // positive: type checking is occurring with EnableAlias set
44 var _aliasAny int32
45
46 func aliasAny() bool {
47 return atomic.LoadInt32(&_aliasAny) >= 0 // default true
48 }
49
50 // exprInfo stores information about an untyped expression.
51 type exprInfo struct {
52 isLhs bool // expression is lhs operand of a shift with delayed type-check
53 mode operandMode
54 typ *Basic
55 val constant.Value // constant value; or nil (if not a constant)
56 }
57
58 // An environment represents the environment within which an object is
59 // type-checked.
60 type environment struct {
61 decl *declInfo // package-level declaration whose init expression/function body is checked
62 scope *Scope // top-most scope for lookups
63 version goVersion // current accepted language version; changes across files
64 iota constant.Value // value of iota in a constant declaration; nil otherwise
65 errpos syntax.Pos // if valid, identifier position of a constant with inherited initializer
66 inTParamList bool // set if inside a type parameter list
67 sig *Signature // function signature if inside a function; nil otherwise
68 isPanic map[*syntax.CallExpr]bool // set of panic call expressions (used for termination check)
69 hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
70 hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
71 }
72
73 // lookupScope looks up name in the current environment and if an object
74 // is found it returns the scope containing the object and the object.
75 // Otherwise it returns (nil, nil).
76 //
77 // Note that obj.Parent() may be different from the returned scope if the
78 // object was inserted into the scope and already had a parent at that
79 // time (see Scope.Insert). This can only happen for dot-imported objects
80 // whose parent is the scope of the package that exported them.
81 func (env *environment) lookupScope(name string) (*Scope, Object) {
82 for s := env.scope; s != nil; s = s.parent {
83 if obj := s.Lookup(name); obj != nil {
84 return s, obj
85 }
86 }
87 return nil, nil
88 }
89
90 // lookup is like lookupScope but it only returns the object (or nil).
91 func (env *environment) lookup(name string) Object {
92 _, obj := env.lookupScope(name)
93 return obj
94 }
95
96 // An importKey identifies an imported package by import path and source directory
97 // (directory containing the file containing the import). In practice, the directory
98 // may always be the same, or may not matter. Given an (import path, directory), an
99 // importer must always return the same package (but given two different import paths,
100 // an importer may still return the same package by mapping them to the same package
101 // paths).
102 type importKey struct {
103 path, dir string
104 }
105
106 // A dotImportKey describes a dot-imported object in the given scope.
107 type dotImportKey struct {
108 scope *Scope
109 name string
110 }
111
112 // An action describes a (delayed) action.
113 type action struct {
114 version goVersion // applicable language version
115 f func() // action to be executed
116 desc *actionDesc // action description; may be nil, requires debug to be set
117 }
118
119 // If debug is set, describef sets a printf-formatted description for action a.
120 // Otherwise, it is a no-op.
121 func (a *action) describef(pos poser, format string, args ...any) {
122 if debug {
123 a.desc = &actionDesc{pos, format, args}
124 }
125 }
126
127 // An actionDesc provides information on an action.
128 // For debugging only.
129 type actionDesc struct {
130 pos poser
131 format string
132 args []any
133 }
134
135 // A Checker maintains the state of the type checker.
136 // It must be created with NewChecker.
137 type Checker struct {
138 // package information
139 // (initialized by NewChecker, valid for the life-time of checker)
140 conf *Config
141 ctxt *Context // context for de-duplicating instances
142 pkg *Package
143 *Info
144 nextID uint64 // unique Id for type parameters (first valid Id is 1)
145 objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
146 objList []Object // source-ordered keys of objMap
147 impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
148 // see TODO in validtype.go
149 // valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
150
151 // pkgPathMap maps package names to the set of distinct import paths we've
152 // seen for that name, anywhere in the import graph. It is used for
153 // disambiguating package names in error messages.
154 //
155 // pkgPathMap is allocated lazily, so that we don't pay the price of building
156 // it on the happy path. seenPkgMap tracks the packages that we've already
157 // walked.
158 pkgPathMap map[string]map[string]bool
159 seenPkgMap map[*Package]bool
160
161 // information collected during type-checking of a set of package files
162 // (initialized by Files, valid only for the duration of check.Files;
163 // maps and lists are allocated on demand)
164 files []*syntax.File // list of package files
165 versions map[*syntax.PosBase]string // maps files to version strings (each file has an entry); shared with Info.FileVersions if present; may be unaltered Config.GoVersion
166 imports []*PkgName // list of imported packages
167 dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
168 brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
169 unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
170 usedVars map[*Var]bool // set of used variables
171 usedPkgNames map[*PkgName]bool // set of used package names
172 mono monoGraph // graph for detecting non-monomorphizable instantiation loops
173
174 firstErr error // first error encountered
175 methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
176 untyped map[syntax.Expr]exprInfo // map of expressions without final type
177 delayed []action // stack of delayed action segments; segments are processed in FIFO order
178 objPath []Object // path of object dependencies during type-checking (for cycle reporting)
179 objPathIdx map[Object]int // map of object to object path index during type-checking (for cycle reporting)
180 cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
181
182 // environment within which the current object is type-checked (valid only
183 // for the duration of type-checking a specific object)
184 environment
185
186 // debugging
187 posStack []syntax.Pos // stack of source positions seen; used for panic tracing
188 indent int // indentation for tracing
189 }
190
191 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
192 func (check *Checker) addDeclDep(to Object) {
193 from := check.decl
194 if from == nil {
195 return // not in a package-level init expression
196 }
197 if _, found := check.objMap[to]; !found {
198 return // to is not a package-level object
199 }
200 from.addDep(to)
201 }
202
203 // Note: The following three alias-related functions are only used
204 // when Alias types are not enabled.
205
206 // brokenAlias records that alias doesn't have a determined type yet.
207 // It also sets alias.typ to Typ[Invalid].
208 // Not used if check.conf.EnableAlias is set.
209 func (check *Checker) brokenAlias(alias *TypeName) {
210 assert(!check.conf.EnableAlias)
211 if check.brokenAliases == nil {
212 check.brokenAliases = make(map[*TypeName]bool)
213 }
214 check.brokenAliases[alias] = true
215 alias.typ = Typ[Invalid]
216 }
217
218 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
219 func (check *Checker) validAlias(alias *TypeName, typ Type) {
220 assert(!check.conf.EnableAlias)
221 delete(check.brokenAliases, alias)
222 alias.typ = typ
223 }
224
225 // isBrokenAlias reports whether alias doesn't have a determined type yet.
226 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
227 assert(!check.conf.EnableAlias)
228 return check.brokenAliases[alias]
229 }
230
231 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
232 m := check.untyped
233 if m == nil {
234 m = make(map[syntax.Expr]exprInfo)
235 check.untyped = m
236 }
237 m[e] = exprInfo{lhs, mode, typ, val}
238 }
239
240 // later pushes f on to the stack of actions that will be processed later;
241 // either at the end of the current statement, or in case of a local constant
242 // or variable declaration, before the constant or variable is in scope
243 // (so that f still sees the scope before any new declarations).
244 // later returns the pushed action so one can provide a description
245 // via action.describef for debugging, if desired.
246 func (check *Checker) later(f func()) *action {
247 i := len(check.delayed)
248 check.delayed = append(check.delayed, action{version: check.version, f: f})
249 return &check.delayed[i]
250 }
251
252 // push pushes obj onto the object path and records its index in the path index map.
253 func (check *Checker) push(obj Object) {
254 if check.objPathIdx == nil {
255 check.objPathIdx = make(map[Object]int)
256 }
257 check.objPathIdx[obj] = len(check.objPath)
258 check.objPath = append(check.objPath, obj)
259 }
260
261 // pop pops an object from the object path and removes it from the path index map.
262 func (check *Checker) pop() {
263 i := len(check.objPath) - 1
264 obj := check.objPath[i]
265 check.objPath[i] = nil // help the garbage collector
266 check.objPath = check.objPath[:i]
267 delete(check.objPathIdx, obj)
268 }
269
270 type cleaner interface {
271 cleanup()
272 }
273
274 // needsCleanup records objects/types that implement the cleanup method
275 // which will be called at the end of type-checking.
276 func (check *Checker) needsCleanup(c cleaner) {
277 check.cleaners = append(check.cleaners, c)
278 }
279
280 // NewChecker returns a new Checker instance for a given package.
281 // Package files may be added incrementally via checker.Files.
282 func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
283 // make sure we have a configuration
284 if conf == nil {
285 conf = new(Config)
286 }
287
288 // make sure we have an info struct
289 if info == nil {
290 info = new(Info)
291 }
292
293 // Note: clients may call NewChecker with the Unsafe package, which is
294 // globally shared and must not be mutated. Therefore NewChecker must not
295 // mutate *pkg.
296 //
297 // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
298
299 return &Checker{
300 conf: conf,
301 ctxt: conf.Context,
302 pkg: pkg,
303 Info: info,
304 objMap: make(map[Object]*declInfo),
305 impMap: make(map[importKey]*Package),
306 usedVars: make(map[*Var]bool),
307 usedPkgNames: make(map[*PkgName]bool),
308 }
309 }
310
311 // initFiles initializes the files-specific portion of checker.
312 // The provided files must all belong to the same package.
313 func (check *Checker) initFiles(files []*syntax.File) {
314 // start with a clean slate (check.Files may be called multiple times)
315 // TODO(gri): what determines which fields are zeroed out here, vs at the end
316 // of checkFiles?
317 check.files = nil
318 check.imports = nil
319 check.dotImportMap = nil
320
321 check.firstErr = nil
322 check.methods = nil
323 check.untyped = nil
324 check.delayed = nil
325 check.objPath = nil
326 check.objPathIdx = nil
327 check.cleaners = nil
328
329 // We must initialize usedVars and usedPkgNames both here and in NewChecker,
330 // because initFiles is not called in the CheckExpr or Eval codepaths, yet we
331 // want to free this memory at the end of Files ('used' predicates are
332 // only needed in the context of a given file).
333 check.usedVars = make(map[*Var]bool)
334 check.usedPkgNames = make(map[*PkgName]bool)
335
336 // determine package name and collect valid files
337 pkg := check.pkg
338 for _, file := range files {
339 switch name := file.PkgName.Value; pkg.name {
340 case "":
341 if name != "_" {
342 pkg.name = name
343 } else {
344 check.error(file.PkgName, BlankPkgName, "invalid package name _")
345 }
346 fallthrough
347
348 case name:
349 check.files = append(check.files, file)
350
351 default:
352 check.errorf(file, MismatchedPkgName, "package %s; expected package %s", name, pkg.name)
353 // ignore this file
354 }
355 }
356
357 // reuse Info.FileVersions if provided
358 versions := check.Info.FileVersions
359 if versions == nil {
360 versions = make(map[*syntax.PosBase]string)
361 }
362 check.versions = versions
363
364 pkgVersion := asGoVersion(check.conf.GoVersion)
365 if pkgVersion.isValid() && len(files) > 0 && pkgVersion.cmp(go_current) > 0 {
366 check.errorf(files[0], TooNew, "package requires newer Go version %v (application built with %v)",
367 pkgVersion, go_current)
368 }
369
370 // determine Go version for each file
371 for _, file := range check.files {
372 // use unaltered Config.GoVersion by default
373 // (This version string may contain dot-release numbers as in go1.20.1,
374 // unlike file versions which are Go language versions only, if valid.)
375 v := check.conf.GoVersion
376
377 // If the file specifies a version, use max(fileVersion, go1.21).
378 if fileVersion := asGoVersion(file.GoVersion); fileVersion.isValid() {
379 // Go 1.21 introduced the feature of allowing //go:build lines
380 // to sometimes set the Go version in a given file. Versions Go 1.21 and later
381 // can be set backwards compatibly as that was the first version
382 // files with go1.21 or later build tags could be built with.
383 //
384 // Set the version to max(fileVersion, go1.21): That will allow a
385 // downgrade to a version before go1.22, where the for loop semantics
386 // change was made, while being backwards compatible with versions of
387 // go before the new //go:build semantics were introduced.
388 v = string(versionMax(fileVersion, go1_21))
389
390 // Report a specific error for each tagged file that's too new.
391 // (Normally the build system will have filtered files by version,
392 // but clients can present arbitrary files to the type checker.)
393 if fileVersion.cmp(go_current) > 0 {
394 // Use position of 'package [p]' for types/types2 consistency.
395 // (Ideally we would use the //build tag itself.)
396 check.errorf(file.PkgName, TooNew, "file requires newer Go version %v", fileVersion)
397 }
398 }
399 versions[file.Pos().FileBase()] = v // file.Pos().FileBase() may be nil for tests
400 }
401 }
402
403 func versionMax(a, b goVersion) goVersion {
404 if a.cmp(b) > 0 {
405 return a
406 }
407 return b
408 }
409
410 // pushPos pushes pos onto the pos stack.
411 func (check *Checker) pushPos(pos syntax.Pos) {
412 check.posStack = append(check.posStack, pos)
413 }
414
415 // popPos pops from the pos stack.
416 func (check *Checker) popPos() {
417 check.posStack = check.posStack[:len(check.posStack)-1]
418 }
419
420 // A bailout panic is used for early termination.
421 type bailout struct{}
422
423 func (check *Checker) handleBailout(err *error) {
424 switch p := recover().(type) {
425 case nil, bailout:
426 // normal return or early exit
427 *err = check.firstErr
428 default:
429 if len(check.posStack) > 0 {
430 doPrint := func(ps []syntax.Pos) {
431 for i := len(ps) - 1; i >= 0; i-- {
432 fmt.Fprintf(os.Stderr, "\t%v\n", ps[i])
433 }
434 }
435
436 fmt.Fprintln(os.Stderr, "The following panic happened checking types near:")
437 if len(check.posStack) <= 10 {
438 doPrint(check.posStack)
439 } else {
440 // if it's long, truncate the middle; it's least likely to help
441 doPrint(check.posStack[len(check.posStack)-5:])
442 fmt.Fprintln(os.Stderr, "\t...")
443 doPrint(check.posStack[:5])
444 }
445 }
446
447 // re-panic
448 panic(p)
449 }
450 }
451
452 // Files checks the provided files as part of the checker's package.
453 func (check *Checker) Files(files []*syntax.File) (err error) {
454 if check.pkg == Unsafe {
455 // Defensive handling for Unsafe, which cannot be type checked, and must
456 // not be mutated. See https://go.dev/issue/61212 for an example of where
457 // Unsafe is passed to NewChecker.
458 return nil
459 }
460
461 // Avoid early returns here! Nearly all errors can be
462 // localized to a piece of syntax and needn't prevent
463 // type-checking of the rest of the package.
464
465 defer check.handleBailout(&err)
466 check.checkFiles(files)
467 return
468 }
469
470 // checkFiles type-checks the specified files. Errors are reported as
471 // a side effect, not by returning early, to ensure that well-formed
472 // syntax is properly type annotated even in a package containing
473 // errors.
474 func (check *Checker) checkFiles(files []*syntax.File) {
475 // Ensure that EnableAlias is consistent among concurrent type checking
476 // operations. See the documentation of [_aliasAny] for details.
477 if check.conf.EnableAlias {
478 if atomic.AddInt32(&_aliasAny, 1) <= 0 {
479 panic("EnableAlias set while !EnableAlias type checking is ongoing")
480 }
481 defer atomic.AddInt32(&_aliasAny, -1)
482 } else {
483 if atomic.AddInt32(&_aliasAny, -1) >= 0 {
484 panic("!EnableAlias set while EnableAlias type checking is ongoing")
485 }
486 defer atomic.AddInt32(&_aliasAny, 1)
487 }
488
489 print := func(msg string) {
490 if check.conf.Trace {
491 fmt.Println()
492 fmt.Println(msg)
493 }
494 }
495
496 print("== initFiles ==")
497 check.initFiles(files)
498
499 print("== collectObjects ==")
500 check.collectObjects()
501
502 print("== sortObjects ==")
503 check.sortObjects()
504
505 print("== directCycles ==")
506 check.directCycles()
507
508 print("== packageObjects ==")
509 check.packageObjects()
510
511 print("== processDelayed ==")
512 check.processDelayed(0) // incl. all functions
513
514 print("== cleanup ==")
515 check.cleanup()
516
517 print("== initOrder ==")
518 check.initOrder()
519
520 if !check.conf.DisableUnusedImportCheck {
521 print("== unusedImports ==")
522 check.unusedImports()
523 }
524
525 print("== recordUntyped ==")
526 check.recordUntyped()
527
528 if check.firstErr == nil {
529 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
530 check.monomorph()
531 }
532
533 check.pkg.goVersion = check.conf.GoVersion
534 check.pkg.complete = true
535
536 // no longer needed - release memory
537 check.imports = nil
538 check.dotImportMap = nil
539 check.pkgPathMap = nil
540 check.seenPkgMap = nil
541 check.brokenAliases = nil
542 check.unionTypeSets = nil
543 check.usedVars = nil
544 check.usedPkgNames = nil
545 check.ctxt = nil
546
547 // TODO(gri): shouldn't the cleanup above occur after the bailout?
548 // TODO(gri) There's more memory we should release at this point.
549 }
550
551 // processDelayed processes all delayed actions pushed after top.
552 func (check *Checker) processDelayed(top int) {
553 // If each delayed action pushes a new action, the
554 // stack will continue to grow during this loop.
555 // However, it is only processing functions (which
556 // are processed in a delayed fashion) that may
557 // add more actions (such as nested functions), so
558 // this is a sufficiently bounded process.
559 savedVersion := check.version
560 for i := top; i < len(check.delayed); i++ {
561 a := &check.delayed[i]
562 if check.conf.Trace {
563 if a.desc != nil {
564 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
565 } else {
566 check.trace(nopos, "-- delayed %p", a.f)
567 }
568 }
569 check.version = a.version // reestablish the effective Go version captured earlier
570 a.f() // may append to check.delayed
571 if check.conf.Trace {
572 fmt.Println()
573 }
574 }
575 assert(top <= len(check.delayed)) // stack must not have shrunk
576 check.delayed = check.delayed[:top]
577 check.version = savedVersion
578 }
579
580 // cleanup runs cleanup for all collected cleaners.
581 func (check *Checker) cleanup() {
582 // Don't use a range clause since Named.cleanup may add more cleaners.
583 for i := 0; i < len(check.cleaners); i++ {
584 check.cleaners[i].cleanup()
585 }
586 check.cleaners = nil
587 }
588
589 // types2-specific support for recording type information in the syntax tree.
590 func (check *Checker) recordTypeAndValueInSyntax(x syntax.Expr, mode operandMode, typ Type, val constant.Value) {
591 if check.StoreTypesInSyntax {
592 tv := TypeAndValue{mode, typ, val}
593 stv := syntax.TypeAndValue{Type: typ, Value: val}
594 if tv.IsVoid() {
595 stv.SetIsVoid()
596 }
597 if tv.IsType() {
598 stv.SetIsType()
599 }
600 if tv.IsBuiltin() {
601 stv.SetIsBuiltin()
602 }
603 if tv.IsValue() {
604 stv.SetIsValue()
605 }
606 if tv.IsNil() {
607 stv.SetIsNil()
608 }
609 if tv.Addressable() {
610 stv.SetAddressable()
611 }
612 if tv.Assignable() {
613 stv.SetAssignable()
614 }
615 if tv.HasOk() {
616 stv.SetHasOk()
617 }
618 x.SetTypeInfo(stv)
619 }
620 }
621
622 // types2-specific support for recording type information in the syntax tree.
623 func (check *Checker) recordCommaOkTypesInSyntax(x syntax.Expr, t0, t1 Type) {
624 if check.StoreTypesInSyntax {
625 // Note: this loop is duplicated because the type of tv is different.
626 // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
627 for {
628 tv := x.GetTypeInfo()
629 assert(tv.Type != nil) // should have been recorded already
630 pos := x.Pos()
631 tv.Type = NewTuple(
632 NewParam(pos, check.pkg, "", t0),
633 NewParam(pos, check.pkg, "", t1),
634 )
635 x.SetTypeInfo(tv)
636 p, _ := x.(*syntax.ParenExpr)
637 if p == nil {
638 break
639 }
640 x = p.X
641 }
642 }
643 }
644
645 // instantiatedIdent determines the identifier of the type instantiated in expr.
646 // Helper function for recordInstance in recording.go.
647 func instantiatedIdent(expr syntax.Expr) *syntax.Name {
648 var selOrIdent syntax.Expr
649 switch e := expr.(type) {
650 case *syntax.IndexExpr:
651 selOrIdent = e.X
652 case *syntax.SelectorExpr, *syntax.Name:
653 selOrIdent = e
654 }
655 switch x := selOrIdent.(type) {
656 case *syntax.Name:
657 return x
658 case *syntax.SelectorExpr:
659 return x.Sel
660 }
661
662 // extra debugging of go.dev/issue/63933
663 panic(sprintf(nil, true, "instantiated ident not found; please report: %s", expr))
664 }