Source file src/go/types/api.go
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. 4 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]. 10 // 11 // Type-checking consists of several interdependent phases: 12 // 13 // Name resolution maps each identifier ([ast.Ident]) in the program 14 // to the symbol ([Object]) it denotes. Use the Defs and Uses fields 15 // of [Info] or the [Info.ObjectOf] method to find the symbol for an 16 // identifier, and use the Implicits field of [Info] to find the 17 // symbol for certain other kinds of syntax node. 18 // 19 // Constant folding computes the exact constant value 20 // ([constant.Value]) of every expression ([ast.Expr]) that is a 21 // compile-time constant. Use the Types field of [Info] to find the 22 // results of constant folding for an expression. 23 // 24 // Type deduction computes the type ([Type]) of every expression 25 // ([ast.Expr]) and checks for compliance with the language 26 // specification. Use the Types field of [Info] for the results of 27 // type deduction. 28 // 29 // For a tutorial, see https://go.dev/s/types-tutorial. 30 package types 31 32 import ( 33 "bytes" 34 "fmt" 35 "go/ast" 36 "go/constant" 37 "go/token" 38 . "internal/types/errors" 39 ) 40 41 // An Error describes a type-checking error; it implements the error interface. 42 // A "soft" error is an error that still permits a valid interpretation of a 43 // package (such as "unused variable"); "hard" errors may lead to unpredictable 44 // behavior if ignored. 45 type Error struct { 46 Fset *token.FileSet // file set for interpretation of Pos 47 Pos token.Pos // error position 48 Msg string // error message 49 Soft bool // if set, error is "soft" 50 51 // go116code is a future API, unexported as the set of error codes is large 52 // and likely to change significantly during experimentation. Tools wishing 53 // to preview this feature may read go116code using reflection (see 54 // errorcodes_test.go), but beware that there is no guarantee of future 55 // compatibility. 56 go116code Code 57 go116start token.Pos 58 go116end token.Pos 59 } 60 61 // Error returns an error string formatted as follows: 62 // filename:line:column: message 63 func (err Error) Error() string { 64 return fmt.Sprintf("%s: %s", err.Fset.Position(err.Pos), err.Msg) 65 } 66 67 // An ArgumentError holds an error associated with an argument index. 68 type ArgumentError struct { 69 Index int 70 Err error 71 } 72 73 func (e *ArgumentError) Error() string { return e.Err.Error() } 74 func (e *ArgumentError) Unwrap() error { return e.Err } 75 76 // An Importer resolves import paths to Packages. 77 // 78 // CAUTION: This interface does not support the import of locally 79 // vendored packages. See https://golang.org/s/go15vendor. 80 // If possible, external implementations should implement [ImporterFrom]. 81 type Importer interface { 82 // Import returns the imported package for the given import path. 83 // The semantics is like for ImporterFrom.ImportFrom except that 84 // dir and mode are ignored (since they are not present). 85 Import(path string) (*Package, error) 86 } 87 88 // ImportMode is reserved for future use. 89 type ImportMode int 90 91 // An ImporterFrom resolves import paths to packages; it 92 // supports vendoring per https://golang.org/s/go15vendor. 93 // Use go/importer to obtain an ImporterFrom implementation. 94 type ImporterFrom interface { 95 // Importer is present for backward-compatibility. Calling 96 // Import(path) is the same as calling ImportFrom(path, "", 0); 97 // i.e., locally vendored packages may not be found. 98 // The types package does not call Import if an ImporterFrom 99 // is present. 100 Importer 101 102 // ImportFrom returns the imported package for the given import 103 // path when imported by a package file located in dir. 104 // If the import failed, besides returning an error, ImportFrom 105 // is encouraged to cache and return a package anyway, if one 106 // was created. This will reduce package inconsistencies and 107 // follow-on type checker errors due to the missing package. 108 // The mode value must be 0; it is reserved for future use. 109 // Two calls to ImportFrom with the same path and dir must 110 // return the same package. 111 ImportFrom(path, dir string, mode ImportMode) (*Package, error) 112 } 113 114 // A Config specifies the configuration for type checking. 115 // The zero value for Config is a ready-to-use default configuration. 116 type Config struct { 117 // Context is the context used for resolving global identifiers. If nil, the 118 // type checker will initialize this field with a newly created context. 119 Context *Context 120 121 // GoVersion describes the accepted Go language version. The string must 122 // start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or 123 // "go1.21.0") or it must be empty; an empty string disables Go language 124 // version checks. If the format is invalid, invoking the type checker will 125 // result in an error. 126 GoVersion string 127 128 // If IgnoreFuncBodies is set, function bodies are not 129 // type-checked. 130 IgnoreFuncBodies bool 131 132 // If FakeImportC is set, `import "C"` (for packages requiring Cgo) 133 // declares an empty "C" package and errors are omitted for qualified 134 // identifiers referring to package C (which won't find an object). 135 // This feature is intended for the standard library cmd/api tool. 136 // 137 // Caution: Effects may be unpredictable due to follow-on errors. 138 // Do not use casually! 139 FakeImportC bool 140 141 // If go115UsesCgo is set, the type checker expects the 142 // _cgo_gotypes.go file generated by running cmd/cgo to be 143 // provided as a package source file. Qualified identifiers 144 // referring to package C will be resolved to cgo-provided 145 // declarations within _cgo_gotypes.go. 146 // 147 // It is an error to set both FakeImportC and go115UsesCgo. 148 go115UsesCgo bool 149 150 // If _Trace is set, a debug trace is printed to stdout. 151 _Trace bool 152 153 // If Error != nil, it is called with each error found 154 // during type checking; err has dynamic type Error. 155 // Secondary errors (for instance, to enumerate all types 156 // involved in an invalid recursive type declaration) have 157 // error strings that start with a '\t' character. 158 // If Error == nil, type-checking stops with the first 159 // error found. 160 Error func(err error) 161 162 // An importer is used to import packages referred to from 163 // import declarations. 164 // If the installed importer implements ImporterFrom, the type 165 // checker calls ImportFrom instead of Import. 166 // The type checker reports an error if an importer is needed 167 // but none was installed. 168 Importer Importer 169 170 // If Sizes != nil, it provides the sizing functions for package unsafe. 171 // Otherwise SizesFor("gc", "amd64") is used instead. 172 Sizes Sizes 173 174 // If DisableUnusedImportCheck is set, packages are not checked 175 // for unused imports. 176 DisableUnusedImportCheck bool 177 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]". 182 _ErrorURL string 183 184 // If _EnableAlias is set, alias declarations produce an Alias type. 185 // Otherwise the alias information is only in the type name, which 186 // points directly to the actual (aliased) type. 187 // This flag will eventually be removed (with Go 1.24 at the earliest). 188 _EnableAlias bool 189 } 190 191 func srcimporter_setUsesCgo(conf *Config) { 192 conf.go115UsesCgo = true 193 } 194 195 // Info holds result type information for a type-checked package. 196 // Only the information for which a map is provided is collected. 197 // If the package has type errors, the collected information may 198 // be incomplete. 199 type Info struct { 200 // Types maps expressions to their types, and for constant 201 // expressions, also their values. Invalid expressions are 202 // omitted. 203 // 204 // For (possibly parenthesized) identifiers denoting built-in 205 // functions, the recorded signatures are call-site specific: 206 // if the call result is not a constant, the recorded type is 207 // an argument-specific signature. Otherwise, the recorded type 208 // is invalid. 209 // 210 // The Types map does not record the type of every identifier, 211 // only those that appear where an arbitrary expression is 212 // permitted. For instance, the identifier f in a selector 213 // expression x.f is found only in the Selections map, the 214 // identifier z in a variable declaration 'var z int' is found 215 // only in the Defs map, and identifiers denoting packages in 216 // qualified identifiers are collected in the Uses map. 217 Types map[ast.Expr]TypeAndValue 218 219 // Instances maps identifiers denoting generic types or functions to their 220 // type arguments and instantiated type. 221 // 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. 228 // 229 // Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs 230 // results in an equivalent of Instances[id].Type. 231 Instances map[*ast.Ident]Instance 232 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. 238 // 239 // For an embedded field, Defs returns the field *Var it defines. 240 // 241 // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos() 242 Defs map[*ast.Ident]Object 243 244 // Uses maps identifiers to the objects they denote. 245 // 246 // For an embedded field, Uses returns the *TypeName it denotes. 247 // 248 // Invariant: Uses[id].Pos() != id.Pos() 249 Uses map[*ast.Ident]Object 250 251 // Implicits maps nodes to their implicitly declared objects, if any. 252 // The following node and object types may appear: 253 // 254 // node declared object 255 // 256 // *ast.ImportSpec *PkgName for imports without renames 257 // *ast.CaseClause type-specific *Var for each type switch case clause (incl. default) 258 // *ast.Field anonymous parameter *Var (incl. unnamed results) 259 // 260 Implicits map[ast.Node]Object 261 262 // Selections maps selector expressions (excluding qualified identifiers) 263 // to their corresponding selections. 264 Selections map[*ast.SelectorExpr]*Selection 265 266 // Scopes maps ast.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. 275 // 276 // The Scope of a function contains the declarations of any 277 // type parameters, parameters, and named results, plus any 278 // local declarations in the body block. 279 // It is coextensive with the complete extent of the 280 // function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]). 281 // The Scopes mapping does not contain an entry for the 282 // function body ([*ast.BlockStmt]); the function's scope is 283 // associated with the [*ast.FuncType]. 284 // 285 // The following node types may appear in Scopes: 286 // 287 // *ast.File 288 // *ast.FuncType 289 // *ast.TypeSpec 290 // *ast.BlockStmt 291 // *ast.IfStmt 292 // *ast.SwitchStmt 293 // *ast.TypeSwitchStmt 294 // *ast.CaseClause 295 // *ast.CommClause 296 // *ast.ForStmt 297 // *ast.RangeStmt 298 // 299 Scopes map[ast.Node]*Scope 300 301 // InitOrder is the list of package-level initializers in the order in which 302 // they must be executed. Initializers referring to variables related by an 303 // initialization dependency appear in topological order, the others appear 304 // in source order. Variables without an initialization expression do not 305 // appear in this list. 306 InitOrder []*Initializer 307 308 // FileVersions maps a file to its Go version string. 309 // If the file doesn't specify a version, the reported 310 // string is Config.GoVersion. 311 // Version strings begin with “go”, like “go1.21”, and 312 // are suitable for use with the [go/version] package. 313 FileVersions map[*ast.File]string 314 } 315 316 func (info *Info) recordTypes() bool { 317 return info.Types != nil 318 } 319 320 // TypeOf returns the type of expression e, or nil if not found. 321 // Precondition: the Types, Uses and Defs maps are populated. 322 func (info *Info) TypeOf(e ast.Expr) Type { 323 if t, ok := info.Types[e]; ok { 324 return t.Type 325 } 326 if id, _ := e.(*ast.Ident); id != nil { 327 if obj := info.ObjectOf(id); obj != nil { 328 return obj.Type() 329 } 330 } 331 return nil 332 } 333 334 // ObjectOf returns the object denoted by the specified id, 335 // or nil if not found. 336 // 337 // If id is an embedded struct field, [Info.ObjectOf] returns the field (*[Var]) 338 // it defines, not the type (*[TypeName]) it uses. 339 // 340 // Precondition: the Uses and Defs maps are populated. 341 func (info *Info) ObjectOf(id *ast.Ident) Object { 342 if obj := info.Defs[id]; obj != nil { 343 return obj 344 } 345 return info.Uses[id] 346 } 347 348 // PkgNameOf returns the local package name defined by the import, 349 // or nil if not found. 350 // 351 // For dot-imports, the package name is ".". 352 // 353 // Precondition: the Defs and Implicts maps are populated. 354 func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName { 355 var obj Object 356 if imp.Name != nil { 357 obj = info.Defs[imp.Name] 358 } else { 359 obj = info.Implicits[imp] 360 } 361 pkgname, _ := obj.(*PkgName) 362 return pkgname 363 } 364 365 // TypeAndValue reports the type and value (for constants) 366 // of the corresponding expression. 367 type TypeAndValue struct { 368 mode operandMode 369 Type Type 370 Value constant.Value 371 } 372 373 // IsVoid reports whether the corresponding expression 374 // is a function call without results. 375 func (tv TypeAndValue) IsVoid() bool { 376 return tv.mode == novalue 377 } 378 379 // IsType reports whether the corresponding expression specifies a type. 380 func (tv TypeAndValue) IsType() bool { 381 return tv.mode == typexpr 382 } 383 384 // IsBuiltin reports whether the corresponding expression denotes 385 // a (possibly parenthesized) built-in function. 386 func (tv TypeAndValue) IsBuiltin() bool { 387 return tv.mode == builtin 388 } 389 390 // IsValue reports whether the corresponding expression is a value. 391 // Builtins are not considered values. Constant values have a non- 392 // nil Value. 393 func (tv TypeAndValue) IsValue() bool { 394 switch tv.mode { 395 case constant_, variable, mapindex, value, commaok, commaerr: 396 return true 397 } 398 return false 399 } 400 401 // IsNil reports whether the corresponding expression denotes the 402 // predeclared value nil. 403 func (tv TypeAndValue) IsNil() bool { 404 return tv.mode == value && tv.Type == Typ[UntypedNil] 405 } 406 407 // Addressable reports whether the corresponding expression 408 // is addressable (https://golang.org/ref/spec#Address_operators). 409 func (tv TypeAndValue) Addressable() bool { 410 return tv.mode == variable 411 } 412 413 // Assignable reports whether the corresponding expression 414 // is assignable to (provided a value of the right type). 415 func (tv TypeAndValue) Assignable() bool { 416 return tv.mode == variable || tv.mode == mapindex 417 } 418 419 // HasOk reports whether the corresponding expression may be 420 // used on the rhs of a comma-ok assignment. 421 func (tv TypeAndValue) HasOk() bool { 422 return tv.mode == commaok || tv.mode == mapindex 423 } 424 425 // Instance reports the type arguments and instantiated type for type and 426 // function instantiations. For type instantiations, [Type] will be of dynamic 427 // type *[Named]. For function instantiations, [Type] will be of dynamic type 428 // *Signature. 429 type Instance struct { 430 TypeArgs *TypeList 431 Type Type 432 } 433 434 // An Initializer describes a package-level variable, or a list of variables in case 435 // of a multi-valued initialization expression, and the corresponding initialization 436 // expression. 437 type Initializer struct { 438 Lhs []*Var // var Lhs = Rhs 439 Rhs ast.Expr 440 } 441 442 func (init *Initializer) String() string { 443 var buf bytes.Buffer 444 for i, lhs := range init.Lhs { 445 if i > 0 { 446 buf.WriteString(", ") 447 } 448 buf.WriteString(lhs.Name()) 449 } 450 buf.WriteString(" = ") 451 WriteExpr(&buf, init.Rhs) 452 return buf.String() 453 } 454 455 // Check type-checks a package and returns the resulting package object and 456 // the first error if any. Additionally, if info != nil, Check populates each 457 // of the non-nil maps in the [Info] struct. 458 // 459 // The package is marked as complete if no errors occurred, otherwise it is 460 // incomplete. See [Config.Error] for controlling behavior in the presence of 461 // errors. 462 // 463 // The package is specified by a list of *ast.Files and corresponding 464 // file set, and the package path the package is identified with. 465 // The clean path must not be empty or dot ("."). 466 func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error) { 467 pkg := NewPackage(path, "") 468 return pkg, NewChecker(conf, fset, pkg, info).Files(files) 469 } 470