Go 语言

Go 语言教程 Go 语言环境安装 Go 语言结构 Go 语言基础语法 Go 语言数据类型 Go 语言变量 Go 语言常量 Go 语言运算符 Go 语言条件语句 Go 语言 if 语句 Go 语言 if...else 语句 Go 语言 if 语句嵌套 Go 语言 switch 语句 Go 语言 select 语句 Go 语言循环语句 Go 语言 for 循环 Go 语言循环嵌套 Go 语言 break 语句 Go 语言 continue 语句 Go 语言 goto 语句 Go 语言函数 Go 语言函数值传递值 Go 语言函数引用传递值 Go 语言函数作为值 Go 语言函数闭包 Go 语言函数方法 Go 语言变量作用域 Go 语言数组 Go 语言多维数组 Go 语言向函数传递数组 Go 语言指针 Go 语言指针数组 Go 语言指向指针的指针 Go 语言指针作为函数参数 Go 语言结构体 Go 语言切片(Slice) Go 语言范围(Range) Go 语言Map(集合) Go 语言递归函数 Go 语言类型转换 Go 语言接口 Go 错误处理 Go 语言开发工具Go 语言标准库

Go 语言标准库


package types

import "go/types"

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 (ast.Ident) 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 (ast.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 (ast.Expr) and checks for compliance with the language specification. Use Info.Types[expr].Type for the results of type inference.

For a tutorial, see https://github.com/golang/go/blob/master/s/types-tutorial.

Examples

Package Files

api.go assignments.go builtins.go call.go check.go conversions.go decl.go errors.go eval.go expr.go exprstring.go initorder.go labels.go lookup.go methodset.go object.go objset.go operand.go ordering.go package.go predicates.go resolver.go return.go scope.go selection.go sizes.go stmt.go type.go typestring.go typexpr.go universe.go

Variables

var (
    Universe *Scope
    Unsafe   *Package
)
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"},
}

func AssertableTo Uses

func AssertableTo(V *Interface, T Type) bool

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

func AssignableTo Uses

func AssignableTo(V, T Type) bool

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

func Comparable Uses

func Comparable(T Type) bool

Comparable reports whether values of type T are comparable.

func ConvertibleTo Uses

func ConvertibleTo(V, T Type) bool

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

func DefPredeclaredTestFuncs Uses

func DefPredeclaredTestFuncs()

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

func ExprString Uses

func ExprString(x ast.Expr) string

ExprString returns the (possibly simplified) string representation for x.

func Id Uses

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 Uses

func Identical(x, y Type) bool

Identical reports whether x and y are identical.

func IdenticalIgnoreTags Uses

func IdenticalIgnoreTags(x, y Type) bool

IdenticalIgnoreTags reports whether x and y are identical if tags are ignored.

func Implements Uses

func Implements(V Type, T *Interface) bool

Implements reports whether type V implements interface T.

func IsInterface Uses

func IsInterface(typ Type) bool

IsInterface reports whether typ is an interface type.

func ObjectString Uses

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 Uses

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 Uses

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 WriteExpr Uses

func WriteExpr(buf *bytes.Buffer, x ast.Expr)

WriteExpr writes the (possibly simplified) string representation for x to buf.

func WriteSignature Uses

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 Uses

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.

type Array Uses

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

An Array represents an array type.

func NewArray Uses

func NewArray(elem Type, len int64) *Array

NewArray returns a new array type for the given element type and length.

func (*Array) Elem Uses

func (a *Array) Elem() Type

Elem returns element type of array a.

func (*Array) Len Uses

func (a *Array) Len() int64

Len returns the length of array a.

func (*Array) String Uses

func (t *Array) String() string

func (*Array) Underlying Uses

func (t *Array) Underlying() Type

type Basic Uses

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

A Basic represents a basic type.

func (*Basic) Info Uses

func (b *Basic) Info() BasicInfo

