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