types2

Imports

Imports #

"cmd/compile/internal/syntax"
"errors"
"fmt"
"internal/buildcfg"
. "internal/types/errors"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"strconv"
"strings"
"cmd/compile/internal/syntax"
"go/constant"
"go/token"
"fmt"
"go/version"
"internal/goversion"
"cmd/compile/internal/syntax"
"fmt"
"go/constant"
. "internal/types/errors"
"sync/atomic"
"cmd/compile/internal/syntax"
"strings"
"sync"
"sync/atomic"
"bytes"
"fmt"
"bytes"
"fmt"
"slices"
"strconv"
"strings"
"unicode/utf8"
"go/constant"
"strings"
"cmp"
"container/heap"
"fmt"
. "internal/types/errors"
"slices"
"sort"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"cmd/compile/internal/syntax"
"cmp"
"fmt"
"go/constant"
. "internal/types/errors"
"slices"
"strconv"
"strings"
"unicode"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"strings"
"cmd/compile/internal/syntax"
"fmt"
"go/constant"
"go/token"
. "internal/types/errors"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"slices"
"strings"
"cmd/compile/internal/syntax"
"fmt"
"go/constant"
. "internal/types/errors"
"strings"
"cmd/compile/internal/syntax"
"fmt"
"cmd/compile/internal/syntax"
"go/constant"
"go/token"
. "internal/types/errors"
"go/constant"
. "internal/types/errors"
"unicode"
"cmd/compile/internal/syntax"
"fmt"
"io"
"slices"
"strings"
"sync"
"cmd/compile/internal/syntax"
"go/constant"
"cmd/compile/internal/syntax"
"fmt"
. "internal/types/errors"
"path/filepath"
"strings"
"bytes"
"fmt"
"sort"
"strings"
"cmd/compile/internal/syntax"
"fmt"
"cmd/compile/internal/syntax"
"fmt"
"go/constant"
. "internal/types/errors"
"strings"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"strings"
"cmd/compile/internal/syntax"
"fmt"
. "internal/types/errors"
"strings"
"cmd/compile/internal/syntax"
"fmt"
"go/constant"
"internal/buildcfg"
. "internal/types/errors"
"slices"
"bytes"
"cmd/compile/internal/syntax"
"fmt"
"strconv"
"strings"
"cmd/compile/internal/syntax"
"fmt"
"slices"
"strings"
"bytes"
"cmd/compile/internal/syntax"
"cmd/compile/internal/syntax"
"cmd/compile/internal/syntax"
"go/constant"
. "internal/types/errors"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"slices"
"cmd/compile/internal/syntax"
"bytes"
"cmd/compile/internal/syntax"
"fmt"
"go/constant"
"strings"
"unicode"
"unicode/utf8"
"slices"
"unicode"
"sync/atomic"
"cmd/compile/internal/syntax"
"fmt"
. "internal/types/errors"
"runtime"
"strings"
"bytes"
"cmd/compile/internal/syntax"
"fmt"
"go/constant"
. "internal/types/errors"
"fmt"
"cmd/compile/internal/syntax"
"go/constant"
"internal/buildcfg"
. "internal/types/errors"
"slices"
"bytes"
"fmt"
"strconv"
"strings"
"sync"
"cmd/compile/internal/syntax"
"cmd/compile/internal/syntax"
. "internal/types/errors"
"cmd/compile/internal/syntax"
"go/constant"
"go/token"
. "internal/types/errors"
"math"

Constants & Variables

Bool const #

predeclared types

const Bool

Byte const #

aliases

const Byte = Uint8

Complex128 const #

const Complex128

Complex64 const #

const Complex64

FieldVal const #

const FieldVal SelectionKind = iota

Float32 const #

const Float32

Float64 const #

const Float64

Int const #

const Int

Int16 const #

const Int16

Int32 const #

const Int32

Int64 const #

const Int64

Int8 const #

const Int8

Invalid const #

const Invalid BasicKind = iota

IsBoolean const #

Properties of basic types.

const IsBoolean BasicInfo = *ast.BinaryExpr

IsComplex const #

Properties of basic types.

const IsComplex

IsConstType const #

Properties of basic types.

const IsConstType = *ast.BinaryExpr

IsFloat const #

Properties of basic types.

const IsFloat

IsInteger const #

Properties of basic types.

const IsInteger

IsNumeric const #

Properties of basic types.

const IsNumeric = *ast.BinaryExpr

IsOrdered const #

Properties of basic types.

const IsOrdered = *ast.BinaryExpr

IsString const #

Properties of basic types.

const IsString

IsUnsigned const #

Properties of basic types.

const IsUnsigned

IsUntyped const #

Properties of basic types.

const IsUntyped

MethodExpr const #

const MethodExpr

MethodVal const #

const MethodVal

RecvOnly const #

The direction of a channel is indicated by one of these constants.

const RecvOnly

Rune const #

const Rune = Int32

SendOnly const #

The direction of a channel is indicated by one of these constants.

const SendOnly

SendRecv const #

The direction of a channel is indicated by one of these constants.

const SendRecv ChanDir = iota

String const #

const String

Typ var #

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").

var Typ = [...]*Basic{...}

Uint const #

const Uint

Uint16 const #

const Uint16

Uint32 const #

const Uint32

Uint64 const #

const Uint64

Uint8 const #

const Uint8

Uintptr const #

const Uintptr

Universe var #

The Universe scope contains all predeclared objects of Go. It is the outermost scope of any chain of nested scopes.

var Universe *Scope

Unsafe var #

The Unsafe package is the package returned by an importer for the import path "unsafe".

var Unsafe *Package

UnsafePointer const #

const UnsafePointer

UntypedBool const #

types for untyped values

const UntypedBool

UntypedComplex const #

const UntypedComplex

UntypedFloat const #

const UntypedFloat

UntypedInt const #

const UntypedInt

UntypedNil const #

const UntypedNil

UntypedRune const #

const UntypedRune

UntypedString const #

const UntypedString

_Add const #

package unsafe

const _Add

_Alignof const #

const _Alignof

_Append const #

universe scope

const _Append builtinId = iota

_Assert const #

testing support

const _Assert

_Cap const #

const _Cap

_Clear const #

const _Clear

_Close const #

const _Close

_Complex const #

const _Complex

_Copy const #

const _Copy

_Delete const #

const _Delete

_Imag const #

const _Imag

_Len const #

const _Len

_Make const #

const _Make

_Max const #

const _Max

_Min const #

const _Min

_New const #

const _New

_Offsetof const #

const _Offsetof

_Panic const #

const _Panic

_Print const #

const _Print

_Println const #

const _Println

_Real const #

const _Real

_Recover const #

const _Recover

_Sizeof const #

const _Sizeof

_Slice const #

const _Slice

_SliceData const #

const _SliceData

_String const #

const _String

_StringData const #

const _StringData

_Trace const #

const _Trace

_aliasAny var #

_aliasAny changes the behavior of [Scope.Lookup] for "any" in the [Universe] scope. This is necessary because while Alias creation is controlled by [Config.EnableAlias], the representation of "any" is a global. In [Scope.Lookup], we select this global representation based on the result of [aliasAny], but as a result need to guard against this behavior changing during the type checking pass. Therefore we implement the following rule: any number of goroutines can type check concurrently with the same EnableAlias value, but if any goroutine tries to type check concurrently with a different EnableAlias value, we panic. To achieve this, _aliasAny is a state machine: 0: no type checking is occurring negative: type checking is occurring without EnableAlias set positive: type checking is occurring with EnableAlias set

var _aliasAny int32

allTermlist var #

allTermlist represents the set of all types. It is in normal form.

var allTermlist = termlist{...}

assign const #

If assign is set, we are unifying types involved in an assignment: they may match inexactly at the top, but element types must match exactly.

const assign unifyMode = *ast.BinaryExpr

basicAliases var #

var basicAliases = [...]*Basic{...}

basicSizes var #

var basicSizes = [...]byte{...}

binaryOpPredicates var #

var binaryOpPredicates opPredicates

black const #

An object may be painted in one of three colors. Color values other than white or black are considered grey.

const black

breakOk const #

permissible control-flow statements

const breakOk stmtContext = *ast.BinaryExpr

builtin const #

const builtin

cgoPrefixes var #

var cgoPrefixes = [...]string{...}

cgofunc const #

const cgofunc

commaerr const #

const commaerr

commaok const #

const commaok

complete const #

const complete

constant_ const #

const constant_

continueOk const #

const continueOk

conversion const #

const conversion exprKind = iota

debug const #

debugging/development support

const debug = false

emptyInterface var #

emptyInterface represents the empty interface

var emptyInterface = Interface{...}

enableCoreTypeUnification const #

If enableCoreTypeUnification is set, unification will consider the core types, if any, of non-local (unbound) type parameters.

const enableCoreTypeUnification = true

enableReverseTypeInference const #

If enableReverseTypeInference is set, uninstantiated and partially instantiated generic functions may be assigned (incl. returned) to variables of function type and type inference will attempt to infer the missing type arguments. Available with go1.21.

const enableReverseTypeInference = true

exact const #

If exact is set, types unify if they are identical (or can be made identical with suitable arguments for type parameters). Otherwise, a named type and a type literal unify if their underlying types unify, channel directions are ignored, and if there is an interface, the other type must implement the interface.

const exact

expression const #

const expression

fallthroughOk const #

const fallthroughOk

finalSwitchCase const #

additional context information

const finalSwitchCase

gcArchSizes var #

common architecture word sizes and alignments

var gcArchSizes = map[string]*gcSizes{...}

gccgoArchSizes var #

var gccgoArchSizes = map[string]*StdSizes{...}

go1_13 var #

var go1_13 = *ast.CallExpr

go1_14 var #

var go1_14 = *ast.CallExpr

go1_17 var #

var go1_17 = *ast.CallExpr

go1_18 var #

var go1_18 = *ast.CallExpr

go1_20 var #

var go1_20 = *ast.CallExpr

go1_21 var #

var go1_21 = *ast.CallExpr

go1_22 var #

var go1_22 = *ast.CallExpr

go1_23 var #

var go1_23 = *ast.CallExpr

go1_9 var #

Go versions that introduced language changes

var go1_9 = *ast.CallExpr

go_current var #

current (deployed) Go version

var go_current = *ast.CallExpr

grey const #

An object may be painted in one of three colors. Color values other than white or black are considered grey.

const grey

inTypeSwitch const #

const inTypeSwitch

invalid const #

const invalid operandMode = iota

invalidArg const #

const invalidArg = "invalid argument: "

invalidOp const #

const invalidOp = "invalid operation: "

invalidTypeSet var #

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.

var invalidTypeSet _TypeSet

isTypes2 const #

const isTypes2 = true

kind2tok var #

var kind2tok = [...]token.Token{...}

lastID var #

Note: This is a uint32 rather than a uint64 because the respective 64 bit atomic instructions are not available on all platforms.

var lastID atomic.Uint32

mapindex const #

const mapindex

maxTermCount const #

Avoid excessive type-checking times due to quadratic termlist operations.

const maxTermCount = 100

nilvalue const #

const nilvalue

nopos var #

nopos indicates an unknown position

var nopos syntax.Pos

novalue const #

const novalue

op2str1 var #

var op2str1 = [...]string{...}

op2str2 var #

This is only used for operations that may cause overflow.

var op2str2 = [...]string{...}

op2tok var #

op2tok translates syntax.Operators into token.Tokens.

var op2tok = [...]token.Token{...}

operandModeString var #

var operandModeString = [...]string{...}

panicAtUnificationDepthLimit const #

Whether to panic when unificationDepthLimit is reached. If disabled, a recursion depth overflow results in a (quiet) unification failure.

const panicAtUnificationDepthLimit = true

predeclaredConsts var #

var predeclaredConsts = [...]struct{...}{...}

predeclaredFuncs var #

var predeclaredFuncs = [...]struct{...}{...}

resolved const #

const resolved

statement const #

const statement

stdSizes var #

stdSizes is used if Config.Sizes == nil.

var stdSizes = *ast.CallExpr

termSep const #

termSep is the separator used between individual terms.

const termSep = " | "

topTypeSet var #

topTypeSet may be used as type set for the empty interface.

var topTypeSet = _TypeSet{...}

traceInference const #

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

const traceInference = false

typexpr const #

const typexpr

unaryOpPredicates var #

var unaryOpPredicates opPredicates

unificationDepthLimit const #

Upper limit for recursion depth. Used to catch infinite recursions due to implementation issues (e.g., see issues go.dev/issue/48619, go.dev/issue/48656).

const unificationDepthLimit = 50

universeAnyAlias var #

var universeAnyAlias *TypeName

universeAnyNoAlias var #

var universeAnyNoAlias *TypeName

universeBool var #

var universeBool Type

universeByte var #

var universeByte Type

universeComparable var #

var universeComparable Object

universeError var #

var universeError Type

universeIota var #

var universeIota Object

universeRune var #

var universeRune Type

unresolved const #

const unresolved namedState = iota

value const #

const value

variable const #

const variable

white const #

An object may be painted in one of three colors. Color values other than white or black are considered grey.

const white color = iota

Type Aliases

BasicInfo type #

BasicInfo is a set of flags describing properties of a basic type.

type BasicInfo int

BasicKind type #

BasicKind describes the kind of basic type.

type BasicKind int

ChanDir type #

A ChanDir value indicates a channel direction.

type ChanDir int

ImportMode type #

ImportMode is reserved for future use.

type ImportMode int

Qualifier type #

A Qualifier controls how named package-level objects are printed in calls to [TypeString], [ObjectString], and [SelectionString]. These three formatting routines call the Qualifier for each package-level object O, and if the Qualifier returns a non-empty string p, the object is printed in the form p.O. If it returns an empty string, only the object name O is printed. Using a nil Qualifier is equivalent to using (*[Package]).Path: the object is qualified by the import path, e.g., "encoding/json.Marshal".

type Qualifier func(*Package) string

SelectionKind type #

SelectionKind describes the kind of a selector expression x.f (excluding qualified identifiers). If x is a struct or *struct, a selector expression x.f may denote a sequence of selection operations x.a.b.c.f. The SelectionKind describes the kind of the final (explicit) operation; all the previous (implicit) operations are always field selections. Each element of Indices specifies an implicit field (a, b, c) by its index in the struct type of the field selection operand. For a FieldVal operation, the final selection refers to the field specified by Selection.Obj. For a MethodVal operation, the final selection refers to a method. If the "pointerness" of the method's declared receiver does not match that of the effective receiver after implicit field selection, then an & or * operation is implicitly applied to the receiver variable or value. So, x.f denotes (&x.a.b.c).f when f requires a pointer receiver but x.a.b.c is a non-pointer variable; and it denotes (*x.a.b.c).f when f requires a non-pointer receiver but x.a.b.c is a pointer value. All pointer indirections, whether due to implicit or explicit field selections or * operations inserted for "pointerness", panic if applied to a nil pointer, so a method call x.f() may panic even before the function call. By contrast, a MethodExpr operation T.f is essentially equivalent to a function literal of the form: func(x T, args) (results) { return x.f(args) } Consequently, any implicit field selections and * operations inserted for "pointerness" are not evaluated until the function is called, so a T.f or (*T).f expression never panics.

type SelectionKind int

Term type #

A Term represents a term in a Union.

type Term term

Type type #

A Type represents a type of Go. All types implement the Type interface.

type Type syntax.Type

builtinId type #

A builtinId is the id of a builtin function.

type builtinId int

color type #

color encodes the color of an object (see Checker.objDecl for details).

type color uint32

exprKind type #

exprKind describes the kind of an expression; the kind determines if an expression is valid in 'statement context'.

type exprKind int

goVersion type #

A goVersion is a Go language version string of the form "go1.%d" where d is the minor version number. goVersion strings don't contain release numbers ("go1.20.1" is not a valid goVersion).

type goVersion string

namedState type #

namedState represents the possible states that a named type may assume.

type namedState uint32

nodeQueue type #

nodeQueue implements the container/heap interface; a nodeQueue may be used as a priority queue.

type nodeQueue []*graphNode

nodeSet type #

type nodeSet map[*graphNode]bool

objset type #

An objset is a set of objects identified by their unique id. The zero value for objset is a ready-to-use empty objset.

type objset map[string]Object

opPredicates type #

type opPredicates map[syntax.Operator]func(Type) bool

operandMode type #

An operandMode specifies the (addressing) mode of an operand.

type operandMode byte

stmtContext type #

stmtContext is a bitset describing which control-flow statements are permissible, and provides additional context information for better error messages.

type stmtContext uint

substMap type #

type substMap map[*TypeParam]Type

termlist type #

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.

type termlist []*term

typeParamsById type #

type typeParamsById []*TypeParam

unifyMode type #

unifyMode controls the behavior of the unifier.

type unifyMode uint

valueMap type #

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.

type valueMap map[interface{}][]valueType

Interfaces

Importer interface #

An Importer resolves import paths to Packages. CAUTION: This interface does not support the import of locally vendored packages. See https://golang.org/s/go15vendor. If possible, external implementations should implement ImporterFrom.

type Importer interface {
Import(path string) (*Package, error)
}

ImporterFrom interface #

An ImporterFrom resolves import paths to packages; it supports vendoring per https://golang.org/s/go15vendor. Use go/importer to obtain an ImporterFrom implementation.

type ImporterFrom interface {
Importer
ImportFrom(path string, dir string, mode ImportMode) (*Package, error)
}

Object interface #

An Object is a named language entity. An Object may be a constant ([Const]), type name ([TypeName]), variable or struct field ([Var]), function or method ([Func]), imported package ([PkgName]), label ([Label]), built-in function ([Builtin]), or the predeclared identifier 'nil' ([Nil]). The environment, which is structured as a tree of Scopes, maps each name to the unique Object that it denotes.

type Object interface {
Parent() *Scope
Pos() syntax.Pos
Pkg() *Package
Name() string
Type() Type
Exported() bool
Id() string
String() string
order() uint32
color() color
setType(Type)
setOrder(uint32)
setColor(color color)
setParent(*Scope)
sameId(pkg *Package, name string, foldCase bool) bool
scopePos() syntax.Pos
setScopePos(pos syntax.Pos)
}

Sizes interface #

Sizes defines the sizing functions for package unsafe.

type Sizes interface {
Alignof(T Type) int64
Offsetsof(fields []*Var) []int64
Sizeof(T Type) int64
}

cleaner interface #

type cleaner interface {
cleanup()
}

dependency interface #

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.

type dependency interface {
Object
isDependency()
}

genericType interface #

A genericType implements access to its type parameters.

