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