types

package
v0.0.0-...-bb8a734 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2015 License: BSD-2-Clause, BSD-3-Clause Imports: 15 Imported by: 0

Documentation

Overview

Package types declares the data types and implements the algorithms for type-checking of Go packages. Use Check and Config.Check to invoke the type-checker.

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.Objects, Info.Implicits for the results of name resolution.

Constant folding computes the exact constant value (exact.Value) for every expression (ast.Expr) that is a compile-time constant. Use Info.Values 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 for the results of type evaluation.

Index

Constants

This section is empty.

Variables

View Source
var (
	Universe *Scope
	Unsafe   *Package
)
View Source
var GcCompatibilityMode bool

If GcCompatibilityMode is set, printing of types is modified to match the representation of some types in the gc compiler:

  • byte and rune lose their alias name and simply stand for uint8 and int32 respectively
  • embedded interfaces get flattened (the embedding info is lost, and certain recursive interface types cannot be printed anymore)

This makes it easier to compare packages computed with the type- checker vs packages imported from gc export data.

Caution: This flag affects all uses of WriteType, globally. It is only provided for testing in conjunction with gc-generated data. It may be removed at any time.

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

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

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

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 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 ExprString

func ExprString(x ast.Expr) string

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

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 Implements

func Implements(V Type, T *Interface, static bool) bool

Implements reports whether a value of type V implements T, as follows:

1) For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Informally, this reports whether V is a subtype of T.

2) For interface types V, and if static is not set, V implements T if all methods of T which are also present in V have matching types. Informally, this indicates whether a type assertion x.(T) where x is of type V would be legal (the concrete dynamic type of x may implement T even if V does not statically implement it).

func IsAssignableTo

func IsAssignableTo(V, T Type) bool

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

func IsIdentical

func IsIdentical(x, y Type) bool

IsIdentical reports whether x and y are identical.

func ObjectString

func ObjectString(this *Package, obj Object) string

ObjectString returns the string form of obj. Object and type names are printed package-qualified only if they do not belong to this package.

func SelectionString

func SelectionString(this *Package, s *Selection) string

SelectionString returns the string form of s. Type names are printed package-qualified only if they do not belong to this package.

func TypeString

func TypeString(this *Package, typ Type) string

TypeString returns the string representation of typ. Named types are printed package-qualified if they do not belong to this package.

func WriteExpr

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

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

func WriteType

func WriteType(buf *bytes.Buffer, this *Package, typ Type)

WriteType writes the string representation of typ to buf. Named types are printed package-qualified if they do not belong to this package.

Types

type Array

type Array struct {
	Len  int64
	Elem Type
}

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.

func (*Array) MethodSet

func (t *Array) MethodSet() *MethodSet

func (*Array) String

func (t *Array) String() string

func (*Array) Underlying

func (t *Array) Underlying() Type

type Basic

type Basic struct {
	Kind BasicKind
	Info BasicInfo

	Name string
	// contains filtered or unexported fields
}

A Basic represents a basic type.

func (*Basic) MethodSet

func (t *Basic) MethodSet() *MethodSet

func (*Basic) String

func (t *Basic) String() string

func (*Basic) Underlying

func (t *Basic) Underlying() Type

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

func (obj *Builtin) GetName() string

func (*Builtin) GetPkg

func (obj *Builtin) GetPkg() *Package

func (*Builtin) GetType

func (obj *Builtin) GetType() Type

func (*Builtin) Id

func (obj *Builtin) Id() string

func (*Builtin) IsExported

func (obj *Builtin) IsExported() bool

func (*Builtin) Parent

func (obj *Builtin) Parent() *Scope

func (*Builtin) Pos

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

func (*Builtin) String

func (obj *Builtin) String() string

type Chan

type Chan struct {
	Dir  ChanDir
	Elem Type
}

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

func (t *Chan) MethodSet() *MethodSet

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 the following constants.

type Config

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

	// Packages is used to look up (and thus canonicalize) packages by
	// package path. If Packages is nil, it is set to a new empty map.
	// During type-checking, imported packages are added to the map.
	Packages map[string]*Package

	// If Error != nil, it is called with each error found
	// during type checking; err has dynamic type Error.
	Error func(err error)

	// If Import != nil, it is called for each imported package.
	// Otherwise, DefaultImport is called.
	Import Importer

	// If Sizes != nil, it provides the sizing functions for package unsafe.
	// Otherwise &StdSize{WordSize: 8, MaxAlign: 8} is used instead.
	Sizes Sizes
}

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, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)

