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