Info returns information about properties of basic type b.

func (*Basic) Kind Uses

func (b *Basic) Kind() BasicKind

Kind returns the kind of basic type b.

func (*Basic) Name Uses

func (b *Basic) Name() string

Name returns the name of basic type b.

func (*Basic) String Uses

func (t *Basic) String() string

func (*Basic) Underlying Uses

func (t *Basic) Underlying() Type

type BasicInfo Uses

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 Uses

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 Uses

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 Uses

func (obj *Builtin) Exported() bool

func (*Builtin) Id Uses

func (obj *Builtin) Id() string

func (*Builtin) Name Uses

func (obj *Builtin) Name() string

func (*Builtin) Parent Uses

func (obj *Builtin) Parent() *Scope

func (*Builtin) Pkg Uses

func (obj *Builtin) Pkg() *Package

func (*Builtin) Pos Uses

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

func (*Builtin) String Uses

func (obj *Builtin) String() string

func (*Builtin) Type Uses

func (obj *Builtin) Type() Type

type Chan Uses

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

A Chan represents a channel type.

func NewChan Uses

func NewChan(dir ChanDir, elem Type) *Chan

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

func (*Chan) Dir Uses

func (c *Chan) Dir() ChanDir

Dir returns the direction of channel c.

func (*Chan) Elem Uses

func (c *Chan) Elem() Type

Elem returns the element type of channel c.

func (*Chan) String Uses

func (t *Chan) String() string

func (*Chan) Underlying Uses

func (t *Chan) Underlying() Type

type ChanDir Uses

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 Uses

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 Uses