type genericType interface {
Type
TypeParams() *TypeParamList
}

poser interface #

The poser interface is used to extract the position of type-checker errors.

type poser interface {
Pos() syntax.Pos
}

Structs

Alias struct #

An Alias represents an alias type. Alias types are created by alias declarations such as: type A = int The type on the right-hand side of the declaration can be accessed using [Alias.Rhs]. This type may itself be an alias. Call [Unalias] to obtain the first non-alias type in a chain of alias type declarations. Like a defined ([Named]) type, an alias type has a name. Use the [Alias.Obj] method to access its [TypeName] object. Historically, Alias types were not materialized so that, in the example above, A's type was represented by a Basic (int), not an Alias whose [Alias.Rhs] is int. But Go 1.24 allows you to declare an alias type with type parameters or arguments: type Set[K comparable] = map[K]bool s := make(Set[String]) and this requires that Alias types be materialized. Use the [Alias.TypeParams] and [Alias.TypeArgs] methods to access them. To ease the transition, the Alias type was introduced in go1.22, but the type-checker would not construct values of this type unless the GODEBUG=gotypesalias=1 environment variable was provided. Starting in go1.23, this variable is enabled by default. This setting also causes the predeclared type "any" to be represented as an Alias, not a bare [Interface].

type Alias struct {
obj *TypeName
orig *Alias
tparams *TypeParamList
targs *TypeList
fromRHS Type
actual Type
}

ArgumentError struct #

An ArgumentError holds an error associated with an argument index.

type ArgumentError struct {
Index int
Err error
}

Array struct #

An Array represents an array type.

type Array struct {
len int64
elem Type
}

Basic struct #

A Basic represents a basic type.

type Basic struct {
kind BasicKind
info BasicInfo
name string
}

Builtin struct #

A Builtin represents a built-in function. Builtins don't have a valid type.

type Builtin struct {
object
id builtinId
}

Chan struct #

A Chan represents a channel type.

type Chan struct {
dir ChanDir
elem Type
}

Checker struct #

A Checker maintains the state of the type checker. It must be created with NewChecker.

type Checker struct {
conf *Config
ctxt *Context
pkg *Package
*Info
nextID uint64
objMap map[Object]*declInfo
impMap map[importKey]*Package
pkgPathMap map[string]map[string]bool
seenPkgMap map[*Package]bool
files []*syntax.File
versions map[*syntax.PosBase]string
imports []*PkgName
dotImportMap map[dotImportKey]*PkgName
brokenAliases map[*TypeName]bool
unionTypeSets map[*Union]*_TypeSet
usedVars map[*Var]bool
usedPkgNames map[*PkgName]bool
mono monoGraph
firstErr error
methods map[*TypeName][]*Func
untyped map[syntax.Expr]exprInfo
delayed []action
objPath []Object
cleaners []cleaner
environment
indent int
}

Config struct #

A Config specifies the configuration for type checking. The zero value for Config is a ready-to-use default configuration.

type Config struct {
Context *Context
GoVersion string
IgnoreFuncBodies bool
FakeImportC bool
IgnoreBranchErrors bool
go115UsesCgo bool
Trace bool
Error func(err error)
Importer Importer
Sizes Sizes
DisableUnusedImportCheck bool
ErrorURL string
EnableAlias bool
}

Const struct #

A Const represents a declared constant.

type Const struct {
object
val constant.Value
}

Context struct #

A Context is an opaque type checking context. It may be used to share identical type instances across type-checked packages or calls to Instantiate. Contexts are safe for concurrent use. The use of a shared context does not guarantee that identical instances are deduplicated in all cases.

type Context struct {
mu sync.Mutex
typeMap map[string][]ctxtEntry
nextID int
originIDs map[Type]int
}

Error struct #

An Error describes a type-checking error; it implements the error interface. A "soft" error is an error that still permits a valid interpretation of a package (such as "unused variable"); "hard" errors may lead to unpredictable behavior if ignored.

type Error struct {
Pos syntax.Pos
Msg string
Full string
Soft bool
Code Code
}

Func struct #

A Func represents a declared function, concrete method, or abstract (interface) method. Its Type() is always a *Signature. An abstract method may belong to many interfaces due to embedding.

type Func struct {
object
hasPtrRecv_ bool
origin *Func
}

Info struct #

Info holds result type information for a type-checked package. Only the information for which a map is provided is collected. If the package has type errors, the collected information may be incomplete.

type Info struct {
Types map[syntax.Expr]TypeAndValue
StoreTypesInSyntax bool
Instances map[*syntax.Name]Instance
Defs map[*syntax.Name]Object
Uses map[*syntax.Name]Object
Implicits map[syntax.Node]Object
Selections map[*syntax.SelectorExpr]*Selection
Scopes map[syntax.Node]*Scope
InitOrder []*Initializer
FileVersions map[*syntax.PosBase]string
}

Initializer struct #

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.

type Initializer struct {
Lhs []*Var
Rhs syntax.Expr
}

Instance struct #

Instance reports the type arguments and instantiated type for type and function instantiations. For type instantiations, Type will be of dynamic type *Named. For function instantiations, Type will be of dynamic type *Signature.

type Instance struct {
TypeArgs *TypeList
Type Type
}

Interface struct #

An Interface represents an interface type.

type Interface struct {
check *Checker
methods []*Func
embeddeds []Type
embedPos *[]syntax.Pos
implicit bool
complete bool
tset *_TypeSet
}

Label struct #

A Label represents a declared label. Labels don't have a type.

type Label struct {
object
used bool
}

Map struct #

A Map represents a map type.

type Map struct {
key Type
elem Type
}

Named struct #

A Named represents a named (defined) type. A declaration such as: type S struct { ... } creates a defined type whose underlying type is a struct, and binds this type to the object S, a [TypeName]. Use [Named.Underlying] to access the underlying type. Use [Named.Obj] to obtain the object S. Before type aliases (Go 1.9), the spec called defined types "named types".

type Named struct {
check *Checker
obj *TypeName
fromRHS Type
inst *instance
mu sync.Mutex
state_ uint32
underlying Type
tparams *TypeParamList
methods []*Func
loader func(*Named) (tparams []*TypeParam, underlying Type, methods []*Func)
}

Nil struct #

Nil represents the predeclared value nil.

type Nil struct {
object
}

Package struct #

A Package describes a Go package.

type Package struct {
path string
name string
scope *Scope
imports []*Package
complete bool
fake bool
cgo bool
goVersion string
}

PkgName struct #

A PkgName represents an imported Go package. PkgNames don't have a type.

type PkgName struct {
object
imported *Package
}

Pointer struct #

A Pointer represents a pointer type.

type Pointer struct {
base Type
}

Scope struct #

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.

type Scope struct {
parent *Scope
children []*Scope
number int
elems map[string]Object
pos syntax.Pos
end syntax.Pos
comment string
isFunc bool
}

Selection struct #

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

type Selection struct {
kind SelectionKind
recv Type
obj Object
index []int
indirect bool
}

Signature struct #

A Signature represents a (non-builtin) function or method type. The receiver is ignored when comparing signatures for identity.

type Signature struct {
rparams *TypeParamList
tparams *TypeParamList
scope *Scope
recv *Var
params *Tuple
results *Tuple
variadic bool
}

Slice struct #

A Slice represents a slice type.

type Slice struct {
elem Type
}

StdSizes struct #

StdSizes is a convenience type for creating commonly used Sizes. It makes the following simplifying assumptions: - The size of explicitly sized basic types (int16, etc.) is the specified size. - The size of strings and interfaces is 2*WordSize. - The size of slices is 3*WordSize. - The size of an array of n elements corresponds to the size of a struct of n consecutive fields of the array's element type. - The size of a struct is the offset of the last field plus that field's size. As with all element types, if the struct is used in an array its size must first be aligned to a multiple of the struct's alignment. - All other types have size WordSize. - Arrays and structs are aligned per spec definition; all other types are naturally aligned with a maximum alignment MaxAlign. *StdSizes implements Sizes.

type StdSizes struct {
WordSize int64
MaxAlign int64
}

Struct struct #

A Struct represents a struct type.

type Struct struct {
fields []*Var
tags []string
}

Tuple struct #

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.

type Tuple struct {
vars []*Var
}

TypeAndValue struct #

TypeAndValue reports the type and value (for constants) of the corresponding expression.

type TypeAndValue struct {
mode operandMode
Type Type
Value constant.Value
}

TypeList struct #

TypeList holds a list of types.

type TypeList struct {
types []Type
}

TypeName struct #

A TypeName is an [Object] that represents a type with a name: a defined type ([Named]), an alias type ([Alias]), a type parameter ([TypeParam]), or a predeclared type such as int or error.

type TypeName struct {
object
}

TypeParam struct #

A TypeParam represents the type of a type parameter in a generic declaration. A TypeParam has a name; use the [TypeParam.Obj] method to access its [TypeName] object.

type TypeParam struct {
check *Checker
id uint64
obj *TypeName
index int
bound Type
}

TypeParamList struct #

TypeParamList holds a list of type parameters.

type TypeParamList struct {
tparams []*TypeParam
}

Union struct #

A Union represents a union of terms embedded in an interface.

type Union struct {
terms []*Term
}

Var struct #

A Variable represents a declared variable (including function parameters and results, and struct fields).

type Var struct {
object
origin *Var
embedded bool
isField bool
isParam bool
}

_TypeSet struct #

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.

type _TypeSet struct {
methods []*Func
terms termlist
comparable bool
}

action struct #

An action describes a (delayed) action.

type action struct {
version goVersion
f func()
desc *actionDesc
}

actionDesc struct #

An actionDesc provides information on an action. For debugging only.

type actionDesc struct {
pos poser
format string
args []interface{}
}

bailout struct #

A bailout panic is used for early termination.

type bailout struct {

}

block struct #

A block tracks label declarations in a block and its enclosing blocks.

type block struct {
parent *block
lstmt *syntax.LabeledStmt
labels map[string]*syntax.LabeledStmt
}

comparer struct #

A comparer is used to compare types.

type comparer struct {
ignoreTags bool
ignoreInvalids bool
}

ctxtEntry struct #

type ctxtEntry struct {
orig Type
targs []Type
instance Type
}

cycleFinder struct #

type cycleFinder struct {
tparams []*TypeParam
inferred []Type
seen map[Type]bool
}

declInfo struct #

A declInfo describes a package-level const, type, var, or func declaration.

type declInfo struct {
file *Scope
version goVersion
lhs []*Var
vtyp syntax.Expr
init syntax.Expr
inherited bool
tdecl *syntax.TypeDecl
fdecl *syntax.FuncDecl
deps map[Object]bool
}

dotImportKey struct #

A dotImportKey describes a dot-imported object in the given scope.

type dotImportKey struct {
scope *Scope
name string
}

embeddedType struct #

embeddedType represents an embedded type

type embeddedType struct {
typ Type
index []int
indirect bool
multiples bool
}

environment struct #

An environment represents the environment within which an object is type-checked.

type environment struct {
decl *declInfo
scope *Scope
version goVersion
iota constant.Value
errpos syntax.Pos
inTParamList bool
sig *Signature
isPanic map[*syntax.CallExpr]bool
hasLabel bool
hasCallOrRecv bool
}

errorDesc struct #

An errorDesc describes part of a type-checking error.

type errorDesc struct {
pos syntax.Pos
msg string
}

error_ struct #

An error_ represents a type-checking error. A new error_ is created with Checker.newError. To report an error_, call error_.report.

type error_ struct {
check *Checker
desc []errorDesc
code Code
soft bool
}

exprInfo struct #

exprInfo stores information about an untyped expression.

type exprInfo struct {
isLhs bool
mode operandMode
typ *Basic
val constant.Value
}

gcSizes struct #

type gcSizes struct {
WordSize int64
MaxAlign int64
}

graphNode struct #

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.

type graphNode struct {
obj dependency
pred nodeSet
succ nodeSet
index int
ndeps int
}

ifacePair struct #

An ifacePair is a node in a stack of interface type pairs compared for identity.

type ifacePair struct {
x *Interface
y *Interface
prev *ifacePair
}

importKey struct #

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).

type importKey struct {
path string
dir string
}

instance struct #

instance holds information that is only necessary for instantiated named types.

type instance struct {
orig *Named
targs *TypeList
expandedMethods int
ctxt *Context
}

instanceLookup struct #

type instanceLookup struct {
buf [3]*Named
m map[*Named][]*Named
}

lazyObject struct #

A lazyObject represents an imported Object that has not been fully resolved yet by its importer.

type lazyObject struct {
parent *Scope
resolve func() Object
obj Object
once sync.Once
}

monoEdge struct #

type monoEdge struct {
dst int
src int
weight int
pos syntax.Pos
typ Type
}

monoGraph struct #

type monoGraph struct {
vertices []monoVertex
edges []monoEdge
canon map[*TypeParam]*TypeParam
nameIdx map[*TypeName]int
}

monoVertex struct #

type monoVertex struct {
weight int
pre int
len int
obj *TypeName
}

object struct #

An object implements the common parts of an Object.

type object struct {
parent *Scope
pos syntax.Pos
pkg *Package
name string
typ Type
order_ uint32
color_ color
scopePos_ syntax.Pos
}

operand struct #

An operand represents an intermediate value during type checking. Operands have an (addressing) mode, the expression evaluating to the operand, the operand's type, a value for constants, and an id for built-in functions. The zero value of operand is a ready to use invalid operand.

type operand struct {
mode operandMode
expr syntax.Expr
typ Type
val constant.Value
id builtinId
}

subster struct #

type subster struct {
pos syntax.Pos
smap substMap
check *Checker
expanding *Named
ctxt *Context
}

target struct #

target represent the (signature) type and description of the LHS variable of an assignment, or of a function result variable.

type target struct {
sig *Signature
desc string
}

term struct #

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

type term struct {
tilde bool
typ Type
}

tpWalker struct #

type tpWalker struct {
tparams []*TypeParam
seen map[Type]bool
}

typeWriter struct #

type typeWriter struct {
buf *bytes.Buffer
seen map[Type]bool
qf Qualifier
ctxt *Context
tparams *TypeParamList
paramNames bool
tpSubscripts bool
pkgInfo bool
}

unifier struct #

A unifier maintains a list of type parameters and corresponding types inferred for each type parameter. A unifier is created by calling newUnifier.

type unifier struct {
handles map[*TypeParam]*Type
depth int
enableInterfaceInference bool
}

valueType struct #

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.

type valueType struct {
pos syntax.Pos
typ Type
}

Functions

AddMethod method #

AddMethod adds method m unless it is already in the method list. The method must be in the same package as t, and t must not have type arguments.

func (t *Named) AddMethod(m *Func)

Addressable method #

