types2

package standard library
go1.17.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2021 License: BSD-3-Clause Imports: 16 Imported by: 0

Documentation

Overview

Package types declares the data types and implements the algorithms for type-checking of Go packages. Use Config.Check to invoke the type checker for a package. Alternatively, create a new type checker with NewChecker and invoke it incrementally by calling Checker.Files.

Type-checking consists of several interdependent phases:

Name resolution maps each identifier (syntax.Name) in the program to the language object (Object) it denotes. Use Info.{Defs,Uses,Implicits} for the results of name resolution.

Constant folding computes the exact constant value (constant.Value) for every expression (syntax.Expr) that is a compile-time constant. Use Info.Types[expr].Value for the results of constant folding.

Type inference computes the type (Type) of every expression (syntax.Expr) and checks for compliance with the language specification. Use Info.Types[expr].Type for the results of type inference.

Index

Examples

Constants

This section is empty.

Variables

View Source
var Typ = [...]*Basic{
	Invalid: {Invalid, 0, "invalid type"},

	Bool:          {Bool, IsBoolean, "bool"},
	Int:           {Int, IsInteger, "int"},
	Int8:          {Int8, IsInteger, "int8"},
	Int16:         {Int16, IsInteger, "int16"},
	Int32:         {Int32, IsInteger, "int32"},
	Int64:         {Int64, IsInteger, "int64"},
	Uint:          {Uint, IsInteger | IsUnsigned, "uint"},
	Uint8:         {Uint8, IsInteger | IsUnsigned, "uint8"},
	Uint16:        {Uint16, IsInteger | IsUnsigned, "uint16"},
	Uint32:        {Uint32, IsInteger | IsUnsigned, "uint32"},
	Uint64:        {Uint64, IsInteger | IsUnsigned, "uint64"},
	Uintptr:       {Uintptr, IsInteger | IsUnsigned, "uintptr"},
	Float32:       {Float32, IsFloat, "float32"},
	Float64:       {Float64, IsFloat, "float64"},
	Complex64:     {Complex64, IsComplex, "complex64"},
	Complex128:    {Complex128, IsComplex, "complex128"},
	String:        {String, IsString, "string"},
	UnsafePointer: {UnsafePointer, 0, "Pointer"},

	UntypedBool:    {UntypedBool, IsBoolean | IsUntyped, "untyped bool"},
	UntypedInt:     {UntypedInt, IsInteger | IsUntyped, "untyped int"},
	UntypedRune:    {UntypedRune, IsInteger | IsUntyped, "untyped rune"},
	UntypedFloat:   {UntypedFloat, IsFloat | IsUntyped, "untyped float"},
	UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, "untyped complex"},
	UntypedString:  {UntypedString, IsString | IsUntyped, "untyped string"},
	UntypedNil:     {UntypedNil, IsUntyped, "untyped nil"},
}

Typ contains the predeclared *Basic types indexed by their corresponding BasicKind.

The *Basic type for Typ[Byte] will have the name "uint8". Use Universe.Lookup("byte").Type() to obtain the specific alias basic type named "byte" (and analogous for "rune").

Functions

func AssertableTo

func AssertableTo(V *Interface, T Type) bool

AssertableTo reports whether a value of type V can be asserted to have type T.

func AssignableTo

func AssignableTo(V, T Type) bool

AssignableTo reports whether a value of type V is assignable to a variable of type T.

func Comparable

func Comparable(T Type) bool

Comparable reports whether values of type T are comparable.

func ConvertibleTo

func ConvertibleTo(V, T Type) bool

ConvertibleTo reports whether a value of type V is convertible to a value of type T.

func DefPredeclaredTestFuncs

func DefPredeclaredTestFuncs()

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

func Id

func Id(pkg *Package, name string) string

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

func Identical

func Identical(x, y Type) bool

Identical reports whether x and y are identical types. Receivers of Signature types are ignored.

func IdenticalIgnoreTags

func IdenticalIgnoreTags(x, y Type) bool

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

func Implements

func Implements(V Type, T *Interface) bool

Implements reports whether type V implements interface T.

func IsInterface

func IsInterface(typ Type) bool

IsInterface reports whether typ is an interface type.

func ObjectString

func ObjectString(obj Object, qf Qualifier) string

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

func SelectionString

func SelectionString(s *Selection, qf Qualifier) string

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

Examples:

"field (T) f int"
"method (T) f(X) Y"
"method expr (T) f(X) Y"

func TypeString

func TypeString(typ Type, qf Qualifier) string

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

func WriteSignature

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

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 WriteType

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

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

Types

type Array

type Array struct {
	// contains filtered or unexported fields
}

An Array represents an array type.

func NewArray

func NewArray(elem Type, len int64) *Array

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

func (*Array) Elem

func (a *Array) Elem() Type

Elem returns element type of array a.

func (*Array) Len

func (a *Array) Len() int64

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

func (*Array) String

func (t *Array) String() string

func (*Array) Underlying

func (t *Array) Underlying() Type

type Basic

type Basic struct {
	// contains filtered or unexported fields
}

A Basic represents a basic type.

func (*Basic) Info

func (b *Basic) Info() BasicInfo

Info returns information about properties of basic type b.

func (*Basic) Kind

func (b *Basic) Kind() BasicKind

Kind returns the kind of basic type b.

func (*Basic) Name

func (b *Basic) Name() string

Name returns the name of basic type b.

func (*Basic) String

func (t *Basic) String() string

Type-specific implementations of String.

func (*Basic) Underlying

func (t *Basic) Underlying() Type

Type-specific implementations of Underlying.

