Documentation ¶
Overview ¶
Package types declares the data types and implements the algorithms for type-checking of Go packages. Use Check and Config.Check to invoke the type-checker.
Type-checking consists of several interdependent phases:
Name resolution maps each identifier (ast.Ident) in the program to the language object (Object) it denotes. Use Info.Objects, Info.Implicits for the results of name resolution.
Constant folding computes the exact constant value (exact.Value) for every expression (ast.Expr) that is a compile-time constant. Use Info.Values for the results of constant folding.
Type inference computes the type (Type) of every expression (ast.Expr) and checks for compliance with the language specification. Use Info.Types for the results of type evaluation.
Index ¶
- Variables
- func FindGcExportData(r *bufio.Reader) (err error)
- func FindPkg(path, srcDir string) (filename, id string)
- func Id(pkg *Package, name string) string
- func Implements(V Type, T *Interface, static bool) bool
- func IsAssignableTo(V, T Type) bool
- func IsIdentical(x, y Type) bool
- type Array
- type Basic
- type BasicInfo
- type BasicKind
- type Builtin
- func (obj *Builtin) Id() string
- func (obj *Builtin) IsExported() bool
- func (t *Builtin) MethodSet() *MethodSet
- func (obj *Builtin) Name() string
- func (obj *Builtin) Parent() *Scope
- func (obj *Builtin) Pkg() *Package
- func (obj *Builtin) Pos() token.Pos
- func (t *Builtin) String() string
- func (obj *Builtin) Type() Type
- func (t *Builtin) Underlying() Type
- type Chan
- type Config
- type Const
- type Func
- type Info
- type Interface
- type Label
- type Map
- type MethodSet
- type Named
- type Nil
- type Object
- type OverloadInfo
- type Package
- func Check(path string, fset *token.FileSet, files []*ast.File) (*Package, error)
- func GcImport(imports map[string]*Package, path string) (pkg *Package, err error)
- func GcImportData(imports map[string]*Package, filename, id string, data *bufio.Reader) (pkg *Package, err error)
- func NewPackage(path, name string, scope *Scope) *Package
- type PkgName
- type Pointer
- type Scope
- func (s *Scope) Child(i int) *Scope
- func (s *Scope) Insert(obj Object) Object
- func (s *Scope) Len() int
- func (s *Scope) Lookup(name string) Object
- func (s *Scope) LookupParent(name string) Object
- func (s *Scope) Names() []string
- func (s *Scope) NumChildren() int
- func (s *Scope) Parent() *Scope
- func (s *Scope) String() string
- func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)
- type Selection
- type SelectionKind
- type Signature
- type Sizes
- type Slice
- type StdSizes
- type Struct
- type Tuple
- type Type
- type TypeName
- type Var
- Bugs
Constants ¶
This section is empty.
Variables ¶
var ( Universe *Scope Unsafe *Package )
var Typ = [...]*Basic{ Invalid: {Invalid, 0, 0, "invalid type"}, Bool: {Bool, IsBoolean, 1, "bool"}, Int: {Int, IsInteger, 0, "int"}, Int8: {Int8, IsInteger, 1, "int8"}, Int16: {Int16, IsInteger, 2, "int16"}, Int32: {Int32, IsInteger, 4, "int32"}, Int64: {Int64, IsInteger, 8, "int64"}, Uint: {Uint, IsInteger | IsUnsigned, 0, "uint"}, Uint8: {Uint8, IsInteger | IsUnsigned, 1, "uint8"}, Uint16: {Uint16, IsInteger | IsUnsigned, 2, "uint16"}, Uint32: {Uint32, IsInteger | IsUnsigned, 4, "uint32"}, Uint64: {Uint64, IsInteger | IsUnsigned, 8, "uint64"}, Uintptr: {Uintptr, IsInteger | IsUnsigned, 0, "uintptr"}, Float32: {Float32, IsFloat, 4, "float32"}, Float64: {Float64, IsFloat, 8, "float64"}, Complex64: {Complex64, IsComplex, 8, "complex64"}, Complex128: {Complex128, IsComplex, 16, "complex128"}, String: {String, IsString, 0, "string"}, UnsafePointer: {UnsafePointer, 0, 0, "Pointer"}, UntypedBool: {UntypedBool, IsBoolean | IsUntyped, 0, "untyped boolean"}, UntypedInt: {UntypedInt, IsInteger | IsUntyped, 0, "untyped integer"}, UntypedRune: {UntypedRune, IsInteger | IsUntyped, 0, "untyped rune"}, UntypedFloat: {UntypedFloat, IsFloat | IsUntyped, 0, "untyped float"}, UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, 0, "untyped complex"}, UntypedString: {UntypedString, IsString | IsUntyped, 0, "untyped string"}, UntypedNil: {UntypedNil, IsUntyped, 0, "untyped nil"}, }
Functions ¶
func FindGcExportData ¶
FindGcExportData positions the reader r at the beginning of the export data section of an underlying GC-created object/archive file by reading from it. The reader must be positioned at the start of the file before calling this function.
func FindPkg ¶
FindPkg returns the filename and unique package id for an import path based on package information provided by build.Import (using the build.Default build.Context). If no file was found, an empty filename is returned.
func Id ¶
Id returns name if it is exported, otherwise it returns the name qualified with the package path.
func Implements ¶
Implements reports whether a value of type V implements T, as follows:
1) For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Informally, this reports whether V is a subtype of T.
2) For interface types V, and if static is not set, V implements T if all methods of T which are also present in V have matching types. Informally, this indicates whether a type assertion x.(T) where x is of type V would be legal (the concrete dynamic type of x may implement T even if V does not statically implement it).
func IsAssignableTo ¶
IsAssignableTo reports whether a value of type V is assignable to a variable of type T.
func IsIdentical ¶
IsIdentical returns true if x and y are identical.
Types ¶
type Array ¶
type Array struct {
// contains filtered or unexported fields
}
An Array represents an array type.
func (*Array) Underlying ¶
type Basic ¶
type Basic struct {
// contains filtered or unexported fields
}
A Basic represents a basic type.
func (*Basic) Underlying ¶
type BasicInfo ¶
type BasicInfo int
BasicInfo is a set of flags describing properties of a basic type.
type BasicKind ¶
type BasicKind int
BasicKind describes the kind of basic type.
const ( Invalid BasicKind = iota // type is invalid // predeclared types Bool Int Int8 Int16 Int32 Int64 Uint Uint8 Uint16 Uint32 Uint64 Uintptr Float32 Float64 Complex64 Complex128 String UnsafePointer // types for untyped values UntypedBool UntypedInt UntypedRune UntypedFloat UntypedComplex UntypedString UntypedNil // aliases Byte = Uint8 Rune = Int32 )
type Builtin ¶
type Builtin struct {
// contains filtered or unexported fields
}
A Builtin represents a built-in function. Builtins don't have a valid type.
func (*Builtin) IsExported ¶
func (obj *Builtin) IsExported() bool
func (*Builtin) Underlying ¶
type Chan ¶
type Chan struct {
// contains filtered or unexported fields
}
A Chan represents a channel type.
func (*Chan) Underlying ¶
type Config ¶
type Config struct { // If IgnoreFuncBodies is set, function bodies are not // type-checked. IgnoreFuncBodies bool // If FakeImportC is set, `import "C"` (for packages requiring Cgo) // declares an empty "C" package and errors are omitted for qualified // identifiers referring to package C (which won't find an object). // This feature is intended for the standard library cmd/api tool. // // Caution: Effects may be unpredictable due to follow-up errors. // Do not use casually! FakeImportC bool // Packages is used to look up (and thus canonicalize) packages by // package path. If Packages is nil, it is set to a new empty map. // During type-checking, imported packages are added to the map. Packages map[string]*Package // If Error != nil, it is called with each error found // during type checking. The error strings of errors with // detailed position information are formatted as follows: // filename:line:column: message Error func(err error) // If Import != nil, it is called for each imported package. // Otherwise, GcImporter is called. // An importer resolves import paths to Packages. // The imports map records packages already known, // indexed by canonical package path. The type-checker will // invoke Import with Config.Packages. // An importer must determine the canonical package path and // check imports to see if it is already present in the map. // If so, the Importer can return the map entry. Otherwise, // the importer must load the package data for the given path // into a new *Package, record it in imports map, and return // the package. Import func(imports map[string]*Package, path string) (pkg *Package, err error) // If Sizes != nil, it provides the sizing functions for package unsafe. // Otherwise &StdSize{WordSize: 8, MaxAlign: 8} is used instead. Sizes Sizes }
A Config specifies the configuration for type checking. The zero value for Config is a ready-to-use default configuration.
func (*Config) Check ¶
func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)
Check type-checks a package and returns the resulting package object, the first error if any, and if info != nil, additional type information. The package is marked as complete if no errors occurred, otherwise it is incomplete.
The package is specified by a list of *ast.Files and corresponding file set, and the package path the package is identified with. The clean path must not be empty or dot (".").
type Const ¶
type Const struct {
// contains filtered or unexported fields
}
A Const represents a declared constant.
func (*Const) IsExported ¶
func (obj *Const) IsExported() bool
type Func ¶
type Func struct {
// contains filtered or unexported fields
}
A Func represents a declared function, concrete method, or abstract (interface) method. Its Type() is always a *Signature. An abstract method may belong to many interfaces due to embedding.
func MissingMethod ¶
MissingMethod returns (nil, false) if V implements T, otherwise it returns a missing method required by T and whether it is missing or just has the wrong type.
For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Otherwise (V is an interface and static is not set), MissingMethod only checks that methods of T which are also present in V have matching types (e.g., for a type assertion x.(T) where x is of interface type typ).
func (*Func) FullName ¶
FullName returns the package- or receiver-type-qualified name of function or method obj.
func (*Func) IsExported ¶
func (obj *Func) IsExported() bool
type Info ¶
type Info struct { // Types maps expressions to their types. Identifiers on the // lhs of declarations are collected in Objects, not Types. // // For an expression denoting a predeclared built-in function // the recorded signature is call-site specific. If the call // result is not a constant, the recorded type is an argument- // specific signature. Otherwise, the recorded type is invalid. Types map[ast.Expr]Type // Values maps constant expressions to their values. Values map[ast.Expr]exact.Value // Objects maps identifiers to their corresponding objects (including // package names, dots "." of dot-imports, and blank "_" identifiers). // For identifiers that do not denote objects (e.g., the package name // in package clauses, blank identifiers on the lhs of assignments, or // symbolic variables t in t := x.(type) of type switch headers), the // corresponding objects are nil. Objects map[*ast.Ident]Object // Implicits maps nodes to their implicitly declared objects, if any. // The following node and object types may appear: // // node declared object // // *ast.ImportSpec *PkgName (imports w/o renames), or imported objects (dot-imports) // *ast.CaseClause type-specific *Var for each type switch case clause (incl. default) // *ast.Field anonymous struct field or parameter *Var // Implicits map[ast.Node]Object // Selections maps selector expressions to their corresponding selections. Selections map[*ast.SelectorExpr]*Selection // Scopes maps ast.Nodes to the scopes they define. Note that package scopes // are not associated with a specific node but with all files belonging to a // package. Thus, the package scope can be found in the type-checked package // object. // // The following node types may appear in Scopes: // // *ast.File // *ast.FuncType // *ast.BlockStmt // *ast.IfStmt // *ast.SwitchStmt // *ast.TypeSwitchStmt // *ast.CaseClause // *ast.CommClause // *ast.ForStmt // *ast.RangeStmt // Scopes map[ast.Node]*Scope }
Info holds result type information for a type-checked package. Only the information for which a map is provided is collected. If the package has type errors, the collected information may be incomplete.
type Interface ¶
type Interface struct {
// contains filtered or unexported fields
}
An Interface represents an interface type.
func NewInterface ¶
NewInterface returns a new interface for the given methods.
func (*Interface) Method ¶
Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
func (*Interface) NumMethods ¶
NumMethods returns the number of methods of interface t.
func (*Interface) Underlying ¶
type Label ¶
type Label struct {
// contains filtered or unexported fields
}
A Label represents a declared label.
func (*Label) IsExported ¶
func (obj *Label) IsExported() bool
type Map ¶
type Map struct {
// contains filtered or unexported fields
}
A Map represents a map type.
func (*Map) Underlying ¶
type MethodSet ¶
type MethodSet struct {
// contains filtered or unexported fields
}
A MethodSet is an ordered set of concrete or abstract (interface) methods; a method is a MethodVal selection. The zero value for a MethodSet is a ready-to-use empty method set.
func NewMethodSet ¶
NewMethodSet computes the method set for the given type T. It always returns a non-nil method set, even if it is empty.
type Named ¶
type Named struct {
// contains filtered or unexported fields
}
A Named represents a named type.
func NewNamed ¶
NewNamed returns a new named type for the given type name, underlying type, and associated methods. The underlying type must exist and not be a *Named, and the methods scope entries must be *Func objects if the scope is not empty.
func (*Named) NumMethods ¶
NumMethods returns the number of explicit methods whose receiver is named type t.
func (*Named) Underlying ¶
type Nil ¶
type Nil struct {
// contains filtered or unexported fields
}
Nil represents the predeclared value nil.
func (*Nil) IsExported ¶
func (obj *Nil) IsExported() bool
type Object ¶
type Object interface { Parent() *Scope // scope in which this object is declared Pos() token.Pos // position of object identifier in declaration Pkg() *Package // nil for objects in the Universe scope and labels Name() string // package local object name Type() Type // object type IsExported() bool // reports whether the name starts with a capital letter Id() string // object id (see Id below) // String returns a human-readable string of the object. String() string // contains filtered or unexported methods }
An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label. All objects implement the Object interface.
func LookupFieldOrMethod ¶
func LookupFieldOrMethod(T Type, pkg *Package, name string) (obj Object, index []int, indirect bool)
LookupFieldOrMethod looks up a field or method with given package and name in T and returns the corresponding *Var or *Func, an index sequence, and a bool indicating if there were any pointer indirections on the path to the field or method.
The last index entry is the field or method index in the (possibly embedded) type where the entry was found, either:
- the list of declared methods of a named type; or
- the list of all methods (method set) of an interface type; or
- the list of fields of a struct type.
The earlier index entries are the indices of the embedded fields traversed to get to the found entry, starting at depth 0.
If no entry is found, a nil object is returned. In this case, the returned index sequence points to an ambiguous entry if it exists, or it is nil.
type Package ¶
type Package struct {
// contains filtered or unexported fields
}
A Package describes a Go package.
func Check ¶
Check type-checks a package and returns the resulting complete package object, or a nil package and the first error. The package is specified by a list of *ast.Files and corresponding file set, and the import path the package is identified with. The clean path must not be empty or dot (".").
For more control over type-checking and results, use Config.Check.
func GcImport ¶
GcImport imports a gc-generated package given its import path, adds the corresponding package object to the imports map, and returns the object. Local import paths are interpreted relative to the current working directory. The imports map must contains all packages already imported.
func GcImportData ¶
func GcImportData(imports map[string]*Package, filename, id string, data *bufio.Reader) (pkg *Package, err error)
GcImportData imports a package by reading the gc-generated export data, adds the corresponding package object to the imports map indexed by id, and returns the object.
The imports map must contains all packages already imported. The data reader position must be the beginning of the export data section. The filename is only used in error messages.
If imports[id] contains the completely imported package, that package can be used directly, and there is no need to call this function (but there is also no harm but for extra time used).
func NewPackage ¶
NewPackage returns a new Package for the given package path, name, and scope. The package is not complete and contains no explicit imports.
func (*Package) Complete ¶
A package is complete if its scope contains (at least) all exported objects; otherwise it is incomplete.
type PkgName ¶
type PkgName struct {
// contains filtered or unexported fields
}
A PkgName represents an imported Go package.
func (*PkgName) IsExported ¶
func (obj *PkgName) IsExported() bool
type Pointer ¶
type Pointer struct {
// contains filtered or unexported fields
}
A Pointer represents a pointer type.
func NewPointer ¶
NewPointer returns a new pointer type for the given element (base) type.
func (*Pointer) Underlying ¶
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
A Scope maintains a set of objects and links to its containing (parent) and contained (children) scopes. Objects may be inserted and looked up by name. The zero value for Scope is a ready-to-use empty scope.
func (*Scope) Insert ¶
Insert attempts to insert an object obj into scope s. If s already contains an alternative object alt with the same name, Insert leaves s unchanged and returns alt. Otherwise it inserts obj, sets the object's scope to s, and returns nil. Objects with blank "_" names are not inserted, but have their parent field set to s.
func (*Scope) Lookup ¶
Lookup returns the object in scope s with the given name if such an object exists; otherwise the result is nil.
func (*Scope) LookupParent ¶
LookupParent follows the parent chain of scopes starting with s until it finds a scope where Lookup(name) returns a non-nil object, and then returns that object. If no such scope exists, the result is nil.
func (*Scope) NumChildren ¶
NumChildren() returns the number of scopes nested in s.
type Selection ¶
type Selection struct {
// contains filtered or unexported fields
}
A Selection describes a selector expression x.f. For the declarations:
type T struct{ x int; E } type E struct{} func (e E) m() {} var p *T
the following relations exist:
Selector Kind Recv Obj Type Index Indirect p.x FieldVal T x int {0} true p.m MethodVal *T m func (e *T) m() {1, 0} true T.m MethodExpr T m func m(_ T) {1, 0} false math.Pi PackageObj nil Pi untyped numeric nil false
func (*Selection) Index ¶
Index describes the path from x to f in x.f. The result is nil if x.f is a qualified identifier (PackageObj).
The last index entry is the field or method index of the type declaring f; either:
- the list of declared methods of a named type; or
- the list of methods of an interface type; or
- the list of fields of a struct type.
The earlier index entries are the indices of the embedded fields implicitly traversed to get from (the type of) x to f, starting at embedding depth 0.
func (*Selection) Indirect ¶
Indirect reports whether any pointer indirection was required to get from x to f in x.f. The result is false if x.f is a qualified identifier (PackageObj).
func (*Selection) Obj ¶
Obj returns the object denoted by x.f. The following object types may appear:
Kind Object FieldVal *Var field MethodVal *Func method MethodExpr *Func method PackageObj *Const, *Type, *Var, *Func imported const, type, var, or func
type SelectionKind ¶
type SelectionKind int
SelectionKind describes the kind of a selector expression x.f.
const ( FieldVal SelectionKind = iota // x.f is a struct field selector MethodVal // x.f is a method selector MethodExpr // x.f is a method expression PackageObj // x.f is a qualified identifier )
type Signature ¶
type Signature struct {
// contains filtered or unexported fields
}
A Signature represents a (non-builtin) function or method type.
func NewSignature ¶
NewSignature returns a new function type for the given receiver, parameters, and results, either of which may be nil. If isVariadic is set, the function is variadic, it must have at least one parameter, and the last parameter must be of unnamed slice type.
func (*Signature) IsVariadic ¶
IsVariadic reports whether the signature s is variadic.
func (*Signature) Recv ¶
Recv returns the receiver of signature s (if a method), or nil if a function.
For an abstract method, Recv returns the enclosing interface either as a *Named or an *Interface. Due to embedding, an interface may contain methods whose receiver type is a different interface.
func (*Signature) Underlying ¶
type Sizes ¶
type Sizes interface { // Alignof returns the alignment of a variable of type T. // Alignof must implement the alignment guarantees required by the spec. Alignof(T Type) int64 // Offsetsof returns the offsets of the given struct fields, in bytes. // Offsetsof must implement the offset guarantees required by the spec. Offsetsof(fields []*Var) []int64 // Sizeof returns the size of a variable of type T. // Sizeof must implement the size guarantees required by the spec. Sizeof(T Type) int64 }
Sizes defines the sizing functions for package unsafe.
type Slice ¶
type Slice struct {
// contains filtered or unexported fields
}
A Slice represents a slice type.
func (*Slice) Underlying ¶
type StdSizes ¶
type StdSizes struct { WordSize int64 // word size in bytes - must be >= 4 (32bits) MaxAlign int64 // maximum alignment in bytes - must be >= 1 }
StdSizes is a convenience type for creating commonly used Sizes. It makes the following simplifying assumptions:
- The size of explicitly sized basic types (int16, etc.) is the specified size.
- The size of strings, functions, and interfaces is 2*WordSize.
- The size of slices is 3*WordSize.
- All other types have size WordSize.
- Arrays and structs are aligned per spec definition; all other types are naturally aligned with a maximum alignment MaxAlign.
*StdSizes implements Sizes.
type Struct ¶
type Struct struct {
// contains filtered or unexported fields
}
A Struct represents a struct type.
func NewStruct ¶
NewStruct returns a new struct with the given fields and corresponding field tags. If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be only as long as required to hold the tag with the largest index i. Consequently, if no field has a tag, tags may be nil.
func (*Struct) NumFields ¶
NumFields returns the number of fields in the struct (including blank and anonymous fields).
func (*Struct) Underlying ¶
type Tuple ¶
type Tuple struct {
// contains filtered or unexported fields
}
A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple. Tuples are used as components of signatures and to represent the type of multiple assignments; they are not first class types of Go.
func (*Tuple) Underlying ¶
type Type ¶
type Type interface { // Underlying returns the underlying type of a type. Underlying() Type // MethodSet returns the method set of a type. MethodSet() *MethodSet // String returns a string representation of a type. String() string }
A Type represents a type of Go. All types implement the Type interface.
func Eval ¶
Eval returns the type and, if constant, the value for the expression or type literal string str evaluated in scope. If the expression contains function literals, the function bodies are ignored (though they must be syntactically correct).
If pkg == nil, the Universe scope is used and the provided scope is ignored. Otherwise, the scope must belong to the package (either the package scope, or nested within the package scope).
An error is returned if the scope is incorrect, the string has syntax errors, or if it cannot be evaluated in the scope. Position info for objects in the result type is undefined.
Note: Eval should not be used instead of running Check to compute types and values, but in addition to Check. Eval will re-evaluate its argument each time, and it also does not know about the context in which an expression is used (e.g., an assignment). Thus, top- level untyped constants will return an untyped type rather then the respective context-specific type.
func EvalNode ¶
func EvalNode(fset *token.FileSet, node ast.Expr, pkg *Package, scope *Scope) (typ Type, val exact.Value, err error)
EvalNode is like Eval but instead of string it accepts an expression node and respective file set.
An error is returned if the scope is incorrect if the node cannot be evaluated in the scope.
func New ¶
New is a convenience function to create a new type from a given expression or type literal string evaluated in Universe scope. New(str) is shorthand for Eval(str, nil, nil), but only returns the type result, and panics in case of an error. Position info for objects in the result type is undefined.
type TypeName ¶
type TypeName struct {
// contains filtered or unexported fields
}
A TypeName represents a declared type.
func (*TypeName) IsExported ¶
func (obj *TypeName) IsExported() bool
Notes ¶
Bugs ¶
Interface vs non-interface comparisons are not correctly implemented.
Switch statements don't check duplicate cases for all types for which it is required.
Source Files ¶
- api.go
- assignments.go
- builtins.go
- call.go
- check.go
- conversions.go
- errors.go
- eval.go
- exportdata.go
- expr.go
- gcimporter.go
- go12.go
- labels.go
- lookup.go
- methodset.go
- objects.go
- objset.go
- operand.go
- overload.go
- package.go
- predicates.go
- resolver.go
- return.go
- scope.go
- selection.go
- sizes.go
- stmt.go
- types.go
- typexpr.go
- universe.go
Directories ¶
Path | Synopsis |
---|---|
Package typemap defines type M, a hash-table-based mapping from types (go/types.Type) to arbitrary values, and a hash function on types.
|
Package typemap defines type M, a hash-table-based mapping from types (go/types.Type) to arbitrary values, and a hash function on types. |