Addressable reports whether the corresponding expression is addressable (https://golang.org/ref/spec#Address_operators).

func (tv TypeAndValue) Addressable() bool

Alignof method #

func (s *StdSizes) Alignof(T Type) (result int64)

Alignof method #

func (s *gcSizes) Alignof(T Type) (result int64)

Anonymous method #

Anonymous reports whether the variable is an embedded field. Same as Embedded; only present for backward-compatibility.

func (obj *Var) Anonymous() bool

AsPointer function #

If t is a pointer, AsPointer returns that type, otherwise it returns nil.

func AsPointer(t Type) *Pointer

AsSignature function #

If t is a signature, AsSignature returns that type, otherwise it returns nil.

func AsSignature(t Type) *Signature

AssertableTo function #

AssertableTo reports whether a value of type V can be asserted to have type T. The behavior of AssertableTo is unspecified in three cases: - if T is Typ[Invalid] - if V is a generalized interface; i.e., an interface that may only be used as a type constraint in Go code - if T is an uninstantiated generic type

func AssertableTo(V *Interface, T Type) bool

Assignable method #

Assignable reports whether the corresponding expression is assignable to (provided a value of the right type).

func (tv TypeAndValue) Assignable() bool

AssignableTo function #

AssignableTo reports whether a value of type V is assignable to a variable of type T. The behavior of AssignableTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

func AssignableTo(V Type, T Type) bool

At method #

At returns the i'th type in the list.

func (l *TypeList) At(i int) Type

At method #

At returns the i'th type parameter in the list.

func (l *TypeParamList) At(i int) *TypeParam

At method #

At returns the i'th variable of tuple t.

func (t *Tuple) At(i int) *Var

Check method #

Check type-checks a package and returns the resulting package object and the first error if any. Additionally, if info != nil, Check populates each of the non-nil maps in the Info struct. The package is marked as complete if no errors occurred, otherwise it is incomplete. See Config.Error for controlling behavior in the presence of errors. The package is specified by a list of *syntax.Files and corresponding file set, and the package path the package is identified with. The clean path must not be empty or dot (".").

func (conf *Config) Check(path string, files []*syntax.File, info *Info) (*Package, error)

Child method #

Child returns the i'th child scope for 0 <= i < NumChildren().

func (s *Scope) Child(i int) *Scope

Comparable function #

Comparable reports whether values of type T are comparable.

func Comparable(T Type) bool

Complete method #

A package is complete if its scope contains (at least) all exported objects; otherwise it is incomplete.

func (pkg *Package) Complete() bool

Constraint method #

Constraint returns the type constraint specified for t.

func (t *TypeParam) Constraint() Type

ConvertibleTo function #

ConvertibleTo reports whether a value of type V is convertible to a value of type T. The behavior of ConvertibleTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

func ConvertibleTo(V Type, T Type) bool

CoreType function #

If typ is a type parameter, CoreType returns the single underlying type of all types in the corresponding type constraint if it exists, or nil otherwise. If the type set contains only unrestricted and restricted channel types (with identical element types), the single underlying type is the restricted channel type if the restrictions are always the same. If typ is not a type parameter, CoreType returns the underlying type.

func CoreType(t Type) Type

DefPredeclaredTestFuncs function #

DefPredeclaredTestFuncs defines the assert and trace built-ins. These built-ins are intended for debugging and testing of this package only.

func DefPredeclaredTestFuncs()

Default function #

Default returns the default "typed" type for an "untyped" type; it returns the incoming type for all other types. The default type for untyped nil is untyped nil.

func Default(t Type) Type

Dir method #

Dir returns the direction of channel c.

func (c *Chan) Dir() ChanDir

Elem method #

Elem returns the element type of slice s.

func (s *Slice) Elem() Type

Elem method #

Elem returns the element type of channel c.

func (c *Chan) Elem() Type

Elem method #

Elem returns element type of array a.

func (a *Array) Elem() Type

Elem method #

Elem returns the element type of map m.

func (m *Map) Elem() Type

Elem method #

Elem returns the element type for the given pointer p.

func (p *Pointer) Elem() Type

Embedded method #

Embedded reports whether the variable is an embedded field.

func (obj *Var) Embedded() bool

EmbeddedType method #

EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().

func (t *Interface) EmbeddedType(i int) Type

Empty method #

Empty reports whether t is the empty interface.

func (t *Interface) Empty() bool

Error method #

func (e *ArgumentError) Error() string

Error method #

Error returns an error string formatted as follows: filename:line:column: message

func (err Error) Error() string

ExplicitMethod method #

ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods(). The methods are ordered by their unique Id.

func (t *Interface) ExplicitMethod(i int) *Func

Exported method #

func (*lazyObject) Exported() bool

Exported method #

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (obj *object) Exported() bool

ExprString function #

ExprString returns a string representation of x.

func ExprString(x syntax.Node) string

Field method #

Field returns the i'th field for 0 <= i < NumFields().

func (s *Struct) Field(i int) *Var

Files method #

Files checks the provided files as part of the checker's package.

func (check *Checker) Files(files []*syntax.File) (err error)

FullError method #

FullError returns an error string like Error, buy it may contain type-checker internal details such as subscript indices for type parameters and more. Useful for debugging.

func (err Error) FullError() string

FullName method #

FullName returns the package- or receiver-type-qualified name of function or method obj.

func (obj *Func) FullName() string

GoVersion method #

GoVersion returns the minimum Go version required by this package. If the minimum version is unknown, GoVersion returns the empty string. Individual source files may specify a different minimum Go version, as reported in the [go/ast.File.GoVersion] field.

func (pkg *Package) GoVersion() string

HasOk method #

HasOk reports whether the corresponding expression may be used on the rhs of a comma-ok assignment.

func (tv TypeAndValue) HasOk() bool

Id method #

func (*lazyObject) Id() string

Id function #

Id returns name if it is exported, otherwise it returns the name qualified with the package path.

func Id(pkg *Package, name string) string

Id method #

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (obj *object) Id() string

Identical function #

Identical reports whether x and y are identical types. Receivers of [Signature] types are ignored. Predicates such as [Identical], [Implements], and [Satisfies] assume that both operands belong to a consistent collection of symbols ([Object] values). For example, two [Named] types can be identical only if their [Named.Obj] methods return the same [TypeName] symbol. A collection of symbols is consistent if, for each logical package whose path is P, the creation of those symbols involved at most one call to [NewPackage](P, ...). To ensure consistency, use a single [Importer] for all loaded packages and their dependencies. For more information, see https://github.com/golang/go/issues/57497.

func Identical(x Type, y Type) bool

IdenticalIgnoreTags function #

IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored. Receivers of [Signature] types are ignored.

func IdenticalIgnoreTags(x Type, y Type) bool

Implements function #

Implements reports whether type V implements interface T. The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

func Implements(V Type, T *Interface) bool

Imported method #

Imported returns the package that was imported. It is distinct from Pkg(), which is the package containing the import statement.

func (obj *PkgName) Imported() *Package

Imports method #

Imports returns the list of packages directly imported by pkg; the list is in source order. If pkg was loaded from export data, Imports includes packages that provide package-level objects referenced by pkg. This may be more or less than the set of packages directly imported by pkg's source code. If pkg uses cgo and the FakeImportC configuration option was enabled, the imports list may contain a fake "C" package.

func (pkg *Package) Imports() []*Package

Index method #

Index describes the path from x to f in x.f. The last index entry is the field or method index of the type declaring f; either: 1. the list of declared methods of a named type; or 2. the list of methods of an interface type; or 3. the list of fields of a struct type. The earlier index entries are the indices of the embedded fields implicitly traversed to get from (the type of) x to f, starting at embedding depth 0.

func (s *Selection) Index() []int

Index method #

Index returns the index of the type param within its param list, or -1 if the type parameter has not yet been bound to a type.

func (t *TypeParam) Index() int

Indirect method #

Indirect reports whether any pointer indirection was required to get from x to f in x.f. Beware: Indirect spuriously returns true (Go issue #8353) for a MethodVal selection in which the receiver argument and parameter both have type *T so there is no indirection. Unfortunately, a fix is too risky.

func (s *Selection) Indirect() bool

Info method #

Info returns information about properties of basic type b.

func (b *Basic) Info() BasicInfo

Insert method #

Insert attempts to insert an object obj into scope s. If s already contains an alternative object alt with the same name, Insert leaves s unchanged and returns alt. Otherwise it inserts obj, sets the object's parent scope if not already set, and returns nil.

func (s *Scope) Insert(obj Object) Object

InsertLazy method #

InsertLazy is like Insert, but allows deferring construction of the inserted object until it's accessed with Lookup. The Object returned by resolve must have the same name as given to InsertLazy. If s already contains an alternative object with the same name, InsertLazy leaves s unchanged and returns false. Otherwise it records the binding and returns true. The object's parent scope will be set to s after resolve is called.

func (s *Scope) InsertLazy(name string, resolve func() Object) bool

Instantiate function #

Instantiate instantiates the type orig with the given type arguments targs. orig must be an *Alias, *Named, or *Signature type. If there is no error, the resulting Type is an instantiated type of the same kind (*Alias, *Named or *Signature, respectively). Methods attached to a *Named type are also instantiated, and associated with a new *Func that has the same position as the original method, but nil function scope. If ctxt is non-nil, it may be used to de-duplicate the instance against previous instances with the same identity. As a special case, generic *Signature origin types are only considered identical if they are pointer equivalent, so that instantiating distinct (but possibly identical) signatures will yield different instances. The use of a shared context does not guarantee that identical instances are deduplicated in all cases. If validate is set, Instantiate verifies that the number of type arguments and parameters match, and that the type arguments satisfy their respective type constraints. If verification fails, the resulting error may wrap an *ArgumentError indicating which type argument did not satisfy its type parameter constraint, and why. If validate is not set, Instantiate does not verify the type argument count or whether the type arguments satisfy their constraints. Instantiate is guaranteed to not return an error, but may panic. Specifically, for *Signature types, Instantiate will panic immediately if the type argument count is incorrect; for *Named types, a panic may occur later inside the *Named API.

func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)

IsAlias method #

IsAlias reports whether obj is an alias name for a type.

func (obj *TypeName) IsAlias() bool

IsAll method #

IsAll reports whether s is the set of all types (corresponding to the empty interface).

func (s *_TypeSet) IsAll() bool

IsBuiltin method #

IsBuiltin reports whether the corresponding expression denotes a (possibly parenthesized) built-in function.

func (tv TypeAndValue) IsBuiltin() bool

IsComparable method #

IsComparable reports whether each type in interface t's type set is comparable.

func (t *Interface) IsComparable() bool

IsComparable method #

IsComparable reports whether each type in the set is comparable.

func (s *_TypeSet) IsComparable(seen map[Type]bool) bool

IsEmpty method #

IsEmpty reports whether s is the empty set.

func (s *_TypeSet) IsEmpty() bool

IsField method #

IsField reports whether the variable is a struct field.

func (obj *Var) IsField() bool

IsImplicit method #

IsImplicit reports whether the interface t is a wrapper for a type set literal.

func (t *Interface) IsImplicit() bool

IsInterface function #

IsInterface reports whether t is an interface type.

func IsInterface(t Type) bool

IsMethodSet method #

IsMethodSet reports whether the interface t is fully described by its method set.

func (t *Interface) IsMethodSet() bool

IsMethodSet method #

IsMethodSet reports whether the interface t is fully described by its method set.

func (s *_TypeSet) IsMethodSet() bool

IsNil method #

IsNil reports whether the corresponding expression denotes the predeclared value nil. Depending on context, it may have been given a type different from UntypedNil.

func (tv TypeAndValue) IsNil() bool

IsSyncAtomicAlign64 function #

func IsSyncAtomicAlign64(T Type) bool

IsType method #

IsType reports whether the corresponding expression specifies a type.

func (tv TypeAndValue) IsType() bool

IsValue method #

IsValue reports whether the corresponding expression is a value. Builtins are not considered values. Constant values have a non- nil Value.

func (tv TypeAndValue) IsValue() bool

IsVoid method #

IsVoid reports whether the corresponding expression is a function call without results.

func (tv TypeAndValue) IsVoid() bool

Key method #

Key returns the key type of map m.

func (m *Map) Key() Type

Kind method #

Kind returns the selection kind.

func (s *Selection) Kind() SelectionKind

Kind method #

Kind returns the kind of basic type b.

func (b *Basic) Kind() BasicKind

Len method #

Len returns the number of type parameters in the list. It is safe to call on a nil receiver.

func (l *TypeParamList) Len() int

Len method #

func (s typeParamsById) Len() int

Len method #

func (a nodeQueue) Len() int

Len method #

Len returns the number of types in the list. It is safe to call on a nil receiver.

func (l *TypeList) Len() int

Len method #

func (u *Union) Len() int

Len method #

Len returns the number variables of tuple t.

func (t *Tuple) Len() int

Len method #

Len returns the length of array a. A negative result indicates an unknown length.

func (a *Array) Len() int64

Len method #

Len returns the number of scope elements.

func (s *Scope) Len() int

Less method #

func (a nodeQueue) Less(i int, j int) bool

Less method #

func (s typeParamsById) Less(i int, j int) bool

Lookup method #

Lookup returns the object in scope s with the given name if such an object exists; otherwise the result is nil.

func (s *Scope) Lookup(name string) Object

LookupFieldOrMethod function #

LookupFieldOrMethod looks up a field or method with given package and name in T and returns the corresponding *Var or *Func, an index sequence, and a bool indicating if there were any pointer indirections on the path to the field or method. If addressable is set, T is the type of an addressable variable (only matters for method lookups). T must not be nil. The last index entry is the field or method index in the (possibly embedded) type where the entry was found, either: 1. the list of declared methods of a named type; or 2. the list of all methods (method set) of an interface type; or 3. the list of fields of a struct type. The earlier index entries are the indices of the embedded struct fields traversed to get to the found entry, starting at depth 0. If no entry is found, a nil object is returned. In this case, the returned index and indirect values have the following meaning: - If index != nil, the index sequence points to an ambiguous entry (the same name appeared more than once at the same embedding level). - If indirect is set, a method with a pointer receiver type was found but there was no pointer on the path from the actual receiver type to the method's formal receiver base type, nor was the receiver addressable.

func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)

LookupMethod method #

LookupMethod returns the index of and method with matching package and name, or (-1, nil).

func (s *_TypeSet) LookupMethod(pkg *Package, name string, foldCase bool) (int, *Func)

MarkComplete method #

MarkComplete marks a package as complete.

func (pkg *Package) MarkComplete()

MarkImplicit method #

MarkImplicit marks the interface t as implicit, meaning this interface corresponds to a constraint literal such as ~T or A|B without explicit interface embedding. MarkImplicit should be called before any concurrent use of implicit interfaces.

func (t *Interface) MarkImplicit()

Method method #

Method returns the i'th method of named type t for 0 <= i < t.NumMethods(). For an ordinary or instantiated type t, the receiver base type of this method is the named type t. For an uninstantiated generic type t, each method receiver is instantiated with its receiver type parameters. Methods are numbered deterministically: given the same list of source files presented to the type checker, or the same sequence of NewMethod and AddMethod calls, the mapping from method index to corresponding method remains the same. But the specific ordering is not specified and must not be relied on as it may change in the future.

func (t *Named) Method(i int) *Func

Method method #

Method returns the i'th method of s for 0 <= i < s.NumMethods(). The methods are ordered by their unique ID.

func (s *_TypeSet) Method(i int) *Func

Method method #

Method returns the i'th method of interface t for 0 <= i < t.NumMethods(). The methods are ordered by their unique Id.

func (t *Interface) Method(i int) *Func

MissingMethod function #

MissingMethod returns (nil, false) if V implements T, otherwise it returns a missing method required by T and whether it is missing or just has the wrong type: either a pointer receiver or wrong signature. For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Otherwise (V is an interface and static is not set), MissingMethod only checks that methods of T which are also present in V have matching types (e.g., for a type assertion x.(T) where x is of interface type V).

func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)

Name method #

func (*lazyObject) Name() string

Name method #

Name returns the package name.

func (pkg *Package) Name() string

Name method #

Name returns the name of basic type b.

func (b *Basic) Name() string

Name method #

Name returns the object's (package-local, unqualified) name.

func (obj *object) Name() string

Names method #

Names returns the scope's element names in sorted order.

func (s *Scope) Names() []string

NewAlias function #

NewAlias creates a new Alias type with the given type name and rhs. rhs must not be nil.

func NewAlias(obj *TypeName, rhs Type) *Alias

NewArray function #

NewArray returns a new array type for the given element type and length. A negative length indicates an unknown length.

func NewArray(elem Type, len int64) *Array

NewChan function #

NewChan returns a new channel type for the given direction and element type.

func NewChan(dir ChanDir, elem Type) *Chan

NewChecker function #

NewChecker returns a new Checker instance for a given package. Package files may be added incrementally via checker.Files.

func NewChecker(conf *Config, pkg *Package, info *Info) *Checker

NewConst function #

NewConst returns a new constant with value val. The remaining arguments set the attributes found with all Objects.