func NewChecker(conf *Config, fset *token.FileSet, 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 Uses

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

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

type Config Uses

type Config struct {
    // 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-up errors.
    //          Do not use casually!
    FakeImportC 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 &StdSizes{WordSize: 8, MaxAlign: 8} is used instead.
    Sizes Sizes

    // If DisableUnusedImportCheck is set, packages are not checked
    // for unused imports.
    DisableUnusedImportCheck bool
}

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

func (*Config) Check Uses

func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.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 *ast.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 Uses

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

A Const represents a declared constant.

func NewConst Uses

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

func (*Const) Exported Uses

func (obj *Const) Exported() bool

func (*Const) Id Uses

func (obj *Const) Id() string

func (*Const) Name Uses

func (obj *Const) Name() string

func (*Const) Parent Uses

func (obj *Const) Parent() *Scope

func (*Const) Pkg Uses

func (obj *Const) Pkg() *Package

func (*Const) Pos Uses

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

func (*Const) String Uses

func (obj *Const) String() string

func (*Const) Type Uses

func (obj *Const) Type() Type

func (*Const) Val Uses

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

type Error Uses

type Error struct {
    Fset *token.FileSet // file set for interpretation of Pos
    Pos  token.Pos      // error position
    Msg  string         // error message
    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 Uses

func (err Error) Error() string

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

type Func Uses

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 Uses

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 Uses

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

func (*Func) Exported Uses

func (obj *Func) Exported() bool

func (*Func) FullName Uses

func (obj *Func) FullName() string

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

func (*Func) Id Uses

func (obj *Func) Id() string

func (*Func) Name Uses

func (obj *Func) Name() string

func (*Func) Parent Uses

func (obj *Func) Parent() *Scope

func (*Func) Pkg Uses

func (obj *Func) Pkg() *Package

func (*Func) Pos Uses

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

func (*Func) Scope Uses

func (obj *Func) Scope() *Scope

func (*Func) String Uses

func (obj *Func) String() string

func (*Func) Type Uses

func (obj *Func) Type() Type

type ImportMode Uses

type ImportMode int

ImportMode is reserved for future use.

type Importer Uses

type Importer interface {
    // Import returns the imported package for the given import
    // path, or an error if the package couldn't be imported.
    // Two calls to Import with the same path return the same
    // package.
    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://github.com/golang/go/blob/master/s/go15vendor. If possible, external implementations should implement ImporterFrom.

type ImporterFrom Uses

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 the package in srcDir, or an error
    // if the package couldn't be imported. The mode value must
    // be 0; it is reserved for future use.
    // Two calls to ImportFrom with the same path and srcDir return
    // the same package.
    ImportFrom(path, srcDir string, mode ImportMode) (*Package, error)
}

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

type Info Uses

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[ast.Expr]TypeAndValue

    // 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 anonymous field, Defs returns the field *Var it defines.
    //
    // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
    Defs map[*ast.Ident]Object

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

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

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

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

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

Code:

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

type S string

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

func fib(x int) int {
	if x < 2 {
		return x
	}
	return fib(x-1) - fib(x-2)
}`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "fib.go", input, 0)
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 := types.Info{
    Types: make(map[ast.Expr]types.TypeAndValue),
    Defs:  make(map[*ast.Ident]types.Object),
    Uses:  make(map[*ast.Ident]types.Object),
}
var conf types.Config
pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)
if err != nil {
    log.Fatal(err)
}

// 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[types.Object][]string)
for id, obj := range info.Uses {
    posn := fset.Position(id.Pos())
    lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
    usesByObj[obj] = append(usesByObj[obj], lineCol)
}
var items []string
for obj, uses := range usesByObj {
    sort.Strings(uses)
    item := fmt.Sprintf("%s:\n  defined at %s\n  used at %s",
        types.ObjectString(obj, types.RelativeTo(pkg)),
        fset.Position(obj.Pos()),
        strings.Join(uses, ", "))
    items = append(items, item)
}
sort.Strings(items) // sort by line:col, in effect
fmt.Println(strings.Join(items, "\n"))
fmt.Println()

fmt.Println("Types and Values of each expression:")
items = nil
for expr, tv := range info.Types {
    var buf bytes.Buffer
    posn := fset.Position(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.Column, exprString(fset, expr),
        mode(tv), tvstr)
    items = append(items, buf.String())
}
sort.Strings(items)
fmt.Println(strings.Join(items, "\n"))

Output:

InitOrder: [c = "hello" b = S(c) a = len(b)]

Defs and Uses of each named object:
builtin len:
  defined at -
  used at 6:15
func fib(x int) int:
  defined at fib.go:8:6
  used at 12:20, 12:9
type S string:
  defined at fib.go:4:6
  used at 6:23
type int int:
  defined at -
  used at 8:12, 8:17
type string string:
  defined at -
  used at 4:8
var b S:
  defined at fib.go:6:8
  used at 6:19
var c string:
  defined at fib.go:6:11
  used at 6:25
var x int:
  defined at fib.go:8:10
  used at 10:10, 12:13, 12:24, 9:5

Types and Values of each expression:
 4: 8 | string              | type    : string
 6:15 | len                 | builtin : func(string) int
 6:15 | len(b)              | value   : int
 6:19 | b                   | var     : fib.S
 6:23 | S                   | type    : fib.S
 6:23 | S(c)                | value   : fib.S
 6:25 | c                   | var     : string
 6:29 | "hello"             | value   : string = "hello"
 8:12 | int                 | type    : int
 8:17 | int                 | type    : int
 9: 5 | x                   | var     : int
 9: 5 | x < 2               | value   : untyped bool
 9: 9 | 2                   | value   : int = 2
10:10 | x                   | var     : int
12: 9 | fib                 | value   : func(x int) int
12: 9 | fib(x - 1)          | value   : int
12: 9 | fib(x-1) - fib(x-2) | value   : int
12:13 | x                   | var     : int
12:13 | x - 1               | value   : int
12:15 | 1                   | value   : int = 1
12:20 | fib                 | value   : func(x int) int
12:20 | fib(x - 2)          | value   : int
12:24 | x                   | var     : int
12:24 | x - 2               | value   : int
12:26 | 2                   | value   : int = 2

func (*Info) ObjectOf Uses

func (info *Info) ObjectOf(id *ast.Ident) Object

ObjectOf returns the object denoted by the specified id, or nil if not found.

If id is an anonymous struct field, ObjectOf returns the field (*Var) it uses, not the type (*TypeName) it defines.

Precondition: the Uses and Defs maps are populated.

func (*Info) TypeOf Uses

func (info *Info) TypeOf(e ast.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 Uses

type Initializer struct {
    Lhs []*Var // var Lhs = Rhs
    Rhs ast.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 Uses

func (init *Initializer) String() string

type Interface Uses

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

An Interface represents an interface type.

func NewInterface Uses

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

NewInterface returns a new interface for the given methods and embedded types.

func (*Interface) Complete Uses

func (t *Interface) Complete() *Interface

Complete computes the interface's method set. It must be called by users of 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. Complete returns the receiver.

func (*Interface) Embedded Uses

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

Embedded returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds(). The types are ordered by the corresponding TypeName's unique Id.

func (*Interface) Empty Uses

func (t *Interface) Empty() bool

Empty returns true if t is the empty interface.

func (*Interface) ExplicitMethod Uses

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) Method Uses

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.

func (*Interface) NumEmbeddeds Uses

func (t *Interface) NumEmbeddeds() int

NumEmbeddeds returns the number of embedded types in interface t.

func (*Interface) NumExplicitMethods Uses

func (t *Interface) NumExplicitMethods() int

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

func (*Interface) NumMethods Uses

func (t *Interface) NumMethods() int

NumMethods returns the total number of methods of interface t.

func (*Interface) String Uses

func (t *Interface) String() string

func (*Interface) Underlying Uses

func (t *Interface) Underlying() Type

type Label Uses

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

A Label represents a declared label.

func NewLabel Uses

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

func (*Label) Exported Uses

func (obj *Label) Exported() bool

func (*Label) Id Uses

func (obj *Label) Id() string

func (*Label) Name Uses

func (obj *Label) Name() string

func (*Label) Parent Uses

func (obj *Label) Parent() *Scope

func (*Label) Pkg Uses

func (obj *Label) Pkg() *Package

func (*Label) Pos Uses

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

func (*Label) String Uses

func (obj *Label) String() string

func (*Label) Type Uses

func (obj *Label) Type() Type

type Map Uses

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

A Map represents a map type.

func NewMap Uses

func NewMap(key, elem Type) *Map

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

func (*Map) Elem Uses

func (m *Map) Elem() Type

Elem returns the element type of map m.

func (*Map) Key Uses

func (m *Map) Key() Type

Key returns the key type of map m.

func (*Map) String Uses

func (t *Map) String() string

func (*Map) Underlying Uses

func (t *Map) Underlying() Type

type MethodSet Uses

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

A MethodSet is an ordered set of concrete or abstract (interface) methods; a method is a MethodVal selection, and they are ordered by ascending m.Obj().Id(). The zero value for a MethodSet is a ready-to-use empty method set.

ExampleMethodSet prints the method sets of various types.

Code:play 

// Parse a single source file.
const input = `
package temperature
import "fmt"
type Celsius float64
func (c Celsius) String() string  { return fmt.Sprintf("%g°C", c) }
func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "celsius.go", input, 0)
if err != nil {
    log.Fatal(err)
}

// Type-check a package consisting of this file.
// Type information for the imported packages
// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
if err != nil {
    log.Fatal(err)
}

// Print the method sets of Celsius and *Celsius.
celsius := pkg.Scope().Lookup("Celsius").Type()
for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
    fmt.Printf("Method set of %s:\n", t)
    mset := types.NewMethodSet(t)
    for i := 0; i < mset.Len(); i++ {
        fmt.Println(mset.At(i))
    }
    fmt.Println()
}