type BasicInfo

type BasicInfo int

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

const (
	IsBoolean BasicInfo = 1 << iota
	IsInteger
	IsUnsigned
	IsFloat
	IsComplex
	IsString
	IsUntyped

	IsOrdered   = IsInteger | IsFloat | IsString
	IsNumeric   = IsInteger | IsFloat | IsComplex
	IsConstType = IsBoolean | IsNumeric | IsString
)

Properties of basic types.

type BasicKind

type BasicKind int

BasicKind describes the kind of basic type.

const (
	Invalid BasicKind = iota // type is invalid

	// predeclared types
	Bool
	Int
	Int8
	Int16
	Int32
	Int64
	Uint
	Uint8
	Uint16
	Uint32
	Uint64
	Uintptr
	Float32
	Float64
	Complex64
	Complex128
	String
	UnsafePointer

	// types for untyped values
	UntypedBool
	UntypedInt
	UntypedRune
	UntypedFloat
	UntypedComplex
	UntypedString
	UntypedNil

	// aliases
	Byte = Uint8
	Rune = Int32
)

type Builtin

type Builtin struct {
	// contains filtered or unexported fields
}

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

func (*Builtin) Exported

func (obj *Builtin) Exported() bool

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 (*Builtin) Id

func (obj *Builtin) Id() string

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

func (*Builtin) Name

func (obj *Builtin) Name() string

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

func (*Builtin) Parent

func (obj *Builtin) Parent() *Scope

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

func (*Builtin) Pkg

func (obj *Builtin) Pkg() *Package

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

func (*Builtin) Pos

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

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

func (*Builtin) String

func (obj *Builtin) String() string

func (*Builtin) Type

func (obj *Builtin) Type() Type

Type returns the object's type.

type Chan

type Chan struct {
	// contains filtered or unexported fields
}

A Chan represents a channel type.

func NewChan

func NewChan(dir ChanDir, elem Type) *Chan

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

func (*Chan) Dir

func (c *Chan) Dir() ChanDir

Dir returns the direction of channel c.

func (*Chan) Elem

func (c *Chan) Elem() Type

Elem returns the element type of channel c.

func (*Chan) String

func (t *Chan) String() string

func (*Chan) Underlying

func (t *Chan) Underlying() Type

type ChanDir

type ChanDir int

A ChanDir value indicates a channel direction.

const (
	SendRecv ChanDir = iota
	SendOnly
	RecvOnly
)

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

type Checker

type Checker struct {
	*Info
	// contains filtered or unexported fields
}

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

func NewChecker

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

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

func (*Checker) Files

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

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

func (*Checker) NewTypeParam

func (check *Checker) NewTypeParam(obj *TypeName, index int, bound Type) *TypeParam

NewTypeParam returns a new TypeParam.

type Config

type Config struct {
	// GoVersion describes the accepted Go language version. The string
	// must follow the format "go%d.%d" (e.g. "go1.12") or ist must be
	// empty; an empty string indicates the latest language version.
	// If the format is invalid, invoking the type checker will cause a
	// panic.
	GoVersion string

	// If IgnoreFuncBodies is set, function bodies are not
	// type-checked.
	IgnoreFuncBodies bool

	// If FakeImportC is set, `import "C"` (for packages requiring Cgo)
	// declares an empty "C" package and errors are omitted for qualified
	// identifiers referring to package C (which won't find an object).
	// This feature is intended for the standard library cmd/api tool.
	//
	// Caution: Effects may be unpredictable due to follow-on errors.
	//          Do not use casually!
	FakeImportC bool

	// If IgnoreLabels is set, correct label use is not checked.
	// TODO(gri) Consolidate label checking and remove this flag.
	IgnoreLabels bool

	// If CompilerErrorMessages is set, errors are reported using
	// cmd/compile error strings to match $GOROOT/test errors.
	// TODO(gri) Consolidate error messages and remove this flag.
	CompilerErrorMessages bool

	// If Trace is set, a debug trace is printed to stdout.
	Trace bool

	// If Error != nil, it is called with each error found
	// during type checking; err has dynamic type Error.
	// Secondary errors (for instance, to enumerate all types
	// involved in an invalid recursive type declaration) have
	// error strings that start with a '\t' character.
	// If Error == nil, type-checking stops with the first
	// error found.
	Error func(err error)

	// An importer is used to import packages referred to from
	// import declarations.
	// If the installed importer implements ImporterFrom, the type
	// checker calls ImportFrom instead of Import.
	// The type checker reports an error if an importer is needed
	// but none was installed.
	Importer Importer

	// If Sizes != nil, it provides the sizing functions for package unsafe.
	// Otherwise SizesFor("gc", "amd64") is used instead.
	Sizes Sizes

	// If DisableUnusedImportCheck is set, packages are not checked
	// for unused imports.
	DisableUnusedImportCheck bool
	// contains filtered or unexported fields
}

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

func (*Config) Check

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

Check type-checks a package and returns the resulting package object and the first error if any. Additionally, if info != nil, Check populates each of the non-nil maps in the Info struct.

The package is marked as complete if no errors occurred, otherwise it is incomplete. See Config.Error for controlling behavior in the presence of errors.

The package is specified by a list of *syntax.Files and corresponding file set, and the package path the package is identified with. The clean path must not be empty or dot (".").

type Const

type Const struct {
	// contains filtered or unexported fields
}

A Const represents a declared constant.

func NewConst

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

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

func (*Const) Exported

func (obj *Const) Exported() bool

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 (*Const) Id

func (obj *Const) Id() string

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

func (*Const) Name

func (obj *Const) Name() string

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