func NewConst(pos syntax.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const

NewContext function #

NewContext creates a new Context.

func NewContext() *Context

NewField function #

NewField returns a new variable representing a struct field. For embedded fields, the name is the unqualified type name under which the field is accessible.

func NewField(pos syntax.Pos, pkg *Package, name string, typ Type, embedded bool) *Var

NewFunc function #

NewFunc returns a new function with the given signature, representing the function's type.

func NewFunc(pos syntax.Pos, pkg *Package, name string, sig *Signature) *Func

NewInterfaceType function #

NewInterfaceType returns a new interface for the given methods and embedded types. NewInterfaceType takes ownership of the provided methods and may modify their types by setting missing receivers.

func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface

NewLabel function #

NewLabel returns a new label.

func NewLabel(pos syntax.Pos, pkg *Package, name string) *Label

NewMap function #

NewMap returns a new map for the given key and element types.

func NewMap(key Type, elem Type) *Map

NewNamed function #

NewNamed returns a new named type for the given type name, underlying type, and associated methods. If the given type name obj doesn't have a type yet, its type is set to the returned named type. The underlying type must not be a *Named.

func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named

NewPackage function #

NewPackage returns a new Package for the given package path and name. The package is not complete and contains no explicit imports.

func NewPackage(path string, name string) *Package

NewParam function #

NewParam returns a new variable representing a function parameter.

func NewParam(pos syntax.Pos, pkg *Package, name string, typ Type) *Var

NewPkgName function #

NewPkgName returns a new PkgName object representing an imported package. The remaining arguments set the attributes found with all Objects.

func NewPkgName(pos syntax.Pos, pkg *Package, name string, imported *Package) *PkgName

NewPointer function #

NewPointer returns a new pointer type for the given element (base) type.

func NewPointer(elem Type) *Pointer

NewScope function #

NewScope returns a new, empty scope contained in the given parent scope, if any. The comment is for debugging only.

func NewScope(parent *Scope, pos syntax.Pos, end syntax.Pos, comment string) *Scope

NewSignatureType function #

NewSignatureType creates a new function type for the given receiver, receiver type parameters, type parameters, parameters, and results. If variadic is set, params must hold at least one parameter and the last parameter's core type must be of unnamed slice or bytestring type. If recv is non-nil, typeParams must be empty. If recvTypeParams is non-empty, recv must be non-nil.

func NewSignatureType(recv *Var, recvTypeParams []*TypeParam, typeParams []*TypeParam, params *Tuple, results *Tuple, variadic bool) *Signature

NewSlice function #

NewSlice returns a new slice type for the given element type.

func NewSlice(elem Type) *Slice

NewStruct function #

NewStruct returns a new struct with the given fields and corresponding field tags. If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be only as long as required to hold the tag with the largest index i. Consequently, if no field has a tag, tags may be nil.

func NewStruct(fields []*Var, tags []string) *Struct

NewTerm function #

NewTerm returns a new union term.

func NewTerm(tilde bool, typ Type) *Term

NewTuple function #

NewTuple returns a new tuple for the given variables.

func NewTuple(x ...*Var) *Tuple

NewTypeName function #

NewTypeName returns a new type name denoting the given typ. The remaining arguments set the attributes found with all Objects. The typ argument may be a defined (Named) type or an alias type. It may also be nil such that the returned TypeName can be used as argument for NewNamed, which will set the TypeName's type as a side- effect.

func NewTypeName(pos syntax.Pos, pkg *Package, name string, typ Type) *TypeName

NewTypeNameLazy function #

NewTypeNameLazy returns a new defined type like NewTypeName, but it lazily calls resolve to finish constructing the Named object.

func NewTypeNameLazy(pos syntax.Pos, pkg *Package, name string, load func(named *Named) (tparams []*TypeParam, underlying Type, methods []*Func)) *TypeName

NewTypeParam function #

NewTypeParam returns a new TypeParam. Type parameters may be set on a Named type by calling SetTypeParams. Setting a type parameter on more than one type will result in a panic. The constraint argument can be nil, and set later via SetConstraint. If the constraint is non-nil, it must be fully defined.

func NewTypeParam(obj *TypeName, constraint Type) *TypeParam

NewUnion function #

NewUnion returns a new Union type with the given terms. It is an error to create an empty union; they are syntactically not possible.

func NewUnion(terms []*Term) *Union

NewVar function #

NewVar returns a new variable. The arguments set the attributes found with all Objects.

func NewVar(pos syntax.Pos, pkg *Package, name string, typ Type) *Var

NumChildren method #

NumChildren returns the number of scopes nested in s.

func (s *Scope) NumChildren() int

NumEmbeddeds method #

NumEmbeddeds returns the number of embedded types in interface t.

func (t *Interface) NumEmbeddeds() int

NumExplicitMethods method #

NumExplicitMethods returns the number of explicitly declared methods of interface t.

func (t *Interface) NumExplicitMethods() int

NumFields method #

NumFields returns the number of fields in the struct (including blank and embedded fields).

func (s *Struct) NumFields() int

NumMethods method #

NumMethods returns the number of methods available.

func (s *_TypeSet) NumMethods() int

NumMethods method #

NumMethods returns the total number of methods of interface t.

func (t *Interface) NumMethods() int

NumMethods method #

NumMethods returns the number of explicit methods defined for t.

func (t *Named) NumMethods() int

Obj method #

Obj returns the type name for the declaration defining the alias type a. For instantiated types, this is same as the type name of the origin type.

func (a *Alias) Obj() *TypeName

Obj method #

Obj returns the type name for the type parameter t.

func (t *TypeParam) Obj() *TypeName

Obj method #

Obj returns the type name for the declaration defining the named type t. For instantiated types, this is same as the type name of the origin type.

func (t *Named) Obj() *TypeName

Obj method #

Obj returns the object denoted by x.f; a *Var for a field selection, and a *Func in all other cases.

func (s *Selection) Obj() Object

ObjectOf method #

ObjectOf returns the object denoted by the specified id, or nil if not found. If id is an embedded struct field, ObjectOf returns the field (*Var) it defines, not the type (*TypeName) it uses. Precondition: the Uses and Defs maps are populated.

func (info *Info) ObjectOf(id *syntax.Name) Object

ObjectString function #

ObjectString returns the string form of obj. The Qualifier controls the printing of package-level objects, and may be nil.

func ObjectString(obj Object, qf Qualifier) string

Offsetsof method #

func (s *StdSizes) Offsetsof(fields []*Var) []int64

Offsetsof method #

func (s *gcSizes) Offsetsof(fields []*Var) []int64

Origin method #

Origin returns the generic Alias type of which a is an instance. If a is not an instance of a generic alias, Origin returns a.

func (a *Alias) Origin() *Alias

Origin method #

Origin returns the canonical Func for its receiver, i.e. the Func object recorded in Info.Defs. For synthetic functions created during instantiation (such as methods on an instantiated Named type or interface methods that depend on type arguments), this will be the corresponding Func on the generic (uninstantiated) type. For all other Funcs Origin returns the receiver.

func (obj *Func) Origin() *Func

Origin method #

Origin returns the canonical Var for its receiver, i.e. the Var object recorded in Info.Defs. For synthetic Vars created during instantiation (such as struct fields or function parameters that depend on type arguments), this will be the corresponding Var on the generic (uninstantiated) type. For all other Vars Origin returns the receiver.

func (obj *Var) Origin() *Var

Origin method #

Origin returns the generic type from which the named type t is instantiated. If t is not an instantiated type, the result is t.

func (t *Named) Origin() *Named

Params method #

Params returns the parameters of signature s, or nil.

func (s *Signature) Params() *Tuple

Parent method #

stub implementations so *lazyObject implements Object and we can store them directly into Scope.elems.

func (*lazyObject) Parent() *Scope

Parent method #

Parent returns the scope's containing (parent) scope.

func (s *Scope) Parent() *Scope

Parent method #

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (obj *object) Parent() *Scope

Path method #

Path returns the package path.

func (pkg *Package) Path() string

Pkg method #

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (obj *object) Pkg() *Package

Pkg method #

func (*lazyObject) Pkg() *Package

Pkg method #

Pkg returns the package to which the function belongs. The result is nil for methods of types in the Universe scope, like method Error of the error built-in interface type.

func (obj *Func) Pkg() *Package

PkgNameOf method #

PkgNameOf returns the local package name defined by the import, or nil if not found. For dot-imports, the package name is ".". Precondition: the Defs and Implicts maps are populated.

func (info *Info) PkgNameOf(imp *syntax.ImportDecl) *PkgName

Pop method #

func (a *nodeQueue) Pop() any

Pos method #

Pos returns the declaration position of the object's identifier.

func (obj *object) Pos() syntax.Pos

Pos method #

func (*lazyObject) Pos() syntax.Pos

Pos method #

Pos returns the position of the expression corresponding to x. If x is invalid the position is nopos.

func (x *operand) Pos() syntax.Pos

Push method #

func (a *nodeQueue) Push(x any)

RangeKeyVal function #

RangeKeyVal returns the key and value types for a range over typ. It panics if range over typ is invalid.

func RangeKeyVal(typ Type) (Type, Type)

Recv method #

Recv returns the type of x in x.f.

func (s *Selection) Recv() Type

Recv method #

Recv returns the receiver of signature s (if a method), or nil if a function. It is ignored when comparing signatures for identity. For an abstract method, Recv returns the enclosing interface either as a *[Named] or an *[Interface]. Due to embedding, an interface may contain methods whose receiver type is a different interface.

func (s *Signature) Recv() *Var

RecvTypeParams method #

RecvTypeParams returns the receiver type parameters of signature s, or nil.

func (s *Signature) RecvTypeParams() *TypeParamList

RelativeTo function #

RelativeTo returns a [Qualifier] that fully qualifies members of all packages other than pkg.

func RelativeTo(pkg *Package) Qualifier

RenameResult method #

RenameResult takes an array of (result) fields and an index, and if the indexed field does not have a name and if the result in the signature also does not have a name, then the signature and field are renamed to fmt.Sprintf("#rv%d", i+1) the newly named object is inserted into the signature's scope, and the object and new field name are returned. The intended use for RenameResult is to allow rangefunc to assign results within a closure. This is a hack, as narrowly targeted as possible to discourage abuse.

func (s *Signature) RenameResult(results []*syntax.Field, i int) (*Var, *syntax.Name)

Results method #

Results returns the results of signature s, or nil.

func (s *Signature) Results() *Tuple

Rhs method #

Rhs returns the type R on the right-hand side of an alias declaration "type A = R", which may be another alias.

func (a *Alias) Rhs() Type

Satisfies function #

Satisfies reports whether type V satisfies the constraint T. The behavior of Satisfies is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

func Satisfies(V Type, T *Interface) bool

Scope method #

Scope returns the scope of the function's body block. The result is nil for imported or instantiated functions and methods (but there is also no mechanism to get to an instantiated function).

func (obj *Func) Scope() *Scope

Scope method #

Scope returns the (complete or incomplete) package scope holding the objects declared at package level (TypeNames, Consts, Vars, and Funcs). For a nil pkg receiver, Scope returns the Universe scope.

func (pkg *Package) Scope() *Scope

SelectionString function #

SelectionString returns the string form of s. The Qualifier controls the printing of package-level objects, and may be nil. Examples: "field (T) f int" "method (T) f(X) Y" "method expr (T) f(X) Y"

func SelectionString(s *Selection, qf Qualifier) string

SetConstraint method #

SetConstraint sets the type constraint for t. It must be called by users of NewTypeParam after the bound's underlying is fully defined, and before using the type parameter in any way other than to form other types. Once SetConstraint returns the receiver, t is safe for concurrent use.

func (t *TypeParam) SetConstraint(bound Type)

SetImports method #

SetImports sets the list of explicitly imported packages to list. It is the caller's responsibility to make sure list elements are unique.

func (pkg *Package) SetImports(list []*Package)

SetName method #

SetName sets the package name.

func (pkg *Package) SetName(name string)

SetTypeParams method #

SetTypeParams sets the type parameters of the alias type a. The alias a must not have type arguments.

func (a *Alias) SetTypeParams(tparams []*TypeParam)

SetTypeParams method #

SetTypeParams sets the type parameters of the named type t. t must not have type arguments.

func (t *Named) SetTypeParams(tparams []*TypeParam)

SetUnderlying method #

SetUnderlying sets the underlying type and marks t as complete. t must not have type arguments.

func (t *Named) SetUnderlying(underlying Type)

Signature method #

Signature returns the signature (type) of the function or method.

func (obj *Func) Signature() *Signature

Sizeof method #

func (s *gcSizes) Sizeof(T Type) int64

Sizeof method #

func (s *StdSizes) Sizeof(T Type) int64

SizesFor function #

SizesFor returns the Sizes used by a compiler for an architecture. The result is nil if a compiler/architecture pair is not known. Supported architectures for compiler "gc": "386", "amd64", "amd64p32", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm".

func SizesFor(compiler string, arch string) Sizes

String method #

func (obj *Nil) String() string

String method #

String returns a string representation of the scope, for debugging.

func (s *Scope) String() string

String method #

func (p *Pointer) String() string

String method #

func (c *Chan) String() string

String method #

String returns a string representation of the current mapping from type parameters to types.

func (u *unifier) String() string

String method #

func (a *Array) String() string

String method #

func (x *term) String() string

String method #

func (obj *Label) String() string

String method #

func (s *Slice) String() string

String method #

func (c color) String() string

String method #

func (t *Interface) String() string

String method #

func (init *Initializer) String() string

String method #

String prints the termlist exactly (without normalization).

func (xl termlist) String() string

String method #

func (obj *object) String() string

String method #

func (m unifyMode) String() string

String method #

func (s *Selection) String() string

String method #

func (t *Named) String() string

String method #

func (s *Signature) String() string

String method #

func (obj *Var) String() string

String method #

func (pkg *Package) String() string

String method #

func (u *Union) String() string

String method #

func (a *Alias) String() string

String method #

func (t *Tuple) String() string

String method #

func (obj *Func) String() string

String method #

func (obj *Builtin) String() string

String method #

func (obj *TypeName) String() string

String method #

func (s *_TypeSet) String() string

String method #

func (t *TypeParam) String() string

String method #

func (obj *Const) String() string

String method #

func (obj *PkgName) String() string

String method #

func (s *Struct) String() string

String method #

func (b *Basic) String() string

String method #

func (*lazyObject) String() string

String method #

func (x *operand) String() string

String method #

func (t *Term) String() string

String method #

func (t *Map) String() string

Swap method #

func (a nodeQueue) Swap(i int, j int)

Swap method #

func (s typeParamsById) Swap(i int, j int)

Tag method #

Tag returns the i'th field tag for 0 <= i < NumFields().

func (s *Struct) Tag(i int) string

Term method #

func (u *Union) Term(i int) *Term

Tilde method #

func (t *Term) Tilde() bool

Type method #

func (*lazyObject) Type() Type

Type method #

func (t *Term) Type() Type

Type method #

Type returns the object's type.

func (obj *object) Type() Type

Type method #

Type returns the type of x.f, which may be different from the type of f. See Selection for more information.

func (s *Selection) Type() Type

TypeArgs method #

TypeArgs returns the type arguments used to instantiate the Alias type. If a is not an instance of a generic alias, the result is nil.

func (a *Alias) TypeArgs() *TypeList

TypeArgs method #

TypeArgs returns the type arguments used to instantiate the named type t.

func (t *Named) TypeArgs() *TypeList

TypeOf method #

TypeOf returns the type of expression e, or nil if not found. Precondition 1: the Types map is populated or StoreTypesInSyntax is set. Precondition 2: Uses and Defs maps are populated.

func (info *Info) TypeOf(e syntax.Expr) Type

TypeParams method #

TypeParams returns the type parameters of signature s, or nil.

func (s *Signature) TypeParams() *TypeParamList

TypeParams method #

TypeParams returns the type parameters of the alias type a, or nil. A generic Alias and its instances have the same type parameters.

func (a *Alias) TypeParams() *TypeParamList

TypeParams method #

TypeParams returns the type parameters of the named type t, or nil. The result is non-nil for an (originally) generic type even if it is instantiated.

func (t *Named) TypeParams() *TypeParamList

TypeString function #

TypeString returns the string representation of typ. The [Qualifier] controls the printing of package-level objects, and may be nil.

func TypeString(typ Type, qf Qualifier) string

Unalias function #

Unalias returns t if it is not an alias type; otherwise it follows t's alias chain until it reaches a non-alias type which is then returned. Consequently, the result is never an alias type.

func Unalias(t Type) Type

Underlying method #

func (s *Slice) Underlying() Type

Underlying method #

Underlying returns the [underlying type] of the named type t, resolving all forwarding declarations. Underlying types are never Named, TypeParam, or Alias types. [underlying type]: https://go.dev/ref/spec#Underlying_types.

func (t *Named) Underlying() Type

Underlying method #

func (t *Interface) Underlying() Type

Underlying method #

func (c *Chan) Underlying() Type

Underlying method #

Underlying returns the [underlying type] of the type parameter t, which is the underlying type of its constraint. This type is always an interface. [underlying type]: https://go.dev/ref/spec#Underlying_types.

func (t *TypeParam) Underlying() Type

Underlying method #

func (a *Array) Underlying() Type

Underlying method #

func (s *Signature) Underlying() Type

Underlying method #

func (u *Union) Underlying() Type

Underlying method #

func (p *Pointer) Underlying() Type

Underlying method #

func (t *Map) Underlying() Type

Underlying method #

func (t *Tuple) Underlying() Type

Underlying method #

func (b *Basic) Underlying() Type

Underlying method #

Underlying returns the [underlying type] of the alias type a, which is the underlying type of the aliased type. Underlying types are never Named, TypeParam, or Alias types. [underlying type]: https://go.dev/ref/spec#Underlying_types.

func (a *Alias) Underlying() Type

Underlying method #

func (s *Struct) Underlying() Type

Unwrap method #

func (e *ArgumentError) Unwrap() error

Val method #

Val returns the constant's value.

func (obj *Const) Val() constant.Value

Variadic method #

Variadic reports whether the signature s is variadic.

func (s *Signature) Variadic() bool

WriteSignature function #

WriteSignature writes the representation of the signature sig to buf, without a leading "func" keyword. The [Qualifier] controls the printing of package-level objects, and may be nil.

func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)

WriteTo method #

WriteTo writes a string representation of the scope to w, with the scope elements sorted by name. The level of indentation is controlled by n >= 0, with n == 0 for no indentation. If recurse is set, it also writes nested (children) scopes.

func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)

WriteType function #

WriteType writes the string representation of typ to buf. The [Qualifier] controls the printing of package-level objects, and may be nil.

func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)

add method #

func (s *nodeSet) add(p *graphNode)

add method #

func (l *instanceLookup) add(inst *Named)

addAltDecl method #

addAltDecl is a specialized form of addf reporting another declaration of obj.

func (err *error_) addAltDecl(obj Object)

addDeclDep method #

addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists

func (check *Checker) addDeclDep(to Object)

addDep method #

addDep adds obj to the set of objects d's init expression depends on.

func (d *declInfo) addDep(obj Object)

addEdge method #

func (w *monoGraph) addEdge(dst int, src int, weight int, pos syntax.Pos, typ Type)

addf method #

addf adds formatted error information to err. It may be called multiple times to provide additional information. The position of the first call to addf determines the position of the reported Error. Subsequent calls to addf provide additional information in the form of additional lines in the error message (types2) or continuation errors identified by a tab-indented error message (go/types).

func (err *error_) addf(at poser, format string, args ...interface{})

aliasAny function #

func aliasAny() bool

align function #

align returns the smallest y >= x such that y % a == 0. a must be within 1 and 8 and it must be a power of 2. The result may be negative due to overflow.

func align(x int64, a int64) int64

alignof method #

func (conf *Config) alignof(T Type) int64

allBasic function #

allBasic reports whether under(t) is a basic type with the specified info. If t is a type parameter, the result is true if isBasic(t, info) is true for all specific types of the type parameter's type set. allBasic(t, info) is an optimized version of isBasic(coreType(t), info).

func allBasic(t Type, info BasicInfo) bool

allBoolean function #

func allBoolean(t Type) bool

allInteger function #

func allInteger(t Type) bool

allNumeric function #

func allNumeric(t Type) bool

allNumericOrString function #

func allNumericOrString(t Type) bool

allOrdered function #

func allOrdered(t Type) bool

allString function #

func allString(t Type) bool

allUnsigned function #

func allUnsigned(t Type) bool

allowVersion method #

allowVersion reports whether the current effective Go version (which may vary from one file to another) is allowed to use the feature version (want).

func (check *Checker) allowVersion(want goVersion) bool

applyTypeFunc method #

applyTypeFunc applies f to x. If x is a type parameter, the result is a type parameter constrained by a new interface bound. The type bounds for that interface are computed by applying f to each of the type bounds of x. If any of these applications of f return nil, applyTypeFunc returns nil. If x is not a type parameter, the result is f(x).

func (check *Checker) applyTypeFunc(f func(Type) Type, x *operand, id builtinId) Type

argErrPos function #

argErrPos returns the node (poser) for reporting an invalid argument count.

func argErrPos(call *syntax.CallExpr) *syntax.CallExpr

arguments method #

arguments type-checks arguments passed to a function call with the given signature. The function and its arguments may be generic, and possibly partially instantiated. targs and xlist are the function's type arguments (and corresponding expressions). args are the function arguments. If an argument args[i] is a partially instantiated generic function, atargs[i] and atxlist[i] are the corresponding type arguments (and corresponding expressions). If the callee is variadic, arguments adjusts its signature to match the provided arguments. The type parameters and arguments of the callee and all its arguments are used together to infer any missing type arguments, and the callee and argument functions are instantiated as necessary. The result signature is the (possibly adjusted and instantiated) function signature. If an error occurred, the result signature is the incoming sig.

func (check *Checker) arguments(call *syntax.CallExpr, sig *Signature, targs []Type, xlist []syntax.Expr, args []*operand, atargs [][]Type, atxlist [][]syntax.Expr) (rsig *Signature)

arity method #

arity checks that the lhs and rhs of a const or var decl have a matching number of names and initialization values. If inherited is set, the initialization values are from another (constant) declaration.

func (check *Checker) arity(pos syntax.Pos, names []*syntax.Name, inits []syntax.Expr, constDecl bool, inherited bool)

arrayLength method #

arrayLength type-checks the array length expression e and returns the constant length >= 0, or a value < 0 to indicate an error (and thus an unknown length).

func (check *Checker) arrayLength(e syntax.Expr) int64

arrayPtrDeref function #

arrayPtrDeref returns A if typ is of the form *A and A is an array; otherwise it returns typ.

func arrayPtrDeref(typ Type) Type

asBoundTypeParam method #

asBoundTypeParam returns x.(*TypeParam) if x is a type parameter recorded with u. Otherwise, the result is nil.

func (u *unifier) asBoundTypeParam(x Type) *TypeParam

asGoVersion function #

asGoVersion returns v as a goVersion (e.g., "go1.20.1" becomes "go1.20"). If v is not a valid Go version, the result is the empty string.

func asGoVersion(v string) goVersion

asInterface function #

asInterface returns the underlying type of x as an interface if it is a non-type parameter interface. Otherwise it returns nil.

func asInterface(x Type) (i *Interface)

asNamed function #

asNamed returns t as *Named if that is t's actual type. It returns nil otherwise.

func asNamed(t Type) *Named

assert function #

func assert(p bool)

assertSortedMethods function #

func assertSortedMethods(list []*Func)

assertableTo method #

assertableTo reports whether a value of type V can be asserted to have type T. The receiver may be nil if assertableTo is invoked through an exported API call (such as AssertableTo), i.e., when all methods have been type-checked. The underlying type of V must be an interface. If the result is false and cause is not nil, *cause describes the error. TODO(gri) replace calls to this function with calls to newAssertableTo.

func (check *Checker) assertableTo(V Type, T Type, cause *string) bool