Check type-checks a package and returns the resulting package object, the first error if any, and if info != nil, additional type information. The package is marked as complete if no errors occurred, otherwise it is incomplete.

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

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

A Const represents a declared constant.

func NewConst

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

func (*Const) GetName

func (obj *Const) GetName() string

func (*Const) GetPkg

func (obj *Const) GetPkg() *Package

func (*Const) GetType

func (obj *Const) GetType() Type

func (*Const) Id

func (obj *Const) Id() string

func (*Const) IsExported

func (obj *Const) IsExported() bool

func (*Const) Parent

func (obj *Const) Parent() *Scope

func (*Const) Pos

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

func (*Const) String

func (obj *Const) String() string

func (*Const) Val

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

type Error

type Error struct {
	Fset *token.FileSet // file set for interpretation of Pos
	Pos  token.Pos      // error position
	Msg  string         // error message
}

An Error describes a type-checking error; it implements the error interface.

func (Error) Error

func (err Error) Error() string

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

type FieldSet

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

A FieldSet is an ordered set of struct fields; a field is a FieldVal selection. The zero value for a FieldSet is a ready-to-use empty field set.

func NewFieldSet

func NewFieldSet(T Type) *FieldSet

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

func (*FieldSet) At

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

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

func (*FieldSet) Len

func (s *FieldSet) Len() int

Len returns the number of fields in s.

func (*FieldSet) Lookup

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

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

func (*FieldSet) String

func (s *FieldSet) String() string

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

func NewFunc

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

func (*Func) FullName

func (obj *Func) FullName() string

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

func (*Func) GetName

func (obj *Func) GetName() string

func (*Func) GetPkg

func (obj *Func) GetPkg() *Package

func (*Func) GetType

func (obj *Func) GetType() Type

func (*Func) Id

func (obj *Func) Id() string

func (*Func) IsExported

func (obj *Func) IsExported() bool

func (*Func) Parent

func (obj *Func) Parent() *Scope

func (*Func) Pos

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

func (*Func) String

func (obj *Func) String() string

type Importer

type Importer func(map[string]*Package, string) (*Package, error)

An importer resolves import paths to Packages. The imports map records packages already known, indexed by package path. The type-checker will invoke Import with Config.Packages. An importer must determine the canonical package path and check imports to see if it is already present in the map. If so, the Importer can return the map entry. Otherwise, the importer must load the package data for the given path into a new *Package, record it in imports map, and return the package. TODO(gri) Need to be clearer about requirements of completeness.

var DefaultImport Importer

DefaultImport is the default importer invoked if Config.Import == nil. The declaration:

import _ "golang.org/x/tools/go/gcimporter"

in a client of go/types will initialize DefaultImport to gcimporter.Import.

type Info

type Info struct {
	// Types maps expressions to their types. Identifiers on the
	// lhs of declarations are collected in Objects, not Types.
	//
	// For an expression denoting a predeclared built-in function
	// the recorded signature is 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.
	Types map[ast.Expr]Type

	// Values maps constant expressions to their values.
	Values map[ast.Expr]exact.Value

	// Objects maps identifiers to their corresponding objects (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, blank identifiers on the lhs of assignments, or
	// symbolic variables t in t := x.(type) of type switch headers), the
	// corresponding objects are nil.
	Objects 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 struct field or parameter *Var
	//
	Implicits map[ast.Node]Object

	// Selections maps selector expressions to their corresponding selections.
	Selections map[*ast.SelectorExpr]*Selection

	// Scopes maps ast.Nodes to the scopes they define. Note that 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.
	//
	// 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.

type Initializer

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

func (init *Initializer) String() string

type Interface

type Interface struct {
	Methods   []*Func  // ordered list of explicitly declared methods
	Embeddeds []*Named // ordered list of explicitly embedded types
	// contains filtered or unexported fields
}

An Interface represents an interface type.

func NewInterface

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

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

func (*Interface) Embedded

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

func (t *Interface) Empty() bool

Empty returns true if 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) 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.

func (*Interface) MethodSet

func (t *Interface) MethodSet() *MethodSet

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.

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.

func NewLabel

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

func (*Label) GetName

func (obj *Label) GetName() string

func (*Label) GetPkg

func (obj *Label) GetPkg() *Package

func (*Label) GetType

func (obj *Label) GetType() Type

func (*Label) Id

func (obj *Label) Id() string

func (*Label) IsExported

func (obj *Label) IsExported() bool

func (*Label) Parent

func (obj *Label) Parent() *Scope

func (*Label) Pos

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

func (*Label) String

