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