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