func (obj *Label) String() string

type Map

type Map struct {
	Key, Elem Type
}

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

func (t *Map) MethodSet() *MethodSet

func (*Map) String

func (t *Map) String() string

func (*Map) Underlying

func (t *Map) Underlying() Type

type MethodSet

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. The zero value for a MethodSet is a ready-to-use empty method set.

func NewMethodSet

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.

A MethodSetCache handles repeat queries more efficiently.

func (*MethodSet) At

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

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

func (*MethodSet) Len

func (s *MethodSet) Len() int

Len returns the number of methods in s.

func (*MethodSet) Lookup

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

func (s *MethodSet) String() string

type Named

type Named struct {
	Obj         *TypeName // corresponding declared object
	UnderlyingT Type      // possibly a *Named if !complete; never a *Named if complete

	Methods []*Func // methods declared for this type (not the method set of this type)
	// contains filtered or unexported fields
}

A Named represents a named type.

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. 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. TODO(gri) find a better solution instead of providing this function

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

func (t *Named) MethodSet() *MethodSet

func (*Named) NumMethods

func (t *Named) NumMethods() int

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

func (*Named) SetUnderlying

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

func (t *Named) String() string

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

func (obj *Nil) GetName() string

func (*Nil) GetPkg

func (obj *Nil) GetPkg() *Package

func (*Nil) GetType

func (obj *Nil) GetType() Type

func (*Nil) Id

func (obj *Nil) Id() string

func (*Nil) IsExported

func (obj *Nil) IsExported() bool

func (*Nil) Parent

func (obj *Nil) Parent() *Scope

func (*Nil) Pos

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

func (*Nil) String

func (obj *Nil) String() string

type Object

type Object interface {
	Parent() *Scope   // scope in which this object is declared
	Pos() token.Pos   // position of object identifier in declaration
	GetPkg() *Package // nil for objects in the Universe scope and labels
	GetName() string  // package local object name
	GetType() Type    // object type
	IsExported() 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

func LookupFieldOrMethod(T Type, 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.

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 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 sequence points to an ambiguous entry if it exists, or it is nil.

type Package

type Package struct {
	Path string
	Name string

	Imports []*Package
	// contains filtered or unexported fields
}

A Package describes a Go package.

func Check

func Check(path string, fset *token.FileSet, files []*ast.File) (*Package, error)

Check type-checks a package and returns the resulting complete package object, or a nil package and the first error. The package is specified by a list of *ast.Files and corresponding file set, and the import path the package is identified with. The clean path must not be empty or dot (".").

For more control over type-checking and results, use Config.Check.

func NewPackage

func NewPackage(path, name string, scope *Scope) *Package

NewPackage returns a new Package for the given package path, name, and scope. 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) MarkComplete

func (pkg *Package) MarkComplete()

MarkComplete marks a package as complete.

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

func (pkg *Package) String() string

type PkgName

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

A PkgName represents an imported Go package.

func NewPkgName

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

func (*PkgName) GetName

func (obj *PkgName) GetName() string

func (*PkgName) GetPkg

func (obj *PkgName) GetPkg() *Package

func (*PkgName) GetType

func (obj *PkgName) GetType() Type

func (*PkgName) Id

func (obj *PkgName) Id() string

func (*PkgName) IsExported

func (obj *PkgName) IsExported() bool

func (*PkgName) Parent

func (obj *PkgName) Parent() *Scope

func (*PkgName) Pos

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

func (*PkgName) String

func (obj *PkgName) String() string

type Pointer

type Pointer struct {
	Elem Type // element type
	// contains filtered or unexported fields
}

A Pointer represents a pointer type.

func NewPointer

func NewPointer(elem Type) *Pointer

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

func (*Pointer) MethodSet

func (t *Pointer) MethodSet() *MethodSet

func (*Pointer) String

func (t *Pointer) String() string

func (*Pointer) Underlying

func (t *Pointer) Underlying() Type

type Scope

type Scope struct {
	Objects map[string]Object
	// 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.

func NewScope

func NewScope(parent *Scope) *Scope

NewScope returns a new, empty scope contained in the given parent scope, if any.

func (*Scope) Child

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

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

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 scope to s, and returns nil. Objects with blank "_" names are not inserted, but have their parent field set to s.

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) 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 object. If no such scope exists, the result is nil.

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) 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 {
	Kind     SelectionKind
	Recv     Type   // type of x, nil if kind == PackageObj
	Obj      Object // object denoted by x.f
	Index    []int  // path from x to x.f, nil if kind == PackageObj
	Indirect bool   // set if there was any pointer indirection on the path, false if kind == PackageObj
}

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
math.Pi     PackageObj    nil     Pi     untyped numeric    nil       false

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.

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
	PackageObj                      // x.f is a qualified identifier
)

