Functions
AddMethod
method
#
AddMethod adds method m unless it is already in the method list.
The method must be in the same package as t, and t must not have
type arguments.
func (t *Named) AddMethod(m *Func)
Addressable
method
#
Addressable reports whether the corresponding expression
is addressable (https://golang.org/ref/spec#Address_operators).
func (tv TypeAndValue) Addressable() bool
Alignof
method
#
func (s *StdSizes) Alignof(T Type) (result int64)
Alignof
method
#
func (s *gcSizes) Alignof(T Type) (result int64)
Anonymous
method
#
Anonymous reports whether the variable is an embedded field.
Same as Embedded; only present for backward-compatibility.
func (obj *Var) Anonymous() bool
AsPointer
function
#
If t is a pointer, AsPointer returns that type, otherwise it returns nil.
func AsPointer(t Type) *Pointer
AsSignature
function
#
If t is a signature, AsSignature returns that type, otherwise it returns nil.
func AsSignature(t Type) *Signature
AssertableTo
function
#
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 AssertableTo(V *Interface, T Type) bool
Assignable
method
#
Assignable reports whether the corresponding expression
is assignable to (provided a value of the right type).
func (tv TypeAndValue) Assignable() bool
AssignableTo
function
#
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 AssignableTo(V Type, T Type) bool
At
method
#
At returns the i'th type in the list.
func (l *TypeList) At(i int) Type
At
method
#
At returns the i'th type parameter in the list.
func (l *TypeParamList) At(i int) *TypeParam
At
method
#
At returns the i'th variable of tuple t.
func (t *Tuple) At(i int) *Var
Check
method
#
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 *syntax.Files and corresponding
file set, and the package path the package is identified with.
The clean path must not be empty or dot (".").
func (conf *Config) Check(path string, files []*syntax.File, info *Info) (*Package, error)
Child
method
#
Child returns the i'th child scope for 0 <= i < NumChildren().
func (s *Scope) Child(i int) *Scope
Comparable
function
#
Comparable reports whether values of type T are comparable.
func Comparable(T Type) bool
Complete
method
#
A package is complete if its scope contains (at least) all
exported objects; otherwise it is incomplete.
func (pkg *Package) Complete() bool
Constraint
method
#
Constraint returns the type constraint specified for t.
func (t *TypeParam) Constraint() Type
ConvertibleTo
function
#
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 ConvertibleTo(V Type, T Type) bool
CoreType
function
#
If typ is a type parameter, CoreType returns the single underlying
type of all types in the corresponding type constraint if it exists, or
nil otherwise. If the type set contains only unrestricted and restricted
channel types (with identical element types), the single underlying type
is the restricted channel type if the restrictions are always the same.
If typ is not a type parameter, CoreType returns the underlying type.
func CoreType(t Type) Type
DefPredeclaredTestFuncs
function
#
DefPredeclaredTestFuncs defines the assert and trace built-ins.
These built-ins are intended for debugging and testing of this
package only.
func DefPredeclaredTestFuncs()
Default
function
#
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 Default(t Type) Type
Dir
method
#
Dir returns the direction of channel c.
func (c *Chan) Dir() ChanDir
Elem
method
#
Elem returns the element type of slice s.
func (s *Slice) Elem() Type
Elem
method
#
Elem returns the element type of channel c.
func (c *Chan) Elem() Type
Elem
method
#
Elem returns element type of array a.
func (a *Array) Elem() Type
Elem
method
#
Elem returns the element type of map m.
func (m *Map) Elem() Type
Elem
method
#
Elem returns the element type for the given pointer p.
func (p *Pointer) Elem() Type
Embedded
method
#
Embedded reports whether the variable is an embedded field.
func (obj *Var) Embedded() bool
EmbeddedType
method
#
EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
func (t *Interface) EmbeddedType(i int) Type
Empty
method
#
Empty reports whether t is the empty interface.
func (t *Interface) Empty() bool
Error
method
#
func (e *ArgumentError) Error() string
Error
method
#
Error returns an error string formatted as follows:
filename:line:column: message
func (err Error) Error() string
ExplicitMethod
method
#
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 (t *Interface) ExplicitMethod(i int) *Func
Exported
method
#
func (*lazyObject) Exported() bool
Exported
method
#
Exported reports whether the object is exported (starts with a capital letter).
It doesn't take into account whether the object is in a local (function) scope
or not.
func (obj *object) Exported() bool
ExprString
function
#
ExprString returns a string representation of x.
func ExprString(x syntax.Node) string
Field
method
#
Field returns the i'th field for 0 <= i < NumFields().
func (s *Struct) Field(i int) *Var
Files
method
#
Files checks the provided files as part of the checker's package.
func (check *Checker) Files(files []*syntax.File) (err error)
FullError
method
#
FullError returns an error string like Error, buy it may contain
type-checker internal details such as subscript indices for type
parameters and more. Useful for debugging.
func (err Error) FullError() string
FullName
method
#
FullName returns the package- or receiver-type-qualified name of
function or method obj.
func (obj *Func) FullName() string
GoVersion
method
#
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 (pkg *Package) GoVersion() string
HasOk
method
#
HasOk reports whether the corresponding expression may be
used on the rhs of a comma-ok assignment.
func (tv TypeAndValue) HasOk() bool
Id
method
#
func (*lazyObject) Id() string
Id
function
#
Id returns name if it is exported, otherwise it
returns the name qualified with the package path.
func Id(pkg *Package, name string) string
Id
method
#
Id is a wrapper for Id(obj.Pkg(), obj.Name()).
func (obj *object) Id() string
Identical
function
#
Identical reports whether x and y are identical types.
Receivers of [Signature] types are ignored.
Predicates such as [Identical], [Implements], and
[Satisfies] assume that both operands belong to a
consistent collection of symbols ([Object] values).
For example, two [Named] types can be identical only if their
[Named.Obj] methods return the same [TypeName] symbol.
A collection of symbols is consistent if, for each logical
package whose path is P, the creation of those symbols
involved at most one call to [NewPackage](P, ...).
To ensure consistency, use a single [Importer] for
all loaded packages and their dependencies.
For more information, see https://github.com/golang/go/issues/57497.
func Identical(x Type, y Type) bool
IdenticalIgnoreTags
function
#
IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored.
Receivers of [Signature] types are ignored.
func IdenticalIgnoreTags(x Type, y Type) bool
Implements
function
#
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 Implements(V Type, T *Interface) bool
Imported
method
#
Imported returns the package that was imported.
It is distinct from Pkg(), which is the package containing the import statement.
func (obj *PkgName) Imported() *Package
Imports
method
#
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 (pkg *Package) Imports() []*Package
Index
method
#
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:
1. the list of declared methods of a named type; or
2. the list of methods of an interface type; or
3. 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 (s *Selection) Index() []int
Index
method
#
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 (t *TypeParam) Index() int
Indirect
method
#
Indirect reports whether any pointer indirection was required to get from
x to f in x.f.
Beware: Indirect spuriously returns true (Go issue #8353) for a
MethodVal selection in which the receiver argument and parameter
both have type *T so there is no indirection.
Unfortunately, a fix is too risky.
func (s *Selection) Indirect() bool
Info
method
#
Info returns information about properties of basic type b.
func (b *Basic) Info() BasicInfo
Insert
method
#
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 (s *Scope) Insert(obj Object) Object
InsertLazy
method
#
InsertLazy is like Insert, but allows deferring construction of the
inserted object until it's accessed with Lookup. The Object
returned by resolve must have the same name as given to InsertLazy.
If s already contains an alternative object with the same name,
InsertLazy leaves s unchanged and returns false. Otherwise it
records the binding and returns true. The object's parent scope
will be set to s after resolve is called.
func (s *Scope) InsertLazy(name string, resolve func() Object) bool
Instantiate
function
#
Instantiate instantiates the type orig with the given type arguments targs.
orig must be an *Alias, *Named, or *Signature type. If there is no error,
the resulting Type is an instantiated type of the same kind (*Alias, *Named
or *Signature, respectively).
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 respective
type constraints. If verification fails, the resulting error may wrap an
*ArgumentError indicating which type argument did not satisfy its 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.
func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)
IsAlias
method
#
IsAlias reports whether obj is an alias name for a type.
func (obj *TypeName) IsAlias() bool
IsAll
method
#
IsAll reports whether s is the set of all types (corresponding to the empty interface).
func (s *_TypeSet) IsAll() bool
IsBuiltin
method
#
IsBuiltin reports whether the corresponding expression denotes
a (possibly parenthesized) built-in function.
func (tv TypeAndValue) IsBuiltin() bool
IsComparable
method
#
IsComparable reports whether each type in interface t's type set is comparable.
func (t *Interface) IsComparable() bool
IsComparable
method
#
IsComparable reports whether each type in the set is comparable.
func (s *_TypeSet) IsComparable(seen map[Type]bool) bool
IsEmpty
method
#
IsEmpty reports whether s is the empty set.
func (s *_TypeSet) IsEmpty() bool
IsField
method
#
IsField reports whether the variable is a struct field.
func (obj *Var) IsField() bool
IsImplicit
method
#
IsImplicit reports whether the interface t is a wrapper for a type set literal.
func (t *Interface) IsImplicit() bool
IsInterface
function
#
IsInterface reports whether t is an interface type.
func IsInterface(t Type) bool
IsMethodSet
method
#
IsMethodSet reports whether the interface t is fully described by its method set.
func (t *Interface) IsMethodSet() bool
IsMethodSet
method
#
IsMethodSet reports whether the interface t is fully described by its method set.
func (s *_TypeSet) IsMethodSet() bool
IsNil
method
#
IsNil reports whether the corresponding expression denotes the
predeclared value nil. Depending on context, it may have been
given a type different from UntypedNil.
func (tv TypeAndValue) IsNil() bool
IsSyncAtomicAlign64
function
#
func IsSyncAtomicAlign64(T Type) bool
IsType
method
#
IsType reports whether the corresponding expression specifies a type.
func (tv TypeAndValue) IsType() bool
IsValue
method
#
IsValue reports whether the corresponding expression is a value.
Builtins are not considered values. Constant values have a non-
nil Value.
func (tv TypeAndValue) IsValue() bool
IsVoid
method
#
IsVoid reports whether the corresponding expression
is a function call without results.
func (tv TypeAndValue) IsVoid() bool
Key
method
#
Key returns the key type of map m.
func (m *Map) Key() Type
Kind
method
#
Kind returns the selection kind.
func (s *Selection) Kind() SelectionKind
Kind
method
#
Kind returns the kind of basic type b.
func (b *Basic) Kind() BasicKind
Len
method
#
Len returns the number of type parameters in the list.
It is safe to call on a nil receiver.
func (l *TypeParamList) Len() int
Len
method
#
func (s typeParamsById) Len() int
Len
method
#
func (a nodeQueue) Len() int
Len
method
#
Len returns the number of types in the list.
It is safe to call on a nil receiver.
func (l *TypeList) Len() int
Len
method
#
func (u *Union) Len() int
Len
method
#
Len returns the number variables of tuple t.
func (t *Tuple) Len() int
Len
method
#
Len returns the length of array a.
A negative result indicates an unknown length.
func (a *Array) Len() int64
Len
method
#
Len returns the number of scope elements.
func (s *Scope) Len() int
Less
method
#
func (a nodeQueue) Less(i int, j int) bool
Less
method
#
func (s typeParamsById) Less(i int, j int) bool
Lookup
method
#
Lookup returns the object in scope s with the given name if such an
object exists; otherwise the result is nil.
func (s *Scope) Lookup(name string) Object
LookupFieldOrMethod
function
#
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:
1. the list of declared methods of a named type; or
2. the list of all methods (method set) of an interface type; or
3. 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.
func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)
LookupMethod
method
#
LookupMethod returns the index of and method with matching package and name, or (-1, nil).
func (s *_TypeSet) LookupMethod(pkg *Package, name string, foldCase bool) (int, *Func)
MarkComplete
method
#
MarkComplete marks a package as complete.
func (pkg *Package) MarkComplete()
MarkImplicit
method
#
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 (t *Interface) MarkImplicit()
Method
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.
Methods are numbered deterministically: given the same list of source files
presented to the type checker, or the same sequence of NewMethod and AddMethod
calls, the mapping from method index to corresponding method remains the same.
But the specific ordering is not specified and must not be relied on as it may
change in the future.
func (t *Named) Method(i int) *Func
Method
method
#
Method returns the i'th method of s for 0 <= i < s.NumMethods().
The methods are ordered by their unique ID.
func (s *_TypeSet) Method(i int) *Func
Method
method
#
Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
The methods are ordered by their unique Id.
func (t *Interface) Method(i int) *Func
MissingMethod
function
#
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 MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
Name
method
#
func (*lazyObject) Name() string
Name
method
#
Name returns the package name.
func (pkg *Package) Name() string
Name
method
#
Name returns the name of basic type b.
func (b *Basic) Name() string
Name
method
#
Name returns the object's (package-local, unqualified) name.
func (obj *object) Name() string
Names
method
#
Names returns the scope's element names in sorted order.
func (s *Scope) Names() []string
NewAlias
function
#
NewAlias creates a new Alias type with the given type name and rhs.
rhs must not be nil.
func NewAlias(obj *TypeName, rhs Type) *Alias
NewArray
function
#
NewArray returns a new array type for the given element type and length.
A negative length indicates an unknown length.
func NewArray(elem Type, len int64) *Array
NewChan
function
#
NewChan returns a new channel type for the given direction and element type.
func NewChan(dir ChanDir, elem Type) *Chan
NewChecker
function
#
NewChecker returns a new Checker instance for a given package.
Package files may be added incrementally via checker.Files.
func NewChecker(conf *Config, pkg *Package, info *Info) *Checker
NewConst
function
#
NewConst returns a new constant with value val.
The remaining arguments set the attributes found with all Objects.
func NewConst(pos syntax.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const
NewContext
function
#
NewContext creates a new Context.
func NewContext() *Context
NewField
function
#
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 NewField(pos syntax.Pos, pkg *Package, name string, typ Type, embedded bool) *Var
NewFunc
function
#
NewFunc returns a new function with the given signature, representing
the function's type.
func NewFunc(pos syntax.Pos, pkg *Package, name string, sig *Signature) *Func
NewInterfaceType
function
#
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.
func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface
NewLabel
function
#
NewLabel returns a new label.
func NewLabel(pos syntax.Pos, pkg *Package, name string) *Label
NewMap
function
#
NewMap returns a new map for the given key and element types.
func NewMap(key Type, elem Type) *Map
NewNamed
function
#
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 NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
NewPackage
function
#
NewPackage returns a new Package for the given package path and name.
The package is not complete and contains no explicit imports.
func NewPackage(path string, name string) *Package
NewParam
function
#
NewParam returns a new variable representing a function parameter.
func NewParam(pos syntax.Pos, pkg *Package, name string, typ Type) *Var
NewPkgName
function
#
NewPkgName returns a new PkgName object representing an imported package.
The remaining arguments set the attributes found with all Objects.
func NewPkgName(pos syntax.Pos, pkg *Package, name string, imported *Package) *PkgName
NewPointer
function
#
NewPointer returns a new pointer type for the given element (base) type.
func NewPointer(elem Type) *Pointer
NewScope
function
#
NewScope returns a new, empty scope contained in the given parent
scope, if any. The comment is for debugging only.
func NewScope(parent *Scope, pos syntax.Pos, end syntax.Pos, comment string) *Scope
NewSignatureType
function
#
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 NewSignatureType(recv *Var, recvTypeParams []*TypeParam, typeParams []*TypeParam, params *Tuple, results *Tuple, variadic bool) *Signature
NewSlice
function
#
NewSlice returns a new slice type for the given element type.
func NewSlice(elem Type) *Slice
NewStruct
function
#
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 NewStruct(fields []*Var, tags []string) *Struct
NewTerm
function
#
NewTerm returns a new union term.
func NewTerm(tilde bool, typ Type) *Term
NewTuple
function
#
NewTuple returns a new tuple for the given variables.
func NewTuple(x ...*Var) *Tuple
NewTypeName
function
#
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.
func NewTypeName(pos syntax.Pos, pkg *Package, name string, typ Type) *TypeName
NewTypeNameLazy
function
#
NewTypeNameLazy returns a new defined type like NewTypeName, but it
lazily calls resolve to finish constructing the Named object.
func NewTypeNameLazy(pos syntax.Pos, pkg *Package, name string, load func(named *Named) (tparams []*TypeParam, underlying Type, methods []*Func)) *TypeName
NewTypeParam
function
#
NewTypeParam returns a new TypeParam. Type parameters may be set on a Named
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 NewTypeParam(obj *TypeName, constraint Type) *TypeParam
NewUnion
function
#
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 NewUnion(terms []*Term) *Union
NewVar
function
#
NewVar returns a new variable.
The arguments set the attributes found with all Objects.
func NewVar(pos syntax.Pos, pkg *Package, name string, typ Type) *Var
NumChildren
method
#
NumChildren returns the number of scopes nested in s.
func (s *Scope) NumChildren() int
NumEmbeddeds
method
#
NumEmbeddeds returns the number of embedded types in interface t.
func (t *Interface) NumEmbeddeds() int
NumExplicitMethods
method
#
NumExplicitMethods returns the number of explicitly declared methods of interface t.
func (t *Interface) NumExplicitMethods() int
NumFields
method
#
NumFields returns the number of fields in the struct (including blank and embedded fields).
func (s *Struct) NumFields() int
NumMethods
method
#
NumMethods returns the number of methods available.
func (s *_TypeSet) NumMethods() int
NumMethods
method
#
NumMethods returns the total number of methods of interface t.
func (t *Interface) NumMethods() int
NumMethods
method
#
NumMethods returns the number of explicit methods defined for t.
func (t *Named) NumMethods() int
Obj
method
#
Obj returns the type name for the declaration defining the alias type a.
For instantiated types, this is same as the type name of the origin type.
func (a *Alias) Obj() *TypeName
Obj
method
#
Obj returns the type name for the type parameter t.
func (t *TypeParam) Obj() *TypeName
Obj
method
#
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 (t *Named) Obj() *TypeName
Obj
method
#
Obj returns the object denoted by x.f; a *Var for
a field selection, and a *Func in all other cases.
func (s *Selection) Obj() Object
ObjectOf
method
#
ObjectOf returns the object denoted by the specified id,
or nil if not found.
If id is an embedded struct field, ObjectOf returns the field (*Var)
it defines, not the type (*TypeName) it uses.
Precondition: the Uses and Defs maps are populated.
func (info *Info) ObjectOf(id *syntax.Name) Object
ObjectString
function
#
ObjectString returns the string form of obj.
The Qualifier controls the printing of
package-level objects, and may be nil.
func ObjectString(obj Object, qf Qualifier) string
Offsetsof
method
#
func (s *StdSizes) Offsetsof(fields []*Var) []int64
Offsetsof
method
#
func (s *gcSizes) Offsetsof(fields []*Var) []int64
Origin
method
#
Origin returns the generic Alias type of which a is an instance.
If a is not an instance of a generic alias, Origin returns a.
func (a *Alias) Origin() *Alias
Origin
method
#
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.
func (obj *Func) Origin() *Func
Origin
method
#
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.
func (obj *Var) Origin() *Var
Origin
method
#
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 (t *Named) Origin() *Named
Params
method
#
Params returns the parameters of signature s, or nil.
func (s *Signature) Params() *Tuple
Parent
method
#
stub implementations so *lazyObject implements Object and we can
store them directly into Scope.elems.
func (*lazyObject) Parent() *Scope
Parent
method
#
Parent returns the scope's containing (parent) scope.
func (s *Scope) Parent() *Scope
Parent
method
#
Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields.
func (obj *object) Parent() *Scope
Path
method
#
Path returns the package path.
func (pkg *Package) Path() string
Pkg
method
#
Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope.
func (obj *object) Pkg() *Package
Pkg
method
#
func (*lazyObject) Pkg() *Package
Pkg
method
#
Pkg returns the package to which the function belongs.
The result is nil for methods of types in the Universe scope,
like method Error of the error built-in interface type.
func (obj *Func) Pkg() *Package
PkgNameOf
method
#
PkgNameOf returns the local package name defined by the import,
or nil if not found.
For dot-imports, the package name is ".".
Precondition: the Defs and Implicts maps are populated.
func (info *Info) PkgNameOf(imp *syntax.ImportDecl) *PkgName
Pop
method
#
func (a *nodeQueue) Pop() any
Pos
method
#
Pos returns the declaration position of the object's identifier.
func (obj *object) Pos() syntax.Pos
Pos
method
#
func (*lazyObject) Pos() syntax.Pos
Pos
method
#
Pos returns the position of the expression corresponding to x.
If x is invalid the position is nopos.
func (x *operand) Pos() syntax.Pos
Push
method
#
func (a *nodeQueue) Push(x any)
RangeKeyVal
function
#
RangeKeyVal returns the key and value types for a range over typ.
It panics if range over typ is invalid.
func RangeKeyVal(typ Type) (Type, Type)
Recv
method
#
Recv returns the type of x in x.f.
func (s *Selection) Recv() Type
Recv
method
#
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 (s *Signature) Recv() *Var
RecvTypeParams
method
#
RecvTypeParams returns the receiver type parameters of signature s, or nil.
func (s *Signature) RecvTypeParams() *TypeParamList
RelativeTo
function
#
RelativeTo returns a [Qualifier] that fully qualifies members of
all packages other than pkg.
func RelativeTo(pkg *Package) Qualifier
RenameResult
method
#
RenameResult takes an array of (result) fields and an index, and if the indexed field
does not have a name and if the result in the signature also does not have a name,
then the signature and field are renamed to
fmt.Sprintf("#rv%d", i+1)
the newly named object is inserted into the signature's scope,
and the object and new field name are returned.
The intended use for RenameResult is to allow rangefunc to assign results within a closure.
This is a hack, as narrowly targeted as possible to discourage abuse.
func (s *Signature) RenameResult(results []*syntax.Field, i int) (*Var, *syntax.Name)
Results
method
#
Results returns the results of signature s, or nil.
func (s *Signature) Results() *Tuple
Rhs
method
#
Rhs returns the type R on the right-hand side of an alias
declaration "type A = R", which may be another alias.
func (a *Alias) Rhs() Type
Satisfies
function
#
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 Satisfies(V Type, T *Interface) bool
Scope
method
#
Scope returns the scope of the function's body block.
The result is nil for imported or instantiated functions and methods
(but there is also no mechanism to get to an instantiated function).
func (obj *Func) Scope() *Scope
Scope
method
#
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 (pkg *Package) Scope() *Scope
SelectionString
function
#
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 SelectionString(s *Selection, qf Qualifier) string
SetConstraint
method
#
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 (t *TypeParam) SetConstraint(bound Type)
SetImports
method
#
SetImports sets the list of explicitly imported packages to list.
It is the caller's responsibility to make sure list elements are unique.
func (pkg *Package) SetImports(list []*Package)
SetName
method
#
SetName sets the package name.
func (pkg *Package) SetName(name string)
SetTypeParams
method
#
SetTypeParams sets the type parameters of the alias type a.
The alias a must not have type arguments.
func (a *Alias) SetTypeParams(tparams []*TypeParam)
SetTypeParams
method
#
SetTypeParams sets the type parameters of the named type t.
t must not have type arguments.
func (t *Named) SetTypeParams(tparams []*TypeParam)
SetUnderlying
method
#
SetUnderlying sets the underlying type and marks t as complete.
t must not have type arguments.
func (t *Named) SetUnderlying(underlying Type)
Signature
method
#
Signature returns the signature (type) of the function or method.
func (obj *Func) Signature() *Signature
Sizeof
method
#
func (s *gcSizes) Sizeof(T Type) int64
Sizeof
method
#
func (s *StdSizes) Sizeof(T Type) int64
SizesFor
function
#
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".
func SizesFor(compiler string, arch string) Sizes
String
method
#
func (obj *Nil) String() string
String
method
#
String returns a string representation of the scope, for debugging.
func (s *Scope) String() string
String
method
#
func (p *Pointer) String() string
String
method
#
func (c *Chan) String() string
String
method
#
String returns a string representation of the current mapping
from type parameters to types.
func (u *unifier) String() string
String
method
#
func (a *Array) String() string
String
method
#
func (x *term) String() string
String
method
#
func (obj *Label) String() string
String
method
#
func (s *Slice) String() string
String
method
#
func (c color) String() string
String
method
#
func (t *Interface) String() string
String
method
#
func (init *Initializer) String() string
String
method
#
String prints the termlist exactly (without normalization).
func (xl termlist) String() string
String
method
#
func (obj *object) String() string
String
method
#
func (m unifyMode) String() string
String
method
#
func (s *Selection) String() string
String
method
#
func (t *Named) String() string
String
method
#
func (s *Signature) String() string
String
method
#
func (obj *Var) String() string
String
method
#
func (pkg *Package) String() string
String
method
#
func (u *Union) String() string
String
method
#
func (a *Alias) String() string
String
method
#
func (t *Tuple) String() string
String
method
#
func (obj *Func) String() string
String
method
#
func (obj *Builtin) String() string
String
method
#
func (obj *TypeName) String() string
String
method
#
func (s *_TypeSet) String() string
String
method
#
func (t *TypeParam) String() string
String
method
#
func (obj *Const) String() string
String
method
#
func (obj *PkgName) String() string
String
method
#
func (s *Struct) String() string
String
method
#
func (b *Basic) String() string
String
method
#
func (*lazyObject) String() string
String
method
#
func (x *operand) String() string
String
method
#
func (t *Term) String() string
String
method
#
func (t *Map) String() string
Swap
method
#
func (a nodeQueue) Swap(i int, j int)
Swap
method
#
func (s typeParamsById) Swap(i int, j int)
Tag
method
#
Tag returns the i'th field tag for 0 <= i < NumFields().
func (s *Struct) Tag(i int) string
Term
method
#
func (u *Union) Term(i int) *Term
Tilde
method
#
func (t *Term) Tilde() bool
Type
method
#
func (*lazyObject) Type() Type
Type
method
#
func (t *Term) Type() Type
Type
method
#
Type returns the object's type.
func (obj *object) Type() Type
Type
method
#
Type returns the type of x.f, which may be different from the type of f.
See Selection for more information.
func (s *Selection) Type() Type
TypeArgs
method
#
TypeArgs returns the type arguments used to instantiate the Alias type.
If a is not an instance of a generic alias, the result is nil.
func (a *Alias) TypeArgs() *TypeList
TypeArgs
method
#
TypeArgs returns the type arguments used to instantiate the named type t.
func (t *Named) TypeArgs() *TypeList
TypeOf
method
#
TypeOf returns the type of expression e, or nil if not found.
Precondition 1: the Types map is populated or StoreTypesInSyntax is set.
Precondition 2: Uses and Defs maps are populated.
func (info *Info) TypeOf(e syntax.Expr) Type
TypeParams
method
#
TypeParams returns the type parameters of signature s, or nil.
func (s *Signature) TypeParams() *TypeParamList
TypeParams
method
#
TypeParams returns the type parameters of the alias type a, or nil.
A generic Alias and its instances have the same type parameters.
func (a *Alias) TypeParams() *TypeParamList
TypeParams
method
#
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 (t *Named) TypeParams() *TypeParamList
TypeString
function
#
TypeString returns the string representation of typ.
The [Qualifier] controls the printing of
package-level objects, and may be nil.
func TypeString(typ Type, qf Qualifier) string
Unalias
function
#
Unalias returns t if it is not an alias type;
otherwise it follows t's alias chain until it
reaches a non-alias type which is then returned.
Consequently, the result is never an alias type.
func Unalias(t Type) Type
Underlying
method
#
func (s *Slice) Underlying() Type
Underlying
method
#
Underlying returns the [underlying type] of the named type t, resolving all
forwarding declarations. Underlying types are never Named, TypeParam, or
Alias types.
[underlying type]: https://go.dev/ref/spec#Underlying_types.
func (t *Named) Underlying() Type
Underlying
method
#
func (t *Interface) Underlying() Type
Underlying
method
#
func (c *Chan) Underlying() Type
Underlying
method
#
Underlying returns the [underlying type] of the type parameter t, which is
the underlying type of its constraint. This type is always an interface.
[underlying type]: https://go.dev/ref/spec#Underlying_types.
func (t *TypeParam) Underlying() Type
Underlying
method
#
func (a *Array) Underlying() Type
Underlying
method
#
func (s *Signature) Underlying() Type
Underlying
method
#
func (u *Union) Underlying() Type
Underlying
method
#
func (p *Pointer) Underlying() Type
Underlying
method
#
func (t *Map) Underlying() Type
Underlying
method
#
func (t *Tuple) Underlying() Type
Underlying
method
#
func (b *Basic) Underlying() Type
Underlying
method
#
Underlying returns the [underlying type] of the alias type a, which is the
underlying type of the aliased type. Underlying types are never Named,
TypeParam, or Alias types.
[underlying type]: https://go.dev/ref/spec#Underlying_types.
func (a *Alias) Underlying() Type
Underlying
method
#
func (s *Struct) Underlying() Type
Unwrap
method
#
func (e *ArgumentError) Unwrap() error
Val
method
#
Val returns the constant's value.
func (obj *Const) Val() constant.Value
Variadic
method
#
Variadic reports whether the signature s is variadic.
func (s *Signature) Variadic() bool
WriteSignature
function
#
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.
func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
WriteTo
method
#
WriteTo writes a string representation of the scope to w,
with the scope elements sorted by name.
The level of indentation is controlled by n >= 0, with
n == 0 for no indentation.
If recurse is set, it also writes nested (children) scopes.
func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)
WriteType
function
#
WriteType writes the string representation of typ to buf.
The [Qualifier] controls the printing of
package-level objects, and may be nil.
func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)
add
method
#
func (s *nodeSet) add(p *graphNode)
add
method
#
func (l *instanceLookup) add(inst *Named)
addAltDecl
method
#
addAltDecl is a specialized form of addf reporting another declaration of obj.
func (err *error_) addAltDecl(obj Object)
addDeclDep
method
#
addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
func (check *Checker) addDeclDep(to Object)
addDep
method
#
addDep adds obj to the set of objects d's init expression depends on.
func (d *declInfo) addDep(obj Object)
addEdge
method
#
func (w *monoGraph) addEdge(dst int, src int, weight int, pos syntax.Pos, typ Type)
addf
method
#
addf adds formatted error information to err.
It may be called multiple times to provide additional information.
The position of the first call to addf determines the position of the reported Error.
Subsequent calls to addf provide additional information in the form of additional lines
in the error message (types2) or continuation errors identified by a tab-indented error
message (go/types).
func (err *error_) addf(at poser, format string, args ...interface{})
aliasAny
function
#
func aliasAny() bool
align
function
#
align returns the smallest y >= x such that y % a == 0.
a must be within 1 and 8 and it must be a power of 2.
The result may be negative due to overflow.
func align(x int64, a int64) int64
alignof
method
#
func (conf *Config) alignof(T Type) int64
allBasic
function
#
allBasic reports whether under(t) is a basic type with the specified info.
If t is a type parameter, the result is true if isBasic(t, info) is true
for all specific types of the type parameter's type set.
allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
func allBasic(t Type, info BasicInfo) bool
allBoolean
function
#
func allBoolean(t Type) bool
allInteger
function
#
func allInteger(t Type) bool
allNumeric
function
#
func allNumeric(t Type) bool
allNumericOrString
function
#
func allNumericOrString(t Type) bool
allOrdered
function
#
func allOrdered(t Type) bool
allString
function
#
func allString(t Type) bool
allUnsigned
function
#
func allUnsigned(t Type) bool
allowVersion
method
#
allowVersion reports whether the current effective Go version
(which may vary from one file to another) is allowed to use the
feature version (want).
func (check *Checker) allowVersion(want goVersion) bool
applyTypeFunc
method
#
applyTypeFunc applies f to x. If x is a type parameter,
the result is a type parameter constrained by a new
interface bound. The type bounds for that interface
are computed by applying f to each of the type bounds
of x. If any of these applications of f return nil,
applyTypeFunc returns nil.
If x is not a type parameter, the result is f(x).
func (check *Checker) applyTypeFunc(f func(Type) Type, x *operand, id builtinId) Type
argErrPos
function
#
argErrPos returns the node (poser) for reporting an invalid argument count.
func argErrPos(call *syntax.CallExpr) *syntax.CallExpr
arguments
method
#
arguments type-checks arguments passed to a function call with the given signature.
The function and its arguments may be generic, and possibly partially instantiated.
targs and xlist are the function's type arguments (and corresponding expressions).
args are the function arguments. If an argument args[i] is a partially instantiated
generic function, atargs[i] and atxlist[i] are the corresponding type arguments
(and corresponding expressions).
If the callee is variadic, arguments adjusts its signature to match the provided
arguments. The type parameters and arguments of the callee and all its arguments
are used together to infer any missing type arguments, and the callee and argument
functions are instantiated as necessary.
The result signature is the (possibly adjusted and instantiated) function signature.
If an error occurred, the result signature is the incoming sig.
func (check *Checker) arguments(call *syntax.CallExpr, sig *Signature, targs []Type, xlist []syntax.Expr, args []*operand, atargs [][]Type, atxlist [][]syntax.Expr) (rsig *Signature)
arity
method
#
arity checks that the lhs and rhs of a const or var decl
have a matching number of names and initialization values.
If inherited is set, the initialization values are from
another (constant) declaration.
func (check *Checker) arity(pos syntax.Pos, names []*syntax.Name, inits []syntax.Expr, constDecl bool, inherited bool)
arrayLength
method
#
arrayLength type-checks the array length expression e
and returns the constant length >= 0, or a value < 0
to indicate an error (and thus an unknown length).
func (check *Checker) arrayLength(e syntax.Expr) int64
arrayPtrDeref
function
#
arrayPtrDeref returns A if typ is of the form *A and A is an array;
otherwise it returns typ.
func arrayPtrDeref(typ Type) Type
asBoundTypeParam
method
#
asBoundTypeParam returns x.(*TypeParam) if x is a type parameter recorded with u.
Otherwise, the result is nil.
func (u *unifier) asBoundTypeParam(x Type) *TypeParam
asGoVersion
function
#
asGoVersion returns v as a goVersion (e.g., "go1.20.1" becomes "go1.20").
If v is not a valid Go version, the result is the empty string.
func asGoVersion(v string) goVersion
asInterface
function
#
asInterface returns the underlying type of x as an interface if
it is a non-type parameter interface. Otherwise it returns nil.
func asInterface(x Type) (i *Interface)
asNamed
function
#
asNamed returns t as *Named if that is t's
actual type. It returns nil otherwise.
func asNamed(t Type) *Named
assert
function
#
func assert(p bool)
assertSortedMethods
function
#
func assertSortedMethods(list []*Func)
assertableTo
method
#
assertableTo reports whether a value of type V can be asserted to have type T.
The receiver may be nil if assertableTo is invoked through an exported API call
(such as AssertableTo), i.e., when all methods have been type-checked.
The underlying type of V must be an interface.
If the result is false and cause is not nil, *cause describes the error.
TODO(gri) replace calls to this function with calls to newAssertableTo.
func (check *Checker) assertableTo(V Type, T Type, cause *string) bool
assign
method
#
assign records that tpar was instantiated as targ at pos.
func (w *monoGraph) assign(pkg *Package, pos syntax.Pos, tpar *TypeParam, targ Type)
assignError
method
#
func (check *Checker) assignError(rhs []syntax.Expr, l int, r int)
assignVar
method
#
assignVar checks the assignment lhs = rhs (if x == nil), or lhs = x (if x != nil).
If x != nil, it must be the evaluation of rhs (and rhs will be ignored).
If the assignment check fails and x != nil, x.mode is set to invalid.
func (check *Checker) assignVar(lhs syntax.Expr, rhs syntax.Expr, x *operand, context string)
assignVars
method
#
assignVars type-checks assignments of expressions orig_rhs to variables lhs.
func (check *Checker) assignVars(lhs []syntax.Expr, orig_rhs []syntax.Expr)
assignableTo
method
#
assignableTo reports whether x is assignable to a variable of type T. If the
result is false and a non-nil cause is provided, it may be set to a more
detailed explanation of the failure (result != ""). The returned error code
is only valid if the (first) result is false. The check parameter may be nil
if assignableTo is invoked through an exported API call, i.e., when all
methods have been type-checked.
func (x *operand) assignableTo(check *Checker, T Type, cause *string) (bool, Code)
assignment
method
#
assignment reports whether x can be assigned to a variable of type T,
if necessary by attempting to convert untyped values to the appropriate
type. context describes the context in which the assignment takes place.
Use T == nil to indicate assignment to an untyped blank identifier.
If the assignment check fails, x.mode is set to invalid.
func (check *Checker) assignment(x *operand, T Type, context string)
at
method
#
at returns the (possibly nil) type for type parameter x.
func (u *unifier) at(x *TypeParam) Type
atPos
function
#
atPos reports the left (= start) position of at.
func atPos(at poser) syntax.Pos
basicLit
method
#
func (check *Checker) basicLit(x *operand, e *syntax.BasicLit)
binary
method
#
If e != nil, it must be the binary expression; it may be nil for non-constant expressions
(when invoked for an assignment operation where the binary expression is implicit).
func (check *Checker) binary(x *operand, e syntax.Expr, lhs syntax.Expr, rhs syntax.Expr, op syntax.Operator)
bindTParams
function
#
func bindTParams(list []*TypeParam) *TypeParamList
blockBranches
method
#
blockBranches processes a block's statement list and returns the set of outgoing forward jumps.
all is the scope of all declared labels, parent the set of labels declared in the immediately
enclosing block, and lstmt is the labeled statement this block is associated with (or nil).
func (check *Checker) blockBranches(all *Scope, parent *block, lstmt *syntax.LabeledStmt, list []syntax.Stmt) []*syntax.BranchStmt
bound
method
#
func (check *Checker) bound(x syntax.Expr) Type
brokenAlias
method
#
brokenAlias records that alias doesn't have a determined type yet.
It also sets alias.typ to Typ[Invalid].
Not used if check.conf.EnableAlias is set.
func (check *Checker) brokenAlias(alias *TypeName)
builtin
method
#
builtin type-checks a call to the built-in specified by id and
reports whether the call is valid, with *x holding the result;
but x.expr is not set. If the call is invalid, the result is
false, and *x is undefined.
func (check *Checker) builtin(x *operand, call *syntax.CallExpr, id builtinId) (_ bool)
byte
method
#
func (w *typeWriter) byte(b byte)
callExpr
method
#
func (check *Checker) callExpr(x *operand, call *syntax.CallExpr) exprKind
caseTypes
method
#
caseTypes typechecks the type expressions of a type case, checks for duplicate types
using the seen map, and verifies that each type is valid with respect to the type of
the operand x corresponding to the type switch expression. If that expression is not
valid, x must be nil.
switch .(type) {
case : ...
...
}
caseTypes returns the case-specific type for a variable v introduced through a short
variable declaration by the type switch:
switch v := .(type) {
case : // T is the type of in this case
...
}
If there is exactly one type expression, T is the type of that expression. If there
are multiple type expressions, or if predeclared nil is among the types, the result
is the type of x. If x is invalid (nil), the result is the invalid type.
func (check *Checker) caseTypes(x *operand, types []syntax.Expr, seen map[Type]syntax.Expr) Type
caseTypes_currently_unused
method
#
TODO(gri) Once we are certain that typeHash is correct in all situations, use this version of caseTypes instead.
(Currently it may be possible that different types have identical names and import paths due to ImporterFrom.)
func (check *Checker) caseTypes_currently_unused(x *operand, xtyp *Interface, types []syntax.Expr, seen map[string]syntax.Expr) Type
caseValues
method
#
func (check *Checker) caseValues(x *operand, values []syntax.Expr, seen valueMap)
checkFieldUniqueness
method
#
func (check *Checker) checkFieldUniqueness(base *Named)
checkFiles
method
#
checkFiles type-checks the specified files. Errors are reported as
a side effect, not by returning early, to ensure that well-formed
syntax is properly type annotated even in a package containing
errors.
func (check *Checker) checkFiles(files []*syntax.File)
cleanup
method
#
func (t *Named) cleanup()
cleanup
method
#
func (t *TypeParam) cleanup()
cleanup
method
#
func (t *Interface) cleanup()
cleanup
method
#
cleanup runs cleanup for all collected cleaners.
func (check *Checker) cleanup()
cleanup
method
#
func (a *Alias) cleanup()
clone
function
#
clone makes a "flat copy" of *p and returns a pointer to the copy.
func clone(p P) P
cloneFunc
function
#
func cloneFunc(f *Func, typ Type) *Func
cloneVar
function
#
func cloneVar(v *Var, typ Type) *Var
closeScope
method
#
func (check *Checker) closeScope()
cmp
method
#
cmp returns -1, 0, or +1 depending on whether x < y, x == y, or x > y,
interpreted as Go versions.
func (x goVersion) cmp(y goVersion) int
cmp
method
#
cmp reports whether object a is ordered before object b.
cmp returns:
-1 if a is before b
0 if a is equivalent to b
+1 if a is behind b
Objects are ordered nil before non-nil, exported before
non-exported, then by name, and finally (for non-exported
functions) by package path.
func (a *object) cmp(b *object) int
cmpPos
function
#
cmpPos compares the positions p and q and returns a result r as follows:
r < 0: p is before q
r == 0: p and q are the same position (but may not be identical)
r > 0: p is after q
If p and q are in different files, p is before q if the filename
of p sorts lexicographically before the filename of q.
func cmpPos(p syntax.Pos, q syntax.Pos) int
collectMethods
method
#
func (check *Checker) collectMethods(obj *TypeName)
collectObjects
method
#
collectObjects collects all file and package objects and inserts them
into their respective scopes. It also performs imports and associates
methods with receiver base type names.
func (check *Checker) collectObjects()
collectParams
method
#
collectParams collects (but does not declare) all parameters of list and returns
the list of parameter names, corresponding parameter variables, and whether the
parameter list is variadic. Anonymous parameters are recorded with nil names.
func (check *Checker) collectParams(list []*syntax.Field, variadicOk bool) (names []*syntax.Name, params []*Var, variadic bool)
collectRecv
method
#
collectRecv extracts the method receiver and its type parameters (if any) from rparam.
It declares the type parameters (but not the receiver) in the current scope, and
returns the receiver variable and its type parameter list (if any).
func (check *Checker) collectRecv(rparam *syntax.Field, scopePos syntax.Pos) (*Var, *TypeParamList)
collectTypeParams
method
#
func (check *Checker) collectTypeParams(dst **TypeParamList, list []*syntax.Field)
color
method
#
func (obj *object) color() color
color
method
#
func (*lazyObject) color() color
colorFor
function
#
colorFor returns the (initial) color for an object depending on
whether its type t is known or not.
func colorFor(t Type) color
comparableType
function
#
If dynamic is set, non-type parameter interfaces are always comparable.
If reportf != nil, it may be used to report why T is not comparable.
func comparableType(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool
compareFunc
function
#
func compareFunc(a *Func, b *Func) int
comparison
method
#
If switchCase is true, the operator op is ignored.
func (check *Checker) comparison(x *operand, y *operand, op syntax.Operator, switchCase bool)
compositeKind
function
#
compositeKind returns the kind of the given composite type
("array", "slice", etc.) or the empty string if typ is not
composite but a basic type.
func compositeKind(typ Type) string
compositeLit
method
#
func (check *Checker) compositeLit(x *operand, e *syntax.CompositeLit, hint Type)
computeInterfaceTypeSet
function
#
computeInterfaceTypeSet may be called with check == nil.
func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_TypeSet
computeUnionTypeSet
function
#
computeUnionTypeSet may be called with check == nil.
The result is &invalidTypeSet if the union overflows.
func computeUnionTypeSet(check *Checker, unionSets map[*Union]*_TypeSet, pos syntax.Pos, utyp *Union) *_TypeSet
concat
function
#
concat returns the result of concatenating list and i.
The result does not share its underlying array with list.
func concat(list []int, i int) []int
consolidateMultiples
function
#
consolidateMultiples collects multiple list entries with the same type
into a single entry marked as containing multiples. The result is the
consolidated list.
func consolidateMultiples(list []embeddedType) []embeddedType
constDecl
method
#
func (check *Checker) constDecl(obj *Const, typ syntax.Expr, init syntax.Expr, inherited bool)
context
method
#
context returns the type-checker context.
func (check *Checker) context() *Context
conversion
method
#
conversion type-checks the conversion T(x).
The result is in x.
func (check *Checker) conversion(x *operand, T Type)
convertUntyped
method
#
convertUntyped attempts to set the type of an untyped value to the target type.
func (check *Checker) convertUntyped(x *operand, target Type)
convertibleTo
method
#
convertibleTo reports whether T(x) is valid. In the failure case, *cause
may be set to the cause for the failure.
The check parameter may be nil if convertibleTo is invoked through an
exported API call, i.e., when all methods have been type-checked.
func (x *operand) convertibleTo(check *Checker, T Type, cause *string) bool
coreString
function
#
coreString is like coreType but also considers []byte
and strings as identical. In this case, if successful and we saw
a string, the result is of type (possibly untyped) string.
func coreString(t Type) Type
coreTerm
function
#
If the type parameter has a single specific type S, coreTerm returns (S, true).
Otherwise, if tpar has a core type T, it returns a term corresponding to that
core type and false. In that case, if any term of tpar has a tilde, the core
term has a tilde. In all other cases coreTerm returns (nil, false).
func coreTerm(tpar *TypeParam) (*term, bool)
coreType
function
#
If t is not a type parameter, coreType returns the underlying type.
If t is a type parameter, coreType returns the single underlying
type of all types in its type set if it exists, or nil otherwise. If the
type set contains only unrestricted and restricted channel types (with
identical element types), the single underlying type is the restricted
channel type if the restrictions are always the same, or nil otherwise.
func coreType(t Type) Type
cost
method
#
cost returns the cost of removing this node, which involves copying each
predecessor to each successor (and vice-versa).
func (n *graphNode) cost() int
cycleError
method
#
cycleError reports a declaration cycle starting with the object at cycle[start].
func (check *Checker) cycleError(cycle []Object, start int)
dddErrPos
function
#
dddErrPos returns the node (poser) for reporting an invalid ... use in a call.
func dddErrPos(call *syntax.CallExpr) *syntax.CallExpr
declStmt
method
#
func (check *Checker) declStmt(list []syntax.Decl)
declare
method
#
func (check *Checker) declare(scope *Scope, id *syntax.Name, obj Object, pos syntax.Pos)
declareInSet
method
#
func (check *Checker) declareInSet(oset *objset, pos syntax.Pos, obj Object) bool
declareParams
method
#
declareParams declares each named parameter in the current scope.
func (check *Checker) declareParams(names []*syntax.Name, params []*Var, scopePos syntax.Pos)
declarePkgObj
method
#
declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
and updates check.objMap. The object must not be a function or method.
func (check *Checker) declarePkgObj(ident *syntax.Name, obj Object, d *declInfo)
declareTypeParam
method
#
func (check *Checker) declareTypeParam(name *syntax.Name, scopePos syntax.Pos) *TypeParam
def
function
#
Objects with names containing blanks are internal and not entered into
a scope. Objects with exported names are inserted in the unsafe package
scope; other objects are inserted in the universe scope.
func def(obj Object)
defPredeclaredConsts
function
#
func defPredeclaredConsts()
defPredeclaredFuncs
function
#
func defPredeclaredFuncs()
defPredeclaredNil
function
#
func defPredeclaredNil()
defPredeclaredTypes
function
#
func defPredeclaredTypes()
definedType
method
#
definedType is like typ but also accepts a type name def.
If def != nil, e is the type specification for the type named def, declared
in a type declaration, and def.typ.underlying will be set to the type of e
before any components of e are type-checked.
func (check *Checker) definedType(e syntax.Expr, def *TypeName) Type
dependencyGraph
function
#
dependencyGraph computes the object dependency graph from the given objMap,
with any function nodes removed. The resulting graph contains only constants
and variables.
func dependencyGraph(objMap map[Object]*declInfo) []*graphNode
deref
function
#
deref dereferences typ if it is a *Pointer (but not a *Named type
with an underlying pointer type!) and returns its base and true.
Otherwise it returns (typ, false).
func deref(typ Type) (Type, bool)
derefStructPtr
function
#
derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
(named or unnamed) struct and returns its base. Otherwise it returns typ.
func derefStructPtr(typ Type) Type
describef
method
#
If debug is set, describef sets a printf-formatted description for action a.
Otherwise, it is a no-op.
func (a *action) describef(pos poser, format string, args ...interface{})
dir
function
#
dir makes a good-faith attempt to return the directory
portion of path. If path is empty, the result is ".".
(Per the go/build package dependency tests, we cannot import
path/filepath and simply use filepath.Dir.)
func dir(path string) string
disjoint
method
#
disjoint reports whether x ∩ y == ∅.
x.typ and y.typ must not be nil.
func (x *term) disjoint(y *term) bool
dump
method
#
dump is only needed for debugging
func (check *Checker) dump(format string, args ...any)
embeddedFieldIdent
function
#
func embeddedFieldIdent(e syntax.Expr) *syntax.Name
empty
method
#
func (m substMap) empty() bool
empty
method
#
func (err *error_) empty() bool
enclosingTarget
method
#
enclosingTarget returns the innermost enclosing labeled
statement with the given label name, or nil.
func (b *block) enclosingTarget(name string) *syntax.LabeledStmt
endPos
function
#
endPos returns the position of the first character immediately after node n.
func endPos(n syntax.Node) syntax.Pos
equal
method
#
equal reports whether x and y represent the same type set.
func (x *term) equal(y *term) bool
equal
method
#
equal reports whether xl and yl represent the same type set.
func (xl termlist) equal(yl termlist) bool
error
method
#
func (w *typeWriter) error(msg string)
error
method
#
func (check *Checker) error(at poser, code Code, msg string)
errorUnusedPkg
method
#
func (check *Checker) errorUnusedPkg(obj *PkgName)
errorf
method
#
func (check *Checker) errorf(at poser, code Code, format string, args ...any)
exclude
method
#
exclude reports an error if x.mode is in modeset and sets x.mode to invalid.
The modeset may contain any of 1<
func (check *Checker) exclude(x *operand, modeset uint)
expandMethod
method
#
expandMethod substitutes type arguments in the i'th method for an
instantiated receiver.
func (t *Named) expandMethod(i int) *Func
expandUnderlying
method
#
expandUnderlying substitutes type arguments in the underlying type n.orig,
returning the result. Returns Typ[Invalid] if there was an error.
func (n *Named) expandUnderlying() Type
expr
method
#
expr typechecks expression e and initializes x with the expression value.
If a non-nil target T is given and e is a generic function or
a function call, T is used to infer the type arguments for e.
The result must be a single value.
If an error occurred, x.mode is set to invalid.
func (check *Checker) expr(T *target, x *operand, e syntax.Expr)
exprInternal
method
#
exprInternal contains the core of type checking of expressions.
Must only be called by rawExpr.
(See rawExpr for an explanation of the parameters.)
func (check *Checker) exprInternal(T *target, x *operand, e syntax.Expr, hint Type) exprKind
exprList
method
#
exprList evaluates a list of expressions and returns the corresponding operands.
A single-element expression list may evaluate to multiple operands.
func (check *Checker) exprList(elist []syntax.Expr) (xlist []*operand)
exprOrType
method
#
exprOrType typechecks expression or type e and initializes x with the expression value or type.
If allowGeneric is set, the operand type may be an uninstantiated parameterized type or function
value.
If an error occurred, x.mode is set to invalid.
func (check *Checker) exprOrType(x *operand, e syntax.Expr, allowGeneric bool)
exprWithHint
method
#
exprWithHint typechecks expression e and initializes x with the expression value;
hint is the type of a composite literal element.
If an error occurred, x.mode is set to invalid.
func (check *Checker) exprWithHint(x *operand, e syntax.Expr, hint Type)
fieldIndex
function
#
fieldIndex returns the index for the field with matching package and name, or a value < 0.
See Object.sameId for the meaning of foldCase.
func fieldIndex(fields []*Var, pkg *Package, name string, foldCase bool) int
filename
method
#
filename returns a filename suitable for debugging output.
func (check *Checker) filename(fileNo int) string
findPath
function
#
findPath returns the (reversed) list of objects []Object{to, ... from}
such that there is a path of object dependencies from 'from' to 'to'.
If there is no such path, the result is nil.
func findPath(objMap map[Object]*declInfo, from Object, to Object, seen map[Object]bool) []Object
firstInSrc
function
#
firstInSrc reports the index of the object with the "smallest"
source position in path. path must not be empty.
func firstInSrc(path []Object) int
fitsFloat32
function
#
func fitsFloat32(x constant.Value) bool
fitsFloat64
function
#
func fitsFloat64(x constant.Value) bool
flattenUnion
function
#
flattenUnion walks a union type expression of the form A | B | C | ...,
extracting both the binary exprs (blist) and leaf types (tlist).
func flattenUnion(list []syntax.Expr, x syntax.Expr) (blist []syntax.Expr, tlist []syntax.Expr)
funcBody
method
#
decl may be nil
func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body *syntax.BlockStmt, iota constant.Value)
funcDecl
method
#
func (check *Checker) funcDecl(obj *Func, decl *declInfo)
funcInst
method
#
funcInst type-checks a function instantiation.
The incoming x must be a generic function.
If inst != nil, it provides some or all of the type arguments (inst.Index).
If target != nil, it may be used to infer missing type arguments of x, if any.
At least one of T or inst must be provided.
There are two modes of operation:
1. If infer == true, funcInst infers missing type arguments as needed and
instantiates the function x. The returned results are nil.
2. If infer == false and inst provides all type arguments, funcInst
instantiates the function x. The returned results are nil.
If inst doesn't provide enough type arguments, funcInst returns the
available arguments and the corresponding expression list; x remains
unchanged.
If an error (other than a version error) occurs in any case, it is reported
and x.mode is set to invalid.
func (check *Checker) funcInst(T *target, pos syntax.Pos, x *operand, inst *syntax.IndexExpr, infer bool) ([]Type, []syntax.Expr)
funcLit
method
#
func (check *Checker) funcLit(x *operand, e *syntax.FuncLit)
funcString
method
#
funcString returns a string of the form name + signature for f.
check may be nil.
func (check *Checker) funcString(f *Func, pkgInfo bool) string
funcType
method
#
funcType type-checks a function or method type.
func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType)
func_
method
#
func (subst *subster) func_(f *Func) *Func
gcSizesFor
function
#
gcSizesFor returns the Sizes used by gc for an architecture.
The result is a nil *gcSizes pointer (which is not a valid types.Sizes)
if a compiler/architecture pair is not known.
func gcSizesFor(compiler string, arch string) *gcSizes
genericExpr
method
#
genericExpr is like expr but the result may also be generic.
func (check *Checker) genericExpr(x *operand, e syntax.Expr)
genericExprList
method
#
genericExprList is like exprList but result operands may be uninstantiated or partially
instantiated generic functions (where constraint information is insufficient to infer
the missing type arguments) for Go 1.21 and later.
For each non-generic or uninstantiated generic operand, the corresponding targsList and
xlistList elements do not exist (targsList and xlistList are nil) or the elements are nil.
For each partially instantiated generic function operand, the corresponding targsList and
xlistList elements are the operand's partial type arguments and type expression lists.
func (check *Checker) genericExprList(elist []syntax.Expr) (resList []*operand, targsList [][]Type, xlistList [][]syntax.Expr)
genericType
method
#
genericType is like typ but the type must be an (uninstantiated) generic
type. If cause is non-nil and the type expression was a valid type but not
generic, cause will be populated with a message describing the error.
Note: If the type expression was invalid and an error was reported before,
cause will not be populated; thus cause alone cannot be used to determine
if an error occurred.
func (check *Checker) genericType(e syntax.Expr, cause *string) Type
getID
method
#
getID returns a unique ID for the type t.
func (ctxt *Context) getID(t Type) int
goTypeName
function
#
goTypeName returns the Go type name for typ and
removes any occurrences of "types2." from that name.
func goTypeName(typ Type) string
goVal
function
#
goVal returns the Go value for val, or nil.
func goVal(val constant.Value) interface{}
gotoTarget
method
#
gotoTarget returns the labeled statement in the current
or an enclosing block with the given label name, or nil.
func (b *block) gotoTarget(name string) *syntax.LabeledStmt
handleBailout
method
#
func (check *Checker) handleBailout(err *error)
handleError
method
#
handleError should only be called by error_.report.
func (check *Checker) handleError(index int, pos syntax.Pos, code Code, msg string, soft bool)
hasAllMethods
method
#
hasAllMethods is similar to checkMissingMethod but instead reports whether all methods are present.
If V is not a valid type, or if it is a struct containing embedded fields with invalid types, the
result is true because it is not possible to say with certainty whether a method is missing or not
(an embedded field may have the method in question).
If the result is false and cause is not nil, *cause describes the error.
Use hasAllMethods to avoid follow-on errors due to incorrect types.
func (check *Checker) hasAllMethods(V Type, T Type, static bool, equivalent func(x Type, y Type) bool, cause *string) bool
hasBreak
function
#
hasBreak reports if s is or contains a break statement
referring to the label-ed statement or implicit-ly the
closest outer breakable statement.
func hasBreak(s syntax.Stmt, label string, implicit bool) bool
hasBreakCaseList
function
#
func hasBreakCaseList(list []*syntax.CaseClause, label string, implicit bool) bool
hasBreakCommList
function
#
func hasBreakCommList(list []*syntax.CommClause, label string, implicit bool) bool
hasBreakList
function
#
func hasBreakList(list []syntax.Stmt, label string, implicit bool) bool
hasDots
function
#
hasDots reports whether the last argument in the call is followed by ...
func hasDots(call *syntax.CallExpr) bool
hasEmptyTypeset
function
#
hasEmptyTypeset reports whether t is a type parameter with an empty type set.
The function does not force the computation of the type set and so is safe to
use anywhere, but it may report a false negative if the type set has not been
computed yet.
func hasEmptyTypeset(t Type) bool
hasInitializer
method
#
hasInitializer reports whether the declared object has an initialization
expression or function body.
func (d *declInfo) hasInitializer() bool
hasInvalidEmbeddedFields
function
#
hasInvalidEmbeddedFields reports whether T is a struct (or a pointer to a struct) that contains
(directly or indirectly) embedded fields with invalid types.
func hasInvalidEmbeddedFields(T Type, seen map[*Struct]bool) bool
hasName
function
#
hasName reports whether t has a name. This includes
predeclared types, defined types, and type parameters.
hasName may be called with types that are not fully set up.
func hasName(t Type) bool
hasNil
function
#
hasNil reports whether type t includes the nil value.
func hasNil(t Type) bool
hasPtrRecv
method
#
hasPtrRecv reports whether the receiver is of the form *T for the given method obj.
func (obj *Func) hasPtrRecv() bool
hasTerms
method
#
hasTerms reports whether s has specific type terms.
func (s *_TypeSet) hasTerms() bool
hasVarSize
function
#
hasVarSize reports if the size of type t is variable due to type parameters
or if the type is infinitely-sized due to a cycle for which the type has not
yet been checked.
func hasVarSize(t Type, seen map[*Named]bool) (varSized bool)
ident
method
#
ident type-checks identifier e and initializes x with the value or type of e.
If an error occurred, x.mode is set to invalid.
For the meaning of def, see Checker.definedType, below.
If wantType is set, the identifier e is expected to denote a type.
func (check *Checker) ident(x *operand, e *syntax.Name, def *TypeName, wantType bool)
identical
method
#
func (p *ifacePair) identical(q *ifacePair) bool
identical
method
#
For changes to this code the corresponding changes should be made to unifier.nify.
func (c *comparer) identical(x Type, y Type, p *ifacePair) bool
identicalInstance
function
#
identicalInstance reports if two type instantiations are identical.
Instantiations are identical if their origin and type arguments are
identical.
func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool
identicalOrigin
function
#
identicalOrigin reports whether x and y originated in the same declaration.
func identicalOrigin(x *Named, y *Named) bool
iface
method
#
iface returns the constraint interface of t.
func (t *TypeParam) iface() *Interface
implements
method
#
implements checks if V implements T. The receiver may be nil if implements
is called through an exported API call such as AssignableTo. If constraint
is set, T is a type constraint.
If the provided cause is non-nil, it may be set to an error string
explaining why V does not implement (or satisfy, for constraints) T.
func (check *Checker) implements(V Type, T Type, constraint bool, cause *string) bool
implicitTypeAndValue
method
#
implicitTypeAndValue returns the implicit type of x when used in a context
where the target type is expected. If no such implicit conversion is
possible, it returns a nil Type and non-zero error code.
If x is a constant operand, the returned constant.Value will be the
representation of x in this context.
func (check *Checker) implicitTypeAndValue(x *operand, target Type) (Type, constant.Value, Code)
importPackage
method
#
func (check *Checker) importPackage(pos syntax.Pos, path string, dir string) *Package
inNode
function
#
inNode is a dummy function returning pos.
func inNode(_ syntax.Node, pos syntax.Pos) syntax.Pos
includes
method
#
includes reports whether t ∈ xl.
func (xl termlist) includes(t Type) bool
includes
method
#
includes reports whether t ∈ x.
func (x *term) includes(t Type) bool
incomparableCause
method
#
incomparableCause returns a more specific cause why typ is not comparable.
If there is no more specific cause, the result is "".
func (check *Checker) incomparableCause(typ Type) string
index
method
#
index checks an index expression for validity.
If max >= 0, it is the upper bound for index.
If the result typ is != Typ[Invalid], index is valid and typ is its (possibly named) integer type.
If the result val >= 0, index is valid and val is its constant int value.
func (check *Checker) index(index syntax.Expr, max int64) (typ Type, val int64)
indexExpr
method
#
If e is a valid function instantiation, indexExpr returns true.
In that case x represents the uninstantiated function value and
it is the caller's responsibility to instantiate the function.
func (check *Checker) indexExpr(x *operand, e *syntax.IndexExpr) (isFuncInst bool)
indexedElts
method
#
indexedElts checks the elements (elts) of an array or slice composite literal
against the literal's element type (typ), and the element indices against
the literal length if known (length >= 0). It returns the length of the
literal (maximum index value + 1).
func (check *Checker) indexedElts(elts []syntax.Expr, typ Type, length int64) int64
infer
method
#
infer attempts to infer the complete set of type arguments for generic function instantiation/call
based on the given type parameters tparams, type arguments targs, function parameters params, and
function arguments args, if any. There must be at least one type parameter, no more type arguments
than type parameters, and params and args must match in number (incl. zero).
If reverse is set, an error message's contents are reversed for a better error message for some
errors related to reverse type inference (where the function call is synthetic).
If successful, infer returns the complete list of given and inferred type arguments, one for each
type parameter. Otherwise the result is nil. Errors are reported through the err parameter.
Note: infer may fail (return nil) due to invalid args operands without reporting additional errors.
func (check *Checker) infer(pos syntax.Pos, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand, reverse bool, err *error_) (inferred []Type)
inferred
method
#
inferred returns the list of inferred types for the given type parameter list.
The result is never nil and has the same length as tparams; result types that
could not be inferred are nil. Corresponding type parameters and result types
have identical indices.
func (u *unifier) inferred(tparams []*TypeParam) []Type
init
function
#
func init()
init
function
#
func init()
init
function
#
func init()
initConst
method
#
func (check *Checker) initConst(lhs *Const, x *operand)
initFiles
method
#
initFiles initializes the files-specific portion of checker.
The provided files must all belong to the same package.
func (check *Checker) initFiles(files []*syntax.File)
initOrder
method
#
initOrder computes the Info.InitOrder for package variables.
func (check *Checker) initOrder()
initVar
method
#
initVar checks the initialization lhs = x in a variable declaration.
If lhs doesn't have a type yet, it is given the type of x,
or Typ[Invalid] in case of an error.
If the initialization check fails, x.mode is set to invalid.
func (check *Checker) initVar(lhs *Var, x *operand, context string)
initVars
method
#
initVars type-checks assignments of initialization expressions orig_rhs
to variables lhs.
If returnStmt is non-nil, initVars type-checks the implicit assignment
of result expressions orig_rhs to function result parameters lhs.
func (check *Checker) initVars(lhs []*Var, orig_rhs []syntax.Expr, returnStmt syntax.Stmt)
insert
method
#
insert attempts to insert an object obj into objset s.
If s already contains an alternative object alt with
the same name, insert leaves s unchanged and returns alt.
Otherwise it inserts obj and returns nil.
func (s *objset) insert(obj Object) Object
insert
method
#
func (s *Scope) insert(name string, obj Object)
insert
method
#
insert records a new label declaration for the current block.
The label must not have been declared before in any block.
func (b *block) insert(s *syntax.LabeledStmt)
instance
method
#
instance instantiates the given original (generic) function or type with the
provided type arguments and returns the resulting instance. If an identical
instance exists already in the given contexts, it returns that instance,
otherwise it creates a new one. If there is an error (such as wrong number
of type arguments), the result is Typ[Invalid].
If expanding is non-nil, it is the Named instance type currently being
expanded. If ctxt is non-nil, it is the context associated with the current
type-checking pass or call to Instantiate. At least one of expanding or ctxt
must be non-nil.
For Named types the resulting instance may be unexpanded.
check may be nil (when not type-checking syntax); pos is used only only if check is non-nil.
func (check *Checker) instance(pos syntax.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type)
instanceHash
method
#
instanceHash returns a string representation of typ instantiated with targs.
The hash should be a perfect hash, though out of caution the type checker
does not assume this. The result is guaranteed to not contain blanks.
func (ctxt *Context) instanceHash(orig Type, targs []Type) string
instantiateSignature
method
#
func (check *Checker) instantiateSignature(pos syntax.Pos, expr syntax.Expr, typ *Signature, targs []Type, xlist []syntax.Expr) (res *Signature)
instantiatedIdent
function
#
instantiatedIdent determines the identifier of the type instantiated in expr.
Helper function for recordInstance in recording.go.
func instantiatedIdent(expr syntax.Expr) *syntax.Name
instantiatedType
method
#
func (check *Checker) instantiatedType(x syntax.Expr, xlist []syntax.Expr, def *TypeName) (res Type)
interfacePtrError
method
#
check may be nil.
func (check *Checker) interfacePtrError(T Type) string
interfaceType
method
#
func (check *Checker) interfaceType(ityp *Interface, iface *syntax.InterfaceType, def *TypeName)
intersect
method
#
intersect returns the intersection xl ∩ yl.
func (xl termlist) intersect(yl termlist) termlist
intersect
method
#
intersect returns the intersection x ∩ y.
func (x *term) intersect(y *term) *term
intersectTermLists
function
#
intersectTermLists computes the intersection of two term lists and respective comparable bits.
xcomp, ycomp are valid only if xterms.isAll() and yterms.isAll() respectively.
func intersectTermLists(xterms termlist, xcomp bool, yterms termlist, ycomp bool) (termlist, bool)
invalidConversion
method
#
func (check *Checker) invalidConversion(code Code, x *operand, target Type)
is
method
#
is calls f with the specific type terms of t's constraint and reports whether
all calls to f returned true. If there are no specific terms, is
returns the result of f(nil).
func (t *TypeParam) is(f func(*term) bool) bool
is
method
#
is calls f with the specific type terms of s and reports whether
all calls to f returned true. If there are no specific terms, is
returns the result of f(nil).
func (s *_TypeSet) is(f func(*term) bool) bool
isAll
method
#
isAll reports whether the termlist xl represents the set of all types.
func (xl termlist) isAll() bool
isBasic
function
#
isBasic reports whether under(t) is a basic type with the specified info.
If t is a type parameter the result is false; i.e.,
isBasic does not look inside a type parameter.
func isBasic(t Type, info BasicInfo) bool
isBoolean
function
#
func isBoolean(t Type) bool
isBrokenAlias
method
#
isBrokenAlias reports whether alias doesn't have a determined type yet.
func (check *Checker) isBrokenAlias(alias *TypeName) bool
isBytesOrRunes
function
#
func isBytesOrRunes(typ Type) bool
isCGoTypeObj
function
#
isCGoTypeObj reports whether the given type name was created by cgo.
func isCGoTypeObj(obj *TypeName) bool
isComparison
function
#
func isComparison(op syntax.Operator) bool
isComplex
function
#
func isComplex(t Type) bool
isConstType
function
#
func isConstType(t Type) bool
isDependency
method
#
func (*Func) isDependency()
isDependency
method
#
func (*Var) isDependency()
isDependency
method
#
func (*Const) isDependency()
isEmpty
method
#
isEmpty reports whether the termlist xl represents the empty set of types.
func (xl termlist) isEmpty() bool
isExported
function
#
func isExported(name string) bool
isFloat
function
#
func isFloat(t Type) bool
isGeneric
function
#
isGeneric reports whether a type is a generic, uninstantiated type
(generic signatures are not included).
TODO(gri) should we include signatures or assert that they are not present?
func isGeneric(t Type) bool
isImportedConstraint
method
#
isImportedConstraint reports whether typ is an imported type constraint.
func (check *Checker) isImportedConstraint(typ Type) bool
isInteger
function
#
func isInteger(t Type) bool
isIntegerOrFloat
function
#
func isIntegerOrFloat(t Type) bool
isInterfacePtr
function
#
func isInterfacePtr(T Type) bool
isNil
method
#
isNil reports whether x is the (untyped) nil value.
func (x *operand) isNil() bool
isNil
method
#
isNil reports whether the expression e denotes the predeclared value nil.
func (check *Checker) isNil(e syntax.Expr) bool
isNonTypeParamInterface
function
#
isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
func isNonTypeParamInterface(t Type) bool
isNumeric
function
#
func isNumeric(t Type) bool
isParameterized
function
#
isParameterized reports whether typ contains any of the type parameters of tparams.
If typ is a generic function, isParameterized ignores the type parameter declarations;
it only considers the signature proper (incoming and result parameters).
func isParameterized(tparams []*TypeParam, typ Type) bool
isParameterized
method
#
func (w *tpWalker) isParameterized(typ Type) (res bool)
isPointer
function
#
func isPointer(typ Type) bool
isShift
function
#
func isShift(op syntax.Operator) bool
isString
function
#
func isString(t Type) bool
isTerminating
method
#
isTerminating reports if s is a terminating statement.
If s is labeled, label is the label name; otherwise s
is "".
func (check *Checker) isTerminating(s syntax.Stmt, label string) bool
isTerminatingList
method
#
func (check *Checker) isTerminatingList(list []syntax.Stmt, label string) bool
isTerminatingSwitch
method
#
func (check *Checker) isTerminatingSwitch(body []*syntax.CaseClause, label string) bool
isTypeLit
function
#
isTypeLit reports whether t is a type literal.
This includes all non-defined types, but also basic types.
isTypeLit may be called with types that are not fully set up.
func isTypeLit(t Type) bool
isTypeParam
function
#
isTypeParam reports whether t is a type parameter.
func isTypeParam(t Type) bool
isTyped
function
#
isTyped reports whether t is typed; i.e., not an untyped
constant or boolean.
Safe to call from types that are not fully set up.
func isTyped(t Type) bool
isUintptr
function
#
func isUintptr(typ Type) bool
isUnsafePointer
function
#
func isUnsafePointer(typ Type) bool
isUnsigned
function
#
func isUnsigned(t Type) bool
isUntyped
function
#
isUntyped(t) is the same as !isTyped(t).
Safe to call from types that are not fully set up.
func isUntyped(t Type) bool
isUntypedNumeric
function
#
isUntypedNumeric reports whether t is an untyped numeric type.
Safe to call from types that are not fully set up.
func isUntypedNumeric(t Type) bool
isValid
function
#
isValid reports whether t is a valid type.
func isValid(t Type) bool
isValid
method
#
isValid reports whether v is a valid Go version.
func (v goVersion) isValid() bool
isValidIndex
method
#
isValidIndex checks whether operand x satisfies the criteria for integer
index values. If allowNegative is set, a constant operand may be negative.
If the operand is not valid, an error is reported (using what as context)
and the result is false.
func (check *Checker) isValidIndex(x *operand, code Code, what string, allowNegative bool) bool
isValidName
function
#
isValidName reports whether s is a valid Go identifier.
func isValidName(s string) bool
isdddArray
function
#
isdddArray reports whether atyp is of the form [...]E.
func isdddArray(atyp *syntax.ArrayType) bool
join
method
#
join unifies the given type parameters x and y.
If both type parameters already have a type associated with them
and they are not joined, join fails and returns false.
func (u *unifier) join(x *TypeParam, y *TypeParam) bool
keyVal
function
#
keyVal maps a complex, float, integer, string or boolean constant value
to the corresponding complex128, float64, int64, uint64, string, or bool
Go value if possible; otherwise it returns x.
A complex constant that can be represented as a float (such as 1.2 + 0i)
is returned as a floating point value; if a floating point value can be
represented as an integer (such as 1.0) it is returned as an integer value.
This ensures that constants of different kind but equal value (such as
1.0 + 0i, 1.0, 1) result in the same value.
func keyVal(x constant.Value) interface{}
killCycles
function
#
killCycles walks through the given type parameters and looks for cycles
created by type parameters whose inferred types refer back to that type
parameter, either directly or indirectly. If such a cycle is detected,
it is killed by setting the corresponding inferred type to nil.
TODO(gri) Determine if we can simply abort inference as soon as we have
found a single cycle.
func killCycles(tparams []*TypeParam, inferred []Type)
labels
method
#
labels checks correct label use in body.
func (check *Checker) labels(body *syntax.BlockStmt)
langCompat
method
#
langCompat reports an error if the representation of a numeric
literal is not compatible with the current language version.
func (check *Checker) langCompat(lit *syntax.BasicLit)
later
method
#
later pushes f on to the stack of actions that will be processed later;
either at the end of the current statement, or in case of a local constant
or variable declaration, before the constant or variable is in scope
(so that f still sees the scope before any new declarations).
later returns the pushed action so one can provide a description
via action.describef for debugging, if desired.
func (check *Checker) later(f func()) *action
lhsVar
method
#
lhsVar checks a lhs variable in an assignment and returns its type.
lhsVar takes care of not counting a lhs identifier as a "use" of
that identifier. The result is nil if it is the blank identifier,
and Typ[Invalid] if it is an invalid lhs expression.
func (check *Checker) lhsVar(lhs syntax.Expr) Type
list
method
#
list is for internal use where we expect a []*TypeParam.
TODO(rfindley): list should probably be eliminated: we can pass around a
TypeParamList instead.
func (l *TypeParamList) list() []*TypeParam
list
method
#
list is for internal use where we expect a []Type.
TODO(rfindley): list should probably be eliminated: we can pass around a
TypeList instead.
func (l *TypeList) list() []Type
localNamedVertex
method
#
localNamedVertex returns the index of the vertex representing
named, or -1 if named doesn't need representation.
func (w *monoGraph) localNamedVertex(pkg *Package, named *Named) int
lookup
method
#
func (l *instanceLookup) lookup(inst *Named) *Named
lookup
method
#
lookup is like lookupScope but it only returns the object (or nil).
func (env *environment) lookup(name string) Object
lookup
method
#
func (m substMap) lookup(tpar *TypeParam) Type
lookup
method
#
lookup returns an existing instantiation of orig with targs, if it exists.
Otherwise, it returns nil.
func (ctxt *Context) lookup(h string, orig Type, targs []Type) Type
lookupError
method
#
lookupError returns a case-specific error when a lookup of selector sel in the
given type fails but an object with alternative spelling (case folding) is found.
If structLit is set, the error message is specifically for struct literal fields.
func (check *Checker) lookupError(typ Type, sel string, obj Object, structLit bool) string
lookupFieldOrMethod
function
#
lookupFieldOrMethod is like LookupFieldOrMethod but with the additional foldCase parameter
(see Object.sameId for the meaning of foldCase).
func lookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool)
lookupFieldOrMethodImpl
function
#
lookupFieldOrMethodImpl is the implementation of lookupFieldOrMethod.
Notably, in contrast to lookupFieldOrMethod, it won't find struct fields
in base types of defined (*Named) pointer types T. For instance, given
the declaration:
type T *struct{f int}
lookupFieldOrMethodImpl won't find the field f in the defined (*Named) type T
(methods on T are not permitted in the first place).
Thus, lookupFieldOrMethodImpl should only be called by lookupFieldOrMethod
and missingMethod (the latter doesn't care about struct fields).
The resulting object may not be fully type-checked.
func lookupFieldOrMethodImpl(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool)
lookupMethod
method
#
func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func)
lookupScope
method
#
lookupScope looks up name in the current environment and if an object
is found it returns the scope containing the object and the object.
Otherwise it returns (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 Scope.Insert). This can only happen for dot-imported objects
whose parent is the scope of the package that exported them.
func (env *environment) lookupScope(name string) (*Scope, Object)
lookupType
function
#
func lookupType(m map[Type]int, typ Type) (int, bool)
makeFromLiteral
function
#
makeFromLiteral returns the constant value for the given literal string and kind.
func makeFromLiteral(lit string, kind syntax.LitKind) constant.Value
makeObjList
function
#
makeObjList returns the list of type name objects for the given
list of named types.
func makeObjList(tlist []*Named) []Object
makeRenameMap
function
#
makeRenameMap is like makeSubstMap, but creates a map used to rename type
parameters in from with the type parameters in to.
func makeRenameMap(from []*TypeParam, to []*TypeParam) substMap
makeSig
function
#
makeSig makes a signature for the given argument and result types.
Default types are used for untyped arguments, and res may be nil.
func makeSig(res Type, args ...Type) *Signature
makeSubstMap
function
#
makeSubstMap creates a new substitution map mapping tpars[i] to targs[i].
If targs[i] is nil, tpars[i] is not substituted.
func makeSubstMap(tpars []*TypeParam, targs []Type) substMap
markComplete
method
#
func (s *Struct) markComplete()
markImports
method
#
markImports recursively walks pkg and its imports, to record unique import
paths in pkgPathMap.
func (check *Checker) markImports(pkg *Package)
match
function
#
If x and y are identical, match returns x.
If x and y are identical channels but for their direction
and one of them is unrestricted, match returns the channel
with the restricted direction.
In all other cases, match returns nil.
func match(x Type, y Type) Type
matchTypes
method
#
matchTypes attempts to convert any untyped types x and y such that they match.
If an error occurs, x.mode is set to invalid.
func (check *Checker) matchTypes(x *operand, y *operand)
maxType
function
#
maxType returns the "largest" type that encompasses both x and y.
If x and y are different untyped numeric types, the result is the type of x or y
that appears later in this list: integer, rune, floating-point, complex.
Otherwise, if x != y, the result is nil.
func maxType(x Type, y Type) Type
measure
function
#
func measure(x int, unit string) string
mentions
function
#
mentions reports whether type T "mentions" typ in an (embedded) element or term
of T (whether typ is in the type set of T or not). For better error messages.
func mentions(T Type, typ Type) bool
methodIndex
method
#
methodIndex returns the index of the method with the given name.
If foldCase is set, capitalization in the name is ignored.
The result is negative if no such method exists.
func (t *Named) methodIndex(name string, foldCase bool) int
methodIndex
function
#
methodIndex returns the index of and method with matching package and name, or (-1, nil).
See Object.sameId for the meaning of foldCase.
func methodIndex(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func)
missingMethod
method
#
missingMethod is like MissingMethod but accepts a *Checker as receiver,
a comparator equivalent for type comparison, and a *string for error causes.
The receiver may be nil if missingMethod is invoked through an exported
API call (such as MissingMethod), i.e., when all methods have been type-
checked.
The underlying type of T must be an interface; T (rather than its under-
lying type) is used for better error messages (reported through *cause).
The comparator is used to compare signatures.
If a method is missing and cause is not nil, *cause describes the error.
func (check *Checker) missingMethod(V Type, T Type, static bool, equivalent func(x Type, y Type) bool, cause *string) (method *Func, wrongType bool)
monomorph
method
#
func (check *Checker) monomorph()
msg
method
#
msg returns the formatted error message without the primary error position pos().
func (err *error_) msg() string
multiExpr
method
#
multiExpr typechecks e and returns its value (or values) in list.
If allowCommaOk is set and e is a map index, comma-ok, or comma-err
expression, the result is a two-element list containing the value
of e, and an untyped bool value or an error value, respectively.
If an error occurred, list[0] is not valid.
func (check *Checker) multiExpr(e syntax.Expr, allowCommaOk bool) (list []*operand, commaOk bool)
multipleSelectDefaults
method
#
func (check *Checker) multipleSelectDefaults(list []*syntax.CommClause)
multipleSwitchDefaults
method
#
func (check *Checker) multipleSwitchDefaults(list []*syntax.CaseClause)
needsCleanup
method
#
needsCleanup records objects/types that implement the cleanup method
which will be called at the end of type-checking.
func (check *Checker) needsCleanup(c cleaner)
newAlias
method
#
newAlias creates a new Alias type with the given type name and rhs.
rhs must not be nil.
func (check *Checker) newAlias(obj *TypeName, rhs Type) *Alias
newAliasInstance
method
#
newAliasInstance creates a new alias instance for the given origin and type
arguments, recording pos as the position of its synthetic object (for error
reporting).
func (check *Checker) newAliasInstance(pos syntax.Pos, orig *Alias, targs []Type, expanding *Named, ctxt *Context) *Alias
newAssertableTo
method
#
newAssertableTo reports whether a value of type V can be asserted to have type T.
It also implements behavior for interfaces that currently are only permitted
in constraint position (we have not yet defined that behavior in the spec).
The underlying type of V must be an interface.
If the result is false and cause is not nil, *cause is set to the error cause.
func (check *Checker) newAssertableTo(V Type, T Type, cause *string) bool
newBuiltin
function
#
func newBuiltin(id builtinId) *Builtin
newError
method
#
newError returns a new error_ with the given error code.
func (check *Checker) newError(code Code) *error_
newInterface
method
#
check may be nil
func (check *Checker) newInterface() *Interface
newNamed
method
#
newNamed is like NewNamed but with a *Checker receiver.
func (check *Checker) newNamed(obj *TypeName, underlying Type, methods []*Func) *Named
newNamedInstance
method
#
newNamedInstance creates a new named instance for the given origin and type
arguments, recording pos as the position of its synthetic object (for error
reporting).
If set, expanding is the named type instance currently being expanded, that
led to the creation of this instance.
func (check *Checker) newNamedInstance(pos syntax.Pos, orig *Named, targs []Type, expanding *Named) *Named
newTarget
function
#
newTarget creates a new target for the given type and description.
The result is nil if typ is not a signature.
func newTarget(typ Type, desc string) *target
newTypeHasher
function
#
func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter
newTypeList
function
#
newTypeList returns a new TypeList with the types in list.
func newTypeList(list []Type) *TypeList
newTypeParam
method
#
check may be nil
func (check *Checker) newTypeParam(obj *TypeName, constraint Type) *TypeParam
newTypeWriter
function
#
func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter
newUnifier
function
#
newUnifier returns a new unifier initialized with the given type parameter
and corresponding type argument lists. The type argument list may be shorter
than the type parameter list, and it may contain nil types. Matching type
parameters and arguments must have the same index.
func newUnifier(tparams []*TypeParam, targs []Type, enableInterfaceInference bool) *unifier
nextID
function
#
nextID returns a value increasing monotonically by 1 with
each call, starting with 1. It may be called concurrently.
func nextID() uint64
nify
method
#
nify implements the core unification algorithm which is an
adapted version of Checker.identical. For changes to that
code the corresponding changes should be made here.
Must not be called directly from outside the unifier.
func (u *unifier) nify(x Type, y Type, mode unifyMode, p *ifacePair) (result bool)
nonGeneric
method
#
If x is a generic type, or a generic function whose type arguments cannot be inferred
from a non-nil target T, nonGeneric reports an error and invalidates x.mode and x.typ.
Otherwise it leaves x alone.
func (check *Checker) nonGeneric(T *target, x *operand)
norm
method
#
norm returns the normal form of xl.
func (xl termlist) norm() termlist
objDecl
method
#
objDecl type-checks the declaration of obj in its respective (file) environment.
For the meaning of def, see Checker.definedType, in typexpr.go.
func (check *Checker) objDecl(obj Object, def *TypeName)
offsetof
method
#
offsetof returns the offset of the field specified via
the index sequence relative to T. All embedded fields
must be structs (rather than pointers to structs).
If the offset is too large (because T is too large),
the result is negative.
func (conf *Config) offsetof(T Type, index []int) int64
offsetsof
method
#
func (conf *Config) offsetsof(T *Struct) []int64
op
method
#
func (check *Checker) op(m opPredicates, x *operand, op syntax.Operator) bool
opName
function
#
opName returns the name of the operation if x is an operation
that might overflow; otherwise it returns the empty string.
func opName(x syntax.Expr) string
opPos
function
#
opPos returns the position of the operator if x is an operation;
otherwise it returns the start position of x.
func opPos(x syntax.Expr) syntax.Pos
openScope
method
#
func (check *Checker) openScope(node syntax.Node, comment string)
operandString
function
#
Operand string formats
(not all "untyped" cases can appear due to the type system,
but they fall out naturally here)
mode format
invalid ( )
novalue ( )
builtin ( )
typexpr ( )
constant ( )
constant ( of type )
constant ( )
constant ( of type )
variable ( )
variable ( of type )
mapindex ( )
mapindex ( of type )
value ( )
value ( of type )
nilvalue untyped nil
nilvalue nil ( of type )
commaok ( )
commaok ( of type )
commaerr ( )
commaerr ( of type )
cgofunc ( )
cgofunc ( of type )
func operandString(x *operand, qf Qualifier) string
operandTypes
function
#
operandTypes returns the list of types for the given operands.
func operandTypes(list []*operand) (res []Type)
order
method
#
func (*lazyObject) order() uint32
order
method
#
func (obj *object) order() uint32
overflow
method
#
overflow checks that the constant x is representable by its type.
For untyped constants, it checks that the value doesn't become
arbitrarily large.
func (check *Checker) overflow(x *operand, opPos syntax.Pos)
overlappingTerm
function
#
overlappingTerm reports the index of the term x in terms which is
overlapping (not disjoint) from y. The result is < 0 if there is no
such term. The type of term y must not be an interface, and terms
with an interface type are ignored in the terms list.
func overlappingTerm(terms []*Term, y *Term) int
packageObjects
method
#
packageObjects typechecks all package objects, but not function bodies.
func (check *Checker) packageObjects()
packagePrefix
function
#
func packagePrefix(pkg *Package, qf Qualifier) string
parseTilde
function
#
func parseTilde(check *Checker, tx syntax.Expr) *Term
parseUnion
function
#
parseUnion parses uexpr as a union of expressions.
The result is a Union type, or Typ[Invalid] for some errors.
func parseUnion(check *Checker, uexpr syntax.Expr) Type
pathString
function
#
pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
func pathString(path []Object) string
pop
method
#
pop pops and returns the topmost object from the object path.
func (check *Checker) pop() Object
pos
method
#
func (err *error_) pos() syntax.Pos
processDelayed
method
#
processDelayed processes all delayed actions pushed after top.
func (check *Checker) processDelayed(top int)
ptrBase
function
#
func ptrBase(x *syntax.Operation) syntax.Expr
push
method
#
push pushes obj onto the object path and returns its index in the path.
func (check *Checker) push(obj Object) int
qualifier
method
#
func (check *Checker) qualifier(pkg *Package) string
rangeKeyVal
function
#
rangeKeyVal returns the key and value type produced by a range clause
over an expression of type typ.
If allowVersion != nil, it is used to check the required language version.
If the range clause is not permitted, rangeKeyVal returns ok = false.
When ok = false, rangeKeyVal may also return a reason in cause.
func rangeKeyVal(typ Type, allowVersion func(goVersion) bool) (key Type, val Type, cause string, ok bool)
rangeStmt
method
#
func (check *Checker) rangeStmt(inner stmtContext, s *syntax.ForStmt, rclause *syntax.RangeClause)
rawExpr
method
#
rawExpr typechecks expression e and initializes x with the expression
value or type. If an error occurred, x.mode is set to invalid.
If a non-nil target T is given and e is a generic function,
T is used to infer the type arguments for e.
If hint != nil, it is the type of a composite literal element.
If allowGeneric is set, the operand type may be an uninstantiated
parameterized type or function value.
func (check *Checker) rawExpr(T *target, x *operand, e syntax.Expr, hint Type, allowGeneric bool) exprKind
record
method
#
func (check *Checker) record(x *operand)
recordBuiltinType
method
#
func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature)
recordCanon
method
#
recordCanon records that tpar is the canonical type parameter
corresponding to method type parameter mpar.
func (w *monoGraph) recordCanon(mpar *TypeParam, tpar *TypeParam)
recordCommaOkTypes
method
#
recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
(and therefore has tuple type).
func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand)
recordCommaOkTypesInSyntax
method
#
types2-specific support for recording type information in the syntax tree.
func (check *Checker) recordCommaOkTypesInSyntax(x syntax.Expr, t0 Type, t1 Type)
recordDef
method
#
func (check *Checker) recordDef(id *syntax.Name, obj Object)
recordImplicit
method
#
func (check *Checker) recordImplicit(node syntax.Node, obj Object)
recordInstance
method
#
recordInstance records instantiation information into check.Info, if the
Instances map is non-nil. The given expr must be an ident, selector, or
index (list) expr with ident or selector operand.
TODO(rfindley): the expr parameter is fragile. See if we can access the
instantiated identifier in some other way.
func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type)
recordInstance
method
#
recordInstance records that the given type parameters were
instantiated with the corresponding type arguments.
func (w *monoGraph) recordInstance(pkg *Package, pos syntax.Pos, tparams []*TypeParam, targs []Type, xlist []syntax.Expr)
recordParenthesizedRecvTypes
method
#
recordParenthesizedRecvTypes records parenthesized intermediate receiver type
expressions that all map to the same type, by recursively unpacking expr and
recording the corresponding type for it. Example:
expression --> type
----------------------
(*(T[P])) *T[P]
*(T[P]) *T[P]
(T[P]) T[P]
T[P] T[P]
func (check *Checker) recordParenthesizedRecvTypes(expr syntax.Expr, typ Type)
recordScope
method
#
func (check *Checker) recordScope(node syntax.Node, scope *Scope)
recordSelection
method
#
func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool)
recordTypeAndValue
method
#
func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value)
recordTypeAndValueInSyntax
method
#
types2-specific support for recording type information in the syntax tree.
func (check *Checker) recordTypeAndValueInSyntax(x syntax.Expr, mode operandMode, typ Type, val constant.Value)
recordTypes
method
#
func (info *Info) recordTypes() bool
recordUntyped
method
#
func (check *Checker) recordUntyped()
recordUse
method
#
func (check *Checker) recordUse(id *syntax.Name, obj Object)
rememberUntyped
method
#
func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value)
renameTParams
method
#
renameTParams renames the type parameters in the given type such that each type
parameter is given a new identity. renameTParams returns the new type parameters
and updated type. If the result type is unchanged from the argument type, none
of the type parameters in tparams occurred in the type.
If typ is a generic function, type parameters held with typ are not changed and
must be updated separately if desired.
The positions is only used for debug traces.
func (check *Checker) renameTParams(pos syntax.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type)
replaceRecvType
function
#
replaceRecvType updates any function receivers that have type old to have
type new. It does not modify the input slice; if modifications are required,
the input slice and any affected signatures will be copied before mutating.
The resulting out slice contains the updated functions, and copied reports
if anything was modified.
func replaceRecvType(in []*Func, old Type, new Type) (out []*Func, copied bool)
report
method
#
report reports the error err, setting check.firstError if necessary.
func (err *error_) report()
reportCycle
method
#
reportCycle reports an error for the given cycle.
func (check *Checker) reportCycle(cycle []Object)
reportInstanceLoop
method
#
func (check *Checker) reportInstanceLoop(v int)
representable
method
#
representable checks that a constant operand is representable in the given
basic type.
func (check *Checker) representable(x *operand, typ *Basic)
representableConst
function
#
representableConst reports whether x can be represented as
value of the given basic type and for the configuration
provided (only needed for int/uint sizes).
If rounded != nil, *rounded is set to the rounded value of x for
representable floating-point and complex values, and to an Int
value for integer values; it is left alone otherwise.
It is ok to provide the addressof the first argument for rounded.
The check parameter may be nil if representableConst is invoked
(indirectly) through an exported API call (AssignableTo, ConvertibleTo)
because we don't need the Checker's config for those calls.
func representableConst(x constant.Value, check *Checker, typ *Basic, rounded *constant.Value) bool
representation
method
#
representation returns the representation of the constant operand x as the
basic type typ.
If no such representation is possible, it returns a non-zero error code.
func (check *Checker) representation(x *operand, typ *Basic) (constant.Value, Code)
resolve
function
#
resolve returns the Object represented by obj, resolving lazy
objects as appropriate.
func resolve(name string, obj Object) Object
resolve
method
#
resolve resolves the type parameters, methods, and underlying type of n.
This information may be loaded from a provided loader function, or computed
from an origin type (in the case of instances).
After resolution, the type parameters, methods, and underlying type of n are
accessible; but if n is an instantiated type, its methods may still be
unexpanded.
func (n *Named) resolve() *Named
resolveBaseTypeName
method
#
resolveBaseTypeName returns the non-alias base type name for the given name, and whether
there was a pointer indirection to get to it. The base type name must be declared
in package scope, and there can be at most one pointer indirection. Traversals
through generic alias types are not permitted. If no such type name exists, the
returned base is nil.
func (check *Checker) resolveBaseTypeName(ptr bool, name *syntax.Name) (ptr_ bool, base *TypeName)
returnError
method
#
func (check *Checker) returnError(at poser, lhs []*Var, rhs []*operand)
roundFloat32
function
#
func roundFloat32(x constant.Value) constant.Value
roundFloat64
function
#
func roundFloat64(x constant.Value) constant.Value
safeUnderlying
function
#
safeUnderlying returns the underlying type of typ without expanding
instances, to avoid infinite recursion.
TODO(rfindley): eliminate this function or give it a better name.
func safeUnderlying(typ Type) Type
sameId
method
#
func (obj *object) sameId(pkg *Package, name string, foldCase bool) bool
sameId
method
#
func (*lazyObject) sameId(*Package, string, bool) bool
samePkg
function
#
samePkg reports whether packages a and b are the same.
func samePkg(a *Package, b *Package) bool
scopePos
method
#
func (obj *object) scopePos() syntax.Pos
scopePos
method
#
func (*lazyObject) scopePos() syntax.Pos
selector
method
#
func (check *Checker) selector(x *operand, e *syntax.SelectorExpr, def *TypeName, wantType bool)
set
method
#
set sets the type t for type parameter x;
t must not be nil.
func (u *unifier) set(x *TypeParam, t Type)
setColor
method
#
func (obj *object) setColor(color color)
setColor
method
#
func (*lazyObject) setColor(color color)
setConst
method
#
setConst sets x to the untyped constant for literal lit.
func (x *operand) setConst(k syntax.LitKind, lit string)
setDefType
function
#
func setDefType(def *TypeName, typ Type)
setHandle
method
#
setHandle sets the handle for type parameter x
(and all its joined type parameters) to h.
func (u *unifier) setHandle(x *TypeParam, h *Type)
setOrder
method
#
func (*lazyObject) setOrder(uint32)
setOrder
method
#
func (obj *object) setOrder(order uint32)
setParent
method
#
func (obj *object) setParent(parent *Scope)
setParent
method
#
func (*lazyObject) setParent(*Scope)
setScopePos
method
#
func (obj *object) setScopePos(pos syntax.Pos)
setScopePos
method
#
func (*lazyObject) setScopePos(syntax.Pos)
setState
method
#
setState atomically stores the given state for n.
Must only be called while holding n.mu.
func (n *Named) setState(state namedState)
setType
method
#
func (obj *object) setType(typ Type)
setType
method
#
func (*lazyObject) setType(Type)
shift
method
#
If e != nil, it must be the shift expression; it may be nil for non-constant shifts.
func (check *Checker) shift(x *operand, y *operand, e syntax.Expr, op syntax.Operator)
shortVarDecl
method
#
func (check *Checker) shortVarDecl(pos poser, lhs []syntax.Expr, rhs []syntax.Expr)
signature
method
#
func (w *typeWriter) signature(sig *Signature)
simpleStmt
method
#
func (check *Checker) simpleStmt(s syntax.Stmt)
singleIndex
method
#
singleIndex returns the (single) index from the index expression e.
If the index is missing, or if there are multiple indices, an error
is reported and the result is nil.
func (check *Checker) singleIndex(e *syntax.IndexExpr) syntax.Expr
singleValue
method
#
singleValue reports an error if x describes a tuple and sets x.mode to invalid.
func (check *Checker) singleValue(x *operand)
sizeof
method
#
sizeof returns the size of T.
If T is too large, the result is negative.
func (conf *Config) sizeof(T Type) int64
sliceExpr
method
#
func (check *Checker) sliceExpr(x *operand, e *syntax.SliceExpr)
softErrorf
method
#
func (check *Checker) softErrorf(at poser, code Code, format string, args ...any)
sortMethods
function
#
func sortMethods(list []*Func)
sprintf
method
#
check may be nil.
func (check *Checker) sprintf(format string, args ...any) string
sprintf
function
#
func sprintf(qf Qualifier, tpSubscripts bool, format string, args ...any) string
srcimporter_setUsesCgo
function
#
func srcimporter_setUsesCgo(conf *Config)
startPos
function
#
startPos returns the start position of node n.
func startPos(n syntax.Node) syntax.Pos
state
method
#
state atomically accesses the current state of the receiver.
func (n *Named) state() namedState
stmt
method
#
stmt typechecks statement s.
func (check *Checker) stmt(ctxt stmtContext, s syntax.Stmt)
stmtList
method
#
func (check *Checker) stmtList(ctxt stmtContext, list []syntax.Stmt)
string
method
#
func (w *typeWriter) string(s string)
stripAnnotations
function
#
stripAnnotations removes internal (type) annotations from s.
func stripAnnotations(s string) string
structType
method
#
func (check *Checker) structType(styp *Struct, e *syntax.StructType)
subscript
function
#
subscript returns the decimal (utf8) representation of x using subscript digits.
func subscript(x uint64) string
subsetOf
method
#
subsetOf reports whether x ⊆ y.
func (x *term) subsetOf(y *term) bool
subsetOf
method
#
subsetOf reports whether xl ⊆ yl.
func (xl termlist) subsetOf(yl termlist) bool
subsetOf
method
#
subsetOf reports whether s1 ⊆ s2.
func (s1 *_TypeSet) subsetOf(s2 *_TypeSet) bool
subst
method
#
subst returns the type typ with its type parameters tpars replaced by the
corresponding type arguments targs, recursively. subst doesn't modify the
incoming type. If a substitution took place, the result type is different
from the incoming type.
If expanding is non-nil, it is the instance type currently being expanded.
One of expanding or ctxt must be non-nil.
func (check *Checker) subst(pos syntax.Pos, typ Type, smap substMap, expanding *Named, ctxt *Context) Type
substList
function
#
substList applies subst to each element of the incoming slice.
If at least one element changes, the result is a new slice with
all the (possibly updated) elements of the incoming slice;
otherwise the result it nil. The incoming slice is unchanged.
func substList(in []T, subst func(T) T) (out []T)
supersetOf
method
#
supersetOf reports whether y ⊆ xl.
func (xl termlist) supersetOf(y *term) bool
suspendedCall
method
#
func (check *Checker) suspendedCall(keyword string, call syntax.Expr)
switchStmt
method
#
func (check *Checker) switchStmt(inner stmtContext, s *syntax.SwitchStmt)
tParamList
method
#
func (w *typeWriter) tParamList(list []*TypeParam)
tag
method
#
func (check *Checker) tag(t *syntax.BasicLit) string
tail
function
#
tail returns the string s without its first (UTF-8) character.
If len(s) == 0, the result is s.
func tail(s string) string
term
method
#
func (subst *subster) term(t *Term) *Term
trace
method
#
func (check *Checker) trace(pos syntax.Pos, format string, args ...any)
tracef
method
#
func (u *unifier) tracef(format string, args ...interface{})
trimTrailingEmptyStmts
function
#
func trimTrailingEmptyStmts(list []syntax.Stmt) []syntax.Stmt
tuple
method
#
func (subst *subster) tuple(t *Tuple) *Tuple
tuple
method
#
func (w *typeWriter) tuple(tup *Tuple, variadic bool)
typ
method
#
func (subst *subster) typ(typ Type) Type
typ
method
#
func (w *cycleFinder) typ(typ Type)
typ
method
#
func (w *typeWriter) typ(typ Type)
typ
method
#
typ type-checks the type expression e and returns its type, or Typ[Invalid].
The type must not be an (uninstantiated) generic type.
func (check *Checker) typ(e syntax.Expr) Type
typInternal
method
#
typInternal drives type checking of types.
Must only be called by definedType or genericType.
func (check *Checker) typInternal(e0 syntax.Expr, def *TypeName) (T Type)
typOrNil
method
#
typOrNil is like typ but if the argument is nil it is replaced with Typ[Invalid].
A nil type may appear in pathological cases such as type T[P any] []func(_ T([]_))
where an array/slice element is accessed before it is set up.
func (subst *subster) typOrNil(typ Type) Type
typeAssertion
method
#
typeAssertion checks x.(T). The type of x must be an interface.
func (check *Checker) typeAssertion(e syntax.Expr, x *operand, T Type, typeSwitch bool)
typeDecl
method
#
func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *TypeName)
typeList
method
#
func (w *typeWriter) typeList(list []Type)
typeList
method
#
typeList provides the list of types corresponding to the incoming expression list.
If an error occurred, the result is nil, but all list elements were type-checked.
func (check *Checker) typeList(list []syntax.Expr) []Type
typeName
method
#
func (w *typeWriter) typeName(obj *TypeName)
typeParamVertex
method
#
typeParamVertex returns the index of the vertex representing tpar.
func (w *monoGraph) typeParamVertex(tpar *TypeParam) int
typeParamsString
function
#
typeParamsString produces a string containing all the type parameter names
in list suitable for human consumption.
func typeParamsString(list []*TypeParam) string
typeSet
method
#
typeSet returns the type set for interface t.
func (t *Interface) typeSet() *_TypeSet
typeSet
method
#
typeSet writes a canonical hash for an interface type set.
func (w *typeWriter) typeSet(s *_TypeSet)
typeSwitchStmt
method
#
func (check *Checker) typeSwitchStmt(inner stmtContext, s *syntax.SwitchStmt, guard *syntax.TypeSwitchGuard)
typesSummary
method
#
typesSummary returns a string of the form "(t1, t2, ...)" where the
ti's are user-friendly string representations for the given types.
If variadic is set and the last type is a slice, its string is of
the form "...E" where E is the slice's element type.
If hasDots is set, the last argument string is of the form "T..."
where T is the last type.
Only one of variadic and hasDots may be set.
func (check *Checker) typesSummary(list []Type, variadic bool, hasDots bool) string
typeset
method
#
typeset is an iterator over the (type/underlying type) pairs of the
specific type terms of t's constraint.
If there are no specific terms, typeset calls yield with (nil, nil).
In any case, typeset is guaranteed to call yield at least once.
func (t *TypeParam) typeset(yield func(t Type, u Type) bool)
typeset
method
#
typeset is an iterator over the (type/underlying type) pairs in s.
If s has no specific terms, typeset calls yield with (nil, nil).
In any case, typeset is guaranteed to call yield at least once.
func (s *_TypeSet) typeset(yield func(t Type, u Type) bool)
typeset
function
#
typeset is an iterator over the (type/underlying type) pairs of the
specific type terms of the type set implied by t.
If t is a type parameter, the implied type set is the type set of t's constraint.
In that case, if there are no specific terms, typeset calls yield with (nil, nil).
If t is not a type parameter, the implied type set consists of just t.
In any case, typeset is guaranteed to call yield at least once.
func typeset(t Type, yield func(t Type, u Type) bool)
unalias
function
#
func unalias(a0 *Alias) Type
unary
method
#
func (check *Checker) unary(x *operand, e *syntax.Operation)
under
function
#
under returns the true expanded underlying type.
If it doesn't exist, the result is Typ[Invalid].
under must only be called when a type is known
to be fully set up.
func under(t Type) Type
under
method
#
under returns the expanded underlying type of n0; possibly by following
forward chains of named types. If an underlying type is found, resolve
the chain by setting the underlying type for each defined type in the
chain before returning it. If no underlying type is found or a cycle
is detected, the result is Typ[Invalid]. If a cycle is detected and
n0.check != nil, the cycle is reported.
This is necessary because the underlying type of named may be itself a
named type that is incomplete:
type (
A B
B *C
C A
)
The type of C is the (named) type of A which is incomplete,
and which has as its underlying type the named type B.
func (n0 *Named) under() Type
underIs
function
#
If typ is a type parameter, underIs returns the result of typ.underIs(f).
Otherwise, underIs returns the result of f(under(typ)).
func underIs(typ Type, f func(Type) bool) bool
unify
method
#
unify attempts to unify x and y and reports whether it succeeded.
As a side-effect, types may be inferred for type parameters.
The mode parameter controls how types are compared.
func (u *unifier) unify(x Type, y Type, mode unifyMode) bool
union
method
#
union returns the union x ∪ y: zero, one, or two non-nil terms.
func (x *term) union(y *term) (_ *term, _ *term)
union
method
#
union returns the union xl ∪ yl.
func (xl termlist) union(yl termlist) termlist
unknowns
method
#
unknowns returns the number of type parameters for which no type has been set yet.
func (u *unifier) unknowns() int
unpackRecv
method
#
unpackRecv unpacks a receiver type expression and returns its components: ptr indicates
whether rtyp is a pointer receiver, base is the receiver base type expression stripped
of its type parameters (if any), and tparams are its type parameter names, if any. The
type parameters are only unpacked if unpackParams is set. For instance, given the rtyp
*T[A, _]
ptr is true, base is T, and tparams is [A, _] (assuming unpackParams is set).
Note that base may not be a *syntax.Name for erroneous programs.
func (check *Checker) unpackRecv(rtyp syntax.Expr, unpackParams bool) (ptr bool, base syntax.Expr, tparams []*syntax.Name)
unpointer
function
#
func unpointer(t Type) Type
unusedImports
method
#
unusedImports checks for unused imports.
func (check *Checker) unusedImports()
update
method
#
update de-duplicates inst against previously seen types with the hash h.
If an identical type is found with the type hash h, the previously seen
type is returned. Otherwise, inst is returned, and recorded in the Context
for the hash h.
func (ctxt *Context) update(h string, orig Type, targs []Type, inst Type) Type
updateExprType
method
#
updateExprType updates the type of x to typ and invokes itself
recursively for the operands of x, depending on expression kind.
If typ is still an untyped and not the final type, updateExprType
only updates the recorded untyped type for x and possibly its
operands. Otherwise (i.e., typ is not an untyped type anymore,
or it is the final type for x), the type and value are recorded.
Also, if x is a constant, it must be representable as a value of typ,
and if x is the (formerly untyped) lhs operand of a non-constant
shift, it must be an integer value.
func (check *Checker) updateExprType(x syntax.Expr, typ Type, final bool)
updateExprVal
method
#
updateExprVal updates the value of x to val.
func (check *Checker) updateExprVal(x syntax.Expr, val constant.Value)
usage
method
#
func (check *Checker) usage(scope *Scope)
use
method
#
use type-checks each argument.
Useful to make sure expressions are evaluated
(and variables are "used") in the presence of
other errors. Arguments may be nil.
Reports if all arguments evaluated without error.
func (check *Checker) use(args ...syntax.Expr) bool
use1
method
#
func (check *Checker) use1(e syntax.Expr, lhs bool) bool
useLHS
method
#
useLHS is like use, but doesn't "use" top-level identifiers.
It should be called instead of use if the arguments are
expressions on the lhs of an assignment.
func (check *Checker) useLHS(args ...syntax.Expr) bool
useN
method
#
func (check *Checker) useN(args []syntax.Expr, lhs bool) bool
validAlias
method
#
validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
func (check *Checker) validAlias(alias *TypeName, typ Type)
validCycle
method
#
validCycle reports whether the cycle starting with obj is valid and
reports an error if it is not.
func (check *Checker) validCycle(obj Object) (valid bool)
validRecv
method
#
validRecv verifies that the receiver satisfies its respective spec requirements
and reports an error otherwise.
func (check *Checker) validRecv(pos poser, recv *Var)
validType
method
#
validType verifies that the given type does not "expand" indefinitely
producing a cycle in the type graph.
(Cycles involving alias types, as in "type A = [10]A" are detected
earlier, via the objDecl cycle detection mechanism.)
func (check *Checker) validType(typ *Named)
validType0
method
#
validType0 checks if the given type is valid. If typ is a type parameter
its value is looked up in the type argument list of the instantiated
(enclosing) type, if it exists. Otherwise the type parameter must be from
an enclosing function and can be ignored.
The nest list describes the stack (the "nest in memory") of types which
contain (or embed in the case of interfaces) other types. For instance, a
struct named S which contains a field of named type F contains (the memory
of) F in S, leading to the nest S->F. If a type appears in its own nest
(say S->F->S) we have an invalid recursive type. The path list is the full
path of named types in a cycle, it is only needed for error reporting.
func (check *Checker) validType0(pos syntax.Pos, typ Type, nest []*Named, path []*Named) bool
validVarType
method
#
validVarType reports an error if typ is a constraint interface.
The expression e is used for error reporting, if any.
func (check *Checker) validVarType(e syntax.Expr, typ Type)
validateTArgLen
method
#
validateTArgLen checks that the number of type arguments (got) matches the
number of type parameters (want); if they don't match an error is reported.
If validation fails and check is nil, validateTArgLen panics.
func (check *Checker) validateTArgLen(pos syntax.Pos, name string, want int, got int) bool
validatedImportPath
function
#
func validatedImportPath(path string) (string, error)
varDecl
method
#
func (check *Checker) varDecl(obj *Var, lhs []*Var, typ syntax.Expr, init syntax.Expr)
varList
method
#
func (w *cycleFinder) varList(list []*Var)
varList
method
#
func (w *tpWalker) varList(list []*Var) bool
varType
method
#
varType type-checks the type expression e and returns its type, or Typ[Invalid].
The type must not be an (uninstantiated) generic type and it must not be a
constraint interface.
func (check *Checker) varType(e syntax.Expr) Type
varTypes
function
#
varTypes returns the list of types for the given variables.
func varTypes(list []*Var) (res []Type)
var_
method
#
func (subst *subster) var_(v *Var) *Var
verify
method
#
check may be nil; pos is used only if check is non-nil.
func (check *Checker) verify(pos syntax.Pos, tparams []*TypeParam, targs []Type, ctxt *Context) (int, error)
verifyVersionf
method
#
verifyVersionf is like allowVersion but also accepts a format string and arguments
which are used to report a version error if allowVersion returns false.
func (check *Checker) verifyVersionf(at poser, v goVersion, format string, args ...interface{}) bool
versionErrorf
method
#
func (check *Checker) versionErrorf(at poser, v goVersion, format string, args ...any)
versionMax
function
#
func versionMax(a goVersion, b goVersion) goVersion
writeFuncName
function
#
func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier)
writeObject
function
#
func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier)