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 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()
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 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, the identifier f in a selector
expression x.f is found only in the Selections map, the
identifier z in a variable declaration 'var z int' is found
only in the Defs map, and identifiers denoting packages in
qualified identifiers are collected in the Uses map.
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
// 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)
// if valid, identifiers are looked up as if at position pos (used by Eval)
// top-most scope for lookups
// function signature if inside a function; nil otherwise
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 encountered
fset*token.FileSet
// maps (import path, source directory) to (complete or fake) package
// list of imported packages
debugging
// indentation for tracing
// maps named types to their associated type info (for cycle detection)
// 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.
// maps blank receiver type parameters to their type
seenPkgMapmap[*Package]bool
// computed type sets for union types
// map of expressions without final type
// accepted language version
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, ObjectOf returns the field (*Var)
it defines, not the type (*TypeName) it uses.
Precondition: the Uses and Defs 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 given package
is allowed to use version major.minor.
applyTypeFunc applies f to x. If x is a type parameter,
the result is a type parameter constrained by an 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).
xlist is the list of type argument expressions supplied in the source code.
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.
It returns (nil, false) as affirmative answer. Otherwise it returns a missing
method required by V and whether it is missing or just has the wrong type.
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.
TODO(gri) replace calls to this function with calls to newAssertableTo.
(*Checker) assignError(rhs []ast.Expr, nvars, nvals int)(*Checker) assignVar(lhs ast.Expr, x *operand) Type(*Checker) assignVars(lhs, origRHS []ast.Expr)
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.
x.mode is set to invalid if the assignment failed.
bestContext returns the best available context. In order of preference:
- the given ctxt, if non-nil
- check.ctxt, if check is non-nil
- a new Context
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].
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
If the type switch expression is invalid, x is nil.
(*Checker) caseValues(x *operand, values []ast.Expr, seen valueMap)(*Checker) checkFieldUniqueness(base *Named)(*Checker) checkFiles(files []*ast.File) (err error)
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 declares the parameters of list in scope and returns the corresponding
variable list.
(*Checker) collectTypeParams(dst **TypeParamList, list *ast.FieldList)
If switchCase is true, the operator op is ignored.
(*Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool)
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 in cycle that is "first" in the source.
(*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
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) declareTypeParams(tparams []*TypeParam, names []*ast.Ident) []*TypeParam
definedType is like typ but also accepts a type name def.
If def != nil, e is the type specification for the defined type def, declared
in a type declaration, and def.underlying will be set to the type of e before
any components of e are type-checked.
dump is only needed for debugging
(*Checker) err(err error)(*Checker) error(at positioner, code errorCode, msg string)(*Checker) errorUnusedPkg(obj *PkgName)(*Checker) errorf(at positioner, code errorCode, 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.
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.
(*Checker) exprList(elist []ast.Expr, allowCommaOk bool) (xlist []*operand, commaOk bool)
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.
(*Checker) funcBody(decl *declInfo, name string, sig *Signature, body *ast.BlockStmt, iota constant.Value)(*Checker) funcDecl(obj *Func, decl *declInfo)
funcInst type-checks a function instantiation inst and returns the result in x.
The operand x must be the evaluation of inst.X and its type must be a signature.
check may be nil.
funcType type-checks a function or method type.
genericType is like typ but the type must be an (uninstantiated) generic
type. If reason is non-nil and the type expression was a valid type but not
generic, reason will be populated with a message describing the error.
(*Checker) handleBailout(err *error)
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 and reports an error if it doesn't.
The receiver may be nil if implements is called through an exported
API call such as AssignableTo.
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.
indexElts 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 successful, infer returns the complete list of type arguments, one for each type parameter.
Otherwise the result is nil and appropriate errors will be reported.
Inference proceeds as follows:
Starting with given type arguments
1) apply FTI (function type inference) with typed arguments,
2) apply CTI (constraint type inference),
3) apply FTI with untyped function arguments,
4) apply CTI.
The process stops as soon as all type arguments are known or an error occurs.
inferB returns the list of actual type arguments inferred from the type parameters'
bounds and an initial set of type arguments. If type inference is impossible because
unification fails, an error is reported if report is set to true, the resulting types
list is nil, and index is 0.
Otherwise, types is the list of inferred type arguments, and index is the index of the
first type argument in that list that couldn't be inferred (and thus is nil). If all
type arguments were inferred successfully, index is < 0. The number of type arguments
provided may be less than the number of type parameters, but there must be at least one.
(*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.
(*Checker) initVar(lhs *Var, x *operand, context string) Type
If returnStmt != nil, initVars is called to type-check the assignment
of return expressions, and returnStmt is the return statement.
instance creates a type or function instance using the given original type
typ and arguments targs. For Named types the resulting instance will be
unexpanded.
(*Checker) instantiateSignature(pos token.Pos, typ *Signature, targs []Type, xlist []ast.Expr) (res *Signature)(*Checker) instantiatedType(ix *typeparams.IndexExpr, def *Named) (res Type)
check may be nil.
(*Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named)(*Checker) invalidAST(at positioner, format string, args ...any)(*Checker) invalidArg(at positioner, code errorCode, format string, args ...any)(*Checker) invalidConversion(code errorCode, x *operand, target Type)(*Checker) invalidOp(at positioner, code errorCode, format string, args ...any)
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 errorCode, what string, allowNegative bool) bool
kindString returns the type kind as a string.
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.
lookup looks up name in the current environment and returns the matching object, or nil.
markImports recursively walks pkg and its imports, to record unique import
paths in pkgPathMap.
missingMethod is like MissingMethod but accepts a *Checker as receiver.
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.
If a method is missing on T but is found on *T, or if a method is found
on T when looked up with case-folding, this alternative method is returned
as the second result.
missingMethodReason returns a string giving the detailed reason for a missing method m,
where m is missing from V, but required by T. It puts the reason in parentheses,
and may include more have/want info after that. If non-nil, alt is a relevant
method that matches in some way. It may have the correct name, but wrong type, or
it may have a pointer receiver, or it may have the correct name except wrong case.
check may be nil.
(*Checker) monomorph()
multiExpr is like expr but the result may also be a multi-value.
(*Checker) multipleDefaults(list []ast.Stmt)
needsCleanup records objects/types that implement the cleanup method
which will be called at the end of type-checking.
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).
(*Checker) newError(at positioner, code errorCode, soft bool, msg string) error
newErrorf creates a new Error, but does not handle it.
check may be nil
newNamed is like NewNamed but with a *Checker receiver and additional orig argument.
check may be nil
If x is a generic function or type, 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
rawExpr typechecks expression e and initializes x with the expression
value or type. If an error occurred, x.mode is set to invalid.
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)(*Checker) recordCommaOkTypes(x ast.Expr, a [2]Type)(*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.
(*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)(*Checker) recordUntyped()(*Checker) recordUse(id *ast.Ident, obj Object)(*Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value)(*Checker) reportAltDecl(obj Object)
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 typ, 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. If no such type
name exists, the returned base is nil.
(*Checker) selector(x *operand, e *ast.SelectorExpr, def *Named)
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 errorCode, 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 is pure in the sense
that it doesn't modify the incoming type. If a substitution took place, the
result type is different from the incoming type.
If the given context is non-nil, it is used in lieu of check.Config.Context
(*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 *Named)
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.
The unary expression e may be nil. It's passed in for better error messages only.
unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
type parameters, if any. The type parameters are only unpacked if unpackParams is
set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
cannot easily work around).
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.
(*Checker) updateExprType0(parent, x ast.Expr, typ Type, final bool)
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.
The arguments may be nil.
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.
The arguments must not be nil.
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.
validType verifies that the given type does not "expand" indefinitely
producing a cycle in the type graph. Cycles are detected by marking
defined types.
(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 provided environment. The environment is
nil if typ is not part of (the RHS of) an instantiated type, in that case
any type parameter encountered must be from an enclosing function and can
be ignored. The path is the list of type names that lead to the current typ.
validVarType reports an error if typ is a constraint interface.
The expression e is used for error reporting, if any.
validateTArgLen verifies that the length of targs and tparams matches,
reporting an error if not. 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.
(*Checker) verify(pos token.Pos, tparams []*TypeParam, targs []Type) (int, error)(*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 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 follow the format "go%d.%d" (e.g. "go1.12") or it must be
empty; an empty string indicates the latest language version.
If the format is invalid, invoking the type checker will cause a
panic.
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 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 typ. All embedded fields
must be structs (rather than pointer to structs).
(*Config) offsetsof(T *Struct) []int64(*Config) sizeof(T Type) int64
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 n 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, n is returned, and recorded in the Context for the hash
h.
func NewContext() *Context
func golang.org/x/tools/internal/typeparams.NewContext() *typeparams.Context
func (*Checker).bestContext(ctxt *Context) *Context
func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)
func golang.org/x/tools/internal/typeparams.GenericAssignableTo(ctxt *typeparams.Context, V, T Type) bool
func golang.org/x/tools/internal/typeparams.Instantiate(ctxt *typeparams.Context, typ Type, targs []Type, validate bool) (Type, error)
func expandNamed(ctxt *Context, n *Named, instPos token.Pos) (tparams *TypeParamList, underlying Type, methods *methodList)
func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter
func (*Checker).bestContext(ctxt *Context) *Context
func (*Checker).instance(pos token.Pos, orig Type, targs []Type, ctxt *Context) (res Type)
func (*Checker).subst(pos token.Pos, typ Type, smap substMap, ctxt *Context) Type
func (*Named).resolve(ctxt *Context) *Named
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.ReadGo116ErrorData(err Error) (code typesinternal.ErrorCode, start, end token.Pos, ok 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()
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 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, the identifier f in a selector
expression x.f is found only in the Selections map, the
identifier z in a variable declaration 'var z int' is found
only in the Defs map, and identifiers denoting packages in
qualified identifiers are collected in the Uses map.
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, ObjectOf returns the field (*Var)
it defines, not the type (*TypeName) it uses.
Precondition: the Uses and Defs maps are populated.
TypeOf returns the type of expression e, or nil if not found.
Precondition: the Types, Uses and Defs maps are populated.
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/internal/typeparams.GetInstances(info *Info) map[*ast.Ident]typeparams.Instance
func golang.org/x/tools/internal/typeparams.InitInstanceInfo(info *Info)
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 = Rhs
Rhsast.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
func golang.org/x/tools/internal/typeparams.GetInstances(info *Info) map[*ast.Ident]typeparams.Instance
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 name object defining this interface; or nil (for better error messages)
// 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 EmbeddedType which is not restricted to defined (*Named) types.
EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
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.
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.
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 (*Checker).newInterface() *Interface
func (*TypeParam).iface() *Interface
func golang.org/x/tools/internal/gcimporter.newInterface(methods []*Func, embeddeds []Type) *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 golang.org/x/tools/internal/typeparams.InterfaceTermSet(iface *Interface) ([]*typeparams.Term, error)
func golang.org/x/tools/internal/typeparams.IsComparable(iface *Interface) bool
func golang.org/x/tools/internal/typeparams.IsImplicit(iface *Interface) bool
func golang.org/x/tools/internal/typeparams.IsMethodSet(iface *Interface) bool
func golang.org/x/tools/internal/typeparams.MarkImplicit(iface *Interface)
func computeInterfaceTypeSet(check *Checker, pos token.Pos, ityp *Interface) *_TypeSet
func (*Checker).assertableTo(V *Interface, T Type) (method, wrongType *Func)
func (*Checker).interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named)
func (*Checker).missingMethod(V Type, T *Interface, static bool) (method, alt *Func)
func (*Checker).newAssertableTo(V *Interface, T Type) error
func golang.org/x/exp/apidiff.unexportedMethod(t *Interface) *Func
var emptyInterface
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.
(*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
var emptyMethodSet
A Named represents a named (defined) type.
check*Checker
// type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
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, this is a 'lazy' list, and methods are instantiated
when they are first accessed.
// corresponding declared object for declared types; placeholder for instantiated types
// ensures that tparams, underlying, and methods are resolved before accessing
// original, uninstantiated type
resolver may be provided to lazily resolve type parameters, underlying, and methods.
// type arguments (after instantiation), or nil
// 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.
t must not have type arguments.
Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
NumMethods returns the number of explicit methods defined for t.
For an ordinary or instantiated type t, the receiver base type of these
methods will be the named type t. For an uninstantiated generic type t, each
method receiver will be instantiated with its receiver type parameters.
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.
(*Named) Underlying() Type(*Named) cleanup()
instiateMethod instantiates the i'th method for an instantiated receiver.
(*Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func)(*Named) resolve(ctxt *Context) *Named(*Named) setUnderlying(typ Type)
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 : cleaner
*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 (*Checker).newNamed(obj *TypeName, orig *Named, underlying Type, tparams *TypeParamList, methods *methodList) *Named
func (*Named).resolve(ctxt *Context) *Named
func golang.org/x/exp/apidiff.receiverNamedType(method Object) *Named
func golang.org/x/tools/internal/gcimporter.baseType(typ Type) *Named
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
func golang.org/x/tools/internal/typeparams.ForNamed(named *Named) *typeparams.TypeParamList
func golang.org/x/tools/internal/typeparams.NamedTypeArgs(named *Named) *typeparams.TypeList
func golang.org/x/tools/internal/typeparams.NamedTypeOrigin(named *Named) Type
func golang.org/x/tools/internal/typeparams.SetForNamed(n *Named, tparams []*typeparams.TypeParam)
func expandNamed(ctxt *Context, n *Named, instPos token.Pos) (tparams *TypeParamList, underlying Type, methods *methodList)
func (*Checker).checkFieldUniqueness(base *Named)
func (*Checker).definedType(e ast.Expr, def *Named) Type
func (*Checker).ident(x *operand, e *ast.Ident, def *Named, wantType bool)
func (*Checker).instantiatedType(ix *typeparams.IndexExpr, def *Named) (res Type)
func (*Checker).interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named)
func (*Checker).newNamed(obj *TypeName, orig *Named, underlying Type, tparams *TypeParamList, methods *methodList) *Named
func (*Checker).objDecl(obj Object, def *Named)
func (*Checker).selector(x *operand, e *ast.SelectorExpr, def *Named)
func (*Checker).typeDecl(obj *TypeName, tdecl *ast.TypeSpec, def *Named)
func (*Checker).typInternal(e0 ast.Expr, def *Named) (T Type)
func (*Checker).validType(typ *Named)
func golang.org/x/tools/internal/gcimporter.canReuse(def *Named, rhs Type) bool
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 parent
parent*Scope
// scope extent; may be invalid
Child returns the i'th child scope for 0 <= i < NumChildren().
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).
Note that obj.Parent() may be different from the returned scope if the
object was inserted into the scope and already had a parent at that
time (see Insert). This can only happen for dot-imported objects
whose scope is the scope of the package that exported them.
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)
squash merges s with its parent scope p by adding all
objects of s to p, adding all children of s to the
children of p, and removing s from p's children.
The function f is called for each object obj in s which
has an object alt in p. s should be discarded after
having been squashed.
*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).collectParams(scope *Scope, list *ast.FieldList, variadicOk bool) (params []*Var, variadic bool)
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)
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 path
kindSelectionKind
// 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.
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 SelectionString(s *Selection, qf Qualifier) string
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 : 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 golang.org/x/tools/internal/typeparams.NewSignatureType(recv *Var, recvTypeParams, typeParams []*typeparams.TypeParam, params, results *Tuple, variadic bool) *Signature
func makeSig(res Type, args ...Type) *Signature
func (*Checker).arguments(call *ast.CallExpr, sig *Signature, targs []Type, args []*operand, xlist []ast.Expr) (rsig *Signature)
func (*Checker).instantiateSignature(pos token.Pos, 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 golang.org/x/tools/internal/typeparams.ForSignature(sig *Signature) *typeparams.TypeParamList
func golang.org/x/tools/internal/typeparams.RecvTypeParams(sig *Signature) *typeparams.TypeParamList
func (*Checker).arguments(call *ast.CallExpr, sig *Signature, targs []Type, args []*operand, xlist []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, 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.
Offsetsof returns the offsets of the given struct fields, in bytes.
Offsetsof must implement the offset guarantees required by the spec.
Sizeof returns the size of a variable of type T.
Sizeof must implement the size guarantees required by the spec.
*StdSizes
func SizesFor(compiler, arch string) Sizes
func golang.org/x/tools/go/internal/packagesdriver.GetSizesGolist(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (Sizes, error)
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) 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().
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 (*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
A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple.
Tuples are used as components of signatures and to represent the type of multiple
assignments; they are not first class types of Go.
vars[]*Var
At returns the i'th variable of tuple t.
Len returns the number variables of tuple t.
(*Tuple) String() string(*Tuple) Underlying() Type
*Tuple : Type
*Tuple : expvar.Var
*Tuple : fmt.Stringer
*Tuple : context.stringer
*Tuple : github.com/aws/smithy-go/middleware.stringer
*Tuple : runtime.stringer
func NewTuple(x ...*Var) *Tuple
func (*Signature).Params() *Tuple
func (*Signature).Results() *Tuple
func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
func golang.org/x/tools/internal/typeparams.NewSignatureType(recv *Var, recvTypeParams, typeParams []*typeparams.TypeParam, params, results *Tuple, variadic bool) *Signature
func (*Checker).infer(posn positioner, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand) (result []Type)
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.
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 (*Named).TypeArgs() *TypeList
func golang.org/x/tools/internal/typeparams.NamedTypeArgs(named *Named) *typeparams.TypeList
func newTypeList(list []Type) *TypeList
A TypeParam represents a type parameter type.
// 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 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(*TypeParam) Underlying() Type(*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).
underIs calls f with the underlying types of the specific type terms
of t's constraint and reports whether all calls to f returned true.
If there are no specific terms, underIs returns the result of f(nil).
*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 golang.org/x/tools/internal/typeparams.NewTypeParam(name *TypeName, constraint Type) *typeparams.TypeParam
func (*Checker).declareTypeParams(tparams []*TypeParam, names []*ast.Ident) []*TypeParam
func (*Checker).newTypeParam(obj *TypeName, constraint Type) *TypeParam
func (*TypeParamList).list() []*TypeParam
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
func (*Named).SetTypeParams(tparams []*TypeParam)
func golang.org/x/tools/internal/typeparams.NewSignatureType(recv *Var, recvTypeParams, typeParams []*typeparams.TypeParam, params, results *Tuple, variadic bool) *Signature
func golang.org/x/tools/internal/typeparams.SetForNamed(n *Named, tparams []*typeparams.TypeParam)
func golang.org/x/tools/internal/typeparams.SetTypeParamConstraint(tparam *typeparams.TypeParam, constraint Type)
func golang.org/x/tools/internal/typeparams.StructuralTerms(tparam *typeparams.TypeParam) ([]*typeparams.Term, error)
func bindTParams(list []*TypeParam) *TypeParamList
func coreTerm(tpar *TypeParam) (*term, bool)
func isParameterized(tparams []*TypeParam, typ Type) bool
func makeRenameMap(from, to []*TypeParam) substMap
func makeSubstMap(tpars []*TypeParam, targs []Type) substMap
func tparamIndex(list []*TypeParam, tpar *TypeParam) int
func tparamIndex(list []*TypeParam, tpar *TypeParam) int
func typeParamsString(list []*TypeParam) string
func (*Checker).declareTypeParams(tparams []*TypeParam, names []*ast.Ident) []*TypeParam
func (*Checker).infer(posn positioner, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand) (result []Type)
func (*Checker).inferB(posn positioner, tparams []*TypeParam, targs []Type) (types []Type, index int)
func (*Checker).verify(pos token.Pos, tparams []*TypeParam, targs []Type) (int, error)
func golang.org/x/tools/internal/gcimporter.tparamExportName(prefix string, tparam *typeparams.TypeParam) string
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 type set 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 type set 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 type set 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 the type set 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.
underIs calls f with the underlying types of the specific type terms
of s and reports whether all calls to f returned true. If there are
no specific terms, underIs returns the result of f(nil).
*_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
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
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 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
// 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.
// 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.
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 depth
typType
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
// 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)
// if valid, identifiers are looked up as if at position pos (used by Eval)
// top-most scope for lookups
// function signature if inside a function; nil otherwise
lookup looks up name in the current environment and returns the matching object, or nil.
exprInfo stores information about an untyped expression.
// expression is lhs operand of a shift with delayed type-check
modeoperandModetyp*Basic
// constant value; or nil (if not a constant)
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 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
methodList holds a list of methods that may be lazily resolved by a provided
resolution method.
guards synchronizes the instantiation of lazy methods. For lazy method
lists, guards is non-nil and of the length passed to newLazyMethodList.
For non-lazy method lists, guards is nil.
methods[]*Func
Add appends a method to the method list if not not already present. Add
panics if the receiver is lazy.
At returns the i'th method of the method list. At panics if i is out of
bounds, or if the receiver is lazy and resolve is nil.
Len returns the length of the method list.
Lookup looks up the method identified by pkg and name in the receiver.
Lookup panics if the receiver is lazy. If foldCase is true, method names
are considered equal if they are equal with case folding.
isLazy reports whether the receiver is a lazy method list.
func expandNamed(ctxt *Context, n *Named, instPos token.Pos) (tparams *TypeParamList, underlying Type, methods *methodList)
func newLazyMethodList(length int) *methodList
func newMethodList(methods []*Func) *methodList
func (*Checker).newNamed(obj *TypeName, orig *Named, underlying Type, tparams *TypeParamList, methods *methodList) *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
nodeQueue implements the container/heap interface;
a nodeQueue may be used as a priority queue.
( nodeQueue) Len() int( nodeQueue) Less(i, j int) bool(*nodeQueue) Pop() any(*nodeQueue) Push(x any)( nodeQueue) Swap(i, j int)
*nodeQueue : container/heap.Interface
nodeQueue : sort.Interface
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.
(*object) color() color(*object) order() uint32(*object) sameId(pkg *Package, name string) 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 Instantiate
ctxt*Contextpostoken.PossmapsubstMap(*subster) funcList(in []*Func) (out []*Func, copied bool)(*subster) func_(f *Func) *Func(*subster) termlist(in []*Term) (out []*Term, copied bool)(*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) typeList(in []Type) (out []Type, copied bool)(*subster) varList(in []*Var) (out []*Var, copied bool)(*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 != nil
typType(*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 tparamEnv provides the environment for looking up the type arguments
with which type parameters for a given instance were instantiated.
If we don't have an instance, the corresponding tparamEnv is nil.
link*tparamEnvtmapsubstMap(*tparamEnv) push(typ *Named) *tparamEnv
func (*Checker).validType0(typ Type, env *tparamEnv, path []Object) typeInfo
A tparamsList describes a list of type parameters and the types inferred for them.
For each tparams element, there is a corresponding type slot index in indices.
index < 0: unifier.types[-index-1] == nil
index == 0: no type slot allocated yet
index > 0: unifier.types[index-1] == typ
Joined tparams elements share the same type slot and thus have the same index.
By using a negative index for nil types we don't need to check unifier.types
to see if we have a type or not.
// len(d.indices) == len(d.tparams)
tparams[]*TypeParamunifier*unifier
String returns a string representation for a tparamsList. For debugging.
at returns the type set for the i'th type parameter; or nil.
If typ is a type parameter of d, index returns the type parameter index.
Otherwise, the result is < 0.
init initializes d with the given type parameters.
The type parameters must be in the order in which they appear in their declaration
(this ensures that the tparams indices match the respective type parameter index).
set sets the type typ for the i'th type parameter;
typ must not be nil and it must not have been set before.
setIndex sets the type slot index for the i'th type parameter
(and all its joined parameters) to tj. The type parameter
must have a (possibly nil) type slot associated with it.
types returns the list of inferred types (via unification) for the type parameters
described by d, and an index. If all types were inferred, the returned index is < 0.
Otherwise, it is the index of the first type parameter which couldn't be inferred;
i.e., for which list[index] is nil.
unknowns returns the number of type parameters for which no type has been set yet.
*tparamsList : expvar.Var
*tparamsList : fmt.Stringer
*tparamsList : context.stringer
*tparamsList : github.com/aws/smithy-go/middleware.stringer
*tparamsList : runtime.stringer
A unifier maintains the current type parameters for x and y
and the respective types inferred for each type parameter.
A unifier is created by calling newUnifier.
// recursion depth during unification
exactbool
// inferred types, shared by x and y
// x and y must initialized via tparamsList.init
// x and y must initialized via tparamsList.init
join unifies the i'th type parameter of x with the j'th type parameter of 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.
(*unifier) nifyEq(x, y Type, p *ifacePair) bool(*unifier) tracef(format string, args ...interface{})
unify attempts to unify x and y and reports whether it succeeded.
func newUnifier(exact bool) *unifier
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 187, in which 53 are exported)
AssertableTo reports whether a value of type V can be asserted to have type T.
The behavior of AssertableTo is undefined in two cases:
- 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 undefined if V or T is 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 then 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 undefined if V or T is 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.
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 undefined if V is an uninstantiated generic
type.
Instantiate instantiates the type orig with the given type arguments targs.
orig must be a *Named or a *Signature type. If there is no error, the
resulting Type is an instantiated type of the same kind (either a *Named or
a *Signature). Methods attached to a *Named type are also instantiated, and
associated with a new *Func that has the same position as the original
method, but nil function scope.
If ctxt is non-nil, it may be used to de-duplicate the instance against
previous instances with the same identity. As a special case, generic
*Signature origin types are only considered identical if they are pointer
equivalent, so that instantiating distinct (but possibly identical)
signatures will yield different instances. The use of a shared context does
not guarantee that identical instances are deduplicated in all cases.
If validate is set, Instantiate verifies that the number of type arguments
and parameters match, and that the type arguments satisfy their
corresponding type constraints. If verification fails, the resulting error
may wrap an *ArgumentError indicating which type argument did not satisfy
its corresponding type parameter constraint, and why.
If validate is not set, Instantiate does not verify the type argument count
or whether the type arguments satisfy their constraints. Instantiate is
guaranteed to not return an error, but may panic. Specifically, for
*Signature types, Instantiate will panic immediately if the type argument
count is incorrect; for *Named types, a panic may occur later inside the
*Named API.
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.
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).
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 must be of unnamed slice 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
or Signature type by calling SetTypeParams. Setting a type parameter on more
than one type will result in a panic.
The constraint argument can be nil, and set later via SetConstraint. If the
constraint is non-nil, it must be fully defined.
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.
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", "arm", "arm64", "amd64", "amd64p32", "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.
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.
_NewTypeNameLazy returns a new defined type like NewTypeName, but it
lazily calls resolve to finish constructing the Named object.
align returns the smallest y >= x such that y % a == 0.
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).
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.
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.
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 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.)
expandNamed ensures that the underlying type of n is instantiated.
The underlying type will be Typ[Invalid] if there was an error.
fieldIndex returns the index for the field with matching package and name, or a value < 0.
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.
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.
For changes to this code the corresponding changes should be made to unifier.nify.
identicalInstance reports if two type instantiations are identical.
Instantiations are identical if their origin and type arguments are
identical.
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).
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?
lookupFieldOrMethod should only be called by LookupFieldOrMethod and missingMethod.
If foldCase is true, the lookup for methods will include looking for any method
which case-folds to the same as 'name' (used for giving helpful error messages).
The resulting object may not be fully type-checked.
lookupMethod returns the index of and method with matching package and name, or (-1, nil).
If foldCase is true, method names are considered equal if they are equal with case folding.
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.
newUnifier returns a new unifier.
If exact is set, unification requires unified types to match
exactly. If exact is not set, a named type's underlying type
is considered if unification would fail otherwise, and the
direction of channels is ignored.
TODO(gri) exact is not set anymore by a caller. Consider removing it.
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>)
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 an operation, or the empty string.
Only operations that might overflow are handled.
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.
parseGoVersion parses a Go version string (such as "go1.12")
and returns the version, or an error. If s is the empty
string, the version is 0.0.
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 the range clause is not permitted
the results are nil.
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 of typ without expanding instances, to
avoid infinite recursion.
TODO(rfindley): eliminate this function or give it a better name.
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.
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)).
unparen returns e with any enclosing parentheses stripped.
Package-Level Variables (total 30, 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".
goVersionRx matches a Go version string, e.g. "go1.12".
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.
_AmbiguousSelector occurs when a selector is ambiguous.
Example:
type E1 struct { i int }
type E2 struct { i int }
type T struct { E1; E2 }
var x T
var _ = x.i
universe scope
testing support
_BadDecl occurs when a declaration has invalid syntax.
_BadDotDotDotSyntax occurs when a "..." occurs in a context where it is
not valid.
Example:
var _ = map[int][...]int{0: {}}
_BadImportPath occurs when an import path is not valid.
_BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument
that is not a selector expression.
Example:
import "unsafe"
var x int
var _ = unsafe.Offsetof(x)
_BadRecv occurs when a method declaration does not have exactly one
receiver parameter.
Example:
func () _() {}
_BadTypeKeyword occurs when a .(type) expression is used anywhere other
than a type switch.
Example:
type I interface {
m()
}
var t I
var _ = t.(type)
_BlankIfaceMethod occurs when a method name is '_'.
Per the spec:
"The name of each explicitly specified method must be unique and not
blank."
Example:
type T interface {
_(int)
}
_BlankPkgName occurs when a package name is the blank identifier "_".
Per the spec:
"The PackageName must not be the blank identifier."
_BrokenImport occurs when importing a package fails.
Example:
import "amissingpackage"
_CannotInferTypeArgs occurs when type or function type argument inference
fails to infer all type arguments.
Example:
func f[T any]() {}
func _() {
f()
}
_DivByZero occurs when a division operation is provable at compile
time to be a division by zero.
Example:
const divisor = 0
var x int = 1/divisor
_DuplicateCase occurs when a type or expression switch has duplicate
cases.
Example:
func printInt(i int) {
switch i {
case 1:
println("one")
case 1:
println("One")
}
}
_DuplicateDecl occurs when an identifier is declared multiple times.
Example:
var x = 1
var x = 2
_DuplicateDefault occurs when a type or expression switch has multiple
default clauses.
Example:
func printInt(i int) {
switch i {
case 1:
println("one")
default:
println("One")
default:
println("1")
}
}
_DuplicateFieldAndMethod occurs when an identifier appears as both a field
and method name.
Example:
type T struct {
m int
}
func (T) m() {}
_DuplicateLabel occurs when a label is declared more than once.
Example:
func f() int {
L:
L:
return 1
}
_DuplicateLitField occurs when a struct literal contains duplicated
fields.
Example:
var _ = struct{i int}{i: 1, i: 2}
_DuplicateLitKey occurs when an index is duplicated in a slice, array, or
map literal.
Example:
var _ = []int{0:1, 0:2}
Example:
var _ = map[string]int{"a": 1, "a": 2}
_DuplicateMethod occurs when two methods on the same receiver type have
the same name.
Example:
type T struct {}
func (T) m() {}
func (T) m(i int) int { return i }
_ImportCRenamed occurs when the special import "C" is renamed. "C" is a
pseudo-package, and must not be renamed.
Example:
import _ "C"
_ImpossibleAssert occurs for a type assertion x.(T) when the value x of
interface cannot have dynamic type T, due to a missing or mismatching
method on T.
Example:
type T int
func (t *T) m() int { return int(*t) }
type I interface { m() int }
var x I
var _ = x.(T)
_IncomparableMapKey occurs when a map key type does not support the == and
!= operators.
Per the spec:
"The comparison operators == and != must be fully defined for operands of
the key type; thus the key type must not be a function, map, or slice."
Example:
var x map[T]int
type T []int
_IncompatibleAssign occurs when the type of the right-hand side expression
in an assignment cannot be assigned to the type of the variable being
assigned.
Example:
var x []int
var _ int = x
_InvalidAppend occurs when append is called with a first argument that is
not a slice.
Example:
var _ = append(1, 2)
_InvalidArrayLen occurs when an array length is not a constant value.
Example:
var n = 3
var _ = [n]int{}
_InvalidAssert occurs when a type assertion is applied to a
value that is not of interface type.
Example:
var x = 1
var _ = x.(float64)
_InvalidBlank occurs when a blank identifier is used as a value or type.
Per the spec:
"The blank identifier may appear as an operand only on the left-hand side
of an assignment."
Example:
var x = _
_InvalidCall occurs when an expression is called that is not of function
type.
Example:
var x = "x"
var y = x()
_InvalidCap occurs when an argument to the cap built-in function is not of
supported type.
See https://golang.org/ref/spec#Length_and_capacity for information on
which underlying types are supported as arguments to cap and len.
Example:
var s = 2
var x = cap(s)
_InvalidChanAssign occurs when a chan assignment is invalid.
Per the spec, a value x is assignable to a channel type T if:
"x is a bidirectional channel value, T is a channel type, x's type V and
T have identical element types, and at least one of V or T is not a
defined type."
Example:
type T1 chan int
type T2 chan int
var x T1
// Invalid assignment because both types are named
var _ T2 = x
_InvalidClose occurs when close(...) is called with an argument that is
not of channel type, or that is a receive-only channel.
Example:
func f() {
var x int
close(x)
}
_InvalidComplex occurs when the complex built-in function is called with
arguments with incompatible types.
Example:
var _ = complex(float32(1), float64(2))
_InvalidCond occurs when an if condition is not a boolean expression.
Example:
func checkReturn(i int) {
if i {
panic("non-zero return")
}
}
_InvalidConstInit occurs when a const declaration has a non-constant
initializer.
Example:
var x int
const _ = x
_InvalidConstType occurs when the underlying type in a const declaration
is not a valid constant type.
Example:
const c *int = 4
_InvalidConstVal occurs when a const value cannot be converted to its
target type.
TODO(findleyr): this error code and example are not very clear. Consider
removing it.
Example:
const _ = 1 << "hello"
_InvalidConversion occurs when the argument type cannot be converted to the
target.
See https://golang.org/ref/spec#Conversions for the rules of
convertibility.
Example:
var x float64
var _ = string(x)
_InvalidCopy occurs when the arguments are not of slice type or do not
have compatible type.
See https://golang.org/ref/spec#Appending_and_copying_slices for more
information on the type requirements for the copy built-in.
Example:
func f() {
var x []int
y := []int64{1,2,3}
copy(x, y)
}
_InvalidDeclCycle occurs when a declaration cycle is not valid.
Example:
type S struct {
S
}
_InvalidDefer occurs when a deferred expression is not a function call,
for example if the expression is a type conversion.
Example:
func f(i int) int {
defer int32(i)
return i
}
_InvalidDelete occurs when the delete built-in function is called with a
first argument that is not a map.
Example:
func f() {
m := "hello"
delete(m, "e")
}
_InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in
function.
Example:
var s = []int{1, 2, 3}
var l = len(s...)
_InvalidExprSwitch occurs when a switch expression is not comparable.
Example:
func _() {
var a struct{ _ func() }
switch a /* ERROR cannot switch on a */ {
}
}
_InvalidGo occurs when a go expression is not a function call, for example
if the expression is a type conversion.
Example:
func f(i int) int {
go int32(i)
return i
}
_InvalidIfaceAssign occurs when a value of type T is used as an
interface, but T does not implement a method of the expected interface.
Example:
type I interface {
f()
}
type T int
var x I = T(1)
_InvalidIfaceEmbed occurs when a non-interface type is embedded in an
interface (for go 1.17 or earlier).
_InvalidImag occurs when the imag built-in function is called with an
argument that does not have complex type.
Example:
var _ = imag(int(1))
_InvalidIndex occurs when an index argument is not of integer type,
negative, or out-of-bounds.
Example:
var s = [...]int{1,2,3}
var x = s[5]
Example:
var s = []int{1,2,3}
var _ = s[-1]
Example:
var s = []int{1,2,3}
var i string
var _ = s[i]
_InvalidIndirection occurs when a non-pointer value is indirected via the
'*' operator.
Example:
var x int
var y = *x
_InvalidInitCycle occurs when an invalid cycle is detected within the
initialization graph.
Example:
var x int = f()
func f() int { return x }
_InvalidInitDecl occurs when init is declared as anything other than a
function.
Example:
var init = 1
Example:
func init() int { return 1 }
_InvalidInitSig occurs when an init function declares parameters or
results.
Deprecated: no longer emitted by the type checker. _InvalidInitDecl is
used instead.
_InvalidInstanceCycle occurs when an invalid cycle is detected
within the instantiation graph.
Example:
func f[T any]() { f[*T]() }
_InvalidIota occurs when the predeclared identifier iota is used outside
of a constant declaration.
Example:
var x = iota
_InvalidIterVar occurs when two iteration variables are used while ranging
over a channel.
Example:
func f(c chan int) {
for k, v := range c {
println(k, v)
}
}
_InvalidLen occurs when an argument to the len built-in function is not of
supported type.
See https://golang.org/ref/spec#Length_and_capacity for information on
which underlying types are supported as arguments to cap and len.
Example:
var s = 2
var x = len(s)
_InvalidLit occurs when a composite literal expression does not match its
type.
Example:
type P *struct{
x int
}
var _ = P {}
_InvalidLitField occurs when a field name is not a valid identifier.
Example:
var _ = struct{i int}{1: 1}
_InvalidLitIndex occurs when the key in a key-value element of a slice or
array literal is not an integer constant.
Example:
var i = 0
var x = []string{i: "world"}
_InvalidMainDecl occurs when main is declared as anything other than a
function, in a main package.
_InvalidMake occurs when make is called with an unsupported type argument.
See https://golang.org/ref/spec#Making_slices_maps_and_channels for
information on the types that may be created using make.
Example:
var x = make(int)
_InvalidMethodExpr occurs when a pointer method is called but the argument
is not addressable.
Example:
type T struct {}
func (*T) m() int { return 1 }
var _ = T.m(T{})
_InvalidMethodTypeParams occurs when methods have type parameters.
It cannot be encountered with an AST parsed using go/parser.
_InvalidOffsetof occurs when unsafe.Offsetof is called with a method
selector, rather than a field selector, or when the field is embedded via
a pointer.
Per the spec:
"If f is an embedded field, it must be reachable without pointer
indirections through fields of the struct. "
Example:
import "unsafe"
type T struct { f int }
type S struct { *T }
var s S
var _ = unsafe.Offsetof(s.f)
Example:
import "unsafe"
type S struct{}
func (S) m() {}
var s S
var _ = unsafe.Offsetof(s.m)
_InvalidPkgUse occurs when a package identifier is used outside of a
selector expression.
Example:
import "fmt"
var _ = fmt
_InvalidPostDecl occurs when there is a declaration in a for-loop post
statement.
Example:
func f() {
for i := 0; i < 10; j := 0 {}
}
_InvalidPtrEmbed occurs when an embedded field is of the pointer form *T,
and T itself is itself a pointer, an unsafe.Pointer, or an interface.
Per the spec:
"An embedded field must be specified as a type name T or as a pointer to
a non-interface type name *T, and T itself may not be a pointer type."
Example:
type T *int
type S struct {
*T
}
_InvalidRangeExpr occurs when the type of a range expression is not array,
slice, string, map, or channel.
Example:
func f(i int) {
for j := range i {
println(j)
}
}
_InvalidReal occurs when the real built-in function is called with an
argument that does not have complex type.
Example:
var _ = real(int(1))
_InvalidReceive occurs when there is a channel receive from a value that
is either not a channel, or is a send-only channel.
Example:
func f() {
var x = 1
<-x
}
_InvalidRecv occurs when a receiver type expression is not of the form T
or *T, or T is a pointer type.
Example:
type T struct {}
func (**T) m() {}
_InvalidSelectCase occurs when a select case is not a channel send or
receive.
Example:
func checkChan(c <-chan int) bool {
select {
case c:
return true
default:
return false
}
}
_InvalidSend occurs when there is a channel send to a value that is not a
channel, or is a receive-only channel.
Example:
func f() {
var x = 1
x <- "hello!"
}
_InvalidShiftCount occurs when the right-hand side of a shift operation is
either non-integer, negative, or too large.
Example:
var (
x string
y int = 1 << x
)
_InvalidShiftOperand occurs when the shifted operand is not an integer.
Example:
var s = "hello"
var x = s << 2
_InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is
applied to a string.
Example:
var s = "hello"
var x = s[1:2:3]
_InvalidStructLit occurs when a positional struct literal has an incorrect
number of values.
Example:
var _ = struct{i, j int}{1,2,3}
_InvalidTypeArg occurs when a type argument does not satisfy its
corresponding type parameter constraints.
Example:
type T[P ~int] struct{}
var _ T[string]
_InvalidTypeCycle occurs when a cycle in type definitions results in a
type that is not well-defined.
Example:
import "unsafe"
type T [unsafe.Sizeof(T{})]int
_InvalidTypeSwitch occurs when .(type) is used on an expression that is
not of interface type.
Example:
func f(i int) {
switch x := i.(type) {}
}
_InvalidUnion occurs when an embedded union or approximation element is
not valid.
Example:
type _ interface {
~int | interface{ m() }
}
_InvalidUnsafeAdd occurs when unsafe.Add is called with a
length argument that is not of integer type.
Example:
import "unsafe"
var p unsafe.Pointer
var _ = unsafe.Add(p, float64(1))
_InvalidUnsafeSlice occurs when unsafe.Slice is called with a
pointer argument that is not of pointer type or a length argument
that is not of integer type, negative, or out of bounds.
Example:
import "unsafe"
var x int
var _ = unsafe.Slice(x, 1)
Example:
import "unsafe"
var x int
var _ = unsafe.Slice(&x, float64(1))
Example:
import "unsafe"
var x int
var _ = unsafe.Slice(&x, -1)
Example:
import "unsafe"
var x int
var _ = unsafe.Slice(&x, uint64(1) << 63)
_InvalidUntypedConversion occurs when an there is no valid implicit
conversion from an untyped value satisfying the type constraints of the
context in which it is used.
Example:
var _ = 1 + new(int)
_JumpIntoBlock occurs when a forward jump goes to a label inside a nested
block.
Example:
func f(x int) {
goto L
if x > 0 {
L:
print("inside block")
}
}
_JumpOverDecl occurs when a label jumps over a variable declaration.
Example:
func f() int {
goto L
x := 2
L:
x++
return x
}
_MismatchedPkgName occurs when a file's package name doesn't match the
package name already established by other files.
_MismatchedTypes occurs when operand types are incompatible in a binary
operation.
Example:
var a = "hello"
var b = 1
var c = a - b
_MisplacedBreak occurs when a break statement is not within a for, switch,
or select statement of the innermost function definition.
Example:
func f() {
break
}
_MisplacedConstraintIface occurs when a constraint-type interface is used
outside of constraint position.
Example:
type I interface { ~int }
var _ I
_MisplacedContinue occurs when a continue statement is not within a for
loop of the innermost function definition.
Example:
func sumeven(n int) int {
proceed := func() {
continue
}
sum := 0
for i := 1; i <= n; i++ {
if i % 2 != 0 {
proceed()
}
sum += i
}
return sum
}
_MisplacedDotDotDot occurs when a "..." is used somewhere other than the
final argument in a function declaration.
Example:
func f(...int, int)
_MisplacedFallthrough occurs when a fallthrough statement is not within an
expression switch.
Example:
func typename(i interface{}) string {
switch i.(type) {
case int64:
fallthrough
case int:
return "int"
}
return "unsupported"
}
_MisplacedLabel occurs when a break or continue label is not on a for,
switch, or select statement.
Example:
func f() {
L:
a := []int{1,2,3}
for _, e := range a {
if e > 10 {
break L
}
println(a)
}
}
_MisplacedTypeParam occurs when a type parameter is used in a place where
it is not permitted.
Example:
type T[P any] P
Example:
type T[P any] struct{ *P }
_MissingFieldOrMethod occurs when a selector references a field or method
that does not exist.
Example:
type T struct {}
var x = T{}.f
_MissingInitBody occurs when an init function is missing its body.
Example:
func init()
_MissingLitField occurs when a struct literal refers to a field that does
not exist on the struct type.
Example:
var _ = struct{i int}{j: 2}
_MissingLitKey occurs when a map literal is missing a key expression.
Example:
var _ = map[string]int{1}
_MissingReturn occurs when a function with results is missing a return
statement.
Example:
func f() int {}
_MixedStructLit occurs when a struct literal contains a mix of positional
and named elements.
Example:
var _ = struct{i, j int}{i: 1, 2}
_MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does
not have single-valued left-hand or right-hand side.
Per the spec:
"In assignment operations, both the left- and right-hand expression lists
must contain exactly one single-valued expression"
Example:
func f() int {
x, y := 1, 2
x, y += 1
return x + y
}
_NoNewVar occurs when a short variable declaration (':=') does not declare
new variables.
Example:
func f() {
x := 1
x := 2
}
_NonIndexableOperand occurs when an index operation is applied to a value
that cannot be indexed.
Example:
var x = 1
var y = x[1]
_NonNumericIncDec occurs when an increment or decrement operator is
applied to a non-numeric value.
Example:
func f() {
var c = "c"
c++
}
_NonSliceableOperand occurs when a slice operation is applied to a value
whose type is not sliceable, or is unaddressable.
Example:
var x = [...]int{1, 2, 3}[:1]
Example:
var x = 1
var y = 1[:1]
_NonVariadicDotDotDot occurs when a "..." is used on the final argument to
a non-variadic function.
Example:
func printArgs(s []string) {
for _, a := range s {
println(a)
}
}
func f() {
s := []string{"a", "b", "c"}
printArgs(s...)
}
_NotAGenericType occurs when a non-generic type is used where a generic
type is expected: in type or function instantiation.
Example:
type T int
var _ T[int]
_NotAnExpr occurs when a type expression is used where a value expression
is expected.
Example:
type T struct {}
func f() {
T
}
_NotAType occurs when the identifier used as the underlying type in a type
declaration or the right-hand side of a type alias does not denote a type.
Example:
var S = 2
type T S
_NumericOverflow occurs when a numeric constant overflows its target type.
Example:
var x int8 = 1000
_OutOfScopeResult occurs when the name of a value implicitly returned by
an empty return statement is shadowed in a nested scope.
Example:
func factor(n int) (i int) {
for i := 2; i < n; i++ {
if n%i == 0 {
return
}
}
return 0
}
_OversizeArrayLit occurs when an array literal exceeds its length.
Example:
var _ = [2]int{1,2,3}
_RepeatedDecl occurs when an identifier occurs more than once on the left
hand side of a short variable declaration.
Example:
func _() {
x, y, y := 1, 2, 3
}
_SwappedMakeArgs occurs when make is called with three arguments, and its
length argument is larger than its capacity argument.
Example:
var x = make([]int, 3, 2)
_SwappedSliceIndices occurs when constant indices in a slice expression
are decreasing in value.
Example:
var _ = []int{1,2,3}[2:1]
_Test is reserved for errors that only apply while in self-test mode.
_TooManyValues occurs when a function returns too many values for the
expression context in which it is used.
Example:
func ReturnTwo() (int, int) {
return 1, 2
}
var x = ReturnTwo()
_TruncatedFloat occurs when a float constant is truncated to an integer
value.
Example:
var _ int = 98.6
_UnaddressableFieldAssign occurs when trying to assign to a struct field
in a map value.
Example:
func f() {
m := make(map[string]struct{i int})
m["foo"].i = 42
}
_UnaddressableOperand occurs when the & operator is applied to an
unaddressable expression.
Example:
var x = &1
_UnassignableOperand occurs when the left-hand side of an assignment is
not assignable.
Example:
func f() {
const c = 1
c = 2
}
_UncalledBuiltin occurs when a built-in function is used as a
function-valued expression, instead of being called.
Per the spec:
"The built-in functions do not have standard Go types, so they can only
appear in call expressions; they cannot be used as function values."
Example:
var _ = copy
_UndeclaredImportedName occurs when a package-qualified identifier is
undeclared by the imported package.
Example:
import "go/types"
var _ = types.NotAnActualIdentifier
_UndeclaredLabel occurs when an undeclared label is jumped to.
Example:
func f() {
goto L
}
_UndeclaredName occurs when an identifier is not declared in the current
scope.
Example:
var x T
_UndefinedOp occurs when an operator is not defined for the type(s) used
in an operation.
Example:
var c = "a" - "b"
_UnexportedLitField occurs when a positional struct literal implicitly
assigns an unexported field of an imported type.
_UnexportedName occurs when a selector refers to an unexported identifier
of an imported package.
Example:
import "reflect"
type _ reflect.flag
_UnsupportedFeature occurs when a language feature is used that is not
supported at this Go version.
_UntypedLit occurs when a composite literal omits a required type
identifier.
Example:
type outer struct{
inner struct { i int }
}
var _ = outer{inner: {1}}
_UntypedNil occurs when the predeclared (untyped) value nil is used to
initialize a variable declared without an explicit type.
Example:
var x = nil
_UnusedExpr occurs when a side-effect free expression is used as a
statement. Such a statement has no effect.
Example:
func f(i int) {
i*i
}
_UnusedImport occurs when an import is unused.
Example:
import "fmt"
func main() {}
_UnusedLabel occurs when a label is declared but not used.
Example:
func f() {
L:
}
_UnusedResults occurs when a restricted expression-only built-in function
is suspended via go or defer. Such a suspension discards the results of
these side-effect free built-in functions, and therefore is ineffectual.
Example:
func f(a []int) int {
defer len(a)
return i
}
_UnusedVar occurs when a variable is declared but unused.
Example:
func f() {
x := 1
}
_WrongArgCount occurs when too few or too many arguments are passed by a
function call.
Example:
func f(i int) {}
var x = f()
_WrongAssignCount occurs when the number of values on the right-hand side
of an assignment or initialization expression does not match the number
of variables on the left-hand side.
Example:
var x = 1, 2
_WrongResultCount occurs when a return statement returns an incorrect
number of values.
Example:
func ReturnOne() int {
return 1, 2
}
_WrongTypeArgCount occurs when a type or function is instantiated with an
incorrent number of type arguments, including when a generic type or
function is used without instantiation.
Errors inolving failed type inference are assigned other error codes.
Example:
type T[p any] int
var _ T[int, string]
Example:
func f[T any]() {}
var x = f
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