type Signature

type Signature struct {
	Recv       *Var   // nil if not a method
	Params     []*Var // (incoming) parameters from left to right; or nil
	Results    []*Var // (outgoing) results from left to right; or nil
	IsVariadic bool   // true if the last parameter's type is of the form ...T
	// contains filtered or unexported fields
}

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

func NewSignature

func NewSignature(scope *Scope, recv *Var, params, results []*Var, isVariadic bool) *Signature

NewSignature returns a new function type for the given receiver, parameters, and results, either of which may be nil. If isVariadic 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) MethodSet

func (t *Signature) MethodSet() *MethodSet

func (*Signature) String

func (t *Signature) String() string

func (*Signature) Underlying

func (t *Signature) Underlying() Type

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.

type Slice

type Slice struct {
	Elem Type
}

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

func (t *Slice) MethodSet() *MethodSet

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, functions, and interfaces is 2*WordSize.
  • The size of slices is 3*WordSize.
  • 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 {
	Fields []*Var
	// 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) MethodSet

func (t *Struct) MethodSet() *MethodSet

func (*Struct) NumFields

func (s *Struct) NumFields() int

NumFields returns the number of fields in the struct (including blank and anonymous 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 Tuple

type Tuple []*Var

A Tuple represents an ordered list of variables; a nil Tuple is a valid (empty) tuple. Tuples 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) MethodSet

func (t *Tuple) MethodSet() *MethodSet

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.
	Underlying() Type

	// MethodSet returns the method set of a type.
	MethodSet() *MethodSet

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

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

func Eval

func Eval(str string, pkg *Package, scope *Scope) (typ Type, val exact.Value, err error)

Eval returns the type and, if constant, the value for the expression or type literal string str evaluated in scope. If the expression contains function literals, the function bodies are ignored (though they must be syntactically correct).

If pkg == nil, the Universe scope is used and the provided scope is ignored. Otherwise, the scope must belong to the package (either the package scope, or nested within the package scope).

An error is returned if the scope is incorrect, the string has syntax errors, or if it cannot be evaluated in the scope. Position info for objects in the result type is undefined.

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 EvalNode

func EvalNode(fset *token.FileSet, node ast.Expr, pkg *Package, scope *Scope) (typ Type, val exact.Value, err error)

EvalNode is like Eval but instead of string it accepts an expression node and respective file set.

An error is returned if the scope is incorrect if the node cannot be evaluated in the scope.

func New

func New(str string) Type

New is a convenience function to create a new type from a given expression or type literal string evaluated in Universe scope. New(str) is shorthand for Eval(str, nil, nil), but only returns the type result, and panics in case of an error. Position info for objects in the result type is undefined.

type TypeName

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

A TypeName represents a declared type.

func NewTypeName

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

func (*TypeName) GetName

func (obj *TypeName) GetName() string

func (*TypeName) GetPkg

func (obj *TypeName) GetPkg() *Package

func (*TypeName) GetType

func (obj *TypeName) GetType() Type

func (*TypeName) Id

func (obj *TypeName) Id() string

func (*TypeName) IsExported

func (obj *TypeName) IsExported() bool

func (*TypeName) Parent

func (obj *TypeName) Parent() *Scope

func (*TypeName) Pos

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

func (*TypeName) String

func (obj *TypeName) String() string

type Var

type Var struct {
	Anonymous bool // if set, the variable is an anonymous struct field, and name is the type name

	IsField bool // var is struct field
	// contains filtered or unexported fields
}

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

func NewField

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

func NewParam

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

func NewVar

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

func (*Var) GetName

func (obj *Var) GetName() string

func (*Var) GetPkg

func (obj *Var) GetPkg() *Package

func (*Var) GetType

func (obj *Var) GetType() Type

func (*Var) Id

func (obj *Var) Id() string

func (*Var) IsExported

func (obj *Var) IsExported() bool

func (*Var) Parent

func (obj *Var) Parent() *Scope

func (*Var) Pos

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

func (*Var) String

func (obj *Var) String() string

Directories

Path Synopsis
Package typemap defines type M, a hash-table-based mapping from types (go/types.Type) to arbitrary values, and a hash function on types.
Package typemap defines type M, a hash-table-based mapping from types (go/types.Type) to arbitrary values, and a hash function on types.

Jump to

Keyboard shortcuts

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