Documentation
¶
Overview ¶
Package vm provides a virtual machine for executing rumo bytecode
Index ¶
- Variables
- func CountObjects(o Object) (c int)
- func Format(format string, a ...Object) (string, error)
- func FormatInstructions(b []byte, posOffset int) []string
- func FormatWithConfig(format string, cfg *Config, a ...Object) (string, error)
- func MakeInstruction(opcode parser.Opcode, operands ...int) []byte
- func MarshalLive(o Object) ([]byte, error)
- func MarshalObject(n int, b []byte, o Object) int
- func NativeSupported() bool
- func NewChanID() int64
- func ResolveChans(o Object, registry *ChanRegistry, fallback ChanTransport)
- func ResolveNativePath(_ string) string
- func SizeOfObject(o Object) int
- func SizeOfObjectPtr(op *ObjectPtr) int
- func ToBool(o Object) (v bool, ok bool)
- func ToByteSlice(o Object) (v []byte, ok bool)
- func ToFloat32(o Object) (v float32, ok bool)
- func ToFloat64(o Object) (v float64, ok bool)
- func ToInt(o Object) (v int, ok bool)
- func ToInt64(o Object) (v int64, ok bool)
- func ToInterface(o Object) (res interface{})
- func ToPtr(o Object) (v unsafe.Pointer, ok bool)
- func ToRune(o Object) (v rune, ok bool)
- func ToString(o Object) (v string, ok bool)
- func ToUint64(o Object) (v uint64, ok bool)
- func TypeOfObject(o Object) byte
- type Array
- func (o *Array) BinaryOp(op token.Token, rhs Object) (Object, error)
- func (o *Array) CanIterate() bool
- func (o *Array) Copy() Object
- func (o *Array) Equals(x Object) bool
- func (o *Array) Freeze()
- func (o *Array) IndexGet(index Object) (res Object, err error)
- func (o *Array) IndexSet(index, value Object) (err error)
- func (o *Array) IsFalsy() bool
- func (o *Array) IsFrozen() bool
- func (o *Array) Iterate() Iterator
- func (o *Array) Melt()
- func (o *Array) String() string
- func (o *Array) TypeName() string
- type ArrayIterator
- func (i *ArrayIterator) Copy() Object
- func (i *ArrayIterator) Equals(Object) bool
- func (i *ArrayIterator) IsFalsy() bool
- func (i *ArrayIterator) Key() Object
- func (i *ArrayIterator) Next() bool
- func (i *ArrayIterator) String() string
- func (i *ArrayIterator) TypeName() string
- func (i *ArrayIterator) Value() Object
- type Bool
- type BuiltinFunction
- type BuiltinModule
- type Byte
- type Bytecode
- func (b *Bytecode) CountObjects() int
- func (b *Bytecode) Equals(other *Bytecode) bool
- func (b *Bytecode) FormatConstants() (output []string)
- func (b *Bytecode) FormatInstructions() []string
- func (b *Bytecode) Marshal() ([]byte, error)
- func (b *Bytecode) RemoveDuplicates()
- func (b *Bytecode) Unmarshal(data []byte, modules *ModuleMap) (err error)
- type Bytes
- func (o *Bytes) BinaryOp(op token.Token, rhs Object) (Object, error)
- func (o *Bytes) CanIterate() bool
- func (o *Bytes) Copy() Object
- func (o *Bytes) Equals(x Object) bool
- func (o *Bytes) IndexGet(index Object) (res Object, err error)
- func (o *Bytes) IsFalsy() bool
- func (o *Bytes) Iterate() Iterator
- func (o *Bytes) String() string
- func (o *Bytes) TypeName() string
- type BytesIterator
- type CallableFunc
- type Chan
- type ChanCore
- type ChanRegistry
- type ChanTransport
- type Char
- type CompiledFunction
- type Compiler
- type CompilerError
- type CompilerWarning
- type Config
- type ContextKey
- type Double
- type EmbedFile
- type ErrInvalidArgumentType
- type ErrPanic
- type Error
- type Float
- type Float32
- type Float64
- type Importable
- type Int
- type Int8
- type Int16
- type Int32
- type Int64
- type Iterator
- type LocalChanCore
- type Map
- func (o *Map) CanIterate() bool
- func (o *Map) Copy() Object
- func (o *Map) Equals(x Object) bool
- func (o *Map) Freeze()
- func (o *Map) IndexGet(index Object) (res Object, err error)
- func (o *Map) IndexSet(index, value Object) (err error)
- func (o *Map) IsFalsy() bool
- func (o *Map) IsFrozen() bool
- func (o *Map) Iterate() Iterator
- func (o *Map) Melt()
- func (o *Map) ModuleName() string
- func (o *Map) String() string
- func (o *Map) TypeName() string
- type MapIterator
- type ModuleMap
- func (m *ModuleMap) Add(name string, module Importable)
- func (m *ModuleMap) AddBuiltinModule(name string, attrs map[string]Object)
- func (m *ModuleMap) AddMap(o *ModuleMap)
- func (m *ModuleMap) AddSourceModule(name string, src []byte)
- func (m *ModuleMap) Copy() *ModuleMap
- func (m *ModuleMap) Each(f func(name string, mod Importable))
- func (m *ModuleMap) Get(name string) Importable
- func (m *ModuleMap) GetBuiltinModule(name string) *BuiltinModule
- func (m *ModuleMap) GetSourceModule(name string) *SourceModule
- func (m *ModuleMap) Len() int
- func (m *ModuleMap) Remove(name string)
- type Native
- type NativeFuncSpec
- type NativeKind
- type NativeStructFieldSpec
- type NativeStructSpec
- type Object
- func CallFunc(ctx context.Context, fn Object, args ...Object) (Object, error)
- func FixDecodedObject(o Object, modules *ModuleMap) (Object, error)
- func FromInterface(v interface{}) (Object, error)
- func MakeObject(code byte) Object
- func UnmarshalLive(buf []byte) (Object, error)
- func UnmarshalObject(nn int, b []byte) (n int, o Object, err error)
- type ObjectImpl
- func (o *ObjectImpl) BinaryOp(_ token.Token, _ Object) (Object, error)
- func (o *ObjectImpl) Call(_ context.Context, _ ...Object) (ret Object, err error)
- func (o *ObjectImpl) CanCall() bool
- func (o *ObjectImpl) CanIterate() bool
- func (o *ObjectImpl) Copy() Object
- func (o *ObjectImpl) Equals(x Object) bool
- func (o *ObjectImpl) Freeze()
- func (o *ObjectImpl) IndexGet(_ Object) (res Object, err error)
- func (o *ObjectImpl) IndexSet(_, _ Object) (err error)
- func (o *ObjectImpl) IsFalsy() bool
- func (o *ObjectImpl) IsFrozen() bool
- func (o *ObjectImpl) Iterate() Iterator
- func (o *ObjectImpl) Melt()
- func (o *ObjectImpl) String() string
- func (o *ObjectImpl) TypeName() string
- type ObjectPtr
- type Permissions
- func (p Permissions) WithDenyChdir() Permissions
- func (p Permissions) WithDenyEnvWrite() Permissions
- func (p Permissions) WithDenyExec() Permissions
- func (p Permissions) WithDenyExit() Permissions
- func (p Permissions) WithDenyFileRead() Permissions
- func (p Permissions) WithDenyFileWrite() Permissions
- type Ptr
- type RangeIterator
- func (it *RangeIterator) Copy() Object
- func (it *RangeIterator) Equals(Object) bool
- func (it *RangeIterator) IsFalsy() bool
- func (it *RangeIterator) Key() Object
- func (it *RangeIterator) Next() bool
- func (it *RangeIterator) String() string
- func (it *RangeIterator) TypeName() string
- func (it *RangeIterator) Value() Object
- type RangeObject
- func (r *RangeObject) CanIterate() bool
- func (r *RangeObject) Copy() Object
- func (r *RangeObject) Equals(x Object) bool
- func (r *RangeObject) IndexGet(index Object) (Object, error)
- func (r *RangeObject) IsFalsy() bool
- func (r *RangeObject) Iterate() Iterator
- func (r *RangeObject) String() string
- func (r *RangeObject) TypeName() string
- type RemoteChanCore
- type RoutineHandle
- type Rune
- type SourceModule
- type String
- func (o *String) BinaryOp(op token.Token, rhs Object) (Object, error)
- func (o *String) CanIterate() bool
- func (o *String) Copy() Object
- func (o *String) Equals(x Object) bool
- func (o *String) IndexGet(index Object) (res Object, err error)
- func (o *String) IsFalsy() bool
- func (o *String) Iterate() Iterator
- func (o *String) String() string
- func (o *String) TypeName() string
- type StringIterator
- func (i *StringIterator) Copy() Object
- func (i *StringIterator) Equals(Object) bool
- func (i *StringIterator) IsFalsy() bool
- func (i *StringIterator) Key() Object
- func (i *StringIterator) Next() bool
- func (i *StringIterator) String() string
- func (i *StringIterator) TypeName() string
- func (i *StringIterator) Value() Object
- type StructInstance
- func (s *StructInstance) BinaryOp(op token.Token, rhs Object) (Object, error)
- func (s *StructInstance) CanIterate() bool
- func (s *StructInstance) Copy() Object
- func (s *StructInstance) Equals(x Object) bool
- func (s *StructInstance) Freeze()
- func (s *StructInstance) IndexGet(index Object) (Object, error)
- func (s *StructInstance) IndexSet(index, value Object) error
- func (s *StructInstance) IsFalsy() bool
- func (s *StructInstance) IsFrozen() bool
- func (s *StructInstance) Iterate() Iterator
- func (s *StructInstance) Melt()
- func (s *StructInstance) String() string
- func (s *StructInstance) TypeName() string
- type Symbol
- type SymbolScope
- type SymbolTable
- func (t *SymbolTable) BuiltinSymbols() []*Symbol
- func (t *SymbolTable) Define(name string) *Symbol
- func (t *SymbolTable) DefineBuiltin(index int, name string) *Symbol
- func (t *SymbolTable) Fork(block bool) *SymbolTable
- func (t *SymbolTable) FreeSymbols() []*Symbol
- func (t *SymbolTable) MaxSymbols() int
- func (t *SymbolTable) Names() []string
- func (t *SymbolTable) Parent(skipBlock bool) *SymbolTable
- func (t *SymbolTable) Resolve(name string, recur bool) (*Symbol, int, bool)
- type Uint
- type Uint8
- type Uint16
- type Uint64
- type Undefined
- func (o *Undefined) CanIterate() bool
- func (o *Undefined) Copy() Object
- func (o *Undefined) Equals(x Object) bool
- func (o *Undefined) IndexGet(_ Object) (Object, error)
- func (o *Undefined) IsFalsy() bool
- func (o *Undefined) Iterate() Iterator
- func (o *Undefined) Key() Object
- func (o *Undefined) Next() bool
- func (o *Undefined) String() string
- func (o *Undefined) TypeName() string
- func (o *Undefined) Value() Object
- type UserType
- type UserTypeKind
- type VM
- func (v *VM) Abort()
- func (v *VM) Config() Config
- func (v *VM) Globals() []Object
- func (v *VM) IsStackEmpty() bool
- func (v *VM) Permissions() Permissions
- func (v *VM) Run() (err error)
- func (v *VM) RunCompiled(fn *CompiledFunction, args ...Object) (val Object, err error)
- func (v *VM) ShallowClone() *VM
Constants ¶
This section is empty.
Variables ¶
var ( // ErrStackOverflow is a stack overflow error. ErrStackOverflow = errors.New("stack overflow") // ErrObjectAllocLimit is an objects allocation limit error. ErrObjectAllocLimit = errors.New("object allocation limit exceeded") // ErrIndexOutOfBounds is an error where a given index is out of the // bounds. ErrIndexOutOfBounds = errors.New("index out of bounds") // ErrInvalidIndexType represents an invalid index type. ErrInvalidIndexType = errors.New("invalid index type") // ErrInvalidIndexValueType represents an invalid index value type. ErrInvalidIndexValueType = errors.New("invalid index value type") // ErrInvalidIndexOnError represents an invalid index on error. ErrInvalidIndexOnError = errors.New("invalid index on error") // ErrInvalidOperator represents an error for invalid operator usage. ErrInvalidOperator = errors.New("invalid operator") // ErrWrongNumArguments represents a wrong number of arguments error. ErrWrongNumArguments = errors.New("wrong number of arguments") // ErrBytesLimit represents an error where the size of bytes value exceeds // the limit. ErrBytesLimit = errors.New("exceeding bytes size limit") // ErrStringLimit represents an error where the size of string value // exceeds the limit. ErrStringLimit = errors.New("exceeding string size limit") // ErrNotIndexable is an error where an Object is not indexable. ErrNotIndexable = errors.New("not indexable") // ErrNotIndexAssignable is an error where an Object is not index // assignable. ErrNotIndexAssignable = errors.New("not index-assignable") // ErrNotImplemented is an error where an Object has not implemented a // required method. ErrNotImplemented = errors.New("not implemented") // ErrInvalidRangeStep is an error where the step parameter is less than or equal to 0 when using builtin range function. ErrInvalidRangeStep = errors.New("range step must be greater than 0") // ErrVMAborted is an error to denote the VM was forcibly terminated without proper exit. ErrVMAborted = errors.New("virtual machine aborted") // ErrChannelAlreadyClosed is returned when close() is called on an already-closed channel. ErrChannelAlreadyClosed = errors.New("channel already closed") // ErrSendOnClosedChannel is returned when send() is called on a closed channel. ErrSendOnClosedChannel = errors.New("send on closed channel") // ErrDivisionByZero is returned when an integer division or modulo // operation has a zero right-hand operand. ErrDivisionByZero = errors.New("division by zero") // ErrNotPermitted is returned when a script attempts an operation that has // been denied by the VM's Permissions configuration. ErrNotPermitted = errors.New("operation not permitted") // ErrFormatWidthLimit is returned when a width or precision specifier in a // format string exceeds Config.MaxFormatWidth. This prevents a DoS where a // tiny format string such as "%999999d" would allocate ~1 MB of padding. ErrFormatWidthLimit = errors.New("format width/precision exceeds limit") // ErrModifyFrozen is returned when a script attempts to mutate (e.g. // IndexSet, append-in-place, delete) a value that has been frozen via the // `freeze` builtin or constructed as a frozen module export. ErrModifyFrozen = errors.New("cannot modify frozen object") )
var DefaultConfig = &defaultCfg
DefaultConfig is the Config used when nil is passed to NewVM. Treat it as read-only. Use ConfigFromContext(ctx) inside builtin functions to respect the running VM's per-instance configuration.
Functions ¶
func CountObjects ¶
CountObjects returns the number of objects that a given object o contains. For scalar value types, it will always be 1. For compound value types, this will include its elements and all of their elements recursively.
func Format ¶
Format is like fmt.Sprintf but using Objects. It applies DefaultConfig's MaxFormatWidth limit to width and precision specifiers.
func FormatInstructions ¶
FormatInstructions returns string representation of bytecode instructions.
func FormatWithConfig ¶
FormatWithConfig is like Format but uses the limits from cfg instead of DefaultConfig. cfg may be nil, in which case no MaxFormatWidth limit is applied (but MaxStringLen from DefaultConfig still guards the output size).
func MakeInstruction ¶
MakeInstruction returns a bytecode for an opcode and the operands.
func MarshalLive ¶
MarshalLive serialises an Object for live IPC (across SharedWorkers, RPC, etc.). Today it is a thin wrapper over MarshalObject — *Chan values get their core stripped automatically by encoding.go (see _chan case there) so only the chan id travels.
Use ResolveChans on the receiving side to upgrade nil-core *Chan back to a LocalChanCore (when the receiver owns the chan) or a RemoteChanCore (when it does not).
func MarshalObject ¶
MarshalObject marshals the given object into a byte slice.
func NativeSupported ¶
func NativeSupported() bool
NativeSupported reports whether the current build includes FFI (native) support. It returns false in non-native builds and true when compiled with -tags native.
func NewChanID ¶
func NewChanID() int64
NewChanID mints a fresh globally-unique chan id without allocating a Chan. Used by transports that own queues out-of-band (e.g. the js/wasm SharedArrayBuffer-backed chan in the coordinator) but still need an id in the same address space as locally-created chans.
func ResolveChans ¶
func ResolveChans(o Object, registry *ChanRegistry, fallback ChanTransport)
ResolveChans walks o and binds every *Chan with a nil Core to either a local core (when the chan is in registry) or a fresh RemoteChanCore using fallback. The walk handles arrays, maps, error wrappers, and CompiledFunction Free cells. ObjectPtr is followed.
Cycles are tolerated through a visited-set keyed by *Chan/*Map/*Array to avoid infinite recursion on self-referential structures.
func ResolveNativePath ¶
ResolveNativePath always returns an empty string in non-native builds. Native FFI is not compiled in, so no library path can be resolved.
func SizeOfObject ¶
SizeOfObject returns the size of the given object.
func SizeOfObjectPtr ¶
SizeOfObjectPtr returns the size of the given object pointer.
Must mirror the marshaler used in the _compiledFunction Free-slice path, which calls MarshalObject(*ObjectPtr) — that dispatches to the _objectPtr case which writes a 1-byte type tag plus the inner value. Returning only SizeOfObject(*op.Value) would under-count by one byte per free variable and cause MarshalSlice's trailing sentinel write to panic with "slice bounds out of range" once the slice is non-empty.
func ToByteSlice ¶
ToByteSlice will try to convert object o to []byte value.
func ToInterface ¶
func ToInterface(o Object) (res interface{})
ToInterface attempts to convert an object o to an interface{} value
func ToPtr ¶
ToPtr tries to convert object o to an unsafe.Pointer value. Only an existing Ptr or Undefined (nil) are accepted; integer-to-pointer coercion is intentionally rejected to prevent scripts from fabricating arbitrary memory addresses.
func TypeOfObject ¶
TypeOfObject returns the type code of the given object.
Types ¶
type Array ¶
type Array struct {
ObjectImpl
Value []Object
Frozen bool
// contains filtered or unexported fields
}
Array represents an array of objects.
func NewFrozenArray ¶
NewFrozenArray returns a Frozen *Array wrapping the given slice. The slice is used as-is (the caller must not retain a mutable reference to it).
func (*Array) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*Array) CanIterate ¶
CanIterate returns whether the Object can be Iterated.
func (*Array) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
func (*Array) Freeze ¶
func (o *Array) Freeze()
Freeze marks the array as immutable. Subsequent IndexSet calls return ErrModifyFrozen.
type ArrayIterator ¶
type ArrayIterator struct {
ObjectImpl
// contains filtered or unexported fields
}
ArrayIterator is an iterator for an array.
func (*ArrayIterator) Equals ¶
func (i *ArrayIterator) Equals(Object) bool
Equals returns true if the value of the type is equal to the value of another object.
func (*ArrayIterator) IsFalsy ¶
func (i *ArrayIterator) IsFalsy() bool
IsFalsy returns true if the value of the type is falsy.
func (*ArrayIterator) Key ¶
func (i *ArrayIterator) Key() Object
Key returns the key or index value of the current element.
func (*ArrayIterator) Next ¶
func (i *ArrayIterator) Next() bool
Next returns true if there are more elements to iterate.
func (*ArrayIterator) String ¶
func (i *ArrayIterator) String() string
func (*ArrayIterator) TypeName ¶
func (i *ArrayIterator) TypeName() string
TypeName returns the name of the type.
func (*ArrayIterator) Value ¶
func (i *ArrayIterator) Value() Object
Value returns the value of the current element.
type Bool ¶
type Bool struct {
ObjectImpl
// contains filtered or unexported fields
}
Bool represents a boolean value.
func (*Bool) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type BuiltinFunction ¶
type BuiltinFunction struct {
ObjectImpl
Name string
Value CallableFunc
}
BuiltinFunction represents a builtin function.
func GetAllBuiltinFunctions ¶
func GetAllBuiltinFunctions() []*BuiltinFunction
GetAllBuiltinFunctions returns all builtin function objects.
func (*BuiltinFunction) CanCall ¶
func (o *BuiltinFunction) CanCall() bool
CanCall returns whether the Object can be Called.
func (*BuiltinFunction) Copy ¶
func (o *BuiltinFunction) Copy() Object
Copy returns a copy of the type.
func (*BuiltinFunction) Equals ¶
func (o *BuiltinFunction) Equals(x Object) bool
Equals returns true if the value of the type is equal to the value of another object. Two BuiltinFunction instances are equal when they share the same non-empty name, which uniquely identifies a builtin in the registry.
func (*BuiltinFunction) String ¶
func (o *BuiltinFunction) String() string
func (*BuiltinFunction) TypeName ¶
func (o *BuiltinFunction) TypeName() string
TypeName returns the name of the type.
type BuiltinModule ¶
BuiltinModule is an importable module that's written in Go.
func (*BuiltinModule) AsFrozenMap ¶
func (m *BuiltinModule) AsFrozenMap(moduleName string) *Map
AsFrozenMap converts builtin module into a Frozen *Map carrying the given module name. The name "AsFrozenMap" is preserved for API compatibility — the returned map is now an ordinary *Map with its Frozen flag set.
func (*BuiltinModule) Import ¶
func (m *BuiltinModule) Import(moduleName string) (interface{}, error)
Import returns a Frozen map for the module.
type Byte ¶
type Byte struct {
ObjectImpl
Value byte
}
Byte represents a byte value (signed 8-bit in rumo semantics; stored as Go byte).
type Bytecode ¶
type Bytecode struct {
FileSet *parser.SourceFileSet
MainFunction *CompiledFunction
Constants []Object
// Embeds records every file that was embedded at compile time via an
// //embed directive, in compilation order. It is serialized as part of
// the bytecode body so that tools like rumo.Stat can report embedded
// files without re-running the compiler.
Embeds []EmbedFile
// contains filtered or unexported fields
}
Bytecode is a compiled instructions and constants. mu protects concurrent access to MainFunction.Instructions and Constants: RemoveDuplicates holds the write lock; Marshal and any read-only inspection hold the read lock.
func (*Bytecode) CountObjects ¶
CountObjects returns the number of objects found in Constants.
func (*Bytecode) FormatConstants ¶
FormatConstants returns human readable string representations of compiled constants.
func (*Bytecode) FormatInstructions ¶
FormatInstructions returns human readable string representations of compiled instructions.
func (*Bytecode) Marshal ¶
Marshal writes Bytecode data to the writer. The encoding begins with a builtin name table that maps the OpGetBuiltin indices used in this bytecode to their canonical names. On Unmarshal the names are resolved to the current runtime indices, so compiled bytecode remains correct even when new builtins are inserted at arbitrary positions in the registration list.
func (*Bytecode) RemoveDuplicates ¶
func (b *Bytecode) RemoveDuplicates()
RemoveDuplicates finds and remove the duplicate values in Constants. Note this function mutates Bytecode.
type Bytes ¶
type Bytes struct {
ObjectImpl
Value []byte
}
Bytes represents a byte array.
func (*Bytes) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*Bytes) CanIterate ¶
CanIterate returns whether the Object can be Iterated.
func (*Bytes) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type BytesIterator ¶
type BytesIterator struct {
ObjectImpl
// contains filtered or unexported fields
}
BytesIterator represents an iterator for a string.
func (*BytesIterator) Equals ¶
func (i *BytesIterator) Equals(Object) bool
Equals returns true if the value of the type is equal to the value of another object.
func (*BytesIterator) Key ¶
func (i *BytesIterator) Key() Object
Key returns the key or index value of the current element.
func (*BytesIterator) Next ¶
func (i *BytesIterator) Next() bool
Next returns true if there are more elements to iterate.
func (*BytesIterator) String ¶
func (i *BytesIterator) String() string
func (*BytesIterator) TypeName ¶
func (i *BytesIterator) TypeName() string
TypeName returns the name of the type.
func (*BytesIterator) Value ¶
func (i *BytesIterator) Value() Object
Value returns the value of the current element.
type CallableFunc ¶
CallableFunc is a function signature for the callable functions.
type Chan ¶
type Chan struct {
ObjectImpl
// contains filtered or unexported fields
}
Chan is the script-visible channel object. It exposes the same surface as the legacy `*Map{send,recv,close}` shape (so existing scripts work without changes) but routes through a pluggable Core, which can be either:
- LocalChanCore: backed by a Go channel (the native default).
- RemoteChanCore: backed by a ChanTransport, used by the js/wasm runtime so that channels created in one SharedWorker can be used by send/recv calls running in a different SharedWorker.
Each Chan has a globally unique int64 id within the running process. The id is what travels over the wire when a Chan is marshalled into a routine spawn payload. The receiving side resolves the id either to its own local core (if it owns the channel) or to a RemoteChanCore that posts back to the owner via a ChanTransport.
func NewLocalChan ¶
NewLocalChan creates a buffered chan backed by a local Go channel. Used by the native runtime and by the coordinator SharedWorker (which owns chan queues and serves send/recv calls from remote vm-host workers).
func NewRemoteChan ¶
func NewRemoteChan(id int64, tr ChanTransport) *Chan
NewRemoteChan returns a Chan whose send/recv/close calls route through the supplied transport. Useful for vm-host SharedWorkers that need to interact with channels owned by the coordinator.
type ChanCore ¶
type ChanCore interface {
Send(ctx context.Context, val Object) error
Recv(ctx context.Context) (Object, error)
Close() error
ID() int64
}
ChanCore is the abstract backing for a Chan. Native and remote chans both implement this. ctx is the caller's VM context — used to abort the call if the VM is being torn down.
type ChanRegistry ¶
type ChanRegistry struct {
// contains filtered or unexported fields
}
ChanRegistry tracks every locally-owned chan by id so that incoming transport messages can resolve the target. Both the coordinator (which hosts every queue) and any VM that creates a chan locally use this.
func NewChanRegistry ¶
func NewChanRegistry() *ChanRegistry
NewChanRegistry returns an empty registry.
func (*ChanRegistry) Forget ¶
func (r *ChanRegistry) Forget(id int64)
Forget removes id from the registry. Called by Close paths.
func (*ChanRegistry) Lookup ¶
func (r *ChanRegistry) Lookup(id int64) *Chan
Lookup returns the chan associated with id (or nil).
func (*ChanRegistry) Register ¶
func (r *ChanRegistry) Register(c *Chan)
Register inserts a chan into the registry, keyed by its id.
type ChanTransport ¶
type ChanTransport interface {
// SendOp blocks until the owner accepts the value or returns an error.
SendOp(ctx context.Context, chanID int64, val Object) error
// RecvOp blocks until the owner returns a value or an error.
RecvOp(ctx context.Context, chanID int64) (Object, error)
// CloseOp closes the chan on the owner side.
CloseOp(ctx context.Context, chanID int64) error
}
ChanTransport is the abstract wire used by RemoteChanCore. It carries chan ops between SharedWorkers (in js/wasm) or between processes (any future RPC backend). Implementations must serialise the value via the live codec and may block until the remote side acks.
type Char ¶
type Char struct {
ObjectImpl
Value rune
}
Char represents a character value.
func (*Char) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*Char) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type CompiledFunction ¶
type CompiledFunction struct {
ObjectImpl
Instructions []byte
NumLocals int // number of local variables (including function parameters)
NumParameters int
VarArgs bool
SourceMap map[int]parser.Pos
Free []*ObjectPtr
// contains filtered or unexported fields
}
CompiledFunction represents a compiled function.
func (*CompiledFunction) CanCall ¶
func (o *CompiledFunction) CanCall() bool
CanCall returns whether the Object can be Called.
func (*CompiledFunction) Copy ¶
func (o *CompiledFunction) Copy() Object
Copy returns a copy of the type.
func (*CompiledFunction) Equals ¶
func (o *CompiledFunction) Equals(_ Object) bool
Equals returns true if the value of the type is equal to the value of another object.
func (*CompiledFunction) SourcePos ¶
func (o *CompiledFunction) SourcePos(ip int) parser.Pos
SourcePos returns the source position of the instruction at ip.
func (*CompiledFunction) String ¶
func (o *CompiledFunction) String() string
func (*CompiledFunction) TypeName ¶
func (o *CompiledFunction) TypeName() string
TypeName returns the name of the type.
type Compiler ¶
type Compiler struct {
// contains filtered or unexported fields
}
Compiler compiles the AST into a bytecode.
func NewCompiler ¶
func NewCompiler(file *parser.SourceFile, symbolTable *SymbolTable, constants []Object, modules *ModuleMap, trace io.Writer) *Compiler
NewCompiler creates a Compiler.
func (*Compiler) EnableFileImport ¶
EnableFileImport enables or disables module loading from local files. Local file modules are disabled by default.
func (*Compiler) SetImportDir ¶
SetImportDir sets the initial import directory path for file imports. When no FS has been provided via SetImportFS, a default os.DirFS(dir) is created automatically so that all file reads are routed through the fs.FS abstraction.
func (*Compiler) SetImportFS ¶
SetImportFS sets a custom fs.FS implementation used to resolve import and embed paths. The FS should be rooted at the same directory as importBase so that security containment checks (isPathWithinBase) still apply correctly. Call SetImportDir first so that importBase is established, then call SetImportFS to override the default os.DirFS with a virtualised filesystem. This enables sandboxed compilation (e.g. in WASM / wasip1 environments) where os.ReadFile is unavailable or restricted.
func (*Compiler) Warnings ¶
func (c *Compiler) Warnings() []*CompilerWarning
Warnings returns all non-fatal diagnostics emitted during compilation. It collects warnings from child (module) compilers as well.
type CompilerError ¶
type CompilerError struct {
FileSet *parser.SourceFileSet
Node parser.Node
Err error
}
CompilerError represents a compiler error.
func (*CompilerError) Error ¶
func (e *CompilerError) Error() string
type CompilerWarning ¶
type CompilerWarning struct {
FileSet *parser.SourceFileSet
Node parser.Node
Message string
}
CompilerWarning represents a non-fatal diagnostic emitted during compilation.
func (*CompilerWarning) String ¶
func (w *CompilerWarning) String() string
type Config ¶
type Config struct {
// GlobalsSize is the maximum number of global variables for a VM.
GlobalsSize int
// StackSize is the maximum stack size for a VM.
StackSize int
// MaxFrames is the maximum number of function frames for a VM.
MaxFrames int
// MaxAllocs is the maximum number of object allocations (-1 = unlimited).
MaxAllocs int64
// MaxStringLen is the maximum byte-length for string values.
MaxStringLen int
// MaxBytesLen is the maximum length for bytes values.
MaxBytesLen int
// MaxFormatWidth is the maximum width or precision allowed in a single
// format verb (e.g. the "999999" in "%999999d"). Values above this limit
// cause Format / FormatWithConfig to return ErrFormatWidthLimit instead of
// allocating a potentially huge string. 0 is replaced by DefaultConfig's
// value during eval(); set to -1 to disable the limit entirely.
MaxFormatWidth int
// Permissions restricts which privileged os-module operations are allowed.
// The zero value of Permissions allows all operations.
Permissions Permissions
// Spawner overrides the in-process goroutine used by the `go fn(...)` /
// routine.start primitive. When non-nil, the VM calls Spawner instead of
// launching a child VM via `go func() { vm.RunCompiled(...) }()`. The
// returned RoutineHandle is wrapped in the script-visible
// {result, wait, stop} object.
//
// Native builds leave Spawner nil so behaviour is unchanged. The js/wasm
// runtime installs a Spawner that posts a `runVM` message to a fresh
// SharedWorker per call, realising the "every `go` is its own worker"
// model.
Spawner func(ctx context.Context, fn Object, args []Object) (RoutineHandle, error)
// ChanFactory overrides the backing implementation returned by the `chan`
// builtin. When nil, builtinChan returns the local Go-channel-backed
// implementation. The js/wasm runtime installs a factory that returns a
// channel proxy whose send/recv route through the coordinator
// SharedWorker, so values can travel across worker boundaries.
ChanFactory func(buf int) (Object, error)
}
Config holds the VM limits. Pass a *Config to NewVM to override the defaults. Passing nil selects DefaultConfig. Zero values in a non-nil Config are filled in from DefaultConfig by the eval method.
func ConfigFromContext ¶
ConfigFromContext returns the configuration of the VM stored in ctx. If ctx does not contain a running VM (e.g. in tests that call builtin functions directly with context.Background()), DefaultConfig is returned as a fallback so existing behaviour is preserved.
func UnlimitedConfig ¶
func UnlimitedConfig() *Config
UnlimitedConfig returns a Config with all resource limits disabled, equivalent to the pre-safe-defaults behaviour. Use it when the script is fully trusted and may need to process arbitrarily large data or perform a very large number of allocations.
type ContextKey ¶
type ContextKey string
ContextKey is a type for context keys used in the VM.
func (ContextKey) String ¶
func (c ContextKey) String() string
type EmbedFile ¶
type EmbedFile struct {
// Name is the path of the file relative to the script's import directory,
// using forward slashes (e.g. "assets/logo.png").
Name string
// Size is the byte length of the file's content at compile time.
Size int
}
EmbedFile describes a single file that was baked into the bytecode by an //embed directive at compile time.
type ErrInvalidArgumentType ¶
ErrInvalidArgumentType represents an invalid argument value type error.
func (ErrInvalidArgumentType) Error ¶
func (e ErrInvalidArgumentType) Error() string
type ErrPanic ¶
type ErrPanic struct {
// contains filtered or unexported fields
}
ErrPanic is an error where panic happended in the VM.
type Error ¶
type Error struct {
ObjectImpl
Value Object
}
Error represents an error value.
func (*Error) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type Float32 ¶
type Float32 struct {
ObjectImpl
Value float32
}
Float32 represents a 32-bit floating point number value (maps to C float).
func (*Float32) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*Float32) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type Float64 ¶
type Float64 struct {
ObjectImpl
Value float64
}
Float64 represents a 64-bit floating point number value (maps to C double).
func (*Float64) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*Float64) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type Importable ¶
type Importable interface {
// Import should return either an Object or module source code ([]byte).
Import(moduleName string) (interface{}, error)
}
Importable interface represents importable module instance.
type Int ¶
type Int struct {
ObjectImpl
Value int64
}
Int represents an integer value.
func NewInt ¶
NewInt returns an *Int for v. For v in [-128, 127] a pre-allocated cached instance is returned so that arithmetic-heavy scripts do not churn the GC.
func (*Int) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*Int) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type Int64 ¶
type Int64 = Int
Int64 is an alias for Int; Int is stored as int64 so Int64 is identical.
type Iterator ¶
type Iterator interface {
Object
// Next returns true if there are more elements to iterate.
Next() bool
// Key returns the key or index value of the current element.
Key() Object
// Value returns the value of the current element.
Value() Object
}
Iterator represents an iterator for underlying data type.
type LocalChanCore ¶
type LocalChanCore struct {
// contains filtered or unexported fields
}
LocalChanCore is the native, in-process backing for a Chan. It re-uses the pre-existing objchan struct so that all the existing close-state and abort semantics keep working unchanged.
func (*LocalChanCore) Close ¶
func (l *LocalChanCore) Close() error
func (*LocalChanCore) ID ¶
func (l *LocalChanCore) ID() int64
type Map ¶
type Map struct {
ObjectImpl
Value map[string]Object
Frozen bool
// contains filtered or unexported fields
}
Map represents a map of objects.
func NewFrozenMap ¶
NewFrozenMap returns a Frozen *Map. moduleName may be empty for ordinary Frozen maps; module proxies set it to the imported module's name.
func (*Map) CanIterate ¶
CanIterate returns whether the Object can be Iterated.
func (*Map) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
func (*Map) Iterate ¶
Iterate creates a map iterator. It snapshots the current keys and values so the iterator is not affected by concurrent mutations.
func (*Map) ModuleName ¶
ModuleName returns the module name associated with this map (only set on Frozen module proxies). Returns an empty string for user-constructed maps.
type MapIterator ¶
type MapIterator struct {
ObjectImpl
// contains filtered or unexported fields
}
MapIterator represents an iterator for the map.
func (*MapIterator) Equals ¶
func (i *MapIterator) Equals(Object) bool
Equals returns true if the value of the type is equal to the value of another object.
func (*MapIterator) IsFalsy ¶
func (i *MapIterator) IsFalsy() bool
IsFalsy returns true if the value of the type is falsy.
func (*MapIterator) Key ¶
func (i *MapIterator) Key() Object
Key returns the key or index value of the current element.
func (*MapIterator) Next ¶
func (i *MapIterator) Next() bool
Next returns true if there are more elements to iterate.
func (*MapIterator) String ¶
func (i *MapIterator) String() string
func (*MapIterator) TypeName ¶
func (i *MapIterator) TypeName() string
TypeName returns the name of the type.
func (*MapIterator) Value ¶
func (i *MapIterator) Value() Object
Value returns the value of the current element.
type ModuleMap ¶
type ModuleMap struct {
// contains filtered or unexported fields
}
ModuleMap represents a set of named modules. Use NewModuleMap to create a new module map.
func (*ModuleMap) Add ¶
func (m *ModuleMap) Add(name string, module Importable)
Add adds an import module.
func (*ModuleMap) AddBuiltinModule ¶
AddBuiltinModule adds a builtin module.
func (*ModuleMap) AddSourceModule ¶
AddSourceModule adds a source module.
func (*ModuleMap) Each ¶
func (m *ModuleMap) Each(f func(name string, mod Importable))
Each iterates over all named modules and applies the given function to each of them.
func (*ModuleMap) Get ¶
func (m *ModuleMap) Get(name string) Importable
Get returns an import module identified by name. It returns if the name is not found.
func (*ModuleMap) GetBuiltinModule ¶
func (m *ModuleMap) GetBuiltinModule(name string) *BuiltinModule
GetBuiltinModule returns a builtin module identified by name. It returns if the name is not found or the module is not a builtin module.
func (*ModuleMap) GetSourceModule ¶
func (m *ModuleMap) GetSourceModule(name string) *SourceModule
GetSourceModule returns a source module identified by name. It returns if the name is not found or the module is not a source module.
type Native ¶
type Native struct {
ObjectImpl
Path string
Funcs []NativeFuncSpec
Structs []NativeStructSpec
}
Native is a stub type used in non-native builds so that the bytecode deduplication switch in bytecode.go can still compile. It can never be instantiated at runtime because compileNative (compiler_native_stub.go) always returns an error before creating one. The Path and Funcs fields are populated during bytecode decoding so that Stat() can still inspect what native libraries a bytecode file would require.
func (*Native) NativePath ¶
NativePath returns the shared library path embedded in this loader constant.
type NativeFuncSpec ¶
type NativeFuncSpec struct {
Name string
Params []NativeKind
ParamStructIdx []int // parallel to Params; -1 if not NativeStruct
ParamPointer []bool // parallel to Params; true if declared as *Name
Return NativeKind // NativeVoid = no return
ReturnStructIdx int // -1 if Return is not NativeStruct
ReturnPointer bool // true if return declared as *Name
}
NativeFuncSpec is the compile-time description of a single native function binding captured from a `native ... { ... }` statement.
Scalar parameter / return types are encoded directly in the corresponding NativeKind. For NativeStruct entries the parallel ParamStructIdx / ReturnStructIdx slot points into Native.Structs, and the matching ParamPointer / ReturnPointer flag distinguishes between by-value and by pointer (`*Name`) passing semantics.
type NativeKind ¶
type NativeKind int
NativeKind identifies a rumo <-> C type mapping used by the native runtime. Each kind corresponds to exactly one C ABI type per the rumo Type Mapping table in doc/types.md.
const ( NativeInvalid NativeKind = iota NativeVoid // no value (return only) NativeByte // signed char / Go byte (treated as signed 8-bit) NativeInt8 // signed char / int8 NativeUint8 // unsigned char / uint8 NativeInt16 // short int / int16 NativeUint16 // short unsigned int / uint16 NativeInt32 // int / int32 (used for rumo Int) NativeUint32 // unsigned int / uint32 (used for rumo Uint) NativeInt64 // long long int / int64 NativeUint64 // long long unsigned int / uint64 NativeBool // bool NativeFloat32 // float <=> float32 NativeFloat64 // double <=> float64 NativeRune // wchar_t / int32 character NativeString // const char* (null-terminated) NativePtr // void* NativeBytes // void* (pointer to slice data) + length NativeStruct // user-declared struct (resolved via NativeFuncSpec.ParamStructIdx / ReturnStructIdx) // NativeInt is the rumo "int" which is implementation-defined as 32- or // 64-bit. We treat it as a C long (64-bit on modern targets) for ABI // convenience, matching the previous behavior. NativeInt = NativeInt64 // NativeUInt is the rumo "uint" equivalent of NativeInt. NativeUInt = NativeUint64 // NativeFloat is a backward-compatible alias for NativeFloat32 per the // new Type Mapping where "float" denotes a 32-bit IEEE 754 value. NativeFloat = NativeFloat32 // NativeDouble is the explicit 64-bit floating-point kind. NativeDouble = NativeFloat64 )
type NativeStructFieldSpec ¶
type NativeStructFieldSpec struct {
Name string
Kind NativeKind
StructIdx int // index into Native.Structs when Kind == NativeStruct, else -1
Pointer bool // reserved for future use; always false in v1
}
NativeStructFieldSpec describes a single field of a NativeStructSpec. A field may be a scalar (Kind != NativeStruct) or a nested struct (Kind == NativeStruct, StructIdx >= 0). Pointer field types are not supported in v1.
type NativeStructSpec ¶
type NativeStructSpec struct {
Name string
Fields []NativeStructFieldSpec
}
NativeStructSpec describes a struct declared inside a native block.
type Object ¶
type Object interface {
// TypeName should return the name of the type.
TypeName() string
// String should return a string representation of the type's value.
String() string
// BinaryOp should return another object that is the result of a given
// binary operator and a right-hand side object. If BinaryOp returns an
// error, the VM will treat it as a run-time error.
BinaryOp(op token.Token, rhs Object) (Object, error)
// IsFalsy should return true if the value of the type should be considered
// as falsy.
IsFalsy() bool
// Equals should return true if the value of the type should be considered
// as equal to the value of another object.
Equals(another Object) bool
// Copy should return a copy of the type (and its value). Copy function
// will be used for copy() builtin function which is expected to deep-copy
// the values generally.
Copy() Object
// IndexGet should take an index Object and return a result Object or an
// error for indexable objects. Indexable is an object that can take an
// index and return an object. If error is returned, the runtime will treat
// it as a run-time error and ignore returned value. If Object is not
// indexable, ErrNotIndexable should be returned as error. If nil is
// returned as value, it will be converted to UndefinedToken value by the
// runtime.
IndexGet(index Object) (value Object, err error)
// IndexSet should take an index Object and a value Object for index
// assignable objects. Index assignable is an object that can take an index
// and a value on the left-hand side of the assignment statement. If Object
// is not index assignable, ErrNotIndexAssignable should be returned as
// error. If an error is returned, it will be treated as a run-time error.
IndexSet(index, value Object) error
// Iterate should return an Iterator for the type.
Iterate() Iterator
// CanIterate should return whether the Object can be Iterated.
CanIterate() bool
// Call should take an arbitrary number of arguments and returns a return
// value and/or an error, which the VM will consider as a run-time error.
Call(ctx context.Context, args ...Object) (ret Object, err error)
// CanCall should return whether the Object can be Called.
CanCall() bool
// Freeze makes the object immutable. After Freeze, mutating operations
// (such as IndexSet) must return ErrNotIndexAssignable. Freeze is idempotent
// and is a no-op for objects whose value is already inherently immutable
// (Int, Float, String, Char, Bool, Bytes, ...).
Freeze()
// Melt makes the object mutable again. Melt is idempotent and is a
// no-op for objects whose value is inherently immutable.
Melt()
// IsFrozen reports whether the object is currently immutable. Inherently
// immutable objects always return true.
IsFrozen() bool
}
Object represents an object in the VM.
func CallFunc ¶
CallFunc invokes a rumo callback (compiled or builtin). For CompiledFunction values it extracts the parent VM from ctx, creates a shallow clone, and runs the function on the clone. For every other callable Object it falls back to Object.Call().
func FixDecodedObject ¶
FixDecodedObject re-binds module references and canonicalises decoded builtins / bools / undefined values inside o. Use it on objects produced by UnmarshalLive (e.g. globals shipped from another worker) before letting a VM call them — without it, *BuiltinFunction values have a nil Value pointer and *Map module proxies are still detached from their host implementations.
func FromInterface ¶
FromInterface will attempt to convert an interface{} v to a vm Object
func MakeObject ¶
MakeObject creates a new object based on the given type code. Returns nil if the type code is not recognised; callers should check for nil and convert it to an error rather than letting it propagate.
func UnmarshalLive ¶
UnmarshalLive deserialises an Object produced by MarshalLive. The returned object may contain *Chan values whose Core is nil — the caller must run ResolveChans before letting scripts call send/recv on them.
type ObjectImpl ¶
type ObjectImpl struct {
}
ObjectImpl represents a default Object Implementation. To defined a new value type, one can embed ObjectImpl in their type declarations to avoid implementing all non-significant methods. TypeName() and String() methods still need to be implemented.
func (*ObjectImpl) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*ObjectImpl) Call ¶
Call takes an arbitrary number of arguments and returns a return value and/or an error.
func (*ObjectImpl) CanCall ¶
func (o *ObjectImpl) CanCall() bool
CanCall returns whether the Object can be Called.
func (*ObjectImpl) CanIterate ¶
func (o *ObjectImpl) CanIterate() bool
CanIterate returns whether the Object can be Iterated.
func (*ObjectImpl) Equals ¶
func (o *ObjectImpl) Equals(x Object) bool
Equals returns true if the value of the type is equal to the value of another object.
func (*ObjectImpl) Freeze ¶
func (o *ObjectImpl) Freeze()
Freeze is a no-op for inherently immutable objects.
func (*ObjectImpl) IndexGet ¶
func (o *ObjectImpl) IndexGet(_ Object) (res Object, err error)
IndexGet returns an element at a given index.
func (*ObjectImpl) IndexSet ¶
func (o *ObjectImpl) IndexSet(_, _ Object) (err error)
IndexSet sets an element at a given index.
func (*ObjectImpl) IsFalsy ¶
func (o *ObjectImpl) IsFalsy() bool
IsFalsy returns true if the value of the type is falsy.
func (*ObjectImpl) IsFrozen ¶
func (o *ObjectImpl) IsFrozen() bool
IsFrozen returns true: types using the default ObjectImpl have no mutable state. Container types (Array, Map, StructInstance) override this method with a runtime-checked flag.
func (*ObjectImpl) Melt ¶
func (o *ObjectImpl) Melt()
Melt is a no-op for inherently immutable objects.
func (*ObjectImpl) String ¶
func (o *ObjectImpl) String() string
func (*ObjectImpl) TypeName ¶
func (o *ObjectImpl) TypeName() string
TypeName returns the name of the type.
type ObjectPtr ¶
type ObjectPtr struct {
ObjectImpl
Value *Object
}
ObjectPtr represents a free variable.
func (*ObjectPtr) Copy ¶
Copy returns a new ObjectPtr cell whose contents are a deep copy of the original. Returning o (the same pointer) would cause two callers — e.g. two VMs importing the same BuiltinModule — to share a single mutable cell, making a write through one caller visible in the other.
func (*ObjectPtr) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type Permissions ¶
type Permissions struct {
// AllowExec permits os.exec and os.start_process to launch subprocesses.
AllowExec bool
// AllowExit permits os.exit to terminate the host process.
AllowExit bool
// AllowEnvWrite permits os.setenv, os.unsetenv, and os.clearenv to mutate
// the host process's environment.
AllowEnvWrite bool
// AllowChdir permits os.chdir to change the host process's working directory.
AllowChdir bool
// AllowFileRead permits os.read_file and read-only os.open to read files.
AllowFileRead bool
// AllowFileWrite permits os.create and write-mode os.open_file to create
// or write files.
AllowFileWrite bool
}
Permissions controls which privileged operations in the os standard-library module are available to scripts. The zero value (all fields false) denies every operation — this is the safe, deny-by-default posture. Set individual Allow* fields to true to grant the corresponding capability. Use UnrestrictedPermissions() to enable all capabilities at once (opt-in to the old allow-all behaviour).
func UnrestrictedPermissions ¶
func UnrestrictedPermissions() Permissions
UnrestrictedPermissions returns a Permissions value that allows every privileged os-module operation. Pass this (or the result of its fluent With-methods) to Script.SetPermissions or Program.SetPermissions when the script is trusted and needs full host access.
func (Permissions) WithDenyChdir ¶
func (p Permissions) WithDenyChdir() Permissions
WithDenyChdir returns a copy of p with AllowChdir set to false.
func (Permissions) WithDenyEnvWrite ¶
func (p Permissions) WithDenyEnvWrite() Permissions
WithDenyEnvWrite returns a copy of p with AllowEnvWrite set to false.
func (Permissions) WithDenyExec ¶
func (p Permissions) WithDenyExec() Permissions
WithDenyExec returns a copy of p with AllowExec set to false.
func (Permissions) WithDenyExit ¶
func (p Permissions) WithDenyExit() Permissions
WithDenyExit returns a copy of p with AllowExit set to false.
func (Permissions) WithDenyFileRead ¶
func (p Permissions) WithDenyFileRead() Permissions
WithDenyFileRead returns a copy of p with AllowFileRead set to false.
func (Permissions) WithDenyFileWrite ¶
func (p Permissions) WithDenyFileWrite() Permissions
WithDenyFileWrite returns a copy of p with AllowFileWrite set to false.
type Ptr ¶
type Ptr struct {
ObjectImpl
Value unsafe.Pointer
}
Ptr represents an untyped pointer (unsafe.Pointer in Go, void* in C).
type RangeIterator ¶
type RangeIterator struct {
ObjectImpl
// contains filtered or unexported fields
}
RangeIterator is a lazy iterator over a RangeObject. It computes each element on demand, using O(1) memory regardless of range size.
func (*RangeIterator) Copy ¶
func (it *RangeIterator) Copy() Object
Copy returns an independent copy of the iterator at the same position.
func (*RangeIterator) Equals ¶
func (it *RangeIterator) Equals(Object) bool
Equals implements Object.
func (*RangeIterator) Key ¶
func (it *RangeIterator) Key() Object
Key returns the 0-based index of the current element.
func (*RangeIterator) Next ¶
func (it *RangeIterator) Next() bool
Next advances the iterator and returns true if a value is available.
func (*RangeIterator) TypeName ¶
func (it *RangeIterator) TypeName() string
TypeName implements Object.
func (*RangeIterator) Value ¶
func (it *RangeIterator) Value() Object
Value returns the current element without allocating the full range.
type RangeObject ¶
type RangeObject struct {
ObjectImpl
Start int64
Stop int64
Step int64 // always > 0
}
RangeObject is a lazy, iterable representation of an integer range produced by the built-in range(start, stop[, step]) function. It does not allocate the individual element values until they are actually consumed by a for-loop or explicit iteration, avoiding O(N) memory usage for large ranges.
func (*RangeObject) CanIterate ¶
func (r *RangeObject) CanIterate() bool
CanIterate always returns true.
func (*RangeObject) Copy ¶
func (r *RangeObject) Copy() Object
Copy returns a shallow copy of the RangeObject (all fields are value types).
func (*RangeObject) Equals ¶
func (r *RangeObject) Equals(x Object) bool
Equals reports whether x is a RangeObject with identical parameters.
func (*RangeObject) IndexGet ¶
func (r *RangeObject) IndexGet(index Object) (Object, error)
IndexGet returns the element at position index (0-based). Out-of-bounds access returns UndefinedValue (consistent with Array).
func (*RangeObject) IsFalsy ¶
func (r *RangeObject) IsFalsy() bool
IsFalsy returns true when the range contains no elements.
func (*RangeObject) Iterate ¶
func (r *RangeObject) Iterate() Iterator
Iterate returns a RangeIterator positioned before the first element.
type RemoteChanCore ¶
type RemoteChanCore struct {
// contains filtered or unexported fields
}
RemoteChanCore proxies ops to a ChanTransport. The id identifies the channel in the owner's registry.
func (*RemoteChanCore) Close ¶
func (r *RemoteChanCore) Close() error
func (*RemoteChanCore) ID ¶
func (r *RemoteChanCore) ID() int64
type RoutineHandle ¶
type RoutineHandle interface {
// Result blocks until the routine completes and returns its value or an
// Error wrapper. ctx is the caller's VM context (used by the host to
// abort if the parent VM is being torn down).
Result(ctx context.Context) (Object, error)
// Wait blocks until the routine completes or `seconds` elapses (negative
// means wait forever). Returns true if completed in time.
Wait(ctx context.Context, seconds int64) bool
// Cancel signals the routine to abort. It must be safe to call multiple
// times and from any goroutine.
Cancel()
}
RoutineHandle is the abstract interface satisfied by both the goroutine- backed routineVM and the SharedWorker-backed remote routine. The result of `go fn(...)` is wrapped in a script-level Map exposing {result, wait, stop}; those methods all delegate to the methods below.
type SourceModule ¶
type SourceModule struct {
Src []byte
}
SourceModule is an importable module that's written in vm.
func (*SourceModule) Import ¶
func (m *SourceModule) Import(_ string) (interface{}, error)
Import returns a module source code.
type String ¶
type String struct {
ObjectImpl
Value string
// contains filtered or unexported fields
}
String represents a string value.
func (*String) BinaryOp ¶
BinaryOp returns another object that is the result of a given binary operator and a right-hand side object.
func (*String) CanIterate ¶
CanIterate returns whether the Object can be Iterated.
func (*String) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
func (*String) IndexGet ¶
IndexGet returns a character at a given index. It scans the UTF-8 string one rune at a time so that a single index access does not need to decode (and allocate) the full rune slice.
type StringIterator ¶
type StringIterator struct {
ObjectImpl
// contains filtered or unexported fields
}
StringIterator represents an iterator for a string.
func (*StringIterator) Copy ¶
func (i *StringIterator) Copy() Object
Copy returns a copy of the type.
func (*StringIterator) Equals ¶
func (i *StringIterator) Equals(Object) bool
Equals returns true if the value of the type is equal to the value of another object.
func (*StringIterator) IsFalsy ¶
func (i *StringIterator) IsFalsy() bool
IsFalsy returns true if the value of the type is falsy.
func (*StringIterator) Key ¶
func (i *StringIterator) Key() Object
Key returns the key or index value of the current element.
func (*StringIterator) Next ¶
func (i *StringIterator) Next() bool
Next returns true if there are more elements to iterate.
func (*StringIterator) String ¶
func (i *StringIterator) String() string
func (*StringIterator) TypeName ¶
func (i *StringIterator) TypeName() string
TypeName returns the name of the type.
func (*StringIterator) Value ¶
func (i *StringIterator) Value() Object
Value returns the value of the current element.
type StructInstance ¶
type StructInstance struct {
ObjectImpl
Type *UserType
Values map[string]Object
Frozen bool
// contains filtered or unexported fields
}
StructInstance is a single value of a user-defined struct type. It supports indexed access by field name (`.x` and `["x"]`), iteration over fields, and equality against other instances of the same type.
func (*StructInstance) BinaryOp ¶
BinaryOp supports only equality/inequality via Equals elsewhere. Structs have no arithmetic operators.
func (*StructInstance) CanIterate ¶
func (s *StructInstance) CanIterate() bool
CanIterate returns true; struct instances iterate as (name, value) pairs.
func (*StructInstance) Copy ¶
func (s *StructInstance) Copy() Object
Copy returns a deep copy of the instance.
func (*StructInstance) Equals ¶
func (s *StructInstance) Equals(x Object) bool
Equals returns true if s and x are instances of the same user type and every field compares equal.
func (*StructInstance) Freeze ¶
func (s *StructInstance) Freeze()
Freeze marks the struct instance as immutable.
func (*StructInstance) IndexGet ¶
func (s *StructInstance) IndexGet(index Object) (Object, error)
IndexGet returns the value of the given field.
func (*StructInstance) IndexSet ¶
func (s *StructInstance) IndexSet(index, value Object) error
IndexSet assigns a value to an existing field, validating the declared type. Unknown fields are rejected.
func (*StructInstance) IsFalsy ¶
func (s *StructInstance) IsFalsy() bool
IsFalsy returns true if all field values are falsy.
func (*StructInstance) IsFrozen ¶
func (s *StructInstance) IsFrozen() bool
IsFrozen reports whether the struct instance has been Frozen.
func (*StructInstance) Iterate ¶
func (s *StructInstance) Iterate() Iterator
Iterate produces (fieldName, value) pairs in declared order.
func (*StructInstance) Melt ¶
func (s *StructInstance) Melt()
Melt makes the struct instance mutable again.
func (*StructInstance) String ¶
func (s *StructInstance) String() string
func (*StructInstance) TypeName ¶
func (s *StructInstance) TypeName() string
TypeName returns the name of the type.
type Symbol ¶
type Symbol struct {
Name string
Scope SymbolScope
Index int
LocalAssigned bool // if the local symbol is assigned at least once
}
Symbol represents a symbol in the symbol table.
type SymbolScope ¶
type SymbolScope string
SymbolScope represents a symbol scope.
const ( ScopeGlobal SymbolScope = "GLOBAL" ScopeLocal SymbolScope = "LOCAL" ScopeBuiltin SymbolScope = "BUILTIN" ScopeFree SymbolScope = "FREE" )
List of symbol scopes
type SymbolTable ¶
type SymbolTable struct {
// contains filtered or unexported fields
}
SymbolTable represents a symbol table.
func (*SymbolTable) BuiltinSymbols ¶
func (t *SymbolTable) BuiltinSymbols() []*Symbol
BuiltinSymbols returns builtin symbols for the scope.
func (*SymbolTable) Define ¶
func (t *SymbolTable) Define(name string) *Symbol
Define adds a new symbol in the current scope.
func (*SymbolTable) DefineBuiltin ¶
func (t *SymbolTable) DefineBuiltin(index int, name string) *Symbol
DefineBuiltin adds a symbol for builtin function.
func (*SymbolTable) Fork ¶
func (t *SymbolTable) Fork(block bool) *SymbolTable
Fork creates a new symbol table for a new scope.
func (*SymbolTable) FreeSymbols ¶
func (t *SymbolTable) FreeSymbols() []*Symbol
FreeSymbols returns free symbols for the scope.
func (*SymbolTable) MaxSymbols ¶
func (t *SymbolTable) MaxSymbols() int
MaxSymbols returns the total number of symbols defined in the scope.
func (*SymbolTable) Names ¶
func (t *SymbolTable) Names() []string
Names returns the name of all the symbols.
func (*SymbolTable) Parent ¶
func (t *SymbolTable) Parent(skipBlock bool) *SymbolTable
Parent returns the outer scope of the current symbol table.
type Uint ¶
type Uint struct {
ObjectImpl
Value uint32
}
Uint represents an unsigned 32-bit integer (per rumo Type Mapping).
type Uint8 ¶
type Uint8 struct {
ObjectImpl
Value uint8
}
Uint8 represents an unsigned 8-bit integer.
type Uint16 ¶
type Uint16 struct {
ObjectImpl
Value uint16
}
Uint16 represents an unsigned 16-bit integer.
type Uint64 ¶
type Uint64 struct {
ObjectImpl
Value uint64
}
Uint64 represents an unsigned 64-bit integer.
type Undefined ¶
type Undefined struct {
ObjectImpl
}
Undefined represents an undefined value.
func (*Undefined) CanIterate ¶
CanIterate returns whether the Object can be Iterated.
func (*Undefined) Equals ¶
Equals returns true if the value of the type is equal to the value of another object.
type UserType ¶
type UserType struct {
ObjectImpl
Name string
Kind UserTypeKind
// Struct metadata (UserTypeStruct). FieldTypes is parallel to Fields.
Fields []string
FieldTypes []string
// Func metadata (UserTypeFunc). ParamTypes is parallel to Params.
Params []string // parameter names (may be empty strings for unnamed)
ParamTypes []string
VarArgs bool
NumParams int // number of fixed parameters (excluding the varargs slot)
Result string // return type name; "" = no return
// Value metadata (UserTypeValue). Underlying is the name of the base
// type (e.g. "int", "string"). The converter is resolved lazily.
Underlying string
}
UserType is the runtime representation of a user-defined type introduced by a `type` statement.
A UserType is a callable value; invoking it constructs a value of the declared type:
- struct: returns a *StructInstance whose fields are initialised from positional or keyword arguments, each value validated against the declared field type.
- func: wraps the given callable so subsequent invocations validate their arguments (and return value) against the declared signature.
- value: delegates to the underlying built-in converter (int, float, string, bool, bytes, array, map, ...).
func (*UserType) Copy ¶
Copy returns the same UserType. Type definitions are immutable, so sharing is safe.
type UserTypeKind ¶
type UserTypeKind int
UserTypeKind identifies the form of a user-defined type.
const ( // UserTypeStruct is declared with `type X struct { ... }`. UserTypeStruct UserTypeKind = iota + 1 // UserTypeFunc is declared with `type X func(...)`. UserTypeFunc // UserTypeValue is declared with `type X Name` (alias / named value type). UserTypeValue )
type VM ¶
type VM struct {
In io.Reader
Out io.Writer
Args []string
// contains filtered or unexported fields
}
VM is a virtual machine that executes the bytecode compiled by Compiler.
func NewVM ¶
NewVM creates a VM. cfg sets limits (GlobalsSize, StackSize, MaxFrames, MaxAllocs); pass nil to use DefaultConfig. Zero fields in a non-nil cfg are filled from DefaultConfig.
func (*VM) Abort ¶
func (v *VM) Abort()
Abort aborts the execution of current VM and all its descendant VMs. The CAS guarantees that exactly one goroutine transitions aborting 0→1 and executes the abort body, eliminating the TOCTOU window that existed between the old atomic.Load check and the subsequent lock acquisition.
func (*VM) IsStackEmpty ¶
IsStackEmpty tests if the stack is empty or not.
func (*VM) Permissions ¶
func (v *VM) Permissions() Permissions
Permissions returns the permission set configured for this VM.
func (*VM) RunCompiled ¶
func (v *VM) RunCompiled(fn *CompiledFunction, args ...Object) (val Object, err error)
RunCompiled run the VM with user supplied function fn.
func (*VM) ShallowClone ¶
ShallowClone creates a shallow copy of the current VM, with separate stack, frame and globals. The copy shares constants with the original but gets its own snapshot of globals so that concurrent OpSetGlobal/OpGetGlobal operations in parent and child do not race on the same slice. ShallowClone is typically followed by RunCompiled to run user supplied compiled function.
Source Files
¶
- builtins.go
- builtins_new.go
- bytecode.go
- callfunc.go
- chan.go
- compiler.go
- compiler_native_stub.go
- compiler_type.go
- doc.go
- encoding.go
- errors.go
- formatter.go
- instructions.go
- iterator.go
- livecodec.go
- modules.go
- native_stub.go
- native_types.go
- numeric.go
- objects.go
- range.go
- routinevm.go
- select.go
- symbol_table.go
- types.go
- vm.go
- vvm.go