]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/check.go
go/types: record Config.GoVersion for reporting in Package.GoVersion method
[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         versionErr error                  // version error, delayed from NewChecker
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         posVers       map[*token.File]version   // Pos -> Go version mapping
124         imports       []*PkgName                // list of imported packages
125         dotImportMap  map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
126         recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
127         brokenAliases map[*TypeName]bool        // set of aliases with broken (not yet determined) types
128         unionTypeSets map[*Union]*_TypeSet      // computed type sets for union types
129         mono          monoGraph                 // graph for detecting non-monomorphizable instantiation loops
130
131         firstErr error                 // first error encountered
132         methods  map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
133         untyped  map[ast.Expr]exprInfo // map of expressions without final type
134         delayed  []action              // stack of delayed action segments; segments are processed in FIFO order
135         objPath  []Object              // path of object dependencies during type inference (for cycle reporting)
136         cleaners []cleaner             // list of types that may need a final cleanup at the end of type-checking
137
138         // environment within which the current object is type-checked (valid only
139         // for the duration of type-checking a specific object)
140         environment
141
142         // debugging
143         indent int // indentation for tracing
144 }
145
146 // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
147 func (check *Checker) addDeclDep(to Object) {
148         from := check.decl
149         if from == nil {
150                 return // not in a package-level init expression
151         }
152         if _, found := check.objMap[to]; !found {
153                 return // to is not a package-level object
154         }
155         from.addDep(to)
156 }
157
158 // brokenAlias records that alias doesn't have a determined type yet.
159 // It also sets alias.typ to Typ[Invalid].
160 func (check *Checker) brokenAlias(alias *TypeName) {
161         if check.brokenAliases == nil {
162                 check.brokenAliases = make(map[*TypeName]bool)
163         }
164         check.brokenAliases[alias] = true
165         alias.typ = Typ[Invalid]
166 }
167
168 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
169 func (check *Checker) validAlias(alias *TypeName, typ Type) {
170         delete(check.brokenAliases, alias)
171         alias.typ = typ
172 }
173
174 // isBrokenAlias reports whether alias doesn't have a determined type yet.
175 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
176         return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
177 }
178
179 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
180         m := check.untyped
181         if m == nil {
182                 m = make(map[ast.Expr]exprInfo)
183                 check.untyped = m
184         }
185         m[e] = exprInfo{lhs, mode, typ, val}
186 }
187
188 // later pushes f on to the stack of actions that will be processed later;
189 // either at the end of the current statement, or in case of a local constant
190 // or variable declaration, before the constant or variable is in scope
191 // (so that f still sees the scope before any new declarations).
192 // later returns the pushed action so one can provide a description
193 // via action.describef for debugging, if desired.
194 func (check *Checker) later(f func()) *action {
195         i := len(check.delayed)
196         check.delayed = append(check.delayed, action{f: f})
197         return &check.delayed[i]
198 }
199
200 // push pushes obj onto the object path and returns its index in the path.
201 func (check *Checker) push(obj Object) int {
202         check.objPath = append(check.objPath, obj)
203         return len(check.objPath) - 1
204 }
205
206 // pop pops and returns the topmost object from the object path.
207 func (check *Checker) pop() Object {
208         i := len(check.objPath) - 1
209         obj := check.objPath[i]
210         check.objPath[i] = nil
211         check.objPath = check.objPath[:i]
212         return obj
213 }
214
215 type cleaner interface {
216         cleanup()
217 }
218
219 // needsCleanup records objects/types that implement the cleanup method
220 // which will be called at the end of type-checking.
221 func (check *Checker) needsCleanup(c cleaner) {
222         check.cleaners = append(check.cleaners, c)
223 }
224
225 // NewChecker returns a new Checker instance for a given package.
226 // Package files may be added incrementally via checker.Files.
227 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
228         // make sure we have a configuration
229         if conf == nil {
230                 conf = new(Config)
231         }
232
233         // make sure we have an info struct
234         if info == nil {
235                 info = new(Info)
236         }
237
238         version, versionErr := parseGoVersion(conf.GoVersion)
239         if pkg != nil {
240                 pkg.goVersion = conf.GoVersion
241         }
242
243         return &Checker{
244                 conf:       conf,
245                 ctxt:       conf.Context,
246                 fset:       fset,
247                 pkg:        pkg,
248                 Info:       info,
249                 version:    version,
250                 versionErr: versionErr,
251                 objMap:     make(map[Object]*declInfo),
252                 impMap:     make(map[importKey]*Package),
253         }
254 }
255
256 // initFiles initializes the files-specific portion of checker.
257 // The provided files must all belong to the same package.
258 func (check *Checker) initFiles(files []*ast.File) {
259         // start with a clean slate (check.Files may be called multiple times)
260         check.files = nil
261         check.imports = nil
262         check.dotImportMap = nil
263
264         check.firstErr = nil
265         check.methods = nil
266         check.untyped = nil
267         check.delayed = nil
268         check.objPath = nil
269         check.cleaners = nil
270
271         // determine package name and collect valid files
272         pkg := check.pkg
273         for _, file := range files {
274                 switch name := file.Name.Name; pkg.name {
275                 case "":
276                         if name != "_" {
277                                 pkg.name = name
278                         } else {
279                                 check.error(file.Name, BlankPkgName, "invalid package name _")
280                         }
281                         fallthrough
282
283                 case name:
284                         check.files = append(check.files, file)
285
286                 default:
287                         check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected %s", name, pkg.name)
288                         // ignore this file
289                 }
290         }
291
292         for _, file := range check.files {
293                 v, _ := parseGoVersion(file.GoVersion)
294                 if v.major > 0 {
295                         if v.equal(check.version) {
296                                 continue
297                         }
298                         // Go 1.21 introduced the feature of setting the go.mod
299                         // go line to an early version of Go and allowing //go:build lines
300                         // to “upgrade” the Go version in a given file.
301                         // We can do that backwards compatibly.
302                         // Go 1.21 also introduced the feature of allowing //go:build lines
303                         // to “downgrade” the Go version in a given file.
304                         // That can't be done compatibly in general, since before the
305                         // build lines were ignored and code got the module's Go version.
306                         // To work around this, downgrades are only allowed when the
307                         // module's Go version is Go 1.21 or later.
308                         // If there is no check.version, then we don't really know what Go version to apply.
309                         // Legacy tools may do this, and they historically have accepted everything.
310                         // Preserve that behavior by ignoring //go:build constraints entirely in that case.
311                         if (v.before(check.version) && check.version.before(version{1, 21})) || check.version.equal(version{0, 0}) {
312                                 continue
313                         }
314                         if check.posVers == nil {
315                                 check.posVers = make(map[*token.File]version)
316                         }
317                         check.posVers[check.fset.File(file.FileStart)] = v
318                 }
319         }
320 }
321
322 // A posVers records that the file starting at pos declares the Go version vers.
323 type posVers struct {
324         pos  token.Pos
325         vers version
326 }
327
328 // A bailout panic is used for early termination.
329 type bailout struct{}
330
331 func (check *Checker) handleBailout(err *error) {
332         switch p := recover().(type) {
333         case nil, bailout:
334                 // normal return or early exit
335                 *err = check.firstErr
336         default:
337                 // re-panic
338                 panic(p)
339         }
340 }
341
342 // Files checks the provided files as part of the checker's package.
343 func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
344
345 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
346
347 func (check *Checker) checkFiles(files []*ast.File) (err error) {
348         if check.versionErr != nil {
349                 return check.versionErr
350         }
351         if check.version.after(version{1, goversion.Version}) {
352                 return fmt.Errorf("package requires newer Go version %v", check.version)
353         }
354         if check.conf.FakeImportC && check.conf.go115UsesCgo {
355                 return errBadCgo
356         }
357
358         defer check.handleBailout(&err)
359
360         print := func(msg string) {
361                 if check.conf._Trace {
362                         fmt.Println()
363                         fmt.Println(msg)
364                 }
365         }
366
367         print("== initFiles ==")
368         check.initFiles(files)
369
370         print("== collectObjects ==")
371         check.collectObjects()
372
373         print("== packageObjects ==")
374         check.packageObjects()
375
376         print("== processDelayed ==")
377         check.processDelayed(0) // incl. all functions
378
379         print("== cleanup ==")
380         check.cleanup()
381
382         print("== initOrder ==")
383         check.initOrder()
384
385         if !check.conf.DisableUnusedImportCheck {
386                 print("== unusedImports ==")
387                 check.unusedImports()
388         }
389
390         print("== recordUntyped ==")
391         check.recordUntyped()
392
393         if check.firstErr == nil {
394                 // TODO(mdempsky): Ensure monomorph is safe when errors exist.
395                 check.monomorph()
396         }
397
398         check.pkg.complete = true
399
400         // no longer needed - release memory
401         check.imports = nil
402         check.dotImportMap = nil
403         check.pkgPathMap = nil
404         check.seenPkgMap = nil
405         check.recvTParamMap = nil
406         check.brokenAliases = nil
407         check.unionTypeSets = nil
408         check.ctxt = nil
409
410         // TODO(rFindley) There's more memory we should release at this point.
411
412         return
413 }
414
415 // processDelayed processes all delayed actions pushed after top.
416 func (check *Checker) processDelayed(top int) {
417         // If each delayed action pushes a new action, the
418         // stack will continue to grow during this loop.
419         // However, it is only processing functions (which
420         // are processed in a delayed fashion) that may
421         // add more actions (such as nested functions), so
422         // this is a sufficiently bounded process.
423         for i := top; i < len(check.delayed); i++ {
424                 a := &check.delayed[i]
425                 if check.conf._Trace {
426                         if a.desc != nil {
427                                 check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
428                         } else {
429                                 check.trace(nopos, "-- delayed %p", a.f)
430                         }
431                 }
432                 a.f() // may append to check.delayed
433                 if check.conf._Trace {
434                         fmt.Println()
435                 }
436         }
437         assert(top <= len(check.delayed)) // stack must not have shrunk
438         check.delayed = check.delayed[:top]
439 }
440
441 // cleanup runs cleanup for all collected cleaners.
442 func (check *Checker) cleanup() {
443         // Don't use a range clause since Named.cleanup may add more cleaners.
444         for i := 0; i < len(check.cleaners); i++ {
445                 check.cleaners[i].cleanup()
446         }
447         check.cleaners = nil
448 }
449
450 func (check *Checker) record(x *operand) {
451         // convert x into a user-friendly set of values
452         // TODO(gri) this code can be simplified
453         var typ Type
454         var val constant.Value
455         switch x.mode {
456         case invalid:
457                 typ = Typ[Invalid]
458         case novalue:
459                 typ = (*Tuple)(nil)
460         case constant_:
461                 typ = x.typ
462                 val = x.val
463         default:
464                 typ = x.typ
465         }
466         assert(x.expr != nil && typ != nil)
467
468         if isUntyped(typ) {
469                 // delay type and value recording until we know the type
470                 // or until the end of type checking
471                 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
472         } else {
473                 check.recordTypeAndValue(x.expr, x.mode, typ, val)
474         }
475 }
476
477 func (check *Checker) recordUntyped() {
478         if !debug && check.Types == nil {
479                 return // nothing to do
480         }
481
482         for x, info := range check.untyped {
483                 if debug && isTyped(info.typ) {
484                         check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
485                         unreachable()
486                 }
487                 check.recordTypeAndValue(x, info.mode, info.typ, info.val)
488         }
489 }
490
491 func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
492         assert(x != nil)
493         assert(typ != nil)
494         if mode == invalid {
495                 return // omit
496         }
497         if mode == constant_ {
498                 assert(val != nil)
499                 // We check allBasic(typ, IsConstType) here as constant expressions may be
500                 // recorded as type parameters.
501                 assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
502         }
503         if m := check.Types; m != nil {
504                 m[x] = TypeAndValue{mode, typ, val}
505         }
506 }
507
508 func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
509         // f must be a (possibly parenthesized, possibly qualified)
510         // identifier denoting a built-in (including unsafe's non-constant
511         // functions Add and Slice): record the signature for f and possible
512         // children.
513         for {
514                 check.recordTypeAndValue(f, builtin, sig, nil)
515                 switch p := f.(type) {
516                 case *ast.Ident, *ast.SelectorExpr:
517                         return // we're done
518                 case *ast.ParenExpr:
519                         f = p.X
520                 default:
521                         unreachable()
522                 }
523         }
524 }
525
526 // recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
527 // (and therefore has tuple type).
528 func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
529         assert(x != nil)
530         assert(len(a) == 2)
531         if a[0].mode == invalid {
532                 return
533         }
534         t0, t1 := a[0].typ, a[1].typ
535         assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
536         if m := check.Types; m != nil {
537                 for {
538                         tv := m[x]
539                         assert(tv.Type != nil) // should have been recorded already
540                         pos := x.Pos()
541                         tv.Type = NewTuple(
542                                 NewVar(pos, check.pkg, "", t0),
543                                 NewVar(pos, check.pkg, "", t1),
544                         )
545                         m[x] = tv
546                         // if x is a parenthesized expression (p.X), update p.X
547                         p, _ := x.(*ast.ParenExpr)
548                         if p == nil {
549                                 break
550                         }
551                         x = p.X
552                 }
553         }
554 }
555
556 // recordInstance records instantiation information into check.Info, if the
557 // Instances map is non-nil. The given expr must be an ident, selector, or
558 // index (list) expr with ident or selector operand.
559 //
560 // TODO(rfindley): the expr parameter is fragile. See if we can access the
561 // instantiated identifier in some other way.
562 func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
563         ident := instantiatedIdent(expr)
564         assert(ident != nil)
565         assert(typ != nil)
566         if m := check.Instances; m != nil {
567                 m[ident] = Instance{newTypeList(targs), typ}
568         }
569 }
570
571 func instantiatedIdent(expr ast.Expr) *ast.Ident {
572         var selOrIdent ast.Expr
573         switch e := expr.(type) {
574         case *ast.IndexExpr:
575                 selOrIdent = e.X
576         case *ast.IndexListExpr:
577                 selOrIdent = e.X
578         case *ast.SelectorExpr, *ast.Ident:
579                 selOrIdent = e
580         }
581         switch x := selOrIdent.(type) {
582         case *ast.Ident:
583                 return x
584         case *ast.SelectorExpr:
585                 return x.Sel
586         }
587         panic("instantiated ident not found")
588 }
589
590 func (check *Checker) recordDef(id *ast.Ident, obj Object) {
591         assert(id != nil)
592         if m := check.Defs; m != nil {
593                 m[id] = obj
594         }
595 }
596
597 func (check *Checker) recordUse(id *ast.Ident, obj Object) {
598         assert(id != nil)
599         assert(obj != nil)
600         if m := check.Uses; m != nil {
601                 m[id] = obj
602         }
603 }
604
605 func (check *Checker) recordImplicit(node ast.Node, obj Object) {
606         assert(node != nil)
607         assert(obj != nil)
608         if m := check.Implicits; m != nil {
609                 m[node] = obj
610         }
611 }
612
613 func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
614         assert(obj != nil && (recv == nil || len(index) > 0))
615         check.recordUse(x.Sel, obj)
616         if m := check.Selections; m != nil {
617                 m[x] = &Selection{kind, recv, obj, index, indirect}
618         }
619 }
620
621 func (check *Checker) recordScope(node ast.Node, scope *Scope) {
622         assert(node != nil)
623         assert(scope != nil)
624         if m := check.Scopes; m != nil {
625                 m[node] = scope
626         }
627 }