gnolang

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2024 License: UNKNOWN not legal advice Imports: 0 Imported by: 0

README

Gnolang

TODO: dedicated README

Documentation

Overview

SPDX-License-Identifier: GNO License Version 1.0

Index

Constants

View Source
const (
	RealmPathPrefix   = "gno.land/r/"
	PackagePathPrefix = "gno.land/p/"
)

RealmPathPrefix is the prefix used to identify pkgpaths which are meant to be realms and as such to have their state persisted. This is used by IsRealmPath.

View Source
const (
	DGTS = `(?:[0-9]+)`
	HExX = `(?:0[xX][0-9a-fA-F]+)`
	PSCI = `(?:[eE]+?[0-9]+)`
	NSCI = `(?:[eE]-[1-9][0-9]+)`
	ASCI = `(?:[eE][-+]?[0-9]+)`
)
View Source
const (
	/* Control operators */
	OpCPUInvalid             = 1
	OpCPUHalt                = 1
	OpCPUNoop                = 1
	OpCPUExec                = 1
	OpCPUPrecall             = 1
	OpCPUCall                = 1
	OpCPUCallNativeBody      = 1
	OpCPUReturn              = 1
	OpCPUReturnFromBlock     = 1
	OpCPUReturnToBlock       = 1
	OpCPUDefer               = 1
	OpCPUCallDeferNativeBody = 1
	OpCPUGo                  = 1
	OpCPUSelect              = 1
	OpCPUSwitchClause        = 1
	OpCPUSwitchClauseCase    = 1
	OpCPUTypeSwitch          = 1
	OpCPUIfCond              = 1
	OpCPUPopValue            = 1
	OpCPUPopResults          = 1
	OpCPUPopBlock            = 1
	OpCPUPopFrameAndReset    = 1
	OpCPUPanic1              = 1
	OpCPUPanic2              = 1

	/* Unary & binary operators */
	OpCPUUpos  = 1
	OpCPUUneg  = 1
	OpCPUUnot  = 1
	OpCPUUxor  = 1
	OpCPUUrecv = 1
	OpCPULor   = 1
	OpCPULand  = 1
	OpCPUEql   = 1
	OpCPUNeq   = 1
	OpCPULss   = 1
	OpCPULeq   = 1
	OpCPUGtr   = 1
	OpCPUGeq   = 1
	OpCPUAdd   = 1
	OpCPUSub   = 1
	OpCPUBor   = 1
	OpCPUXor   = 1
	OpCPUMul   = 1
	OpCPUQuo   = 1
	OpCPURem   = 1
	OpCPUShl   = 1
	OpCPUShr   = 1
	OpCPUBand  = 1
	OpCPUBandn = 1

	/* Other expression operators */
	OpCPUEval         = 1
	OpCPUBinary1      = 1
	OpCPUIndex1       = 1
	OpCPUIndex2       = 1
	OpCPUSelector     = 1
	OpCPUSlice        = 1
	OpCPUStar         = 1
	OpCPURef          = 1
	OpCPUTypeAssert1  = 1
	OpCPUTypeAssert2  = 1
	OpCPUStaticTypeOf = 1
	OpCPUCompositeLit = 1
	OpCPUArrayLit     = 1
	OpCPUSliceLit     = 1
	OpCPUSliceLit2    = 1
	OpCPUMapLit       = 1
	OpCPUStructLit    = 1
	OpCPUFuncLit      = 1
	OpCPUConvert      = 1

	/* Native operators */
	OpCPUArrayLitGoNative  = 1
	OpCPUSliceLitGoNative  = 1
	OpCPUStructLitGoNative = 1
	OpCPUCallGoNative      = 1

	/* Type operators */
	OpCPUFieldType       = 1
	OpCPUArrayType       = 1
	OpCPUSliceType       = 1
	OpCPUPointerType     = 1
	OpCPUInterfaceType   = 1
	OpCPUChanType        = 1
	OpCPUFuncType        = 1
	OpCPUMapType         = 1
	OpCPUStructType      = 1
	OpCPUMaybeNativeType = 1

	/* Statement operators */
	OpCPUAssign      = 1
	OpCPUAddAssign   = 1
	OpCPUSubAssign   = 1
	OpCPUMulAssign   = 1
	OpCPUQuoAssign   = 1
	OpCPURemAssign   = 1
	OpCPUBandAssign  = 1
	OpCPUBandnAssign = 1
	OpCPUBorAssign   = 1
	OpCPUXorAssign   = 1
	OpCPUShlAssign   = 1
	OpCPUShrAssign   = 1
	OpCPUDefine      = 1
	OpCPUInc         = 1
	OpCPUDec         = 1

	/* Decl operators */
	OpCPUValueDecl = 1
	OpCPUTypeDecl  = 1

	/* Loop (sticky) operators (>= 0xD0) */
	OpCPUSticky            = 1
	OpCPUBody              = 1
	OpCPUForLoop           = 1
	OpCPURangeIter         = 1
	OpCPURangeIterString   = 1
	OpCPURangeIterMap      = 1
	OpCPURangeIterArrayPtr = 1
	OpCPUReturnCallDefers  = 1
)
View Source
const (
	IsBoolean category = 1 << iota
	IsInteger
	IsFloat
	IsString
	IsBigInt
	IsBigDec

	IsNumeric = IsInteger | IsFloat | IsBigInt | IsBigDec
	IsOrdered = IsNumeric | IsString
)
View Source
const (
	PointerIndexBlockBlank = -1 // for the "_" identifier in blocks
	PointerIndexMap        = -2 // Base is Map, use Key.
	PointerIndexNative     = -3 // Base is *NativeValue.
)
View Source
const (
	BOTH = SEND | RECV
)
View Source
const GasFactorCPU int64 = 1
View Source
const HashSize = 20
View Source
const (
	VMSliceSize = 1024
)

Variables

View Source
var (
	IncDecStmtChecker = map[Word]func(t Type) bool{
		INC: isNumeric,
		DEC: isNumeric,
	}
	AssignStmtChecker = map[Word]func(t Type) bool{
		ADD_ASSIGN:      isNumericOrString,
		SUB_ASSIGN:      isNumeric,
		MUL_ASSIGN:      isNumeric,
		QUO_ASSIGN:      isNumeric,
		REM_ASSIGN:      isIntNum,
		SHL_ASSIGN:      isIntNum,
		SHR_ASSIGN:      isIntNum,
		BAND_ASSIGN:     isIntNum,
		XOR_ASSIGN:      isIntNum,
		BOR_ASSIGN:      isIntNum,
		BAND_NOT_ASSIGN: isIntNum,
	}
)

here are a range of rules predefined for preprocessor to check the compatibility between operands and operators e,g. for binary expr x + y, x, y can only be numeric or string, 1+2, "a" + "b" this is used in assertCompatible()s.

View Source
var Package = amino.RegisterPackage(amino.NewPackage(
	"github.com/gnolang/gno/gnovm/pkg/gnolang",
	"gno",
	amino.GetCallersDirname(),
).WithDependencies().WithTypes(

	&TypedValue{},
	StringValue(""),
	BigintValue{},
	BigdecValue{},

	PointerValue{},
	&ArrayValue{},
	&SliceValue{},
	&StructValue{},
	&FuncValue{},
	&MapValue{},
	&MapList{},
	&MapListItem{},
	&BoundMethodValue{},
	TypeValue{},
	&PackageValue{},

	&Block{},
	RefValue{},
	&HeapItemValue{},

	ObjectID{},
	&ObjectInfo{},

	ValueHash{},
	Hashlet{},

	ValuePath{},
	Location{},

	Attributes{},
	NameExpr{},
	BasicLitExpr{},
	BinaryExpr{},
	CallExpr{},
	IndexExpr{},
	SelectorExpr{},
	SliceExpr{},
	StarExpr{},
	RefExpr{},
	TypeAssertExpr{},
	UnaryExpr{},
	CompositeLitExpr{},
	KeyValueExpr{},
	FuncLitExpr{},
	ConstExpr{},
	FieldTypeExpr{},
	ArrayTypeExpr{},
	SliceTypeExpr{},
	InterfaceTypeExpr{},
	ChanTypeExpr{},
	FuncTypeExpr{},
	MapTypeExpr{},
	StructTypeExpr{},
	constTypeExpr{},
	MaybeNativeTypeExpr{},
	AssignStmt{},
	BlockStmt{},
	BranchStmt{},
	DeclStmt{},
	DeferStmt{},
	ExprStmt{},
	ForStmt{},
	GoStmt{},
	IfStmt{},
	IfCaseStmt{},
	IncDecStmt{},
	RangeStmt{},
	ReturnStmt{},
	PanicStmt{},
	SelectStmt{},
	SelectCaseStmt{},
	SendStmt{},
	SwitchStmt{},
	SwitchClauseStmt{},
	EmptyStmt{},
	bodyStmt{},
	FuncDecl{},
	ImportDecl{},
	ValueDecl{},
	TypeDecl{},

	StaticBlock{},
	FileSet{},
	FileNode{},
	PackageNode{},
	RefNode{},

	PrimitiveType(0),
	&PointerType{},
	&ArrayType{},
	&SliceType{},
	&StructType{},
	FieldType{},
	&FuncType{},
	&MapType{},
	&InterfaceType{},
	&TypeType{},
	&DeclaredType{},
	&PackageType{},
	&ChanType{},
	blockType{},
	&tupleType{},
	RefType{},
))
View Source
var ReGnoRunPath = regexp.MustCompile(`^gno\.land/r/g[a-z0-9]+/run$`)

ReGnoRunPath is the path used for realms executed in maketx run. These are not considered realms, as an exception to the RealmPathPrefix rule.

Functions

func Analyze

func Analyze(f *FuncDecl) []error

func ClearDebugErrors

func ClearDebugErrors()

func ConvertTo

func ConvertTo(alloc *Allocator, store Store, tv *TypedValue, t Type, isConst bool)

t cannot be nil or untyped or DataByteType. the conversion is forced and overflow/underflow is ignored. TODO: return error, and let caller also print the file and line.

func ConvertUntypedBigdecTo

func ConvertUntypedBigdecTo(dst *TypedValue, bv BigdecValue, t Type)

func ConvertUntypedBigintTo

func ConvertUntypedBigintTo(dst *TypedValue, bv BigintValue, t Type)

func ConvertUntypedRuneTo

func ConvertUntypedRuneTo(dst *TypedValue, t Type)

All fields may be modified to complete the conversion.

func ConvertUntypedTo

func ConvertUntypedTo(tv *TypedValue, t Type)

TODO: move untyped const stuff to preprocess.go Convert the untyped const tv to the t type. If t is nil, the default type is used. Panics if conversion is illegal. TODO: method on TypedValue?

func CopyFromCachedStore

func CopyFromCachedStore(destStore, cachedStore Store, cachedBase, cachedIavl store.Store)

CopyCachesFromStore allows to copy a store's internal object, type and BlockNode cache into the dst store. This is mostly useful for testing, where many stores have to be initialized.

func DerivePkgAddr

func DerivePkgAddr(pkgPath string) crypto.Address

For keeping record of package & realm coins.

func DisableDebug

func DisableDebug()

func EnableDebug

func EnableDebug()

func GetDebugErrors

func GetDebugErrors() []string

func Gno2GoValue

func Gno2GoValue(tv *TypedValue, rv reflect.Value) (ret reflect.Value)

NOTE: used by imports_test.go TestSetOrigCaller.

func HasDebugErrors

func HasDebugErrors() bool

func HasDeclName

func HasDeclName(d Decl, n2 Name) bool

func InitStoreCaches

func InitStoreCaches(store Store)

func IsDebug

func IsDebug() bool

func IsDebugEnabled

func IsDebugEnabled() bool

func IsImplementedBy

func IsImplementedBy(it Type, ot Type) bool

TODO: empty interface? refer to assertAssignableTo

func IsPurePackagePath

func IsPurePackagePath(pkgPath string) bool

IsPurePackagePath determines whether the given pkgpath is for a published Gno package. It only considers "pure" those starting with gno.land/p/, so it returns false for stdlib packages and MsgRun paths.

func IsRealmPath

func IsRealmPath(pkgPath string) bool

IsRealmPath determines whether the given pkgpath is for a realm, and as such should persist the global state.

func IsStdlib

func IsStdlib(s string) bool

IsStdlib determines whether s is a pkgpath for a standard library.

func NewStore

func NewStore(alloc *Allocator, baseStore, iavlStore store.Store) *defaultStore

func PredefineFileSet

func PredefineFileSet(store Store, pn *PackageNode, fset *FileSet)

In the case of a *FileSet, some declaration steps have to happen in a restricted parallel way across all the files. Anything predefined or preprocessed here get skipped during the Preprocess phase.

func ReadMemPackage

func ReadMemPackage(dir string, pkgPath string) *gnovm.MemPackage

ReadMemPackage initializes a new MemPackage by reading the OS directory at dir, and saving it with the given pkgPath (import path). The resulting MemPackage will contain the names and content of all *.gno files, and additionally README.md, LICENSE.

ReadMemPackage does not perform validation aside from the package's name; the files are not parsed but their contents are merely stored inside a MemFile.

NOTE: panics if package name is invalid (characters must be alphanumeric or _, lowercase, and must start with a letter).

func ReadMemPackageFromList

func ReadMemPackageFromList(list []string, pkgPath string) *gnovm.MemPackage

ReadMemPackageFromList creates a new gnovm.MemPackage with the specified pkgPath, containing the contents of all the files provided in the list slice. No parsing or validation is done on the filenames.

NOTE: panics if package name is invalid (characters must be alphanumeric or _, lowercase, and must start with a letter).

func SaveBlockNodes

func SaveBlockNodes(store Store, fn *FileNode)

Iterate over all block nodes recursively and saves them. Ensures uniqueness of BlockNode.Locations.

func TypeCheckMemPackage

func TypeCheckMemPackage(mempkg *gnovm.MemPackage, getter MemPackageGetter, format bool) error

TypeCheckMemPackage performs type validation and checking on the given mempkg. To retrieve dependencies, it uses getter.

The syntax checking is performed entirely using Go's go/types package.

If format is true, the code will be automatically updated with the formatted source code.

Types

type Allocator

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