func (*Const) Parent

func (obj *Const) Parent() *Scope

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

func (*Const) Pkg

func (obj *Const) Pkg() *Package

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

func (*Const) Pos

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

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

func (*Const) String

func (obj *Const) String() string

func (*Const) Type

func (obj *Const) Type() Type

Type returns the object's type.

func (*Const) Val

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

Val returns the constant's value.

type Error

type Error struct {
	Pos  syntax.Pos // error position
	Msg  string     // default error message, user-friendly
	Full string     // full error message, for debugging (may contain internal details)
	Soft bool       // if set, error is "soft"
}

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.

func (Error) Error

func (err Error) Error() string

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

func (Error) FullError

func (err Error) FullError() string

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.

type Func

type Func struct {
	// contains filtered or unexported fields
}

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

func MissingMethod

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

MissingMethod returns (nil, false) if V implements T, otherwise it returns a missing method required by T and whether it is missing or just has the wrong type.

For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Otherwise (V is an interface and static is not set), MissingMethod only checks that methods of T which are also present in V have matching types (e.g., for a type assertion x.(T) where x is of interface type V).

func NewFunc

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

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

func (*Func) Exported

func (obj *Func) Exported() bool

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 (*Func) FullName

func (obj *Func) FullName() string

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

func (*Func) Id

func (obj *Func) Id() string

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

func (*Func) Name

func (obj *Func) Name() string

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

func (*Func) Parent

func (obj *Func) Parent() *Scope

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

func (*Func) Pkg

func (obj *Func) Pkg() *Package

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

func (*Func) Pos

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

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

func (*Func) Scope

func (obj *Func) Scope() *Scope

Scope returns the scope of the function's body block.

func (*Func) String

func (obj *Func) String() string

func (*Func) Type

func (obj *Func) Type() Type

Type returns the object's type.

type ImportMode

type ImportMode int

ImportMode is reserved for future use.

type Importer

type Importer interface {
	// Import returns the imported package for the given import path.
	// The semantics is like for ImporterFrom.ImportFrom except that
	// dir and mode are ignored (since they are not present).
	Import(path string) (*Package, error)
}

An Importer resolves import paths to Packages.

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

type ImporterFrom

type ImporterFrom interface {
	// Importer is present for backward-compatibility. Calling
	// Import(path) is the same as calling ImportFrom(path, "", 0);
	// i.e., locally vendored packages may not be found.
	// The types package does not call Import if an ImporterFrom
	// is present.
	Importer

	// ImportFrom returns the imported package for the given import
	// path when imported by a package file located in dir.
	// If the import failed, besides returning an error, ImportFrom
	// is encouraged to cache and return a package anyway, if one
	// was created. This will reduce package inconsistencies and
	// follow-on type checker errors due to the missing package.
	// The mode value must be 0; it is reserved for future use.
	// Two calls to ImportFrom with the same path and dir must
	// return the same package.
	ImportFrom(path, dir string, mode ImportMode) (*Package, error)
}

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

type Inferred

type Inferred struct {
	Targs []Type
	Sig   *Signature
}

Inferred reports the inferred type arguments and signature for a parameterized function call that uses type inference.

type Info

type Info struct {
	// Types maps expressions to their types, and for constant
	// expressions, also their values. Invalid expressions are
	// omitted.
	//
	// For (possibly parenthesized) identifiers denoting built-in
	// functions, the recorded signatures are call-site specific:
	// if the call result is not a constant, the recorded type is
	// an argument-specific signature. Otherwise, the recorded type
	// is invalid.
	//
	// The Types map does not record the type of every identifier,
	// only those that appear where an arbitrary expression is
	// permitted. For instance, the identifier f in a selector
	// expression x.f is found only in the Selections map, the
	// identifier z in a variable declaration 'var z int' is found
	// only in the Defs map, and identifiers denoting packages in
	// qualified identifiers are collected in the Uses map.
	Types map[syntax.Expr]TypeAndValue

	// Inferred maps calls of parameterized functions that use
	// type inference to the inferred type arguments and signature
	// of the function called. The recorded "call" expression may be
	// an *ast.CallExpr (as in f(x)), or an *ast.IndexExpr (s in f[T]).
	Inferred map[syntax.Expr]Inferred

	// Defs maps identifiers to the objects they define (including
	// package names, dots "." of dot-imports, and blank "_" identifiers).
	// For identifiers that do not denote objects (e.g., the package name
	// in package clauses, or symbolic variables t in t := x.(type) of
	// type switch headers), the corresponding objects are nil.
	//
	// For an embedded field, Defs returns the field *Var it defines.
	//
	// Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
	Defs map[*syntax.Name]Object

	// Uses maps identifiers to the objects they denote.
	//
	// For an embedded field, Uses returns the *TypeName it denotes.
	//
	// Invariant: Uses[id].Pos() != id.Pos()
	Uses map[*syntax.Name]Object

	// Implicits maps nodes to their implicitly declared objects, if any.
	// The following node and object types may appear:
	//
	//     node               declared object
	//
	//     *syntax.ImportDecl    *PkgName for imports without renames
	//     *syntax.CaseClause    type-specific *Var for each type switch case clause (incl. default)
	//     *syntax.Field         anonymous parameter *Var (incl. unnamed results)
	//
	Implicits map[syntax.Node]Object

	// Selections maps selector expressions (excluding qualified identifiers)
	// to their corresponding selections.
	Selections map[*syntax.SelectorExpr]*Selection

	// Scopes maps syntax.Nodes to the scopes they define. Package scopes are not
	// associated with a specific node but with all files belonging to a package.
	// Thus, the package scope can be found in the type-checked Package object.
	// Scopes nest, with the Universe scope being the outermost scope, enclosing
	// the package scope, which contains (one or more) files scopes, which enclose
	// function scopes which in turn enclose statement and function literal scopes.
	// Note that even though package-level functions are declared in the package
	// scope, the function scopes are embedded in the file scope of the file
	// containing the function declaration.
	//
	// The following node types may appear in Scopes:
	//
	//     *syntax.File
	//     *syntax.FuncType
	//     *syntax.BlockStmt
	//     *syntax.IfStmt
	//     *syntax.SwitchStmt
	//     *syntax.CaseClause
	//     *syntax.CommClause
	//     *syntax.ForStmt
	//
	Scopes map[syntax.Node]*Scope

	// InitOrder is the list of package-level initializers in the order in which
	// they must be executed. Initializers referring to variables related by an
	// initialization dependency appear in topological order, the others appear
	// in source order. Variables without an initialization expression do not
	// appear in this list.
	InitOrder []*Initializer
}

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