Output:

Method set of temperature.Celsius:
method (temperature.Celsius) String() string

Method set of *temperature.Celsius:
method (*temperature.Celsius) SetF(f float64)
method (*temperature.Celsius) String() string

func NewMethodSet Uses

func NewMethodSet(T Type) *MethodSet

NewMethodSet returns the method set for the given type T. It always returns a non-nil method set, even if it is empty.

func (*MethodSet) At Uses

func (s *MethodSet) At(i int) *Selection

At returns the i'th method in s for 0 <= i < s.Len().

func (*MethodSet) Len Uses

func (s *MethodSet) Len() int

Len returns the number of methods in s.

func (*MethodSet) Lookup Uses

func (s *MethodSet) Lookup(pkg *Package, name string) *Selection

Lookup returns the method with matching package and name, or nil if not found.

func (*MethodSet) String Uses

func (s *MethodSet) String() string

type Named Uses

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

A Named represents a named type.

func NewNamed Uses

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. The underlying type must not be a *Named.

func (*Named) AddMethod Uses

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

AddMethod adds method m unless it is already in the method list. TODO(gri) find a better solution instead of providing this function

func (*Named) Method Uses

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 Uses

func (t *Named) NumMethods() int

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

func (*Named) Obj Uses

func (t *Named) Obj() *TypeName