Keeps track of in-memory allocations. In the future, allocations within realm boundaries will be (optionally?) condensed (objects to be GC'd will be discarded), but for now, allocations strictly increment across the whole tx.

func NewAllocator

func NewAllocator(maxBytes int64) *Allocator

func (*Allocator) Allocate

func (alloc *Allocator) Allocate(size int64)

func (*Allocator) AllocateAmino

func (alloc *Allocator) AllocateAmino(l int64)

NOTE: a reasonable max-bounds calculation for simplicity.

func (*Allocator) AllocateBlock

func (alloc *Allocator) AllocateBlock(items int64)

func (*Allocator) AllocateBlockItems

func (alloc *Allocator) AllocateBlockItems(items int64)

func (*Allocator) AllocateBoundMethod

func (alloc *Allocator) AllocateBoundMethod()

func (*Allocator) AllocateDataArray

func (alloc *Allocator) AllocateDataArray(size int64)

func (*Allocator) AllocateFunc

func (alloc *Allocator) AllocateFunc()

func (*Allocator) AllocateHeapItem

func (alloc *Allocator) AllocateHeapItem()

func (*Allocator) AllocateListArray

func (alloc *Allocator) AllocateListArray(items int64)

func (*Allocator) AllocateMap

func (alloc *Allocator) AllocateMap(items int64)

func (*Allocator) AllocateMapItem

func (alloc *Allocator) AllocateMapItem()

func (*Allocator) AllocateNative

func (alloc *Allocator) AllocateNative()

NOTE: does not allocate for the underlying value.

func (*Allocator) AllocatePointer

func (alloc *Allocator) AllocatePointer()

func (*Allocator) AllocateSlice

func (alloc *Allocator) AllocateSlice()

func (*Allocator) AllocateString

func (alloc *Allocator) AllocateString(size int64)

func (*Allocator) AllocateStruct

func (alloc *Allocator) AllocateStruct()

NOTE: fields must be allocated separately.

func (*Allocator) AllocateStructFields

func (alloc *Allocator) AllocateStructFields(fields int64)

func (*Allocator) AllocateType

func (alloc *Allocator) AllocateType()

func (*Allocator) Fork

func (alloc *Allocator) Fork() *Allocator

func (*Allocator) NewArrayFromData

func (alloc *Allocator) NewArrayFromData(data []byte) *ArrayValue

func (*Allocator) NewBlock

func (alloc *Allocator) NewBlock(source BlockNode, parent *Block) *Block

func (*Allocator) NewDataArray

func (alloc *Allocator) NewDataArray(n int) *ArrayValue

func (*Allocator) NewHeapItem

func (alloc *Allocator) NewHeapItem(tv TypedValue) *HeapItemValue

func (*Allocator) NewListArray

func (alloc *Allocator) NewListArray(n int) *ArrayValue

func (*Allocator) NewMap

func (alloc *Allocator) NewMap(size int) *MapValue

func (*Allocator) NewNative

func (alloc *Allocator) NewNative(rv reflect.Value) *NativeValue

func (*Allocator) NewSlice

func (alloc *Allocator) NewSlice(base Value, offset, length, maxcap int) *SliceValue

func (*Allocator) NewSliceFromData

func (alloc *Allocator) NewSliceFromData(data []byte) *SliceValue

NewSliceFromData allocates a new slice with the underlying data array value populated from `data`. See the doc for `NewSliceFromList` for correct usage notes.

func (*Allocator) NewSliceFromList

func (alloc *Allocator) NewSliceFromList(list []TypedValue) *SliceValue

NewSliceFromList allocates a new slice with the underlying array value populated from `list`. This should not be called from areas in the codebase that are doing allocations with potentially large user provided values, e.g. `make()` and `append()`. Using `Alloc.NewListArray` can be used is most cases to allocate the space for the `TypedValue` list before doing the allocation in the go runtime -- see the `make()` code in uverse.go.

func (*Allocator) NewString

func (alloc *Allocator) NewString(s string) StringValue

func (*Allocator) NewStruct

func (alloc *Allocator) NewStruct(fields []TypedValue) *StructValue

NOTE: fields must be allocated (e.g. from NewStructFields)

func (*Allocator) NewStructFields

func (alloc *Allocator) NewStructFields(fields int) []TypedValue

func (*Allocator) NewStructWithFields

func (alloc *Allocator) NewStructWithFields(fields ...TypedValue) *StructValue

NOTE: fields will be allocated.

func (*Allocator) NewType

func (alloc *Allocator) NewType(t Type) Type

func (*Allocator) Reset

func (alloc *Allocator) Reset() *Allocator

func (*Allocator) Status

func (alloc *Allocator) Status() (maxBytes int64, bytes int64)

type ArrayType

type ArrayType struct {
	Len int
	Elt Type
	Vrd bool
	// contains filtered or unexported fields
}

func (*ArrayType) Elem

func (at *ArrayType) Elem() Type

func (*ArrayType) GetPkgPath

func (at *ArrayType) GetPkgPath() string

func (*ArrayType) IsNamed

func (at *ArrayType) IsNamed() bool

func (*ArrayType) Kind

func (at *ArrayType) Kind() Kind

func (*ArrayType) String

func (at *ArrayType) String() string

func (*ArrayType) TypeID

func (at *ArrayType) TypeID() TypeID

type ArrayTypeExpr

type ArrayTypeExpr struct {
	Attributes
	Len Expr // if nil, variadic array lit
	Elt Expr // element type
}

func ArrayT

func ArrayT(l, elt interface{}) *ArrayTypeExpr

func (*ArrayTypeExpr) Copy

func (x *ArrayTypeExpr) Copy() Node

func (ArrayTypeExpr) String

func (x ArrayTypeExpr) String() string

type ArrayValue

type ArrayValue struct {
	ObjectInfo
	List []TypedValue
	Data []byte
}

func (*ArrayValue) Copy

func (av *ArrayValue) Copy(alloc *Allocator) *ArrayValue

func (*ArrayValue) GetCapacity

func (av *ArrayValue) GetCapacity() int

func (*ArrayValue) GetLength

func (av *ArrayValue) GetLength() int

func (*ArrayValue) GetPointerAtIndexInt2

func (av *ArrayValue) GetPointerAtIndexInt2(store Store, ii int, et Type) PointerValue

et is only required for .List byte-arrays.

func (*ArrayValue) GetReadonlyBytes

func (av *ArrayValue) GetReadonlyBytes() []byte

NOTE: Result should not be written to, behavior is unexpected when .List bytes.

func (*ArrayValue) ProtectedString

func (av *ArrayValue) ProtectedString(seen *seenValues) string

func (*ArrayValue) String

func (av *ArrayValue) String() string

type AssignStmt

type AssignStmt struct {
	Attributes
	Lhs Exprs
	Op  Word // assignment word (DEFINE, ASSIGN)
	Rhs Exprs
}

func A

func A(args ...interface{}) *AssignStmt

Usage: A(lhs1, lhs2, ..., ":=", rhs1, rhs2, ...) Operation can be like ":=", "=", "+=", etc. Other strings are automatically parsed as X(arg).

func (*AssignStmt) AssertCompatible

func (x *AssignStmt) AssertCompatible(store Store, last BlockNode)

func (*AssignStmt) Copy

func (x *AssignStmt) Copy() Node

func (AssignStmt) String

func (x AssignStmt) String() string

type Attributes

type Attributes struct {
	Line   int
	Column int
	Label  Name
	// contains filtered or unexported fields
}

func (*Attributes) DelAttribute

func (attr *Attributes) DelAttribute(key GnoAttribute)

func (*Attributes) GetAttribute

func (attr *Attributes) GetAttribute(key GnoAttribute) interface{}

GnoAttribute must not be user provided / arbitrary, otherwise will create potential exploits.

func (*Attributes) GetColumn

func (attr *Attributes) GetColumn() int

func (*Attributes) GetLabel

func (attr *Attributes) GetLabel() Name

func (*Attributes) GetLine

func (attr *Attributes) GetLine() int

func (*Attributes) HasAttribute

func (attr *Attributes) HasAttribute(key GnoAttribute) bool

func (*Attributes) SetAttribute

func (attr *Attributes) SetAttribute(key GnoAttribute, value interface{})

func (*Attributes) SetColumn

func (attr *Attributes) SetColumn(column int)

func (*Attributes) SetLabel

func (attr *Attributes) SetLabel(label Name)

func (*Attributes) SetLine

func (attr *Attributes) SetLine(line int)

type BasicLitExpr

type BasicLitExpr struct {
	Attributes
	// INT, FLOAT, IMAG, CHAR, or STRING
	Kind Word
	// literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo"
	// or `\m\n\o`
	Value string
}

func Num

func Num(s string) *BasicLitExpr

func Str

func Str(s string) *BasicLitExpr

func (*BasicLitExpr) Copy

func (x *BasicLitExpr) Copy() Node

func (*BasicLitExpr) GetInt

func (x *BasicLitExpr) GetInt() int

func (*BasicLitExpr) GetString

func (x *BasicLitExpr) GetString() string

func (BasicLitExpr) String

func (x BasicLitExpr) String() string

type BigdecValue

type BigdecValue struct {
	V *apd.Decimal
}

func (BigdecValue) Copy

func (bv BigdecValue) Copy(alloc *Allocator) BigdecValue

func (BigdecValue) MarshalAmino

func (bv BigdecValue) MarshalAmino() (string, error)

func (BigdecValue) String

func (bv BigdecValue) String() string

func (*BigdecValue) UnmarshalAmino

func (bv *BigdecValue) UnmarshalAmino(s string) error

type BigintValue

type BigintValue struct {
	V *big.Int
}

func (BigintValue) Copy

func (bv BigintValue) Copy(alloc *Allocator) BigintValue

func (BigintValue) MarshalAmino

func (bv BigintValue) MarshalAmino() (string, error)

func (BigintValue) String

func (bv BigintValue) String() string

func (*BigintValue) UnmarshalAmino

func (bv *BigintValue) UnmarshalAmino(s string) error

type BinaryExpr

type BinaryExpr struct {
	Attributes
	Left  Expr // left operand
	Op    Word // operator
	Right Expr // right operand
}

func (*BinaryExpr) AssertCompatible

func (x *BinaryExpr) AssertCompatible(lt, rt Type)

AssertCompatible works as a pre-check prior to checkOrConvertType. It checks against expressions to ensure the compatibility between operands and operators. e.g. "a" << 1, the left hand operand is not compatible with <<, it will fail the check. Overall,it efficiently filters out incompatible expressions, stopping before the next checkOrConvertType() operation to optimize performance.

func (*BinaryExpr) Copy

func (x *BinaryExpr) Copy() Node

func (BinaryExpr) String

func (x BinaryExpr) String() string

type Block

type Block struct {
	ObjectInfo
	Source BlockNode
	Values []TypedValue
	Parent Value
	Blank  TypedValue // captures "_" // XXX remove and replace with global instance.
	// contains filtered or unexported fields
}

TODO rename to BlockValue.

func NewBlock

func NewBlock(source BlockNode, parent *Block) *Block

NOTE: for allocation, use *Allocator.NewBlock.

func (*Block) ExpandToSize

func (b *Block) ExpandToSize(alloc *Allocator, size uint16)

Used by SwitchStmt upon clause match.

func (*Block) GetBlankRef

func (b *Block) GetBlankRef() *TypedValue

Result is used has lhs for any assignments to "_".

func (*Block) GetBodyStmt

func (b *Block) GetBodyStmt() *bodyStmt

func (*Block) GetParams1

func (b *Block) GetParams1() (pv1 PointerValue)

Convenience for implementing nativeBody functions.

func (*Block) GetParams2

func (b *Block) GetParams2() (pv1, pv2 PointerValue)

Convenience for implementing nativeBody functions.

func (*Block) GetParams3

func (b *Block) GetParams3() (pv1, pv2, pv3 PointerValue)

Convenience for implementing nativeBody functions.

func (*Block) GetParent

func (b *Block) GetParent(store Store) *Block

func (*Block) GetPointerTo

func (b *Block) GetPointerTo(store Store, path ValuePath) PointerValue

func (*Block) GetPointerToHeapDefine

func (b *Block) GetPointerToHeapDefine(store Store, path ValuePath) PointerValue

First defines a new HeapItemValue. This gets called from NameExprTypeHeapDefine name expressions.

func (*Block) GetPointerToHeapUse

func (b *Block) GetPointerToHeapUse(store Store, path ValuePath) PointerValue

Assumes a HeapItemValue, and gets inner pointer. This gets called from NameExprTypeHeapUse name expressions.

func (*Block) GetPointerToInt

func (b *Block) GetPointerToInt(store Store, index int) PointerValue

func (*Block) GetPointerToMaybeHeapDefine

func (b *Block) GetPointerToMaybeHeapDefine(store Store, nx *NameExpr) PointerValue

Convenience

func (*Block) GetPointerToMaybeHeapUse

func (b *Block) GetPointerToMaybeHeapUse(store Store, nx *NameExpr) PointerValue

Convenience

func (*Block) GetSource

func (b *Block) GetSource(store Store) BlockNode

func (*Block) String

func (b *Block) String() string

func (*Block) StringIndented

func (b *Block) StringIndented(indent string) string

type BlockNode

type BlockNode interface {
	Node
	InitStaticBlock(BlockNode, BlockNode)
	IsInitialized() bool
	GetStaticBlock() *StaticBlock
	GetLocation() Location
	SetLocation(Location)

	// StaticBlock promoted methods
	GetBlockNames() []Name
	GetExternNames() []Name
	GetNumNames() uint16
	GetParentNode(Store) BlockNode
	GetPathForName(Store, Name) ValuePath
	GetBlockNodeForPath(Store, ValuePath) BlockNode
	GetIsConst(Store, Name) bool
	GetLocalIndex(Name) (uint16, bool)
	GetValueRef(Store, Name, bool) *TypedValue
	GetStaticTypeOf(Store, Name) Type
	GetStaticTypeOfAt(Store, ValuePath) Type
	Predefine(bool, Name)
	Define(Name, TypedValue)
	Define2(bool, Name, Type, TypedValue)
	GetBody() Body
	SetBody(Body)
}

Nodes that create their own scope satisfy this interface.

type BlockStmt

type BlockStmt struct {
	Attributes
	StaticBlock
	Body
}

func (*BlockStmt) Copy

func (x *BlockStmt) Copy() Node

func (BlockStmt) String

func (x BlockStmt) String() string

type Body

type Body []Stmt

func (Body) GetBody

func (ss Body) GetBody() Body

func (Body) GetLabeledStmt

func (ss Body) GetLabeledStmt(label Name) (stmt Stmt, idx int)

func (*Body) SetBody

func (ss *Body) SetBody(nb Body)

func (Body) String

func (ss Body) String() string

type BoundMethodValue

type BoundMethodValue struct {
	ObjectInfo

	// Underlying unbound method function.
	// The type without the receiver (since bound)
	// is computed lazily if needed.
	Func *FuncValue

	// This becomes the first arg.
	// The type is .Func.Type.Params[0].
	Receiver TypedValue
}

func (*BoundMethodValue) String

func (v *BoundMethodValue) String() string

type BranchStmt

type BranchStmt struct {
	Attributes
	Op        Word  // keyword word (BREAK, CONTINUE, GOTO, FALLTHROUGH)
	Label     Name  // label name; or empty
	Depth     uint8 // blocks to pop
	BodyIndex int   // index of statement of body
}

func Break

func Break(label interface{}) *BranchStmt

func Continue

func Continue(label interface{}) *BranchStmt

func Fallthrough

func Fallthrough(label interface{}) *BranchStmt

func Goto

func Goto(label interface{}) *BranchStmt

func (*BranchStmt) Copy

func (x *BranchStmt) Copy() Node

func (BranchStmt) String

func (x BranchStmt) String() string

type CallExpr

type CallExpr struct {
	Attributes
	Func    Expr  // function expression
	Args    Exprs // function arguments, if any.
	Varg    bool  // if true, final arg is variadic.
	NumArgs int   // len(Args) or len(Args[0].Results)
}

func Call

func Call(fn interface{}, args ...interface{}) *CallExpr

func Len

func Len(x Expr) *CallExpr

func (*CallExpr) Copy

func (x *CallExpr) Copy() Node

func (CallExpr) String

func (x CallExpr) String() string

type ChanDir

type ChanDir int
const (
	SEND ChanDir = 1 << iota
	RECV
)

type ChanType

type ChanType struct {
	Dir ChanDir
	Elt Type
	// contains filtered or unexported fields
}

func (*ChanType) Elem

func (ct *ChanType) Elem() Type

func (*ChanType) GetPkgPath

func (ct *ChanType) GetPkgPath() string

func (*ChanType) IsNamed

func (ct *ChanType) IsNamed() bool

func (*ChanType) Kind

func (ct *ChanType) Kind() Kind

func (*ChanType) String

func (ct *ChanType) String() string

func (*ChanType) TypeID

func (ct *ChanType) TypeID() TypeID

type ChanTypeExpr

type ChanTypeExpr struct {
	Attributes
	Dir   ChanDir // channel direction
	Value Expr    // value type
}

func (*ChanTypeExpr) Copy

func (x *ChanTypeExpr) Copy() Node

func (ChanTypeExpr) String

func (x ChanTypeExpr) String() string

type CompositeLitExpr

type CompositeLitExpr struct {
	Attributes
	Type Expr          // literal type; or nil
	Elts KeyValueExprs // list of struct fields; if any
}

MyType{<key>:<value>} struct, array, slice, and map expressions.

func (*CompositeLitExpr) Copy

func (x *CompositeLitExpr) Copy() Node

func (*CompositeLitExpr) IsKeyed

func (x *CompositeLitExpr) IsKeyed() bool

Returns true if any elements are keyed. Panics if inconsistent.

func (CompositeLitExpr) String

func (x CompositeLitExpr) String() string

type ConstExpr

type ConstExpr struct {
	Attributes
	Source Expr // (preprocessed) source of this value.
	TypedValue
}

The preprocessor replaces const expressions with *ConstExpr nodes.

func (*ConstExpr) Copy

func (x *ConstExpr) Copy() Node

func (ConstExpr) String

func (x ConstExpr) String() string

type DataByteValue

type DataByteValue struct {
	Base     *ArrayValue // base array.
	Index    int         // base.Data index.
	ElemType Type        // is Uint8Kind.
}

func (DataByteValue) GetByte

func (dbv DataByteValue) GetByte() byte

func (DataByteValue) SetByte

func (dbv DataByteValue) SetByte(b byte)

func (DataByteValue) String

func (dbv DataByteValue) String() string

type DebugState

type DebugState int

DebugState is the state of the machine debugger, defined by a finite state automaton with the following transitions, evaluated at each debugger input or each gnoVM instruction while in step mode: - DebugAtInit -> DebugAtCmd: initial debugger setup is performed - DebugAtCmd -> DebugAtCmd: when command is for inspecting or setting a breakpoint - DebugAtCmd -> DebuAtRun: when command is 'continue', 'step' or 'stepi' - DebugAtCmd -> DebugAtExit: when command is 'quit' or 'resume' - DebugAtRun -> DebugAtRun: when current machine instruction doesn't match a breakpoint - DebugAtRun -> DebugAtCmd: when current machine instruction matches a breakpoint - DebugAtRun -> DebugAtExit: when the program terminates

const (
	DebugAtInit DebugState = iota // performs debugger IO setup and enters gnoVM in step mode
	DebugAtCmd                    // awaits a new command from the debugger input stream
	DebugAtRun                    // awaits the next machine instruction
	DebugAtExit                   // closes debugger IO and exits gnoVM from step mode
)

type Debugger

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

Debugger describes a machine debugger.

func (*Debugger) Disable

func (d *Debugger) Disable()

Disable makes the debugger d inactive.

func (*Debugger) Enable

func (d *Debugger) Enable(in io.Reader, out io.Writer, f func(string) string)

Enable makes the debugger d active, using in as input reader, out as output writer and f as a source helper.

func (*Debugger) Serve

func (d *Debugger) Serve(addr string) error

Serve waits for a remote client to connect to addr and use this connection for debugger IO. It returns an error if the connection can not be established, or nil.

type Decl

type Decl interface {
	Node
	GetDeclNames() []Name
	// contains filtered or unexported methods
}

type DeclStmt

type DeclStmt struct {
	Attributes
	Body // (simple) ValueDecl or TypeDecl
}

func Var

func Var(name interface{}, typ Expr, value Expr) *DeclStmt

func (*DeclStmt) Copy

func (x *DeclStmt) Copy() Node

func (DeclStmt) String

func (x DeclStmt) String() string

type DeclaredType

type DeclaredType struct {
	PkgPath string
	Name    Name
	Base    Type         // not a DeclaredType
	Methods []TypedValue // {T:*FuncType,V:*FuncValue}...
	// contains filtered or unexported fields
}

func (*DeclaredType) DefineMethod

func (dt *DeclaredType) DefineMethod(fv *FuncValue)

func (*DeclaredType) Elem

func (dt *DeclaredType) Elem() Type

func (*DeclaredType) FindEmbeddedFieldType

func (dt *DeclaredType) FindEmbeddedFieldType(callerPath string, n Name, m map[Type]struct{}) (
	trail []ValuePath, hasPtr bool, rcvr Type, ft Type, accessError bool,
)

Searches embedded fields to find matching field or method. This function is slow. TODO: consider memoizing for successful matches.

func (*DeclaredType) GetPathForName

func (dt *DeclaredType) GetPathForName(n Name) ValuePath

func (*DeclaredType) GetPkgPath

func (dt *DeclaredType) GetPkgPath() string

func (*DeclaredType) GetStaticValueAt

func (dt *DeclaredType) GetStaticValueAt(path ValuePath) TypedValue

Like GetValueAt, but doesn't fill *FuncValue closures.

func (*DeclaredType) GetUnboundPathForName

func (dt *DeclaredType) GetUnboundPathForName(n Name) ValuePath

func (*DeclaredType) GetValueAt

func (dt *DeclaredType) GetValueAt(alloc *Allocator, store Store, path ValuePath) TypedValue

The Preprocesses uses *DT.FindEmbeddedFieldType() to set the path. OpSelector uses *TV.GetPointerTo(path), and for declared types, in turn uses *DT.GetValueAt(path) to find any methods (see values.go).

i.e.,

preprocessor: *DT.FindEmbeddedFieldType(name)
              *DT.GetValueAt(path) // from op_type/evalTypeOf()

     runtime: *TV.GetPointerTo(path)
               -> *DT.GetValueAt(path)

func (*DeclaredType) IsNamed

func (dt *DeclaredType) IsNamed() bool

func (*DeclaredType) Kind

func (dt *DeclaredType) Kind() Kind

NOTE: it may be faster to switch on baseOf().

func (*DeclaredType) Seal

func (dt *DeclaredType) Seal()

func (*DeclaredType) String

func (dt *DeclaredType) String() string

func (*DeclaredType) TryDefineMethod

func (dt *DeclaredType) TryDefineMethod(fv *FuncValue) bool

TryDefineMethod attempts to define the method fv on type dt. It returns false if this does not succeeds, as a result of a re-declaration.

func (*DeclaredType) TypeID

func (dt *DeclaredType) TypeID() TypeID

type Decls

type Decls []Decl

func (Decls) String

func (ds Decls) String() string

type Defer

type Defer struct {
	Func   *FuncValue   // function value
	GoFunc *NativeValue // go function value
	Args   []TypedValue // arguments
	Source *DeferStmt   // source
	Parent *Block

	// PanicScope is set to the value of the Machine's PanicScope when the
	// defer is created. The PanicScope of the Machine is incremented each time
	// a panic occurs and is decremented each time a panic is recovered.
	PanicScope uint
}

type DeferStmt

type DeferStmt struct {
	Attributes
	Call CallExpr
}

func (*DeferStmt) Copy

func (x *DeferStmt) Copy() Node

func (DeferStmt) String

func (x DeferStmt) String() string

type EmptyStmt

type EmptyStmt struct {
	Attributes
}

A compile artifact to use in place of nil. For example, _ctif() may return an empty statement.

func (*EmptyStmt) Copy

func (x *EmptyStmt) Copy() Node

func (EmptyStmt) String

func (x EmptyStmt) String() string

type Exception

type Exception struct {
	// Value is the value passed to panic.
	Value TypedValue
	// Frame is used to reference the frame a panic occurred in so that recover() knows if the
	// currently executing deferred function is able to recover from the panic.
	Frame *Frame

	Stacktrace Stacktrace
}

Exception represents a panic that originates from a gno program.

func (Exception) Sprint

func (e Exception) Sprint(m *Machine) string

type Expr

type Expr interface {
	Node
	// contains filtered or unexported methods
}

func Bx

func Bx(lx interface{}, op string, rx interface{}) Expr

Binary expression. x, y can be Expr or string.

func MustParseExpr

func MustParseExpr(expr string) Expr

func ParseExpr

func ParseExpr(expr string) (retx Expr, err error)

func X

func X(x interface{}, args ...interface{}) Expr

Parses simple expressions (but not all). Useful for parsing strings to ast nodes, like foo.bar["qwe"](), new(bytes.Buffer), *bytes.Buffer, package.MyStruct{FieldA:1}, numeric

  • num/char (e.g. e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f')
  • strings (e.g. "foo" or `\m\n\o`), nil, function calls
  • square bracket indexing
  • dot notation
  • star expression for pointers
  • composite expressions
  • nil
  • type assertions, for EXPR.(EXPR) and also EXPR.(type)
  • []type slice types
  • [n]type array types
  • &something referencing
  • unary operations, namely "+" | "-" | "!" | "^" | "*" | "&" | "<-" .
  • binary operations, namely "||", "&&", "==" | "!=" | "<" | "<=" | ">" | ">=" "+" | "-" | "|" | "^" "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .

If the first argument is an expression, returns it. TODO replace this with rewrite of Joeson parser.

func Xs

func Xs(exprs ...Expr) []Expr

type ExprStmt

type ExprStmt struct {
	Attributes
	X Expr
}

func (*ExprStmt) Copy

func (x *ExprStmt) Copy() Node

func (ExprStmt) String

func (x ExprStmt) String() string

type Exprs

type Exprs []Expr

func (Exprs) String

func (xs Exprs) String() string

type FieldType

type FieldType struct {
	Name     Name
	Type     Type
	Embedded bool
	Tag      Tag
}

func (FieldType) Elem

func (ft FieldType) Elem() Type

func (FieldType) GetPkgPath

func (ft FieldType) GetPkgPath() string

func (FieldType) IsNamed

func (ft FieldType) IsNamed() bool

func (FieldType) Kind

func (ft FieldType) Kind() Kind

func (FieldType) String

func (ft FieldType) String() string

func (FieldType) TypeID

func (ft FieldType) TypeID() TypeID

type FieldTypeExpr

type FieldTypeExpr struct {
	Attributes
	Name
	Type Expr

	// Currently only BasicLitExpr allowed.
	// NOTE: In Go, only struct fields can have tags.
	Tag Expr
}

func Recv

func Recv(n, t interface{}) FieldTypeExpr

func (*FieldTypeExpr) Copy

func (x *FieldTypeExpr) Copy() Node

func (FieldTypeExpr) String

func (x FieldTypeExpr) String() string

type FieldTypeExprs

type FieldTypeExprs []FieldTypeExpr

func Flds

func Flds(args ...interface{}) FieldTypeExprs

func (FieldTypeExprs) IsNamed

func (ftxz FieldTypeExprs) IsNamed() bool

func (FieldTypeExprs) String

func (ftxz FieldTypeExprs) String() string

type FieldTypeList

type FieldTypeList []FieldType

func (FieldTypeList) HasUnexported

func (l FieldTypeList) HasUnexported() bool

func (FieldTypeList) Len

func (l FieldTypeList) Len() int

FieldTypeList implements sort.Interface.

func (FieldTypeList) Less

func (l FieldTypeList) Less(i, j int) bool

FieldTypeList implements sort.Interface.

func (FieldTypeList) String

func (l FieldTypeList) String() string

func (FieldTypeList) StringWithCommas

func (l FieldTypeList) StringWithCommas() string

func (FieldTypeList) Swap

func (l FieldTypeList) Swap(i, j int)

FieldTypeList implements sort.Interface.

func (FieldTypeList) TypeID

func (l FieldTypeList) TypeID() TypeID

User should call sort for interface methods. XXX how though?

func (FieldTypeList) TypeIDForPackage

func (l FieldTypeList) TypeIDForPackage(pkgPath string) TypeID

For use in fields of packages, structs, and interfaces, where any unexported lowercase fields are private and unequal to other package types.

func (FieldTypeList) Types

func (l FieldTypeList) Types() []Type

func (FieldTypeList) UnnamedTypeID

func (l FieldTypeList) UnnamedTypeID() TypeID

Like TypeID() but without considering field names; used for function parameters and results.

type FileNode

type FileNode struct {
	Attributes
	StaticBlock
	Name
	PkgName Name
	Decls
}

func MustParseFile

func MustParseFile(filename string, body string) *FileNode

func MustReadFile

func MustReadFile(path string) *FileNode

func ParseFile

func ParseFile(filename string, body string) (fn *FileNode, err error)

ParseFile uses the Go parser to parse body. It then runs Go2Gno on the resulting AST -- the resulting FileNode is returned, together with any other error (including panics, which are recovered) from Go2Gno.

func ReadFile

func ReadFile(path string) (*FileNode, error)

func (*FileNode) Copy

func (x *FileNode) Copy() Node

func (*FileNode) GetBody

func (x *FileNode) GetBody() Body

func (*FileNode) SetBody

func (x *FileNode) SetBody(b Body)

func (FileNode) String

func (x FileNode) String() string

type FileSet

type FileSet struct {
	Files []*FileNode
}

func ParseMemPackage

func ParseMemPackage(memPkg *gnovm.MemPackage) (fset *FileSet)

ParseMemPackage executes ParseFile on each file of the memPkg, excluding test and spurious (non-gno) files. The resulting *FileSet is returned.

If one of the files has a different package name than memPkg.Name, or ParseFile returns an error, ParseMemPackage panics.

func (*FileSet) AddFiles

func (fs *FileSet) AddFiles(fns ...*FileNode)

func (*FileSet) CopyFileSet

func (fs *FileSet) CopyFileSet() *FileSet

func (*FileSet) FileNames

func (fs *FileSet) FileNames() []string

func (*FileSet) GetDeclFor

func (fs *FileSet) GetDeclFor(n Name) (*FileNode, *Decl)

Returns a pointer to the file body decl (as well as the *FileNode which contains it) that declares n for the associated package with *FileSet. Does not work for import decls which are for the file level. The file body decl can be replaced by reference assignment. TODO move to package?

func (*FileSet) GetDeclForSafe

func (fs *FileSet) GetDeclForSafe(n Name) (*FileNode, *Decl, bool)

func (*FileSet) GetFileByName

func (fs *FileSet) GetFileByName(n Name) *FileNode

type ForContext

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

type ForStmt

type ForStmt struct {
	Attributes
	StaticBlock
	Init Stmt // initialization (simple) statement; or nil
	Cond Expr // condition; or nil
	Post Stmt // post iteration (simple) statement; or nil
	Body
}

func For

func For(init, cond, post interface{}, b ...Stmt) *ForStmt

func Loop

func Loop(b ...Stmt) *ForStmt

func Once

func Once(b ...Stmt) *ForStmt

func (*ForStmt) Copy

func (x *ForStmt) Copy() Node

func (ForStmt) String

func (x ForStmt) String() string

type Frame

type Frame struct {
	// general
	Label     Name // for break/continue
	Source    Node // source of frame
	NumOps    int  // number of ops in stack
	NumValues int  // number of values in stack
	NumExprs  int  // number of exprs in stack
	NumStmts  int  // number of statements in stack
	NumBlocks int  // number of blocks in stack

	// call frame
	Func        *FuncValue    // function value
	GoFunc      *NativeValue  // go function value
	Receiver    TypedValue    // if bound method
	NumArgs     int           // number of arguments in call
	IsVarg      bool          // is form fncall(???, vargs...)
	Defers      []Defer       // deferred calls
	LastPackage *PackageValue // previous package context
	LastRealm   *Realm        // previous realm context

	Popped bool // true if frame has been popped
}

func (*Frame) IsCall

func (fr *Frame) IsCall() bool

func (*Frame) PopDefer

func (fr *Frame) PopDefer() (res Defer, ok bool)

func (*Frame) PushDefer

func (fr *Frame) PushDefer(dfr Defer)

func (Frame) String

func (fr Frame) String() string

type FuncDecl

type FuncDecl struct {
	Attributes
	StaticBlock
	NameExpr
	IsMethod bool
	Recv     FieldTypeExpr // receiver (if method); or empty (if function)
	Type     FuncTypeExpr  // function signature: parameters and results
	Body                   // function body; or empty for external (non-Go) function
}

func FuncD

func FuncD(name interface{}, params, results FieldTypeExprs, body []Stmt) *FuncDecl

FuncD creates a new function declaration.

There is a difference between passing nil to body or passing []Stmt{}: nil means that the curly brackets are missing in the source code, indicating a declaration for an externally-defined function, while []Stmt{} is simply a functions with no statements (func() {}).

func MthdD

func MthdD(name interface{}, recv FieldTypeExpr, params, results FieldTypeExprs, body []Stmt) *FuncDecl

func (*FuncDecl) Copy

func (x *FuncDecl) Copy() Node

func (*FuncDecl) GetDeclNames

func (x *FuncDecl) GetDeclNames() []Name

func (FuncDecl) String

func (x FuncDecl) String() string

type FuncDeclContext

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

type FuncLitContext

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

type FuncLitExpr

type FuncLitExpr struct {
	Attributes
	StaticBlock
	Type         FuncTypeExpr // function type
	Body                      // function body
	HeapCaptures NameExprs    // filled in findLoopUses1
}

A FuncLitExpr node represents a function literal. Here one can reference statements from an expression, which completes the procedural circle.

func Fn

func Fn(params, results FieldTypeExprs, body []Stmt) *FuncLitExpr

func (*FuncLitExpr) Copy

func (x *FuncLitExpr) Copy() Node

func (FuncLitExpr) String

func (x FuncLitExpr) String() string

type FuncType

type FuncType struct {
	Params  []FieldType
	Results []FieldType
	// contains filtered or unexported fields
}

func (*FuncType) BoundType

func (ft *FuncType) BoundType() *FuncType

bound function type (if ft is a method).

func (*FuncType) Elem

func (ft *FuncType) Elem() Type

func (*FuncType) GetPkgPath

func (ft *FuncType) GetPkgPath() string

func (*FuncType) HasPointerReceiver

func (ft *FuncType) HasPointerReceiver() bool

if ft is a method, returns whether method takes a pointer receiver.

func (*FuncType) HasVarg

func (ft *FuncType) HasVarg() bool

func (*FuncType) IsNamed

func (ft *FuncType) IsNamed() bool

func (*FuncType) IsZero

func (ft *FuncType) IsZero() bool

true for predefined func types that are not filled in yet.

func (*FuncType) Kind

func (ft *FuncType) Kind() Kind

func (*FuncType) Specify

func (ft *FuncType) Specify(store Store, argTVs []TypedValue, isVarg bool) *FuncType

given the call arg types (and whether is ...varg), specify any generic types to return the ultimate specified func type. Any untyped arg types are first converted to its default type. NOTE: if ft.HasVarg() and !isVarg, argTVs[len(ft.Params):] are ignored (since they are of the same type as argTVs[len(ft.Params)-1]).

func (*FuncType) String

func (ft *FuncType) String() string

func (*FuncType) TypeID

func (ft *FuncType) TypeID() TypeID

func (*FuncType) UnboundType

func (ft *FuncType) UnboundType(rft FieldType) *FuncType

unbound function type

type FuncTypeExpr

type FuncTypeExpr struct {
	Attributes
	Params  FieldTypeExprs // (incoming) parameters, if any.
	Results FieldTypeExprs // (outgoing) results, if any.
}

func FuncT

func FuncT(params, results FieldTypeExprs) *FuncTypeExpr

func (*FuncTypeExpr) Copy

func (x *FuncTypeExpr) Copy() Node

func (FuncTypeExpr) String

func (x FuncTypeExpr) String() string

type FuncValue

type FuncValue struct {
	Type       Type         // includes unbound receiver(s)
	IsMethod   bool         // is an (unbound) method
	Source     BlockNode    // for block mem allocation
	Name       Name         // name of function/method
	Closure    Value        // *Block or RefValue to closure (may be nil for file blocks; lazy)
	Captures   []TypedValue `json:",omitempty"` // HeapItemValues captured from closure.
	FileName   Name         // file name where declared
	PkgPath    string
	NativePkg  string // for native bindings through NativeStore
	NativeName Name   // not redundant with Name; this cannot be changed in userspace
	// contains filtered or unexported fields
}

FuncValue.Type stores the method signature from the declaration, and has exact parameter/result names declared, whereas the TypedValue.T that contains at .V may not. (i.e. TypedValue.T doesn't care about parameter/result names, but the *FuncValue requires this for execution. In leu of FuncValue.Type, we could refer to FuncValue.Source or create a different field with param/result names, but *FuncType is already a suitable structure, and re-using makes construction TypedValue{T:*FuncType{},V:*FuncValue{}} faster.

func (*FuncValue) Copy

func (fv *FuncValue) Copy(alloc *Allocator) *FuncValue

func (*FuncValue) GetBodyFromSource

func (fv *FuncValue) GetBodyFromSource(store Store) []Stmt

func (*FuncValue) GetClosure

func (fv *FuncValue) GetClosure(store Store) *Block

NOTE: this function does not automatically memoize the closure for file-level declared methods and functions. For those, caller should set .Closure manually after *FuncValue.Copy().

func (*FuncValue) GetPackage

func (fv *FuncValue) GetPackage(store Store) *PackageValue

func (*FuncValue) GetSource

func (fv *FuncValue) GetSource(store Store) BlockNode

func (*FuncValue) GetType

func (fv *FuncValue) GetType(store Store) *FuncType

func (*FuncValue) IsNative

func (fv *FuncValue) IsNative() bool

func (*FuncValue) String

func (fv *FuncValue) String() string

func (*FuncValue) UpdateBodyFromSource

func (fv *FuncValue) UpdateBodyFromSource()

type GnoAttribute

type GnoAttribute string
const (
	ATTR_PREPROCESSED    GnoAttribute = "ATTR_PREPROCESSED"
	ATTR_PREDEFINED      GnoAttribute = "ATTR_PREDEFINED"
	ATTR_TYPE_VALUE      GnoAttribute = "ATTR_TYPE_VALUE"
	ATTR_TYPEOF_VALUE    GnoAttribute = "ATTR_TYPEOF_VALUE"
	ATTR_IOTA            GnoAttribute = "ATTR_IOTA"
	ATTR_LOCATIONED      GnoAttribute = "ATTR_LOCATIONE"     // XXX DELETE
	ATTR_GOTOLOOP_STMT   GnoAttribute = "ATTR_GOTOLOOP_STMT" // XXX delete?
	ATTR_LOOP_DEFINES    GnoAttribute = "ATTR_LOOP_DEFINES"  // []Name defined within loops.
	ATTR_LOOP_USES       GnoAttribute = "ATTR_LOOP_USES"     // []Name loop defines actually used.
	ATTR_SHIFT_RHS       GnoAttribute = "ATTR_SHIFT_RHS"
	ATTR_LAST_BLOCK_STMT GnoAttribute = "ATTR_LAST_BLOCK_STMT"
)

type GoStmt

type GoStmt struct {
	Attributes
	Call CallExpr
}

func (*GoStmt) Copy

func (x *GoStmt) Copy() Node

func (GoStmt) String

func (x GoStmt) String() string

type Hashlet

type Hashlet [HashSize]byte

func HashBytes

func HashBytes(bz []byte) (res Hashlet)

func NewHashlet

func NewHashlet(bz []byte) Hashlet

func (Hashlet) Bytes

func (h Hashlet) Bytes() []byte

func (Hashlet) Copy

func (h Hashlet) Copy() Hashlet

func (Hashlet) IsZero

func (h Hashlet) IsZero() bool

type HeapItemValue

type HeapItemValue struct {
	ObjectInfo
	Value TypedValue
}

Base for a detached singleton (e.g. new(int) or &struct{}) Conceptually like a Block that holds one value. NOTE: could be renamed to HeapItemBaseValue. See also note in realm.go about auto-unwrapping.

func (*HeapItemValue) String

func (v *HeapItemValue) String() string

type IfCaseStmt

type IfCaseStmt struct {
	Attributes
	StaticBlock
	Body
}

func (*IfCaseStmt) Copy

func (x *IfCaseStmt) Copy() Node

func (IfCaseStmt) String

func (x IfCaseStmt) String() string

type IfStmt

type IfStmt struct {
	Attributes
	StaticBlock
	Init Stmt       // initialization (simple) statement; or nil
	Cond Expr       // condition; or nil
	Then IfCaseStmt // body statements
	Else IfCaseStmt // else statements
}

NOTE: syntactically, code may choose to chain if-else statements with `} else if ... {` constructions, but this is not represented in the logical AST.

func If

func If(cond Expr, b ...Stmt) *IfStmt

func IfElse

func IfElse(cond Expr, bdy, els Stmt) *IfStmt

func (*IfStmt) Copy

func (x *IfStmt) Copy() Node

func (*IfStmt) GetBody

func (x *IfStmt) GetBody() Body

func (*IfStmt) SetBody

func (x *IfStmt) SetBody(b Body)

func (IfStmt) String

func (x IfStmt) String() string

type ImportDecl

type ImportDecl struct {
	Attributes
	NameExpr // local package name. required.
	PkgPath  string
}

func ImportD

func ImportD(name interface{}, path string) *ImportDecl

func (*ImportDecl) Copy

func (x *ImportDecl) Copy() Node

func (*ImportDecl) GetDeclNames

func (x *ImportDecl) GetDeclNames() []Name

func (ImportDecl) String

func (x ImportDecl) String() string

type IncDecStmt

type IncDecStmt struct {
	Attributes
	X  Expr
	Op Word // INC or DEC
}

func Dec

func Dec(x interface{}) *IncDecStmt

func Inc

func Inc(x interface{}) *IncDecStmt

func (*IncDecStmt) AssertCompatible

func (x *IncDecStmt) AssertCompatible(t Type)

func (*IncDecStmt) Copy

func (x *IncDecStmt) Copy() Node

func (IncDecStmt) String

func (x IncDecStmt) String() string

type IndexExpr

type IndexExpr struct {
	Attributes
	X     Expr // expression
	Index Expr // index expression
	HasOK bool // if true, is form: `value, ok := <X>[<Key>]`
}

func Idx

func Idx(x interface{}, idx interface{}) *IndexExpr

func (*IndexExpr) Copy

func (x *IndexExpr) Copy() Node

func (IndexExpr) String

func (x IndexExpr) String() string

type InterfaceType

type InterfaceType struct {
	PkgPath string
	Methods []FieldType
	Generic Name // for uverse "generics"
	// contains filtered or unexported fields
}

func (*InterfaceType) Elem

func (it *InterfaceType) Elem() Type

func (*InterfaceType) FindEmbeddedFieldType

func (it *InterfaceType) FindEmbeddedFieldType(callerPath string, n Name, m map[Type]struct{}) (
	trail []ValuePath, hasPtr bool, rcvr Type, ft Type, accessError bool,
)

func (*InterfaceType) GetPathForName

func (it *InterfaceType) GetPathForName(n Name) ValuePath

func (*InterfaceType) GetPkgPath

func (it *InterfaceType) GetPkgPath() string

func (*InterfaceType) IsEmptyInterface

func (it *InterfaceType) IsEmptyInterface() bool

func (*InterfaceType) IsImplementedBy

func (it *InterfaceType) IsImplementedBy(ot Type) bool

func (*InterfaceType) IsNamed

func (it *InterfaceType) IsNamed() bool

func (*InterfaceType) Kind

func (it *InterfaceType) Kind() Kind

func (*InterfaceType) String

func (it *InterfaceType) String() string

func (*InterfaceType) TypeID

func (it *InterfaceType) TypeID() TypeID

func (*InterfaceType) VerifyImplementedBy

func (it *InterfaceType) VerifyImplementedBy(ot Type) error

For run-time type assertion. TODO: optimize somehow.

type InterfaceTypeExpr

type InterfaceTypeExpr struct {
	Attributes
	Methods FieldTypeExprs // list of methods
	Generic Name           // for uverse generics
}

func AnyT

func AnyT() *InterfaceTypeExpr

func GenT

func GenT(generic Name, methods FieldTypeExprs) *InterfaceTypeExpr

func InterfaceT

func InterfaceT(methods FieldTypeExprs) *InterfaceTypeExpr

func (*InterfaceTypeExpr) Copy

func (x *InterfaceTypeExpr) Copy() Node

func (InterfaceTypeExpr) String

func (x InterfaceTypeExpr) String() string

type KeyValueExpr

type KeyValueExpr struct {
	Attributes
	Key   Expr // or nil
	Value Expr // never nil
}

A KeyValueExpr represents a single key-value pair in struct, array, slice, and map expressions.

func Kv

func Kv(n, v interface{}) KeyValueExpr

func (*KeyValueExpr) Copy

func (x *KeyValueExpr) Copy() Node

func (KeyValueExpr) String

func (x KeyValueExpr) String() string

type KeyValueExprs

type KeyValueExprs []KeyValueExpr

func (KeyValueExprs) String

func (kvs KeyValueExprs) String() string

type Kind

type Kind uint
const (
	InvalidKind Kind = iota
	BoolKind
	StringKind
	IntKind
	Int8Kind
	Int16Kind
	Int32Kind
	Int64Kind
	UintKind
	Uint8Kind
	Uint16Kind
	Uint32Kind
	Uint64Kind
	Float32Kind
	Float64Kind
	BigintKind // not in go.
	BigdecKind // not in go.
	// UintptrKind
	ArrayKind
	SliceKind
	PointerKind
	StructKind
	PackageKind // not in go.
	InterfaceKind
	ChanKind
	FuncKind
	MapKind
	TypeKind // not in go.
	// UnsafePointerKind
	BlockKind    // not in go.
	HeapItemKind // not in go.
	TupleKind    // not in go.
	RefTypeKind  // not in go.
)

func KindOf

func KindOf(t Type) Kind

This is generally slower than switching on baseOf(t).

func (Kind) String

func (i Kind) String() string

type Location

type Location struct {
	PkgPath string
	File    string
	Line    int
	Column  int
}

func PackageNodeLocation

func PackageNodeLocation(path string) Location

func (Location) IsZero

func (loc Location) IsZero() bool

func (Location) String

func (loc Location) String() string

type Machine

type Machine struct {
	// State
	Ops        []Op // main operations
	NumOps     int
	Values     []TypedValue  // buffer of values to be operated on
	NumValues  int           // number of values
	Exprs      []Expr        // pending expressions
	Stmts      []Stmt        // pending statements
	Blocks     []*Block      // block (scope) stack
	Frames     []*Frame      // func call stack
	Package    *PackageValue // active package
	Realm      *Realm        // active realm
	Alloc      *Allocator    // memory allocations
	Exceptions []Exception
	NumResults int   // number of results returned
	Cycles     int64 // number of "cpu" cycles

	Debugger Debugger

	// Configuration
	PreprocessorMode bool // this is used as a flag when const values are evaluated during preprocessing
	ReadOnly         bool
	MaxCycles        int64
	Output           io.Writer
	Store            Store
	Context          interface{}
	GasMeter         store.GasMeter
	// PanicScope is incremented each time a panic occurs and is reset to
	// zero when it is recovered.
	PanicScope uint
	// DeferPanicScope is set to the value of the defer's panic scope before
	// it is executed. It is reset to zero after the defer functions in the current
	// scope have finished executing.
	DeferPanicScope uint
}

func NewMachine

func NewMachine(pkgPath string, store Store) *Machine

NewMachine initializes a new gno virtual machine, acting as a shorthand for NewMachineWithOptions, setting the given options PkgPath and Store.

The machine will run on the package at the given path, which will be retrieved through the given store. If it is not set, the machine has no active package, and one must be set prior to usage.

Like for NewMachineWithOptions, Machines initialized through this constructor must be finalized with Machine.Release.

func NewMachineWithOptions

func NewMachineWithOptions(opts MachineOptions) *Machine

NewMachineWithOptions initializes a new gno virtual machine with the given options.

Machines initialized through this constructor must be finalized with Machine.Release.

func (*Machine) CheckEmpty

func (m *Machine) CheckEmpty() error

for testing.

func (*Machine) Debug

func (m *Machine) Debug()

Debug is the debug callback invoked at each VM execution step. It implements the DebugState FSA.

func (*Machine) Eval

func (m *Machine) Eval(x Expr) []TypedValue

Evaluate throwaway expression in new block scope. If x is a function call, it may return any number of results including 0. Otherwise it returns 1. Input must not have been preprocessed, that is, it should not be the child of any parent.

func (*Machine) EvalStatic

func (m *Machine) EvalStatic(last BlockNode, x Expr) TypedValue

Evaluate any preprocessed expression statically. This is primiarily used by the preprocessor to evaluate static types and values.

func (*Machine) EvalStaticTypeOf

func (m *Machine) EvalStaticTypeOf(last BlockNode, x Expr) Type

Evaluate the type of any preprocessed expression statically. This is primiarily used by the preprocessor to evaluate static types of nodes.

func (*Machine) ExceptionsStacktrace

func (m *Machine) ExceptionsStacktrace() string

func (*Machine) ForcePopOp

func (m *Machine) ForcePopOp()

func (*Machine) ForcePopStmt

func (m *Machine) ForcePopStmt() (s Stmt)

func (*Machine) LastBlock

func (m *Machine) LastBlock() *Block

The result is a volatile reference in the machine's type stack. Mutate and forget.

func (*Machine) LastCallFrame

func (m *Machine) LastCallFrame(n int) *Frame

LastCallFrame behaves the same as MustLastCallFrame, but rather than panicking, returns nil if the frame is not found.

func (*Machine) LastFrame

func (m *Machine) LastFrame() *Frame

func (*Machine) MustLastCallFrame

func (m *Machine) MustLastCallFrame(n int) *Frame

MustLastCallFrame returns the last call frame with an offset of n. It panics if the frame is not found.

func (*Machine) NumFrames

func (m *Machine) NumFrames() int

func (*Machine) Panic

func (m *Machine) Panic(ex TypedValue)

func (*Machine) PeekExpr

func (m *Machine) PeekExpr(offset int) Expr

Offset starts at 1.

func (*Machine) PeekFrameAndContinueFor

func (m *Machine) PeekFrameAndContinueFor()

func (*Machine) PeekFrameAndContinueRange

func (m *Machine) PeekFrameAndContinueRange()

func (*Machine) PeekStmt

func (m *Machine) PeekStmt(offset int) Stmt

Offset starts at 1. DEPRECATED use PeekStmt1() instead.

func (*Machine) PeekStmt1

func (m *Machine) PeekStmt1() Stmt

func (*Machine) PeekType

func (m *Machine) PeekType(offset int) Type

XXX delete?

func (*Machine) PeekValue

func (m *Machine) PeekValue(offset int) *TypedValue

Returns reference to value in Values stack. Offset starts at 1.

func (*Machine) PopAsPointer

func (m *Machine) PopAsPointer(lx Expr) PointerValue

func (*Machine) PopBlock

func (m *Machine) PopBlock() (b *Block)

func (*Machine) PopCopyValues

func (m *Machine) PopCopyValues(n int) []TypedValue

Like PopValues(), but copies the values onto a new slice.

func (*Machine) PopExpr

func (m *Machine) PopExpr() Expr

func (*Machine) PopFrame

func (m *Machine) PopFrame() Frame

func (*Machine) PopFrameAndReset

func (m *Machine) PopFrameAndReset()

func (*Machine) PopFrameAndReturn

func (m *Machine) PopFrameAndReturn()

TODO: optimize by passing in last frame.

func (*Machine) PopOp

func (m *Machine) PopOp() Op

func (*Machine) PopResults

func (m *Machine) PopResults()

Decrements NumValues by number of last results.

func (*Machine) PopStmt

func (m *Machine) PopStmt() Stmt

func (*Machine) PopUntilLastCallFrame

func (m *Machine) PopUntilLastCallFrame() *Frame

pops the last non-call (loop) frames and returns the last call frame (which is left on stack).

func (*Machine) PopValue

func (m *Machine) PopValue() (tv *TypedValue)

Resulting reference is volatile.

func (*Machine) PopValues

func (m *Machine) PopValues(n int) []TypedValue

Returns a slice of n values in the stack and decrements NumValues. NOTE: The results are on the values stack, so they must be copied or used immediately. If you need to use the machine before or during usage, consider using PopCopyValues(). NOTE: the values are in stack order, oldest first, the opposite order of multiple pop calls. This is used for params assignment, for example.

func (*Machine) PreprocessAllFilesAndSaveBlockNodes

func (m *Machine) PreprocessAllFilesAndSaveBlockNodes()

Upon restart, preprocess all MemPackage and save blocknodes. This is a temporary measure until we optimize/make-lazy.

NOTE: package paths not beginning with gno.land will be allowed to override, to support cases of stdlibs processed through [RunMemPackagesWithOverrides].

func (*Machine) Printf

func (m *Machine) Printf(format string, args ...interface{})

func (*Machine) Println

func (m *Machine) Println(args ...interface{})

func (*Machine) PushBlock

func (m *Machine) PushBlock(b *Block)

func (*Machine) PushExpr

func (m *Machine) PushExpr(x Expr)

func (*Machine) PushForPointer

func (m *Machine) PushForPointer(lx Expr)

func (*Machine) PushFrameBasic

func (m *Machine) PushFrameBasic(s Stmt)

Pushes a frame with one less statement.

func (*Machine) PushFrameCall

func (m *Machine) PushFrameCall(cx *CallExpr, fv *FuncValue, recv TypedValue)

TODO: track breaks/panics/returns on frame and ensure the counts are consistent, otherwise we mask bugs with frame pops.

func (*Machine) PushFrameGoNative

func (m *Machine) PushFrameGoNative(cx *CallExpr, fv *NativeValue)

func (*Machine) PushOp

func (m *Machine) PushOp(op Op)

func (*Machine) PushStmt

func (m *Machine) PushStmt(s Stmt)

func (*Machine) PushStmts

func (m *Machine) PushStmts(ss ...Stmt)

func (*Machine) PushValue

func (m *Machine) PushValue(tv TypedValue)

func (*Machine) ReapValues

func (m *Machine) ReapValues(start int) []TypedValue

Pops values with index start or greater.

func (*Machine) Release

func (m *Machine) Release()

Release resets some of the values of *Machine and puts back m into the machine pool; for this reason, Release() should be called as a finalizer, and m should not be used after this call. Only Machines initialized with this package's constructors should be released.

func (*Machine) Run

func (m *Machine) Run()

func (*Machine) RunDeclaration

func (m *Machine) RunDeclaration(d Decl)

Runs a declaration after preprocessing d. If d was already preprocessed, call runDeclaration() instead. This function is primarily for testing, so no blocknodes are saved to store, and declarations are not realm compatible. NOTE: to support realm persistence of types, must first require the validation of blocknode locations.

func (*Machine) RunFiles

func (m *Machine) RunFiles(fns ...*FileNode)

Convenience for tests. Production must not use this, because realm package init must happen after persistence and realm finalization, then changes from init persisted again.

func (*Machine) RunFunc

func (m *Machine) RunFunc(fn Name)

func (*Machine) RunMain

func (m *Machine) RunMain()

func (*Machine) RunMemPackage

func (m *Machine) RunMemPackage(memPkg *gnovm.MemPackage, save bool) (*PackageNode, *PackageValue)

Parses files, sets the package if doesn't exist, runs files, saves mempkg and corresponding package node, package value, and types to store. Save is set to false for tests where package values may be native.

func (*Machine) RunMemPackageWithOverrides

func (m *Machine) RunMemPackageWithOverrides(memPkg *gnovm.MemPackage, save bool) (*PackageNode, *PackageValue)

RunMemPackageWithOverrides works as [RunMemPackage], however after parsing, declarations are filtered removing duplicate declarations. To control which declaration overrides which, use ReadMemPackageFromList, putting the overrides at the top of the list.

func (*Machine) RunStatement

func (m *Machine) RunStatement(s Stmt)

func (*Machine) SetActivePackage

func (m *Machine) SetActivePackage(pv *PackageValue)

func (*Machine) Stacktrace

func (m *Machine) Stacktrace() (stacktrace Stacktrace)

Stacktrace returns the stack trace of the machine. It collects the executions and frames from the machine's frames and statements.

func (*Machine) String

func (m *Machine) String() string

type MachineOptions

type MachineOptions struct {
	// Active package of the given machine; must be set before execution.
	PkgPath          string
	PreprocessorMode bool
	ReadOnly         bool
	Debug            bool
	Input            io.Reader // used for default debugger input only
	Output           io.Writer // default os.Stdout
	Store            Store     // default NewStore(Alloc, nil, nil)
	Context          interface{}
	Alloc            *Allocator // or see MaxAllocBytes.
	MaxAllocBytes    int64      // or 0 for no limit.
	MaxCycles        int64      // or 0 for no limit.
	GasMeter         store.GasMeter
}

MachineOptions is used to pass options to NewMachineWithOptions.

type MapKey

type MapKey string

type MapList

type MapList struct {
	Head *MapListItem
	Tail *MapListItem
	Size int
}

func (*MapList) Append

func (ml *MapList) Append(alloc *Allocator, key TypedValue) *MapListItem

NOTE: Value is undefined until assigned.

func (MapList) MarshalAmino

func (ml MapList) MarshalAmino() (MapListImage, error)

func (*MapList) Remove

func (ml *MapList) Remove(mli *MapListItem)

func (*MapList) UnmarshalAmino

func (ml *MapList) UnmarshalAmino(mlimg MapListImage) error

type MapListImage

type MapListImage struct {
	List []*MapListItem
}

type MapListItem

type MapListItem struct {
	Prev  *MapListItem `json:"-"`
	Next  *MapListItem `json:"-"`
	Key   TypedValue
	Value TypedValue
}

type MapType

type MapType struct {
	Key   Type
	Value Type
	// contains filtered or unexported fields
}

func (*MapType) Elem

func (mt *MapType) Elem() Type

func (*MapType) GetPkgPath

func (mt *MapType) GetPkgPath() string

func (*MapType) IsNamed

func (mt *MapType) IsNamed() bool

func (*MapType) Kind

func (mt *MapType) Kind() Kind

func (*MapType) String

func (mt *MapType) String() string

func (*MapType) TypeID

func (mt *MapType) TypeID() TypeID

type MapTypeExpr

type MapTypeExpr struct {
	Attributes
	Key   Expr // const
	Value Expr // value type
}

func MapT

func MapT(key, value interface{}) *MapTypeExpr

func (*MapTypeExpr) Copy

func (x *MapTypeExpr) Copy() Node

func (MapTypeExpr) String

func (x MapTypeExpr) String() string

type MapValue

type MapValue struct {
	ObjectInfo
	List *MapList
	// contains filtered or unexported fields
}

func (*MapValue) DeleteForKey

func (mv *MapValue) DeleteForKey(store Store, key *TypedValue)

func (*MapValue) GetLength

func (mv *MapValue) GetLength() int

func (*MapValue) GetPointerForKey

func (mv *MapValue) GetPointerForKey(alloc *Allocator, store Store, key *TypedValue) PointerValue

NOTE: Go doesn't support referencing into maps, and maybe Gno will, but here we just use this method signature as we do for structs and arrays for assigning new entries. If key doesn't exist, a new slot is created.

func (*MapValue) GetValueForKey

func (mv *MapValue) GetValueForKey(store Store, key *TypedValue) (val TypedValue, ok bool)

Like GetPointerForKey, but does not create a slot if key doesn't exist.

func (*MapValue) MakeMap

func (mv *MapValue) MakeMap(c int)

func (*MapValue) ProtectedString

func (mv *MapValue) ProtectedString(seen *seenValues) string

func (*MapValue) String

func (mv *MapValue) String() string

type MaybeNativeType

type MaybeNativeType struct {
	Type
}

MaybeNativeType wraps an underlying gno type and allows the generic matching of spec to gno type, or go2GnoType2(spec) to gno type if spec is native.

func (MaybeNativeType) Elem

func (mn MaybeNativeType) Elem() Type

func (MaybeNativeType) GetPkgPath

func (mn MaybeNativeType) GetPkgPath() string

func (MaybeNativeType) IsNamed

func (mn MaybeNativeType) IsNamed() bool

func (MaybeNativeType) Kind

func (mn MaybeNativeType) Kind() Kind

func (MaybeNativeType) String

func (mn MaybeNativeType) String() string

func (MaybeNativeType) TypeID

func (mn MaybeNativeType) TypeID() TypeID

type MaybeNativeTypeExpr

type MaybeNativeTypeExpr struct {
	Attributes
	Type Expr
}

Only used for native func arguments

func MaybeNativeT

func MaybeNativeT(tx interface{}) *MaybeNativeTypeExpr

func (*MaybeNativeTypeExpr) Copy

func (x *MaybeNativeTypeExpr) Copy() Node

func (MaybeNativeTypeExpr) String

func (x MaybeNativeTypeExpr) String() string

type MemPackageGetter

type MemPackageGetter interface {
	GetMemPackage(path string) *gnovm.MemPackage
}

MemPackageGetter implements the GetMemPackage() method. It is a subset of Store, separated for ease of testing.

type Name

type Name string

func N

func N(n interface{}) Name

func PackageNameFromFileBody

func PackageNameFromFileBody(name, body string) Name

PackageNameFromFileBody extracts the package name from the given Gno code body. The 'name' parameter is used for better error traces, and 'body' contains the Gno code.

type NameExpr

type NameExpr struct {
	Attributes
	// TODO rename .Path's to .ValuePaths.
	Path ValuePath // set by preprocessor.
	Name
	Type NameExprType
}

func Nx

func Nx(n interface{}) *NameExpr

func (*NameExpr) Copy

func (x *NameExpr) Copy() Node

func (NameExpr) String

func (x NameExpr) String() string

type NameExprType

type NameExprType int
const (
	NameExprTypeNormal      NameExprType = iota // default
	NameExprTypeDefine                          // when defining normally
	NameExprTypeHeapDefine                      // when defining escaped name in loop
	NameExprTypeHeapUse                         // when above used in non-define lhs/rhs
	NameExprTypeHeapClosure                     // when closure captures name
)

type NameExprs

type NameExprs []NameExpr

func (NameExprs) String

func (nxs NameExprs) String() string

type NativeStore

type NativeStore func(pkgName string, name Name) func(m *Machine)

NativeStore is a function which can retrieve native bodies of native functions.

type NativeType

type NativeType struct {
	Type reflect.Type // Go "native" type
	// contains filtered or unexported fields
}

func (*NativeType) Elem

func (nt *NativeType) Elem() Type

TODO: memoize?

func (*NativeType) FindEmbeddedFieldType

func (nt *NativeType) FindEmbeddedFieldType(n Name, m map[Type]struct{}) (
	trail []ValuePath, hasPtr bool, rcvr Type, field Type, accessError bool,
)

TODO implement accessError return value.

func (*NativeType) GetPkgPath

func (nt *NativeType) GetPkgPath() string

func (*NativeType) GnoType

func (nt *NativeType) GnoType(store Store) Type

func (*NativeType) IsNamed

func (nt *NativeType) IsNamed() bool

func (*NativeType) Key

func (nt *NativeType) Key() Type

TODO: memoize?

func (*NativeType) Kind

func (nt *NativeType) Kind() Kind

func (*NativeType) String

func (nt *NativeType) String() string

func (*NativeType) TypeID

func (nt *NativeType) TypeID() TypeID

type NativeValue

type NativeValue struct {
	Value reflect.Value `json:"-"`
	Bytes []byte        // XXX is this used?
}

func (*NativeValue) Copy

func (nv *NativeValue) Copy(alloc *Allocator) *NativeValue

func (*NativeValue) String

func (nv *NativeValue) String() string

type Node

type Node interface {
	String() string
	Copy() Node
	GetLine() int
	SetLine(int)
	GetColumn() int
	SetColumn(int)
	GetLabel() Name
	SetLabel(Name)
	HasAttribute(key GnoAttribute) bool
	GetAttribute(key GnoAttribute) interface{}
	SetAttribute(key GnoAttribute, value interface{})
	DelAttribute(key GnoAttribute)
	// contains filtered or unexported methods
}

func Go2Gno

func Go2Gno(fs *token.FileSet, gon ast.Node) (n Node)

If gon is a *ast.File, the name must be filled later.

func Preprocess

func Preprocess(store Store, ctx BlockNode, n Node) Node

Preprocess n whose parent block node is ctx. If any names are defined in another file, generally you must call PredefineFileSet() on the whole fileset first before calling Preprocess.

The ctx passed in may be mutated if there are any statements or declarations. The file or package which contains ctx may be mutated if there are any file-level declarations.

Store is used to load external package values, but otherwise the package and newly created blocks/values are expected to be non-RefValues -- in some cases, nil is passed for store to enforce this.

List of what Preprocess() does:

  • Assigns BlockValuePath to NameExprs.
  • TODO document what it does.

func Transcribe

func Transcribe(n Node, t Transform) (nn Node)

n MUST be a pointer to a node struct. returns the transcribe code returned for n. returns new node nn to replace n.

type Object

type Object interface {
	Value
	GetObjectInfo() *ObjectInfo
	GetObjectID() ObjectID
	MustGetObjectID() ObjectID
	SetObjectID(oid ObjectID)
	GetHash() ValueHash
	SetHash(ValueHash)
	GetOwner() Object
	GetOwnerID() ObjectID
	SetOwner(Object)
	GetIsOwned() bool
	// GetIsReal determines the reality of an Object.
	// During a transaction, the object is fake, but becomes real upon successful completion, making it persisted and verifiable.
	// This concept reflects a metaphysical understanding, where proof and persistence define an object's reality.
	GetIsReal() bool
	GetModTime() uint64
	IncRefCount() int
	DecRefCount() int
	GetRefCount() int
	GetIsDirty() bool
	SetIsDirty(bool, uint64)
	GetIsEscaped() bool
	SetIsEscaped(bool)
	GetIsDeleted() bool
	SetIsDeleted(bool, uint64)
	GetIsNewReal() bool
	SetIsNewReal(bool)
	GetIsNewEscaped() bool
	SetIsNewEscaped(bool)
	GetIsNewDeleted() bool
	SetIsNewDeleted(bool)
	GetIsTransient() bool
}

type ObjectID

type ObjectID struct {
	PkgID   PkgID  // base
	NewTime uint64 // time created
}

func ObjectIDFromPkgID

func ObjectIDFromPkgID(pkgID PkgID) ObjectID

Returns the ObjectID of the PackageValue associated with pkgID.

func ObjectIDFromPkgPath

func ObjectIDFromPkgPath(path string) ObjectID

Returns the ObjectID of the PackageValue associated with path.

func (ObjectID) IsZero

func (oid ObjectID) IsZero() bool

TODO: make faster by making PkgID a pointer and enforcing that the value of PkgID is never zero.

func (ObjectID) MarshalAmino

func (oid ObjectID) MarshalAmino() (string, error)

func (ObjectID) String

func (oid ObjectID) String() string

func (*ObjectID) UnmarshalAmino

func (oid *ObjectID) UnmarshalAmino(oids string) error

type ObjectInfo

type ObjectInfo struct {
	ID        ObjectID  // set if real.
	Hash      ValueHash `json:",omitempty"` // zero if dirty.
	OwnerID   ObjectID  `json:",omitempty"` // parent in the ownership tree.
	ModTime   uint64    // time last updated.
	RefCount  int       // for persistence. deleted/gc'd if 0.
	IsEscaped bool      `json:",omitempty"` // hash in iavl.
	// contains filtered or unexported fields
}

func (*ObjectInfo) Copy

func (oi *ObjectInfo) Copy() ObjectInfo

Copy used for serialization of objects. Note that "owner" is nil.

func (*ObjectInfo) DecRefCount

func (oi *ObjectInfo) DecRefCount() int

func (*ObjectInfo) GetHash

func (oi *ObjectInfo) GetHash() ValueHash

func (*ObjectInfo) GetIsDeleted

func (oi *ObjectInfo) GetIsDeleted() bool

func (*ObjectInfo) GetIsDirty

func (oi *ObjectInfo) GetIsDirty() bool

func (*ObjectInfo) GetIsEscaped

func (oi *ObjectInfo) GetIsEscaped() bool

func (*ObjectInfo) GetIsNewDeleted

func (oi *ObjectInfo) GetIsNewDeleted() bool

func (*ObjectInfo) GetIsNewEscaped

func (oi *ObjectInfo) GetIsNewEscaped() bool

func (*ObjectInfo) GetIsNewReal

func (oi *ObjectInfo) GetIsNewReal() bool

func (*ObjectInfo) GetIsOwned

func (oi *ObjectInfo) GetIsOwned() bool

func (*ObjectInfo) GetIsReal

func (oi *ObjectInfo) GetIsReal() bool

NOTE: does not return true for new reals.

func (*ObjectInfo) GetIsTransient

func (oi *ObjectInfo) GetIsTransient() bool

func (*ObjectInfo) GetModTime

func (oi *ObjectInfo) GetModTime() uint64

func (*ObjectInfo) GetObjectID

func (oi *ObjectInfo) GetObjectID() ObjectID

func (*ObjectInfo) GetObjectInfo

func (oi *ObjectInfo) GetObjectInfo() *ObjectInfo

func (*ObjectInfo) GetOwner

func (oi *ObjectInfo) GetOwner() Object

func (*ObjectInfo) GetOwnerID

func (oi *ObjectInfo) GetOwnerID() ObjectID

func (*ObjectInfo) GetRefCount

func (oi *ObjectInfo) GetRefCount() int

func (*ObjectInfo) IncRefCount

func (oi *ObjectInfo) IncRefCount() int

func (*ObjectInfo) MustGetObjectID

func (oi *ObjectInfo) MustGetObjectID() ObjectID

func (*ObjectInfo) SetHash

func (oi *ObjectInfo) SetHash(vh ValueHash)

func (*ObjectInfo) SetIsDeleted

func (oi *ObjectInfo) SetIsDeleted(x bool, mt uint64)

func (*ObjectInfo) SetIsDirty

func (oi *ObjectInfo) SetIsDirty(x bool, mt uint64)

func (*ObjectInfo) SetIsEscaped

func (oi *ObjectInfo) SetIsEscaped(x bool)

func (*ObjectInfo) SetIsNewDeleted

func (oi *ObjectInfo) SetIsNewDeleted(x bool)

func (*ObjectInfo) SetIsNewEscaped

func (oi *ObjectInfo) SetIsNewEscaped(x bool)

func (*ObjectInfo) SetIsNewReal

func (oi *ObjectInfo) SetIsNewReal(x bool)

func (*ObjectInfo) SetObjectID

func (oi *ObjectInfo) SetObjectID(oid ObjectID)

func (*ObjectInfo) SetOwner

func (oi *ObjectInfo) SetOwner(po Object)

func (*ObjectInfo) String

func (oi *ObjectInfo) String() string

type Op

type Op uint8
const (

	/* Control operators */
	OpInvalid             Op = 0x00 // invalid
	OpHalt                Op = 0x01 // halt (e.g. last statement)
	OpNoop                Op = 0x02 // no-op
	OpExec                Op = 0x03 // exec next statement
	OpPrecall             Op = 0x04 // sets X (func) to frame
	OpCall                Op = 0x05 // call(Frame.Func, [...])
	OpCallNativeBody      Op = 0x06 // call body is native
	OpReturn              Op = 0x07 // return ...
	OpReturnFromBlock     Op = 0x08 // return results (after defers)
	OpReturnToBlock       Op = 0x09 // copy results to block (before defer)
	OpDefer               Op = 0x0A // defer call(X, [...])
	OpCallDeferNativeBody Op = 0x0B // call body is native
	OpGo                  Op = 0x0C // go call(X, [...])
	OpSelect              Op = 0x0D // exec next select case
	OpSwitchClause        Op = 0x0E // exec next switch clause
	OpSwitchClauseCase    Op = 0x0F // exec next switch clause case
	OpTypeSwitch          Op = 0x10 // exec type switch clauses (all)
	OpIfCond              Op = 0x11 // eval cond
	OpPopValue            Op = 0x12 // pop X
	OpPopResults          Op = 0x13 // pop n call results
	OpPopBlock            Op = 0x14 // pop block NOTE breaks certain invariants.
	OpPopFrameAndReset    Op = 0x15 // pop frame and reset.
	OpPanic1              Op = 0x16 // pop exception and pop call frames.
	OpPanic2              Op = 0x17 // pop call frames.

	/* Unary & binary operators */
	OpUpos  Op = 0x20 // + (unary)
	OpUneg  Op = 0x21 // - (unary)
	OpUnot  Op = 0x22 // ! (unary)
	OpUxor  Op = 0x23 // ^ (unary)
	OpUrecv Op = 0x25 // <- (unary) // TODO make expr
	OpLor   Op = 0x26 // ||
	OpLand  Op = 0x27 // &&
	OpEql   Op = 0x28 // ==
	OpNeq   Op = 0x29 // !=
	OpLss   Op = 0x2A // <
	OpLeq   Op = 0x2B // <=
	OpGtr   Op = 0x2C // >
	OpGeq   Op = 0x2D // >=
	OpAdd   Op = 0x2E // +
	OpSub   Op = 0x2F // -
	OpBor   Op = 0x30 // |
	OpXor   Op = 0x31 // ^
	OpMul   Op = 0x32 // *
	OpQuo   Op = 0x33 // /
	OpRem   Op = 0x34 // %
	OpShl   Op = 0x35 // <<
	OpShr   Op = 0x36 // >>
	OpBand  Op = 0x37 // &
	OpBandn Op = 0x38 // &^

	/* Other expression operators */
	OpEval         Op = 0x40 // eval next expression
	OpBinary1      Op = 0x41 // X op ?
	OpIndex1       Op = 0x42 // X[Y]
	OpIndex2       Op = 0x43 // (_, ok :=) X[Y]
	OpSelector     Op = 0x44 // X.Y
	OpSlice        Op = 0x45 // X[Low:High:Max]
	OpStar         Op = 0x46 // *X (deref or pointer-to)
	OpRef          Op = 0x47 // &X
	OpTypeAssert1  Op = 0x48 // X.(Type)
	OpTypeAssert2  Op = 0x49 // (_, ok :=) X.(Type)
	OpStaticTypeOf Op = 0x4A // static type of X
	OpCompositeLit Op = 0x4B // X{???}
	OpArrayLit     Op = 0x4C // [Len]{...}
	OpSliceLit     Op = 0x4D // []{value,...}
	OpSliceLit2    Op = 0x4E // []{key:value,...}
	OpMapLit       Op = 0x4F // X{...}
	OpStructLit    Op = 0x50 // X{...}
	OpFuncLit      Op = 0x51 // func(T){Body}
	OpConvert      Op = 0x52 // Y(X)

	/* Native operators */
	OpArrayLitGoNative  Op = 0x60
	OpSliceLitGoNative  Op = 0x61
	OpStructLitGoNative Op = 0x62
	OpCallGoNative      Op = 0x63

	/* Type operators */
	OpFieldType       Op = 0x70 // Name: X `tag`
	OpArrayType       Op = 0x71 // [X]Y{}
	OpSliceType       Op = 0x72 // []X{}
	OpPointerType     Op = 0x73 // *X
	OpInterfaceType   Op = 0x74 // interface{...}
	OpChanType        Op = 0x75 // [<-]chan[<-]X
	OpFuncType        Op = 0x76 // func(params...)results...
	OpMapType         Op = 0x77 // map[X]Y
	OpStructType      Op = 0x78 // struct{...}
	OpMaybeNativeType Op = 0x79 // maybenative{X}

	/* Statement operators */
	OpAssign      Op = 0x80 // Lhs = Rhs
	OpAddAssign   Op = 0x81 // Lhs += Rhs
	OpSubAssign   Op = 0x82 // Lhs -= Rhs
	OpMulAssign   Op = 0x83 // Lhs *= Rhs
	OpQuoAssign   Op = 0x84 // Lhs /= Rhs
	OpRemAssign   Op = 0x85 // Lhs %= Rhs
	OpBandAssign  Op = 0x86 // Lhs &= Rhs
	OpBandnAssign Op = 0x87 // Lhs &^= Rhs
	OpBorAssign   Op = 0x88 // Lhs |= Rhs
	OpXorAssign   Op = 0x89 // Lhs ^= Rhs
	OpShlAssign   Op = 0x8A // Lhs <<= Rhs
	OpShrAssign   Op = 0x8B // Lhs >>= Rhs
	OpDefine      Op = 0x8C // X... := Y...
	OpInc         Op = 0x8D // X++
	OpDec         Op = 0x8E // X--

	/* Decl operators */
	OpValueDecl Op = 0x90 // var/const ...
	OpTypeDecl  Op = 0x91 // type ...

	/* Loop (sticky) operators (>= 0xD0) */
	OpSticky            Op = 0xD0 // not a real op.
	OpBody              Op = 0xD1 // if/block/switch/select.
	OpForLoop           Op = 0xD2
	OpRangeIter         Op = 0xD3
	OpRangeIterString   Op = 0xD4
	OpRangeIterMap      Op = 0xD5
	OpRangeIterArrayPtr Op = 0xD6
	OpReturnCallDefers  Op = 0xD7 // TODO rename?
)

func (Op) String

func (i Op) String() string

type PackageGetter

type PackageGetter func(pkgPath string, store Store) (*PackageNode, *PackageValue)

PackageGetter specifies how the store may retrieve packages which are not already in its cache. PackageGetter should return nil when the requested package does not exist. store should be used to run the machine, or otherwise call any methods which may call store.GetPackage; avoid using any "global" store as the one passed to the PackageGetter may be a fork of that (ie. the original is not meant to be written to). Loading dependencies may cause writes to happen to the store, such as MemPackages to iavlstore.

type PackageNode

type PackageNode struct {
	Attributes
	StaticBlock
	PkgPath string
	PkgName Name
	*FileSet
}

func NewPackageNode

func NewPackageNode(name Name, path string, fset *FileSet) *PackageNode

func UverseNode

func UverseNode() *PackageNode

UverseNode returns the uverse PackageNode. If called while initializing the UverseNode itself, it will return an empty PackageNode.

func (*PackageNode) Copy

func (x *PackageNode) Copy() Node

func (*PackageNode) DefineGoNativeConstValue

func (x *PackageNode) DefineGoNativeConstValue(name Name, nv interface{})

func (*PackageNode) DefineGoNativeValue

func (x *PackageNode) DefineGoNativeValue(name Name, nv interface{})

func (*PackageNode) DefineNative

func (x *PackageNode) DefineNative(n Name, ps, rs FieldTypeExprs, native func(*Machine))

DefineNativeFunc defines a native function. This is not the same as DefineGoNativeValue, which DOES NOT give access to the running machine.

func (*PackageNode) DefineNativeOverride

func (x *PackageNode) DefineNativeOverride(n Name, native func(*Machine))

Same as DefineNative but allow the overriding of previously defined natives. For example, overriding a native function defined in stdlibs/stdlibs for testing. Caller must ensure that the function type is identical.

func (*PackageNode) GetBody

func (x *PackageNode) GetBody() Body

func (*PackageNode) NewPackage

func (x *PackageNode) NewPackage() *PackageValue

func (*PackageNode) PrepareNewValues

func (x *PackageNode) PrepareNewValues(pv *PackageValue) []TypedValue

Prepares new func values (e.g. by attaching the proper file block closure). Returns a slice of new PackageValue.Values. After return, *PackageNode.Values and *PackageValue.Values have the same length. NOTE: declared methods do not get their closures set here. See *DeclaredType.GetValueAt() which returns a filled copy.

func (*PackageNode) SetBody

func (x *PackageNode) SetBody(b Body)

func (PackageNode) String

func (x PackageNode) String() string

type PackageType

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

func (*PackageType) Elem

func (pt *PackageType) Elem() Type

func (*PackageType) GetPkgPath

func (pt *PackageType) GetPkgPath() string

func (*PackageType) IsNamed

func (pt *PackageType) IsNamed() bool

func (*PackageType) Kind

func (pt *PackageType) Kind() Kind

func (*PackageType) String

func (pt *PackageType) String() string

func (*PackageType) TypeID

func (pt *PackageType) TypeID() TypeID

type PackageValue

type PackageValue struct {
	ObjectInfo // is a separate object from .Block.
	Block      Value
	PkgName    Name
	PkgPath    string
	FNames     []Name
	FBlocks    []Value
	Realm      *Realm `json:"-"` // if IsRealmPath(PkgPath), otherwise nil.
	// contains filtered or unexported fields
}

func Uverse

func Uverse() *PackageValue

UverseNode returns the uverse PackageValue. If called while initializing the UverseNode itself, it will return an empty PackageValue.

func (*PackageValue) AddFileBlock

func (pv *PackageValue) AddFileBlock(fn Name, fb *Block)

func (*PackageValue) GetBlock

func (pv *PackageValue) GetBlock(store Store) *Block

func (*PackageValue) GetFileBlock

func (pv *PackageValue) GetFileBlock(store Store, fname Name) *Block

func (*PackageValue) GetPackageNode

func (pv *PackageValue) GetPackageNode(store Store) *PackageNode

Convenience.

func (*PackageValue) GetPkgAddr

func (pv *PackageValue) GetPkgAddr() crypto.Address

Convenience

func (*PackageValue) GetRealm

func (pv *PackageValue) GetRealm() *Realm

func (*PackageValue) GetValueAt

func (pv *PackageValue) GetValueAt(store Store, path ValuePath) TypedValue

func (*PackageValue) IsRealm

func (pv *PackageValue) IsRealm() bool

IsRealm returns true if pv represents a realm.

func (*PackageValue) SetRealm

func (pv *PackageValue) SetRealm(rlm *Realm)

func (*PackageValue) String

func (pv *PackageValue) String() string

type PanicStmt

type PanicStmt struct {
	Attributes
	Exception Expr // panic expression; not nil
}

func (*PanicStmt) Copy

func (x *PanicStmt) Copy() Node

func (PanicStmt) String

func (x PanicStmt) String() string

type PkgID

type PkgID struct {
	Hashlet
}

func PkgIDFromPkgPath

func PkgIDFromPkgPath(path string) PkgID

func (PkgID) Bytes

func (pid PkgID) Bytes() []byte

func (PkgID) MarshalAmino

func (pid PkgID) MarshalAmino() (string, error)

func (PkgID) String

func (pid PkgID) String() string

func (*PkgID) UnmarshalAmino

func (pid *PkgID) UnmarshalAmino(h string) error

type PointerType

type PointerType struct {
	Elt Type
	// contains filtered or unexported fields
}

func (*PointerType) Elem

func (pt *PointerType) Elem() Type

func (*PointerType) FindEmbeddedFieldType

func (pt *PointerType) FindEmbeddedFieldType(callerPath string, n Name, m map[Type]struct{}) (
	trail []ValuePath, hasPtr bool, rcvr Type, field Type, accessError bool,
)

func (*PointerType) GetPkgPath

func (pt *PointerType) GetPkgPath() string

func (*PointerType) IsNamed

func (pt *PointerType) IsNamed() bool

func (*PointerType) Kind

func (pt *PointerType) Kind() Kind

func (*PointerType) String

func (pt *PointerType) String() string

func (*PointerType) TypeID

func (pt *PointerType) TypeID() TypeID

type PointerValue

type PointerValue struct {
	TV    *TypedValue // escape val if pointer to var.
	Base  Value       // array/struct/block, or heapitem.
	Index int         // list/fields/values index, or -1 or -2 (see below).
	Key   *TypedValue `json:",omitempty"` // for maps.
}

Base is set if the pointer refers to an array index or struct field or block var. A pointer constructed via a &x{} composite lit expression or constructed via new() or make() are independent objects, and have nil Base. A pointer to a block var may end up pointing to an escape value after a block var escapes "to the heap". *(PointerValue.TypedValue) must have already become initialized, namely T set if a typed-nil. Index is -1 for the shared "_" block var, and -2 for (gno and native) map items.

A pointer constructed via a &x{} composite lit expression or constructed via new() or make() will have a virtual HeapItemValue as base.

Allocation for PointerValue is not immediate, as usually PointerValues are temporary for assignment or binary operations. When a pointer is to be allocated, *Allocator.AllocatePointer() is called separately, as in OpRef.

Since PointerValue is used internally for assignment etc, it MUST stay minimal for computational efficiency.

func (PointerValue) Assign2

func (pv PointerValue) Assign2(alloc *Allocator, store Store, rlm *Realm, tv2 TypedValue, cu bool)

cu: convert untyped; pass false for const definitions TODO: document as something that enables into-native assignment. TODO: maybe consider this as entrypoint for DataByteValue too?

func (PointerValue) Deref

func (pv PointerValue) Deref() (tv TypedValue)

func (*PointerValue) GetBase

func (pv *PointerValue) GetBase(store Store) Object

func (PointerValue) ProtectedString

func (pv PointerValue) ProtectedString(seen *seenValues) string

func (PointerValue) String

func (pv PointerValue) String() string

type PreprocessError

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

PreprocessError wraps a processing error along with its associated preprocessing stack for enhanced error reporting.

func (*PreprocessError) Error

func (p *PreprocessError) Error() string

Error consolidates and returns the full error message, including the actual error followed by its associated preprocessing stack.

func (*PreprocessError) Stack

func (p *PreprocessError) Stack() string

Stack produces a string representation of the preprocessing stack trace that was associated with the error occurrence.

func (*PreprocessError) Unwrap

func (p *PreprocessError) Unwrap() error

Unwrap returns the encapsulated error message.

type PrimitiveType

type PrimitiveType int
const (
	InvalidType PrimitiveType = 1 << iota
	UntypedBoolType
	BoolType
	UntypedStringType
	StringType
	IntType
	Int8Type
	Int16Type
	UntypedRuneType
	Int32Type
	Int64Type
	UintType
	Uint8Type
	DataByteType
	Uint16Type
	Uint32Type
	Uint64Type
	Float32Type
	Float64Type
	UntypedBigintType
	BigintType
	UntypedBigdecType
	BigdecType
)

func (PrimitiveType) Elem

func (pt PrimitiveType) Elem() Type

func (PrimitiveType) GetPkgPath

func (pt PrimitiveType) GetPkgPath() string

func (PrimitiveType) IsNamed

func (pt PrimitiveType) IsNamed() bool

func (PrimitiveType) Kind

func (pt PrimitiveType) Kind() Kind

func (PrimitiveType) Specificity

func (pt PrimitiveType) Specificity() int

Used for converting constant binary expressions. Smaller number means more specific. Spec: "If the untyped operands of a binary operation (other than a shift) are of different kinds, the result is of the operand's kind that appears later in this list: integer, rune, floating-point, complex. For example, an untyped integer constant divided by an untyped complex constant yields an untyped complex constant."

func (PrimitiveType) String

func (pt PrimitiveType) String() string

func (PrimitiveType) TypeID

func (pt PrimitiveType) TypeID() TypeID

type RangeStmt

type RangeStmt struct {
	Attributes
	StaticBlock
	X          Expr // value to range over
	Key, Value Expr // Key, Value may be nil
	Op         Word // ASSIGN or DEFINE
	Body
	IsMap      bool // if X is map type
	IsString   bool // if X is string type
	IsArrayPtr bool // if X is array-pointer type
}

func (*RangeStmt) AssertCompatible

func (x *RangeStmt) AssertCompatible(store Store, last BlockNode)

func (*RangeStmt) Copy

func (x *RangeStmt) Copy() Node

func (RangeStmt) String

func (x RangeStmt) String() string

type Realm

type Realm struct {
	ID   PkgID
	Path string
	Time uint64
	// contains filtered or unexported fields
}

NOTE: A nil realm is special and has limited functionality; enough to support methods that don't require persistence. This is the default realm when a machine starts with a non-realm package.

func NewRealm

func NewRealm(path string) *Realm

Creates a blank new realm with counter 0.

func (*Realm) DidUpdate

func (rlm *Realm) DidUpdate(po, xo, co Object)

po's old elem value is xo, will become co. po, xo, and co may each be nil. if rlm or po is nil, do nothing. xo or co is nil if the element value is undefined or has no associated object.

func (*Realm) FinalizeRealmTransaction

func (rlm *Realm) FinalizeRealmTransaction(readonly bool, store Store)

OpReturn calls this when exiting a realm transaction.

func (*Realm) MarkDirty

func (rlm *Realm) MarkDirty(oo Object)

func (*Realm) MarkNewDeleted

func (rlm *Realm) MarkNewDeleted(oo Object)

func (*Realm) MarkNewEscaped

func (rlm *Realm) MarkNewEscaped(oo Object)

func (*Realm) MarkNewReal

func (rlm *Realm) MarkNewReal(oo Object)

func (*Realm) String

func (rlm *Realm) String() string

type RefExpr

type RefExpr struct {
	Attributes
	X Expr // operand
}

func Ref

func Ref(x interface{}) *RefExpr

func (*RefExpr) Copy

func (x *RefExpr) Copy() Node

func (RefExpr) String

func (x RefExpr) String() string

type RefNode

type RefNode struct {
	Location  Location // location of node.
	BlockNode          // convenience to implement BlockNode (nil).
}

Reference to a node by its location.

func (RefNode) GetLocation

func (rn RefNode) GetLocation() Location

func (RefNode) String

func (rn RefNode) String() string

type RefType

type RefType struct {
	ID TypeID
}

func (RefType) Elem

func (rt RefType) Elem() Type

func (RefType) GetPkgPath

func (rt RefType) GetPkgPath() string

func (RefType) IsNamed

func (rt RefType) IsNamed() bool

func (RefType) Kind

func (RefType) Kind() Kind

func (RefType) String

func (rt RefType) String() string

func (RefType) TypeID

func (rt RefType) TypeID() TypeID

type RefValue

type RefValue struct {
	ObjectID ObjectID  `json:",omitempty"`
	Escaped  bool      `json:",omitempty"`
	PkgPath  string    `json:",omitempty"`
	Hash     ValueHash `json:",omitempty"`
}

NOTE: RefValue Object methods declared in ownership.go

func (RefValue) String

func (v RefValue) String() string

type ReturnStmt

type ReturnStmt struct {
	Attributes
	Results Exprs // result expressions; or nil
}

func Return

func Return(results ...Expr) *ReturnStmt

func (*ReturnStmt) Copy

func (x *ReturnStmt) Copy() Node

func (ReturnStmt) String

func (x ReturnStmt) String() string

type SelectCaseStmt

type SelectCaseStmt struct {
	Attributes
	StaticBlock
	Comm Stmt // send or receive statement; nil means default case
	Body
}

func (*SelectCaseStmt) Copy

func (x *SelectCaseStmt) Copy() Node

func (SelectCaseStmt) String

func (x SelectCaseStmt) String() string

type SelectStmt

type SelectStmt struct {
	Attributes
	Cases []SelectCaseStmt
}

func (*SelectStmt) Copy

func (x *SelectStmt) Copy() Node

func (SelectStmt) String

func (x SelectStmt) String() string

type SelectorExpr

type SelectorExpr struct {
	Attributes
	X    Expr      // expression
	Path ValuePath // set by preprocessor.
	Sel  Name      // field selector
}

func Sel

func Sel(x interface{}, sel interface{}) *SelectorExpr

func (*SelectorExpr) Copy

func (x *SelectorExpr) Copy() Node

func (SelectorExpr) String

func (x SelectorExpr) String() string

type SendStmt

type SendStmt struct {
	Attributes
	Chan  Expr
	Value Expr
}

func (*SendStmt) Copy

func (x *SendStmt) Copy() Node

func (SendStmt) String

func (x SendStmt) String() string

type SimpleDeclStmt

type SimpleDeclStmt interface {
	Decl
	Stmt
	// contains filtered or unexported methods
}

type SimpleStmt

type SimpleStmt interface {
	Stmt
	// contains filtered or unexported methods
}

type SliceExpr

type SliceExpr struct {
	Attributes
	X    Expr // expression
	Low  Expr // begin of slice range; or nil
	High Expr // end of slice range; or nil
	Max  Expr // maximum capacity of slice; or nil; added in Go 1.2
}

func (*SliceExpr) Copy

func (x *SliceExpr) Copy() Node

func (SliceExpr) String

func (x SliceExpr) String() string

type SliceType

type SliceType struct {
	Elt Type
	Vrd bool // used for *FuncType.HasVarg()
	// contains filtered or unexported fields
}

func (*SliceType) Elem

func (st *SliceType) Elem() Type

func (*SliceType) GetPkgPath

func (st *SliceType) GetPkgPath() string

func (*SliceType) IsNamed

func (st *SliceType) IsNamed() bool

func (*SliceType) Kind

func (st *SliceType) Kind() Kind

func (*SliceType) String

func (st *SliceType) String() string

func (*SliceType) TypeID

func (st *SliceType) TypeID() TypeID

type SliceTypeExpr

type SliceTypeExpr struct {
	Attributes
	Elt Expr // element type
	Vrd bool // variadic arg expression
}

func SliceT

func SliceT(elt interface{}) *SliceTypeExpr

func Vrd

func Vrd(elt interface{}) *SliceTypeExpr

func (*SliceTypeExpr) Copy

func (x *SliceTypeExpr) Copy() Node

func (SliceTypeExpr) String

func (x SliceTypeExpr) String() string

type SliceValue

type SliceValue struct {
	Base   Value
	Offset int
	Length int
	Maxcap int
}

func (*SliceValue) GetBase

func (sv *SliceValue) GetBase(store Store) *ArrayValue

func (*SliceValue) GetCapacity

func (sv *SliceValue) GetCapacity() int

func (*SliceValue) GetLength

func (sv *SliceValue) GetLength() int

func (*SliceValue) GetPointerAtIndexInt2

func (sv *SliceValue) GetPointerAtIndexInt2(store Store, ii int, et Type) PointerValue

et is only required for .List byte-slices.

func (*SliceValue) ProtectedString

func (sv *SliceValue) ProtectedString(seen *seenValues) string

func (*SliceValue) String

func (sv *SliceValue) String() string

type Stacktrace

type Stacktrace struct {
	Calls           []StacktraceCall
	NumFramesElided int
}

func (Stacktrace) String

func (s Stacktrace) String() string

type StacktraceCall

type StacktraceCall struct {
	Stmt  Stmt
	Frame *Frame
}

type StarExpr

type StarExpr struct {
	Attributes
	X Expr // operand
}

A StarExpr node represents an expression of the form "*" Expression. Semantically it could be a unary "*" expression, or a pointer type.

func Deref

func Deref(x interface{}) *StarExpr

func Ptr

func Ptr(x interface{}) *StarExpr

NOTE: Same as DEREF, but different context.

func (*StarExpr) Copy

func (x *StarExpr) Copy() Node

func (StarExpr) String

func (x StarExpr) String() string

type StaticBlock

type StaticBlock struct {
	Block
	Types    []Type
	NumNames uint16
	Names    []Name
	Consts   []Name // TODO consider merging with Names.
	Externs  []Name
	Loc      Location
	// contains filtered or unexported fields
}

Embed in node to make it a BlockNode.

func (*StaticBlock) Define

func (sb *StaticBlock) Define(n Name, tv TypedValue)

Implements BlockNode Statically declares a name definition. At runtime, use *Block.GetPointerTo() which takes a path value, which is pre-computeed in the preprocessor. Once a typed value is defined, it cannot be changed.

NOTE: Currently tv.V is only set when the value represents a Type(Value) or a FuncValue. The purpose of tv is to describe the invariant of a named value, at the minimum its type, but also sometimes the typeval value; but we could go further and store preprocessed constant results here too. See "anyValue()" and "asValue()" for usage.

func (*StaticBlock) Define2

func (sb *StaticBlock) Define2(isConst bool, n Name, st Type, tv TypedValue)

The declared type st may not be the same as the static tv; e.g. var x MyInterface = MyStruct{}. Setting st and tv to nil/zero reserves (predefines) name for definition later.

func (*StaticBlock) GetBlock

func (sb *StaticBlock) GetBlock() *Block

Does not implement BlockNode to prevent confusion. To get the static *Block, call Blocknode.GetStaticBlock().GetBlock().

func (*StaticBlock) GetBlockNames

func (sb *StaticBlock) GetBlockNames() (ns []Name)

Implements BlockNode.

func (*StaticBlock) GetBlockNodeForPath

func (sb *StaticBlock) GetBlockNodeForPath(store Store, path ValuePath) BlockNode

Get the containing block node for node with path relative to this containing block.

func (*StaticBlock) GetExternNames

func (sb *StaticBlock) GetExternNames() (ns []Name)

Implements BlockNode. NOTE: Extern names may also be local, if declared after usage as an extern (thus shadowing the extern name).

func (*StaticBlock) GetIsConst

func (sb *StaticBlock) GetIsConst(store Store, n Name) bool

Returns whether a name defined here in in ancestry is a const. This is not the same as whether a name's static type is untyped -- as in c := a == b, a name may be an untyped non-const. Implements BlockNode.

func (*StaticBlock) GetLocalIndex

func (sb *StaticBlock) GetLocalIndex(n Name) (uint16, bool)

Implements BlockNode.

func (*StaticBlock) GetLocation

func (sb *StaticBlock) GetLocation() Location

Implements BlockNode.

func (*StaticBlock) GetNumNames

func (sb *StaticBlock) GetNumNames() (nn uint16)

Implements BlockNode.

func (*StaticBlock) GetParentNode

func (sb *StaticBlock) GetParentNode(store Store) BlockNode

Implements BlockNode.

func (*StaticBlock) GetPathForName

func (sb *StaticBlock) GetPathForName(store Store, n Name) ValuePath

Implements BlockNode. As a side effect, notes externally defined names.

func (*StaticBlock) GetStaticBlock

func (sb *StaticBlock) GetStaticBlock() *StaticBlock

Implements BlockNode.

func (*StaticBlock) GetStaticTypeOf

func (sb *StaticBlock) GetStaticTypeOf(store Store, n Name) Type

Implements BlockNode. XXX XXX what about uverse?

func (*StaticBlock) GetStaticTypeOfAt

func (sb *StaticBlock) GetStaticTypeOfAt(store Store, path ValuePath) Type

Implements BlockNode.

func (*StaticBlock) GetValueRef

func (sb *StaticBlock) GetValueRef(store Store, n Name, skipPredefined bool) *TypedValue

Implemented BlockNode. This method is too slow for runtime, but it is used during preprocessing to compute types. If skipPredefined, skips over names that are only predefined. Returns nil if not defined.

func (*StaticBlock) InitStaticBlock

func (sb *StaticBlock) InitStaticBlock(source BlockNode, parent BlockNode)

Implements BlockNode

func (*StaticBlock) IsInitialized

func (sb *StaticBlock) IsInitialized() bool

Implements BlockNode.

func (*StaticBlock) Predefine

func (sb *StaticBlock) Predefine(isConst bool, n Name)

Set type to nil, only reserving the name.

func (*StaticBlock) SetLocation

func (sb *StaticBlock) SetLocation(loc Location)

Implements BlockNode.

func (*StaticBlock) SetStaticBlock

func (sb *StaticBlock) SetStaticBlock(osb StaticBlock)

Implements BlockNode

type Stmt

type Stmt interface {
	Node
	// contains filtered or unexported methods
}

func S

func S(args ...interface{}) Stmt

Tries to infer statement from args.

func SIf

func SIf(cond bool, then_, else_ Stmt) Stmt

func Ss

func Ss(b ...Stmt) []Stmt

type Store

type Store interface {
	// STABLE
	BeginTransaction(baseStore, iavlStore store.Store) TransactionStore
	SetPackageGetter(PackageGetter)
	GetPackage(pkgPath string, isImport bool) *PackageValue
	SetCachePackage(*PackageValue)
	GetPackageRealm(pkgPath string) *Realm
	SetPackageRealm(*Realm)
	GetObject(oid ObjectID) Object
	GetObjectSafe(oid ObjectID) Object
	SetObject(Object)
	DelObject(Object)
	GetType(tid TypeID) Type
	GetTypeSafe(tid TypeID) Type
	SetCacheType(Type)
	SetType(Type)
	GetBlockNode(Location) BlockNode // to get a PackageNode, use PackageNodeLocation().
	GetBlockNodeSafe(Location) BlockNode
	SetBlockNode(BlockNode)
	// UNSTABLE
	Go2GnoType(rt reflect.Type) Type
	GetAllocator() *Allocator
	NumMemPackages() int64
	// Upon restart, all packages will be re-preprocessed; This
	// loads BlockNodes and Types onto the store for persistence
	// version 1.
	AddMemPackage(memPkg *gnovm.MemPackage)
	GetMemPackage(path string) *gnovm.MemPackage
	GetMemFile(path string, name string) *gnovm.MemFile
	IterMemPackage() <-chan *gnovm.MemPackage
	ClearObjectCache()                                    // run before processing a message
	SetNativeStore(NativeStore)                           // for "new" natives XXX
	GetNative(pkgPath string, name Name) func(m *Machine) // for "new" natives XXX
	SetLogStoreOps(enabled bool)
	SprintStoreOps() string
	LogSwitchRealm(rlmpath string) // to mark change of realm boundaries
	Print()
}

Store is the central interface that specifies the communications between the GnoVM and the underlying data store; currently, generally the gno.land blockchain, or the file system.

type StoreOp

type StoreOp struct {
	Type    StoreOpType
	Object  Object // ref'd objects
	RlmPath string // for StoreOpSwitchRealm
}

func (StoreOp) String

func (sop StoreOp) String() string

used by the tests/file_test system to check veracity of realm operations.

type StoreOpType

type StoreOpType uint8
const (
	StoreOpNew StoreOpType = iota
	StoreOpMod
	StoreOpDel
	StoreOpSwitchRealm
)

type StringValue

type StringValue string

func (StringValue) String

func (v StringValue) String() string

type StructType

type StructType struct {
	PkgPath string
	Fields  []FieldType
	// contains filtered or unexported fields
}

func (*StructType) Elem

func (st *StructType) Elem() Type

func (*StructType) FindEmbeddedFieldType

func (st *StructType) FindEmbeddedFieldType(callerPath string, n Name, m map[Type]struct{}) (
	trail []ValuePath, hasPtr bool, rcvr Type, field Type, accessError bool,
)

Searches embedded fields to find matching method or field, which may be embedded. This function is slow. DeclaredType uses this. There is probably no need to cache positive results here; it may be better to implement it on DeclaredType. The resulting ValuePaths may be modified. If not found, all returned values are nil; for consistency, check the trail.

func (*StructType) GetPathForName

func (st *StructType) GetPathForName(n Name) ValuePath

NOTE only works for exposed non-embedded fields.

func (*StructType) GetPkgPath

func (st *StructType) GetPkgPath() string

func (*StructType) GetStaticTypeOfAt

func (st *StructType) GetStaticTypeOfAt(path ValuePath) Type

func (*StructType) IsNamed

func (st *StructType) IsNamed() bool

func (*StructType) Kind

func (st *StructType) Kind() Kind

func (*StructType) String

func (st *StructType) String() string

func (*StructType) TypeID

func (st *StructType) TypeID() TypeID

type StructTypeExpr

type StructTypeExpr struct {
	Attributes
	Fields FieldTypeExprs // list of field declarations
}

func (*StructTypeExpr) Copy

func (x *StructTypeExpr) Copy() Node

func (StructTypeExpr) String

func (x StructTypeExpr) String() string

type StructValue

type StructValue struct {
	ObjectInfo
	Fields []TypedValue
}

func (*StructValue) Copy

func (sv *StructValue) Copy(alloc *Allocator) *StructValue

func (*StructValue) GetPointerTo

func (sv *StructValue) GetPointerTo(store Store, path ValuePath) PointerValue

TODO handle unexported fields in debug, and also ensure in the preprocessor.

func (*StructValue) GetPointerToInt

func (sv *StructValue) GetPointerToInt(store Store, index int) PointerValue

func (*StructValue) GetSubrefPointerTo

func (sv *StructValue) GetSubrefPointerTo(store Store, st *StructType, path ValuePath) PointerValue

Like GetPointerTo*, but returns (a pointer of) a reference to field.

func (*StructValue) ProtectedString

func (sv *StructValue) ProtectedString(seen *seenValues) string

func (*StructValue) String

func (sv *StructValue) String() string

type SwitchClauseStmt

type SwitchClauseStmt struct {
	Attributes
	StaticBlock
	Cases Exprs // list of expressions or types; nil means default case
	Body
}

func (*SwitchClauseStmt) Copy

func (x *SwitchClauseStmt) Copy() Node

func (SwitchClauseStmt) String

func (x SwitchClauseStmt) String() string

type SwitchContext

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

type SwitchStmt

type SwitchStmt struct {
	Attributes
	StaticBlock
	Init         Stmt               // init (simple) stmt; or nil
	X            Expr               // tag or _.(type) expr; or nil
	IsTypeSwitch bool               // true iff X is .(type) expr
	Clauses      []SwitchClauseStmt // case clauses
	VarName      Name               // type-switched value; or ""
}

func (*SwitchStmt) Copy

func (x *SwitchStmt) Copy() Node

func (*SwitchStmt) GetBody

func (x *SwitchStmt) GetBody() Body

func (*SwitchStmt) SetBody

func (x *SwitchStmt) SetBody(b Body)

func (SwitchStmt) String

func (x SwitchStmt) String() string

type Tag

type Tag string

type TransCtrl

type TransCtrl uint8
const (
	TRANS_CONTINUE TransCtrl = iota
	TRANS_SKIP
	TRANS_BREAK
	TRANS_EXIT
)

func (TransCtrl) String

func (i TransCtrl) String() string

type TransField

type TransField uint8
const (
	TRANS_ROOT TransField = iota
	TRANS_BINARY_LEFT
	TRANS_BINARY_RIGHT
	TRANS_CALL_FUNC
	TRANS_CALL_ARG
	TRANS_INDEX_X
	TRANS_INDEX_INDEX
	TRANS_SELECTOR_X
	TRANS_SLICE_X
	TRANS_SLICE_LOW
	TRANS_SLICE_HIGH
	TRANS_SLICE_MAX
	TRANS_STAR_X
	TRANS_REF_X
	TRANS_TYPEASSERT_X
	TRANS_TYPEASSERT_TYPE
	TRANS_UNARY_X
	TRANS_COMPOSITE_TYPE
	TRANS_COMPOSITE_KEY
	TRANS_COMPOSITE_VALUE
	TRANS_FUNCLIT_TYPE
	TRANS_FUNCLIT_HEAP_CAPTURE
	TRANS_FUNCLIT_BODY
	TRANS_FIELDTYPE_TYPE
	TRANS_FIELDTYPE_TAG
	TRANS_ARRAYTYPE_LEN
	TRANS_ARRAYTYPE_ELT
	TRANS_SLICETYPE_ELT
	TRANS_INTERFACETYPE_METHOD
	TRANS_CHANTYPE_VALUE
	TRANS_FUNCTYPE_PARAM
	TRANS_FUNCTYPE_RESULT
	TRANS_MAPTYPE_KEY
	TRANS_MAPTYPE_VALUE
	TRANS_STRUCTTYPE_FIELD
	TRANS_MAYBENATIVETYPE_TYPE
	TRANS_ASSIGN_LHS
	TRANS_ASSIGN_RHS
	TRANS_BLOCK_BODY
	TRANS_DECL_BODY
	TRANS_DEFER_CALL
	TRANS_EXPR_X
	TRANS_FOR_INIT
	TRANS_FOR_COND
	TRANS_FOR_POST
	TRANS_FOR_BODY
	TRANS_GO_CALL
	TRANS_IF_INIT
	TRANS_IF_COND
	TRANS_IF_BODY
	TRANS_IF_ELSE
	TRANS_IF_CASE_BODY
	TRANS_INCDEC_X
	TRANS_RANGE_X
	TRANS_RANGE_KEY
	TRANS_RANGE_VALUE
	TRANS_RANGE_BODY
	TRANS_RETURN_RESULT
	TRANS_PANIC_EXCEPTION
	TRANS_SELECT_CASE
	TRANS_SELECTCASE_COMM
	TRANS_SELECTCASE_BODY
	TRANS_SEND_CHAN
	TRANS_SEND_VALUE
	TRANS_SWITCH_INIT
	TRANS_SWITCH_X
	TRANS_SWITCH_CASE
	TRANS_SWITCHCASE_CASE
	TRANS_SWITCHCASE_BODY
	TRANS_FUNC_RECV
	TRANS_FUNC_TYPE
	TRANS_FUNC_BODY
	TRANS_IMPORT_PATH
	TRANS_CONST_TYPE
	TRANS_CONST_VALUE
	TRANS_VAR_NAME // XXX stringer
	TRANS_VAR_TYPE
	TRANS_VAR_VALUE
	TRANS_TYPE_TYPE
	TRANS_FILE_BODY
)

func (TransField) String

func (i TransField) String() string

type TransStage

type TransStage uint8
const (
	TRANS_ENTER TransStage = iota
	TRANS_BLOCK
	TRANS_BLOCK2
	TRANS_LEAVE
)

type TransactionStore

type TransactionStore interface {
	Store

	// Write commits the current buffered transaction data to the underlying store.
	// It also clears the current buffer of the transaction.
	Write()
}

TransactionStore is a store where the operations modifying the underlying store's caches are temporarily held in a buffer, and then executed together after executing Write.

type Transform

type Transform func(ns []Node, ftype TransField, index int, n Node, stage TransStage) (Node, TransCtrl)

return:

  • TRANS_CONTINUE to visit children recursively;
  • TRANS_SKIP to break out of the ENTER,CHILDS1,[BLOCK,CHILDS2]?,LEAVE sequence for that node, i.e. skipping (the rest of) it;
  • TRANS_BREAK to break out of looping in CHILDS1 or CHILDS2, but still perform TRANS_LEAVE.
  • TRANS_EXIT to stop traversing altogether.

Do not mutate ns. Must return a new node to replace the old one, or the node will be deleted (or set to nil). Read: transform the ftype/index of context ns which is n during stage.

type Type

type Type interface {
	Kind() Kind     // penetrates *DeclaredType & *NativeType
	TypeID() TypeID // deterministic
	String() string // for dev/debugging
	Elem() Type     // for TODO... types
	GetPkgPath() string
	IsNamed() bool // named vs unname type. property as a method
	// contains filtered or unexported methods
}

func BaseOf

func BaseOf(t Type) Type

type TypeAssertExpr

type TypeAssertExpr struct {
	Attributes
	X     Expr // expression.
	Type  Expr // asserted type, never nil.
	HasOK bool // if true, is form: `_, ok := <X>.(<Type>)`.
}

func TypeAssert

func TypeAssert(x interface{}, t interface{}) *TypeAssertExpr

func (*TypeAssertExpr) Copy

func (x *TypeAssertExpr) Copy() Node

func (TypeAssertExpr) String

func (x TypeAssertExpr) String() string

type TypeDecl

type TypeDecl struct {
	Attributes
	NameExpr
	Type    Expr // Name, SelectorExpr, StarExpr, or XxxTypes
	IsAlias bool // type alias since Go 1.9
}

func (*TypeDecl) Copy

func (x *TypeDecl) Copy() Node

func (*TypeDecl) GetDeclNames

func (x *TypeDecl) GetDeclNames() []Name

func (TypeDecl) String

func (x TypeDecl) String() string

type TypeExpr

type TypeExpr interface {
	Expr
	// contains filtered or unexported methods
}

type TypeID

type TypeID string

func DeclaredTypeID

func DeclaredTypeID(pkgPath string, name Name) TypeID

func (TypeID) Bytes

func (tid TypeID) Bytes() []byte

func (TypeID) IsZero

func (tid TypeID) IsZero() bool

func (TypeID) String

func (tid TypeID) String() string

type TypeType

type TypeType struct {
}

func (*TypeType) Elem

func (tt *TypeType) Elem() Type

func (*TypeType) GetPkgPath

func (tt *TypeType) GetPkgPath() string

func (*TypeType) IsNamed

func (tt *TypeType) IsNamed() bool

func (*TypeType) Kind

func (tt *TypeType) Kind() Kind

func (*TypeType) String

func (tt *TypeType) String() string

func (*TypeType) TypeID

func (tt *TypeType) TypeID() TypeID

type TypeValue

type TypeValue struct {
	Type Type
}

The type itself as a value.

func (TypeValue) String

func (v TypeValue) String() string

type TypedValue

type TypedValue struct {
	T Type    `json:",omitempty"` // never nil
	V Value   `json:",omitempty"` // an untyped value
	N [8]byte `json:",omitempty"` // numeric bytes
}

func Go2GnoNativeValue

func Go2GnoNativeValue(alloc *Allocator, rv reflect.Value) (tv TypedValue)

NOTE: used by vm module. Shallow, preserves native namedness.

func Go2GnoValue

func Go2GnoValue(alloc *Allocator, store Store, rv reflect.Value) (tv TypedValue)

NOTE: used by vm module. Recursively converts.

func (*TypedValue) AssertNonNegative

func (tv *TypedValue) AssertNonNegative(msg string)

func (*TypedValue) Assign

func (tv *TypedValue) Assign(alloc *Allocator, tv2 TypedValue, cu bool)

Unlike PointerValue.Assign2, does not consider DataByte or addressable NativeValue fields/elems. cu: convert untyped after assignment. pass false for const definitions, but true for all else.

func (*TypedValue) ClearNum

func (tv *TypedValue) ClearNum()

func (*TypedValue) ComputeMapKey

func (tv *TypedValue) ComputeMapKey(store Store, omitType bool) MapKey

func (*TypedValue) ConvertGetInt

func (tv *TypedValue) ConvertGetInt() int

func (TypedValue) Copy

func (tv TypedValue) Copy(alloc *Allocator) (cp TypedValue)

func (*TypedValue) DebugHasValue

func (tv *TypedValue) DebugHasValue() bool

for debugging, returns true if V or N is not zero. just because V and N are zero doesn't mean it didn't get a value set.

func (*TypedValue) GetBigDec

func (tv *TypedValue) GetBigDec() *apd.Decimal

func (*TypedValue) GetBigInt

func (tv *TypedValue) GetBigInt() *big.Int

func (*TypedValue) GetBool

func (tv *TypedValue) GetBool() bool

func (*TypedValue) GetCapacity

func (tv *TypedValue) GetCapacity() int

func (*TypedValue) GetDataByte

func (tv *TypedValue) GetDataByte() uint8

func (*TypedValue) GetFirstObject

func (tv *TypedValue) GetFirstObject(store Store) Object

func (*TypedValue) GetFloat32

func (tv *TypedValue) GetFloat32() float32

func (*TypedValue) GetFloat64

func (tv *TypedValue) GetFloat64() float64

func (*TypedValue) GetFunc

func (tv *TypedValue) GetFunc() *FuncValue

func (*TypedValue) GetInt

func (tv *TypedValue) GetInt() int

func (*TypedValue) GetInt16

func (tv *TypedValue) GetInt16() int16

func (*TypedValue) GetInt32

func (tv *TypedValue) GetInt32() int32

func (*TypedValue) GetInt64

func (tv *TypedValue) GetInt64() int64

func (*TypedValue) GetInt8

func (tv *TypedValue) GetInt8() int8

func (*TypedValue) GetLength

func (tv *TypedValue) GetLength() int

func (*TypedValue) GetPointerAtIndex

func (tv *TypedValue) GetPointerAtIndex(alloc *Allocator, store Store, iv *TypedValue) PointerValue

func (*TypedValue) GetPointerAtIndexInt

func (tv *TypedValue) GetPointerAtIndexInt(store Store, ii int) PointerValue

Convenience for GetPointerAtIndex(). Slow.

func (*TypedValue) GetPointerToFromTV

func (tv *TypedValue) GetPointerToFromTV(alloc *Allocator, store Store, path ValuePath) PointerValue

NOTE: Allocation for PointerValue is not immediate, as usually PointerValues are temporary for assignment or binary operations. When a pointer is to be allocated, *Allocator.AllocatePointer() is called separately, as in OpRef.

func (*TypedValue) GetSlice

func (tv *TypedValue) GetSlice(alloc *Allocator, low, high int) TypedValue

func (*TypedValue) GetSlice2

func (tv *TypedValue) GetSlice2(alloc *Allocator, low, high, max int) TypedValue

func (*TypedValue) GetString

func (tv *TypedValue) GetString() string

func (*TypedValue) GetType

func (tv *TypedValue) GetType() Type

func (*TypedValue) GetUint

func (tv *TypedValue) GetUint() uint

func (*TypedValue) GetUint16

func (tv *TypedValue) GetUint16() uint16

func (*TypedValue) GetUint32

func (tv *TypedValue) GetUint32() uint32

func (*TypedValue) GetUint64

func (tv *TypedValue) GetUint64() uint64

func (*TypedValue) GetUint8

func (tv *TypedValue) GetUint8() uint8

func (*TypedValue) HasKind

func (tv *TypedValue) HasKind(k Kind) bool

func (*TypedValue) IsDefined

func (tv *TypedValue) IsDefined() bool

func (*TypedValue) IsNilInterface

func (tv *TypedValue) IsNilInterface() bool

func (*TypedValue) IsUndefined

func (tv *TypedValue) IsUndefined() bool

func (*TypedValue) PrimitiveBytes

func (tv *TypedValue) PrimitiveBytes() (data []byte)

Returns encoded bytes for primitive values. These bytes are used for both value hashes as well as hash key bytes.

func (*TypedValue) ProtectedSprint

func (tv *TypedValue) ProtectedSprint(seen *seenValues, considerDeclaredType bool) string

func (TypedValue) ProtectedString

func (tv TypedValue) ProtectedString(seen *seenValues) string

func (*TypedValue) SetBool

func (tv *TypedValue) SetBool(b bool)

func (*TypedValue) SetDataByte

func (tv *TypedValue) SetDataByte(n uint8)

func (*TypedValue) SetFloat32

func (tv *TypedValue) SetFloat32(n float32)

func (*TypedValue) SetFloat64

func (tv *TypedValue) SetFloat64(n float64)

func (*TypedValue) SetInt

func (tv *TypedValue) SetInt(n int)

func (*TypedValue) SetInt16

func (tv *TypedValue) SetInt16(n int16)

func (*TypedValue) SetInt32

func (tv *TypedValue) SetInt32(n int32)

func (*TypedValue) SetInt64

func (tv *TypedValue) SetInt64(n int64)

func (*TypedValue) SetInt8

func (tv *TypedValue) SetInt8(n int8)

func (*TypedValue) SetString

func (tv *TypedValue) SetString(s StringValue)

func (*TypedValue) SetType

func (tv *TypedValue) SetType(tt Type)

func (*TypedValue) SetUint

func (tv *TypedValue) SetUint(n uint)

func (*TypedValue) SetUint16

func (tv *TypedValue) SetUint16(n uint16)

func (*TypedValue) SetUint32

func (tv *TypedValue) SetUint32(n uint32)

func (*TypedValue) SetUint64

func (tv *TypedValue) SetUint64(n uint64)

func (*TypedValue) SetUint8

func (tv *TypedValue) SetUint8(n uint8)

func (*TypedValue) Sign

func (tv *TypedValue) Sign() int

func (*TypedValue) Sprint

func (tv *TypedValue) Sprint(m *Machine) string

for print() and println().

func (TypedValue) String

func (tv TypedValue) String() string

For gno debugging/testing.

type UnaryExpr

type UnaryExpr struct {
	Attributes
	X  Expr // operand
	Op Word // operator
}

A UnaryExpr node represents a unary expression. Unary "*" expressions (dereferencing and pointer-types) are represented with StarExpr nodes. Unary & expressions (referencing) are represented with RefExpr nodes.

func Not

func Not(x Expr) *UnaryExpr

func (*UnaryExpr) AssertCompatible

func (x *UnaryExpr) AssertCompatible(t Type)

func (*UnaryExpr) Copy

func (x *UnaryExpr) Copy() Node

func (UnaryExpr) String

func (x UnaryExpr) String() string

type UnhandledPanicError

type UnhandledPanicError struct {
	Descriptor string // Description of the unhandled panic.
}

UnhandledPanicError represents an error thrown when a panic is not handled in the realm.

func (UnhandledPanicError) Error

func (e UnhandledPanicError) Error() string

type VPType

type VPType uint8
const (
	VPUverse         VPType = 0x00
	VPBlock          VPType = 0x01 // blocks and packages
	VPField          VPType = 0x02
	VPValMethod      VPType = 0x03
	VPPtrMethod      VPType = 0x04
	VPInterface      VPType = 0x05
	VPSubrefField    VPType = 0x06 // not deref type
	VPDerefField     VPType = 0x12 // 0x10 + VPField
	VPDerefValMethod VPType = 0x13 // 0x10 + VPValMethod
	VPDerefPtrMethod VPType = 0x14 // 0x10 + VPPtrMethod
	VPDerefInterface VPType = 0x15 // 0x10 + VPInterface
	VPNative         VPType = 0x20
)

func (VPType) String

func (i VPType) String() string

type Value

type Value interface {
	String() string // for debugging
	// contains filtered or unexported methods
}

type ValueDecl

type ValueDecl struct {
	Attributes
	NameExprs
	Type   Expr  // value type; or nil
	Values Exprs // initial value; or nil (unless const).
	Const  bool
}

func (*ValueDecl) Copy

func (x *ValueDecl) Copy() Node

func (*ValueDecl) GetDeclNames

func (x *ValueDecl) GetDeclNames() []Name

func (ValueDecl) String

func (x ValueDecl) String() string

type ValueHash

type ValueHash struct {
	Hashlet
}

func (ValueHash) Copy

func (vh ValueHash) Copy() ValueHash

func (ValueHash) MarshalAmino

func (vh ValueHash) MarshalAmino() (string, error)

func (*ValueHash) UnmarshalAmino

func (vh *ValueHash) UnmarshalAmino(h string) error

type ValuePath

type ValuePath struct {
	Type  VPType // see VPType* consts.
	Depth uint8  // see doc for ValuePath.
	Index uint16 // index of value, field, or method.
	Name  Name   // name of value, field, or method.
}

A relative pointer to a TypedValue value

(a) a Block scope var or const
(b) a StructValue field
(c) a DeclaredType method
(d) a PackageNode declaration

Depth tells how many layers of access should be unvealed before arriving at the ultimate handler type. In the case of Blocks, the depth tells how many layers of ancestry to ascend before arriving at the target block. For other selector expr paths such as those for *DeclaredType methods or *StructType fields, see tests/selector_test.go.

func NewValuePath

func NewValuePath(t VPType, depth uint8, index uint16, n Name) ValuePath

func NewValuePathBlock

func NewValuePathBlock(depth uint8, index uint16, n Name) ValuePath

func NewValuePathDerefField

func NewValuePathDerefField(depth uint8, index uint16, n Name) ValuePath

func NewValuePathDerefInterface

func NewValuePathDerefInterface(n Name) ValuePath

func NewValuePathDerefPtrMethod

func NewValuePathDerefPtrMethod(index uint16, n Name) ValuePath

func NewValuePathDerefValMethod

func NewValuePathDerefValMethod(index uint16, n Name) ValuePath

func NewValuePathField

func NewValuePathField(depth uint8, index uint16, n Name) ValuePath

func NewValuePathInterface

func NewValuePathInterface(n Name) ValuePath

func NewValuePathNative

func NewValuePathNative(n Name) ValuePath

func NewValuePathPtrMethod

func NewValuePathPtrMethod(index uint16, n Name) ValuePath

func NewValuePathSubrefField

func NewValuePathSubrefField(depth uint8, index uint16, n Name) ValuePath

func NewValuePathUverse

func NewValuePathUverse(index uint16, n Name) ValuePath

func NewValuePathValMethod

func NewValuePathValMethod(index uint16, n Name) ValuePath

func (ValuePath) IsBlockBlankPath

func (vp ValuePath) IsBlockBlankPath() bool

func (ValuePath) IsDerefType

func (vp ValuePath) IsDerefType() bool

func (ValuePath) String

func (vp ValuePath) String() string

func (ValuePath) Validate

func (vp ValuePath) Validate()

type ValuePather

type ValuePather interface {
	GetPathForName(Name) ValuePath
}

type Word

type Word int
const (
	// Special words
	ILLEGAL Word = iota

	// Names and basic type literals
	// (these words stand for classes of literals)
	NAME   // main
	INT    // 12345
	FLOAT  // 123.45
	IMAG   // 123.45i
	CHAR   // 'a'
	STRING // "abc"

	// Operators and delimiters
	ADD // +
	SUB // -
	MUL // *
	QUO // /
	REM // %

	BAND     // &
	BOR      // |
	XOR      // ^
	SHL      // <<
	SHR      // >>
	BAND_NOT // &^

	ADD_ASSIGN      // +=
	SUB_ASSIGN      // -=
	MUL_ASSIGN      // *=
	QUO_ASSIGN      // /=
	REM_ASSIGN      // %=
	BAND_ASSIGN     // &=
	BOR_ASSIGN      // |=
	XOR_ASSIGN      // ^=
	SHL_ASSIGN      // <<=
	SHR_ASSIGN      // >>=
	BAND_NOT_ASSIGN // &^=

	LAND  // &&
	LOR   // ||
	ARROW // <-
	INC   // ++
	DEC   // --

	EQL    // ==
	LSS    // <
	GTR    // >
	ASSIGN // =
	NOT    // !

	NEQ    // !=
	LEQ    // <=
	GEQ    // >=
	DEFINE // :=

	// Keywords
	BREAK
	CASE
	CHAN
	CONST
	CONTINUE

	DEFAULT
	DEFER
	ELSE
	FALLTHROUGH
	FOR

	FUNC
	GO
	GOTO
	IF
	IMPORT

	INTERFACE
	MAP
	PACKAGE
	RANGE
	RETURN

	SELECT
	STRUCT
	SWITCH
	TYPE
	VAR
)

func Op2Word

func Op2Word(op string) Word

func (Word) String

func (i Word) String() string

func (Word) TokenString

func (w Word) TokenString() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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