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 // In ill-typed code, such as a duplicate declaration of the 258 // same name, Defs may lack an entry for a declaring identifier. 259 // 260 // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos() 261 Defs map[*ast.Ident]Object 262 263 // Uses maps identifiers to the objects they denote. 264 // 265 // For an embedded field, Uses returns the *TypeName it denotes. 266 // 267 // Invariant: Uses[id].Pos() != id.Pos() 268 Uses map[*ast.Ident]Object 269 270 // Implicits maps nodes to their implicitly declared objects, if any. 271 // The following node and object types may appear: 272 // 273 // node declared object 274 // 275 // *ast.ImportSpec *PkgName for imports without renames 276 // *ast.CaseClause type-specific *Var for each type switch case clause (incl. default) 277 // *ast.Field anonymous parameter *Var (incl. unnamed results) 278 // 279 Implicits map[ast.Node]Object 280 281 // Selections maps selector expressions (excluding qualified identifiers) 282 // to their corresponding selections. 283 Selections map[*ast.SelectorExpr]*Selection 284 285 // Scopes maps ast.Nodes to the scopes they define. Package scopes are not 286 // associated with a specific node but with all files belonging to a package. 287 // Thus, the package scope can be found in the type-checked Package object. 288 // Scopes nest, with the Universe scope being the outermost scope, enclosing 289 // the package scope, which contains (one or more) files scopes, which enclose 290 // function scopes which in turn enclose statement and function literal scopes. 291 // Note that even though package-level functions are declared in the package 292 // scope, the function scopes are embedded in the file scope of the file 293 // containing the function declaration. 294 // 295 // The Scope of a function contains the declarations of any 296 // type parameters, parameters, and named results, plus any 297 // local declarations in the body block. 298 // It is coextensive with the complete extent of the 299 // function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]). 300 // The Scopes mapping does not contain an entry for the 301 // function body ([*ast.BlockStmt]); the function's scope is 302 // associated with the [*ast.FuncType]. 303 // 304 // The following node types may appear in Scopes: 305 // 306 // *ast.File 307 // *ast.FuncType 308 // *ast.TypeSpec 309 // *ast.BlockStmt 310 // *ast.IfStmt 311 // *ast.SwitchStmt 312 // *ast.TypeSwitchStmt 313 // *ast.CaseClause 314 // *ast.CommClause 315 // *ast.ForStmt 316 // *ast.RangeStmt 317 // 318 Scopes map[ast.Node]*Scope 319 320 // InitOrder is the list of package-level initializers in the order in which 321 // they must be executed. Initializers referring to variables related by an 322 // initialization dependency appear in topological order, the others appear 323 // in source order. Variables without an initialization expression do not 324 // appear in this list. 325 InitOrder []*Initializer 326 327 // FileVersions maps a file to its Go version string. 328 // If the file doesn't specify a version, the reported 329 // string is Config.GoVersion. 330 // Version strings begin with “go”, like “go1.21”, and 331 // are suitable for use with the [go/version] package. 332 FileVersions map[*ast.File]string 333 } 334 335 func (info *Info) recordTypes() bool { 336 return info.Types != nil 337 } 338 339 // TypeOf returns the type of expression e, or nil if not found. 340 // Precondition: the Types, Uses and Defs maps are populated. 341 func (info *Info) TypeOf(e ast.Expr) Type { 342 if t, ok := info.Types[e]; ok { 343 return t.Type 344 } 345 if id, _ := e.(*ast.Ident); id != nil { 346 if obj := info.ObjectOf(id); obj != nil { 347 return obj.Type() 348 } 349 } 350 return nil 351 } 352 353 // ObjectOf returns the object denoted by the specified id, 354 // or nil if not found. 355 // 356 // If id is an embedded struct field, [Info.ObjectOf] returns the field (*[Var]) 357 // it defines, not the type (*[TypeName]) it uses. 358 // 359 // Precondition: the Uses and Defs maps are populated. 360 func (info *Info) ObjectOf(id *ast.Ident) Object { 361 if obj := info.Defs[id]; obj != nil { 362 return obj 363 } 364 return info.Uses[id] 365 } 366 367 // PkgNameOf returns the local package name defined by the import, 368 // or nil if not found. 369 // 370 // For dot-imports, the package name is ".". 371 // 372 // Precondition: the Defs and Implicts maps are populated. 373 func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName { 374 var obj Object 375 if imp.Name != nil { 376 obj = info.Defs[imp.Name] 377 } else { 378 obj = info.Implicits[imp] 379 } 380 pkgname, _ := obj.(*PkgName) 381 return pkgname 382 } 383 384 // TypeAndValue reports the type and value (for constants) 385 // of the corresponding expression. 386 type TypeAndValue struct { 387 mode operandMode 388 Type Type 389 Value constant.Value 390 } 391 392 // IsVoid reports whether the corresponding expression 393 // is a function call without results. 394 func (tv TypeAndValue) IsVoid() bool { 395 return tv.mode == novalue 396 } 397 398 // IsType reports whether the corresponding expression specifies a type. 399 func (tv TypeAndValue) IsType() bool { 400 return tv.mode == typexpr 401 } 402 403 // IsBuiltin reports whether the corresponding expression denotes 404 // a (possibly parenthesized) built-in function. 405 func (tv TypeAndValue) IsBuiltin() bool { 406 return tv.mode == builtin 407 } 408 409 // IsValue reports whether the corresponding expression is a value. 410 // Builtins are not considered values. Constant values have a non- 411 // nil Value. 412 func (tv TypeAndValue) IsValue() bool { 413 switch tv.mode { 414 case constant_, variable, mapindex, value, commaok, commaerr: 415 return true 416 } 417 return false 418 } 419 420 // IsNil reports whether the corresponding expression denotes the 421 // predeclared value nil. 422 func (tv TypeAndValue) IsNil() bool { 423 return tv.mode == value && tv.Type == Typ[UntypedNil] 424 } 425 426 // Addressable reports whether the corresponding expression 427 // is addressable (https://golang.org/ref/spec#Address_operators). 428 func (tv TypeAndValue) Addressable() bool { 429 return tv.mode == variable 430 } 431 432 // Assignable reports whether the corresponding expression 433 // is assignable to (provided a value of the right type). 434 func (tv TypeAndValue) Assignable() bool { 435 return tv.mode == variable || tv.mode == mapindex 436 } 437 438 // HasOk reports whether the corresponding expression may be 439 // used on the rhs of a comma-ok assignment. 440 func (tv TypeAndValue) HasOk() bool { 441 return tv.mode == commaok || tv.mode == mapindex 442 } 443 444 // Instance reports the type arguments and instantiated type for type and 445 // function instantiations. For type instantiations, [Type] will be of dynamic 446 // type *[Named]. For function instantiations, [Type] will be of dynamic type 447 // *Signature. 448 type Instance struct { 449 TypeArgs *TypeList 450 Type Type 451 } 452 453 // An Initializer describes a package-level variable, or a list of variables in case 454 // of a multi-valued initialization expression, and the corresponding initialization 455 // expression. 456 type Initializer struct { 457 Lhs []*Var // var Lhs = Rhs 458 Rhs ast.Expr 459 } 460 461 func (init *Initializer) String() string { 462 var buf bytes.Buffer 463 for i, lhs := range init.Lhs { 464 if i > 0 { 465 buf.WriteString(", ") 466 } 467 buf.WriteString(lhs.Name()) 468 } 469 buf.WriteString(" = ") 470 WriteExpr(&buf, init.Rhs) 471 return buf.String() 472 } 473 474 // Check type-checks a package and returns the resulting package object and 475 // the first error if any. Additionally, if info != nil, Check populates each 476 // of the non-nil maps in the [Info] struct. 477 // 478 // The package is marked as complete if no errors occurred, otherwise it is 479 // incomplete. See [Config.Error] for controlling behavior in the presence of 480 // errors. 481 // 482 // The package is specified by a list of *ast.Files and corresponding 483 // file set, and the package path the package is identified with. 484 // The clean path must not be empty or dot ("."). 485 func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error) { 486 pkg := NewPackage(path, "") 487 return pkg, NewChecker(conf, fset, pkg, info).Files(files) 488 } 489