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