assign method #

assign records that tpar was instantiated as targ at pos.

func (w *monoGraph) assign(pkg *Package, pos syntax.Pos, tpar *TypeParam, targ Type)

assignError method #

func (check *Checker) assignError(rhs []syntax.Expr, l int, r int)

assignVar method #

assignVar checks the assignment lhs = rhs (if x == nil), or lhs = x (if x != nil). If x != nil, it must be the evaluation of rhs (and rhs will be ignored). If the assignment check fails and x != nil, x.mode is set to invalid.

func (check *Checker) assignVar(lhs syntax.Expr, rhs syntax.Expr, x *operand, context string)

assignVars method #

assignVars type-checks assignments of expressions orig_rhs to variables lhs.

func (check *Checker) assignVars(lhs []syntax.Expr, orig_rhs []syntax.Expr)

assignableTo method #

assignableTo reports whether x is assignable to a variable of type T. If the result is false and a non-nil cause is provided, it may be set to a more detailed explanation of the failure (result != ""). The returned error code is only valid if the (first) result is false. The check parameter may be nil if assignableTo is invoked through an exported API call, i.e., when all methods have been type-checked.

func (x *operand) assignableTo(check *Checker, T Type, cause *string) (bool, Code)

assignment method #

assignment reports whether x can be assigned to a variable of type T, if necessary by attempting to convert untyped values to the appropriate type. context describes the context in which the assignment takes place. Use T == nil to indicate assignment to an untyped blank identifier. If the assignment check fails, x.mode is set to invalid.

func (check *Checker) assignment(x *operand, T Type, context string)

at method #

at returns the (possibly nil) type for type parameter x.

func (u *unifier) at(x *TypeParam) Type

atPos function #

atPos reports the left (= start) position of at.

func atPos(at poser) syntax.Pos

basicLit method #

func (check *Checker) basicLit(x *operand, e *syntax.BasicLit)

binary method #

If e != nil, it must be the binary expression; it may be nil for non-constant expressions (when invoked for an assignment operation where the binary expression is implicit).

func (check *Checker) binary(x *operand, e syntax.Expr, lhs syntax.Expr, rhs syntax.Expr, op syntax.Operator)

bindTParams function #

func bindTParams(list []*TypeParam) *TypeParamList

blockBranches method #

blockBranches processes a block's statement list and returns the set of outgoing forward jumps. all is the scope of all declared labels, parent the set of labels declared in the immediately enclosing block, and lstmt is the labeled statement this block is associated with (or nil).

func (check *Checker) blockBranches(all *Scope, parent *block, lstmt *syntax.LabeledStmt, list []syntax.Stmt) []*syntax.BranchStmt

bound method #

func (check *Checker) bound(x syntax.Expr) Type

brokenAlias method #

brokenAlias records that alias doesn't have a determined type yet. It also sets alias.typ to Typ[Invalid]. Not used if check.conf.EnableAlias is set.

func (check *Checker) brokenAlias(alias *TypeName)

builtin method #

builtin type-checks a call to the built-in specified by id and reports whether the call is valid, with *x holding the result; but x.expr is not set. If the call is invalid, the result is false, and *x is undefined.

func (check *Checker) builtin(x *operand, call *syntax.CallExpr, id builtinId) (_ bool)

byte method #

func (w *typeWriter) byte(b byte)

callExpr method #

func (check *Checker) callExpr(x *operand, call *syntax.CallExpr) exprKind

caseTypes method #

caseTypes typechecks the type expressions of a type case, checks for duplicate types using the seen map, and verifies that each type is valid with respect to the type of the operand x corresponding to the type switch expression. If that expression is not valid, x must be nil. switch .(type) { case : ... ... } caseTypes returns the case-specific type for a variable v introduced through a short variable declaration by the type switch: switch v := .(type) { case : // T is the type of in this case ... } If there is exactly one type expression, T is the type of that expression. If there are multiple type expressions, or if predeclared nil is among the types, the result is the type of x. If x is invalid (nil), the result is the invalid type.

func (check *Checker) caseTypes(x *operand, types []syntax.Expr, seen map[Type]syntax.Expr) Type

caseTypes_currently_unused method #

TODO(gri) Once we are certain that typeHash is correct in all situations, use this version of caseTypes instead. (Currently it may be possible that different types have identical names and import paths due to ImporterFrom.)

func (check *Checker) caseTypes_currently_unused(x *operand, xtyp *Interface, types []syntax.Expr, seen map[string]syntax.Expr) Type

caseValues method #

func (check *Checker) caseValues(x *operand, values []syntax.Expr, seen valueMap)

checkFieldUniqueness method #

func (check *Checker) checkFieldUniqueness(base *Named)

checkFiles method #

checkFiles type-checks the specified files. Errors are reported as a side effect, not by returning early, to ensure that well-formed syntax is properly type annotated even in a package containing errors.

func (check *Checker) checkFiles(files []*syntax.File)

cleanup method #

func (t *Named) cleanup()

cleanup method #

func (t *TypeParam) cleanup()

cleanup method #

func (t *Interface) cleanup()

cleanup method #

cleanup runs cleanup for all collected cleaners.

func (check *Checker) cleanup()

cleanup method #

func (a *Alias) cleanup()

clone function #

clone makes a "flat copy" of *p and returns a pointer to the copy.

func clone(p P) P

cloneFunc function #

func cloneFunc(f *Func, typ Type) *Func

cloneVar function #

func cloneVar(v *Var, typ Type) *Var

closeScope method #

func (check *Checker) closeScope()

cmp method #

cmp returns -1, 0, or +1 depending on whether x < y, x == y, or x > y, interpreted as Go versions.

func (x goVersion) cmp(y goVersion) int

cmp method #

cmp reports whether object a is ordered before object b. cmp returns: -1 if a is before b 0 if a is equivalent to b +1 if a is behind b Objects are ordered nil before non-nil, exported before non-exported, then by name, and finally (for non-exported functions) by package path.

func (a *object) cmp(b *object) int

cmpPos function #

cmpPos compares the positions p and q and returns a result r as follows: r < 0: p is before q r == 0: p and q are the same position (but may not be identical) r > 0: p is after q If p and q are in different files, p is before q if the filename of p sorts lexicographically before the filename of q.

func cmpPos(p syntax.Pos, q syntax.Pos) int

collectMethods method #

func (check *Checker) collectMethods(obj *TypeName)

collectObjects method #

collectObjects collects all file and package objects and inserts them into their respective scopes. It also performs imports and associates methods with receiver base type names.

func (check *Checker) collectObjects()

collectParams method #

collectParams collects (but does not declare) all parameters of list and returns the list of parameter names, corresponding parameter variables, and whether the parameter list is variadic. Anonymous parameters are recorded with nil names.

func (check *Checker) collectParams(list []*syntax.Field, variadicOk bool) (names []*syntax.Name, params []*Var, variadic bool)

collectRecv method #

collectRecv extracts the method receiver and its type parameters (if any) from rparam. It declares the type parameters (but not the receiver) in the current scope, and returns the receiver variable and its type parameter list (if any).

func (check *Checker) collectRecv(rparam *syntax.Field, scopePos syntax.Pos) (*Var, *TypeParamList)

collectTypeParams method #

func (check *Checker) collectTypeParams(dst **TypeParamList, list []*syntax.Field)

color method #

func (obj *object) color() color

color method #

func (*lazyObject) color() color

colorFor function #

colorFor returns the (initial) color for an object depending on whether its type t is known or not.

func colorFor(t Type) color

comparableType function #

If dynamic is set, non-type parameter interfaces are always comparable. If reportf != nil, it may be used to report why T is not comparable.

func comparableType(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool

compareFunc function #

func compareFunc(a *Func, b *Func) int

comparison method #

If switchCase is true, the operator op is ignored.

func (check *Checker) comparison(x *operand, y *operand, op syntax.Operator, switchCase bool)

compositeKind function #

compositeKind returns the kind of the given composite type ("array", "slice", etc.) or the empty string if typ is not composite but a basic type.

func compositeKind(typ Type) string

compositeLit method #

func (check *Checker) compositeLit(x *operand, e *syntax.CompositeLit, hint Type)

computeInterfaceTypeSet function #

computeInterfaceTypeSet may be called with check == nil.

func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_TypeSet

computeUnionTypeSet function #

computeUnionTypeSet may be called with check == nil. The result is &invalidTypeSet if the union overflows.

func computeUnionTypeSet(check *Checker, unionSets map[*Union]*_TypeSet, pos syntax.Pos, utyp *Union) *_TypeSet

concat function #

concat returns the result of concatenating list and i. The result does not share its underlying array with list.

func concat(list []int, i int) []int

consolidateMultiples function #

consolidateMultiples collects multiple list entries with the same type into a single entry marked as containing multiples. The result is the consolidated list.

func consolidateMultiples(list []embeddedType) []embeddedType

constDecl method #

func (check *Checker) constDecl(obj *Const, typ syntax.Expr, init syntax.Expr, inherited bool)

context method #

context returns the type-checker context.

func (check *Checker) context() *Context

conversion method #

conversion type-checks the conversion T(x). The result is in x.

func (check *Checker) conversion(x *operand, T Type)

convertUntyped method #

convertUntyped attempts to set the type of an untyped value to the target type.

func (check *Checker) convertUntyped(x *operand, target Type)

convertibleTo method #

convertibleTo reports whether T(x) is valid. In the failure case, *cause may be set to the cause for the failure. The check parameter may be nil if convertibleTo is invoked through an exported API call, i.e., when all methods have been type-checked.

func (x *operand) convertibleTo(check *Checker, T Type, cause *string) bool

coreString function #

coreString is like coreType but also considers []byte and strings as identical. In this case, if successful and we saw a string, the result is of type (possibly untyped) string.

func coreString(t Type) Type

coreTerm function #

If the type parameter has a single specific type S, coreTerm returns (S, true). Otherwise, if tpar has a core type T, it returns a term corresponding to that core type and false. In that case, if any term of tpar has a tilde, the core term has a tilde. In all other cases coreTerm returns (nil, false).

func coreTerm(tpar *TypeParam) (*term, bool)

coreType function #

If t is not a type parameter, coreType returns the underlying type. If t is a type parameter, coreType returns the single underlying type of all types in its type set if it exists, or nil otherwise. If the type set contains only unrestricted and restricted channel types (with identical element types), the single underlying type is the restricted channel type if the restrictions are always the same, or nil otherwise.

func coreType(t Type) Type

cost method #

cost returns the cost of removing this node, which involves copying each predecessor to each successor (and vice-versa).

func (n *graphNode) cost() int

cycleError method #

cycleError reports a declaration cycle starting with the object at cycle[start].

func (check *Checker) cycleError(cycle []Object, start int)

dddErrPos function #

dddErrPos returns the node (poser) for reporting an invalid ... use in a call.

func dddErrPos(call *syntax.CallExpr) *syntax.CallExpr

declStmt method #

func (check *Checker) declStmt(list []syntax.Decl)

declare method #

func (check *Checker) declare(scope *Scope, id *syntax.Name, obj Object, pos syntax.Pos)

declareInSet method #

func (check *Checker) declareInSet(oset *objset, pos syntax.Pos, obj Object) bool

declareParams method #

declareParams declares each named parameter in the current scope.

func (check *Checker) declareParams(names []*syntax.Name, params []*Var, scopePos syntax.Pos)

declarePkgObj method #

declarePkgObj declares obj in the package scope, records its ident -> obj mapping, and updates check.objMap. The object must not be a function or method.

func (check *Checker) declarePkgObj(ident *syntax.Name, obj Object, d *declInfo)

declareTypeParam method #

func (check *Checker) declareTypeParam(name *syntax.Name, scopePos syntax.Pos) *TypeParam

def function #

Objects with names containing blanks are internal and not entered into a scope. Objects with exported names are inserted in the unsafe package scope; other objects are inserted in the universe scope.

func def(obj Object)

defPredeclaredConsts function #

func defPredeclaredConsts()

defPredeclaredFuncs function #

func defPredeclaredFuncs()

defPredeclaredNil function #

func defPredeclaredNil()

defPredeclaredTypes function #

func defPredeclaredTypes()

definedType method #

definedType is like typ but also accepts a type name def. If def != nil, e is the type specification for the type named def, declared in a type declaration, and def.typ.underlying will be set to the type of e before any components of e are type-checked.

func (check *Checker) definedType(e syntax.Expr, def *TypeName) Type

dependencyGraph function #

dependencyGraph computes the object dependency graph from the given objMap, with any function nodes removed. The resulting graph contains only constants and variables.

func dependencyGraph(objMap map[Object]*declInfo) []*graphNode

deref function #

deref dereferences typ if it is a *Pointer (but not a *Named type with an underlying pointer type!) and returns its base and true. Otherwise it returns (typ, false).

func deref(typ Type) (Type, bool)

derefStructPtr function #

derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a (named or unnamed) struct and returns its base. Otherwise it returns typ.

func derefStructPtr(typ Type) Type

describef method #

If debug is set, describef sets a printf-formatted description for action a. Otherwise, it is a no-op.

func (a *action) describef(pos poser, format string, args ...interface{})

dir function #

dir makes a good-faith attempt to return the directory portion of path. If path is empty, the result is ".". (Per the go/build package dependency tests, we cannot import path/filepath and simply use filepath.Dir.)

func dir(path string) string

disjoint method #

disjoint reports whether x ∩ y == ∅. x.typ and y.typ must not be nil.

func (x *term) disjoint(y *term) bool

dump method #

dump is only needed for debugging

func (check *Checker) dump(format string, args ...any)

embeddedFieldIdent function #

func embeddedFieldIdent(e syntax.Expr) *syntax.Name

empty method #

func (m substMap) empty() bool

empty method #

func (err *error_) empty() bool

enclosingTarget method #

enclosingTarget returns the innermost enclosing labeled statement with the given label name, or nil.

func (b *block) enclosingTarget(name string) *syntax.LabeledStmt

endPos function #

endPos returns the position of the first character immediately after node n.

func endPos(n syntax.Node) syntax.Pos

equal method #

equal reports whether x and y represent the same type set.

func (x *term) equal(y *term) bool

equal method #

equal reports whether xl and yl represent the same type set.

func (xl termlist) equal(yl termlist) bool

error method #

func (w *typeWriter) error(msg string)

error method #

func (check *Checker) error(at poser, code Code, msg string)

errorUnusedPkg method #

func (check *Checker) errorUnusedPkg(obj *PkgName)

errorf method #

func (check *Checker) errorf(at poser, code Code, format string, args ...any)

exclude method #

exclude reports an error if x.mode is in modeset and sets x.mode to invalid. The modeset may contain any of 1<

func (check *Checker) exclude(x *operand, modeset uint)

expandMethod method #

expandMethod substitutes type arguments in the i'th method for an instantiated receiver.

func (t *Named) expandMethod(i int) *Func

expandUnderlying method #

expandUnderlying substitutes type arguments in the underlying type n.orig, returning the result. Returns Typ[Invalid] if there was an error.

func (n *Named) expandUnderlying() Type

expr method #

expr typechecks expression e and initializes x with the expression value. If a non-nil target T is given and e is a generic function or a function call, T is used to infer the type arguments for e. The result must be a single value. If an error occurred, x.mode is set to invalid.

func (check *Checker) expr(T *target, x *operand, e syntax.Expr)

exprInternal method #

exprInternal contains the core of type checking of expressions. Must only be called by rawExpr. (See rawExpr for an explanation of the parameters.)

func (check *Checker) exprInternal(T *target, x *operand, e syntax.Expr, hint Type) exprKind

exprList method #

exprList evaluates a list of expressions and returns the corresponding operands. A single-element expression list may evaluate to multiple operands.

func (check *Checker) exprList(elist []syntax.Expr) (xlist []*operand)

exprOrType method #

exprOrType typechecks expression or type e and initializes x with the expression value or type. If allowGeneric is set, the operand type may be an uninstantiated parameterized type or function value. If an error occurred, x.mode is set to invalid.

func (check *Checker) exprOrType(x *operand, e syntax.Expr, allowGeneric bool)

exprWithHint method #

exprWithHint typechecks expression e and initializes x with the expression value; hint is the type of a composite literal element. If an error occurred, x.mode is set to invalid.

func (check *Checker) exprWithHint(x *operand, e syntax.Expr, hint Type)

fieldIndex function #

fieldIndex returns the index for the field with matching package and name, or a value < 0. See Object.sameId for the meaning of foldCase.

func fieldIndex(fields []*Var, pkg *Package, name string, foldCase bool) int

filename method #

filename returns a filename suitable for debugging output.

func (check *Checker) filename(fileNo int) string

findPath function #

findPath returns the (reversed) list of objects []Object{to, ... from} such that there is a path of object dependencies from 'from' to 'to'. If there is no such path, the result is nil.

func findPath(objMap map[Object]*declInfo, from Object, to Object, seen map[Object]bool) []Object

firstInSrc function #

firstInSrc reports the index of the object with the "smallest" source position in path. path must not be empty.

func firstInSrc(path []Object) int

fitsFloat32 function #

func fitsFloat32(x constant.Value) bool

fitsFloat64 function #

func fitsFloat64(x constant.Value) bool

flattenUnion function #

flattenUnion walks a union type expression of the form A | B | C | ..., extracting both the binary exprs (blist) and leaf types (tlist).

func flattenUnion(list []syntax.Expr, x syntax.Expr) (blist []syntax.Expr, tlist []syntax.Expr)

funcBody method #

decl may be nil

func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body *syntax.BlockStmt, iota constant.Value)

funcDecl method #

func (check *Checker) funcDecl(obj *Func, decl *declInfo)

funcInst method #

funcInst type-checks a function instantiation. The incoming x must be a generic function. If inst != nil, it provides some or all of the type arguments (inst.Index). If target != nil, it may be used to infer missing type arguments of x, if any. At least one of T or inst must be provided. There are two modes of operation: 1. If infer == true, funcInst infers missing type arguments as needed and instantiates the function x. The returned results are nil. 2. If infer == false and inst provides all type arguments, funcInst instantiates the function x. The returned results are nil. If inst doesn't provide enough type arguments, funcInst returns the available arguments and the corresponding expression list; x remains unchanged. If an error (other than a version error) occurs in any case, it is reported and x.mode is set to invalid.

func (check *Checker) funcInst(T *target, pos syntax.Pos, x *operand, inst *syntax.IndexExpr, infer bool) ([]Type, []syntax.Expr)

funcLit method #

func (check *Checker) funcLit(x *operand, e *syntax.FuncLit)

funcString method #

funcString returns a string of the form name + signature for f. check may be nil.

func (check *Checker) funcString(f *Func, pkgInfo bool) string

funcType method #

funcType type-checks a function or method type.

func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType)

