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