Documentation
¶
Overview ¶
Package types declares the data types and implements the algorithms for type-checking of Go packages. Use Config.Check to invoke the type checker for a package. Alternatively, create a new type checker with NewChecker and invoke it incrementally by calling Checker.Files.
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.{Defs,Uses,Implicits} for the results of name resolution.
Constant folding computes the exact constant value (constant.Value) for every expression (ast.Expr) that is a compile-time constant. Use Info.Types[expr].Value 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[expr].Type for the results of type inference.
For a tutorial, see https://golang.org/s/types-tutorial.
Index ¶
- Variables
- func AssertableTo(V *Interface, T Type) bool
- func AssignableTo(V, T Type) bool
- func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)
- func Comparable(T Type) bool
- func ConvertibleTo(V, T Type) bool
- func DefPredeclaredTestFuncs()
- func ExprString(x ast.Expr) string
- func Id(pkg *Package, name string) string
- func Identical(x, y Type) bool
- func IdenticalIgnoreTags(x, y Type) bool
- func Implements(V Type, T *Interface) bool
- func IsInterface(t Type) bool
- func ObjectString(obj Object, qf Qualifier) string
- func Satisfies(V Type, T *Interface) bool
- func SelectionString(s *Selection, qf Qualifier) string
- func TypeString(typ Type, qf Qualifier) string
- func WriteExpr(buf *bytes.Buffer, x ast.Expr)
- func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
- func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)
- type ArgumentError
- type Array
- type Basic
- type BasicInfo
- type BasicKind
- type Builtin
- type Chan
- type ChanDir
- type Checker
- type Config
- type Const
- type Context
- type Error
- type Func
- type ImportMode
- type Importer
- type ImporterFrom
- type Info
- type Initializer
- type Instance
- type Interface
- func (t *Interface) Complete() *Interface
- func (t *Interface) Embedded(i int) *Nameddeprecated
- func (t *Interface) EmbeddedType(i int) Type
- func (t *Interface) Empty() bool
- func (t *Interface) ExplicitMethod(i int) *Func
- func (t *Interface) IsComparable() bool
- func (t *Interface) IsImplicit() bool
- func (t *Interface) IsMethodSet() bool
- func (t *Interface) MarkImplicit()
- func (t *Interface) Method(i int) *Func
- func (t *Interface) NumEmbeddeds() int
- func (t *Interface) NumExplicitMethods() int
- func (t *Interface) NumMethods() int
- func (t *Interface) String() string
- func (t *Interface) Underlying() Type
- type Label
- type Map
- type MethodSet
- type Named
- func (t *Named) AddMethod(m *Func)
- func (t *Named) Method(i int) *Func
- func (t *Named) NumMethods() int
- func (t *Named) Obj() *TypeName
- func (t *Named) Origin() *Named
- func (t *Named) SetTypeParams(tparams []*TypeParam)
- func (t *Named) SetUnderlying(underlying Type)
- func (t *Named) String() string
- func (t *Named) TypeArgs() *TypeList
- func (t *Named) TypeParams() *TypeParamList
- func (t *Named) Underlying() Type
- type Nil
- type Object
- type Package
- func (pkg *Package) Complete() bool
- func (pkg *Package) GoVersion() string
- func (pkg *Package) Imports() []*Package
- func (pkg *Package) MarkComplete()
- func (pkg *Package) Name() string
- func (pkg *Package) Path() string
- func (pkg *Package) Scope() *Scope
- func (pkg *Package) SetImports(list []*Package)
- func (pkg *Package) SetName(name string)
- func (pkg *Package) String() string
- type PkgName
- type Pointer
- type Qualifier
- type Scope
- func (s *Scope) Child(i int) *Scope
- func (s *Scope) Contains(pos token.Pos) bool
- func (s *Scope) End() token.Pos
- func (s *Scope) Innermost(pos token.Pos) *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, pos token.Pos) (*Scope, Object)
- func (s *Scope) Names() []string
- func (s *Scope) NumChildren() int
- func (s *Scope) Parent() *Scope
- func (s *Scope) Pos() token.Pos
- func (s *Scope) String() string
- func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)
- type Selection
- type SelectionKind
- type Signature
- func (s *Signature) Params() *Tuple
- func (s *Signature) Recv() *Var
- func (s *Signature) RecvTypeParams() *TypeParamList
- func (s *Signature) Results() *Tuple
- func (t *Signature) String() string
- func (s *Signature) TypeParams() *TypeParamList
- func (t *Signature) Underlying() Type
- func (s *Signature) Variadic() bool
- type Sizes
- type Slice
- type StdSizes
- type Struct
- type Term
- type Tuple
- type Type
- type TypeAndValue
- func (tv TypeAndValue) Addressable() bool
- func (tv TypeAndValue) Assignable() bool
- func (tv TypeAndValue) HasOk() bool
- func (tv TypeAndValue) IsBuiltin() bool
- func (tv TypeAndValue) IsNil() bool
- func (tv TypeAndValue) IsType() bool
- func (tv TypeAndValue) IsValue() bool
- func (tv TypeAndValue) IsVoid() bool
- type TypeList
- type TypeName
- type TypeParam
- type TypeParamList
- type Union
- type Var
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var Typ = []*Basic{ Invalid: {Invalid, 0, "invalid type"}, Bool: {Bool, IsBoolean, "bool"}, Int: {Int, IsInteger, "int"}, Int8: {Int8, IsInteger, "int8"}, Int16: {Int16, IsInteger, "int16"}, Int32: {Int32, IsInteger, "int32"}, Int64: {Int64, IsInteger, "int64"}, Uint: {Uint, IsInteger | IsUnsigned, "uint"}, Uint8: {Uint8, IsInteger | IsUnsigned, "uint8"}, Uint16: {Uint16, IsInteger | IsUnsigned, "uint16"}, Uint32: {Uint32, IsInteger | IsUnsigned, "uint32"}, Uint64: {Uint64, IsInteger | IsUnsigned, "uint64"}, Uintptr: {Uintptr, IsInteger | IsUnsigned, "uintptr"}, Float32: {Float32, IsFloat, "float32"}, Float64: {Float64, IsFloat, "float64"}, Complex64: {Complex64, IsComplex, "complex64"}, Complex128: {Complex128, IsComplex, "complex128"}, String: {String, IsString, "string"}, UnsafePointer: {UnsafePointer, 0, "Pointer"}, UntypedBool: {UntypedBool, IsBoolean | IsUntyped, "untyped bool"}, UntypedInt: {UntypedInt, IsInteger | IsUntyped, "untyped int"}, UntypedRune: {UntypedRune, IsInteger | IsUntyped, "untyped rune"}, UntypedFloat: {UntypedFloat, IsFloat | IsUntyped, "untyped float"}, UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, "untyped complex"}, UntypedString: {UntypedString, IsString | IsUntyped, "untyped string"}, UntypedNil: {UntypedNil, IsUntyped, "untyped nil"}, }
Typ contains the predeclared *Basic types indexed by their corresponding BasicKind.
The *Basic type for Typ[Byte] will have the name "uint8". Use Universe.Lookup("byte").Type() to obtain the specific alias basic type named "byte" (and analogous for "rune").
Functions ¶
func AssertableTo ¶
AssertableTo reports whether a value of type V can be asserted to have type T.
The behavior of AssertableTo is unspecified in three cases:
- if T is Typ[Invalid]
- if V is a generalized interface; i.e., an interface that may only be used as a type constraint in Go code
- if T is an uninstantiated generic type
func AssignableTo ¶
AssignableTo reports whether a value of type V is assignable to a variable of type T.
The behavior of AssignableTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.
func CheckExpr ¶ added in v1.13.0
func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)
CheckExpr type checks the expression expr as if it had appeared at position pos of package pkg. Type information about the expression is recorded in info. The expression may be an identifier denoting an uninstantiated generic function or type.
If pkg == nil, the Universe scope is used and the provided position pos is ignored. If pkg != nil, and pos is invalid, the package scope is used. Otherwise, pos must belong to the package.
An error is returned if pos is not within the package or if the node cannot be type-checked.
Note: Eval and CheckExpr should not be used instead of running Check to compute types and values, but in addition to Check, as these functions ignore the context in which an expression is used (e.g., an assignment). Thus, top-level untyped constants will return an untyped type rather than the respective context-specific type.
func Comparable ¶
Comparable reports whether values of type T are comparable.
func ConvertibleTo ¶
ConvertibleTo reports whether a value of type V is convertible to a value of type T.
The behavior of ConvertibleTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.
func DefPredeclaredTestFuncs ¶
func DefPredeclaredTestFuncs()
DefPredeclaredTestFuncs defines the assert and trace built-ins. These built-ins are intended for debugging and testing of this package only.
func ExprString ¶
ExprString returns the (possibly shortened) string representation for x. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.
func Id ¶
Id returns name if it is exported, otherwise it returns the name qualified with the package path.
func Identical ¶
Identical reports whether x and y are identical types. Receivers of Signature types are ignored.
func IdenticalIgnoreTags ¶ added in v1.8.0
IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored. Receivers of Signature types are ignored.
func Implements ¶
Implements reports whether type V implements interface T.
The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated generic type.
func IsInterface ¶
IsInterface reports whether t is an interface type.
func ObjectString ¶
ObjectString returns the string form of obj. The Qualifier controls the printing of package-level objects, and may be nil.
func Satisfies ¶ added in v1.20.0
Satisfies reports whether type V satisfies the constraint T.
The behavior of Satisfies is unspecified if V is Typ[Invalid] or an uninstantiated generic type.
func SelectionString ¶
SelectionString returns the string form of s. The Qualifier controls the printing of package-level objects, and may be nil.
Examples:
"field (T) f int" "method (T) f(X) Y" "method expr (T) f(X) Y"
func TypeString ¶
TypeString returns the string representation of typ. The Qualifier controls the printing of package-level objects, and may be nil.
func WriteExpr ¶
WriteExpr writes the (possibly shortened) string representation for x to buf. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.
func WriteSignature ¶
WriteSignature writes the representation of the signature sig to buf, without a leading "func" keyword. The Qualifier controls the printing of package-level objects, and may be nil.
Types ¶
type ArgumentError ¶ added in v1.18.0
An ArgumentError holds an error associated with an argument index.
func (*ArgumentError) Error ¶ added in v1.18.0
func (e *ArgumentError) Error() string
func (*ArgumentError) Unwrap ¶ added in v1.18.0
func (e *ArgumentError) Unwrap() error
type Array ¶
type Array struct {
// contains filtered or unexported fields
}
An Array represents an array type.
func NewArray ¶
NewArray returns a new array type for the given element type and length. A negative length indicates an unknown length.
func (*Array) Len ¶
Len returns the length of array a. A negative result indicates an unknown length.
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 // 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.
type Chan ¶
type Chan struct {
// contains filtered or unexported fields
}
A Chan represents a channel type.
func (*Chan) Underlying ¶
type Checker ¶
type Checker struct { *Info // contains filtered or unexported fields }
A Checker maintains the state of the type checker. It must be created with NewChecker.
func NewChecker ¶
NewChecker returns a new Checker instance for a given package. Package files may be added incrementally via checker.Files.
type Config ¶
type Config struct { Context *Context GoVersion string IgnoreFuncBodies bool FakeImportC bool Error func(err error) Importer Importer Sizes Sizes DisableUnusedImportCheck bool // contains filtered or unexported fields }
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 and the first error if any. Additionally, if info != nil, Check populates each of the non-nil maps in the Info struct.
The package is marked as complete if no errors occurred, otherwise it is incomplete. See Config.Error for controlling behavior in the presence of errors.
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.
type Context ¶ added in v1.18.0
type Context struct {
// contains filtered or unexported fields
}
A Context is an opaque type checking context. It may be used to share identical type instances across type-checked packages or calls to Instantiate. Contexts are safe for concurrent use.
The use of a shared context does not guarantee that identical instances are deduplicated in all cases.
type Error ¶
type Error struct { Fset *token.FileSet Pos token.Pos Msg string Soft bool // contains filtered or unexported fields }
An Error describes a type-checking error; it implements the error interface. A "soft" error is an error that still permits a valid interpretation of a package (such as "unused variable"); "hard" errors may lead to unpredictable behavior if ignored.
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: either a pointer receiver or wrong signature.
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 V).
func NewFunc ¶
NewFunc returns a new function with the given signature, representing the function's type.
func (*Func) FullName ¶
FullName returns the package- or receiver-type-qualified name of function or method obj.
func (*Func) Origin ¶ added in v1.19.0
Origin returns the canonical Func for its receiver, i.e. the Func object recorded in Info.Defs.
For synthetic functions created during instantiation (such as methods on an instantiated Named type or interface methods that depend on type arguments), this will be the corresponding Func on the generic (uninstantiated) type. For all other Funcs Origin returns the receiver.
type Importer ¶
An Importer resolves import paths to Packages.
CAUTION: This interface does not support the import of locally vendored packages. See https://golang.org/s/go15vendor. If possible, external implementations should implement ImporterFrom.
type ImporterFrom ¶ added in v1.6.0
type ImporterFrom interface { Importer ImportFrom(path, dir string, mode ImportMode) (*Package, error) }
An ImporterFrom resolves import paths to packages; it supports vendoring per https://golang.org/s/go15vendor. Use go/importer to obtain an ImporterFrom implementation.
type Info ¶
type Info struct { Types map[ast.Expr]TypeAndValue Instances map[*ast.Ident]Instance Defs map[*ast.Ident]Object Uses map[*ast.Ident]Object Implicits map[ast.Node]Object Selections map[*ast.SelectorExpr]*Selection Scopes map[ast.Node]*Scope InitOrder []*Initializer }
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.
Example ¶
ExampleInfo prints various facts recorded by the type checker in a types.Info struct: definitions of and references to each named object, and the type, value, and mode of every expression in the package.
// Parse a single source file. const input = ` package fib type S string var a, b, c = len(b), S(c), "hello" func fib(x int) int { if x < 2 { return x } return fib(x-1) - fib(x-2) }` // We need a specific fileset in this test below for positions. // Cannot use typecheck helper. fset := token.NewFileSet() f := mustParse(fset, input) // Type-check the package. // We create an empty map for each kind of input // we're interested in, and Check populates them. info := types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } var conf types.Config pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info) if err != nil { log.Fatal(err) } // Print package-level variables in initialization order. fmt.Printf("InitOrder: %v\n\n", info.InitOrder) // For each named object, print the line and // column of its definition and each of its uses. fmt.Println("Defs and Uses of each named object:") usesByObj := make(map[types.Object][]string) for id, obj := range info.Uses { posn := fset.Position(id.Pos()) lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column) usesByObj[obj] = append(usesByObj[obj], lineCol) } var items []string for obj, uses := range usesByObj { sort.Strings(uses) item := fmt.Sprintf("%s:\n defined at %s\n used at %s", types.ObjectString(obj, types.RelativeTo(pkg)), fset.Position(obj.Pos()), strings.Join(uses, ", ")) items = append(items, item) } sort.Strings(items) // sort by line:col, in effect fmt.Println(strings.Join(items, "\n")) fmt.Println() fmt.Println("Types and Values of each expression:") items = nil for expr, tv := range info.Types { var buf strings.Builder posn := fset.Position(expr.Pos()) tvstr := tv.Type.String() if tv.Value != nil { tvstr += " = " + tv.Value.String() } // line:col | expr | mode : type = value fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s", posn.Line, posn.Column, exprString(fset, expr), mode(tv), tvstr) items = append(items, buf.String()) } sort.Strings(items) fmt.Println(strings.Join(items, "\n"))
Output: InitOrder: [c = "hello" b = S(c) a = len(b)] Defs and Uses of each named object: builtin len: defined at - used at 6:15 func fib(x int) int: defined at fib:8:6 used at 12:20, 12:9 type S string: defined at fib:4:6 used at 6:23 type int: defined at - used at 8:12, 8:17 type string: defined at - used at 4:8 var b S: defined at fib:6:8 used at 6:19 var c string: defined at fib:6:11 used at 6:25 var x int: defined at fib:8:10 used at 10:10, 12:13, 12:24, 9:5 Types and Values of each expression: 4: 8 | string | type : string 6:15 | len | builtin : func(fib.S) int 6:15 | len(b) | value : int 6:19 | b | var : fib.S 6:23 | S | type : fib.S 6:23 | S(c) | value : fib.S 6:25 | c | var : string 6:29 | "hello" | value : string = "hello" 8:12 | int | type : int 8:17 | int | type : int 9: 5 | x | var : int 9: 5 | x < 2 | value : untyped bool 9: 9 | 2 | value : int = 2 10:10 | x | var : int 12: 9 | fib | value : func(x int) int 12: 9 | fib(x - 1) | value : int 12: 9 | fib(x-1) - fib(x-2) | value : int 12:13 | x | var : int 12:13 | x - 1 | value : int 12:15 | 1 | value : int = 1 12:20 | fib | value : func(x int) int 12:20 | fib(x - 2) | value : int 12:24 | x | var : int 12:24 | x - 2 | value : int 12:26 | 2 | value : int = 2
type Initializer ¶
An Initializer describes a package-level variable, or a list of variables in case of a multi-valued initialization expression, and the corresponding initialization expression.
func (*Initializer) String ¶
func (init *Initializer) String() string
type Instance ¶ added in v1.18.0
Instance reports the type arguments and instantiated type for type and function instantiations. For type instantiations, Type will be of dynamic type *Named. For function instantiations, Type will be of dynamic type *Signature.
type Interface ¶
type Interface struct {
// contains filtered or unexported fields
}
An Interface represents an interface type.
func NewInterface
deprecated
NewInterface returns a new interface for the given methods and embedded types. NewInterface takes ownership of the provided methods and may modify their types by setting missing receivers.
Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.
func NewInterfaceType ¶ added in v1.11.0
NewInterfaceType returns a new interface for the given methods and embedded types. NewInterfaceType takes ownership of the provided methods and may modify their types by setting missing receivers.
To avoid race conditions, the interface's type set should be computed before concurrent use of the interface, by explicitly calling Complete.
func (*Interface) Complete ¶
Complete computes the interface's type set. It must be called by users of NewInterfaceType and NewInterface after the interface's embedded types are fully defined and before using the interface type in any way other than to form other types. The interface must not contain duplicate methods or a panic occurs. Complete returns the receiver.
Interface types that have been completed are safe for concurrent use.
func (*Interface) Embedded
deprecated
func (*Interface) EmbeddedType ¶ added in v1.11.0
EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
func (*Interface) ExplicitMethod ¶
ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods(). The methods are ordered by their unique Id.
func (*Interface) IsComparable ¶ added in v1.18.0
IsComparable reports whether each type in interface t's type set is comparable.
func (*Interface) IsImplicit ¶ added in v1.18.0
IsImplicit reports whether the interface t is a wrapper for a type set literal.
func (*Interface) IsMethodSet ¶ added in v1.18.0
IsMethodSet reports whether the interface t is fully described by its method set.
func (*Interface) MarkImplicit ¶ added in v1.18.0
func (t *Interface) MarkImplicit()
MarkImplicit marks the interface t as implicit, meaning this interface corresponds to a constraint literal such as ~T or A|B without explicit interface embedding. MarkImplicit should be called before any concurrent use of implicit interfaces.
func (*Interface) Method ¶
Method returns the i'th method of interface t for 0 <= i < t.NumMethods(). The methods are ordered by their unique Id.
func (*Interface) NumEmbeddeds ¶
NumEmbeddeds returns the number of embedded types in interface t.
func (*Interface) NumExplicitMethods ¶
NumExplicitMethods returns the number of explicitly declared methods of interface t.
func (*Interface) NumMethods ¶
NumMethods returns the total 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. Labels don't have a type.
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, and they are ordered by ascending m.Obj().Id(). The zero value for a MethodSet is a ready-to-use empty method set.
Example ¶
ExampleMethodSet prints the method sets of various types.
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) func main() { // Parse a single source file. const input = ` package temperature import "fmt" type Celsius float64 func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) } type S struct { I; m int } type I interface { m() byte } ` fset := token.NewFileSet() f, err := parser.ParseFile(fset, "celsius.go", input, 0) if err != nil { log.Fatal(err) } // Type-check a package consisting of this file. // Type information for the imported packages // comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a. conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) } // Print the method sets of Celsius and *Celsius. celsius := pkg.Scope().Lookup("Celsius").Type() for _, t := range []types.Type{celsius, types.NewPointer(celsius)} { fmt.Printf("Method set of %s:\n", t) mset := types.NewMethodSet(t) for i := 0; i < mset.Len(); i++ { fmt.Println(mset.At(i)) } fmt.Println() } // Print the method set of S. styp := pkg.Scope().Lookup("S").Type() fmt.Printf("Method set of %s:\n", styp) fmt.Println(types.NewMethodSet(styp)) }
Output: Method set of temperature.Celsius: method (temperature.Celsius) String() string Method set of *temperature.Celsius: method (*temperature.Celsius) SetF(f float64) method (*temperature.Celsius) String() string Method set of temperature.S: MethodSet {}
func NewMethodSet ¶
NewMethodSet returns 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 (defined) type.
func NewNamed ¶
NewNamed returns a new named type for the given type name, underlying type, and associated methods. If the given type name obj doesn't have a type yet, its type is set to the returned named type. The underlying type must not be a *Named.
func (*Named) AddMethod ¶
AddMethod adds method m unless it is already in the method list. t must not have type arguments.
func (*Named) Method ¶
Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
For an ordinary or instantiated type t, the receiver base type of this method is the named type t. For an uninstantiated generic type t, each method receiver is instantiated with its receiver type parameters.
func (*Named) NumMethods ¶
NumMethods returns the number of explicit methods defined for t.
func (*Named) Obj ¶
Obj returns the type name for the declaration defining the named type t. For instantiated types, this is same as the type name of the origin type.
func (*Named) Origin ¶ added in v1.18.0
Origin returns the generic type from which the named type t is instantiated. If t is not an instantiated type, the result is t.
func (*Named) SetTypeParams ¶ added in v1.18.0
SetTypeParams sets the type parameters of the named type t. t must not have type arguments.
func (*Named) SetUnderlying ¶
SetUnderlying sets the underlying type and marks t as complete. t must not have type arguments.
func (*Named) TypeArgs ¶ added in v1.18.0
TypeArgs returns the type arguments used to instantiate the named type t.
func (*Named) TypeParams ¶ added in v1.18.0
func (t *Named) TypeParams() *TypeParamList
TypeParams returns the type parameters of the named type t, or nil. The result is non-nil for an (originally) generic type even if it is instantiated.
func (*Named) Underlying ¶
type Nil ¶
type Nil struct {
// contains filtered or unexported fields
}
Nil represents the predeclared value nil.
type Object ¶
type Object interface { Parent() *Scope Pos() token.Pos Pkg() *Package Name() string Type() Type Exported() bool Id() string 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, addressable bool, 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. If addressable is set, T is the type of an addressable variable (only matters for method lookups). T must not be nil.
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 struct 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 and indirect values have the following meaning:
If index != nil, the index sequence points to an ambiguous entry (the same name appeared more than once at the same embedding level).
If indirect is set, a method with a pointer receiver type was found but there was no pointer on the path from the actual receiver type to the method's formal receiver base type, nor was the receiver addressable.
type Package ¶
type Package struct {
// contains filtered or unexported fields
}
A Package describes a Go package.
var Unsafe *Package
The Unsafe package is the package returned by an importer for the import path "unsafe".
func NewPackage ¶
NewPackage returns a new Package for the given package path and name. 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.
func (*Package) GoVersion ¶ added in v1.21.0
GoVersion returns the minimum Go version required by this package. If the minimum version is unknown, GoVersion returns the empty string. Individual source files may specify a different minimum Go version, as reported in the go/ast.File.GoVersion field.
func (*Package) Imports ¶
Imports returns the list of packages directly imported by pkg; the list is in source order.
If pkg was loaded from export data, Imports includes packages that provide package-level objects referenced by pkg. This may be more or less than the set of packages directly imported by pkg's source code.
If pkg uses cgo and the FakeImportC configuration option was enabled, the imports list may contain a fake "C" package.
func (*Package) MarkComplete ¶
func (pkg *Package) MarkComplete()
MarkComplete marks a package as complete.
func (*Package) Scope ¶
Scope returns the (complete or incomplete) package scope holding the objects declared at package level (TypeNames, Consts, Vars, and Funcs). For a nil pkg receiver, Scope returns the Universe scope.
func (*Package) SetImports ¶
SetImports sets the list of explicitly imported packages to list. It is the caller's responsibility to make sure list elements are unique.
type PkgName ¶
type PkgName struct {
// contains filtered or unexported fields
}
A PkgName represents an imported Go package. PkgNames don't have a type.
func NewPkgName ¶
NewPkgName returns a new PkgName object representing an imported package. The remaining arguments set the attributes found with all Objects.
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 Qualifier ¶
A Qualifier controls how named package-level objects are printed in calls to TypeString, ObjectString, and SelectionString.
These three formatting routines call the Qualifier for each package-level object O, and if the Qualifier returns a non-empty string p, the object is printed in the form p.O. If it returns an empty string, only the object name O is printed.
Using a nil Qualifier is equivalent to using (*Package).Path: the object is qualified by the import path, e.g., "encoding/json.Marshal".
func RelativeTo ¶
RelativeTo returns a Qualifier that fully qualifies members of all packages other than pkg.
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.
Example ¶
ExampleScope prints the tree of Scopes of a package created from a set of parsed files.
// Parse the source files for a package. fset := token.NewFileSet() var files []*ast.File for _, src := range []string{ `package main import "fmt" func main() { freezing := FToC(-18) fmt.Println(freezing, Boiling) } `, `package main import "fmt" type Celsius float64 func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) } const Boiling Celsius = 100 func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed `, } { files = append(files, mustParse(fset, src)) } // Type-check a package consisting of these files. // Type information for the imported "fmt" package // comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a. conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("temperature", fset, files, nil) if err != nil { log.Fatal(err) } // Print the tree of scopes. // For determinism, we redact addresses. var buf strings.Builder pkg.Scope().WriteTo(&buf, 0, true) rx := regexp.MustCompile(` 0x[a-fA-F\d]*`) fmt.Println(rx.ReplaceAllString(buf.String(), ""))
Output: package "temperature" scope { . const temperature.Boiling temperature.Celsius . type temperature.Celsius float64 . func temperature.FToC(f float64) temperature.Celsius . func temperature.Unused() . func temperature.main() . main scope { . . package fmt . . function scope { . . . var freezing temperature.Celsius . . } . } . main scope { . . package fmt . . function scope { . . . var c temperature.Celsius . . } . . function scope { . . . var f float64 . . } . . function scope { . . . block scope { . . . } . . . block scope { . . . . block scope { . . . . . var x int . . . . } . . . } . . } . } }
var Universe *Scope
The Universe scope contains all predeclared objects of Go. It is the outermost scope of any chain of nested scopes.
func NewScope ¶
NewScope returns a new, empty scope contained in the given parent scope, if any. The comment is for debugging only.
func (*Scope) Contains ¶
Contains reports whether pos is within the scope's extent. The result is guaranteed to be valid only if the type-checked AST has complete position information.
func (*Scope) Innermost ¶
Innermost returns the innermost (child) scope containing pos. If pos is not within any scope, the result is nil. The result is also nil for the Universe scope. The result is guaranteed to be valid only if the type-checked AST has complete position information.
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 parent scope if not already set, and returns nil.
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 scope and object. If a valid position pos is provided, only objects that were declared at or before pos are considered. If no such scope and object exists, the result is (nil, nil).
Note that obj.Parent() may be different from the returned scope if the object was inserted into the scope and already had a parent at that time (see Insert). This can only happen for dot-imported objects whose scope is the scope of the package that exported them.
func (*Scope) NumChildren ¶
NumChildren returns the number of scopes nested in s.
func (*Scope) Pos ¶
Pos and End describe the scope's source code extent [pos, end). The results are guaranteed to be valid only if the type-checked AST has complete position information. The extent is undefined for Universe and package scopes.
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() {1, 0} true T.m MethodExpr T m func(T) {1, 0} false
func (*Selection) Index ¶
Index describes the path from x to f in x.f. 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.
type SelectionKind ¶
type SelectionKind int
SelectionKind describes the kind of a selector expression x.f (excluding qualified identifiers).
const ( FieldVal SelectionKind = iota MethodVal MethodExpr )
type Signature ¶
type Signature struct {
// contains filtered or unexported fields
}
A Signature represents a (non-builtin) function or method type. The receiver is ignored when comparing signatures for identity.
func NewSignature
deprecated
NewSignature returns a new function type for the given receiver, parameters, and results, either of which may be nil. If variadic is set, the function is variadic, it must have at least one parameter, and the last parameter must be of unnamed slice type.
Deprecated: Use NewSignatureType instead which allows for type parameters.
func NewSignatureType ¶ added in v1.18.0
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
NewSignatureType creates a new function type for the given receiver, receiver type parameters, type parameters, parameters, and results. If variadic is set, params must hold at least one parameter and the last parameter's core type must be of unnamed slice or bytestring type. If recv is non-nil, typeParams must be empty. If recvTypeParams is non-empty, recv must be non-nil.
func (*Signature) Recv ¶
Recv returns the receiver of signature s (if a method), or nil if a function. It is ignored when comparing signatures for identity.
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) RecvTypeParams ¶ added in v1.18.0
func (s *Signature) RecvTypeParams() *TypeParamList
RecvTypeParams returns the receiver type parameters of signature s, or nil.
func (*Signature) TypeParams ¶ added in v1.18.0
func (s *Signature) TypeParams() *TypeParamList
TypeParams returns the type parameters of signature s, or nil.
func (*Signature) Underlying ¶
type Sizes ¶
type Sizes interface { Alignof(T Type) int64 Offsetsof(fields []*Var) []int64 Sizeof(T Type) int64 }
Sizes defines the sizing functions for package unsafe.
func SizesFor ¶ added in v1.9.0
SizesFor returns the Sizes used by a compiler for an architecture. The result is nil if a compiler/architecture pair is not known.
Supported architectures for compiler "gc": "386", "amd64", "amd64p32", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm".
type Slice ¶
type Slice struct {
// contains filtered or unexported fields
}
A Slice represents a slice type.
func (*Slice) Underlying ¶
type StdSizes ¶
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 and interfaces is 2*WordSize.
- The size of slices is 3*WordSize.
- The size of an array of n elements corresponds to the size of a struct of n consecutive fields of the array's element type.
- The size of a struct is the offset of the last field plus that field's size. As with all element types, if the struct is used in an array its size must first be aligned to a multiple of the struct's alignment.
- 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 embedded fields).
func (*Struct) Underlying ¶
type Term ¶ added in v1.18.0
type Term term
A Term represents a term in a Union.
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 ¶
A Type represents a type of Go. All types implement the Type interface.
func Default ¶ added in v1.8.0
Default returns the default "typed" type for an "untyped" type; it returns the incoming type for all other types. The default type for untyped nil is untyped nil.
func Instantiate ¶ added in v1.18.0
Instantiate instantiates the type orig with the given type arguments targs. orig must be a *Named or a *Signature type. If there is no error, the resulting Type is an instantiated type of the same kind (either a *Named or a *Signature). Methods attached to a *Named type are also instantiated, and associated with a new *Func that has the same position as the original method, but nil function scope.
If ctxt is non-nil, it may be used to de-duplicate the instance against previous instances with the same identity. As a special case, generic *Signature origin types are only considered identical if they are pointer equivalent, so that instantiating distinct (but possibly identical) signatures will yield different instances. The use of a shared context does not guarantee that identical instances are deduplicated in all cases.
If validate is set, Instantiate verifies that the number of type arguments and parameters match, and that the type arguments satisfy their corresponding type constraints. If verification fails, the resulting error may wrap an *ArgumentError indicating which type argument did not satisfy its corresponding type parameter constraint, and why.
If validate is not set, Instantiate does not verify the type argument count or whether the type arguments satisfy their constraints. Instantiate is guaranteed to not return an error, but may panic. Specifically, for *Signature types, Instantiate will panic immediately if the type argument count is incorrect; for *Named types, a panic may occur later inside the *Named API.
type TypeAndValue ¶
type TypeAndValue struct { Type Type Value constant.Value // contains filtered or unexported fields }
TypeAndValue reports the type and value (for constants) of the corresponding expression.
func Eval ¶
func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)
Eval returns the type and, if constant, the value for the expression expr, evaluated at position pos of package pkg, which must have been derived from type-checking an AST with complete position information relative to the provided file set.
The meaning of the parameters fset, pkg, and pos is the same as in CheckExpr. An error is returned if expr cannot be parsed successfully, or the resulting expr AST cannot be type-checked.
func (TypeAndValue) Addressable ¶
func (tv TypeAndValue) Addressable() bool
Addressable reports whether the corresponding expression is addressable (https://golang.org/ref/spec#Address_operators).
func (TypeAndValue) Assignable ¶
func (tv TypeAndValue) Assignable() bool
Assignable reports whether the corresponding expression is assignable to (provided a value of the right type).
func (TypeAndValue) HasOk ¶
func (tv TypeAndValue) HasOk() bool
HasOk reports whether the corresponding expression may be used on the rhs of a comma-ok assignment.
func (TypeAndValue) IsBuiltin ¶
func (tv TypeAndValue) IsBuiltin() bool
IsBuiltin reports whether the corresponding expression denotes a (possibly parenthesized) built-in function.
func (TypeAndValue) IsNil ¶
func (tv TypeAndValue) IsNil() bool
IsNil reports whether the corresponding expression denotes the predeclared value nil.
func (TypeAndValue) IsType ¶
func (tv TypeAndValue) IsType() bool
IsType reports whether the corresponding expression specifies a type.
func (TypeAndValue) IsValue ¶
func (tv TypeAndValue) IsValue() bool
IsValue reports whether the corresponding expression is a value. Builtins are not considered values. Constant values have a non- nil Value.
func (TypeAndValue) IsVoid ¶
func (tv TypeAndValue) IsVoid() bool
IsVoid reports whether the corresponding expression is a function call without results.
type TypeList ¶ added in v1.18.0
type TypeList struct {
// contains filtered or unexported fields
}
TypeList holds a list of types.
type TypeName ¶
type TypeName struct {
// contains filtered or unexported fields
}
A TypeName represents a name for a (defined or alias) type.
func NewTypeName ¶
NewTypeName returns a new type name denoting the given typ. The remaining arguments set the attributes found with all Objects.
The typ argument may be a defined (Named) type or an alias type. It may also be nil such that the returned TypeName can be used as argument for NewNamed, which will set the TypeName's type as a side- effect.
type TypeParam ¶ added in v1.18.0
type TypeParam struct {
// contains filtered or unexported fields
}
A TypeParam represents a type parameter type.
func NewTypeParam ¶ added in v1.18.0
NewTypeParam returns a new TypeParam. Type parameters may be set on a Named or Signature type by calling SetTypeParams. Setting a type parameter on more than one type will result in a panic.
The constraint argument can be nil, and set later via SetConstraint. If the constraint is non-nil, it must be fully defined.
func (*TypeParam) Constraint ¶ added in v1.18.0
Constraint returns the type constraint specified for t.
func (*TypeParam) Index ¶ added in v1.18.0
Index returns the index of the type param within its param list, or -1 if the type parameter has not yet been bound to a type.
func (*TypeParam) SetConstraint ¶ added in v1.18.0
SetConstraint sets the type constraint for t.
It must be called by users of NewTypeParam after the bound's underlying is fully defined, and before using the type parameter in any way other than to form other types. Once SetConstraint returns the receiver, t is safe for concurrent use.
func (*TypeParam) Underlying ¶ added in v1.18.0
type TypeParamList ¶ added in v1.18.0
type TypeParamList struct {
// contains filtered or unexported fields
}
TypeParamList holds a list of type parameters.
func (*TypeParamList) At ¶ added in v1.18.0
func (l *TypeParamList) At(i int) *TypeParam
At returns the i'th type parameter in the list.
func (*TypeParamList) Len ¶ added in v1.18.0
func (l *TypeParamList) Len() int
Len returns the number of type parameters in the list. It is safe to call on a nil receiver.
type Union ¶ added in v1.18.0
type Union struct {
// contains filtered or unexported fields
}
A Union represents a union of terms embedded in an interface.
func NewUnion ¶ added in v1.18.0
NewUnion returns a new Union type with the given terms. It is an error to create an empty union; they are syntactically not possible.
func (*Union) Underlying ¶ added in v1.18.0
type Var ¶
type Var struct {
// contains filtered or unexported fields
}
A Variable represents a declared variable (including function parameters and results, and struct fields).
func NewField ¶
NewField returns a new variable representing a struct field. For embedded fields, the name is the unqualified type name under which the field is accessible.
func NewVar ¶
NewVar returns a new variable. The arguments set the attributes found with all Objects.
func (*Var) Anonymous ¶
Anonymous reports whether the variable is an embedded field. Same as Embedded; only present for backward-compatibility.
func (*Var) Origin ¶ added in v1.19.0
Origin returns the canonical Var for its receiver, i.e. the Var object recorded in Info.Defs.
For synthetic Vars created during instantiation (such as struct fields or function parameters that depend on type arguments), this will be the corresponding Var on the generic (uninstantiated) type. For all other Vars Origin returns the receiver.
Source Files
¶
- api.go
- array.go
- assignments.go
- basic.go
- builtins.go
- call.go
- chan.go
- check.go
- const.go
- context.go
- conversions.go
- decl.go
- errors.go
- eval.go
- expr.go
- exprstring.go
- gccgosizes.go
- generate.go
- index.go
- infer.go
- initorder.go
- instantiate.go
- interface.go
- labels.go
- lookup.go
- map.go
- methodset.go
- mono.go
- named.go
- object.go
- objset.go
- operand.go
- package.go
- pointer.go
- predicates.go
- resolver.go
- return.go
- scope.go
- selection.go
- signature.go
- sizes.go
- slice.go
- stmt.go
- struct.go
- subst.go
- termlist.go
- tuple.go
- type.go
- typelists.go
- typeparam.go
- typeset.go
- typestring.go
- typeterm.go
- typexpr.go
- under.go
- unify.go
- union.go
- universe.go
- util.go
- validtype.go
- version.go