TypeName returns the type name for the named type t.

func (*Named) SetUnderlying Uses

func (t *Named) SetUnderlying(underlying Type)

SetUnderlying sets the underlying type and marks t as complete. TODO(gri) determine if there's a better solution rather than providing this function

func (*Named) String Uses

func (t *Named) String() string

func (*Named) Underlying Uses

func (t *Named) Underlying() Type

type Nil Uses

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

Nil represents the predeclared value nil.

func (*Nil) Exported Uses

func (obj *Nil) Exported() bool

func (*Nil) Id Uses

func (obj *Nil) Id() string

func (*Nil) Name Uses

func (obj *Nil) Name() string

func (*Nil) Parent Uses

func (obj *Nil) Parent() *Scope

func (*Nil) Pkg Uses

func (obj *Nil) Pkg() *Package

func (*Nil) Pos Uses

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

func (*Nil) String Uses

func (obj *Nil) String() string

func (*Nil) Type Uses

func (obj *Nil) Type() Type

type Object Uses

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

    // 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 Uses

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 anonymous 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 Uses

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

A Package describes a Go package.

func NewPackage Uses

func NewPackage(path, name string) *Package

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

func (*Package) Complete Uses

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 Uses

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

Imports returns the list of packages directly imported by pkg; the list is in source order. Package unsafe is excluded.

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 Uses

func (pkg *Package) MarkComplete()

MarkComplete marks a package as complete.

func (*Package) Name Uses

func (pkg *Package) Name() string

Name returns the package name.

func (*Package) Path Uses

func (pkg *Package) Path() string

Path returns the package path.

func (*Package) Scope Uses

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 Uses

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 Uses

func (pkg *Package) SetName(name string)

SetName sets the package name.

func (*Package) String Uses

func (pkg *Package) String() string

type PkgName Uses

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

A PkgName represents an imported Go package.

func NewPkgName Uses

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

func (*PkgName) Exported Uses

func (obj *PkgName) Exported() bool

func (*PkgName) Id Uses

func (obj *PkgName) Id() string

func (*PkgName) Imported Uses

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 Uses

func (obj *PkgName) Name() string

func (*PkgName) Parent Uses

func (obj *PkgName) Parent() *Scope

func (*PkgName) Pkg Uses

func (obj *PkgName) Pkg() *Package

func (*PkgName) Pos Uses

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

func (*PkgName) String Uses

func (obj *PkgName) String() string

func (*PkgName) Type Uses

func (obj *PkgName) Type() Type

type Pointer Uses

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

A Pointer represents a pointer type.

func NewPointer Uses

