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