Example

ExampleInfo prints various facts recorded by the type checker in a types2.Info struct: definitions of and references to each named object, and the type, value, and mode of every expression in the package.

// Parse a single source file.
const input = `
package fib

type S string

var a, b, c = len(b), S(c), "hello"

func fib(x int) int {
	if x < 2 {
		return x
	}
	return fib(x-1) - fib(x-2)
}`
f, err := parseSrc("fib.go", input)
if err != nil {
	log.Fatal(err)
}

// Type-check the package.
// We create an empty map for each kind of input
// we're interested in, and Check populates them.
info := types2.Info{
	Types: make(map[syntax.Expr]types2.TypeAndValue),
	Defs:  make(map[*syntax.Name]types2.Object),
	Uses:  make(map[*syntax.Name]types2.Object),
}
var conf types2.Config
pkg, err := conf.Check("fib", []*syntax.File{f}, &info)
if err != nil {
	log.Fatal(err)
}

// Print package-level variables in initialization order.
fmt.Printf("InitOrder: %v\n\n", info.InitOrder)

// For each named object, print the line and
// column of its definition and each of its uses.
fmt.Println("Defs and Uses of each named object:")
usesByObj := make(map[types2.Object][]string)
for id, obj := range info.Uses {
	posn := id.Pos()
	lineCol := fmt.Sprintf("%d:%d", posn.Line(), posn.Col())
	usesByObj[obj] = append(usesByObj[obj], lineCol)
}
var items []string
for obj, uses := range usesByObj {
	sort.Strings(uses)
	item := fmt.Sprintf("%s:\n  defined at %s\n  used at %s",
		types2.ObjectString(obj, types2.RelativeTo(pkg)),
		obj.Pos(),
		strings.Join(uses, ", "))
	items = append(items, item)
}
sort.Strings(items) // sort by line:col, in effect
fmt.Println(strings.Join(items, "\n"))
fmt.Println()

// TODO(gri) Enable once positions are updated/verified
// fmt.Println("Types and Values of each expression:")
// items = nil
// for expr, tv := range info.Types {
// 	var buf bytes.Buffer
// 	posn := expr.Pos()
// 	tvstr := tv.Type.String()
// 	if tv.Value != nil {
// 		tvstr += " = " + tv.Value.String()
// 	}
// 	// line:col | expr | mode : type = value
// 	fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
// 		posn.Line(), posn.Col(), types2.ExprString(expr),
// 		mode(tv), tvstr)
// 	items = append(items, buf.String())
// }
// sort.Strings(items)
// fmt.Println(strings.Join(items, "\n"))
Output:

func (*Info) ObjectOf

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

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

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

TypeOf returns the type of expression e, or nil if not found. Precondition: the Types, Uses and Defs maps are populated.

type Initializer

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

An Initializer describes a package-level variable, or a list of variables in case of a multi-valued initialization expression, and the corresponding initialization expression.

func (*Initializer) String

func (init *Initializer) String() string

type Interface

type Interface struct {
	// contains filtered or unexported fields
}

An Interface represents an interface type.

func AsInterface

func AsInterface(t Type) *Interface

func NewInterface deprecated

func NewInterface(methods []*Func, embeddeds []*Named) *Interface

NewInterface returns a new (incomplete) interface for the given methods and embedded types. Each embedded type must have an underlying type of interface type. NewInterface takes ownership of the provided methods and may modify their types by setting missing receivers. To compute the method set of the interface, Complete must be called.

Deprecated: Use NewInterfaceType instead which allows any (even non-defined) interface types to be embedded. This is necessary for interfaces that embed alias type names referring to non-defined (literal) interface types.

func NewInterfaceType

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

