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