func_ method #

func (subst *subster) func_(f *Func) *Func

gcSizesFor function #

gcSizesFor returns the Sizes used by gc for an architecture. The result is a nil *gcSizes pointer (which is not a valid types.Sizes) if a compiler/architecture pair is not known.

func gcSizesFor(compiler string, arch string) *gcSizes

genericExpr method #

genericExpr is like expr but the result may also be generic.

func (check *Checker) genericExpr(x *operand, e syntax.Expr)

genericExprList method #

genericExprList is like exprList but result operands may be uninstantiated or partially instantiated generic functions (where constraint information is insufficient to infer the missing type arguments) for Go 1.21 and later. For each non-generic or uninstantiated generic operand, the corresponding targsList and xlistList elements do not exist (targsList and xlistList are nil) or the elements are nil. For each partially instantiated generic function operand, the corresponding targsList and xlistList elements are the operand's partial type arguments and type expression lists.

func (check *Checker) genericExprList(elist []syntax.Expr) (resList []*operand, targsList [][]Type, xlistList [][]syntax.Expr)

genericType method #

genericType is like typ but the type must be an (uninstantiated) generic type. If cause is non-nil and the type expression was a valid type but not generic, cause will be populated with a message describing the error. Note: If the type expression was invalid and an error was reported before, cause will not be populated; thus cause alone cannot be used to determine if an error occurred.

func (check *Checker) genericType(e syntax.Expr, cause *string) Type

getID method #

getID returns a unique ID for the type t.

func (ctxt *Context) getID(t Type) int

goTypeName function #

goTypeName returns the Go type name for typ and removes any occurrences of "types2." from that name.

func goTypeName(typ Type) string

goVal function #

goVal returns the Go value for val, or nil.

func goVal(val constant.Value) interface{}

gotoTarget method #

gotoTarget returns the labeled statement in the current or an enclosing block with the given label name, or nil.

func (b *block) gotoTarget(name string) *syntax.LabeledStmt

handleBailout method #

func (check *Checker) handleBailout(err *error)

handleError method #

handleError should only be called by error_.report.

func (check *Checker) handleError(index int, pos syntax.Pos, code Code, msg string, soft bool)

hasAllMethods method #

hasAllMethods is similar to checkMissingMethod but instead reports whether all methods are present. If V is not a valid type, or if it is a struct containing embedded fields with invalid types, the result is true because it is not possible to say with certainty whether a method is missing or not (an embedded field may have the method in question). If the result is false and cause is not nil, *cause describes the error. Use hasAllMethods to avoid follow-on errors due to incorrect types.

func (check *Checker) hasAllMethods(V Type, T Type, static bool, equivalent func(x Type, y Type) bool, cause *string) bool

hasBreak function #

hasBreak reports if s is or contains a break statement referring to the label-ed statement or implicit-ly the closest outer breakable statement.

func hasBreak(s syntax.Stmt, label string, implicit bool) bool

hasBreakCaseList function #

func hasBreakCaseList(list []*syntax.CaseClause, label string, implicit bool) bool

hasBreakCommList function #

func hasBreakCommList(list []*syntax.CommClause, label string, implicit bool) bool

hasBreakList function #

func hasBreakList(list []syntax.Stmt, label string, implicit bool) bool

hasDots function #

hasDots reports whether the last argument in the call is followed by ...

func hasDots(call *syntax.CallExpr) bool

hasEmptyTypeset function #

hasEmptyTypeset reports whether t is a type parameter with an empty type set. The function does not force the computation of the type set and so is safe to use anywhere, but it may report a false negative if the type set has not been computed yet.

func hasEmptyTypeset(t Type) bool

hasInitializer method #

hasInitializer reports whether the declared object has an initialization expression or function body.

func (d *declInfo) hasInitializer() bool

hasInvalidEmbeddedFields function #

hasInvalidEmbeddedFields reports whether T is a struct (or a pointer to a struct) that contains (directly or indirectly) embedded fields with invalid types.

func hasInvalidEmbeddedFields(T Type, seen map[*Struct]bool) bool

hasName function #

hasName reports whether t has a name. This includes predeclared types, defined types, and type parameters. hasName may be called with types that are not fully set up.

func hasName(t Type) bool

hasNil function #

hasNil reports whether type t includes the nil value.

func hasNil(t Type) bool

hasPtrRecv method #

hasPtrRecv reports whether the receiver is of the form *T for the given method obj.

func (obj *Func) hasPtrRecv() bool

hasTerms method #

hasTerms reports whether s has specific type terms.

func (s *_TypeSet) hasTerms() bool

hasVarSize function #

hasVarSize reports if the size of type t is variable due to type parameters or if the type is infinitely-sized due to a cycle for which the type has not yet been checked.

func hasVarSize(t Type, seen map[*Named]bool) (varSized bool)

ident method #

ident type-checks identifier e and initializes x with the value or type of e. If an error occurred, x.mode is set to invalid. For the meaning of def, see Checker.definedType, below. If wantType is set, the identifier e is expected to denote a type.

func (check *Checker) ident(x *operand, e *syntax.Name, def *TypeName, wantType bool)

identical method #

func (p *ifacePair) identical(q *ifacePair) bool

identical method #

For changes to this code the corresponding changes should be made to unifier.nify.

func (c *comparer) identical(x Type, y Type, p *ifacePair) bool

identicalInstance function #

identicalInstance reports if two type instantiations are identical. Instantiations are identical if their origin and type arguments are identical.

func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool

identicalOrigin function #

identicalOrigin reports whether x and y originated in the same declaration.

func identicalOrigin(x *Named, y *Named) bool

iface method #

iface returns the constraint interface of t.

func (t *TypeParam) iface() *Interface

implements method #

implements checks if V implements T. The receiver may be nil if implements is called through an exported API call such as AssignableTo. If constraint is set, T is a type constraint. If the provided cause is non-nil, it may be set to an error string explaining why V does not implement (or satisfy, for constraints) T.

func (check *Checker) implements(V Type, T Type, constraint bool, cause *string) bool

implicitTypeAndValue method #

implicitTypeAndValue returns the implicit type of x when used in a context where the target type is expected. If no such implicit conversion is possible, it returns a nil Type and non-zero error code. If x is a constant operand, the returned constant.Value will be the representation of x in this context.

func (check *Checker) implicitTypeAndValue(x *operand, target Type) (Type, constant.Value, Code)

importPackage method #

func (check *Checker) importPackage(pos syntax.Pos, path string, dir string) *Package

inNode function #

inNode is a dummy function returning pos.

func inNode(_ syntax.Node, pos syntax.Pos) syntax.Pos

includes method #

includes reports whether t ∈ xl.

func (xl termlist) includes(t Type) bool

includes method #

includes reports whether t ∈ x.

func (x *term) includes(t Type) bool

incomparableCause method #

incomparableCause returns a more specific cause why typ is not comparable. If there is no more specific cause, the result is "".

func (check *Checker) incomparableCause(typ Type) string

index method #

index checks an index expression for validity. If max >= 0, it is the upper bound for index. If the result typ is != Typ[Invalid], index is valid and typ is its (possibly named) integer type. If the result val >= 0, index is valid and val is its constant int value.

func (check *Checker) index(index syntax.Expr, max int64) (typ Type, val int64)

indexExpr method #

If e is a valid function instantiation, indexExpr returns true. In that case x represents the uninstantiated function value and it is the caller's responsibility to instantiate the function.

func (check *Checker) indexExpr(x *operand, e *syntax.IndexExpr) (isFuncInst bool)

indexedElts method #

indexedElts checks the elements (elts) of an array or slice composite literal against the literal's element type (typ), and the element indices against the literal length if known (length >= 0). It returns the length of the literal (maximum index value + 1).

func (check *Checker) indexedElts(elts []syntax.Expr, typ Type, length int64) int64

infer method #

infer attempts to infer the complete set of type arguments for generic function instantiation/call based on the given type parameters tparams, type arguments targs, function parameters params, and function arguments args, if any. There must be at least one type parameter, no more type arguments than type parameters, and params and args must match in number (incl. zero). If reverse is set, an error message's contents are reversed for a better error message for some errors related to reverse type inference (where the function call is synthetic). If successful, infer returns the complete list of given and inferred type arguments, one for each type parameter. Otherwise the result is nil. Errors are reported through the err parameter. Note: infer may fail (return nil) due to invalid args operands without reporting additional errors.

func (check *Checker) infer(pos syntax.Pos, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand, reverse bool, err *error_) (inferred []Type)

inferred method #

inferred returns the list of inferred types for the given type parameter list. The result is never nil and has the same length as tparams; result types that could not be inferred are nil. Corresponding type parameters and result types have identical indices.

func (u *unifier) inferred(tparams []*TypeParam) []Type

init function #

func init()

init function #

func init()

init function #

func init()

initConst method #

func (check *Checker) initConst(lhs *Const, x *operand)

initFiles method #

initFiles initializes the files-specific portion of checker. The provided files must all belong to the same package.

func (check *Checker) initFiles(files []*syntax.File)

initOrder method #

initOrder computes the Info.InitOrder for package variables.

func (check *Checker) initOrder()

initVar method #

initVar checks the initialization lhs = x in a variable declaration. If lhs doesn't have a type yet, it is given the type of x, or Typ[Invalid] in case of an error. If the initialization check fails, x.mode is set to invalid.

func (check *Checker) initVar(lhs *Var, x *operand, context string)

initVars method #

initVars type-checks assignments of initialization expressions orig_rhs to variables lhs. If returnStmt is non-nil, initVars type-checks the implicit assignment of result expressions orig_rhs to function result parameters lhs.

func (check *Checker) initVars(lhs []*Var, orig_rhs []syntax.Expr, returnStmt syntax.Stmt)

insert method #

insert attempts to insert an object obj into objset s. If s already contains an alternative object alt with the same name, insert leaves s unchanged and returns alt. Otherwise it inserts obj and returns nil.

func (s *objset) insert(obj Object) Object

insert method #

func (s *Scope) insert(name string, obj Object)

insert method #

insert records a new label declaration for the current block. The label must not have been declared before in any block.

func (b *block) insert(s *syntax.LabeledStmt)

instance method #

instance instantiates the given original (generic) function or type with the provided type arguments and returns the resulting instance. If an identical instance exists already in the given contexts, it returns that instance, otherwise it creates a new one. If there is an error (such as wrong number of type arguments), the result is Typ[Invalid]. If expanding is non-nil, it is the Named instance type currently being expanded. If ctxt is non-nil, it is the context associated with the current type-checking pass or call to Instantiate. At least one of expanding or ctxt must be non-nil. For Named types the resulting instance may be unexpanded. check may be nil (when not type-checking syntax); pos is used only only if check is non-nil.

func (check *Checker) instance(pos syntax.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type)

instanceHash method #

instanceHash returns a string representation of typ instantiated with targs. The hash should be a perfect hash, though out of caution the type checker does not assume this. The result is guaranteed to not contain blanks.

func (ctxt *Context) instanceHash(orig Type, targs []Type) string

instantiateSignature method #

func (check *Checker) instantiateSignature(pos syntax.Pos, expr syntax.Expr, typ *Signature, targs []Type, xlist []syntax.Expr) (res *Signature)

instantiatedIdent function #

instantiatedIdent determines the identifier of the type instantiated in expr. Helper function for recordInstance in recording.go.

func instantiatedIdent(expr syntax.Expr) *syntax.Name

instantiatedType method #

func (check *Checker) instantiatedType(x syntax.Expr, xlist []syntax.Expr, def *TypeName) (res Type)

interfacePtrError method #

check may be nil.

func (check *Checker) interfacePtrError(T Type) string

interfaceType method #

func (check *Checker) interfaceType(ityp *Interface, iface *syntax.InterfaceType, def *TypeName)

intersect method #

intersect returns the intersection xl ∩ yl.

func (xl termlist) intersect(yl termlist) termlist

intersect method #

intersect returns the intersection x ∩ y.

func (x *term) intersect(y *term) *term

intersectTermLists function #

intersectTermLists computes the intersection of two term lists and respective comparable bits. xcomp, ycomp are valid only if xterms.isAll() and yterms.isAll() respectively.

func intersectTermLists(xterms termlist, xcomp bool, yterms termlist, ycomp bool) (termlist, bool)

invalidConversion method #

func (check *Checker) invalidConversion(code Code, x *operand, target Type)

is method #

is calls f with the specific type terms of t's constraint and reports whether all calls to f returned true. If there are no specific terms, is returns the result of f(nil).

func (t *TypeParam) is(f func(*term) bool) bool

is method #

is calls f with the specific type terms of s and reports whether all calls to f returned true. If there are no specific terms, is returns the result of f(nil).

func (s *_TypeSet) is(f func(*term) bool) bool

isAll method #

isAll reports whether the termlist xl represents the set of all types.

func (xl termlist) isAll() bool

isBasic function #

isBasic reports whether under(t) is a basic type with the specified info. If t is a type parameter the result is false; i.e., isBasic does not look inside a type parameter.

func isBasic(t Type, info BasicInfo) bool

isBoolean function #

func isBoolean(t Type) bool

isBrokenAlias method #

isBrokenAlias reports whether alias doesn't have a determined type yet.

func (check *Checker) isBrokenAlias(alias *TypeName) bool

isBytesOrRunes function #

func isBytesOrRunes(typ Type) bool

isCGoTypeObj function #

isCGoTypeObj reports whether the given type name was created by cgo.

func isCGoTypeObj(obj *TypeName) bool

isComparison function #

func isComparison(op syntax.Operator) bool

isComplex function #

func isComplex(t Type) bool

isConstType function #

func isConstType(t Type) bool

isDependency method #

func (*Func) isDependency()

isDependency method #

func (*Var) isDependency()

isDependency method #

func (*Const) isDependency()

isEmpty method #

isEmpty reports whether the termlist xl represents the empty set of types.

func (xl termlist) isEmpty() bool

isExported function #

func isExported(name string) bool

isFloat function #

func isFloat(t Type) bool

isGeneric function #

isGeneric reports whether a type is a generic, uninstantiated type (generic signatures are not included). TODO(gri) should we include signatures or assert that they are not present?

func isGeneric(t Type) bool

isImportedConstraint method #

isImportedConstraint reports whether typ is an imported type constraint.

func (check *Checker) isImportedConstraint(typ Type) bool

isInteger function #

func isInteger(t Type) bool

isIntegerOrFloat function #

func isIntegerOrFloat(t Type) bool

isInterfacePtr function #

func isInterfacePtr(T Type) bool

isNil method #

isNil reports whether x is the (untyped) nil value.

func (x *operand) isNil() bool

isNil method #

isNil reports whether the expression e denotes the predeclared value nil.

func (check *Checker) isNil(e syntax.Expr) bool

isNonTypeParamInterface function #

isNonTypeParamInterface reports whether t is an interface type but not a type parameter.

func isNonTypeParamInterface(t Type) bool

isNumeric function #

func isNumeric(t Type) bool

isParameterized function #

isParameterized reports whether typ contains any of the type parameters of tparams. If typ is a generic function, isParameterized ignores the type parameter declarations; it only considers the signature proper (incoming and result parameters).

func isParameterized(tparams []*TypeParam, typ Type) bool

isParameterized method #

func (w *tpWalker) isParameterized(typ Type) (res bool)

isPointer function #

func isPointer(typ Type) bool

isShift function #

func isShift(op syntax.Operator) bool

isString function #

func isString(t Type) bool

isTerminating method #

isTerminating reports if s is a terminating statement. If s is labeled, label is the label name; otherwise s is "".

func (check *Checker) isTerminating(s syntax.Stmt, label string) bool

isTerminatingList method #

func (check *Checker) isTerminatingList(list []syntax.Stmt, label string) bool

isTerminatingSwitch method #

func (check *Checker) isTerminatingSwitch(body []*syntax.CaseClause, label string) bool

isTypeLit function #

isTypeLit reports whether t is a type literal. This includes all non-defined types, but also basic types. isTypeLit may be called with types that are not fully set up.

func isTypeLit(t Type) bool

isTypeParam function #

isTypeParam reports whether t is a type parameter.

func isTypeParam(t Type) bool

isTyped function #

isTyped reports whether t is typed; i.e., not an untyped constant or boolean. Safe to call from types that are not fully set up.

func isTyped(t Type) bool

isUintptr function #

func isUintptr(typ Type) bool

isUnsafePointer function #

func isUnsafePointer(typ Type) bool

isUnsigned function #

func isUnsigned(t Type) bool

isUntyped function #

isUntyped(t) is the same as !isTyped(t). Safe to call from types that are not fully set up.

func isUntyped(t Type) bool

isUntypedNumeric function #

isUntypedNumeric reports whether t is an untyped numeric type. Safe to call from types that are not fully set up.

func isUntypedNumeric(t Type) bool

isValid function #

isValid reports whether t is a valid type.

func isValid(t Type) bool

isValid method #

isValid reports whether v is a valid Go version.

func (v goVersion) isValid() bool

isValidIndex method #

isValidIndex checks whether operand x satisfies the criteria for integer index values. If allowNegative is set, a constant operand may be negative. If the operand is not valid, an error is reported (using what as context) and the result is false.

func (check *Checker) isValidIndex(x *operand, code Code, what string, allowNegative bool) bool

isValidName function #

isValidName reports whether s is a valid Go identifier.

func isValidName(s string) bool

isdddArray function #

isdddArray reports whether atyp is of the form [...]E.

func isdddArray(atyp *syntax.ArrayType) bool

join method #

join unifies the given type parameters x and y. If both type parameters already have a type associated with them and they are not joined, join fails and returns false.

func (u *unifier) join(x *TypeParam, y *TypeParam) bool

keyVal function #

keyVal maps a complex, float, integer, string or boolean constant value to the corresponding complex128, float64, int64, uint64, string, or bool Go value if possible; otherwise it returns x. A complex constant that can be represented as a float (such as 1.2 + 0i) is returned as a floating point value; if a floating point value can be represented as an integer (such as 1.0) it is returned as an integer value. This ensures that constants of different kind but equal value (such as 1.0 + 0i, 1.0, 1) result in the same value.

func keyVal(x constant.Value) interface{}

killCycles function #

killCycles walks through the given type parameters and looks for cycles created by type parameters whose inferred types refer back to that type parameter, either directly or indirectly. If such a cycle is detected, it is killed by setting the corresponding inferred type to nil. TODO(gri) Determine if we can simply abort inference as soon as we have found a single cycle.