func NewPointer(elem Type) *Pointer

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

func (*Pointer) Elem Uses

func (p *Pointer) Elem() Type

Elem returns the element type for the given pointer p.

func (*Pointer) String Uses

func (t *Pointer) String() string

func (*Pointer) Underlying Uses

func (t *Pointer) Underlying() Type

type Qualifier Uses

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 Uses

func RelativeTo(pkg *Package) Qualifier

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

type Scope Uses

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.

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

Code:play 

// Parse the source files for a package.
fset := token.NewFileSet()
var files []*ast.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
`},
} {
    f, err := parser.ParseFile(fset, file.name, file.input, 0)
    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 := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("temperature", fset, files, nil)
if err != nil {
    log.Fatal(err)
}

// Print the tree of scopes.
// For determinism, we redact addresses.
var buf 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.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
.  .  }.  }}

func NewScope Uses

func NewScope(parent *Scope, pos, end token.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 Uses

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

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

func (*Scope) Contains Uses

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

Contains returns true if 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 Uses

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

func (*Scope) Innermost Uses

func (s *Scope) Innermost(pos token.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 Uses

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 Uses

func (s *Scope) Len() int

Len() returns the number of scope elements.

func (*Scope) Lookup Uses

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 Uses

func (s *Scope) LookupParent(name string, pos token.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, below). This can only happen for dot-imported objects whose scope is the scope of the package that exported them.

func (*Scope) Names Uses

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

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

func (*Scope) NumChildren Uses

func (s *Scope) NumChildren() int

NumChildren() returns the number of scopes nested in s.

func (*Scope) Parent Uses

func (s *Scope) Parent() *Scope

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

func (*Scope) Pos Uses

func (s *Scope) Pos() token.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) String Uses

func (s *Scope) String() string

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

func (*Scope) WriteTo Uses

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 Uses

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 (e *T) m()    {1, 0}    true
T.m         MethodExpr    T       m      func m(_ T)        {1, 0}    false

func (*Selection) Index Uses

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 Uses

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 Uses

func (s *Selection) Kind() SelectionKind

Kind returns the selection kind.

func (*Selection) Obj Uses

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 Uses

func (s *Selection) Recv() Type

Recv returns the type of x in x.f.

func (*Selection) String Uses

func (s *Selection) String() string

func (*Selection) Type Uses

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 Uses

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 Uses

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

A Signature represents a (non-builtin) function or method type.

func NewSignature Uses

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 Uses

func (s *Signature) Params() *Tuple

Params returns the parameters of signature s, or nil.

func (*Signature) Recv Uses

func (s *Signature) Recv() *Var

Recv returns the receiver of signature s (if a method), or nil if a function.

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 Uses

func (s *Signature) Results() *Tuple

Results returns the results of signature s, or nil.

func (*Signature) String Uses

func (t *Signature) String() string

func (*Signature) Underlying Uses

func (t *Signature) Underlying() Type

func (*Signature) Variadic Uses

func (s *Signature) Variadic() bool

Variadic reports whether the signature s is variadic.

type Sizes Uses

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.

type Slice Uses

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

A Slice represents a slice type.

func NewSlice Uses

func NewSlice(elem Type) *Slice

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

func (*Slice) Elem Uses

func (s *Slice) Elem() Type

Elem returns the element type of slice s.

func (*Slice) String Uses

func (t *Slice) String() string

func (*Slice) Underlying Uses

func (t *Slice) Underlying() Type

type StdSizes Uses

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 Uses

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

func (*StdSizes) Offsetsof Uses

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

func (*StdSizes) Sizeof Uses

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

type Struct Uses

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

A Struct represents a struct type.

func NewStruct Uses

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 Uses

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

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

func (*Struct) NumFields Uses

func (s *Struct) NumFields() int

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

func (*Struct) String Uses

func (t *Struct) String() string

func (*Struct) Tag Uses

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

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

func (*Struct) Underlying Uses

func (t *Struct) Underlying() Type

type Tuple Uses

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 Uses

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

NewTuple returns a new tuple for the given variables.

func (*Tuple) At Uses

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

At returns the i'th variable of tuple t.

func (*Tuple) Len Uses

func (t *Tuple) Len() int

Len returns the number variables of tuple t.

func (*Tuple) String Uses

func (t *Tuple) String() string

func (*Tuple) Underlying Uses

func (t *Tuple) Underlying() Type

type Type Uses

type Type interface {
    // Underlying returns the underlying type of a type.
    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 Uses

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.

type TypeAndValue Uses

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 Eval Uses

func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (TypeAndValue, error)

Eval returns the type and, if constant, the value for the expression expr, evaluated at position pos of package pkg, which must have been derived from type-checking an AST with complete position information relative to the provided file set.

If the expression contains function literals, their bodies are ignored (i.e., the bodies are not type-checked).

If pkg == nil, the Universe scope is used and the provided position pos is ignored. If pkg != nil, and pos is invalid, the package scope is used. Otherwise, pos must belong to the package.

An error is returned if pos is not within the package or if the node cannot be evaluated.

Note: Eval should not be used instead of running Check to compute types and values, but in addition to Check. Eval will re-evaluate its argument each time, and it also does not know about the context in which an expression is used (e.g., an assignment). Thus, top- level untyped constants will return an untyped type rather then the respective context-specific type.

func (TypeAndValue) Addressable Uses

func (tv TypeAndValue) Addressable() bool

Addressable reports whether the corresponding expression is addressable (https://github.com/golang/go/blob/master/ref/spec#Address_operators).

func (TypeAndValue) Assignable Uses

func (tv TypeAndValue) Assignable() bool

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

func (TypeAndValue) HasOk Uses

func (tv TypeAndValue) HasOk() bool

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

func (TypeAndValue) IsBuiltin Uses

func (tv TypeAndValue) IsBuiltin() bool

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

func (TypeAndValue) IsNil Uses

func (tv TypeAndValue) IsNil() bool

IsNil reports whether the corresponding expression denotes the predeclared value nil.

func (TypeAndValue) IsType Uses

func (tv TypeAndValue) IsType() bool

IsType reports whether the corresponding expression specifies a type.

func (TypeAndValue) IsValue Uses

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 Uses

func (tv TypeAndValue) IsVoid() bool

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

type TypeName Uses

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

A TypeName represents a declared type.

func NewTypeName Uses

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

func (*TypeName) Exported Uses

func (obj *TypeName) Exported() bool

func (*TypeName) Id Uses

func (obj *TypeName) Id() string

func (*TypeName) Name Uses

func (obj *TypeName) Name() string

func (*TypeName) Parent Uses

func (obj *TypeName) Parent() *Scope

func (*TypeName) Pkg Uses

func (obj *TypeName) Pkg() *Package

func (*TypeName) Pos Uses

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

func (*TypeName) String Uses

func (obj *TypeName) String() string

func (*TypeName) Type Uses

func (obj *TypeName) Type() Type

type Var Uses

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

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

func NewField Uses

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

func NewParam Uses

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

func NewVar Uses

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

func (*Var) Anonymous Uses

func (obj *Var) Anonymous() bool

func (*Var) Exported Uses

func (obj *Var) Exported() bool

func (*Var) Id Uses

func (obj *Var) Id() string

func (*Var) IsField Uses

func (obj *Var) IsField() bool

func (*Var) Name Uses

func (obj *Var) Name() string

func (*Var) Parent Uses

func (obj *Var) Parent() *Scope

func (*Var) Pkg Uses

func (obj *Var) Pkg() *Package

func (*Var) Pos Uses

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

func (*Var) String Uses

func (obj *Var) String() string

func (*Var) Type Uses

func (obj *Var) Type() Type