1 // Copyright 2012 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.
5 // Package types declares the data types and implements
6 // the algorithms for type-checking of Go packages. Use
7 // Config.Check to invoke the type checker for a package.
8 // Alternatively, create a new type checker with NewChecker
9 // and invoke it incrementally by calling Checker.Files.
11 // Type-checking consists of several interdependent phases:
13 // Name resolution maps each identifier (syntax.Name) in the program to the
14 // language object (Object) it denotes.
15 // Use Info.{Defs,Uses,Implicits} for the results of name resolution.
17 // Constant folding computes the exact constant value (constant.Value)
18 // for every expression (syntax.Expr) that is a compile-time constant.
19 // Use Info.Types[expr].Value for the results of constant folding.
21 // Type inference computes the type (Type) of every expression (syntax.Expr)
22 // and checks for compliance with the language specification.
23 // Use Info.Types[expr].Type for the results of type inference.
27 "cmd/compile/internal/syntax"
30 . "internal/types/errors"
34 // An Error describes a type-checking error; it implements the error interface.
35 // A "soft" error is an error that still permits a valid interpretation of a
36 // package (such as "unused variable"); "hard" errors may lead to unpredictable
37 // behavior if ignored.
39 Pos syntax.Pos // error position
40 Msg string // default error message, user-friendly
41 Full string // full error message, for debugging (may contain internal details)
42 Soft bool // if set, error is "soft"
43 Code Code // error code
46 // Error returns an error string formatted as follows:
47 // filename:line:column: message
48 func (err Error) Error() string {
49 return fmt.Sprintf("%s: %s", err.Pos, err.Msg)
52 // FullError returns an error string like Error, buy it may contain
53 // type-checker internal details such as subscript indices for type
54 // parameters and more. Useful for debugging.
55 func (err Error) FullError() string {
56 return fmt.Sprintf("%s: %s", err.Pos, err.Full)
59 // An ArgumentError holds an error associated with an argument index.
60 type ArgumentError struct {
65 func (e *ArgumentError) Error() string { return e.Err.Error() }
66 func (e *ArgumentError) Unwrap() error { return e.Err }
68 // An Importer resolves import paths to Packages.
70 // CAUTION: This interface does not support the import of locally
71 // vendored packages. See https://golang.org/s/go15vendor.
72 // If possible, external implementations should implement ImporterFrom.
73 type Importer interface {
74 // Import returns the imported package for the given import path.
75 // The semantics is like for ImporterFrom.ImportFrom except that
76 // dir and mode are ignored (since they are not present).
77 Import(path string) (*Package, error)
80 // ImportMode is reserved for future use.
83 // An ImporterFrom resolves import paths to packages; it
84 // supports vendoring per https://golang.org/s/go15vendor.
85 // Use go/importer to obtain an ImporterFrom implementation.
86 type ImporterFrom interface {
87 // Importer is present for backward-compatibility. Calling
88 // Import(path) is the same as calling ImportFrom(path, "", 0);
89 // i.e., locally vendored packages may not be found.
90 // The types package does not call Import if an ImporterFrom
94 // ImportFrom returns the imported package for the given import
95 // path when imported by a package file located in dir.
96 // If the import failed, besides returning an error, ImportFrom
97 // is encouraged to cache and return a package anyway, if one
98 // was created. This will reduce package inconsistencies and
99 // follow-on type checker errors due to the missing package.
100 // The mode value must be 0; it is reserved for future use.
101 // Two calls to ImportFrom with the same path and dir must
102 // return the same package.
103 ImportFrom(path, dir string, mode ImportMode) (*Package, error)
106 // A Config specifies the configuration for type checking.
107 // The zero value for Config is a ready-to-use default configuration.
109 // Context is the context used for resolving global identifiers. If nil, the
110 // type checker will initialize this field with a newly created context.
113 // GoVersion describes the accepted Go language version. The string must
114 // start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or
115 // "go1.21.0") or it must be empty; an empty string disables Go language
116 // version checks. If the format is invalid, invoking the type checker will
117 // result in an error.
120 // If IgnoreFuncBodies is set, function bodies are not
122 IgnoreFuncBodies bool
124 // If FakeImportC is set, `import "C"` (for packages requiring Cgo)
125 // declares an empty "C" package and errors are omitted for qualified
126 // identifiers referring to package C (which won't find an object).
127 // This feature is intended for the standard library cmd/api tool.
129 // Caution: Effects may be unpredictable due to follow-on errors.
130 // Do not use casually!
133 // If IgnoreBranchErrors is set, branch/label errors are ignored.
134 IgnoreBranchErrors bool
136 // If go115UsesCgo is set, the type checker expects the
137 // _cgo_gotypes.go file generated by running cmd/cgo to be
138 // provided as a package source file. Qualified identifiers
139 // referring to package C will be resolved to cgo-provided
140 // declarations within _cgo_gotypes.go.
142 // It is an error to set both FakeImportC and go115UsesCgo.
145 // If Trace is set, a debug trace is printed to stdout.
148 // If Error != nil, it is called with each error found
149 // during type checking; err has dynamic type Error.
150 // Secondary errors (for instance, to enumerate all types
151 // involved in an invalid recursive type declaration) have
152 // error strings that start with a '\t' character.
153 // If Error == nil, type-checking stops with the first
155 Error func(err error)
157 // An importer is used to import packages referred to from
158 // import declarations.
159 // If the installed importer implements ImporterFrom, the type
160 // checker calls ImportFrom instead of Import.
161 // The type checker reports an error if an importer is needed
162 // but none was installed.
165 // If Sizes != nil, it provides the sizing functions for package unsafe.
166 // Otherwise SizesFor("gc", "amd64") is used instead.
169 // If DisableUnusedImportCheck is set, packages are not checked
170 // for unused imports.
171 DisableUnusedImportCheck bool
173 // If EnableAlias is set, alias declarations produce an _Alias type.
174 // Otherwise the alias information is only in the type name, which
175 // points directly to the actual (aliased) type.
178 // If a non-empty ErrorURL format string is provided, it is used
179 // to format an error URL link that is appended to the first line
180 // of an error message. ErrorURL must be a format string containing
181 // exactly one "%s" format, e.g. "[go.dev/e/%s]".
185 func srcimporter_setUsesCgo(conf *Config) {
186 conf.go115UsesCgo = true
189 // Info holds result type information for a type-checked package.
190 // Only the information for which a map is provided is collected.
191 // If the package has type errors, the collected information may
194 // Types maps expressions to their types, and for constant
195 // expressions, also their values. Invalid expressions are
198 // For (possibly parenthesized) identifiers denoting built-in
199 // functions, the recorded signatures are call-site specific:
200 // if the call result is not a constant, the recorded type is
201 // an argument-specific signature. Otherwise, the recorded type
204 // The Types map does not record the type of every identifier,
205 // only those that appear where an arbitrary expression is
206 // permitted. For instance, the identifier f in a selector
207 // expression x.f is found only in the Selections map, the
208 // identifier z in a variable declaration 'var z int' is found
209 // only in the Defs map, and identifiers denoting packages in
210 // qualified identifiers are collected in the Uses map.
211 Types map[syntax.Expr]TypeAndValue
213 // If StoreTypesInSyntax is set, type information identical to
214 // that which would be put in the Types map, will be set in
215 // syntax.Expr.TypeAndValue (independently of whether Types
217 StoreTypesInSyntax bool
219 // Instances maps identifiers denoting generic types or functions to their
220 // type arguments and instantiated type.
222 // For example, Instances will map the identifier for 'T' in the type
223 // instantiation T[int, string] to the type arguments [int, string] and
224 // resulting instantiated *Named type. Given a generic function
225 // func F[A any](A), Instances will map the identifier for 'F' in the call
226 // expression F(int(1)) to the inferred type arguments [int], and resulting
227 // instantiated *Signature.
229 // Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
230 // results in an equivalent of Instances[id].Type.
231 Instances map[*syntax.Name]Instance
233 // Defs maps identifiers to the objects they define (including
234 // package names, dots "." of dot-imports, and blank "_" identifiers).
235 // For identifiers that do not denote objects (e.g., the package name
236 // in package clauses, or symbolic variables t in t := x.(type) of
237 // type switch headers), the corresponding objects are nil.
239 // For an embedded field, Defs returns the field *Var it defines.
241 // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
242 Defs map[*syntax.Name]Object
244 // Uses maps identifiers to the objects they denote.
246 // For an embedded field, Uses returns the *TypeName it denotes.
248 // Invariant: Uses[id].Pos() != id.Pos()
249 Uses map[*syntax.Name]Object
251 // Implicits maps nodes to their implicitly declared objects, if any.
252 // The following node and object types may appear:
254 // node declared object
256 // *syntax.ImportDecl *PkgName for imports without renames
257 // *syntax.CaseClause type-specific *Var for each type switch case clause (incl. default)
258 // *syntax.Field anonymous parameter *Var (incl. unnamed results)
260 Implicits map[syntax.Node]Object
262 // Selections maps selector expressions (excluding qualified identifiers)
263 // to their corresponding selections.
264 Selections map[*syntax.SelectorExpr]*Selection
266 // Scopes maps syntax.Nodes to the scopes they define. Package scopes are not
267 // associated with a specific node but with all files belonging to a package.
268 // Thus, the package scope can be found in the type-checked Package object.
269 // Scopes nest, with the Universe scope being the outermost scope, enclosing
270 // the package scope, which contains (one or more) files scopes, which enclose
271 // function scopes which in turn enclose statement and function literal scopes.
272 // Note that even though package-level functions are declared in the package
273 // scope, the function scopes are embedded in the file scope of the file
274 // containing the function declaration.
276 // The following node types may appear in Scopes:
283 // *syntax.SwitchStmt
284 // *syntax.CaseClause
285 // *syntax.CommClause
288 Scopes map[syntax.Node]*Scope
290 // InitOrder is the list of package-level initializers in the order in which
291 // they must be executed. Initializers referring to variables related by an
292 // initialization dependency appear in topological order, the others appear
293 // in source order. Variables without an initialization expression do not
294 // appear in this list.
295 InitOrder []*Initializer
297 // FileVersions maps a file to its Go version string.
298 // If the file doesn't specify a version, the reported
299 // string is Config.GoVersion.
300 // Version strings begin with “go”, like “go1.21”, and
301 // are suitable for use with the [go/version] package.
302 FileVersions map[*syntax.PosBase]string
305 func (info *Info) recordTypes() bool {
306 return info.Types != nil || info.StoreTypesInSyntax
309 // TypeOf returns the type of expression e, or nil if not found.
310 // Precondition 1: the Types map is populated or StoreTypesInSynax is set.
311 // Precondition 2: Uses and Defs maps are populated.
312 func (info *Info) TypeOf(e syntax.Expr) Type {
313 if info.Types != nil {
314 if t, ok := info.Types[e]; ok {
317 } else if info.StoreTypesInSyntax {
318 if tv := e.GetTypeInfo(); tv.Type != nil {
323 if id, _ := e.(*syntax.Name); id != nil {
324 if obj := info.ObjectOf(id); obj != nil {
331 // ObjectOf returns the object denoted by the specified id,
332 // or nil if not found.
334 // If id is an embedded struct field, ObjectOf returns the field (*Var)
335 // it defines, not the type (*TypeName) it uses.
337 // Precondition: the Uses and Defs maps are populated.
338 func (info *Info) ObjectOf(id *syntax.Name) Object {
339 if obj := info.Defs[id]; obj != nil {
345 // PkgNameOf returns the local package name defined by the import,
346 // or nil if not found.
348 // For dot-imports, the package name is ".".
350 // Precondition: the Defs and Implicts maps are populated.
351 func (info *Info) PkgNameOf(imp *syntax.ImportDecl) *PkgName {
353 if imp.LocalPkgName != nil {
354 obj = info.Defs[imp.LocalPkgName]
356 obj = info.Implicits[imp]
358 pkgname, _ := obj.(*PkgName)
362 // TypeAndValue reports the type and value (for constants)
363 // of the corresponding expression.
364 type TypeAndValue struct {
370 // IsVoid reports whether the corresponding expression
371 // is a function call without results.
372 func (tv TypeAndValue) IsVoid() bool {
373 return tv.mode == novalue
376 // IsType reports whether the corresponding expression specifies a type.
377 func (tv TypeAndValue) IsType() bool {
378 return tv.mode == typexpr
381 // IsBuiltin reports whether the corresponding expression denotes
382 // a (possibly parenthesized) built-in function.
383 func (tv TypeAndValue) IsBuiltin() bool {
384 return tv.mode == builtin
387 // IsValue reports whether the corresponding expression is a value.
388 // Builtins are not considered values. Constant values have a non-
390 func (tv TypeAndValue) IsValue() bool {
392 case constant_, variable, mapindex, value, nilvalue, commaok, commaerr:
398 // IsNil reports whether the corresponding expression denotes the
399 // predeclared value nil. Depending on context, it may have been
400 // given a type different from UntypedNil.
401 func (tv TypeAndValue) IsNil() bool {
402 return tv.mode == nilvalue
405 // Addressable reports whether the corresponding expression
406 // is addressable (https://golang.org/ref/spec#Address_operators).
407 func (tv TypeAndValue) Addressable() bool {
408 return tv.mode == variable
411 // Assignable reports whether the corresponding expression
412 // is assignable to (provided a value of the right type).
413 func (tv TypeAndValue) Assignable() bool {
414 return tv.mode == variable || tv.mode == mapindex
417 // HasOk reports whether the corresponding expression may be
418 // used on the rhs of a comma-ok assignment.
419 func (tv TypeAndValue) HasOk() bool {
420 return tv.mode == commaok || tv.mode == mapindex
423 // Instance reports the type arguments and instantiated type for type and
424 // function instantiations. For type instantiations, Type will be of dynamic
425 // type *Named. For function instantiations, Type will be of dynamic type
427 type Instance struct {
432 // An Initializer describes a package-level variable, or a list of variables in case
433 // of a multi-valued initialization expression, and the corresponding initialization
435 type Initializer struct {
436 Lhs []*Var // var Lhs = Rhs
440 func (init *Initializer) String() string {
441 var buf strings.Builder
442 for i, lhs := range init.Lhs {
444 buf.WriteString(", ")
446 buf.WriteString(lhs.Name())
448 buf.WriteString(" = ")
449 syntax.Fprint(&buf, init.Rhs, syntax.ShortForm)
453 // Check type-checks a package and returns the resulting package object and
454 // the first error if any. Additionally, if info != nil, Check populates each
455 // of the non-nil maps in the Info struct.
457 // The package is marked as complete if no errors occurred, otherwise it is
458 // incomplete. See Config.Error for controlling behavior in the presence of
461 // The package is specified by a list of *syntax.Files and corresponding
462 // file set, and the package path the package is identified with.
463 // The clean path must not be empty or dot (".").
464 func (conf *Config) Check(path string, files []*syntax.File, info *Info) (*Package, error) {
465 pkg := NewPackage(path, "")
466 return pkg, NewChecker(conf, pkg, info).Files(files)
469 // AssertableTo reports whether a value of type V can be asserted to have type T.
471 // The behavior of AssertableTo is unspecified in three cases:
472 // - if T is Typ[Invalid]
473 // - if V is a generalized interface; i.e., an interface that may only be used
474 // as a type constraint in Go code
475 // - if T is an uninstantiated generic type
476 func AssertableTo(V *Interface, T Type) bool {
477 // Checker.newAssertableTo suppresses errors for invalid types, so we need special
479 if !isValid(T.Underlying()) {
482 return (*Checker)(nil).newAssertableTo(nopos, V, T, nil)
485 // AssignableTo reports whether a value of type V is assignable to a variable
488 // The behavior of AssignableTo is unspecified if V or T is Typ[Invalid] or an
489 // uninstantiated generic type.
490 func AssignableTo(V, T Type) bool {
491 x := operand{mode: value, typ: V}
492 ok, _ := x.assignableTo(nil, T, nil) // check not needed for non-constant x
496 // ConvertibleTo reports whether a value of type V is convertible to a value of
499 // The behavior of ConvertibleTo is unspecified if V or T is Typ[Invalid] or an
500 // uninstantiated generic type.
501 func ConvertibleTo(V, T Type) bool {
502 x := operand{mode: value, typ: V}
503 return x.convertibleTo(nil, T, nil) // check not needed for non-constant x
506 // Implements reports whether type V implements interface T.
508 // The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated
510 func Implements(V Type, T *Interface) bool {
512 // All types (even Typ[Invalid]) implement the empty interface.
515 // Checker.implements suppresses errors for invalid types, so we need special
517 if !isValid(V.Underlying()) {
520 return (*Checker)(nil).implements(nopos, V, T, false, nil)
523 // Satisfies reports whether type V satisfies the constraint T.
525 // The behavior of Satisfies is unspecified if V is Typ[Invalid] or an uninstantiated
527 func Satisfies(V Type, T *Interface) bool {
528 return (*Checker)(nil).implements(nopos, V, T, true, nil)
531 // Identical reports whether x and y are identical types.
532 // Receivers of Signature types are ignored.
533 func Identical(x, y Type) bool {
535 return c.identical(x, y, nil)
538 // IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored.
539 // Receivers of Signature types are ignored.
540 func IdenticalIgnoreTags(x, y Type) bool {
543 return c.identical(x, y, nil)