Code Examples
{
// Parse a single source file.
const input = `
package fib
type S string
var a, b, c = len(b), S(c), "hello"
func fib(x int) int {
if x < 2 {
return x
}
return fib(x-1) - fib(x-2)
}`
fset := token.NewFileSet()
f := mustParse(fset, input)
info := types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
var conf types.Config
pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)
if err != nil {
log.Fatal(err)
}
fmt.Printf("InitOrder: %v\n\n", info.InitOrder)
fmt.Println("Defs and Uses of each named object:")
usesByObj := make(map[types.Object][]string)
for id, obj := range info.Uses {
posn := fset.Position(id.Pos())
lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
usesByObj[obj] = append(usesByObj[obj], lineCol)
}
var items []string
for obj, uses := range usesByObj {
slices.Sort(uses)
item := fmt.Sprintf("%s:\n defined at %s\n used at %s",
types.ObjectString(obj, types.RelativeTo(pkg)),
fset.Position(obj.Pos()),
strings.Join(uses, ", "))
items = append(items, item)
}
slices.Sort(items)
fmt.Println(strings.Join(items, "\n"))
fmt.Println()
fmt.Println("Types and Values of each expression:")
items = nil
for expr, tv := range info.Types {
var buf strings.Builder
posn := fset.Position(expr.Pos())
tvstr := tv.Type.String()
if tv.Value != nil {
tvstr += " = " + tv.Value.String()
}
fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
posn.Line, posn.Column, exprString(fset, expr),
mode(tv), tvstr)
items = append(items, buf.String())
}
slices.Sort(items)
fmt.Println(strings.Join(items, "\n"))
}
{
// Parse a single source file.
const input = `
package temperature
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
type S struct { I; m int }
type I interface { m() byte }
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "celsius.go", input, 0)
if err != nil {
log.Fatal(err)
}
conf := types.Config{Importer: defaultImporter(fset)}
pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err)
}
celsius := pkg.Scope().Lookup("Celsius").Type()
for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
fmt.Printf("Method set of %s:\n", t)
for m := range types.NewMethodSet(t).Methods() {
fmt.Println(m)
}
fmt.Println()
}
styp := pkg.Scope().Lookup("S").Type()
fmt.Printf("Method set of %s:\n", styp)
fmt.Println(types.NewMethodSet(styp))
}
{
fset := token.NewFileSet()
var files []*ast.File
for _, src := range []string{
`package main
import "fmt"
func main() {
freezing := FToC(-18)
fmt.Println(freezing, Boiling) }
`,
`package main
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
const Boiling Celsius = 100
func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
`,
} {
files = append(files, mustParse(fset, src))
}
conf := types.Config{Importer: defaultImporter(fset)}
pkg, err := conf.Check("temperature", fset, files, nil)
if err != nil {
log.Fatal(err)
}
// Print the tree of scopes.
// For determinism, we redact addresses.
var buf strings.Builder
pkg.Scope().WriteTo(&buf, 0, true)
rx := regexp.MustCompile(` 0x[a-fA-F\d]*`)
fmt.Println(rx.ReplaceAllString(buf.String(), ""))
}
Package-Level Type Names (total 114, in which 50 are exported)
/* sort exporteds by: | */
An Alias represents an alias type.
Alias types are created by alias declarations such as:
type A = int
The type on the right-hand side of the declaration can be accessed
using [Alias.Rhs]. This type may itself be an alias.
Call [Unalias] to obtain the first non-alias type in a chain of
alias type declarations.
Like a defined ([Named]) type, an alias type has a name.
Use the [Alias.Obj] method to access its [TypeName] object.
Historically, Alias types were not materialized so that, in the example
above, A's type was represented by a Basic (int), not an Alias
whose [Alias.Rhs] is int. But Go 1.24 allows you to declare an
alias type with type parameters or arguments:
type Set[K comparable] = map[K]bool
s := make(Set[String])
and this requires that Alias types be materialized. Use the
[Alias.TypeParams] and [Alias.TypeArgs] methods to access them.
To ease the transition, the Alias type was introduced in go1.22,
but the type-checker would not construct values of this type unless
the GODEBUG=gotypesalias=1 environment variable was provided.
Starting in go1.23, this variable is enabled by default.
This setting also causes the predeclared type "any" to be
represented as an Alias, not a bare [Interface]. // actual (aliased) type; never an alias // RHS of type alias declaration; may be an alias // corresponding declared alias object // original, uninstantiated alias // type arguments, or nil // type parameters, or nil 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. 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. Rhs returns the type R on the right-hand side of an alias
declaration "type A = R", which may be another alias. SetTypeParams sets the type parameters of the alias type a.
The alias a must not have type arguments.(*Alias) String() string 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. TypeParams returns the type parameters of the alias type a, or nil.
A generic Alias and its instances have the same type parameters. 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.(*Alias) cleanup()
*Alias : Type
*Alias : expvar.Var
*Alias : fmt.Stringer
*Alias : golang.org/x/tools/internal/typesinternal.NamedOrAlias
*Alias : cleaner
*Alias : genericType
*Alias : context.stringer
*Alias : github.com/aws/smithy-go/middleware.stringer
*Alias : runtime.stringer
func NewAlias(obj *TypeName, rhs Type) *Alias
func (*Alias).Origin() *Alias
func golang.org/x/tools/internal/aliases.Origin(alias *Alias) *Alias
func (*Checker).newAlias(obj *TypeName, rhs Type) *Alias
func (*Checker).newAliasInstance(pos token.Pos, orig *Alias, targs []Type, expanding *Named, ctxt *Context) *Alias
func golang.org/x/tools/internal/aliases.Origin(alias *Alias) *Alias
func golang.org/x/tools/internal/aliases.Rhs(alias *Alias) Type
func golang.org/x/tools/internal/aliases.SetTypeParams(alias *Alias, tparams []*TypeParam)
func golang.org/x/tools/internal/aliases.TypeArgs(alias *Alias) *TypeList
func golang.org/x/tools/internal/aliases.TypeParams(alias *Alias) *TypeParamList
func unalias(a0 *Alias) Type
func (*Checker).newAliasInstance(pos token.Pos, orig *Alias, targs []Type, expanding *Named, ctxt *Context) *Alias
An Array represents an array type.elemTypelenint64 Elem returns element type of array a. Len returns the length of array a.
A negative result indicates an unknown length.(*Array) String() string(*Array) Underlying() Type
*Array : Type
*Array : expvar.Var
*Array : fmt.Stringer
*Array : context.stringer
*Array : github.com/aws/smithy-go/middleware.stringer
*Array : runtime.stringer
func NewArray(elem Type, len int64) *Array
A Builtin represents a built-in function.
Builtins don't have a valid type.idbuiltinIdobjectobjectobject.color_colorobject.namestringobject.order_uint32object.parent*Scopeobject.pkg*Packageobject.postoken.Posobject.scopePos_token.Posobject.typType 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Builtin) String() string Type returns the object's type. 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.(*Builtin) color() color(*Builtin) order() uint32(*Builtin) sameId(pkg *Package, name string, foldCase bool) bool(*Builtin) scopePos() token.Pos(*Builtin) setColor(color color)(*Builtin) setOrder(order uint32)(*Builtin) setParent(parent *Scope)(*Builtin) setScopePos(pos token.Pos)(*Builtin) setType(typ Type)
*Builtin : Object
*Builtin : expvar.Var
*Builtin : fmt.Stringer
*Builtin : positioner
*Builtin : context.stringer
*Builtin : github.com/aws/smithy-go/middleware.stringer
*Builtin : runtime.stringer
func newBuiltin(id builtinId) *Builtin
A ChanDir value indicates a channel direction.
func (*Chan).Dir() ChanDir
func golang.org/x/tools/internal/gcimporter.chanDir(d int) ChanDir
func NewChan(dir ChanDir, elem Type) *Chan
const RecvOnly
const SendOnly
const SendRecv
A Checker maintains the state of the type checker.
It must be created with [NewChecker].Info*Info Defs maps identifiers to the objects they define (including
package names, dots "." of dot-imports, and blank "_" identifiers).
For identifiers that do not denote objects (e.g., the package name
in package clauses, or symbolic variables t in t := x.(type) of
type switch headers), the corresponding objects are nil.
For an embedded field, Defs returns the field *Var it defines.
Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos() FileVersions maps a file to its Go version string.
If the file doesn't specify a version, the reported
string is Config.GoVersion.
Version strings begin with “go”, like “go1.21”, and
are suitable for use with the [go/version] package. Implicits maps nodes to their implicitly declared objects, if any.
The following node and object types may appear:
node declared object
*ast.ImportSpec *PkgName for imports without renames
*ast.CaseClause type-specific *Var for each type switch case clause (incl. default)
*ast.Field anonymous parameter *Var (incl. unnamed results) InitOrder is the list of package-level initializers in the order in which
they must be executed. Initializers referring to variables related by an
initialization dependency appear in topological order, the others appear
in source order. Variables without an initialization expression do not
appear in this list. Instances maps identifiers denoting generic types or functions to their
type arguments and instantiated type.
For example, Instances will map the identifier for 'T' in the type
instantiation T[int, string] to the type arguments [int, string] and
resulting instantiated *Named type. Given a generic function
func F[A any](A), Instances will map the identifier for 'F' in the call
expression F(int(1)) to the inferred type arguments [int], and resulting
instantiated *Signature.
Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
results in an equivalent of Instances[id].Type. Scopes maps ast.Nodes to the scopes they define. Package scopes are not
associated with a specific node but with all files belonging to a package.
Thus, the package scope can be found in the type-checked Package object.
Scopes nest, with the Universe scope being the outermost scope, enclosing
the package scope, which contains (one or more) files scopes, which enclose
function scopes which in turn enclose statement and function literal scopes.
Note that even though package-level functions are declared in the package
scope, the function scopes are embedded in the file scope of the file
containing the function declaration.
The Scope of a function contains the declarations of any
type parameters, parameters, and named results, plus any
local declarations in the body block.
It is coextensive with the complete extent of the
function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]).
The Scopes mapping does not contain an entry for the
function body ([*ast.BlockStmt]); the function's scope is
associated with the [*ast.FuncType].
The following node types may appear in Scopes:
*ast.File
*ast.FuncType
*ast.TypeSpec
*ast.BlockStmt
*ast.IfStmt
*ast.SwitchStmt
*ast.TypeSwitchStmt
*ast.CaseClause
*ast.CommClause
*ast.ForStmt
*ast.RangeStmt Selections maps selector expressions (excluding qualified identifiers)
to their corresponding selections. Types maps expressions to their types, and for constant
expressions, also their values. Invalid expressions are
omitted.
For (possibly parenthesized) identifiers denoting built-in
functions, the recorded signatures are call-site specific:
if the call result is not a constant, the recorded type is
an argument-specific signature. Otherwise, the recorded type
is invalid.
The Types map does not record the type of every identifier,
only those that appear where an arbitrary expression is
permitted. For instance:
- an identifier f in a selector expression x.f is found
only in the Selections map;
- an identifier z in a variable declaration 'var z int'
is found only in the Defs map;
- an identifier p denoting a package in a qualified
identifier p.X is found only in the Uses map.
Similarly, no type is recorded for the (synthetic) FuncType
node in a FuncDecl.Type field, since there is no corresponding
syntactic function type expression in the source in this case
Instead, the function type is found in the Defs.map entry for
the corresponding function declaration. Uses maps identifiers to the objects they denote.
For an embedded field, Uses returns the *TypeName it denotes.
Invariant: Uses[id].Pos() != id.Pos() // set of aliases with broken (not yet determined) types // list of types that may need a final cleanup at the end of type-checking package information
(initialized by NewChecker, valid for the life-time of checker) // context for de-duplicating instances // stack of delayed action segments; segments are processed in FIFO order // maps dot-imported objects to the package they were dot-imported through environment within which the current object is type-checked (valid only
for the duration of type-checking a specific object) // package-level declaration whose init expression/function body is checked // if set, identifier position of a constant with inherited initializer go/types only // if valid, identifiers are looked up as if at position pos (used by CheckExpr, Eval) // set if an expression contains a function call or channel receive operation // set if a function makes use of labels (only ~1% of functions); unused outside functions // set if inside a type parameter list // value of iota in a constant declaration; nil otherwise // set of panic call expressions (used for termination check) // top-most scope for lookups // function signature if inside a function; nil otherwise // current accepted language version; changes across files information collected during type-checking of a set of package files
(initialized by Files, valid only for the duration of check.Files;
maps and lists are allocated on demand) // package files // first error encounteredfset*token.FileSet // maps (import path, source directory) to (complete or fake) package // list of imported packages debugging // indentation for tracing // maps package scope type names to associated non-blank (non-interface) methods // graph for detecting non-monomorphizable instantiation loops // unique Id for type parameters (first valid Id is 1) // maps package-level objects and (non-interface) methods to declaration info // path of object dependencies during type inference (for cycle reporting)pkg*Package pkgPathMap maps package names to the set of distinct import paths we've
seen for that name, anywhere in the import graph. It is used for
disambiguating package names in error messages.
pkgPathMap is allocated lazily, so that we don't pay the price of building
it on the happy path. seenPkgMap tracks the packages that we've already
walked.seenPkgMapmap[*Package]bool // computed type sets for union types // map of expressions without final type // set of used package names // set of used variables // maps files to goVersion strings (each file has an entry); shared with Info.FileVersions if present; may be unaltered Config.GoVersion Files checks the provided files as part of the checker's package. ObjectOf returns the object denoted by the specified id,
or nil if not found.
If id is an embedded struct field, [Info.ObjectOf] returns the field (*[Var])
it defines, not the type (*[TypeName]) it uses.
Precondition: the Uses and Defs maps are populated. 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. TypeOf returns the type of expression e, or nil if not found.
Precondition: the Types, Uses and Defs maps are populated. addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists allowVersion reports whether the current effective Go version
(which may vary from one file to another) is allowed to use the
feature version (want). 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). 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. arityMatch checks that the lhs and rhs of a const or var decl
have the appropriate number of names and init exprs. For const
decls, init is the value spec providing the init exprs; for
var decls, init is nil (the init exprs are in s in this case). 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). 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.(*Checker) assignError(rhs []ast.Expr, l, r int) 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. assignVars type-checks assignments of expressions orig_rhs to variables lhs. 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.(*Checker) basicLit(x *operand, e *ast.BasicLit) 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). 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).(*Checker) bound(x ast.Expr) Type 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. 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.(*Checker) callExpr(x *operand, call *ast.CallExpr) exprKind 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 <x>.(type) {
case <types>: ...
...
}
caseTypes returns the case-specific type for a variable v introduced through a short
variable declaration by the type switch:
switch v := <x>.(type) {
case <types>: // T is the type of <v> 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. 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.)(*Checker) caseValues(x *operand, values []ast.Expr, seen valueMap)(*Checker) checkFieldUniqueness(base *Named) 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. cleanup runs cleanup for all collected cleaners.(*Checker) closeScope()(*Checker) collectMethods(obj *TypeName) 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. 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. 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).(*Checker) collectTypeParams(dst **TypeParamList, list *ast.FieldList) If switchCase is true, the operator op is ignored.(*Checker) compositeLit(x *operand, e *ast.CompositeLit, hint Type)(*Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool) context returns the type-checker context. conversion type-checks the conversion T(x).
The result is in x. convertUntyped attempts to set the type of an untyped value to the target type. cycleError reports a declaration cycle starting with the object at cycle[start].(*Checker) declStmt(d ast.Decl)(*Checker) declare(scope *Scope, id *ast.Ident, obj Object, pos token.Pos)(*Checker) declareInSet(oset *objset, pos token.Pos, obj Object) bool declareParams declares each named parameter in the current scope. 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.(*Checker) declareTypeParam(name *ast.Ident, scopePos token.Pos) *TypeParam 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. dump is only needed for debugging(*Checker) error(at positioner, code Code, msg string)(*Checker) errorUnusedPkg(obj *PkgName)(*Checker) errorf(at positioner, code Code, format string, args ...any) exclude reports an error if x.mode is in modeset and sets x.mode to invalid.
The modeset may contain any of 1<<novalue, 1<<builtin, 1<<typexpr. 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. exprInternal contains the core of type checking of expressions.
Must only be called by rawExpr.
(See rawExpr for an explanation of the parameters.) exprList evaluates a list of expressions and returns the corresponding operands.
A single-element expression list may evaluate to multiple operands. 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. 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. filename returns a filename suitable for debugging output. decl may be nil(*Checker) funcDecl(obj *Func, decl *declInfo) funcInst type-checks a function instantiation.
The incoming x must be a generic function.
If ix != nil, it provides some or all of the type arguments (ix.Indices).
If target != nil, it may be used to infer missing type arguments of x, if any.
At least one of T or ix 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.(*Checker) funcLit(x *operand, e *ast.FuncLit) funcString returns a string of the form name + signature for f.
check may be nil. funcType type-checks a function or method type. genericExpr is like expr but the result may also be generic. 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. 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.(*Checker) handleBailout(err *error) handleError should only be called by error_.report. 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. 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. 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. 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.(*Checker) importPackage(at positioner, path, dir string) *Package incomparableCause returns a more specific cause why typ is not comparable.
If there is no more specific cause, the result is "". 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. 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. 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). 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.(*Checker) initConst(lhs *Const, x *operand) initFiles initializes the files-specific portion of checker.
The provided files must all belong to the same package. initOrder computes the Info.InitOrder for package variables. 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. 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. 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.(*Checker) instantiateSignature(pos token.Pos, expr ast.Expr, typ *Signature, targs []Type, xlist []ast.Expr) (res *Signature)(*Checker) instantiatedType(ix *indexedExpr, def *TypeName) (res Type) check may be nil.(*Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *TypeName)(*Checker) invalidConversion(code Code, x *operand, target Type) isBrokenAlias reports whether alias doesn't have a determined type yet. isImportedConstraint reports whether typ is an imported type constraint. isNil reports whether the expression e denotes the predeclared value nil. isTerminating reports if s is a terminating statement.
If s is labeled, label is the label name; otherwise s
is "".(*Checker) isTerminatingList(list []ast.Stmt, label string) bool(*Checker) isTerminatingSwitch(body *ast.BlockStmt, label string) bool(*Checker) isValidIndex(x *operand, code Code, what string, allowNegative bool) bool labels checks correct label use in body. langCompat reports an error if the representation of a numeric
literal is not compatible with the current language version. 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. 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. lookup is like lookupScope but it only returns the object (or nil). 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. 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. markImports recursively walks pkg and its imports, to record unique import
paths in pkgPathMap. matchTypes attempts to convert any untyped types x and y such that they match.
If an error occurs, x.mode is set to invalid. 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.(*Checker) monomorph() 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.(*Checker) multipleDefaults(list []ast.Stmt) needsCleanup records objects/types that implement the cleanup method
which will be called at the end of type-checking. newAlias creates a new Alias type with the given type name and rhs.
rhs must not be nil. 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). 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. newError returns a new error_ with the given error code. check may be nil newNamed is like NewNamed but with a *Checker receiver. 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. check may be nil 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. objDecl type-checks the declaration of obj in its respective (file) environment.
For the meaning of def, see Checker.definedType, in typexpr.go.(*Checker) op(m opPredicates, x *operand, op token.Token) bool(*Checker) openScope(node ast.Node, comment string) overflow checks that the constant x is representable by its type.
For untyped constants, it checks that the value doesn't become
arbitrarily large. packageObjects typechecks all package objects, but not function bodies. pop pops and returns the topmost object from the object path. processDelayed processes all delayed actions pushed after top. push pushes obj onto the object path and returns its index in the path.(*Checker) qualifier(pkg *Package) string(*Checker) rangeStmt(inner stmtContext, s *ast.RangeStmt) 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.(*Checker) record(x *operand)(*Checker) recordBuiltinType(f ast.Expr, sig *Signature) recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
(and therefore has tuple type). go/types doesn't support recording of types directly in the AST.
dummy function to match types2 code.(*Checker) recordDef(id *ast.Ident, obj Object)(*Checker) recordImplicit(node ast.Node, obj Object) 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. 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](*Checker) recordScope(node ast.Node, scope *Scope)(*Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool)(*Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) go/types doesn't support recording of types directly in the AST.
dummy function to match types2 code.( Checker) recordTypes() bool(*Checker) recordUntyped()(*Checker) recordUse(id *ast.Ident, obj Object)(*Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) 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. reportCycle reports an error for the given cycle.(*Checker) reportInstanceLoop(v int) representable checks that a constant operand is representable in the given
basic type. 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. 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.(*Checker) returnError(at positioner, lhs []*Var, rhs []*operand)(*Checker) selector(x *operand, e *ast.SelectorExpr, def *TypeName, wantType bool) If e != nil, it must be the shift expression; it may be nil for non-constant shifts.(*Checker) shortVarDecl(pos positioner, lhs, rhs []ast.Expr)(*Checker) simpleStmt(s ast.Stmt) 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. singleValue reports an error if x describes a tuple and sets x.mode to invalid.(*Checker) sliceExpr(x *operand, e *ast.SliceExpr)(*Checker) softErrorf(at positioner, code Code, format string, args ...any) check may be nil. stmt typechecks statement s.(*Checker) stmtList(ctxt stmtContext, list []ast.Stmt)(*Checker) structType(styp *Struct, e *ast.StructType) 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.(*Checker) suspendedCall(keyword string, call *ast.CallExpr)(*Checker) tag(t *ast.BasicLit) string(*Checker) trace(pos token.Pos, format string, args ...any) typ type-checks the type expression e and returns its type, or Typ[Invalid].
The type must not be an (uninstantiated) generic type. typInternal drives type checking of types.
Must only be called by definedType or genericType. typeAssertion checks x.(T). The type of x must be an interface.(*Checker) typeDecl(obj *TypeName, tdecl *ast.TypeSpec, def *TypeName) 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. 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. The unary expression e may be nil. It's passed in for better error messages only. 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 *ast.Ident for erroneous programs. unusedImports checks for unused imports. 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. updateExprVal updates the value of x to val.(*Checker) usage(scope *Scope) 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.(*Checker) use1(e ast.Expr, lhs bool) bool 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.(*Checker) useN(args []ast.Expr, lhs bool) bool validAlias records that alias has the valid type typ (possibly Typ[Invalid]). validCycle checks if the cycle starting with obj is valid and
reports an error if it is not. validRecv verifies that the receiver satisfies its respective spec requirements
and reports an error otherwise. 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.) 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. validVarType reports an error if typ is a constraint interface.
The expression e is used for error reporting, if any. 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.(*Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) 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. check may be nil; pos is used only if check is non-nil. verifyVersionf is like allowVersion but also accepts a format string and arguments
which are used to report a version error if allowVersion returns false.(*Checker) versionErrorf(at positioner, v goVersion, format string, args ...any)(*Checker) walkDecl(d ast.Decl, f func(decl))(*Checker) walkDecls(decls []ast.Decl, f func(decl))
*Checker : cleaner
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
func badlinkname_Checker_infer(*Checker, positioner, []*TypeParam, []Type, *Tuple, []*operand, bool, *error_) []Type
func computeInterfaceTypeSet(check *Checker, pos token.Pos, ityp *Interface) *_TypeSet
func computeUnionTypeSet(check *Checker, unionSets map[*Union]*_TypeSet, pos token.Pos, utyp *Union) *_TypeSet
func parseTilde(check *Checker, tx ast.Expr) *Term
func parseUnion(check *Checker, uexpr ast.Expr) Type
func representableConst(x constant.Value, check *Checker, typ *Basic, rounded *constant.Value) bool
A Config specifies the configuration for type checking.
The zero value for Config is a ready-to-use default configuration. Context is the context used for resolving global identifiers. If nil, the
type checker will initialize this field with a newly created context. If DisableUnusedImportCheck is set, packages are not checked
for unused imports. If Error != nil, it is called with each error found
during type checking; err has dynamic type Error.
Secondary errors (for instance, to enumerate all types
involved in an invalid recursive type declaration) have
error strings that start with a '\t' character.
If Error == nil, type-checking stops with the first
error found. If FakeImportC is set, `import "C"` (for packages requiring Cgo)
declares an empty "C" package and errors are omitted for qualified
identifiers referring to package C (which won't find an object).
This feature is intended for the standard library cmd/api tool.
Caution: Effects may be unpredictable due to follow-on errors.
Do not use casually! GoVersion describes the accepted Go language version. The string must
start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or
"go1.21.0") or it must be empty; an empty string disables Go language
version checks. If the format is invalid, invoking the type checker will
result in an error. If IgnoreFuncBodies is set, function bodies are not
type-checked. An importer is used to import packages referred to from
import declarations.
If the installed importer implements ImporterFrom, the type
checker calls ImportFrom instead of Import.
The type checker reports an error if an importer is needed
but none was installed. If Sizes != nil, it provides the sizing functions for package unsafe.
Otherwise SizesFor("gc", "amd64") is used instead. If EnableAlias is set, alias declarations produce an Alias type. Otherwise
the alias information is only in the type name, which points directly to
the actual (aliased) type.
This setting must not differ among concurrent type-checking operations,
since it affects the behavior of Universe.Lookup("any").
This flag will eventually be removed (with Go 1.24 at the earliest). If a non-empty _ErrorURL format string is provided, it is used
to format an error URL link that is appended to the first line
of an error message. ErrorURL must be a format string containing
exactly one "%s" format, e.g. "[go.dev/e/%s]". If _Trace is set, a debug trace is printed to stdout. If go115UsesCgo is set, the type checker expects the
_cgo_gotypes.go file generated by running cmd/cgo to be
provided as a package source file. Qualified identifiers
referring to package C will be resolved to cgo-provided
declarations within _cgo_gotypes.go.
It is an error to set both FakeImportC and go115UsesCgo. Check type-checks a package and returns the resulting package object and
the first error if any. Additionally, if info != nil, Check populates each
of the non-nil maps in the [Info] struct.
The package is marked as complete if no errors occurred, otherwise it is
incomplete. See [Config.Error] for controlling behavior in the presence of
errors.
The package is specified by a list of *ast.Files and corresponding
file set, and the package path the package is identified with.
The clean path must not be empty or dot (".").(*Config) alignof(T Type) int64 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.(*Config) offsetsof(T *Struct) []int64 sizeof returns the size of T.
If T is too large, the result is negative.
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
func golang.org/x/tools/internal/typesinternal.SetUsesCgo(conf *Config) bool
func srcimporter_setUsesCgo(conf *Config)
A Context is an opaque type checking context. It may be used to share
identical type instances across type-checked packages or calls to
Instantiate. Contexts are safe for concurrent use.
The use of a shared context does not guarantee that identical instances are
deduplicated in all cases.musync.Mutex // next unique ID // origin type -> unique ID // type hash -> instances entries getID returns a unique ID for the type t. 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. lookup returns an existing instantiation of orig with targs, if it exists.
Otherwise, it returns nil. 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 NewContext() *Context
func (*Checker).context() *Context
func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)
func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter
func (*Checker).instance(pos token.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type)
func (*Checker).newAliasInstance(pos token.Pos, orig *Alias, targs []Type, expanding *Named, ctxt *Context) *Alias
func (*Checker).subst(pos token.Pos, typ Type, smap substMap, expanding *Named, ctxt *Context) Type
func (*Checker).verify(pos token.Pos, tparams []*TypeParam, targs []Type, ctxt *Context) (int, error)
func golang.org/x/tools/internal/gcimporter.readUnifiedPackage(fset *token.FileSet, ctxt *Context, imports map[string]*Package, input pkgbits.PkgDecoder) *Package
An Error describes a type-checking error; it implements the error interface.
A "soft" error is an error that still permits a valid interpretation of a
package (such as "unused variable"); "hard" errors may lead to unpredictable
behavior if ignored. // file set for interpretation of Pos // error message // error position // if set, error is "soft" go116code is a future API, unexported as the set of error codes is large
and likely to change significantly during experimentation. Tools wishing
to preview this feature may read go116code using reflection (see
errorcodes_test.go), but beware that there is no guarantee of future
compatibility.go116endtoken.Posgo116starttoken.Pos Error returns an error string formatted as follows:
filename:line:column: message
Error : error
func golang.org/x/tools/internal/typesinternal.ErrorCodeStartEnd(err Error) (code typesinternal.ErrorCode, start, end token.Pos, ok bool)
A Func represents a declared function, concrete method, or abstract
(interface) method. Its Type() is always a *Signature.
An abstract method may belong to many interfaces due to embedding. // only valid for methods that don't have a type yet; use hasPtrRecv() to readobjectobjectobject.color_colorobject.namestringobject.order_uint32object.parent*Scopeobject.pkg*Packageobject.postoken.Posobject.scopePos_token.Posobject.typType // if non-nil, the Func from which this one was instantiated 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. FullName returns the package- or receiver-type-qualified name of
function or method obj. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. 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. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. 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. Pos returns the declaration position of the object's identifier. 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). Signature returns the signature (type) of the function or method.(*Func) String() string Type returns the object's type. 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) color() color hasPtrRecv reports whether the receiver is of the form *T for the given method obj.(*Func) isDependency()(*Func) order() uint32(*Func) sameId(pkg *Package, name string, foldCase bool) bool(*Func) scopePos() token.Pos(*Func) setColor(color color)(*Func) setOrder(order uint32)(*Func) setParent(parent *Scope)(*Func) setScopePos(pos token.Pos)(*Func) setType(typ Type)
*Func : Object
*Func : expvar.Var
*Func : fmt.Stringer
*Func : dependency
*Func : positioner
*Func : context.stringer
*Func : github.com/aws/smithy-go/middleware.stringer
*Func : runtime.stringer
func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func
func (*Func).Origin() *Func
func (*Interface).ExplicitMethod(i int) *Func
func (*Interface).Method(i int) *Func
func (*Named).Method(i int) *Func
func golang.org/x/tools/go/types/typeutil.StaticCallee(info *Info, call *ast.CallExpr) *Func
func cloneFunc(f *Func, typ Type) *Func
func methodIndex(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func)
func replaceRecvType(in []*Func, old, new Type) (out []*Func, copied bool)
func (*Checker).missingMethod(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) (method *Func, wrongType bool)
func (*Named).expandMethod(i int) *Func
func (*Named).lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func)
func golang.org/x/exp/apidiff.unexportedMethod(t *Interface) *Func
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
func (*Named).AddMethod(m *Func)
func assertSortedMethods(list []*Func)
func cloneFunc(f *Func, typ Type) *Func
func compareFunc(a, b *Func) int
func methodIndex(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func)
func replaceRecvType(in []*Func, old, new Type) (out []*Func, copied bool)
func sortMethods(list []*Func)
func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier)
func (*Checker).funcDecl(obj *Func, decl *declInfo)
func (*Checker).funcString(f *Func, pkgInfo bool) string
func (*Checker).newNamed(obj *TypeName, underlying Type, methods []*Func) *Named
func golang.org/x/tools/go/types/objectpath.(*Encoder).concreteMethod(meth *Func) (objectpath.Path, bool)
func golang.org/x/tools/go/types/typeutil.interfaceMethod(f *Func) bool
func golang.org/x/tools/internal/typesinternal.interfaceMethod(f *Func) bool
An Importer resolves import paths to Packages.
CAUTION: This interface does not support the import of locally
vendored packages. See https://golang.org/s/go15vendor.
If possible, external implementations should implement [ImporterFrom]. Import returns the imported package for the given import path.
The semantics is like for ImporterFrom.ImportFrom except that
dir and mode are ignored (since they are not present).ImporterFrom(interface)
golang.org/x/tools/go/gcexportdata.importer
golang.org/x/tools/go/packages.importerFunc
An ImporterFrom resolves import paths to packages; it
supports vendoring per https://golang.org/s/go15vendor.
Use go/importer to obtain an ImporterFrom implementation. Import returns the imported package for the given import path.
The semantics is like for ImporterFrom.ImportFrom except that
dir and mode are ignored (since they are not present). ImportFrom returns the imported package for the given import
path when imported by a package file located in dir.
If the import failed, besides returning an error, ImportFrom
is encouraged to cache and return a package anyway, if one
was created. This will reduce package inconsistencies and
follow-on type checker errors due to the missing package.
The mode value must be 0; it is reserved for future use.
Two calls to ImportFrom with the same path and dir must
return the same package.
golang.org/x/tools/go/gcexportdata.importer
ImporterFrom : Importer
func golang.org/x/tools/go/gcexportdata.NewImporter(fset *token.FileSet, imports map[string]*Package) ImporterFrom
Info holds result type information for a type-checked package.
Only the information for which a map is provided is collected.
If the package has type errors, the collected information may
be incomplete. Defs maps identifiers to the objects they define (including
package names, dots "." of dot-imports, and blank "_" identifiers).
For identifiers that do not denote objects (e.g., the package name
in package clauses, or symbolic variables t in t := x.(type) of
type switch headers), the corresponding objects are nil.
For an embedded field, Defs returns the field *Var it defines.
Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos() FileVersions maps a file to its Go version string.
If the file doesn't specify a version, the reported
string is Config.GoVersion.
Version strings begin with “go”, like “go1.21”, and
are suitable for use with the [go/version] package. Implicits maps nodes to their implicitly declared objects, if any.
The following node and object types may appear:
node declared object
*ast.ImportSpec *PkgName for imports without renames
*ast.CaseClause type-specific *Var for each type switch case clause (incl. default)
*ast.Field anonymous parameter *Var (incl. unnamed results) InitOrder is the list of package-level initializers in the order in which
they must be executed. Initializers referring to variables related by an
initialization dependency appear in topological order, the others appear
in source order. Variables without an initialization expression do not
appear in this list. Instances maps identifiers denoting generic types or functions to their
type arguments and instantiated type.
For example, Instances will map the identifier for 'T' in the type
instantiation T[int, string] to the type arguments [int, string] and
resulting instantiated *Named type. Given a generic function
func F[A any](A), Instances will map the identifier for 'F' in the call
expression F(int(1)) to the inferred type arguments [int], and resulting
instantiated *Signature.
Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
results in an equivalent of Instances[id].Type. Scopes maps ast.Nodes to the scopes they define. Package scopes are not
associated with a specific node but with all files belonging to a package.
Thus, the package scope can be found in the type-checked Package object.
Scopes nest, with the Universe scope being the outermost scope, enclosing
the package scope, which contains (one or more) files scopes, which enclose
function scopes which in turn enclose statement and function literal scopes.
Note that even though package-level functions are declared in the package
scope, the function scopes are embedded in the file scope of the file
containing the function declaration.
The Scope of a function contains the declarations of any
type parameters, parameters, and named results, plus any
local declarations in the body block.
It is coextensive with the complete extent of the
function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]).
The Scopes mapping does not contain an entry for the
function body ([*ast.BlockStmt]); the function's scope is
associated with the [*ast.FuncType].
The following node types may appear in Scopes:
*ast.File
*ast.FuncType
*ast.TypeSpec
*ast.BlockStmt
*ast.IfStmt
*ast.SwitchStmt
*ast.TypeSwitchStmt
*ast.CaseClause
*ast.CommClause
*ast.ForStmt
*ast.RangeStmt Selections maps selector expressions (excluding qualified identifiers)
to their corresponding selections. Types maps expressions to their types, and for constant
expressions, also their values. Invalid expressions are
omitted.
For (possibly parenthesized) identifiers denoting built-in
functions, the recorded signatures are call-site specific:
if the call result is not a constant, the recorded type is
an argument-specific signature. Otherwise, the recorded type
is invalid.
The Types map does not record the type of every identifier,
only those that appear where an arbitrary expression is
permitted. For instance:
- an identifier f in a selector expression x.f is found
only in the Selections map;
- an identifier z in a variable declaration 'var z int'
is found only in the Defs map;
- an identifier p denoting a package in a qualified
identifier p.X is found only in the Uses map.
Similarly, no type is recorded for the (synthetic) FuncType
node in a FuncDecl.Type field, since there is no corresponding
syntactic function type expression in the source in this case
Instead, the function type is found in the Defs.map entry for
the corresponding function declaration. Uses maps identifiers to the objects they denote.
For an embedded field, Uses returns the *TypeName it denotes.
Invariant: Uses[id].Pos() != id.Pos() ObjectOf returns the object denoted by the specified id,
or nil if not found.
If id is an embedded struct field, [Info.ObjectOf] returns the field (*[Var])
it defines, not the type (*[TypeName]) it uses.
Precondition: the Uses and Defs maps are populated. 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. TypeOf returns the type of expression e, or nil if not found.
Precondition: the Types, Uses and Defs maps are populated.(*Info) recordTypes() bool
func golang.org/x/tools/internal/typesinternal.NewTypesInfo() *Info
func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
func (*Config).Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)
func golang.org/x/tools/go/types/typeutil.Callee(info *Info, call *ast.CallExpr) Object
func golang.org/x/tools/go/types/typeutil.StaticCallee(info *Info, call *ast.CallExpr) *Func
func golang.org/x/tools/internal/typesinternal.ClassifyCall(info *Info, call *ast.CallExpr) typesinternal.CallKind
func golang.org/x/tools/internal/typesinternal.UsedIdent(info *Info, e ast.Expr) *ast.Ident
func golang.org/x/tools/internal/versions.FileVersion(info *Info, file *ast.File) string
func golang.org/x/tools/go/types/typeutil.usedIdent(info *Info, e ast.Expr) *ast.Ident
func golang.org/x/tools/internal/typesinternal.usedIdent(info *Info, e ast.Expr) *ast.Ident
An Initializer describes a package-level variable, or a list of variables in case
of a multi-valued initialization expression, and the corresponding initialization
expression. // var Lhs = RhsRhsast.Expr(*Initializer) String() string
*Initializer : expvar.Var
*Initializer : fmt.Stringer
*Initializer : context.stringer
*Initializer : github.com/aws/smithy-go/middleware.stringer
*Initializer : runtime.stringer
Instance reports the type arguments and instantiated type for type and
function instantiations. For type instantiations, [Type] will be of dynamic
type *[Named]. For function instantiations, [Type] will be of dynamic type
*Signature.TypeTypeTypeArgs*TypeList
An Interface represents an interface type. // for error reporting; nil once type set is computed // indicates that obj, methods, and embeddeds are set and type set can be computed // positions of embedded elements; or nil (for error messages) - use pointer to save space // ordered list of explicitly embedded elements // interface is wrapper for type set literal (non-interface T, ~T, or A|B) // ordered list of explicitly declared methods // type set described by this interface, computed lazily Complete computes the interface's type set. It must be called by users of
[NewInterfaceType] and [NewInterface] after the interface's embedded types are
fully defined and before using the interface type in any way other than to
form other types. The interface must not contain duplicate methods or a
panic occurs. Complete returns the receiver.
Interface types that have been completed are safe for concurrent use. Embedded returns the i'th embedded defined (*[Named]) type of interface t for 0 <= i < t.NumEmbeddeds().
The result is nil if the i'th embedded type is not a defined type.
Deprecated: Use [Interface.EmbeddedType] which is not restricted to defined (*[Named]) types. EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds(). EmbeddedTypes returns a go1.23 iterator over the types embedded within an interface.
Example: for e := range t.EmbeddedTypes() { ... } Empty reports whether t is the empty interface. ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
The methods are ordered by their unique [Id]. ExplicitMethods returns a go1.23 iterator over the explicit methods of
an interface, ordered by Id.
Example: for m := range t.ExplicitMethods() { ... } IsComparable reports whether each type in interface t's type set is comparable. IsImplicit reports whether the interface t is a wrapper for a type set literal. IsMethodSet reports whether the interface t is fully described by its method
set. 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. Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
The methods are ordered by their unique Id. Methods returns a go1.23 iterator over all the methods of an
interface, ordered by Id.
Example: for m := range t.Methods() { ... } NumEmbeddeds returns the number of embedded types in interface t. NumExplicitMethods returns the number of explicitly declared methods of interface t. NumMethods returns the total number of methods of interface t.(*Interface) String() string(*Interface) Underlying() Type(*Interface) cleanup() typeSet returns the type set for interface t.
*Interface : Type
*Interface : expvar.Var
*Interface : fmt.Stringer
*Interface : cleaner
*Interface : context.stringer
*Interface : github.com/aws/smithy-go/middleware.stringer
*Interface : runtime.stringer
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface
func (*Interface).Complete() *Interface
func asInterface(x Type) (i *Interface)
func (*Checker).newInterface() *Interface
func (*TypeParam).iface() *Interface
func AssertableTo(V *Interface, T Type) bool
func Implements(V Type, T *Interface) bool
func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
func Satisfies(V Type, T *Interface) bool
func golang.org/x/tools/internal/typeparams.InterfaceTermSet(iface *Interface) ([]*Term, error)
func computeInterfaceTypeSet(check *Checker, pos token.Pos, ityp *Interface) *_TypeSet
func (*Checker).caseTypes_currently_unused(x *operand, xtyp *Interface, types []ast.Expr, seen map[string]ast.Expr) Type
func (*Checker).interfaceType(ityp *Interface, iface *ast.InterfaceType, def *TypeName)
func golang.org/x/exp/apidiff.unexportedMethod(t *Interface) *Func
var emptyInterface
A Label represents a declared label.
Labels don't have a type.objectobjectobject.color_colorobject.namestringobject.order_uint32object.parent*Scopeobject.pkg*Packageobject.postoken.Posobject.scopePos_token.Posobject.typType // set if the label was used 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Label) String() string Type returns the object's type. 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.(*Label) color() color(*Label) order() uint32(*Label) sameId(pkg *Package, name string, foldCase bool) bool(*Label) scopePos() token.Pos(*Label) setColor(color color)(*Label) setOrder(order uint32)(*Label) setParent(parent *Scope)(*Label) setScopePos(pos token.Pos)(*Label) setType(typ Type)
*Label : Object
*Label : expvar.Var
*Label : fmt.Stringer
*Label : positioner
*Label : context.stringer
*Label : github.com/aws/smithy-go/middleware.stringer
*Label : runtime.stringer
func NewLabel(pos token.Pos, pkg *Package, name string) *Label
A MethodSet is an ordered set of concrete or abstract (interface) methods;
a method is a [MethodVal] selection, and they are ordered by ascending m.Obj().Id().
The zero value for a MethodSet is a ready-to-use empty method set.list[]*Selection At returns the i'th method in s for 0 <= i < s.Len(). Len returns the number of methods in s. Lookup returns the method with matching package and name, or nil if not found. Methods returns a go1.23 iterator over the methods of a method set.
Example: for method := range s.Methods() { ... }(*MethodSet) String() string
*MethodSet : expvar.Var
*MethodSet : fmt.Stringer
*MethodSet : context.stringer
*MethodSet : github.com/aws/smithy-go/middleware.stringer
*MethodSet : runtime.stringer
func NewMethodSet(T Type) *MethodSet
func golang.org/x/tools/go/types/typeutil.(*MethodSetCache).MethodSet(T Type) *MethodSet
var emptyMethodSet
A Named represents a named (defined) type.
A declaration such as:
type S struct { ... }
creates a defined type whose underlying type is a struct,
and binds this type to the object S, a [TypeName].
Use [Named.Underlying] to access the underlying type.
Use [Named.Obj] to obtain the object S.
Before type aliases (Go 1.9), the spec called defined types "named types". // non-nil during type-checking; nil otherwise fromRHS holds the type (on RHS of declaration) this *Named type is derived
from (for cycle reporting). Only used by validType, and therefore does not
require synchronization. information for instantiated types; nil otherwise loader may be provided to lazily load type parameters, underlying type, and methods. methods declared for this type (not the method set of this type)
Signatures are type-checked lazily.
For non-instantiated types, this is a fully populated list of methods. For
instantiated types, methods are individually expanded when they are first
accessed. // guards all fields below // corresponding declared object for declared types; see above for instantiated types // the current state of this type; must only be accessed atomically // type parameters, or nil // possibly a *Named during setup; never a *Named once set up completely 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. 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. Methods returns a go1.23 iterator over the declared methods of a named type.
Example: for m := range t.Methods() { ... } NumMethods returns the number of explicit methods defined for t. 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. Origin returns the generic type from which the named type t is
instantiated. If t is not an instantiated type, the result is t. SetTypeParams sets the type parameters of the named type t.
t must not have type arguments. SetUnderlying sets the underlying type and marks t as complete.
t must not have type arguments.(*Named) String() string TypeArgs returns the type arguments used to instantiate the named type t. 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. 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.(*Named) cleanup() expandMethod substitutes type arguments in the i'th method for an
instantiated receiver. expandUnderlying substitutes type arguments in the underlying type n.orig,
returning the result. Returns Typ[Invalid] if there was an error.(*Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) 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. 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. setState atomically stores the given state for n.
Must only be called while holding n.mu. state atomically accesses the current state of the receiver. 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.
*Named : Type
*Named : expvar.Var
*Named : fmt.Stringer
*Named : golang.org/x/tools/internal/typesinternal.NamedOrAlias
*Named : cleaner
*Named : genericType
*Named : context.stringer
*Named : github.com/aws/smithy-go/middleware.stringer
*Named : runtime.stringer
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
func (*Interface).Embedded(i int) *Named
func (*Named).Origin() *Named
func golang.org/x/tools/internal/typesinternal.ReceiverNamed(recv *Var) (isPtr bool, named *Named)
func asNamed(t Type) *Named
func (*Checker).newNamed(obj *TypeName, underlying Type, methods []*Func) *Named
func (*Checker).newNamedInstance(pos token.Pos, orig *Named, targs []Type, expanding *Named) *Named
func (*Named).resolve() *Named
func golang.org/x/exp/apidiff.receiverNamedType(method Object) *Named
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
func hasVarSize(t Type, seen map[*Named]bool) (varSized bool)
func identicalOrigin(x, y *Named) bool
func makeObjList(tlist []*Named) []Object
func (*Checker).checkFieldUniqueness(base *Named)
func (*Checker).instance(pos token.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type)
func (*Checker).newAliasInstance(pos token.Pos, orig *Alias, targs []Type, expanding *Named, ctxt *Context) *Alias
func (*Checker).newNamedInstance(pos token.Pos, orig *Named, targs []Type, expanding *Named) *Named
func (*Checker).newNamedInstance(pos token.Pos, orig *Named, targs []Type, expanding *Named) *Named
func (*Checker).subst(pos token.Pos, typ Type, smap substMap, expanding *Named, ctxt *Context) Type
func (*Checker).validType(typ *Named)
func (*Checker).validType0(pos token.Pos, typ Type, nest, path []*Named) bool
func golang.org/x/tools/go/types/typeutil.(*MethodSetCache).lookupNamed(named *Named) struct{value, pointer *MethodSet}
func golang.org/x/tools/internal/gcimporter.canReuse(def *Named, rhs Type) bool
Nil represents the predeclared value nil.objectobjectobject.color_colorobject.namestringobject.order_uint32object.parent*Scopeobject.pkg*Packageobject.postoken.Posobject.scopePos_token.Posobject.typType 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Nil) String() string Type returns the object's type. 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.(*Nil) color() color(*Nil) order() uint32(*Nil) sameId(pkg *Package, name string, foldCase bool) bool(*Nil) scopePos() token.Pos(*Nil) setColor(color color)(*Nil) setOrder(order uint32)(*Nil) setParent(parent *Scope)(*Nil) setScopePos(pos token.Pos)(*Nil) setType(typ Type)
*Nil : Object
*Nil : expvar.Var
*Nil : fmt.Stringer
*Nil : positioner
*Nil : context.stringer
*Nil : github.com/aws/smithy-go/middleware.stringer
*Nil : runtime.stringer
A PkgName represents an imported Go package.
PkgNames don't have a type.imported*Packageobjectobjectobject.color_colorobject.namestringobject.order_uint32object.parent*Scopeobject.pkg*Packageobject.postoken.Posobject.scopePos_token.Posobject.typType 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Imported returns the package that was imported.
It is distinct from Pkg(), which is the package containing the import statement. Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*PkgName) String() string Type returns the object's type. 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.(*PkgName) color() color(*PkgName) order() uint32(*PkgName) sameId(pkg *Package, name string, foldCase bool) bool(*PkgName) scopePos() token.Pos(*PkgName) setColor(color color)(*PkgName) setOrder(order uint32)(*PkgName) setParent(parent *Scope)(*PkgName) setScopePos(pos token.Pos)(*PkgName) setType(typ Type)
*PkgName : Object
*PkgName : expvar.Var
*PkgName : fmt.Stringer
*PkgName : positioner
*PkgName : context.stringer
*PkgName : github.com/aws/smithy-go/middleware.stringer
*PkgName : runtime.stringer
func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName
func (*Info).PkgNameOf(imp *ast.ImportSpec) *PkgName
func (*Checker).errorUnusedPkg(obj *PkgName)
A Pointer represents a pointer type. // element type Elem returns the element type for the given pointer p.(*Pointer) String() string(*Pointer) Underlying() Type
*Pointer : Type
*Pointer : expvar.Var
*Pointer : fmt.Stringer
*Pointer : context.stringer
*Pointer : github.com/aws/smithy-go/middleware.stringer
*Pointer : runtime.stringer
func NewPointer(elem Type) *Pointer
A Scope maintains a set of objects and links to its containing
(parent) and contained (children) scopes. Objects may be inserted
and looked up by name. The zero value for Scope is a ready-to-use
empty scope.children[]*Scope // for debugging only // lazily allocated // scope extent; may be invalid // set if this is a function scope (internal use only) // parent.children[number-1] is this scope; 0 if there is no parentparent*Scope // scope extent; may be invalid Child returns the i'th child scope for 0 <= i < NumChildren(). Children returns a go1.23 iterator over the child scopes nested within scope s.
Example: for child := range scope.Children() { ... } Contains reports whether pos is within the scope's extent.
The result is guaranteed to be valid only if the type-checked
AST has complete position information.(*Scope) End() token.Pos Innermost returns the innermost (child) scope containing
pos. If pos is not within any scope, the result is nil.
The result is also nil for the Universe scope.
The result is guaranteed to be valid only if the type-checked
AST has complete position information. 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. Len returns the number of scope elements. Lookup returns the object in scope s with the given name if such an
object exists; otherwise the result is nil. LookupParent follows the parent chain of scopes starting with s until
it finds a scope where Lookup(name) returns a non-nil object, and then
returns that scope and object. If a valid position pos is provided,
only objects that were declared at or before pos are considered.
If no such scope and object exists, the result is (nil, nil).
The results are guaranteed to be valid only if the type-checked
AST has complete position information.
Note that obj.Parent() may be different from the returned scope if the
object was inserted into the scope and already had a parent at that
time (see Insert). This can only happen for dot-imported objects
whose parent is the scope of the package that exported them. Names returns the scope's element names in sorted order. NumChildren returns the number of scopes nested in s. Parent returns the scope's containing (parent) scope. Pos and End describe the scope's source code extent [pos, end).
The results are guaranteed to be valid only if the type-checked
AST has complete position information. The extent is undefined
for Universe and package scopes. String returns a string representation of the scope, for debugging. 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. 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.(*Scope) insert(name string, obj Object)
*Scope : go/ast.Node
*Scope : expvar.Var
*Scope : fmt.Stringer
*Scope : positioner
*Scope : context.stringer
*Scope : github.com/aws/smithy-go/middleware.stringer
*Scope : runtime.stringer
func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope
func (*Func).Scope() *Scope
func Object.Parent() *Scope
func (*Package).Scope() *Scope
func (*Scope).Child(i int) *Scope
func (*Scope).Innermost(pos token.Pos) *Scope
func (*Scope).LookupParent(name string, pos token.Pos) (*Scope, Object)
func (*Scope).Parent() *Scope
func golang.org/x/tools/internal/gcimporter.pkgScope(pkg *Package) *Scope
func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope
func (*Checker).blockBranches(all *Scope, parent *block, lstmt *ast.LabeledStmt, list []ast.Stmt) []*ast.BranchStmt
func (*Checker).declare(scope *Scope, id *ast.Ident, obj Object, pos token.Pos)
func (*Checker).recordScope(node ast.Node, scope *Scope)
func (*Checker).usage(scope *Scope)
func golang.org/x/tools/go/types/objectpath.(*Encoder).scopeObjects(scope *Scope) []Object
var Universe *Scope
A Selection describes a selector expression x.f.
For the declarations:
type T struct{ x int; E }
type E struct{}
func (e E) m() {}
var p *T
the following relations exist:
Selector Kind Recv Obj Type Index Indirect
p.x FieldVal T x int {0} true
p.m MethodVal *T m func() {1, 0} true
T.m MethodExpr T m func(T) {1, 0} false // path from x to x.f // set if there was any pointer indirection on the pathkindSelectionKind // object denoted by x.f // type of x 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. 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. Kind returns the selection kind. Obj returns the object denoted by x.f; a *Var for
a field selection, and a *Func in all other cases. Recv returns the type of x in x.f.(*Selection) String() string Type returns the type of x.f, which may be different from the type of f.
See Selection for more information.
*Selection : expvar.Var
*Selection : fmt.Stringer
*Selection : context.stringer
*Selection : github.com/aws/smithy-go/middleware.stringer
*Selection : runtime.stringer
func (*MethodSet).At(i int) *Selection
func (*MethodSet).Lookup(pkg *Package, name string) *Selection
func golang.org/x/tools/go/types/typeutil.IntuitiveMethodSet(T Type, msets *typeutil.MethodSetCache) []*Selection
func SelectionString(s *Selection, qf Qualifier) string
SelectionKind describes the kind of a selector expression x.f
(excluding qualified identifiers).
If x is a struct or *struct, a selector expression x.f may denote a
sequence of selection operations x.a.b.c.f. The SelectionKind
describes the kind of the final (explicit) operation; all the
previous (implicit) operations are always field selections.
Each element of Indices specifies an implicit field (a, b, c)
by its index in the struct type of the field selection operand.
For a FieldVal operation, the final selection refers to the field
specified by Selection.Obj.
For a MethodVal operation, the final selection refers to a method.
If the "pointerness" of the method's declared receiver does not
match that of the effective receiver after implicit field
selection, then an & or * operation is implicitly applied to the
receiver variable or value.
So, x.f denotes (&x.a.b.c).f when f requires a pointer receiver but
x.a.b.c is a non-pointer variable; and it denotes (*x.a.b.c).f when
f requires a non-pointer receiver but x.a.b.c is a pointer value.
All pointer indirections, whether due to implicit or explicit field
selections or * operations inserted for "pointerness", panic if
applied to a nil pointer, so a method call x.f() may panic even
before the function call.
By contrast, a MethodExpr operation T.f is essentially equivalent
to a function literal of the form:
func(x T, args) (results) { return x.f(args) }
Consequently, any implicit field selections and * operations
inserted for "pointerness" are not evaluated until the function is
called, so a T.f or (*T).f expression never panics.
func (*Selection).Kind() SelectionKind
func (*Checker).recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool)
const FieldVal
const MethodExpr
const MethodVal
A Signature represents a (non-builtin) function or method type.
The receiver is ignored when comparing signatures for identity. // (incoming) parameters from left to right; or nil // nil if not a method // (outgoing) results from left to right; or nil We need to keep the scope in Signature (rather than passing it around
and store it in the Func Object) because when type-checking a function
literal we call the general type checker which returns a general Type.
We then unpack the *Signature and use the scope for the literal body. // receiver type parameters from left to right, or nil // function scope for package-local and non-instantiated signatures; nil otherwise // type parameters from left to right, or nil // true if the last parameter's type is of the form ...T (or string, for append built-in only) Params returns the parameters of signature s, or nil. 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. RecvTypeParams returns the receiver type parameters of signature s, or nil. Results returns the results of signature s, or nil.(*Signature) String() string TypeParams returns the type parameters of signature s, or nil.(*Signature) Underlying() Type Variadic reports whether the signature s is variadic.
*Signature : Type
*Signature : expvar.Var
*Signature : fmt.Stringer
*Signature : genericType
*Signature : context.stringer
*Signature : github.com/aws/smithy-go/middleware.stringer
*Signature : runtime.stringer
func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
func (*Func).Signature() *Signature
func makeSig(res Type, args ...Type) *Signature
func (*Checker).arguments(call *ast.CallExpr, sig *Signature, targs []Type, xlist []ast.Expr, args []*operand, atargs [][]Type, atxlist [][]ast.Expr) (rsig *Signature)
func (*Checker).instantiateSignature(pos token.Pos, expr ast.Expr, typ *Signature, targs []Type, xlist []ast.Expr) (res *Signature)
func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func
func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
func (*Checker).arguments(call *ast.CallExpr, sig *Signature, targs []Type, xlist []ast.Expr, args []*operand, atargs [][]Type, atxlist [][]ast.Expr) (rsig *Signature)
func (*Checker).funcBody(decl *declInfo, name string, sig *Signature, body *ast.BlockStmt, iota constant.Value)
func (*Checker).funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType)
func (*Checker).instantiateSignature(pos token.Pos, expr ast.Expr, typ *Signature, targs []Type, xlist []ast.Expr) (res *Signature)
func (*Checker).recordBuiltinType(f ast.Expr, sig *Signature)
Sizes defines the sizing functions for package unsafe. Alignof returns the alignment of a variable of type T.
Alignof must implement the alignment guarantees required by the spec.
The result must be >= 1. Offsetsof returns the offsets of the given struct fields, in bytes.
Offsetsof must implement the offset guarantees required by the spec.
A negative entry in the result indicates that the struct is too large. Sizeof returns the size of a variable of type T.
Sizeof must implement the size guarantees required by the spec.
A negative result indicates that T is too large.
*StdSizes
*gcSizes
func SizesFor(compiler, arch string) Sizes
var stdSizes
StdSizes is a convenience type for creating commonly used Sizes.
It makes the following simplifying assumptions:
- The size of explicitly sized basic types (int16, etc.) is the
specified size.
- The size of strings and interfaces is 2*WordSize.
- The size of slices is 3*WordSize.
- The size of an array of n elements corresponds to the size of
a struct of n consecutive fields of the array's element type.
- The size of a struct is the offset of the last field plus that
field's size. As with all element types, if the struct is used
in an array its size must first be aligned to a multiple of the
struct's alignment.
- All other types have size WordSize.
- Arrays and structs are aligned per spec definition; all other
types are naturally aligned with a maximum alignment MaxAlign.
*StdSizes implements Sizes. // maximum alignment in bytes - must be >= 1 // word size in bytes - must be >= 4 (32bits)(*StdSizes) Alignof(T Type) (result int64)(*StdSizes) Offsetsof(fields []*Var) []int64(*StdSizes) Sizeof(T Type) int64
*StdSizes : Sizes
A Struct represents a struct type. // fields != nil indicates the struct is set up (possibly with len(fields) == 0) // field tags; nil if there are no tags Field returns the i'th field for 0 <= i < NumFields(). Fields returns a go1.23 iterator over the fields of a struct type.
Example: for field := range s.Fields() { ... } NumFields returns the number of fields in the struct (including blank and embedded fields).(*Struct) String() string Tag returns the i'th field tag for 0 <= i < NumFields().(*Struct) Underlying() Type(*Struct) markComplete()
*Struct : Type
*Struct : expvar.Var
*Struct : fmt.Stringer
*Struct : context.stringer
*Struct : github.com/aws/smithy-go/middleware.stringer
*Struct : runtime.stringer
func NewStruct(fields []*Var, tags []string) *Struct
func hasInvalidEmbeddedFields(T Type, seen map[*Struct]bool) bool
func (*Checker).structType(styp *Struct, e *ast.StructType)
func (*Config).offsetsof(T *Struct) []int64
func golang.org/x/exp/apidiff.contains(ts []*Struct, t *Struct) bool
func golang.org/x/exp/apidiff.contains(ts []*Struct, t *Struct) bool
func golang.org/x/exp/apidiff.exportedFields(s *Struct) map[string]Object
func golang.org/x/exp/apidiff.exportedSelectableFields(s *Struct) map[string]Object
func golang.org/x/exp/apidiff.unambiguousFields(structs []*Struct) map[string]*Var
TypeAndValue reports the type and value (for constants)
of the corresponding expression.TypeTypeValueconstant.ValuemodeoperandMode Addressable reports whether the corresponding expression
is addressable (https://golang.org/ref/spec#Address_operators). Assignable reports whether the corresponding expression
is assignable to (provided a value of the right type). HasOk reports whether the corresponding expression may be
used on the rhs of a comma-ok assignment. IsBuiltin reports whether the corresponding expression denotes
a (possibly parenthesized) built-in function. IsNil reports whether the corresponding expression denotes the
predeclared value nil. IsType reports whether the corresponding expression specifies a type. IsValue reports whether the corresponding expression is a value.
Builtins are not considered values. Constant values have a non-
nil Value. IsVoid reports whether the corresponding expression
is a function call without results.
func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)
TypeList holds a list of types.types[]Type At returns the i'th type in the list. Len returns the number of types in the list.
It is safe to call on a nil receiver. Types returns a go1.23 iterator over the elements of a list of types.
Example: for t := range l.Types() { ... } 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 (*Alias).TypeArgs() *TypeList
func (*Named).TypeArgs() *TypeList
func golang.org/x/tools/internal/aliases.TypeArgs(alias *Alias) *TypeList
func golang.org/x/tools/internal/typesinternal.NamedOrAlias.TypeArgs() *TypeList
func newTypeList(list []Type) *TypeList
A TypeParam represents the type of a type parameter in a generic declaration.
A TypeParam has a name; use the [TypeParam.Obj] method to access
its [TypeName] object. // any type, but underlying is eventually *Interface for correct programs (see TypeParam.iface) // for lazy type bound completion // unique id, for debugging only // type parameter index in source order, starting at 0 // corresponding type name Constraint returns the type constraint specified for t. 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. Obj returns the type name for the type parameter t. 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.(*TypeParam) String() string 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.(*TypeParam) cleanup() iface returns the constraint interface of t. 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). 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.
*TypeParam : Type
*TypeParam : expvar.Var
*TypeParam : fmt.Stringer
*TypeParam : cleaner
*TypeParam : context.stringer
*TypeParam : github.com/aws/smithy-go/middleware.stringer
*TypeParam : runtime.stringer
func NewTypeParam(obj *TypeName, constraint Type) *TypeParam
func (*TypeParamList).At(i int) *TypeParam
func (*Checker).declareTypeParam(name *ast.Ident, scopePos token.Pos) *TypeParam
func (*Checker).newTypeParam(obj *TypeName, constraint Type) *TypeParam
func (*Checker).renameTParams(pos token.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type)
func (*TypeParamList).list() []*TypeParam
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
func (*Alias).SetTypeParams(tparams []*TypeParam)
func (*Named).SetTypeParams(tparams []*TypeParam)
func golang.org/x/tools/internal/aliases.NewAlias(enabled bool, pos token.Pos, pkg *Package, name string, rhs Type, tparams []*TypeParam) *TypeName
func golang.org/x/tools/internal/aliases.SetTypeParams(alias *Alias, tparams []*TypeParam)
func golang.org/x/tools/internal/typeparams.StructuralTerms(tparam *TypeParam) ([]*Term, error)
func golang.org/x/tools/internal/typesinternal.NamedOrAlias.SetTypeParams(tparams []*TypeParam)
func badlinkname_Checker_infer(*Checker, positioner, []*TypeParam, []Type, *Tuple, []*operand, bool, *error_) []Type
func bindTParams(list []*TypeParam) *TypeParamList
func coreTerm(tpar *TypeParam) (*term, bool)
func isParameterized(tparams []*TypeParam, typ Type) bool
func killCycles(tparams []*TypeParam, inferred []Type)
func makeRenameMap(from, to []*TypeParam) substMap
func makeSubstMap(tpars []*TypeParam, targs []Type) substMap
func newUnifier(tparams []*TypeParam, targs []Type, enableInterfaceInference bool) *unifier
func typeParamsString(list []*TypeParam) string
func (*Checker).infer(posn positioner, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand, reverse bool, err *error_) (inferred []Type)
func (*Checker).renameTParams(pos token.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type)
func (*Checker).verify(pos token.Pos, tparams []*TypeParam, targs []Type, ctxt *Context) (int, error)
func golang.org/x/tools/internal/gcimporter.tparamExportName(prefix string, tparam *TypeParam) string
TypeParamList holds a list of type parameters.tparams[]*TypeParam At returns the i'th type parameter in the list. Len returns the number of type parameters in the list.
It is safe to call on a nil receiver. TypeParams returns a go1.23 iterator over a list of type parameters.
Example: for tparam := range l.TypeParams() { ... } 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 (*Alias).TypeParams() *TypeParamList
func (*Named).TypeParams() *TypeParamList
func (*Signature).RecvTypeParams() *TypeParamList
func (*Signature).TypeParams() *TypeParamList
func golang.org/x/tools/internal/aliases.TypeParams(alias *Alias) *TypeParamList
func golang.org/x/tools/internal/typesinternal.NamedOrAlias.TypeParams() *TypeParamList
func bindTParams(list []*TypeParam) *TypeParamList
func (*Checker).collectRecv(rparam *ast.Field, scopePos token.Pos) (*Var, *TypeParamList)
func (*Checker).collectTypeParams(dst **TypeParamList, list *ast.FieldList)
func golang.org/x/exp/apidiff.typeParamListsMatch(tps1, tps2 *TypeParamList) bool
func golang.org/x/tools/go/types/objectpath.findTypeParam(obj Object, list *TypeParamList, path []byte, op byte) []byte
A _TypeSet represents the type set of an interface.
Because of existing language restrictions, methods can be "factored out"
from the terms. The actual type set is the intersection of the type set
implied by the methods and the type set described by the terms and the
comparable bit. To test whether a type is included in a type set
("implements" relation), the type must implement all methods _and_ be
an element of the type set described by the terms and the comparable bit.
If the term list describes the set of all types and comparable is true,
only comparable types are meant; in all other cases comparable is false. // invariant: !comparable || terms.isAll() // all methods of the interface; sorted by unique ID // type terms of the type set IsAll reports whether s is the set of all types (corresponding to the empty interface). IsComparable reports whether each type in the set is comparable. IsEmpty reports whether s is the empty set. IsMethodSet reports whether the interface t is fully described by its method set. LookupMethod returns the index of and method with matching package and name, or (-1, nil). Method returns the i'th method of s for 0 <= i < s.NumMethods().
The methods are ordered by their unique ID. NumMethods returns the number of methods available.(*_TypeSet) String() string hasTerms reports whether s has specific type terms. 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). subsetOf reports whether s1 ⊆ s2. 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.
*_TypeSet : expvar.Var
*_TypeSet : fmt.Stringer
*_TypeSet : context.stringer
*_TypeSet : github.com/aws/smithy-go/middleware.stringer
*_TypeSet : runtime.stringer
func computeInterfaceTypeSet(check *Checker, pos token.Pos, ityp *Interface) *_TypeSet
func computeUnionTypeSet(check *Checker, unionSets map[*Union]*_TypeSet, pos token.Pos, utyp *Union) *_TypeSet
func (*Interface).typeSet() *_TypeSet
func computeUnionTypeSet(check *Checker, unionSets map[*Union]*_TypeSet, pos token.Pos, utyp *Union) *_TypeSet
var invalidTypeSet
var topTypeSet
An action describes a (delayed) action. // action description; may be nil, requires debug to be set // action to be executed // applicable language version If debug is set, describef sets a printf-formatted description for action a.
Otherwise, it is a no-op.
func (*Checker).later(f func()) *action
atPos wraps a token.Pos to implement the positioner interface.( atPos) Pos() token.Pos
atPos : positioner
var noposn
A bailout panic is used for early termination.
A block tracks label declarations in a block and its enclosing blocks. // allocated lazily // labeled statement to which this block belongs, or nil // enclosing block enclosingTarget returns the innermost enclosing labeled
statement with the given label name, or nil. gotoTarget returns the labeled statement in the current
or an enclosing block with the given label name, or nil. insert records a new label declaration for the current block.
The label must not have been declared before in any block.
func (*Checker).blockBranches(all *Scope, parent *block, lstmt *ast.LabeledStmt, list []ast.Stmt) []*ast.BranchStmt
color encodes the color of an object (see Checker.objDecl for details).( color) String() string
color : expvar.Var
color : fmt.Stringer
color : context.stringer
color : github.com/aws/smithy-go/middleware.stringer
color : runtime.stringer
func colorFor(t Type) color
const black
const grey
const white
A comparer is used to compare types. // if set, identical treats an invalid type as identical to any type // if set, identical ignores struct tags For changes to this code the corresponding changes should be made to unifier.nify.
A declInfo describes a package-level const, type, var, or func declaration. The deps field tracks initialization expression dependencies. // lazily initialized // func declaration, or nil // scope of file containing this declaration // if set, the init expression is inherited from a previous constant declaration // init/orig expression, or nil (for const and var declarations only) // lhs of n:1 variable declarations, or nil // type declaration, or nil // Go version of file containing this declaration // type, or nil (for const and var declarations only) addDep adds obj to the set of objects d's init expression depends on. hasInitializer reports whether the declared object has an initialization
expression or function body.
func dependencyGraph(objMap map[Object]*declInfo) []*graphNode
func findPath(objMap map[Object]*declInfo, from, to Object, seen map[Object]bool) []Object
func (*Checker).declarePkgObj(ident *ast.Ident, obj Object, d *declInfo)
func (*Checker).funcBody(decl *declInfo, name string, sig *Signature, body *ast.BlockStmt, iota constant.Value)
func (*Checker).funcDecl(obj *Func, decl *declInfo)
A dependency is an object that may be a dependency in an initialization
expression. Only constants, variables, and functions can be dependencies.
Constants are here because constant expression cycles are reported during
initialization order computation. // reports whether the name starts with a capital letter // object name if exported, qualified name if not exported (see func Id) // package local object name // scope in which this object is declared; nil for methods and struct fields // package to which this object belongs; nil for labels and objects in the Universe scope // position of object identifier in declaration String returns a human-readable string of the object.
Use [ObjectString] to control how package names are formatted in the string. // object type color returns the object's color.( dependency) isDependency() order reflects a package-level object's source order: if object
a is before object b in the source, then a.order() < b.order().
order returns a value > 0 for package-level objects; it returns
0 for all other objects (including objects in file scopes). sameId reports whether obj.Id() and Id(pkg, name) are the same.
If foldCase is true, names are considered equal if they are equal with case folding
and their packages are ignored (e.g., pkg1.m, pkg1.M, pkg2.m, and pkg2.M are all equal). scopePos returns the start position of the scope of this Object setColor sets the object's color. It must not be white. setOrder sets the order number of the object. It must be > 0. setParent sets the parent scope of the object. setScopePos sets the start position of the scope for this Object. setType sets the type of the object.
*Const
*Func
*Var
dependency : Object
dependency : expvar.Var
dependency : fmt.Stringer
dependency : positioner
dependency : context.stringer
dependency : github.com/aws/smithy-go/middleware.stringer
dependency : runtime.stringer
A dotImportKey describes a dot-imported object in the given scope.namestringscope*Scope
embeddedType represents an embedded type // embedded field indices, starting with index at depth 0 // if set, there was a pointer indirection on the path to this field // if set, typ appears multiple times at this depthtypType
func consolidateMultiples(list []embeddedType) []embeddedType
func consolidateMultiples(list []embeddedType) []embeddedType
An environment represents the environment within which an object is
type-checked. // package-level declaration whose init expression/function body is checked // if set, identifier position of a constant with inherited initializer go/types only // if valid, identifiers are looked up as if at position pos (used by CheckExpr, Eval) // set if an expression contains a function call or channel receive operation // set if a function makes use of labels (only ~1% of functions); unused outside functions // set if inside a type parameter list // value of iota in a constant declaration; nil otherwise // set of panic call expressions (used for termination check) // top-most scope for lookups // function signature if inside a function; nil otherwise // current accepted language version; changes across files lookup is like lookupScope but it only returns the object (or nil). 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.
An error_ represents a type-checking error.
A new error_ is created with Checker.newError.
To report an error_, call error_.report.check*CheckercodeCodedesc[]errorDesc // TODO(gri) eventually determine this from an error code addAltDecl is a specialized form of addf reporting another declaration of obj. 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).(*error_) empty() bool msg returns the formatted error message without the primary error position pos().(*error_) posn() positioner report reports the error err, setting check.firstError if necessary.
func (*Checker).newError(code Code) *error_
func badlinkname_Checker_infer(*Checker, positioner, []*TypeParam, []Type, *Tuple, []*operand, bool, *error_) []Type
func (*Checker).infer(posn positioner, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand, reverse bool, err *error_) (inferred []Type)
exprInfo stores information about an untyped expression. // expression is lhs operand of a shift with delayed type-checkmodeoperandModetyp*Basic // constant value; or nil (if not a constant)
A genericType implements access to its type parameters. String returns a string representation of a type.( genericType) TypeParams() *TypeParamList Underlying returns the underlying type of a type.
Underlying types are never Named, TypeParam, or Alias types.
See https://go.dev/ref/spec#Underlying_types.
*Alias
*Named
*Signature
golang.org/x/tools/internal/typesinternal.NamedOrAlias(interface)
genericType : Type
genericType : expvar.Var
genericType : fmt.Stringer
genericType : context.stringer
genericType : github.com/aws/smithy-go/middleware.stringer
genericType : runtime.stringer
func (*Checker).instance(pos token.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type)
A graphNode represents a node in the object dependency graph.
Each node p in n.pred represents an edge p->n, and each node
s in n.succ represents an edge n->s; with a->b indicating that
a depends on b. // node index in graph slice/priority queue // number of outstanding dependencies before this object can be initialized // object represented by this node // consumers and dependencies of this node (lazily initialized) // consumers and dependencies of this node (lazily initialized) cost returns the cost of removing this node, which involves copying each
predecessor to each successor (and vice-versa).
func dependencyGraph(objMap map[Object]*declInfo) []*graphNode
An ifacePair is a node in a stack of interface type pairs compared for identity.prev*ifacePairx*Interfacey*Interface(*ifacePair) identical(q *ifacePair) bool
An importKey identifies an imported package by import path and source directory
(directory containing the file containing the import). In practice, the directory
may always be the same, or may not matter. Given an (import path, directory), an
importer must always return the same package (but given two different import paths,
an importer may still return the same package by mapping them to the same package
paths).dirstringpathstring
indexedExpr wraps an ast.IndexExpr or ast.IndexListExpr.
Orig holds the original ast.Expr from which this indexedExpr was derived.
Note: indexedExpr (intentionally) does not wrap ast.Expr, as that leads to
accidental misuse such as encountered in golang/go#63933.
TODO(rfindley): remove this helper, in favor of just having a helper
function that returns indices. // index expressions // position of "[" // the wrapped expr, which may be distinct from the IndexListExpr below. // position of "]" // expression(*indexedExpr) Pos() token.Pos
*indexedExpr : positioner
func unpackIndexedExpr(n ast.Node) *indexedExpr
func (*Checker).funcInst(T *target, pos token.Pos, x *operand, ix *indexedExpr, infer bool) ([]Type, []ast.Expr)
func (*Checker).indexExpr(x *operand, e *indexedExpr) (isFuncInst bool)
func (*Checker).instantiatedType(ix *indexedExpr, def *TypeName) (res Type)
func (*Checker).singleIndex(expr *indexedExpr) ast.Expr
instance holds information that is only necessary for instantiated named
types. // local Context; set to nil after full expansion // number of expanded methods; expandedMethods <= len(orig.methods) // original, uninstantiated type // type arguments
buf is used to avoid allocating the map m in the common case of a small
number of instances.mmap[*Named][]*Named(*instanceLookup) add(inst *Named)(*instanceLookup) lookup(inst *Named) *Named
A methodSet is a set of methods and name collisions.
A collision indicates that multiple methods with the
same unique id, or a field with that id appeared. Add adds all functions in list to the method set s.
If multiples is set, every function in list appears multiple times
and is treated as a collision.( methodSet) addOne(f *Func, index []int, indirect bool, multiples bool) methodSet
canon maps method receiver type parameters to their respective
receiver type's type parameters.edges[]monoEdge nameIdx maps a defined type or (canonical) type parameter to its
vertex index.vertices[]monoVertex(*monoGraph) addEdge(dst, src, weight int, pos token.Pos, typ Type) assign records that tpar was instantiated as targ at pos. localNamedVertex returns the index of the vertex representing
named, or -1 if named doesn't need representation. recordCanon records that tpar is the canonical type parameter
corresponding to method type parameter mpar. recordInstance records that the given type parameters were
instantiated with the corresponding type arguments. typeParamVertex returns the index of the vertex representing tpar.
// length of the above path obj is the defined type or type parameter represented by this
vertex. // previous edge (if any) in the above path // weight of heaviest known path to this vertex
An object implements the common parts of an Object.color_colornamestringorder_uint32parent*Scopepkg*Packagepostoken.PosscopePos_token.PostypType 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*object) String() string Type returns the object's type. 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.(*object) color() color(*object) order() uint32(*object) sameId(pkg *Package, name string, foldCase bool) bool(*object) scopePos() token.Pos(*object) setColor(color color)(*object) setOrder(order uint32)(*object) setParent(parent *Scope)(*object) setScopePos(pos token.Pos)(*object) setType(typ Type)
*object : Object
*object : expvar.Var
*object : fmt.Stringer
*object : positioner
*object : context.stringer
*object : github.com/aws/smithy-go/middleware.stringer
*object : runtime.stringer
An objset is a set of objects identified by their unique id.
The zero value for objset is a ready-to-use empty objset. 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 (*Checker).declareInSet(oset *objset, pos token.Pos, obj Object) bool
posSpan holds a position range along with a highlighted position within that
range. This is used for positioning errors, with pos by convention being the
first position in the source where the error is known to exist, and start
and end defining the full span of syntax being considered when the error was
detected. Invariant: start <= pos < end || start == pos == end.endtoken.Pospostoken.Posstarttoken.Pos( posSpan) Pos() token.Pos
posSpan : positioner
func inNode(node ast.Node, pos token.Pos) posSpan
func spanOf(at positioner) posSpan
// nil if called via Instantiatectxt*Context // if non-nil, the instance that is being expandedpostoken.PossmapsubstMap(*subster) func_(f *Func) *Func(*subster) term(t *Term) *Term(*subster) tuple(t *Tuple) *Tuple(*subster) typ(typ Type) Type 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.(*subster) var_(v *Var) *Var
A term describes elementary type sets:
∅: (*term)(nil) == ∅ // set of no types (empty set)
𝓤: &term{} == 𝓤 // set of all types (𝓤niverse)
T: &term{false, T} == {T} // set of type T
~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t // valid if typ != niltypType(*term) String() string disjoint reports whether x ∩ y == ∅.
x.typ and y.typ must not be nil. equal reports whether x and y represent the same type set. includes reports whether t ∈ x. intersect returns the intersection x ∩ y. subsetOf reports whether x ⊆ y. union returns the union x ∪ y: zero, one, or two non-nil terms.
*term : expvar.Var
*term : fmt.Stringer
*term : context.stringer
*term : github.com/aws/smithy-go/middleware.stringer
*term : runtime.stringer
func coreTerm(tpar *TypeParam) (*term, bool)
A termlist represents the type set represented by the union
t1 ∪ y2 ∪ ... tn of the type sets of the terms t1 to tn.
A termlist is in normal form if all terms are disjoint.
termlist operations don't require the operands to be in
normal form. String prints the termlist exactly (without normalization). equal reports whether xl and yl represent the same type set. includes reports whether t ∈ xl. intersect returns the intersection xl ∩ yl. isAll reports whether the termlist xl represents the set of all types. isEmpty reports whether the termlist xl represents the empty set of types. norm returns the normal form of xl. subsetOf reports whether xl ⊆ yl. supersetOf reports whether y ⊆ xl. union returns the union xl ∪ yl.
termlist : expvar.Var
termlist : fmt.Stringer
termlist : context.stringer
termlist : github.com/aws/smithy-go/middleware.stringer
termlist : runtime.stringer
func intersectTermLists(xterms termlist, xcomp bool, yterms termlist, ycomp bool) (termlist, bool)
func intersectTermLists(xterms termlist, xcomp bool, yterms termlist, ycomp bool) (termlist, bool)
func intersectTermLists(xterms termlist, xcomp bool, yterms termlist, ycomp bool) (termlist, bool)
var allTermlist
A unifier maintains a list of type parameters and
corresponding types inferred for each type parameter.
A unifier is created by calling newUnifier. // recursion depth during unification // use shared methods for better inference handles maps each type parameter to its inferred type through
an indirection *Type called (inferred type) "handle".
Initially, each type parameter has its own, separate handle,
with a nil (i.e., not yet inferred) type.
After a type parameter P is unified with a type parameter Q,
P and Q share the same handle (and thus type). This ensures
that inferring the type for a given type parameter P will
automatically infer the same type for all other parameters
unified (joined) with P. String returns a string representation of the current mapping
from type parameters to types. asBoundTypeParam returns x.(*TypeParam) if x is a type parameter recorded with u.
Otherwise, the result is nil. at returns the (possibly nil) type for type parameter x. 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. 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. 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. set sets the type t for type parameter x;
t must not be nil. setHandle sets the handle for type parameter x
(and all its joined type parameters) to h.(*unifier) tracef(format string, args ...interface{}) 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. unknowns returns the number of type parameters for which no type has been set yet.
*unifier : expvar.Var
*unifier : fmt.Stringer
*unifier : context.stringer
*unifier : github.com/aws/smithy-go/middleware.stringer
*unifier : runtime.stringer
func newUnifier(tparams []*TypeParam, targs []Type, enableInterfaceInference bool) *unifier
unifyMode controls the behavior of the unifier.( unifyMode) String() string
unifyMode : expvar.Var
unifyMode : fmt.Stringer
unifyMode : context.stringer
unifyMode : github.com/aws/smithy-go/middleware.stringer
unifyMode : runtime.stringer
const assign
const exact
A valueMap maps a case value (of a basic Go type) to a list of positions
where the same case value appeared, together with the corresponding case
types.
Since two case values may have the same "underlying" value but different
types we need to also check the value's types (e.g., byte(1) vs myByte(1))
when the switch expression is of interface type.
func (*Checker).caseValues(x *operand, values []ast.Expr, seen valueMap)
A valueMap maps a case value (of a basic Go type) to a list of positions
where the same case value appeared, together with the corresponding case
types.
Since two case values may have the same "underlying" value but different
types we need to also check the value's types (e.g., byte(1) vs myByte(1))
when the switch expression is of interface type.postoken.PostypType
Package-Level Functions (total 226, in which 56 are exported)
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
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.
CheckExpr type checks the expression expr as if it had appeared at position
pos of package pkg. [Type] information about the expression is recorded in
info. The expression may be an identifier denoting an uninstantiated generic
function or type.
If pkg == nil, the [Universe] scope is used and the provided
position pos is ignored. If pkg != nil, and pos is invalid,
the package scope is used. Otherwise, pos must belong to the
package.
An error is returned if pos is not within the package or
if the node cannot be type-checked.
Note: [Eval] and CheckExpr should not be used instead of running Check
to compute types and values, but in addition to Check, as these
functions ignore the context in which an expression is used (e.g., an
assignment). Thus, top-level untyped constants will return an
untyped type rather than the respective context-specific type.
Comparable reports whether values of type T are comparable.
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.
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.
DefPredeclaredTestFuncs defines the assert and trace built-ins.
These built-ins are intended for debugging and testing of this
package only.
Eval returns the type and, if constant, the value for the
expression expr, evaluated at position pos of package pkg,
which must have been derived from type-checking an AST with
complete position information relative to the provided file
set.
The meaning of the parameters fset, pkg, and pos is the
same as in [CheckExpr]. An error is returned if expr cannot
be parsed successfully, or the resulting expr AST cannot be
type-checked.
ExprString returns the (possibly shortened) string representation for x.
Shortened representations are suitable for user interfaces but may not
necessarily follow Go syntax.
Id returns name if it is exported, otherwise it
returns the name qualified with the package path.
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.
IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored.
Receivers of [Signature] types are ignored.
Implements reports whether type V implements interface T.
The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated
generic type.
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.
IsInterface reports whether t is an interface type.
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.
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).
NewAlias creates a new Alias type with the given type name and rhs.
rhs must not be nil.
NewArray returns a new array type for the given element type and length.
A negative length indicates an unknown length.
NewChan returns a new channel type for the given direction and element type.
NewChecker returns a new [Checker] instance for a given package.
[Package] files may be added incrementally via checker.Files.
NewConst returns a new constant with value val.
The remaining arguments set the attributes found with all Objects.
NewContext creates a new Context.
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.
NewFunc returns a new function with the given signature, representing
the function's type.
NewInterface returns a new interface for the given methods and embedded types.
NewInterface takes ownership of the provided methods and may modify their types
by setting missing receivers.
Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.
NewInterfaceType returns a new interface for the given methods and embedded
types. NewInterfaceType takes ownership of the provided methods and may
modify their types by setting missing receivers.
To avoid race conditions, the interface's type set should be computed before
concurrent use of the interface, by explicitly calling Complete.
NewLabel returns a new label.
NewMap returns a new map for the given key and element types.
NewMethodSet returns the method set for the given type T.
It always returns a non-nil method set, even if it is empty.
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.
NewPackage returns a new Package for the given package path and name.
The package is not complete and contains no explicit imports.
NewParam returns a new variable representing a function parameter.
NewPkgName returns a new PkgName object representing an imported package.
The remaining arguments set the attributes found with all Objects.
NewPointer returns a new pointer type for the given element (base) type.
NewScope returns a new, empty scope contained in the given parent
scope, if any. The comment is for debugging only.
NewSignature returns a new function type for the given receiver, parameters,
and results, either of which may be nil. If variadic is set, the function
is variadic, it must have at least one parameter, and the last parameter
must be of unnamed slice type.
Deprecated: Use [NewSignatureType] instead which allows for type parameters.
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.
NewSlice returns a new slice type for the given element type.
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.
NewTerm returns a new union term.
NewTuple returns a new tuple for the given variables.
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.
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.
NewUnion returns a new [Union] type with the given terms.
It is an error to create an empty union; they are syntactically not possible.
NewVar returns a new variable.
The arguments set the attributes found with all Objects.
ObjectString returns the string form of obj.
The Qualifier controls the printing of
package-level objects, and may be nil.
RelativeTo returns a [Qualifier] that fully qualifies members of
all packages other than pkg.
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.
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"
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".
TypeString returns the string representation of typ.
The [Qualifier] controls the printing of
package-level objects, and may be nil.
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.
WriteExpr writes the (possibly shortened) string representation for x to buf.
Shortened representations are suitable for user interfaces but may not
necessarily follow Go syntax.
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.
WriteType writes the string representation of typ to buf.
The [Qualifier] controls the printing of
package-level objects, and may be nil.
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.
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).
infer should be an internal detail,
but widely used packages access it using linkname.
Notable members of the hall of shame include:
- github.com/goplus/gox
Do not remove or change the type signature.
See go.dev/issue/67401.
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.
colorFor returns the (initial) color for an object depending on
whether its type t is known or not.
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.
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.
computeInterfaceTypeSet may be called with check == nil.
computeUnionTypeSet may be called with check == nil.
The result is &invalidTypeSet if the union overflows.
concat returns the result of concatenating list and i.
The result does not share its underlying array with list.
consolidateMultiples collects multiple list entries with the same type
into a single entry marked as containing multiples. The result is the
consolidated list.
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.
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).
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.
dddErrPos returns the positioner for reporting an invalid ... use in a call.
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.
dependencyGraph computes the object dependency graph from the given objMap,
with any function nodes removed. The resulting graph contains only constants
and variables.
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).
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.
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.)
endPos returns the position of the first character immediately after node n.
fieldIndex returns the index for the field with matching package and name, or a value < 0.
See Object.sameId for the meaning of foldCase.
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.
firstInSrc reports the index of the object with the "smallest"
source position in path. path must not be empty.
flattenUnion walks a union type expression of the form A | B | C | ...,
extracting both the binary exprs (blist) and leaf types (tlist).
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.
goTypeName returns the Go type name for typ and
removes any occurrences of "types." from that name.
goVal returns the Go value for val, or nil.
hasBreak reports if s is or contains a break statement
referring to the label-ed statement or implicit-ly the
closest outer breakable statement.
hasDots reports whether the last argument in the call is followed by ...
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.
hasInvalidEmbeddedFields reports whether T is a struct (or a pointer to a struct) that contains
(directly or indirectly) embedded fields with invalid types.
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.
hasNil reports whether type t includes the nil value.
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.
identicalInstance reports if two type instantiations are identical.
Instantiations are identical if their origin and type arguments are
identical.
identicalOrigin reports whether x and y originated in the same declaration.
inNode creates a posSpan for the given node.
Invariant: node.Pos() <= pos < node.End() (node.End() is the position of the
first byte after node within the source).
instantiatedIdent determines the identifier of the type instantiated in expr.
Helper function for recordInstance in recording.go.
intersectTermLists computes the intersection of two term lists and respective comparable bits.
xcomp, ycomp are valid only if xterms.isAll() and yterms.isAll() respectively.
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.
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?
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).
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.
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.
isTypeParam reports whether t is a type parameter.
isUntyped(t) is the same as !isTyped(t).
Safe to call from types that are not fully set up.
isUntypedNumeric reports whether t is an untyped numeric type.
Safe to call from types that are not fully set up.
isValid reports whether t is a valid type.
isValidName reports whether s is a valid Go identifier.
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.
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.
lookupFieldOrMethod is like LookupFieldOrMethod but with the additional foldCase parameter
(see Object.sameId for the meaning of foldCase).
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.
makeFromLiteral returns the constant value for the given literal string and kind.
makeObjList returns the list of type name objects for the given
list of named types.
makeRenameMap is like makeSubstMap, but creates a map used to rename type
parameters in from with the type parameters in to.
makeSig makes a signature for the given argument and result types.
Default types are used for untyped arguments, and res may be nil.
makeSubstMap creates a new substitution map mapping tpars[i] to targs[i].
If targs[i] is nil, tpars[i] is not substituted.
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.
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.
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.
methodIndex returns the index of and method with matching package and name, or (-1, nil).
See Object.sameId for the meaning of foldCase.
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.
nextID returns a value increasing monotonically by 1 with
each call, starting with 1. It may be called concurrently.
Operand string formats
(not all "untyped" cases can appear due to the type system,
but they fall out naturally here)
mode format
invalid <expr> ( <mode> )
novalue <expr> ( <mode> )
builtin <expr> ( <mode> )
typexpr <expr> ( <mode> )
constant <expr> (<untyped kind> <mode> )
constant <expr> ( <mode> of type <typ>)
constant <expr> (<untyped kind> <mode> <val> )
constant <expr> ( <mode> <val> of type <typ>)
variable <expr> (<untyped kind> <mode> )
variable <expr> ( <mode> of type <typ>)
mapindex <expr> (<untyped kind> <mode> )
mapindex <expr> ( <mode> of type <typ>)
value <expr> (<untyped kind> <mode> )
value <expr> ( <mode> of type <typ>)
nilvalue untyped nil
nilvalue nil ( of type <typ>)
commaok <expr> (<untyped kind> <mode> )
commaok <expr> ( <mode> of type <typ>)
commaerr <expr> (<untyped kind> <mode> )
commaerr <expr> ( <mode> of type <typ>)
cgofunc <expr> (<untyped kind> <mode> )
cgofunc <expr> ( <mode> of type <typ>)
operandTypes returns the list of types for the given operands.
opName returns the name of the operation if x is an operation
that might overflow; otherwise it returns the empty string.
opPos returns the position of the operator if x is an operation;
otherwise it returns the start position of x.
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.
parseUnion parses uexpr as a union of expressions.
The result is a Union type, or Typ[Invalid] for some errors.
pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
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.
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.
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.
resolve returns the Object represented by obj, resolving lazy
objects as appropriate.
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.
samePkg reports whether packages a and b are the same.
spanOf extracts an error span from the given positioner. By default this is
the trivial span starting and ending at pos, but this span is expanded when
the argument naturally corresponds to a span of source code.
stripAnnotations removes internal (type) annotations from s.
subscript returns the decimal (utf8) representation of x using subscript digits.
Type Parameters:
T: comparable 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.
tail returns the string s without its first (UTF-8) character.
If len(s) == 0, the result is s.
typeParamsString produces a string containing all the type parameter names
in list suitable for human consumption.
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.
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.
If typ is a type parameter, underIs returns the result of typ.underIs(f).
Otherwise, underIs returns the result of f(under(typ)).
Package-Level Variables (total 44, in which 3 are exported)
Typ contains the predeclared *Basic types indexed by their
corresponding BasicKind.
The *Basic type for Typ[Byte] will have the name "uint8".
Use Universe.Lookup("byte").Type() to obtain the specific
alias basic type named "byte" (and analogous for "rune").
The Universe scope contains all predeclared objects of Go.
It is the outermost scope of any chain of nested scopes.
The Unsafe package is the package returned by an importer
for the import path "unsafe".
_aliasAny changes the behavior of [Scope.Lookup] for "any" in the
[Universe] scope.
This is necessary because while Alias creation is controlled by
[Config._EnableAlias], based on the gotypealias variable, the representation
of "any" is a global. In [Scope.Lookup], we select this global
representation based on the result of [aliasAny], but as a result need to
guard against this behavior changing during the type checking pass.
Therefore we implement the following rule: any number of goroutines can type
check concurrently with the same EnableAlias value, but if any goroutine
tries to type check concurrently with a different EnableAlias value, we
panic.
To achieve this, _aliasAny is a state machine:
0: no type checking is occurring
negative: type checking is occurring without _EnableAlias set
positive: type checking is occurring with _EnableAlias set
allTermlist represents the set of all types.
It is in normal form.
gotypesalias controls the use of Alias types.
As of Apr 16 2024 they are used by default.
To disable their use, set GODEBUG to gotypesalias=0.
This GODEBUG flag will be removed in the near future (tentatively Go 1.24).
invalidTypeSet is a singleton type set to signal an invalid type set
due to an error. It's also a valid empty type set, so consumers of
type sets may choose to ignore it.
Note: This is a uint32 rather than a uint64 because the
respective 64 bit atomic instructions are not available
on all platforms.
If enableCoreTypeUnification is set, unification will consider
the core types, if any, of non-local (unbound) type parameters.
If enableReverseTypeInference is set, uninstantiated and
partially instantiated generic functions may be assigned
(incl. returned) to variables of function type and type
inference will attempt to infer the missing type arguments.
Available with go1.21.
If exact is set, types unify if they are identical (or can be
made identical with suitable arguments for type parameters).
Otherwise, a named type and a type literal unify if their
underlying types unify, channel directions are ignored, and
if there is an interface, the other type must implement the
interface.
termSep is the separator used between individual terms.
If traceInference is set, unification will print a trace of its operation.
Interpretation of trace:
x ≡ y attempt to unify types x and y
p ➞ y type parameter p is set to type y (p is inferred to be y)
p ⇄ q type parameters p and q match (p is inferred to be q and vice versa)
x ≢ y types x and y cannot be unified
[p, q, ...] ➞ [x, y, ...] mapping from type parameters to types
Upper limit for recursion depth. Used to catch infinite recursions
due to implementation issues (e.g., see issues go.dev/issue/48619, go.dev/issue/48656).