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