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