func killCycles(tparams []*TypeParam, inferred []Type)

labels method #

labels checks correct label use in body.

func (check *Checker) labels(body *syntax.BlockStmt)

langCompat method #

langCompat reports an error if the representation of a numeric literal is not compatible with the current language version.

func (check *Checker) langCompat(lit *syntax.BasicLit)

later method #

later pushes f on to the stack of actions that will be processed later; either at the end of the current statement, or in case of a local constant or variable declaration, before the constant or variable is in scope (so that f still sees the scope before any new declarations). later returns the pushed action so one can provide a description via action.describef for debugging, if desired.

func (check *Checker) later(f func()) *action

lhsVar method #

lhsVar checks a lhs variable in an assignment and returns its type. lhsVar takes care of not counting a lhs identifier as a "use" of that identifier. The result is nil if it is the blank identifier, and Typ[Invalid] if it is an invalid lhs expression.

func (check *Checker) lhsVar(lhs syntax.Expr) Type

list method #

list is for internal use where we expect a []*TypeParam. TODO(rfindley): list should probably be eliminated: we can pass around a TypeParamList instead.

func (l *TypeParamList) list() []*TypeParam

list method #

list is for internal use where we expect a []Type. TODO(rfindley): list should probably be eliminated: we can pass around a TypeList instead.

func (l *TypeList) list() []Type

localNamedVertex method #

localNamedVertex returns the index of the vertex representing named, or -1 if named doesn't need representation.

func (w *monoGraph) localNamedVertex(pkg *Package, named *Named) int

lookup method #

func (l *instanceLookup) lookup(inst *Named) *Named

lookup method #

lookup is like lookupScope but it only returns the object (or nil).

func (env *environment) lookup(name string) Object

lookup method #

func (m substMap) lookup(tpar *TypeParam) Type

lookup method #

lookup returns an existing instantiation of orig with targs, if it exists. Otherwise, it returns nil.

func (ctxt *Context) lookup(h string, orig Type, targs []Type) Type

lookupError method #

lookupError returns a case-specific error when a lookup of selector sel in the given type fails but an object with alternative spelling (case folding) is found. If structLit is set, the error message is specifically for struct literal fields.

func (check *Checker) lookupError(typ Type, sel string, obj Object, structLit bool) string

lookupFieldOrMethod function #

lookupFieldOrMethod is like LookupFieldOrMethod but with the additional foldCase parameter (see Object.sameId for the meaning of foldCase).

func lookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool)

lookupFieldOrMethodImpl function #

lookupFieldOrMethodImpl is the implementation of lookupFieldOrMethod. Notably, in contrast to lookupFieldOrMethod, it won't find struct fields in base types of defined (*Named) pointer types T. For instance, given the declaration: type T *struct{f int} lookupFieldOrMethodImpl won't find the field f in the defined (*Named) type T (methods on T are not permitted in the first place). Thus, lookupFieldOrMethodImpl should only be called by lookupFieldOrMethod and missingMethod (the latter doesn't care about struct fields). The resulting object may not be fully type-checked.

func lookupFieldOrMethodImpl(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool)

lookupMethod method #

func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func)

lookupScope method #

lookupScope looks up name in the current environment and if an object is found it returns the scope containing the object and the object. Otherwise it returns (nil, nil). Note that obj.Parent() may be different from the returned scope if the object was inserted into the scope and already had a parent at that time (see Scope.Insert). This can only happen for dot-imported objects whose parent is the scope of the package that exported them.

func (env *environment) lookupScope(name string) (*Scope, Object)

lookupType function #

func lookupType(m map[Type]int, typ Type) (int, bool)

makeFromLiteral function #

makeFromLiteral returns the constant value for the given literal string and kind.

func makeFromLiteral(lit string, kind syntax.LitKind) constant.Value

makeObjList function #

makeObjList returns the list of type name objects for the given list of named types.

func makeObjList(tlist []*Named) []Object

makeRenameMap function #

makeRenameMap is like makeSubstMap, but creates a map used to rename type parameters in from with the type parameters in to.

func makeRenameMap(from []*TypeParam, to []*TypeParam) substMap

makeSig function #

makeSig makes a signature for the given argument and result types. Default types are used for untyped arguments, and res may be nil.

func makeSig(res Type, args ...Type) *Signature

makeSubstMap function #

makeSubstMap creates a new substitution map mapping tpars[i] to targs[i]. If targs[i] is nil, tpars[i] is not substituted.

func makeSubstMap(tpars []*TypeParam, targs []Type) substMap

markComplete method #

func (s *Struct) markComplete()

markImports method #

markImports recursively walks pkg and its imports, to record unique import paths in pkgPathMap.

func (check *Checker) markImports(pkg *Package)

match function #

If x and y are identical, match returns x. If x and y are identical channels but for their direction and one of them is unrestricted, match returns the channel with the restricted direction. In all other cases, match returns nil.

func match(x Type, y Type) Type

matchTypes method #

matchTypes attempts to convert any untyped types x and y such that they match. If an error occurs, x.mode is set to invalid.

func (check *Checker) matchTypes(x *operand, y *operand)

maxType function #

maxType returns the "largest" type that encompasses both x and y. If x and y are different untyped numeric types, the result is the type of x or y that appears later in this list: integer, rune, floating-point, complex. Otherwise, if x != y, the result is nil.

func maxType(x Type, y Type) Type

measure function #

func measure(x int, unit string) string

mentions function #

mentions reports whether type T "mentions" typ in an (embedded) element or term of T (whether typ is in the type set of T or not). For better error messages.

func mentions(T Type, typ Type) bool

methodIndex method #

methodIndex returns the index of the method with the given name. If foldCase is set, capitalization in the name is ignored. The result is negative if no such method exists.

func (t *Named) methodIndex(name string, foldCase bool) int

methodIndex function #

methodIndex returns the index of and method with matching package and name, or (-1, nil). See Object.sameId for the meaning of foldCase.

func methodIndex(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func)

missingMethod method #

missingMethod is like MissingMethod but accepts a *Checker as receiver, a comparator equivalent for type comparison, and a *string for error causes. The receiver may be nil if missingMethod is invoked through an exported API call (such as MissingMethod), i.e., when all methods have been type- checked. The underlying type of T must be an interface; T (rather than its under- lying type) is used for better error messages (reported through *cause). The comparator is used to compare signatures. If a method is missing and cause is not nil, *cause describes the error.

func (check *Checker) missingMethod(V Type, T Type, static bool, equivalent func(x Type, y Type) bool, cause *string) (method *Func, wrongType bool)

monomorph method #

func (check *Checker) monomorph()

msg method #

msg returns the formatted error message without the primary error position pos().

func (err *error_) msg() string

multiExpr method #

multiExpr typechecks e and returns its value (or values) in list. If allowCommaOk is set and e is a map index, comma-ok, or comma-err expression, the result is a two-element list containing the value of e, and an untyped bool value or an error value, respectively. If an error occurred, list[0] is not valid.

func (check *Checker) multiExpr(e syntax.Expr, allowCommaOk bool) (list []*operand, commaOk bool)

multipleSelectDefaults method #

func (check *Checker) multipleSelectDefaults(list []*syntax.CommClause)

multipleSwitchDefaults method #

func (check *Checker) multipleSwitchDefaults(list []*syntax.CaseClause)

needsCleanup method #

needsCleanup records objects/types that implement the cleanup method which will be called at the end of type-checking.

func (check *Checker) needsCleanup(c cleaner)

newAlias method #

newAlias creates a new Alias type with the given type name and rhs. rhs must not be nil.

func (check *Checker) newAlias(obj *TypeName, rhs Type) *Alias

newAliasInstance method #

newAliasInstance creates a new alias instance for the given origin and type arguments, recording pos as the position of its synthetic object (for error reporting).

func (check *Checker) newAliasInstance(pos syntax.Pos, orig *Alias, targs []Type, expanding *Named, ctxt *Context) *Alias

newAssertableTo method #

newAssertableTo reports whether a value of type V can be asserted to have type T. It also implements behavior for interfaces that currently are only permitted in constraint position (we have not yet defined that behavior in the spec). The underlying type of V must be an interface. If the result is false and cause is not nil, *cause is set to the error cause.

func (check *Checker) newAssertableTo(V Type, T Type, cause *string) bool

newBuiltin function #

func newBuiltin(id builtinId) *Builtin

newError method #

newError returns a new error_ with the given error code.

func (check *Checker) newError(code Code) *error_

newInterface method #

check may be nil

func (check *Checker) newInterface() *Interface

newNamed method #

newNamed is like NewNamed but with a *Checker receiver.

func (check *Checker) newNamed(obj *TypeName, underlying Type, methods []*Func) *Named

newNamedInstance method #

newNamedInstance creates a new named instance for the given origin and type arguments, recording pos as the position of its synthetic object (for error reporting). If set, expanding is the named type instance currently being expanded, that led to the creation of this instance.

func (check *Checker) newNamedInstance(pos syntax.Pos, orig *Named, targs []Type, expanding *Named) *Named

newTarget function #

newTarget creates a new target for the given type and description. The result is nil if typ is not a signature.

func newTarget(typ Type, desc string) *target

newTypeHasher function #

func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter

newTypeList function #

newTypeList returns a new TypeList with the types in list.

func newTypeList(list []Type) *TypeList

newTypeParam method #

check may be nil

func (check *Checker) newTypeParam(obj *TypeName, constraint Type) *TypeParam

newTypeWriter function #

func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter

newUnifier function #

newUnifier returns a new unifier initialized with the given type parameter and corresponding type argument lists. The type argument list may be shorter than the type parameter list, and it may contain nil types. Matching type parameters and arguments must have the same index.

func newUnifier(tparams []*TypeParam, targs []Type, enableInterfaceInference bool) *unifier

nextID function #

nextID returns a value increasing monotonically by 1 with each call, starting with 1. It may be called concurrently.

func nextID() uint64

nify method #

nify implements the core unification algorithm which is an adapted version of Checker.identical. For changes to that code the corresponding changes should be made here. Must not be called directly from outside the unifier.

func (u *unifier) nify(x Type, y Type, mode unifyMode, p *ifacePair) (result bool)

nonGeneric method #

If x is a generic type, or a generic function whose type arguments cannot be inferred from a non-nil target T, nonGeneric reports an error and invalidates x.mode and x.typ. Otherwise it leaves x alone.

func (check *Checker) nonGeneric(T *target, x *operand)

norm method #

norm returns the normal form of xl.

func (xl termlist) norm() termlist

objDecl method #

objDecl type-checks the declaration of obj in its respective (file) environment. For the meaning of def, see Checker.definedType, in typexpr.go.

func (check *Checker) objDecl(obj Object, def *TypeName)

offsetof method #

offsetof returns the offset of the field specified via the index sequence relative to T. All embedded fields must be structs (rather than pointers to structs). If the offset is too large (because T is too large), the result is negative.

func (conf *Config) offsetof(T Type, index []int) int64

offsetsof method #

func (conf *Config) offsetsof(T *Struct) []int64

op method #

func (check *Checker) op(m opPredicates, x *operand, op syntax.Operator) bool

opName function #

opName returns the name of the operation if x is an operation that might overflow; otherwise it returns the empty string.

func opName(x syntax.Expr) string

opPos function #

opPos returns the position of the operator if x is an operation; otherwise it returns the start position of x.

func opPos(x syntax.Expr) syntax.Pos

openScope method #

func (check *Checker) openScope(node syntax.Node, comment string)

operandString function #

Operand string formats (not all "untyped" cases can appear due to the type system, but they fall out naturally here) mode format invalid ( ) novalue ( ) builtin ( ) typexpr ( ) constant ( ) constant ( of type ) constant ( ) constant ( of type ) variable ( ) variable ( of type ) mapindex ( ) mapindex ( of type ) value ( ) value ( of type ) nilvalue untyped nil nilvalue nil ( of type ) commaok ( ) commaok ( of type ) commaerr ( ) commaerr ( of type ) cgofunc ( ) cgofunc ( of type )

func operandString(x *operand, qf Qualifier) string

operandTypes function #

operandTypes returns the list of types for the given operands.

func operandTypes(list []*operand) (res []Type)

order method #

func (*lazyObject) order() uint32

order method #

func (obj *object) order() uint32

overflow method #

overflow checks that the constant x is representable by its type. For untyped constants, it checks that the value doesn't become arbitrarily large.

func (check *Checker) overflow(x *operand, opPos syntax.Pos)

overlappingTerm function #

overlappingTerm reports the index of the term x in terms which is overlapping (not disjoint) from y. The result is < 0 if there is no such term. The type of term y must not be an interface, and terms with an interface type are ignored in the terms list.

func overlappingTerm(terms []*Term, y *Term) int

packageObjects method #

packageObjects typechecks all package objects, but not function bodies.

func (check *Checker) packageObjects()

packagePrefix function #

func packagePrefix(pkg *Package, qf Qualifier) string

parseTilde function #

func parseTilde(check *Checker, tx syntax.Expr) *Term

parseUnion function #

parseUnion parses uexpr as a union of expressions. The result is a Union type, or Typ[Invalid] for some errors.

func parseUnion(check *Checker, uexpr syntax.Expr) Type

pathString function #

pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].

func pathString(path []Object) string

pop method #

pop pops and returns the topmost object from the object path.

func (check *Checker) pop() Object

pos method #

func (err *error_) pos() syntax.Pos

processDelayed method #

processDelayed processes all delayed actions pushed after top.

func (check *Checker) processDelayed(top int)

ptrBase function #

func ptrBase(x *syntax.Operation) syntax.Expr

push method #

push pushes obj onto the object path and returns its index in the path.

func (check *Checker) push(obj Object) int

qualifier method #

func (check *Checker) qualifier(pkg *Package) string

rangeKeyVal function #

rangeKeyVal returns the key and value type produced by a range clause over an expression of type typ. If allowVersion != nil, it is used to check the required language version. If the range clause is not permitted, rangeKeyVal returns ok = false. When ok = false, rangeKeyVal may also return a reason in cause.

func rangeKeyVal(typ Type, allowVersion func(goVersion) bool) (key Type, val Type, cause string, ok bool)

rangeStmt method #

func (check *Checker) rangeStmt(inner stmtContext, s *syntax.ForStmt, rclause *syntax.RangeClause)

rawExpr method #

rawExpr typechecks expression e and initializes x with the expression value or type. If an error occurred, x.mode is set to invalid. If a non-nil target T is given and e is a generic function, T is used to infer the type arguments for e. If hint != nil, it is the type of a composite literal element. If allowGeneric is set, the operand type may be an uninstantiated parameterized type or function value.

func (check *Checker) rawExpr(T *target, x *operand, e syntax.Expr, hint Type, allowGeneric bool) exprKind

record method #

func (check *Checker) record(x *operand)

recordBuiltinType method #

func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature)

recordCanon method #

recordCanon records that tpar is the canonical type parameter corresponding to method type parameter mpar.

func (w *monoGraph) recordCanon(mpar *TypeParam, tpar *TypeParam)

recordCommaOkTypes method #

recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context (and therefore has tuple type).

func (check *Checker) recordCommaOkTypes(x syntax.Expr, a []*operand)

recordCommaOkTypesInSyntax method #

types2-specific support for recording type information in the syntax tree.

func (check *Checker) recordCommaOkTypesInSyntax(x syntax.Expr, t0 Type, t1 Type)

recordDef method #

func (check *Checker) recordDef(id *syntax.Name, obj Object)

recordImplicit method #

func (check *Checker) recordImplicit(node syntax.Node, obj Object)

recordInstance method #

recordInstance records instantiation information into check.Info, if the Instances map is non-nil. The given expr must be an ident, selector, or index (list) expr with ident or selector operand. TODO(rfindley): the expr parameter is fragile. See if we can access the instantiated identifier in some other way.

func (check *Checker) recordInstance(expr syntax.Expr, targs []Type, typ Type)

recordInstance method #

recordInstance records that the given type parameters were instantiated with the corresponding type arguments.

func (w *monoGraph) recordInstance(pkg *Package, pos syntax.Pos, tparams []*TypeParam, targs []Type, xlist []syntax.Expr)

recordParenthesizedRecvTypes method #

recordParenthesizedRecvTypes records parenthesized intermediate receiver type expressions that all map to the same type, by recursively unpacking expr and recording the corresponding type for it. Example: expression --> type ---------------------- (*(T[P])) *T[P] *(T[P]) *T[P] (T[P]) T[P] T[P] T[P]

func (check *Checker) recordParenthesizedRecvTypes(expr syntax.Expr, typ Type)

recordScope method #

func (check *Checker) recordScope(node syntax.Node, scope *Scope)

recordSelection method #

func (check *Checker) recordSelection(x *syntax.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool)

recordTypeAndValue method #

func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Type, val constant.Value)

recordTypeAndValueInSyntax method #

types2-specific support for recording type information in the syntax tree.

func (check *Checker) recordTypeAndValueInSyntax(x syntax.Expr, mode operandMode, typ Type, val constant.Value)

recordTypes method #

func (info *Info) recordTypes() bool

recordUntyped method #

func (check *Checker) recordUntyped()

recordUse method #

func (check *Checker) recordUse(id *syntax.Name, obj Object)

rememberUntyped method #

func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value)

renameTParams method #

renameTParams renames the type parameters in the given type such that each type parameter is given a new identity. renameTParams returns the new type parameters and updated type. If the result type is unchanged from the argument type, none of the type parameters in tparams occurred in the type. If typ is a generic function, type parameters held with typ are not changed and must be updated separately if desired. The positions is only used for debug traces.

func (check *Checker) renameTParams(pos syntax.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type)

replaceRecvType function #

replaceRecvType updates any function receivers that have type old to have type new. It does not modify the input slice; if modifications are required, the input slice and any affected signatures will be copied before mutating. The resulting out slice contains the updated functions, and copied reports if anything was modified.

func replaceRecvType(in []*Func, old Type, new Type) (out []*Func, copied bool)

report method #

report reports the error err, setting check.firstError if necessary.

func (err *error_) report()

reportCycle method #

reportCycle reports an error for the given cycle.

func (check *Checker) reportCycle(cycle []Object)

reportInstanceLoop method #

func (check *Checker) reportInstanceLoop(v int)

representable method #

representable checks that a constant operand is representable in the given basic type.

func (check *Checker) representable(x *operand, typ *Basic)

representableConst function #