NewInterfaceType returns a new (incomplete) interface for the given methods and embedded types. Each embedded type must have an underlying type of interface type (this property is not verified for defined types, which may be in the process of being set up and which don't have a valid underlying type yet). NewInterfaceType takes ownership of the provided methods and may modify their types by setting missing receivers. To compute the method set of the interface, Complete must be called.

func (*Interface) Complete

func (t *Interface) Complete() *Interface

Complete computes the interface's method set. It must be called by users of NewInterfaceType and NewInterface after the interface's embedded types are fully defined and before using the interface type in any way other than to form other types. The interface must not contain duplicate methods or a panic occurs. Complete returns the receiver.

func (*Interface) Embedded deprecated

func (t *Interface) Embedded(i int) *Named

Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds(). The result is nil if the i'th embedded type is not a defined type.

Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.

func (*Interface) EmbeddedType

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

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

func (*Interface) Empty

func (t *Interface) Empty() bool

Empty reports whether t is the empty interface.

func (*Interface) ExplicitMethod

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

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

func (*Interface) HasTypeList

func (t *Interface) HasTypeList() bool

HasTypeList reports whether interface t has a type list, possibly from an embedded type.

func (*Interface) IsComparable

func (t *Interface) IsComparable() bool

IsComparable reports whether interface t is or embeds the predeclared interface "comparable".

func (*Interface) IsConstraint

func (t *Interface) IsConstraint() bool

IsConstraint reports t.HasTypeList() || t.IsComparable().

func (*Interface) Method

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

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

func (*Interface) NumEmbeddeds

func (t *Interface) NumEmbeddeds() int

NumEmbeddeds returns the number of embedded types in interface t.

func (*Interface) NumExplicitMethods

func (t *Interface) NumExplicitMethods() int

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

func (*Interface) NumMethods

func (t *Interface) NumMethods() int

NumMethods returns the total number of methods of interface t. The interface must have been completed.

func (*Interface) String

func (t *Interface) String() string

func (*Interface) Underlying

func (t *Interface) Underlying() Type

type Label

type Label struct {
	// contains filtered or unexported fields
}

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

func NewLabel

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

NewLabel returns a new label.

func (*Label) Exported

func (obj *Label) Exported() bool

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 (*Label) Id

func (obj *Label) Id() string

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

func (*Label) Name

func (obj *Label) Name() string

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

func (*Label) Parent

func (obj *Label) Parent() *Scope

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

func (*Label) Pkg

func (obj *Label) Pkg() *Package

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

func (*Label) Pos

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

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

func (*Label) String

func (obj *Label) String() string

func (*Label) Type

func (obj *Label) Type() Type

Type returns the object's type.

type Map

type Map struct {
	// contains filtered or unexported fields
}

A Map represents a map type.

func NewMap

func NewMap(key, elem Type) *Map

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

func (*Map) Elem

func (m *Map) Elem() Type

Elem returns the element type of map m.

func (*Map) Key

func (m *Map) Key() Type

Key returns the key type of map m.

func (*Map) String

func (t *Map) String() string

func (*Map) Underlying

func (t *Map) Underlying() Type

type Named

type Named struct {
	// contains filtered or unexported fields
}

A Named represents a named (defined) type.

func AsNamed

func AsNamed(t Type) *Named

func NewNamed

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

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

func (*Named) AddMethod

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

AddMethod adds method m unless it is already in the method list.

func (*Named) Method

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

Method returns the i'th method of named type t for 0 <= i < t.NumMethods().

func (*Named) NumMethods

func (t *Named) NumMethods() int

NumMethods returns the number of explicit methods whose receiver is named type t.

func (*Named) Obj

func (t *Named) Obj() *TypeName

Obj returns the type name for the named type t.

func (*Named) Orig

func (t *Named) Orig() *Named

Orig returns the original generic type an instantiated type is derived from. If t is not an instantiated type, the result is t.

func (*Named) SetTArgs

func (t *Named) SetTArgs(args []Type)

SetTArgs sets the type arguments of the named type t.

func (*Named) SetTParams

func (t *Named) SetTParams(tparams []*TypeName)

SetTParams sets the type parameters of the named type t.

func (*Named) SetUnderlying

func (t *Named) SetUnderlying(underlying Type)

SetUnderlying sets the underlying type and marks t as complete.

func (*Named) String

func (t *Named) String() string

func (*Named) TArgs

func (t *Named) TArgs() []Type

TArgs returns the type arguments after instantiation of the named type t, or nil if not instantiated.

func (*Named) TParams

func (t *Named) TParams() []*TypeName

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

func (*Named) Underlying

func (t *Named) Underlying() Type

type Nil

type Nil struct {
	// contains filtered or unexported fields
}

Nil represents the predeclared value nil.

func (*Nil) Exported

func (obj *Nil) Exported() bool

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 (*Nil) Id

func (obj *Nil) Id() string

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

func (*Nil) Name

func (obj *Nil) Name() string

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

func (*Nil) Parent

func (obj *Nil) Parent() *Scope

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

func (*Nil) Pkg

func (obj *Nil) Pkg() *Package

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

func (*Nil) Pos

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

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

func (*Nil) String

func (obj *Nil) String() string

func (*Nil) Type

func (obj *Nil) Type() Type

Type returns the object's type.

type Object

type Object interface {
	Parent() *Scope  // scope in which this object is declared; nil for methods and struct fields
	Pos() syntax.Pos // position of object identifier in declaration
	Pkg() *Package   // package to which this object belongs; nil for labels and objects in the Universe scope
	Name() string    // package local object name
	Type() Type      // object type
	Exported() bool  // reports whether the name starts with a capital letter
	Id() string      // object name if exported, qualified name if not exported (see func Id)

	// String returns a human-readable string of the object.
	String() string
	// contains filtered or unexported methods
}

An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label. All objects implement the Object interface.

func LookupFieldOrMethod

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

LookupFieldOrMethod looks up a field or method with given package and name in T and returns the corresponding *Var or *Func, an index sequence, and a bool indicating if there were any pointer indirections on the path to the field or method. If addressable is set, T is the type of an addressable variable (only matters for method lookups).

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.

type Package

type Package struct {
	// contains filtered or unexported fields
}

A Package describes a Go package.

var Unsafe *Package

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

func NewPackage

func NewPackage(path, name string) *Package

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

func (*Package) Complete

func (pkg *Package) Complete() bool

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

func (*Package) Imports

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

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.

func (*Package) MarkComplete

func (pkg *Package) MarkComplete()

MarkComplete marks a package as complete.

func (*Package) Name

func (pkg *Package) Name() string

Name returns the package name.

func (*Package) Path

func (pkg *Package) Path() string

Path returns the package path.

func (*Package) Scope

func (pkg *Package) Scope() *Scope

Scope returns the (complete or incomplete) package scope holding the objects declared at package level (TypeNames, Consts, Vars, and Funcs).

func (*Package) SetImports

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

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

func (*Package) SetName

func (pkg *Package) SetName(name string)

SetName sets the package name.

func (*Package) String

func (pkg *Package) String() string

type PkgName

type PkgName struct {
	// contains filtered or unexported fields
}

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

func NewPkgName

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

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

func (*PkgName) Exported

func (obj *PkgName) Exported() bool

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 (*PkgName) Id

func (obj *PkgName) Id() string

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

func (*PkgName) Imported

func (obj *PkgName) Imported() *Package

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

func (*PkgName) Name

func (obj *PkgName) Name() string

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

func (*PkgName) Parent

func (obj *PkgName) Parent() *Scope

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

func (*PkgName) Pkg

func (obj *PkgName) Pkg() *Package

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

func (*PkgName) Pos

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

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

func (*PkgName) String

func (obj *PkgName) String() string

func (*PkgName) Type

func (obj *PkgName) Type() Type

Type returns the object's type.

type Pointer

type Pointer struct {
	// contains filtered or unexported fields
}

A Pointer represents a pointer type.

func AsPointer

func AsPointer(t Type) *Pointer

func NewPointer

func NewPointer(elem Type) *Pointer

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

func (*Pointer) Elem

func (p *Pointer) Elem() Type

Elem returns the element type for the given pointer p.

func (*Pointer) String

func (t *Pointer) String() string

func (*Pointer) Underlying

func (t *Pointer) Underlying() Type

type Qualifier

type Qualifier func(*Package) string

A Qualifier controls how named package-level objects are printed in calls to TypeString, ObjectString, and SelectionString.

These three formatting routines call the Qualifier for each package-level object O, and if the Qualifier returns a non-empty string p, the object is printed in the form p.O. If it returns an empty string, only the object name O is printed.

Using a nil Qualifier is equivalent to using (*Package).Path: the object is qualified by the import path, e.g., "encoding/json.Marshal".

func RelativeTo

func RelativeTo(pkg *Package) Qualifier

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

type Scope

type Scope struct {
	// contains filtered or unexported fields
}

A Scope maintains a set of objects and links to its containing (parent) and contained (children) scopes. Objects may be inserted and looked up by name. The zero value for Scope is a ready-to-use empty scope.

Example

ExampleScope prints the tree of Scopes of a package created from a set of parsed files.

// Parse the source files for a package.
var files []*syntax.File
for _, file := range []struct{ name, input string }{
	{"main.go", `
package main
import "fmt"
func main() {
	freezing := FToC(-18)
	fmt.Println(freezing, Boiling) }
`},
	{"celsius.go", `
package main
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
const Boiling Celsius = 100
func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
`},
} {
	f, err := parseSrc(file.name, file.input)
	if err != nil {
		log.Fatal(err)
	}
	files = append(files, f)
}

// Type-check a package consisting of these files.
// Type information for the imported "fmt" package
// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
conf := types2.Config{Importer: defaultImporter()}
pkg, err := conf.Check("temperature", files, nil)
if err != nil {
	log.Fatal(err)
}

// Print the tree of scopes.
// For determinism, we redact addresses.
var buf bytes.Buffer
pkg.Scope().WriteTo(&buf, 0, true)
rx := regexp.MustCompile(` 0x[a-fA-F0-9]*`)
fmt.Println(rx.ReplaceAllString(buf.String(), ""))
Output:

package "temperature" scope {
.  const temperature.Boiling temperature.Celsius
.  type temperature.Celsius float64
.  func temperature.FToC(f float64) temperature.Celsius
.  func temperature.Unused()
.  func temperature.main()
.  main.go scope {
.  .  package fmt
.  .  function scope {
.  .  .  var freezing temperature.Celsius
.  .  }
.  }
.  celsius.go scope {
.  .  package fmt
.  .  function scope {
.  .  .  var c temperature.Celsius
.  .  }
.  .  function scope {
.  .  .  var f float64
.  .  }
.  .  function scope {
.  .  .  block scope {
.  .  .  }
.  .  .  block scope {
.  .  .  .  block scope {
.  .  .  .  .  var x int
.  .  .  .  }
.  .  .  }
.  .  }
.  }
}
var Universe *Scope

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

func NewScope

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

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

func (*Scope) Child

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

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

func (*Scope) Contains

func (s *Scope) Contains(pos syntax.Pos) bool

Contains reports whether pos is within the scope's extent. The result is guaranteed to be valid only if the type-checked AST has complete position information.

func (*Scope) End

func (s *Scope) End() syntax.Pos

func (*Scope) Innermost

func (s *Scope) Innermost(pos syntax.Pos) *Scope

Innermost returns the innermost (child) scope containing pos. If pos is not within any scope, the result is nil. The result is also nil for the Universe scope. The result is guaranteed to be valid only if the type-checked AST has complete position information.

func (*Scope) Insert

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

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

func (*Scope) Len

func (s *Scope) Len() int

Len returns the number of scope elements.

func (*Scope) Lookup

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

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

func (*Scope) LookupParent

func (s *Scope) LookupParent(name string, pos syntax.Pos) (*Scope, Object)

LookupParent follows the parent chain of scopes starting with s until it finds a scope where Lookup(name) returns a non-nil object, and then returns that scope and object. If a valid position pos is provided, only objects that were declared at or before pos are considered. If no such scope and object exists, the result is (nil, nil).

Note that obj.Parent() may be different from the returned scope if the object was inserted into the scope and already had a parent at that time (see Insert). This can only happen for dot-imported objects whose scope is the scope of the package that exported them.

func (*Scope) Names

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

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

func (*Scope) NumChildren

func (s *Scope) NumChildren() int

NumChildren returns the number of scopes nested in s.

func (*Scope) Parent

func (s *Scope) Parent() *Scope

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

func (*Scope) Pos

func (s *Scope) Pos() syntax.Pos

Pos and End describe the scope's source code extent [pos, end). The results are guaranteed to be valid only if the type-checked AST has complete position information. The extent is undefined for Universe and package scopes.

func (*Scope) Squash

func (s *Scope) Squash(err func(obj, alt Object))

Squash merges s with its parent scope p by adding all objects of s to p, adding all children of s to the children of p, and removing s from p's children. The function f is called for each object obj in s which has an object alt in p. s should be discarded after having been squashed.

func (*Scope) String

func (s *Scope) String() string

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

func (*Scope) WriteTo

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

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.

type Selection

type Selection struct {
	// contains filtered or unexported fields
}

A Selection describes a selector expression x.f. For the declarations:

type T struct{ x int; E }
type E struct{}
func (e E) m() {}
var p *T

the following relations exist:

Selector    Kind          Recv    Obj    Type       Index     Indirect

p.x         FieldVal      T       x      int        {0}       true
p.m         MethodVal     *T      m      func()     {1, 0}    true
T.m         MethodExpr    T       m      func(T)    {1, 0}    false

func (*Selection) Index

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

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 (*Selection) Indirect

func (s *Selection) Indirect() bool

Indirect reports whether any pointer indirection was required to get from x to f in x.f.

func (*Selection) Kind

func (s *Selection) Kind() SelectionKind

Kind returns the selection kind.

func (*Selection) Obj

func (s *Selection) Obj() Object

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

func (*Selection) Recv

func (s *Selection) Recv() Type

Recv returns the type of x in x.f.

func (*Selection) String

func (s *Selection) String() string

func (*Selection) Type

func (s *Selection) Type() Type

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

type SelectionKind

type SelectionKind int

SelectionKind describes the kind of a selector expression x.f (excluding qualified identifiers).

const (
	FieldVal   SelectionKind = iota // x.f is a struct field selector
	MethodVal                       // x.f is a method selector
	MethodExpr                      // x.f is a method expression
)

type Signature

type Signature struct {
	// contains filtered or unexported fields
}

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

func AsSignature

func AsSignature(t Type) *Signature

func NewSignature

func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature

NewSignature returns a new function type for the given receiver, parameters, and results, either of which may be nil. If variadic is set, the function is variadic, it must have at least one parameter, and the last parameter must be of unnamed slice type.

func (*Signature) Params

func (s *Signature) Params() *Tuple

Params returns the parameters of signature s, or nil.

func (*Signature) RParams

func (s *Signature) RParams() []*TypeName

RParams returns the receiver type params of signature s, or nil.

func (*Signature) Recv

func (s *Signature) Recv() *Var

Recv returns the receiver of signature s (if a method), or nil if a function. It is ignored when comparing signatures for identity.

For an abstract method, Recv returns the enclosing interface either as a *Named or an *Interface. Due to embedding, an interface may contain methods whose receiver type is a different interface.

func (*Signature) Results

func (s *Signature) Results() *Tuple

Results returns the results of signature s, or nil.

func (*Signature) SetTParams

func (s *Signature) SetTParams(tparams []*TypeName)

SetTParams sets the type parameters of signature s.

func (*Signature) String

func (t *Signature) String() string

func (*Signature) TParams

func (s *Signature) TParams() []*TypeName

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

func (*Signature) Underlying

func (t *Signature) Underlying() Type

func (*Signature) Variadic

func (s *Signature) Variadic() bool

Variadic reports whether the signature s is variadic.

type Sizes

type Sizes interface {
	// Alignof returns the alignment of a variable of type T.
	// Alignof must implement the alignment guarantees required by the spec.
	Alignof(T Type) int64

	// Offsetsof returns the offsets of the given struct fields, in bytes.
	// Offsetsof must implement the offset guarantees required by the spec.
	Offsetsof(fields []*Var) []int64

	// Sizeof returns the size of a variable of type T.
	// Sizeof must implement the size guarantees required by the spec.
	Sizeof(T Type) int64
}

Sizes defines the sizing functions for package unsafe.

func SizesFor

func SizesFor(compiler, arch string) Sizes

SizesFor returns the Sizes used by a compiler for an architecture. The result is nil if a compiler/architecture pair is not known.

Supported architectures for compiler "gc": "386", "arm", "arm64", "amd64", "amd64p32", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm".

type Slice

type Slice struct {
	// contains filtered or unexported fields
}

A Slice represents a slice type.

func NewSlice

func NewSlice(elem Type) *Slice

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

func (*Slice) Elem

func (s *Slice) Elem() Type

Elem returns the element type of slice s.

func (*Slice) String

func (t *Slice) String() string

func (*Slice) Underlying

func (t *Slice) Underlying() Type

type StdSizes

type StdSizes struct {
	WordSize int64 // word size in bytes - must be >= 4 (32bits)
	MaxAlign int64 // maximum alignment in bytes - must be >= 1
}

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.

func (*StdSizes) Alignof

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

func (*StdSizes) Offsetsof

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

func (*StdSizes) Sizeof

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

type Struct

type Struct struct {
	// contains filtered or unexported fields
}

A Struct represents a struct type.

func NewStruct

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

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

func (*Struct) Field

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

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

func (*Struct) NumFields

func (s *Struct) NumFields() int

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

func (*Struct) String

func (t *Struct) String() string

func (*Struct) Tag

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

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

func (*Struct) Underlying

func (t *Struct) Underlying() Type

type Sum

type Sum struct {
	// contains filtered or unexported fields
}

A Sum represents a set of possible types. Sums are currently used to represent type lists of interfaces and thus the underlying types of type parameters; they are not first class types of Go.

func (*Sum) String

func (t *Sum) String() string

func (*Sum) Underlying

func (t *Sum) Underlying() Type

type Tuple

type Tuple struct {
	// contains filtered or unexported fields
}

A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple. Tuples are used as components of signatures and to represent the type of multiple assignments; they are not first class types of Go.

func NewTuple

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

NewTuple returns a new tuple for the given variables.

func (*Tuple) At

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

At returns the i'th variable of tuple t.

func (*Tuple) Len

func (t *Tuple) Len() int

Len returns the number variables of tuple t.

func (*Tuple) String

func (t *Tuple) String() string

func (*Tuple) Underlying

func (t *Tuple) Underlying() Type

type Type

type Type interface {
	// Underlying returns the underlying type of a type
	// w/o following forwarding chains. Only used by
	// client packages (here for backward-compatibility).
	Underlying() Type

	// String returns a string representation of a type.
	String() string
}

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

func Default

func Default(typ Type) Type

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

func Instantiate

func Instantiate(pos syntax.Pos, typ Type, targs []Type) (res Type)

Instantiate instantiates the type typ with the given type arguments. typ must be a *Named or a *Signature type, it must be generic, and its number of type parameters must match the number of provided type arguments. The result is a new, instantiated (not generic) type of the same kind (either a *Named or a *Signature). The type arguments are not checked against the constraints of the type parameters. Any methods attached to a *Named are simply copied; they are not instantiated.

func NewSum

func NewSum(types []Type) Type

NewSum returns a new Sum type consisting of the provided types if there are more than one. If there is exactly one type, it returns that type. If the list of types is empty the result is nil.

type TypeAndValue

type TypeAndValue struct {
	Type  Type
	Value constant.Value
	// contains filtered or unexported fields
}

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

func (TypeAndValue) Addressable

func (tv TypeAndValue) Addressable() bool

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

func (TypeAndValue) Assignable

func (tv TypeAndValue) Assignable() bool

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

func (TypeAndValue) HasOk

func (tv TypeAndValue) HasOk() bool

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

func (TypeAndValue) IsBuiltin

func (tv TypeAndValue) IsBuiltin() bool

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

func (TypeAndValue) IsNil

func (tv TypeAndValue) IsNil() bool

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

func (TypeAndValue) IsType

func (tv TypeAndValue) IsType() bool

IsType reports whether the corresponding expression specifies a type.

func (TypeAndValue) IsValue

func (tv TypeAndValue) IsValue() bool

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

func (TypeAndValue) IsVoid

func (tv TypeAndValue) IsVoid() bool

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

type TypeName

type TypeName struct {
	// contains filtered or unexported fields
}

A TypeName represents a name for a (defined or alias) type.

func NewTypeName

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

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 (*TypeName) Exported

func (obj *TypeName) Exported() bool

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 (*TypeName) Id

func (obj *TypeName) Id() string

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

func (*TypeName) IsAlias

func (obj *TypeName) IsAlias() bool

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

func (*TypeName) Name

func (obj *TypeName) Name() string

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

func (*TypeName) Parent

func (obj *TypeName) Parent() *Scope

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

func (*TypeName) Pkg

func (obj *TypeName) Pkg() *Package

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

func (*TypeName) Pos

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

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

func (*TypeName) String

func (obj *TypeName) String() string

func (*TypeName) Type

func (obj *TypeName) Type() Type

Type returns the object's type.

type TypeParam

type TypeParam struct {
	// contains filtered or unexported fields
}

A TypeParam represents a type parameter type.

func (*TypeParam) Bound

func (t *TypeParam) Bound() *Interface

func (*TypeParam) Obj

func (t *TypeParam) Obj() *TypeName

Obj returns the type name for the type parameter t.

func (*TypeParam) String

func (t *TypeParam) String() string

func (*TypeParam) Underlying

func (t *TypeParam) Underlying() Type

type Var

type Var struct {
	// contains filtered or unexported fields
}

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

func NewField

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

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 NewParam

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

NewParam returns a new variable representing a function parameter.

func NewVar

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

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

func (*Var) Anonymous

func (obj *Var) Anonymous() bool

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

func (*Var) Embedded

func (obj *Var) Embedded() bool

Embedded reports whether the variable is an embedded field.

func (*Var) Exported

func (obj *Var) Exported() bool

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 (*Var) Id

func (obj *Var) Id() string

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

func (*Var) IsField

func (obj *Var) IsField() bool

IsField reports whether the variable is a struct field.

func (*Var) Name

func (obj *Var) Name() string

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

func (*Var) Parent

func (obj *Var) Parent() *Scope

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

func (*Var) Pkg

func (obj *Var) Pkg() *Package

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

func (*Var) Pos

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

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

func (*Var) String

func (obj *Var) String() string

func (*Var) Type

func (obj *Var) Type() Type

Type returns the object's type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL