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