representableConst reports whether x can be represented as value of the given basic type and for the configuration provided (only needed for int/uint sizes). If rounded != nil, *rounded is set to the rounded value of x for representable floating-point and complex values, and to an Int value for integer values; it is left alone otherwise. It is ok to provide the addressof the first argument for rounded. The check parameter may be nil if representableConst is invoked (indirectly) through an exported API call (AssignableTo, ConvertibleTo) because we don't need the Checker's config for those calls.

func representableConst(x constant.Value, check *Checker, typ *Basic, rounded *constant.Value) bool

representation method #

representation returns the representation of the constant operand x as the basic type typ. If no such representation is possible, it returns a non-zero error code.

func (check *Checker) representation(x *operand, typ *Basic) (constant.Value, Code)

resolve function #

resolve returns the Object represented by obj, resolving lazy objects as appropriate.

func resolve(name string, obj Object) Object

resolve method #

resolve resolves the type parameters, methods, and underlying type of n. This information may be loaded from a provided loader function, or computed from an origin type (in the case of instances). After resolution, the type parameters, methods, and underlying type of n are accessible; but if n is an instantiated type, its methods may still be unexpanded.

func (n *Named) resolve() *Named

resolveBaseTypeName method #

resolveBaseTypeName returns the non-alias base type name for the given name, and whether there was a pointer indirection to get to it. The base type name must be declared in package scope, and there can be at most one pointer indirection. Traversals through generic alias types are not permitted. If no such type name exists, the returned base is nil.

func (check *Checker) resolveBaseTypeName(ptr bool, name *syntax.Name) (ptr_ bool, base *TypeName)

returnError method #

func (check *Checker) returnError(at poser, lhs []*Var, rhs []*operand)

roundFloat32 function #

func roundFloat32(x constant.Value) constant.Value

roundFloat64 function #

func roundFloat64(x constant.Value) constant.Value

safeUnderlying function #

safeUnderlying returns the underlying type of typ without expanding instances, to avoid infinite recursion. TODO(rfindley): eliminate this function or give it a better name.

func safeUnderlying(typ Type) Type

sameId method #

func (obj *object) sameId(pkg *Package, name string, foldCase bool) bool

sameId method #

func (*lazyObject) sameId(*Package, string, bool) bool

samePkg function #

samePkg reports whether packages a and b are the same.

func samePkg(a *Package, b *Package) bool

scopePos method #

func (obj *object) scopePos() syntax.Pos

scopePos method #

func (*lazyObject) scopePos() syntax.Pos

selector method #

func (check *Checker) selector(x *operand, e *syntax.SelectorExpr, def *TypeName, wantType bool)

set method #

set sets the type t for type parameter x; t must not be nil.

func (u *unifier) set(x *TypeParam, t Type)

setColor method #

func (obj *object) setColor(color color)

setColor method #

func (*lazyObject) setColor(color color)

setConst method #

setConst sets x to the untyped constant for literal lit.

func (x *operand) setConst(k syntax.LitKind, lit string)

setDefType function #

func setDefType(def *TypeName, typ Type)

setHandle method #

setHandle sets the handle for type parameter x (and all its joined type parameters) to h.

func (u *unifier) setHandle(x *TypeParam, h *Type)

setOrder method #

func (*lazyObject) setOrder(uint32)

setOrder method #

func (obj *object) setOrder(order uint32)

setParent method #

func (obj *object) setParent(parent *Scope)

setParent method #

func (*lazyObject) setParent(*Scope)

setScopePos method #

func (obj *object) setScopePos(pos syntax.Pos)

setScopePos method #

func (*lazyObject) setScopePos(syntax.Pos)

setState method #

setState atomically stores the given state for n. Must only be called while holding n.mu.

func (n *Named) setState(state namedState)

setType method #

func (obj *object) setType(typ Type)

setType method #

func (*lazyObject) setType(Type)

shift method #

If e != nil, it must be the shift expression; it may be nil for non-constant shifts.

func (check *Checker) shift(x *operand, y *operand, e syntax.Expr, op syntax.Operator)

shortVarDecl method #

func (check *Checker) shortVarDecl(pos poser, lhs []syntax.Expr, rhs []syntax.Expr)

signature method #

func (w *typeWriter) signature(sig *Signature)

simpleStmt method #

func (check *Checker) simpleStmt(s syntax.Stmt)

singleIndex method #

singleIndex returns the (single) index from the index expression e. If the index is missing, or if there are multiple indices, an error is reported and the result is nil.

func (check *Checker) singleIndex(e *syntax.IndexExpr) syntax.Expr

singleValue method #

singleValue reports an error if x describes a tuple and sets x.mode to invalid.

func (check *Checker) singleValue(x *operand)

sizeof method #

sizeof returns the size of T. If T is too large, the result is negative.

func (conf *Config) sizeof(T Type) int64

sliceExpr method #

func (check *Checker) sliceExpr(x *operand, e *syntax.SliceExpr)

softErrorf method #

func (check *Checker) softErrorf(at poser, code Code, format string, args ...any)

sortMethods function #

func sortMethods(list []*Func)

sprintf method #

check may be nil.

func (check *Checker) sprintf(format string, args ...any) string

sprintf function #

func sprintf(qf Qualifier, tpSubscripts bool, format string, args ...any) string

srcimporter_setUsesCgo function #

func srcimporter_setUsesCgo(conf *Config)

startPos function #

startPos returns the start position of node n.

func startPos(n syntax.Node) syntax.Pos

state method #

state atomically accesses the current state of the receiver.

func (n *Named) state() namedState

stmt method #

stmt typechecks statement s.

func (check *Checker) stmt(ctxt stmtContext, s syntax.Stmt)

stmtList method #

func (check *Checker) stmtList(ctxt stmtContext, list []syntax.Stmt)

string method #

func (w *typeWriter) string(s string)

stripAnnotations function #

stripAnnotations removes internal (type) annotations from s.

func stripAnnotations(s string) string

structType method #

func (check *Checker) structType(styp *Struct, e *syntax.StructType)

subscript function #

subscript returns the decimal (utf8) representation of x using subscript digits.

func subscript(x uint64) string

subsetOf method #

subsetOf reports whether x ⊆ y.

func (x *term) subsetOf(y *term) bool

subsetOf method #

subsetOf reports whether xl ⊆ yl.

func (xl termlist) subsetOf(yl termlist) bool

subsetOf method #

subsetOf reports whether s1 ⊆ s2.

func (s1 *_TypeSet) subsetOf(s2 *_TypeSet) bool

subst method #

subst returns the type typ with its type parameters tpars replaced by the corresponding type arguments targs, recursively. subst doesn't modify the incoming type. If a substitution took place, the result type is different from the incoming type. If expanding is non-nil, it is the instance type currently being expanded. One of expanding or ctxt must be non-nil.

func (check *Checker) subst(pos syntax.Pos, typ Type, smap substMap, expanding *Named, ctxt *Context) Type

substList function #

substList applies subst to each element of the incoming slice. If at least one element changes, the result is a new slice with all the (possibly updated) elements of the incoming slice; otherwise the result it nil. The incoming slice is unchanged.

func substList(in []T, subst func(T) T) (out []T)

supersetOf method #

supersetOf reports whether y ⊆ xl.

func (xl termlist) supersetOf(y *term) bool

suspendedCall method #

func (check *Checker) suspendedCall(keyword string, call syntax.Expr)

switchStmt method #

func (check *Checker) switchStmt(inner stmtContext, s *syntax.SwitchStmt)

tParamList method #

func (w *typeWriter) tParamList(list []*TypeParam)

tag method #

func (check *Checker) tag(t *syntax.BasicLit) string

tail function #

tail returns the string s without its first (UTF-8) character. If len(s) == 0, the result is s.

func tail(s string) string

term method #

func (subst *subster) term(t *Term) *Term

trace method #

func (check *Checker) trace(pos syntax.Pos, format string, args ...any)

tracef method #

func (u *unifier) tracef(format string, args ...interface{})

trimTrailingEmptyStmts function #

func trimTrailingEmptyStmts(list []syntax.Stmt) []syntax.Stmt

tuple method #

func (subst *subster) tuple(t *Tuple) *Tuple

tuple method #

func (w *typeWriter) tuple(tup *Tuple, variadic bool)

typ method #

func (subst *subster) typ(typ Type) Type

typ method #

func (w *cycleFinder) typ(typ Type)

typ method #

func (w *typeWriter) typ(typ Type)

typ method #

typ type-checks the type expression e and returns its type, or Typ[Invalid]. The type must not be an (uninstantiated) generic type.

func (check *Checker) typ(e syntax.Expr) Type

typInternal method #

typInternal drives type checking of types. Must only be called by definedType or genericType.

func (check *Checker) typInternal(e0 syntax.Expr, def *TypeName) (T Type)

typOrNil method #

typOrNil is like typ but if the argument is nil it is replaced with Typ[Invalid]. A nil type may appear in pathological cases such as type T[P any] []func(_ T([]_)) where an array/slice element is accessed before it is set up.

func (subst *subster) typOrNil(typ Type) Type

typeAssertion method #

typeAssertion checks x.(T). The type of x must be an interface.

func (check *Checker) typeAssertion(e syntax.Expr, x *operand, T Type, typeSwitch bool)

typeDecl method #

func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *TypeName)

typeList method #

func (w *typeWriter) typeList(list []Type)

typeList method #

typeList provides the list of types corresponding to the incoming expression list. If an error occurred, the result is nil, but all list elements were type-checked.

func (check *Checker) typeList(list []syntax.Expr) []Type

typeName method #

func (w *typeWriter) typeName(obj *TypeName)

typeParamVertex method #

typeParamVertex returns the index of the vertex representing tpar.

func (w *monoGraph) typeParamVertex(tpar *TypeParam) int

typeParamsString function #

typeParamsString produces a string containing all the type parameter names in list suitable for human consumption.

func typeParamsString(list []*TypeParam) string

typeSet method #

typeSet returns the type set for interface t.

func (t *Interface) typeSet() *_TypeSet

typeSet method #

typeSet writes a canonical hash for an interface type set.

func (w *typeWriter) typeSet(s *_TypeSet)

typeSwitchStmt method #

func (check *Checker) typeSwitchStmt(inner stmtContext, s *syntax.SwitchStmt, guard *syntax.TypeSwitchGuard)

typesSummary method #

typesSummary returns a string of the form "(t1, t2, ...)" where the ti's are user-friendly string representations for the given types. If variadic is set and the last type is a slice, its string is of the form "...E" where E is the slice's element type. If hasDots is set, the last argument string is of the form "T..." where T is the last type. Only one of variadic and hasDots may be set.

func (check *Checker) typesSummary(list []Type, variadic bool, hasDots bool) string

typeset method #

typeset is an iterator over the (type/underlying type) pairs of the specific type terms of t's constraint. If there are no specific terms, typeset calls yield with (nil, nil). In any case, typeset is guaranteed to call yield at least once.

func (t *TypeParam) typeset(yield func(t Type, u Type) bool)

typeset method #

typeset is an iterator over the (type/underlying type) pairs in s. If s has no specific terms, typeset calls yield with (nil, nil). In any case, typeset is guaranteed to call yield at least once.

func (s *_TypeSet) typeset(yield func(t Type, u Type) bool)

typeset function #

typeset is an iterator over the (type/underlying type) pairs of the specific type terms of the type set implied by t. If t is a type parameter, the implied type set is the type set of t's constraint. In that case, if there are no specific terms, typeset calls yield with (nil, nil). If t is not a type parameter, the implied type set consists of just t. In any case, typeset is guaranteed to call yield at least once.

func typeset(t Type, yield func(t Type, u Type) bool)

unalias function #

func unalias(a0 *Alias) Type

unary method #

func (check *Checker) unary(x *operand, e *syntax.Operation)

under function #

under returns the true expanded underlying type. If it doesn't exist, the result is Typ[Invalid]. under must only be called when a type is known to be fully set up.

func under(t Type) Type

under method #

under returns the expanded underlying type of n0; possibly by following forward chains of named types. If an underlying type is found, resolve the chain by setting the underlying type for each defined type in the chain before returning it. If no underlying type is found or a cycle is detected, the result is Typ[Invalid]. If a cycle is detected and n0.check != nil, the cycle is reported. This is necessary because the underlying type of named may be itself a named type that is incomplete: type ( A B B *C C A ) The type of C is the (named) type of A which is incomplete, and which has as its underlying type the named type B.

func (n0 *Named) under() Type

underIs function #

If typ is a type parameter, underIs returns the result of typ.underIs(f). Otherwise, underIs returns the result of f(under(typ)).

func underIs(typ Type, f func(Type) bool) bool

unify method #

unify attempts to unify x and y and reports whether it succeeded. As a side-effect, types may be inferred for type parameters. The mode parameter controls how types are compared.

func (u *unifier) unify(x Type, y Type, mode unifyMode) bool

union method #

union returns the union x ∪ y: zero, one, or two non-nil terms.

func (x *term) union(y *term) (_ *term, _ *term)

union method #

union returns the union xl ∪ yl.

func (xl termlist) union(yl termlist) termlist

unknowns method #

unknowns returns the number of type parameters for which no type has been set yet.

func (u *unifier) unknowns() int

unpackRecv method #

unpackRecv unpacks a receiver type expression and returns its components: ptr indicates whether rtyp is a pointer receiver, base is the receiver base type expression stripped of its type parameters (if any), and tparams are its type parameter names, if any. The type parameters are only unpacked if unpackParams is set. For instance, given the rtyp *T[A, _] ptr is true, base is T, and tparams is [A, _] (assuming unpackParams is set). Note that base may not be a *syntax.Name for erroneous programs.

func (check *Checker) unpackRecv(rtyp syntax.Expr, unpackParams bool) (ptr bool, base syntax.Expr, tparams []*syntax.Name)

unpointer function #

func unpointer(t Type) Type

unusedImports method #

unusedImports checks for unused imports.

func (check *Checker) unusedImports()

update method #

update de-duplicates inst against previously seen types with the hash h. If an identical type is found with the type hash h, the previously seen type is returned. Otherwise, inst is returned, and recorded in the Context for the hash h.

func (ctxt *Context) update(h string, orig Type, targs []Type, inst Type) Type

updateExprType method #

updateExprType updates the type of x to typ and invokes itself recursively for the operands of x, depending on expression kind. If typ is still an untyped and not the final type, updateExprType only updates the recorded untyped type for x and possibly its operands. Otherwise (i.e., typ is not an untyped type anymore, or it is the final type for x), the type and value are recorded. Also, if x is a constant, it must be representable as a value of typ, and if x is the (formerly untyped) lhs operand of a non-constant shift, it must be an integer value.

func (check *Checker) updateExprType(x syntax.Expr, typ Type, final bool)

updateExprVal method #

updateExprVal updates the value of x to val.

func (check *Checker) updateExprVal(x syntax.Expr, val constant.Value)

usage method #

func (check *Checker) usage(scope *Scope)

use method #

use type-checks each argument. Useful to make sure expressions are evaluated (and variables are "used") in the presence of other errors. Arguments may be nil. Reports if all arguments evaluated without error.

func (check *Checker) use(args ...syntax.Expr) bool

use1 method #

func (check *Checker) use1(e syntax.Expr, lhs bool) bool

useLHS method #

useLHS is like use, but doesn't "use" top-level identifiers. It should be called instead of use if the arguments are expressions on the lhs of an assignment.

func (check *Checker) useLHS(args ...syntax.Expr) bool

useN method #

func (check *Checker) useN(args []syntax.Expr, lhs bool) bool

validAlias method #

validAlias records that alias has the valid type typ (possibly Typ[Invalid]).

func (check *Checker) validAlias(alias *TypeName, typ Type)

validCycle method #

validCycle reports whether the cycle starting with obj is valid and reports an error if it is not.

func (check *Checker) validCycle(obj Object) (valid bool)

validRecv method #

validRecv verifies that the receiver satisfies its respective spec requirements and reports an error otherwise.

func (check *Checker) validRecv(pos poser, recv *Var)

validType method #

validType verifies that the given type does not "expand" indefinitely producing a cycle in the type graph. (Cycles involving alias types, as in "type A = [10]A" are detected earlier, via the objDecl cycle detection mechanism.)

func (check *Checker) validType(typ *Named)

validType0 method #

validType0 checks if the given type is valid. If typ is a type parameter its value is looked up in the type argument list of the instantiated (enclosing) type, if it exists. Otherwise the type parameter must be from an enclosing function and can be ignored. The nest list describes the stack (the "nest in memory") of types which contain (or embed in the case of interfaces) other types. For instance, a struct named S which contains a field of named type F contains (the memory of) F in S, leading to the nest S->F. If a type appears in its own nest (say S->F->S) we have an invalid recursive type. The path list is the full path of named types in a cycle, it is only needed for error reporting.

func (check *Checker) validType0(pos syntax.Pos, typ Type, nest []*Named, path []*Named) bool

validVarType method #

validVarType reports an error if typ is a constraint interface. The expression e is used for error reporting, if any.

func (check *Checker) validVarType(e syntax.Expr, typ Type)

validateTArgLen method #

validateTArgLen checks that the number of type arguments (got) matches the number of type parameters (want); if they don't match an error is reported. If validation fails and check is nil, validateTArgLen panics.

func (check *Checker) validateTArgLen(pos syntax.Pos, name string, want int, got int) bool

validatedImportPath function #

func validatedImportPath(path string) (string, error)

varDecl method #

func (check *Checker) varDecl(obj *Var, lhs []*Var, typ syntax.Expr, init syntax.Expr)

varList method #

func (w *cycleFinder) varList(list []*Var)

varList method #

func (w *tpWalker) varList(list []*Var) bool

varType method #

varType type-checks the type expression e and returns its type, or Typ[Invalid]. The type must not be an (uninstantiated) generic type and it must not be a constraint interface.

func (check *Checker) varType(e syntax.Expr) Type

varTypes function #

varTypes returns the list of types for the given variables.

func varTypes(list []*Var) (res []Type)

var_ method #

func (subst *subster) var_(v *Var) *Var

verify method #

check may be nil; pos is used only if check is non-nil.

func (check *Checker) verify(pos syntax.Pos, tparams []*TypeParam, targs []Type, ctxt *Context) (int, error)

verifyVersionf method #

verifyVersionf is like allowVersion but also accepts a format string and arguments which are used to report a version error if allowVersion returns false.

func (check *Checker) verifyVersionf(at poser, v goVersion, format string, args ...interface{}) bool

versionErrorf method #

func (check *Checker) versionErrorf(at poser, v goVersion, format string, args ...any)

versionMax function #

func versionMax(a goVersion, b goVersion) goVersion

writeFuncName function #

func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier)

writeObject function #

func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier)

Generated with Arrow