Documentation
¶
Index ¶
- Constants
- Variables
- func AllocWithin(n int64) bool
- func AsError(obj Object) string
- func BindGuard(guard *ResourceGuard) (release func())
- func ByteString(b byte) string
- func ClearGCReleaseHook(target any) error
- func CompareDepth(ctx context.Context) int
- func DefaultMaxBackgroundTasks() int64
- func DefaultMaxValueBytes() int64
- func DefaultMemoryLimit() int64
- func DetachRun(ctx context.Context) context.Context
- func DictKey(obj Object) string
- func DictStringKey(name string) string
- func FileEquals(path string, data []byte) bool
- func FloatStr(f float64) string
- func GetFloatArrayData(obj Object) ([]float64, []int, bool)
- func GetFloatMatrix(obj Object) (data []float64, rows, cols int, ok bool)
- func GrowthRoom(oldCap, size int) int64
- func InstanceDataFromContext(ctx context.Context) any
- func IsError(obj Object) bool
- func IsFloatArray(obj Object) bool
- func IsHashable(obj Object) bool
- func IsPropagating(obj Object) bool
- func IsReprContainer(obj Object) bool
- func IterSource(iterable Object) (func() (Object, bool), bool)
- func MaxValueBytes() int64
- func MemoryAccountingEnabled() bool
- func PythonTypeName(obj Object) string
- func ReadAllLimitedErr(r io.Reader, what string) ([]byte, error)
- func ReadFileLimitedErr(path string) ([]byte, error)
- func ReleaseArgs(env *Environment, args []Object)
- func ReleaseCallEnvironment(env *Environment)
- func ReleaseReturnValue(rv *ReturnValue)
- func ReprException(e *Exception) string
- func ReprString(v string) string
- func RunBlocking(ctx interface{ ... }, fn func())
- func SetCompareHooks(equal func(ctx context.Context, a, b Object) (bool, Object), ...)
- func SetDefaultMaxBackgroundTasks(n int64)
- func SetDefaultMaxValueBytes(n int64)
- func SetDefaultMemoryLimit(n int64)
- func SetGCReleaseHook(target any, hook func()) error
- func SlotsWithin(n int) bool
- func TrackAlloc[T any](p *T, size int64)
- func TrackMap(m any, size int64)
- func TrackSlice[E any](s []E)
- func TrackSliceWeighted[E any](s []E, perSlot int64)
- func ValidateTransferable(obj Object) error
- func WithCompareDepth(ctx context.Context, depth int) context.Context
- type Boolean
- func (b *Boolean) AsBool() (bool, Object)
- func (b *Boolean) AsDict() (map[string]Object, Object)
- func (b *Boolean) AsFloat() (float64, Object)
- func (b *Boolean) AsInt() (int64, Object)
- func (b *Boolean) AsList() ([]Object, Object)
- func (b *Boolean) AsString() (string, Object)
- func (b *Boolean) BoolValue() bool
- func (b *Boolean) CoerceFloat() (float64, Object)
- func (b *Boolean) CoerceInt() (int64, Object)
- func (b *Boolean) CoerceString() (string, Object)
- func (b *Boolean) Inspect() string
- func (b *Boolean) Type() ObjectType
- type BoundMethod
- func (bm *BoundMethod) AsBool() (bool, Object)
- func (bm *BoundMethod) AsDict() (map[string]Object, Object)
- func (bm *BoundMethod) AsFloat() (float64, Object)
- func (bm *BoundMethod) AsInt() (int64, Object)
- func (bm *BoundMethod) AsList() ([]Object, Object)
- func (bm *BoundMethod) AsString() (string, Object)
- func (bm *BoundMethod) CoerceFloat() (float64, Object)
- func (bm *BoundMethod) CoerceInt() (int64, Object)
- func (bm *BoundMethod) CoerceString() (string, Object)
- func (bm *BoundMethod) Inspect() string
- func (bm *BoundMethod) SelfArgs() []Object
- func (bm *BoundMethod) Type() ObjectType
- type Break
- func (b *Break) AsBool() (bool, Object)
- func (b *Break) AsDict() (map[string]Object, Object)
- func (b *Break) AsFloat() (float64, Object)
- func (b *Break) AsInt() (int64, Object)
- func (b *Break) AsList() ([]Object, Object)
- func (b *Break) AsString() (string, Object)
- func (b *Break) CoerceFloat() (float64, Object)
- func (b *Break) CoerceInt() (int64, Object)
- func (b *Break) CoerceString() (string, Object)
- func (b *Break) Inspect() string
- func (b *Break) Type() ObjectType
- type Builtin
- func (b *Builtin) AsBool() (bool, Object)
- func (b *Builtin) AsDict() (map[string]Object, Object)
- func (b *Builtin) AsFloat() (float64, Object)
- func (b *Builtin) AsInt() (int64, Object)
- func (b *Builtin) AsList() ([]Object, Object)
- func (b *Builtin) AsString() (string, Object)
- func (b *Builtin) CoerceFloat() (float64, Object)
- func (b *Builtin) CoerceInt() (int64, Object)
- func (b *Builtin) CoerceString() (string, Object)
- func (b *Builtin) Inspect() string
- func (b *Builtin) Type() ObjectType
- type BuiltinFunction
- type Bytes
- func (b *Bytes) AsBool() (bool, Object)
- func (b *Bytes) AsDict() (map[string]Object, Object)
- func (b *Bytes) AsFloat() (float64, Object)
- func (b *Bytes) AsInt() (int64, Object)
- func (b *Bytes) AsList() ([]Object, Object)
- func (b *Bytes) AsString() (string, Object)
- func (b *Bytes) BytesValue() []byte
- func (b *Bytes) CoerceFloat() (float64, Object)
- func (b *Bytes) CoerceInt() (int64, Object)
- func (b *Bytes) CoerceString() (string, Object)
- func (b *Bytes) Equal(other *Bytes) bool
- func (b *Bytes) Inspect() string
- func (b *Bytes) Len() int
- func (b *Bytes) Type() ObjectType
- type CallableSnapshot
- type Class
- func (c *Class) AsBool() (bool, Object)
- func (c *Class) AsDict() (map[string]Object, Object)
- func (c *Class) AsFloat() (float64, Object)
- func (c *Class) AsInt() (int64, Object)
- func (c *Class) AsList() ([]Object, Object)
- func (c *Class) AsString() (string, Object)
- func (c *Class) CoerceFloat() (float64, Object)
- func (c *Class) CoerceInt() (int64, Object)
- func (c *Class) CoerceString() (string, Object)
- func (c *Class) Inspect() string
- func (c *Class) InvalidateLookupCache()
- func (c *Class) LookupMember(name string) (Object, bool)
- func (c *Class) Type() ObjectType
- type ClassBuilder
- func (cb *ClassBuilder) BaseClass(base *Class) *ClassBuilder
- func (cb *ClassBuilder) Build() *Class
- func (cb *ClassBuilder) Constructor(fn interface{}) *ClassBuilder
- func (cb *ClassBuilder) Environment(env *Environment) *ClassBuilder
- func (cb *ClassBuilder) Method(name string, fn interface{}) *ClassBuilder
- func (cb *ClassBuilder) MethodWithHelp(name string, fn interface{}, helpText string) *ClassBuilder
- func (cb *ClassBuilder) Property(name string, fn interface{}) *ClassBuilder
- func (cb *ClassBuilder) PropertyWithSetter(name string, getter interface{}, setter interface{}) *ClassBuilder
- func (cb *ClassBuilder) StaticMethod(name string, fn interface{}) *ClassBuilder
- type ClassMethod
- func (c *ClassMethod) AsBool() (bool, Object)
- func (c *ClassMethod) AsDict() (map[string]Object, Object)
- func (c *ClassMethod) AsFloat() (float64, Object)
- func (c *ClassMethod) AsInt() (int64, Object)
- func (c *ClassMethod) AsList() ([]Object, Object)
- func (c *ClassMethod) AsString() (string, Object)
- func (c *ClassMethod) CoerceFloat() (float64, Object)
- func (c *ClassMethod) CoerceInt() (int64, Object)
- func (c *ClassMethod) CoerceString() (string, Object)
- func (c *ClassMethod) Inspect() string
- func (c *ClassMethod) Type() ObjectType
- type ClientWrapper
- func (w *ClientWrapper) AsBool() (bool, Object)
- func (w *ClientWrapper) AsDict() (map[string]Object, Object)
- func (w *ClientWrapper) AsFloat() (float64, Object)
- func (w *ClientWrapper) AsInt() (int64, Object)
- func (w *ClientWrapper) AsList() ([]Object, Object)
- func (w *ClientWrapper) AsString() (string, Object)
- func (w *ClientWrapper) CoerceFloat() (float64, Object)
- func (w *ClientWrapper) CoerceInt() (int64, Object)
- func (w *ClientWrapper) CoerceString() (string, Object)
- func (w *ClientWrapper) Inspect() string
- func (w *ClientWrapper) Type() ObjectType
- type Continue
- func (c *Continue) AsBool() (bool, Object)
- func (c *Continue) AsDict() (map[string]Object, Object)
- func (c *Continue) AsFloat() (float64, Object)
- func (c *Continue) AsInt() (int64, Object)
- func (c *Continue) AsList() ([]Object, Object)
- func (c *Continue) AsString() (string, Object)
- func (c *Continue) CoerceFloat() (float64, Object)
- func (c *Continue) CoerceInt() (int64, Object)
- func (c *Continue) CoerceString() (string, Object)
- func (c *Continue) Inspect() string
- func (c *Continue) Type() ObjectType
- type Dict
- func (d *Dict) AsBool() (bool, Object)
- func (d *Dict) AsDict() (map[string]Object, Object)
- func (d *Dict) AsFloat() (float64, Object)
- func (d *Dict) AsInt() (int64, Object)
- func (d *Dict) AsList() ([]Object, Object)
- func (d *Dict) AsString() (string, Object)
- func (d *Dict) Clear()
- func (d *Dict) CoerceFloat() (float64, Object)
- func (d *Dict) CoerceInt() (int64, Object)
- func (d *Dict) CoerceString() (string, Object)
- func (d *Dict) CreateIterator() *Iterator
- func (d *Dict) Delete(canonical string)
- func (d *Dict) DeleteByString(name string) bool
- func (d *Dict) Factory() Object
- func (d *Dict) FirstInserted() (string, DictPair, bool)
- func (d *Dict) GetByString(name string) (DictPair, bool)
- func (d *Dict) HasByString(name string) bool
- func (d *Dict) Inspect() string
- func (d *Dict) IsDefaultDict() bool
- func (d *Dict) LastInserted() (string, DictPair, bool)
- func (d *Dict) LinkOwner(inst *Instance)
- func (d *Dict) MoveToEnd(canonical string, last bool) bool
- func (d *Dict) OrderedKeys() []string
- func (d *Dict) OrderedPairs() []DictPair
- func (d *Dict) ResetOrder()
- func (d *Dict) SetByString(name string, value Object)
- func (d *Dict) SetFactory(f Object)
- func (d *Dict) Store(canonical string, key Object, value Object)
- func (d *Dict) StoreFrom(other *Dict)
- func (d *Dict) Type() ObjectType
- type DictItems
- func (di *DictItems) AsBool() (bool, Object)
- func (di *DictItems) AsDict() (map[string]Object, Object)
- func (di *DictItems) AsFloat() (float64, Object)
- func (di *DictItems) AsInt() (int64, Object)
- func (di *DictItems) AsList() ([]Object, Object)
- func (di *DictItems) AsString() (string, Object)
- func (di *DictItems) CoerceFloat() (float64, Object)
- func (di *DictItems) CoerceInt() (int64, Object)
- func (di *DictItems) CoerceString() (string, Object)
- func (di *DictItems) CreateIterator() *Iterator
- func (di *DictItems) Inspect() string
- func (di *DictItems) Type() ObjectType
- type DictKeys
- func (dk *DictKeys) AsBool() (bool, Object)
- func (dk *DictKeys) AsDict() (map[string]Object, Object)
- func (dk *DictKeys) AsFloat() (float64, Object)
- func (dk *DictKeys) AsInt() (int64, Object)
- func (dk *DictKeys) AsList() ([]Object, Object)
- func (dk *DictKeys) AsString() (string, Object)
- func (dk *DictKeys) CoerceFloat() (float64, Object)
- func (dk *DictKeys) CoerceInt() (int64, Object)
- func (dk *DictKeys) CoerceString() (string, Object)
- func (dk *DictKeys) CreateIterator() *Iterator
- func (dk *DictKeys) Inspect() string
- func (dk *DictKeys) Type() ObjectType
- type DictPair
- type DictValues
- func (dv *DictValues) AsBool() (bool, Object)
- func (dv *DictValues) AsDict() (map[string]Object, Object)
- func (dv *DictValues) AsFloat() (float64, Object)
- func (dv *DictValues) AsInt() (int64, Object)
- func (dv *DictValues) AsList() ([]Object, Object)
- func (dv *DictValues) AsString() (string, Object)
- func (dv *DictValues) CoerceFloat() (float64, Object)
- func (dv *DictValues) CoerceInt() (int64, Object)
- func (dv *DictValues) CoerceString() (string, Object)
- func (dv *DictValues) CreateIterator() *Iterator
- func (dv *DictValues) Inspect() string
- func (dv *DictValues) Type() ObjectType
- type Environment
- func AcquireCallEnvironment(outer *Environment, slotIndex map[string]int, slotNames []string) *Environment
- func NewEnclosedEnvironment(outer *Environment) *Environment
- func NewEnclosedEnvironmentWithSlots(outer *Environment, slotIndex map[string]int, slotNames []string) *Environment
- func NewEnvironment() *Environment
- func NewEnvironmentWithGILDomain(owner *Environment) *Environment
- func (e *Environment) CachedEnvContext(base context.Context) (context.Context, bool)
- func (e *Environment) CopyCallableBindingsTo(target *Environment)
- func (e *Environment) Delete(name string)
- func (e *Environment) EachLocal(fn func(name string, val Object))
- func (e *Environment) EnableOutputCapture()
- func (e *Environment) EnterGIL() bool
- func (e *Environment) EnterGILWithContext(ctx context.Context) (acquired, entered bool)
- func (e *Environment) ExitGIL()
- func (e *Environment) ExtendSlots(slotIndex map[string]int, slotNames []string)
- func (e *Environment) Get(name string) (Object, bool)
- func (e *Environment) GetAtLocation(hops, slotIdx int, name string) (Object, bool)
- func (e *Environment) GetAvailableLibrariesCallback() func() []LibraryInfo
- func (e *Environment) GetCachedSlot(idx int, name string) (Object, bool)
- func (e *Environment) GetCurrentModule() string
- func (e *Environment) GetErrorWriter() io.Writer
- func (e *Environment) GetGlobal() *Environment
- func (e *Environment) GetImportCallback() func(string) error
- func (e *Environment) GetImportCallbackWithContext() func(context.Context, string) error
- func (e *Environment) GetOutput() string
- func (e *Environment) GetReader() io.Reader
- func (e *Environment) GetSlotByIndex(idx int) (Object, bool)
- func (e *Environment) GetSlotIndex(name string) (int, bool)
- func (e *Environment) GetStore() map[string]Object
- func (e *Environment) GetWithLocation(name string) (val Object, hops int, slotIdx int, ok bool)
- func (e *Environment) GetWriter() io.Writer
- func (e *Environment) HasSlots() bool
- func (e *Environment) IsGlobal(name string) bool
- func (e *Environment) IsImportedBinding(name string) bool
- func (e *Environment) IsNonlocal(name string) bool
- func (e *Environment) MarkGlobal(name string)
- func (e *Environment) MarkImportedBinding(name string)
- func (e *Environment) MarkNonlocal(name string)
- func (e *Environment) ResetStore(keep map[string]bool)
- func (e *Environment) ResourceGuard() *ResourceGuard
- func (e *Environment) Root() *Environment
- func (e *Environment) RunUnlocked(fn func())
- func (e *Environment) Set(name string, val Object) Object
- func (e *Environment) SetAvailableLibrariesCallback(fn func() []LibraryInfo)
- func (e *Environment) SetCachedSlot(idx int, name string, val Object) bool
- func (e *Environment) SetCurrentModule(module string)
- func (e *Environment) SetErrorWriter(w io.Writer)
- func (e *Environment) SetGlobal(name string, val Object) Object
- func (e *Environment) SetImportCallback(fn func(string) error)
- func (e *Environment) SetImportCallbackWithContext(fn func(context.Context, string) error)
- func (e *Environment) SetInParent(name string, val Object) bool
- func (e *Environment) SetInputReader(r io.Reader)
- func (e *Environment) SetOutputWriter(w io.Writer)
- func (e *Environment) SetResourceGuard(guard *ResourceGuard)
- func (e *Environment) SetSlotByIndex(idx int, val Object) bool
- func (e *Environment) SetupSlots(slotIndex map[string]int, slotNames []string)
- func (e *Environment) SnapshotCallables() *CallableSnapshot
- func (e *Environment) StoreEnvContext(base, derived context.Context)
- type Error
- func (e *Error) AsBool() (bool, Object)
- func (e *Error) AsDict() (map[string]Object, Object)
- func (e *Error) AsFloat() (float64, Object)
- func (e *Error) AsInt() (int64, Object)
- func (e *Error) AsList() ([]Object, Object)
- func (e *Error) AsString() (string, Object)
- func (e *Error) CoerceFloat() (float64, Object)
- func (e *Error) CoerceInt() (int64, Object)
- func (e *Error) CoerceString() (string, Object)
- func (e *Error) Inspect() string
- func (e *Error) Type() ObjectType
- type EvalFn
- type Exception
- func (ex *Exception) AsBool() (bool, Object)
- func (ex *Exception) AsDict() (map[string]Object, Object)
- func (ex *Exception) AsFloat() (float64, Object)
- func (ex *Exception) AsInt() (int64, Object)
- func (ex *Exception) AsList() ([]Object, Object)
- func (ex *Exception) AsString() (string, Object)
- func (ex *Exception) CoerceFloat() (float64, Object)
- func (ex *Exception) CoerceInt() (int64, Object)
- func (ex *Exception) CoerceString() (string, Object)
- func (ex *Exception) GetExitCode() int
- func (ex *Exception) Inspect() string
- func (ex *Exception) IsPermissionError() bool
- func (ex *Exception) IsSystemExit() bool
- func (ex *Exception) Type() ObjectType
- type Float
- func (f *Float) AsBool() (bool, Object)
- func (f *Float) AsDict() (map[string]Object, Object)
- func (f *Float) AsFloat() (float64, Object)
- func (f *Float) AsInt() (int64, Object)
- func (f *Float) AsList() ([]Object, Object)
- func (f *Float) AsString() (string, Object)
- func (f *Float) CoerceFloat() (float64, Object)
- func (f *Float) CoerceInt() (int64, Object)
- func (f *Float) CoerceString() (string, Object)
- func (f *Float) FloatValue() float64
- func (f *Float) Inspect() string
- func (f *Float) Type() ObjectType
- type FloatArray
- func (fa *FloatArray) AsBool() (bool, Object)
- func (fa *FloatArray) AsDict() (map[string]Object, Object)
- func (fa *FloatArray) AsFloat() (float64, Object)
- func (fa *FloatArray) AsInt() (int64, Object)
- func (fa *FloatArray) AsList() ([]Object, Object)
- func (fa *FloatArray) AsString() (string, Object)
- func (fa *FloatArray) CoerceFloat() (float64, Object)
- func (fa *FloatArray) CoerceInt() (int64, Object)
- func (fa *FloatArray) CoerceString() (string, Object)
- func (fa *FloatArray) Cols() int
- func (fa *FloatArray) FloatArrayData() ([]float64, []int, bool)
- func (fa *FloatArray) Inspect() string
- func (fa *FloatArray) Is2D() bool
- func (fa *FloatArray) PrettyPrint() string
- func (fa *FloatArray) Row(i int) []float64
- func (fa *FloatArray) Rows() int
- func (fa *FloatArray) ToList() *List
- func (fa *FloatArray) Type() ObjectType
- type Function
- func (f *Function) AsBool() (bool, Object)
- func (f *Function) AsDict() (map[string]Object, Object)
- func (f *Function) AsFloat() (float64, Object)
- func (f *Function) AsInt() (int64, Object)
- func (f *Function) AsList() ([]Object, Object)
- func (f *Function) AsString() (string, Object)
- func (f *Function) CoerceFloat() (float64, Object)
- func (f *Function) CoerceInt() (int64, Object)
- func (f *Function) CoerceString() (string, Object)
- func (f *Function) Inspect() string
- func (f *Function) Type() ObjectType
- type FunctionBuilder
- type FunctionSignature
- type Instance
- func (i *Instance) AsBool() (bool, Object)
- func (i *Instance) AsDict() (map[string]Object, Object)
- func (i *Instance) AsFloat() (float64, Object)
- func (i *Instance) AsInt() (int64, Object)
- func (i *Instance) AsList() ([]Object, Object)
- func (i *Instance) AsString() (string, Object)
- func (i *Instance) CoerceFloat() (float64, Object)
- func (i *Instance) CoerceInt() (int64, Object)
- func (i *Instance) CoerceString() (string, Object)
- func (i *Instance) DeleteField(name string)
- func (i *Instance) Field(name string) Object
- func (i *Instance) FieldCount() int
- func (i *Instance) FieldsSnapshot() map[string]Object
- func (i *Instance) GetBoundMethod(name string, method Object) *BoundMethod
- func (i *Instance) GetField(name string) (Object, bool)
- func (i *Instance) HasField(name string) bool
- func (i *Instance) Inspect() string
- func (i *Instance) InvalidateBoundMethod(name string)
- func (i *Instance) RangeFields(fn func(name string, val Object) bool)
- func (i *Instance) SetField(name string, val Object)
- func (i *Instance) Type() ObjectType
- type InstanceReprFunc
- type Integer
- func (i *Integer) AsBool() (bool, Object)
- func (i *Integer) AsDict() (map[string]Object, Object)
- func (i *Integer) AsFloat() (float64, Object)
- func (i *Integer) AsInt() (int64, Object)
- func (i *Integer) AsList() ([]Object, Object)
- func (i *Integer) AsString() (string, Object)
- func (i *Integer) CoerceFloat() (float64, Object)
- func (i *Integer) CoerceInt() (int64, Object)
- func (i *Integer) CoerceString() (string, Object)
- func (i *Integer) Inspect() string
- func (i *Integer) IntValue() int64
- func (i *Integer) Type() ObjectType
- type Iterator
- func NewEnumerateIterator(iterable Object, start int64) *Iterator
- func NewInfiniteIterator(nextFn func() (Object, bool)) *Iterator
- func NewIterator(nextFn func() (Object, bool)) *Iterator
- func NewRangeIterator(start, stop, step int64) *Iterator
- func NewReversedIterator(iterable Object) *Iterator
- func NewStrictZipIterator(iterables []Object) *Iterator
- func NewZipIterator(iterables []Object) *Iterator
- func (it *Iterator) AsBool() (bool, Object)
- func (it *Iterator) AsDict() (map[string]Object, Object)
- func (it *Iterator) AsFloat() (float64, Object)
- func (it *Iterator) AsInt() (int64, Object)
- func (it *Iterator) AsList() ([]Object, Object)
- func (it *Iterator) AsString() (string, Object)
- func (it *Iterator) CoerceFloat() (float64, Object)
- func (it *Iterator) CoerceInt() (int64, Object)
- func (it *Iterator) CoerceString() (string, Object)
- func (it *Iterator) Infinite() bool
- func (it *Iterator) Inspect() string
- func (it *Iterator) Len() (int64, bool)
- func (it *Iterator) Next() (Object, bool)
- func (it *Iterator) RangeRemaining() (next, step, n int64, ok bool)
- func (it *Iterator) SetTypeName(name *String) *Iterator
- func (it *Iterator) Type() ObjectType
- func (it *Iterator) TypeName() *String
- type Kwargs
- func (k Kwargs) Get(key string) Object
- func (k Kwargs) GetBool(name string, defaultValue bool) (bool, Object)
- func (k Kwargs) GetFloat(name string, defaultValue float64) (float64, Object)
- func (k Kwargs) GetInt(name string, defaultValue int64) (int64, Object)
- func (k Kwargs) GetList(name string, defaultValue []Object) ([]Object, Object)
- func (k Kwargs) GetString(name string, defaultValue string) (string, Object)
- func (k Kwargs) Has(key string) bool
- func (k Kwargs) Keys() []string
- func (k Kwargs) Len() int
- func (k Kwargs) MustGetBool(name string, defaultValue bool) bool
- func (k Kwargs) MustGetFloat(name string, defaultValue float64) float64
- func (k Kwargs) MustGetInt(name string, defaultValue int64) int64
- func (k Kwargs) MustGetList(name string, defaultValue []Object) []Object
- func (k Kwargs) MustGetString(name string, defaultValue string) string
- type LambdaFunction
- func (lf *LambdaFunction) AsBool() (bool, Object)
- func (lf *LambdaFunction) AsDict() (map[string]Object, Object)
- func (lf *LambdaFunction) AsFloat() (float64, Object)
- func (lf *LambdaFunction) AsInt() (int64, Object)
- func (lf *LambdaFunction) AsList() ([]Object, Object)
- func (lf *LambdaFunction) AsString() (string, Object)
- func (lf *LambdaFunction) CoerceFloat() (float64, Object)
- func (lf *LambdaFunction) CoerceInt() (int64, Object)
- func (lf *LambdaFunction) CoerceString() (string, Object)
- func (lf *LambdaFunction) Inspect() string
- func (lf *LambdaFunction) Type() ObjectType
- type Library
- func (l *Library) AsBool() (bool, Object)
- func (l *Library) AsDict() (map[string]Object, Object)
- func (l *Library) AsFloat() (float64, Object)
- func (l *Library) AsInt() (int64, Object)
- func (l *Library) AsList() ([]Object, Object)
- func (l *Library) AsString() (string, Object)
- func (l *Library) CachedDict() *Dict
- func (l *Library) CoerceFloat() (float64, Object)
- func (l *Library) CoerceInt() (int64, Object)
- func (l *Library) CoerceString() (string, Object)
- func (l *Library) Constants() map[string]Object
- func (l *Library) Description() string
- func (l *Library) Functions() map[string]*Builtin
- func (l *Library) GetDict() *Dict
- func (l *Library) Inspect() string
- func (l *Library) InstanceData() any
- func (l *Library) Instantiate(instanceData any) *Library
- func (l *Library) Name() string
- func (l *Library) Type() ObjectType
- type LibraryBuilder
- func (b *LibraryBuilder) Alias(alias, originalName string) *LibraryBuilder
- func (b *LibraryBuilder) Build() *Library
- func (b *LibraryBuilder) Clear() *LibraryBuilder
- func (b *LibraryBuilder) Constant(name string, value interface{}) *LibraryBuilder
- func (b *LibraryBuilder) ConstantCount() int
- func (b *LibraryBuilder) Description(desc string) *LibraryBuilder
- func (b *LibraryBuilder) Function(name string, fn interface{}) *LibraryBuilder
- func (b *LibraryBuilder) FunctionCount() int
- func (b *LibraryBuilder) FunctionFromVariadic(name string, fn interface{}) *LibraryBuilder
- func (b *LibraryBuilder) FunctionFromVariadicWithHelp(name string, fn interface{}, helpText string) *LibraryBuilder
- func (b *LibraryBuilder) FunctionWithHelp(name string, fn interface{}, helpText string) *LibraryBuilder
- func (b *LibraryBuilder) GetConstantNames() []string
- func (b *LibraryBuilder) GetDescription() string
- func (b *LibraryBuilder) GetFunctionNames() []string
- func (b *LibraryBuilder) HasConstant(name string) bool
- func (b *LibraryBuilder) HasFunction(name string) bool
- func (b *LibraryBuilder) Merge(other *LibraryBuilder) *LibraryBuilder
- func (b *LibraryBuilder) RemoveConstant(name string) *LibraryBuilder
- func (b *LibraryBuilder) RemoveFunction(name string) *LibraryBuilder
- func (b *LibraryBuilder) String() string
- func (b *LibraryBuilder) SubLibrary(name string, lib *Library) *LibraryBuilder
- type LibraryInfo
- type LibraryRegistrar
- type List
- func (l *List) AsBool() (bool, Object)
- func (l *List) AsDict() (map[string]Object, Object)
- func (l *List) AsFloat() (float64, Object)
- func (l *List) AsInt() (int64, Object)
- func (l *List) AsList() ([]Object, Object)
- func (l *List) AsString() (string, Object)
- func (l *List) CoerceFloat() (float64, Object)
- func (l *List) CoerceInt() (int64, Object)
- func (l *List) CoerceString() (string, Object)
- func (l *List) Inspect() string
- func (l *List) Type() ObjectType
- type Null
- func (n *Null) AsBool() (bool, Object)
- func (n *Null) AsDict() (map[string]Object, Object)
- func (n *Null) AsFloat() (float64, Object)
- func (n *Null) AsInt() (int64, Object)
- func (n *Null) AsList() ([]Object, Object)
- func (n *Null) AsString() (string, Object)
- func (n *Null) CoerceFloat() (float64, Object)
- func (n *Null) CoerceInt() (int64, Object)
- func (n *Null) CoerceString() (string, Object)
- func (n *Null) Inspect() string
- func (n *Null) Type() ObjectType
- type Object
- func AcquireArgs(env *Environment, n int) []Object
- func CheckAlloc(n int64) Object
- func CheckAllocFor(what string, n int64) Object
- func CheckElements(n int64) Object
- func CheckRoom(what string, n int64) Object
- func CheckSlots(n int64) Object
- func CheckString(s *String) Object
- func CheckValue(obj Object) Object
- func CloneObject(obj Object) Object
- func CoerceWireString(obj Object) (string, Object)
- func Compare(ctx context.Context, a, b Object) (int, Object)
- func Equal(ctx context.Context, a, b Object) (bool, Object)
- func InspectRepr(obj Object, instanceRepr InstanceReprFunc) (string, Object)
- func IterableToSlice(obj Object) ([]Object, bool)
- func ReadAllLimited(r io.Reader, what string) (data []byte, limitErr Object, err error)
- func ReadFileLimited(path string) (data []byte, limitErr Object, err error)
- type ObjectType
- type Property
- func (p *Property) AsBool() (bool, Object)
- func (p *Property) AsDict() (map[string]Object, Object)
- func (p *Property) AsFloat() (float64, Object)
- func (p *Property) AsInt() (int64, Object)
- func (p *Property) AsList() ([]Object, Object)
- func (p *Property) AsString() (string, Object)
- func (p *Property) CoerceFloat() (float64, Object)
- func (p *Property) CoerceInt() (int64, Object)
- func (p *Property) CoerceString() (string, Object)
- func (p *Property) Inspect() string
- func (p *Property) Type() ObjectType
- type ResourceGuard
- func (g *ResourceGuard) CopyLimits(from *ResourceGuard)
- func (g *ResourceGuard) MaxBackgroundTasks() int64
- func (g *ResourceGuard) MaxValueBytes() int64
- func (g *ResourceGuard) MemoryLimit() int64
- func (g *ResourceGuard) SetMaxBackgroundTasks(n int64)
- func (g *ResourceGuard) SetMaxValueBytes(n int64)
- func (g *ResourceGuard) SetMemoryLimit(n int64)
- func (g *ResourceGuard) StartRun(ctx context.Context) (context.Context, *Run)
- func (g *ResourceGuard) StartTask() (end func(), err error)
- func (g *ResourceGuard) Usage() ResourceUsage
- type ResourceUsage
- type ReturnValue
- func (rv *ReturnValue) AsBool() (bool, Object)
- func (rv *ReturnValue) AsDict() (map[string]Object, Object)
- func (rv *ReturnValue) AsFloat() (float64, Object)
- func (rv *ReturnValue) AsInt() (int64, Object)
- func (rv *ReturnValue) AsList() ([]Object, Object)
- func (rv *ReturnValue) AsString() (string, Object)
- func (rv *ReturnValue) CoerceFloat() (float64, Object)
- func (rv *ReturnValue) CoerceInt() (int64, Object)
- func (rv *ReturnValue) CoerceString() (string, Object)
- func (rv *ReturnValue) Inspect() string
- func (rv *ReturnValue) Type() ObjectType
- type Run
- type ScriptCallable
- type Sentinel
- func (s *Sentinel) AsBool() (bool, Object)
- func (s *Sentinel) AsDict() (map[string]Object, Object)
- func (s *Sentinel) AsFloat() (float64, Object)
- func (s *Sentinel) AsInt() (int64, Object)
- func (s *Sentinel) AsList() ([]Object, Object)
- func (s *Sentinel) AsString() (string, Object)
- func (s *Sentinel) CoerceFloat() (float64, Object)
- func (s *Sentinel) CoerceInt() (int64, Object)
- func (s *Sentinel) CoerceString() (string, Object)
- func (s *Sentinel) Inspect() string
- func (s *Sentinel) Type() ObjectType
- type Set
- func (s *Set) AddKeyed(key string, obj Object)
- func (s *Set) AsBool() (bool, Object)
- func (s *Set) AsDict() (map[string]Object, Object)
- func (s *Set) AsFloat() (float64, Object)
- func (s *Set) AsInt() (int64, Object)
- func (s *Set) AsList() ([]Object, Object)
- func (s *Set) AsString() (string, Object)
- func (s *Set) CoerceFloat() (float64, Object)
- func (s *Set) CoerceInt() (int64, Object)
- func (s *Set) CoerceString() (string, Object)
- func (s *Set) ContainsKeyed(key string) bool
- func (s *Set) Copy() *Set
- func (s *Set) CreateIterator() *Iterator
- func (s *Set) Difference(other *Set) *Set
- func (s *Set) Freeze() *Set
- func (s *Set) InPlaceDifference(other *Set)
- func (s *Set) InPlaceIntersection(other *Set)
- func (s *Set) InPlaceSymmetricDifference(other *Set)
- func (s *Set) InPlaceUnion(other *Set)
- func (s *Set) Inspect() string
- func (s *Set) Intersection(other *Set) *Set
- func (s *Set) IsSubset(other *Set) bool
- func (s *Set) IsSuperset(other *Set) bool
- func (s *Set) SymmetricDifference(other *Set) *Set
- func (s *Set) Type() ObjectType
- func (s *Set) Union(other *Set) *Set
- type Slice
- func (s *Slice) AsBool() (bool, Object)
- func (s *Slice) AsDict() (map[string]Object, Object)
- func (s *Slice) AsFloat() (float64, Object)
- func (s *Slice) AsInt() (int64, Object)
- func (s *Slice) AsList() ([]Object, Object)
- func (s *Slice) AsString() (string, Object)
- func (s *Slice) CoerceFloat() (float64, Object)
- func (s *Slice) CoerceInt() (int64, Object)
- func (s *Slice) CoerceString() (string, Object)
- func (s *Slice) Inspect() string
- func (s *Slice) Type() ObjectType
- type StaticMethod
- func (s *StaticMethod) AsBool() (bool, Object)
- func (s *StaticMethod) AsDict() (map[string]Object, Object)
- func (s *StaticMethod) AsFloat() (float64, Object)
- func (s *StaticMethod) AsInt() (int64, Object)
- func (s *StaticMethod) AsList() ([]Object, Object)
- func (s *StaticMethod) AsString() (string, Object)
- func (s *StaticMethod) CoerceFloat() (float64, Object)
- func (s *StaticMethod) CoerceInt() (int64, Object)
- func (s *StaticMethod) CoerceString() (string, Object)
- func (s *StaticMethod) Inspect() string
- func (s *StaticMethod) Type() ObjectType
- type String
- func (s *String) AsBool() (bool, Object)
- func (s *String) AsDict() (map[string]Object, Object)
- func (s *String) AsFloat() (float64, Object)
- func (s *String) AsInt() (int64, Object)
- func (s *String) AsList() ([]Object, Object)
- func (s *String) AsString() (string, Object)
- func (s *String) CoerceFloat() (float64, Object)
- func (s *String) CoerceInt() (int64, Object)
- func (s *String) CoerceString() (string, Object)
- func (s *String) Inspect() string
- func (s *String) StringValue() string
- func (s *String) Type() ObjectType
- type Super
- func (s *Super) AsBool() (bool, Object)
- func (s *Super) AsDict() (map[string]Object, Object)
- func (s *Super) AsFloat() (float64, Object)
- func (s *Super) AsInt() (int64, Object)
- func (s *Super) AsList() ([]Object, Object)
- func (s *Super) AsString() (string, Object)
- func (s *Super) CoerceFloat() (float64, Object)
- func (s *Super) CoerceInt() (int64, Object)
- func (s *Super) CoerceString() (string, Object)
- func (s *Super) Inspect() string
- func (s *Super) Type() ObjectType
- type Tuple
- func (t *Tuple) AsBool() (bool, Object)
- func (t *Tuple) AsDict() (map[string]Object, Object)
- func (t *Tuple) AsFloat() (float64, Object)
- func (t *Tuple) AsInt() (int64, Object)
- func (t *Tuple) AsList() ([]Object, Object)
- func (t *Tuple) AsString() (string, Object)
- func (t *Tuple) CoerceFloat() (float64, Object)
- func (t *Tuple) CoerceInt() (int64, Object)
- func (t *Tuple) CoerceString() (string, Object)
- func (t *Tuple) Inspect() string
- func (t *Tuple) Type() ObjectType
Constants ¶
const ( // Type conversion error messages (exported for use by external packages) ErrMustBeString = "must be a string" ErrMustBeInteger = "must be an integer" ErrMustBeNumber = "must be a number" ErrMustBeBoolean = "must be a boolean" ErrMustBeList = "must be a list" ErrMustBeDict = "must be a dict" ErrMustBeIterable = "must be iterable" ErrMustBeBytes = "must be bytes or string" )
Small integer cache for common values (-5 to 10000) This follows Python's approach and eliminates allocations for loop counters Extended range to 10000 for better loop performance
const ( ExceptionTypeSystemExit = "SystemExit" ExceptionTypePermissionError = "PermissionError" ExceptionTypeException = "Exception" ExceptionTypeValueError = "ValueError" ExceptionTypeTypeError = "TypeError" ExceptionTypeNameError = "NameError" ExceptionTypeImportError = "ImportError" ExceptionTypeStopIteration = "StopIteration" ExceptionTypeRuntimeError = "RuntimeError" ExceptionTypeRecursionError = "RecursionError" ExceptionTypeZeroDivisionError = "ZeroDivisionError" ExceptionTypeOverflowError = "OverflowError" ExceptionTypeMemoryError = "MemoryError" ExceptionTypeIndexError = "IndexError" ExceptionTypeKeyError = "KeyError" ExceptionTypeAttributeError = "AttributeError" ExceptionTypeOSError = "OSError" ExceptionTypeAssertionError = "AssertionError" ExceptionTypeGeneric = "" // Default for legacy compatibility )
Exception type constants
const DictEntryWeight = dictEntryWeight
DictEntryWeight is the estimated memory per dict entry, for checking a dict's size before it is presized.
const InfiniteIteratorMessage = "" /* 141-byte string literal not displayed */
InfiniteIteratorMessage is the error for collecting an infinite iterator.
const InheritLimit int64 = -1
InheritLimit makes an interpreter's limit follow the process-wide default.
const MaxReprDepth = 10000
MaxReprDepth caps how deeply nested a container repr()/str() will render. Rendering recurses in Go, and a stack overflow is a fatal error that ends the whole process, so past this depth rendering raises RecursionError, as Python does. It matches the nesting depth the data decoders accept.
const SampleInterval int64 = 64 << 10
SampleInterval is the mean number of allocated bytes between memory samples. Allocations of at least this size are always charged exactly.
const SetEntryWeight = setEntryWeight
SetEntryWeight is setEntryWeight for callers outside the package.
const TaskBytes int64 = 48 << 10
TaskBytes is the memory a live background task is charged against its interpreter's memory limit. No allocation point reports a task's cloned environment, evaluator state or goroutine stack, which together measure about 45 KB, so without the charge a script could start tasks until the process ran out of memory while the guard saw almost nothing.
Variables ¶
var ( BREAK = &Break{} CONTINUE = &Continue{} )
Break and Continue singletons (like NULL, TRUE, FALSE)
var ErrMemoryLimitExceeded = stderrors.New("memory limit exceeded")
ErrMemoryLimitExceeded is the cancellation cause attached to a run's context when its interpreter goes over its memory limit.
var ErrOutputLimitExceeded = stderrors.New("captured output exceeds the value limit")
ErrOutputLimitExceeded is returned by a write to captured output that would take it over the interpreter's value limit.
var ErrOutputNoRoom = fmt.Errorf("%w: no room within the memory limit", ErrOutputLimitExceeded)
ErrOutputNoRoom is returned by a write to captured output that would not fit in the interpreter's memory limit. It matches ErrOutputLimitExceeded.
var ErrTaskLimitExceeded = stderrors.New("background task limit reached")
ErrTaskLimitExceeded is the error StartTask returns when the interpreter already runs as many background tasks as its limit allows.
var ErrValueTooLarge = stderrors.New("value too large")
ErrValueTooLarge matches (with errors.Is) the errors ReadAllLimitedErr and ReadFileLimitedErr return for data over the value limit.
var (
IteratorTypeName = NewString("iterator")
)
Iterator type names: what type() reports for an iterator ("range", "map"). An iterator that does not set its own reports "iterator".
Functions ¶
func AllocWithin ¶ added in v0.31.0
AllocWithin reports whether an allocation of n bytes is within every limit without looking the interpreter up: one atomic load, for callers that want to do cheaper work before the full check.
func AsError ¶
AsError returns the error message from an Object, or empty string if not an error. This is a shared helper for extracting error messages from Objects.
func BindGuard ¶ added in v0.31.0
func BindGuard(guard *ResourceGuard) (release func())
BindGuard makes the calling goroutine work for the interpreter that owns guard until release is called: its allocations are charged to that interpreter and its size checks use its limits. Use it in goroutines a builtin starts to do work for a script (parallel requests, for example). A nil guard binds nothing. release must be called on the same goroutine.
func ByteString ¶ added in v0.31.0
ByteString returns the one-byte string b without allocating.
func ClearGCReleaseHook ¶ added in v0.10.0
ClearGCReleaseHook removes a release hook previously installed with SetGCReleaseHook. It is safe to call when no hook is installed.
func CompareDepth ¶ added in v0.33.0
CompareDepth returns the comparison nesting depth carried by ctx, 0 when none is in progress.
func DefaultMaxBackgroundTasks ¶ added in v0.33.0
func DefaultMaxBackgroundTasks() int64
DefaultMaxBackgroundTasks returns the process-wide default background task limit, 0 when there is none.
func DefaultMaxValueBytes ¶ added in v0.31.0
func DefaultMaxValueBytes() int64
DefaultMaxValueBytes returns the process-wide default value limit, 0 when there is none.
func DefaultMemoryLimit ¶ added in v0.31.0
func DefaultMemoryLimit() int64
DefaultMemoryLimit returns the process-wide default memory limit, 0 when there is none.
func DetachRun ¶ added in v0.31.0
DetachRun returns ctx without the cancellation of any run it belongs to: a run's context is cancelled when the run ends, so work that should outlive it (a fire-and-forget background task) starts from the context the outermost run was started from. Its values and the host's cancellation are kept; values added inside the run are not.
func DictKey ¶
DictKey returns a canonical string key for use in Dict and Set maps. Matches Python 3 semantics where:
- int(1), float(1.0), and True all map to the same key
- str("1") maps to a different key
- None maps to its own unique key
func DictStringKey ¶ added in v0.7.1
DictStringKey returns the canonical dict key for a string key without requiring a temporary String object allocation. It must agree with the *String case of DictKey.
func FileEquals ¶ added in v0.31.0
FileEquals reports whether the file at path holds exactly data, reading it only when its size matches, so comparing against a huge file costs nothing.
func FloatStr ¶ added in v0.27.0
FloatStr formats f the way Python's str() and repr() format floats: shortest round-trip digits, positional notation while 1e-4 <= |f| < 1e16, scientific notation outside that range with a two-digit exponent, ".0" appended to integral values, and "inf"/"nan" spellings. Go's 'g' format disagrees on all of these ("2" vs "2.0", "1.23e+08" vs "123456789.123").
func GetFloatArrayData ¶ added in v0.6.3
func GetFloatMatrix ¶ added in v0.6.4
func GrowthRoom ¶ added in v0.31.0
GrowthRoom estimates the memory a buffer of capacity oldCap holds while it grows to hold size bytes: the old backing array stays until the copy is done, and Go allocates at least double the old capacity.
func InstanceDataFromContext ¶
InstanceDataFromContext retrieves instance data from the context Returns nil if no instance data is present
func IsError ¶
IsError returns true if the object is an Error type.
This uses a concrete type assertion rather than obj.Type() == ERROR_OBJ: the assertion compiles to a single itab pointer comparison, avoiding the non-inlinable interface method call on this very hot path.
func IsFloatArray ¶ added in v0.6.3
func IsHashable ¶ added in v0.3.2
IsHashable reports whether obj can be used as a set element or dict key. Matches Python semantics: int, float, bool, string, bytes, None, and tuples of hashable elements are hashable; lists, dicts, sets, and instances are not unless the instance defines __hash__.
func IsPropagating ¶ added in v0.28.0
IsPropagating reports whether a value yielded by an iterator is an internal error or a raised exception that the consumer must propagate.
func IsReprContainer ¶ added in v0.28.0
IsReprContainer reports whether obj is a container whose display renders its elements with repr.
func IterSource ¶ added in v0.28.0
IterSource returns a pull function over iterable. Iterators are consumed lazily (so infinite iterators such as itertools.cycle work, as in Python); other iterables are materialized once. ok is false for non-iterables.
func MaxValueBytes ¶ added in v0.31.0
func MaxValueBytes() int64
MaxValueBytes returns the value limit for the interpreter running on the calling goroutine (the process default when none is), 0 for no limit. Use it to bound reads whose size is not known up front.
func MemoryAccountingEnabled ¶ added in v0.31.0
func MemoryAccountingEnabled() bool
MemoryAccountingEnabled reports whether memory accounting is on.
func PythonTypeName ¶ added in v0.33.0
PythonTypeName is the name Python gives obj's type, for messages such as "unhashable type: 'deque'": int, str, NoneType, the class name of an instance, the exception type of an exception, an iterator's own name.
func ReadAllLimitedErr ¶ added in v0.31.0
ReadAllLimitedErr is ReadAllLimited for code that reports Go errors: data over the value limit is an error matching ErrValueTooLarge.
func ReadFileLimitedErr ¶ added in v0.31.0
ReadFileLimitedErr is ReadFileLimited for code that reports Go errors.
func ReleaseArgs ¶ added in v0.20.0
func ReleaseArgs(env *Environment, args []Object)
ReleaseArgs clears args and returns its backing array to the tree's per-root free-list for reuse. Safe to call with nil/empty args (no-op) and on slices not obtained from AcquireArgs (they simply join the pool). The full backing capacity is cleared so no Object is pinned by an idle buffer.
func ReleaseCallEnvironment ¶ added in v0.7.1
func ReleaseCallEnvironment(env *Environment)
ReleaseCallEnvironment clears a call frame and returns it to its tree's per-root free-list for reuse. Non-pooled environments are ignored. See AcquireCallEnvironment for the no-lock concurrency contract.
func ReleaseReturnValue ¶ added in v0.15.0
func ReleaseReturnValue(rv *ReturnValue)
ReleaseReturnValue clears rv and returns it to its tree's free-list for reuse. Wrappers with no associated root (constructed outside AcquireReturnValue) are left for the garbage collector.
func ReprException ¶ added in v0.28.0
ReprException renders an exception as Python's repr does: ValueError('bad'), or ValueError() when it has no message.
func ReprString ¶ added in v0.28.0
ReprString renders a string the way Python's repr does: single quotes by default, switching to double quotes when the string contains a single quote and no double quote, with backslash, newline, carriage return and tab escaped.
func RunBlocking ¶ added in v0.15.0
RunBlocking runs fn (a blocking operation such as sleep or a socket read) with the interpreter lock released, so other goroutines can run script code in the same tree while this one is blocked. If no environment is available on the context it simply runs fn. Builtins that block should wrap the blocking call in RunBlocking.
func SetCompareHooks ¶ added in v0.33.0
func SetCompareHooks(equal func(ctx context.Context, a, b Object) (bool, Object), compare func(ctx context.Context, a, b Object) (int, Object))
SetCompareHooks registers the evaluator's equality and ordering.
func SetDefaultMaxBackgroundTasks ¶ added in v0.33.0
func SetDefaultMaxBackgroundTasks(n int64)
SetDefaultMaxBackgroundTasks sets the process-wide default for how many background tasks one interpreter may have queued or running at once. 0 (or a negative value) means no limit.
func SetDefaultMaxValueBytes ¶ added in v0.31.0
func SetDefaultMaxValueBytes(n int64)
SetDefaultMaxValueBytes sets the process-wide default for the largest single value one operation may create. 0 (or a negative value) means no limit.
func SetDefaultMemoryLimit ¶ added in v0.31.0
func SetDefaultMemoryLimit(n int64)
SetDefaultMemoryLimit sets the process-wide default memory limit in bytes for interpreters that do not set their own. 0 (or a negative value) means no limit.
func SetGCReleaseHook ¶ added in v0.10.0
SetGCReleaseHook installs hook as a best-effort callback for when target is released by Go's garbage collector.
The target must be a non-nil pointer. The hook must not retain target, either directly or through captured values, or the object will not become unreachable. Finalizers are not prompt and may never run before process exit, so callers should use explicit cleanup for resources that need deterministic release.
func SlotsWithin ¶ added in v0.31.0
SlotsWithin reports whether a container of n elements is within every value limit and needs no tracking, in one atomic load. When it returns false the caller checks with CheckElements and tracks the backing array.
func TrackAlloc ¶ added in v0.31.0
TrackAlloc reports that p was just allocated, holding size bytes. When memory accounting is on it may be sampled and charged to the interpreter on the calling goroutine until p is collected. It costs one atomic load while accounting is off. p must point into a heap allocation.
func TrackMap ¶ added in v0.31.0
TrackMap reports a newly made Go map holding about size bytes, charging it to the interpreter on the calling goroutine until the map is collected. A map has no pointer of its own to attach the credit to, so the cleanup is attached to its header allocation.
func TrackSlice ¶ added in v0.31.0
func TrackSlice[E any](s []E)
TrackSlice reports a newly allocated backing array: s must be the slice returned by the allocation (make or a growing append), with every element slot counting as allocated. Call it only when the backing array is new, for example when an append changed the capacity, and only for Go heap memory: a slice over C or mapped memory cannot carry the credit.
func TrackSliceWeighted ¶ added in v0.31.0
TrackSliceWeighted is TrackSlice charging perSlot bytes for every slot, for backing arrays that stand in for larger hidden storage (a map's buckets).
func ValidateTransferable ¶ added in v0.5.2
ValidateTransferable checks whether obj contains only types that can be safely passed to a background task. Transferable types are scalars (Null, Boolean, Integer, Float, String) and recursively transferable containers (List, Dict, Set, Tuple). Instances, classes, functions, builtins, and other stateful objects are rejected. Circular references are also rejected.
Types ¶
type Boolean ¶
type Boolean struct {
// contains filtered or unexported fields
}
func NewBoolean ¶ added in v0.5.2
func (*Boolean) CoerceFloat ¶
func (*Boolean) CoerceString ¶
func (*Boolean) Type ¶
func (b *Boolean) Type() ObjectType
type BoundMethod ¶
type BoundMethod struct {
Instance Object // The instance (self)
Method Object // The method function
// contains filtered or unexported fields
}
BoundMethod represents a method bound to an instance When called, it automatically prepends self to the arguments
func (*BoundMethod) AsBool ¶
func (bm *BoundMethod) AsBool() (bool, Object)
func (*BoundMethod) AsFloat ¶
func (bm *BoundMethod) AsFloat() (float64, Object)
func (*BoundMethod) AsInt ¶
func (bm *BoundMethod) AsInt() (int64, Object)
func (*BoundMethod) AsList ¶
func (bm *BoundMethod) AsList() ([]Object, Object)
func (*BoundMethod) AsString ¶
func (bm *BoundMethod) AsString() (string, Object)
func (*BoundMethod) CoerceFloat ¶
func (bm *BoundMethod) CoerceFloat() (float64, Object)
func (*BoundMethod) CoerceInt ¶
func (bm *BoundMethod) CoerceInt() (int64, Object)
func (*BoundMethod) CoerceString ¶
func (bm *BoundMethod) CoerceString() (string, Object)
func (*BoundMethod) Inspect ¶
func (bm *BoundMethod) Inspect() string
func (*BoundMethod) SelfArgs ¶ added in v0.5.6
func (bm *BoundMethod) SelfArgs() []Object
func (*BoundMethod) Type ¶
func (bm *BoundMethod) Type() ObjectType
type Break ¶
type Break struct{}
func (*Break) CoerceFloat ¶
func (*Break) CoerceString ¶
func (*Break) Type ¶
func (b *Break) Type() ObjectType
type Builtin ¶
type Builtin struct {
Fn BuiltinFunction
HelpText string // Optional help documentation for this builtin
Attributes map[string]Object // Optional attributes for this builtin
Repr string // Optional repr, e.g. for bound methods
}
DefaultDictType is the collections.defaultdict constructor, registered by the stdlib so isinstance(d, defaultdict) can recognise it. FactoryRepr renders a default factory the way Python does (<class 'list'>); the evaluator installs it. Both are nil until then.
func (*Builtin) CoerceFloat ¶
func (*Builtin) CoerceString ¶
func (*Builtin) Type ¶
func (b *Builtin) Type() ObjectType
type BuiltinFunction ¶
BuiltinFunction is the signature for all builtin functions
- ctx: Context with environment and runtime information
- kwargs: Keyword arguments passed to the function (wrapped with helper methods)
- args: Positional arguments passed to the function
The args slice is BORROWED for the duration of the call: the evaluator reuses the backing array across calls (a per-root free-list, see AcquireArgs). A builtin must therefore not retain args — or any sub-slice such as args[1:] — past the point it returns. Reading elements (args[i], ranging over args, spreading args... into a synchronous call) is always safe; storing the slice in a struct field/map/global, capturing it in a goroutine or returned closure, or using it as a List's Elements requires copying first (make + copy). This matches the convention of CPython's tp_call and Go variadic APIs.
type Bytes ¶ added in v0.19.0
type Bytes struct {
// contains filtered or unexported fields
}
Bytes is an immutable sequence of byte values (0-255), analogous to Python's bytes type. It is the canonical representation for binary data in Scriptling. Strict string operations raise a type error; use Decode() to obtain a string.
func NewBytes ¶ added in v0.19.0
NewBytes returns a new Bytes object that owns a defensive copy of the given slice, so callers may freely mutate the original after the call.
func NewBytesFromString ¶ added in v0.19.0
NewBytesFromString returns a Bytes object whose contents are the UTF-8 encoding of s. This is the equivalent of Python's str.encode("utf-8").
func (*Bytes) AsString ¶ added in v0.19.0
AsString is strict: bytes are not strings. Callers that need a string must call Decode() explicitly (the .decode() method on Bytes). This mirrors Python's TypeError on mixing bytes and str.
func (*Bytes) BytesValue ¶ added in v0.19.0
BytesValue returns the underlying byte slice. Callers MUST NOT mutate the returned slice; treat it as read-only. If mutation is required, copy it.
func (*Bytes) CoerceFloat ¶ added in v0.19.0
func (*Bytes) CoerceInt ¶ added in v0.19.0
CoerceInt returns the length, mirroring the way Python treats bool/len coercion for truthiness only; numeric coercion of bytes is not meaningful.
func (*Bytes) CoerceString ¶ added in v0.19.0
CoerceString returns a base64-encoded representation so that Bytes values can be printed, concatenated into error messages, or interpolated into f-strings without raising. Explicit decoding via .decode() should be preferred for real text content.
func (*Bytes) Equal ¶ added in v0.19.0
Equal reports whether two Bytes values have identical contents.
func (*Bytes) Inspect ¶ added in v0.19.0
Inspect returns a Python-style repr such as b'hello' or b'\x00\xff', suitable for debugging and print(). The default print() path uses CoerceString for a human-readable form; this is what shows up in the REPL and error messages.
func (*Bytes) Type ¶ added in v0.19.0
func (b *Bytes) Type() ObjectType
type CallableSnapshot ¶ added in v0.6.3
type CallableSnapshot struct {
// contains filtered or unexported fields
}
CallableSnapshot holds a snapshot of callable and scalar bindings safe to pass across goroutine boundaries. Use ApplySnapshot to write them into a new Environment.
func (*CallableSnapshot) ApplySnapshot ¶ added in v0.6.3
func (s *CallableSnapshot) ApplySnapshot(target *Environment)
ApplySnapshot writes the snapshot's bindings into target, rebound to target so closures resolve correctly. Dicts are deep-copied so concurrent tasks don't race when mutating intermediate dicts. Scalars are shared as-is — they are immutable value objects.
type Class ¶
type Class struct {
Name string
BaseClass *Class // optional parent class for inheritance
Methods map[string]Object
Env *Environment
// ExceptionBase names the built-in exception type this class derives
// from ("ValueError" for class MyError(ValueError)); "" means the class
// is not an exception. Set when the base is an exception constructor;
// inherited through BaseClass chains of user exception classes.
ExceptionBase string
// IsEnum marks classes deriving from enum.Enum: construction looks up
// members by value and iteration yields the members, in EnumMembers
// order. IntEnum additionally compares equal to plain values.
IsEnum bool
IsIntEnum bool
EnumMembers []Object
// FieldNames lists the class body's annotated names in source order
// (@dataclass fields); AssignNames the plain top-level assignment
// targets (enum members, dataclass defaults). Compile-time metadata;
// values live in Methods.
FieldNames []string
AssignNames []string
// contains filtered or unexported fields
}
func (*Class) CoerceFloat ¶
func (*Class) CoerceString ¶
func (*Class) InvalidateLookupCache ¶ added in v0.5.6
func (c *Class) InvalidateLookupCache()
func (*Class) LookupMember ¶ added in v0.5.6
func (*Class) Type ¶
func (c *Class) Type() ObjectType
type ClassBuilder ¶
type ClassBuilder struct {
// contains filtered or unexported fields
}
ClassBuilder provides a fluent API for creating scriptling classes. It allows registering typed Go methods that are automatically wrapped to handle conversion between Go types and scriptling Objects.
Two styles are supported:
1. *Instance methods — manage fields via SetField/Field:
cb := NewClassBuilder("Person")
cb.Method("__init__", func(self *Instance, name string) {
self.SetField("name", NewString(name))
})
cb.Method("greet", func(self *Instance) string {
return self.Field("name").(*String).StringValue()
})
2. Typed receiver methods — Go struct is auto-managed:
type Config struct { values map[string]any }
cb := NewClassBuilder("Config")
cb.Constructor(func(name string) *Config {
return &Config{values: map[string]any{"name": name}}
})
cb.Method("get", func(self *Config, key string) any {
return self.values[key]
})
When Constructor is used, the returned Go struct is automatically wrapped in a ClientWrapper and stored on the Instance. Methods whose first parameter matches the constructor's return type receive the unwrapped struct directly.
func NewClassBuilder ¶
func NewClassBuilder(name string) *ClassBuilder
NewClassBuilder creates a new ClassBuilder with the given class name.
func (*ClassBuilder) BaseClass ¶
func (cb *ClassBuilder) BaseClass(base *Class) *ClassBuilder
BaseClass sets the base class for inheritance.
func (*ClassBuilder) Build ¶
func (cb *ClassBuilder) Build() *Class
Build creates and returns the Class from this builder. If a Constructor was registered, an __init__ method is auto-generated that calls the constructor and stores the result as a ClientWrapper.
func (*ClassBuilder) Constructor ¶ added in v0.10.0
func (cb *ClassBuilder) Constructor(fn interface{}) *ClassBuilder
Constructor registers a constructor function for typed receiver classes. The function must return a pointer type (e.g., *Config) which becomes the receiver type for subsequent Method calls. The returned struct is automatically wrapped in a ClientWrapper and stored on the Instance.
Example:
type Config struct { values map[string]any }
cb := NewClassBuilder("Config")
cb.Constructor(func(name string) *Config {
return &Config{values: map[string]any{"name": name}}
})
cb.Method("get", func(self *Config, key string) any {
return self.values[key]
})
func (*ClassBuilder) Environment ¶
func (cb *ClassBuilder) Environment(env *Environment) *ClassBuilder
Environment sets the environment for the class. This is optional and usually not needed.
func (*ClassBuilder) Method ¶
func (cb *ClassBuilder) Method(name string, fn interface{}) *ClassBuilder
Method registers a typed Go method with the class. The first parameter is the receiver: either *Instance (manual Fields) or the typed pointer set by Constructor (e.g., *Config).
Example with *Instance:
cb.Method("greet", func(self *Instance, name string) string {
return "Hello, " + name
})
Example with typed receiver:
cb.Method("get", func(self *Config, key string) any {
return self.values[key]
})
func (*ClassBuilder) MethodWithHelp ¶
func (cb *ClassBuilder) MethodWithHelp(name string, fn interface{}, helpText string) *ClassBuilder
MethodWithHelp registers a method with help text. Help text is displayed when users call help() on the method.
func (*ClassBuilder) Property ¶ added in v0.2.0
func (cb *ClassBuilder) Property(name string, fn interface{}) *ClassBuilder
Property registers a getter function as a @property on the class. The getter receives self as its only argument.
Example:
cb.Property("area", func(self *Instance) float64 {
r, _ := self.Field("radius").AsFloat()
return math.Pi * r * r
})
func (*ClassBuilder) PropertyWithSetter ¶ added in v0.2.0
func (cb *ClassBuilder) PropertyWithSetter(name string, getter interface{}, setter interface{}) *ClassBuilder
PropertyWithSetter registers a getter and setter as a @property on the class. The getter receives self only; the setter receives self and the new value.
Example:
cb.PropertyWithSetter("radius",
func(self *Instance) float64 { r, _ := self.Field("r").AsFloat(); return r },
func(self *Instance, v float64) { self.SetField("r", NewFloat(v)) },
)
func (*ClassBuilder) StaticMethod ¶ added in v0.2.0
func (cb *ClassBuilder) StaticMethod(name string, fn interface{}) *ClassBuilder
StaticMethod registers a function as a @staticmethod on the class. The function does NOT receive self — do not include *Instance as the first parameter.
Example:
cb.StaticMethod("from_degrees", func(deg float64) float64 {
return deg * math.Pi / 180
})
type ClassMethod ¶ added in v0.2.0
type ClassMethod struct {
Fn Object
}
ClassMethod wraps a function for use with @classmethod. When called, the class is passed as the first argument instead of self.
func (*ClassMethod) AsBool ¶ added in v0.2.0
func (c *ClassMethod) AsBool() (bool, Object)
func (*ClassMethod) AsDict ¶ added in v0.2.0
func (c *ClassMethod) AsDict() (map[string]Object, Object)
func (*ClassMethod) AsFloat ¶ added in v0.2.0
func (c *ClassMethod) AsFloat() (float64, Object)
func (*ClassMethod) AsInt ¶ added in v0.2.0
func (c *ClassMethod) AsInt() (int64, Object)
func (*ClassMethod) AsList ¶ added in v0.2.0
func (c *ClassMethod) AsList() ([]Object, Object)
func (*ClassMethod) AsString ¶ added in v0.2.0
func (c *ClassMethod) AsString() (string, Object)
func (*ClassMethod) CoerceFloat ¶ added in v0.2.0
func (c *ClassMethod) CoerceFloat() (float64, Object)
func (*ClassMethod) CoerceInt ¶ added in v0.2.0
func (c *ClassMethod) CoerceInt() (int64, Object)
func (*ClassMethod) CoerceString ¶ added in v0.2.0
func (c *ClassMethod) CoerceString() (string, Object)
func (*ClassMethod) Inspect ¶ added in v0.2.0
func (c *ClassMethod) Inspect() string
func (*ClassMethod) Type ¶ added in v0.2.0
func (c *ClassMethod) Type() ObjectType
type ClientWrapper ¶
type ClientWrapper struct {
// TypeName is the display name used in Inspect() (e.g., "OpenAIClient", "MCPClient")
TypeName string
// Client is the underlying Go client pointer (opaque to scriptling)
Client any
}
ClientWrapper is a generic wrapper for storing Go client pointers in object.Instance fields. The underlying client is stored as an opaque pointer and accessed via type assertion.
Example usage:
type MyClientWrapper struct {
instance *MyClientInstance
}
func (w *MyClientWrapper) Type() ObjectType { return INSTANCE_OBJ }
func (w *MyClientWrapper) Inspect() string { return "<MyClient>" }
// ... implement other Object methods ...
// Store in instance:
instance.SetField("_client", &MyClientWrapper{instance: &MyClientInstance{...}})
// Extract from instance:
wrapper, _ := instance.Field("_client").(*MyClientWrapper)
client := wrapper.instance
For convenience, use NewClientWrapper to create a wrapper with a custom type name.
func GetClientField ¶
func GetClientField(instance *Instance, fieldName string) (*ClientWrapper, bool)
GetClientField extracts a ClientWrapper from an object.Instance field. Returns the wrapper and true if found, nil and false otherwise.
This is a convenience function for the common pattern of extracting a client wrapper from the "_client" field of an instance.
func (*ClientWrapper) AsBool ¶
func (w *ClientWrapper) AsBool() (bool, Object)
AsBool returns true - clients are truthy
func (*ClientWrapper) AsDict ¶
func (w *ClientWrapper) AsDict() (map[string]Object, Object)
AsDict returns an error - clients cannot be converted to dict
func (*ClientWrapper) AsFloat ¶
func (w *ClientWrapper) AsFloat() (float64, Object)
AsFloat returns an error - clients cannot be converted to float
func (*ClientWrapper) AsInt ¶
func (w *ClientWrapper) AsInt() (int64, Object)
AsInt returns an error - clients cannot be converted to int
func (*ClientWrapper) AsList ¶
func (w *ClientWrapper) AsList() ([]Object, Object)
AsList returns an error - clients cannot be converted to list
func (*ClientWrapper) AsString ¶
func (w *ClientWrapper) AsString() (string, Object)
AsString returns the inspect representation
func (*ClientWrapper) CoerceFloat ¶
func (w *ClientWrapper) CoerceFloat() (float64, Object)
func (*ClientWrapper) CoerceInt ¶
func (w *ClientWrapper) CoerceInt() (int64, Object)
func (*ClientWrapper) CoerceString ¶
func (w *ClientWrapper) CoerceString() (string, Object)
func (*ClientWrapper) Inspect ¶
func (w *ClientWrapper) Inspect() string
Inspect returns a string representation of the client
func (*ClientWrapper) Type ¶
func (w *ClientWrapper) Type() ObjectType
Type returns INSTANCE_OBJ as this wrapper represents an instance
type Continue ¶
type Continue struct{}
func (*Continue) CoerceFloat ¶
func (*Continue) CoerceString ¶
func (*Continue) Type ¶
func (c *Continue) Type() ObjectType
type Dict ¶
type Dict struct {
Pairs map[string]DictPair
// Module is the import name when this dict is a library module
// ("math", "scriptling.runtime.kv"), empty for an ordinary dict.
// Modules display as <module 'math'> and expose only their members.
Module string
// contains filtered or unexported fields
}
func NewDict ¶ added in v0.29.0
func NewDict() *Dict
NewDict returns an empty, insertion-ordered dict.
func NewDictSized ¶ added in v0.29.0
NewDictSized returns an empty, insertion-ordered dict with room for n pairs.
func NewStringDict ¶
NewStringDict creates a Dict from string key-value pairs. Usage: NewStringDict(map[string]Object{"key": value, ...}) A Go map has no order, so entries are inserted in sorted key order, which makes the resulting dict deterministic.
func (*Dict) Clear ¶ added in v0.29.0
func (d *Dict) Clear()
Clear removes every entry and the recorded insertion order. Use it instead of replacing Pairs, which would leave stale order entries behind.
func (*Dict) CoerceFloat ¶
func (*Dict) CoerceString ¶
func (*Dict) CreateIterator ¶ added in v0.20.0
CreateIterator returns an iterator over the dict's keys. In Python, iterating a dict yields its keys (same as dict.keys()), in insertion order.
func (*Dict) Delete ¶ added in v0.29.0
Delete removes a key. O(1) amortized: the order entry is left in place and skipped as stale (a delete at the tail, as popitem does, trims it at once), and compact() sweeps stale entries once they outnumber live ones. Deleting an absent key is a no-op.
func (*Dict) DeleteByString ¶
DeleteByString deletes a string key from the dict. Returns true if key existed.
func (*Dict) Factory ¶ added in v0.29.0
Factory returns the defaultdict factory, or nil for an ordinary dict.
func (*Dict) FirstInserted ¶ added in v0.29.0
FirstInserted returns the oldest pair that is still live, with its canonical key — what popitem(last=False) removes. Pairs of unknown order are older than every ordered pair, so the result matches OrderedKeys.
func (*Dict) GetByString ¶
GetByString retrieves a pair using a string key (convenience for attribute-style access).
func (*Dict) HasByString ¶
HasByString checks if a string key exists in the dict.
func (*Dict) IsDefaultDict ¶ added in v0.29.0
IsDefaultDict reports whether the dict was created by defaultdict().
func (*Dict) LastInserted ¶ added in v0.29.0
LastInserted returns the most recently inserted pair that is still live, with its canonical key — the pair Python's popitem() removes. Pairs of unknown order are treated as older than every ordered pair, so the result is consistent with OrderedKeys.
func (*Dict) LinkOwner ¶ added in v0.29.0
LinkOwner makes writes to this dict write through to inst's fields, as obj.__dict__ does in Python. Copies of the dict are not linked.
func (*Dict) MoveToEnd ¶ added in v0.29.0
MoveToEnd repositions an existing key at the end (last) or the front of the insertion order, as OrderedDict.move_to_end does, and reports whether the key exists. O(1) amortized: the old order entry goes stale and the key gets a fresh sequence number at its new position.
func (*Dict) OrderedKeys ¶ added in v0.29.0
OrderedKeys returns canonical keys in insertion order (pairs of unknown order first, sorted). Mutating the dict while iterating the result is safe: it is a snapshot.
func (*Dict) OrderedPairs ¶ added in v0.29.0
OrderedPairs returns the pairs in insertion order. Only order-visible reads (iteration, repr, views, serialization) need this; lookups and equality stay on Pairs directly.
func (*Dict) ResetOrder ¶ added in v0.29.0
func (d *Dict) ResetOrder()
ResetOrder forgets the recorded insertion order: every pair becomes order-unknown (sequence 0), so ordered reads fall back to sorted keys.
func (*Dict) SetByString ¶
SetByString sets a pair using a string key (convenience for attribute-style access).
func (*Dict) SetFactory ¶ added in v0.29.0
SetFactory makes the dict a defaultdict with the given factory (nil clears it).
func (*Dict) Store ¶ added in v0.29.0
Store inserts or updates key → value, extending the insertion order for new keys (Python dict semantics: an existing key keeps its position and its original key object). canonical must be the dict's hash key for key, as used in Pairs (DictKey, or evalHashKeyChecked's result).
func (*Dict) StoreFrom ¶ added in v0.29.0
StoreFrom copies every pair from other into d, preserving other's insertion order; later stores override earlier keys as in Python.
func (*Dict) Type ¶
func (d *Dict) Type() ObjectType
type DictItems ¶
type DictItems struct {
Dict *Dict
}
DictItems represents a view of a dictionary's items
func (*DictItems) CoerceFloat ¶
func (*DictItems) CoerceString ¶
func (*DictItems) CreateIterator ¶
func (*DictItems) Type ¶
func (di *DictItems) Type() ObjectType
type DictKeys ¶
type DictKeys struct {
Dict *Dict
}
DictKeys represents a view of a dictionary's keys
func (*DictKeys) CoerceFloat ¶
func (*DictKeys) CoerceString ¶
func (*DictKeys) CreateIterator ¶
CreateIterator returns an iterator for the keys
func (*DictKeys) Type ¶
func (dk *DictKeys) Type() ObjectType
type DictValues ¶
type DictValues struct {
Dict *Dict
}
DictValues represents a view of a dictionary's values
func (*DictValues) AsBool ¶
func (dv *DictValues) AsBool() (bool, Object)
func (*DictValues) AsFloat ¶
func (dv *DictValues) AsFloat() (float64, Object)
func (*DictValues) AsInt ¶
func (dv *DictValues) AsInt() (int64, Object)
func (*DictValues) AsList ¶
func (dv *DictValues) AsList() ([]Object, Object)
func (*DictValues) AsString ¶
func (dv *DictValues) AsString() (string, Object)
func (*DictValues) CoerceFloat ¶
func (dv *DictValues) CoerceFloat() (float64, Object)
func (*DictValues) CoerceInt ¶
func (dv *DictValues) CoerceInt() (int64, Object)
func (*DictValues) CoerceString ¶
func (dv *DictValues) CoerceString() (string, Object)
func (*DictValues) CreateIterator ¶
func (dv *DictValues) CreateIterator() *Iterator
func (*DictValues) Inspect ¶
func (dv *DictValues) Inspect() string
func (*DictValues) Type ¶
func (dv *DictValues) Type() ObjectType
type Environment ¶
type Environment struct {
// contains filtered or unexported fields
}
func AcquireCallEnvironment ¶ added in v0.7.1
func AcquireCallEnvironment(outer *Environment, slotIndex map[string]int, slotNames []string) *Environment
AcquireCallEnvironment returns a function-call environment, reusing an idle frame from the tree's per-root free-list when one is available.
The free-list lives on the root environment and is accessed without locking; this is safe because an environment tree is only ever used by a single goroutine (see callFrameFreeList). Frames acquired here must be returned via ReleaseCallEnvironment.
func NewEnclosedEnvironment ¶
func NewEnclosedEnvironment(outer *Environment) *Environment
func NewEnclosedEnvironmentWithSlots ¶ added in v0.5.6
func NewEnclosedEnvironmentWithSlots(outer *Environment, slotIndex map[string]int, slotNames []string) *Environment
func NewEnvironment ¶
func NewEnvironment() *Environment
func NewEnvironmentWithGILDomain ¶ added in v0.23.0
func NewEnvironmentWithGILDomain(owner *Environment) *Environment
NewEnvironmentWithGILDomain creates an otherwise independent environment that serializes through the same interpreter lock as owner. It is useful for runtime callbacks that must retain a stable lock domain without retaining owner's store (which can create finalizer reachability cycles).
func (*Environment) CachedEnvContext ¶ added in v0.20.0
CachedEnvContext returns the context previously derived from base for this environment, if any.
Builtins are invoked with their environment attached to the context, and deriving that context is a heap allocation. Since the base context is stable for the whole of one evaluation, memoising the derived context turns a per-builtin-call allocation into an atomic load and a comparison.
func (*Environment) CopyCallableBindingsTo ¶ added in v0.5.5
func (e *Environment) CopyCallableBindingsTo(target *Environment)
CopyCallableBindingsTo copies safe bindings into target for background task use. Functions and lambdas are copied and rebound to target. Dicts are copied so imported modules remain available. Other globals are intentionally skipped so background tasks cannot share caller-owned mutable or native-backed state.
func (*Environment) Delete ¶
func (e *Environment) Delete(name string)
Delete removes a variable from this environment (not parent scopes)
func (*Environment) EachLocal ¶ added in v0.25.0
func (e *Environment) EachLocal(fn func(name string, val Object))
EachLocal calls fn for every name bound directly in this environment (its own store and slots), not in any parent scope. Used to collect class-body assignments into class members after executing the body. Iteration order is unspecified.
func (*Environment) EnableOutputCapture ¶
func (e *Environment) EnableOutputCapture()
EnableOutputCapture enables output capture for this environment. Captured output is one value handed back to the host, so it is held to the interpreter's value limit: a write that would take it over fails with ErrOutputLimitExceeded.
func (*Environment) EnterGIL ¶ added in v0.15.0
func (e *Environment) EnterGIL() bool
EnterGIL acquires this tree's interpreter lock for the calling goroutine, unless this goroutine already holds it (a re-entrant call). It returns true if it actually acquired the lock (the caller must pair it with ExitGIL) and false if the call was re-entrant (caller does nothing on exit).
func (*Environment) EnterGILWithContext ¶ added in v0.23.0
func (e *Environment) EnterGILWithContext(ctx context.Context) (acquired, entered bool)
EnterGILWithContext acquires the interpreter lock while allowing a cancellable caller to abandon a contended wait. acquired reports whether the caller must invoke ExitGIL; entered is false only when ctx ended before entry. Contexts without cancellation use the regular blocking fast path.
func (*Environment) ExitGIL ¶ added in v0.15.0
func (e *Environment) ExitGIL()
ExitGIL releases the interpreter lock previously acquired by EnterGIL.
func (*Environment) ExtendSlots ¶ added in v0.7.1
func (e *Environment) ExtendSlots(slotIndex map[string]int, slotNames []string)
ExtendSlots adds new variables to the existing slot layout. Variables already present keep their existing indices. New variables are appended.
func (*Environment) GetAtLocation ¶ added in v0.15.0
func (e *Environment) GetAtLocation(hops, slotIdx int, name string) (Object, bool)
GetAtLocation reads the value at a cached (hops, slotIdx) location, validating that the slot still holds the expected name. Returns false if the cache is stale (chain too short or slot layout changed), so the caller can fall back to a full lookup.
func (*Environment) GetAvailableLibrariesCallback ¶
func (e *Environment) GetAvailableLibrariesCallback() func() []LibraryInfo
GetAvailableLibrariesCallback gets the available libraries callback from this environment or outer
func (*Environment) GetCachedSlot ¶ added in v0.7.1
func (e *Environment) GetCachedSlot(idx int, name string) (Object, bool)
GetCachedSlot returns the value at the given slot index after validating that the slot name matches. This prevents stale cached indices (from shared AST via the parse cache) from reading the wrong variable.
func (*Environment) GetCurrentModule ¶ added in v0.4.0
func (e *Environment) GetCurrentModule() string
GetCurrentModule gets the current module path from this environment or outer
func (*Environment) GetErrorWriter ¶ added in v0.21.0
func (e *Environment) GetErrorWriter() io.Writer
GetErrorWriter returns the appropriate writer for error output (sys.stderr)
func (*Environment) GetGlobal ¶
func (e *Environment) GetGlobal() *Environment
GetGlobal gets the global (outermost) environment
func (*Environment) GetImportCallback ¶
func (e *Environment) GetImportCallback() func(string) error
GetImportCallback returns a context-free view of the import callback for backwards compatibility. Calls made through this wrapper use a background context; evaluator internals use GetImportCallbackWithContext.
func (*Environment) GetImportCallbackWithContext ¶ added in v0.23.0
func (e *Environment) GetImportCallbackWithContext() func(context.Context, string) error
GetImportCallbackWithContext gets the context-aware import callback from this environment or an outer environment.
func (*Environment) GetOutput ¶
func (e *Environment) GetOutput() string
GetOutput returns captured output and clears the buffer
func (*Environment) GetReader ¶
func (e *Environment) GetReader() io.Reader
GetReader returns the appropriate reader for input
func (*Environment) GetSlotByIndex ¶ added in v0.7.1
func (e *Environment) GetSlotByIndex(idx int) (Object, bool)
GetSlotByIndex returns the value at the given slot index. Returns (value, true) if the slot has a value, (nil, false) otherwise.
func (*Environment) GetSlotIndex ¶ added in v0.7.1
func (e *Environment) GetSlotIndex(name string) (int, bool)
GetSlotIndex returns the slot index for the given variable name in this environment's local scope only. Returns (index, true) if found, (0, false) if not a local slot.
func (*Environment) GetStore ¶
func (e *Environment) GetStore() map[string]Object
GetStore returns a copy of the environment's store (only local scope, not outer)
func (*Environment) GetWithLocation ¶ added in v0.15.0
GetWithLocation resolves name like Get, additionally reporting where it was found in the environment chain: hops is the number of outer links traversed and slotIdx is the slot index if the value lives in a slot, or -1 if it came from a store map (not a stable, cacheable location). Used to seed call-site callee caches.
func (*Environment) GetWriter ¶
func (e *Environment) GetWriter() io.Writer
GetWriter returns the appropriate writer for output
func (*Environment) HasSlots ¶ added in v0.7.1
func (e *Environment) HasSlots() bool
HasSlots returns whether this environment has slot-based variable access configured.
func (*Environment) IsGlobal ¶
func (e *Environment) IsGlobal(name string) bool
IsGlobal checks if a variable is marked as global
func (*Environment) IsImportedBinding ¶ added in v0.6.0
func (e *Environment) IsImportedBinding(name string) bool
IsImportedBinding reports whether a local binding came from an import.
func (*Environment) IsNonlocal ¶
func (e *Environment) IsNonlocal(name string) bool
IsNonlocal checks if a variable is marked as nonlocal
func (*Environment) MarkGlobal ¶
func (e *Environment) MarkGlobal(name string)
MarkGlobal marks a variable name as global in this scope
func (*Environment) MarkImportedBinding ¶ added in v0.6.0
func (e *Environment) MarkImportedBinding(name string)
MarkImportedBinding marks a local binding as coming from an import.
func (*Environment) MarkNonlocal ¶
func (e *Environment) MarkNonlocal(name string)
MarkNonlocal marks a variable name as nonlocal in this scope
func (*Environment) ResetStore ¶ added in v0.2.7
func (e *Environment) ResetStore(keep map[string]bool)
ResetStore removes all keys from the environment store except those in keep.
func (*Environment) ResourceGuard ¶ added in v0.31.0
func (e *Environment) ResourceGuard() *ResourceGuard
ResourceGuard returns the guard of the interpreter that owns e's lock, nil when it has none.
func (*Environment) Root ¶ added in v0.15.0
func (e *Environment) Root() *Environment
Root returns the root environment of this tree.
func (*Environment) RunUnlocked ¶ added in v0.15.0
func (e *Environment) RunUnlocked(fn func())
RunUnlocked releases the interpreter lock, runs fn (typically a blocking call such as sleep or a socket read), then re-acquires it — but only if the calling goroutine actually holds the lock. Goroutines that do not hold it (e.g. raw worker goroutines doing pure-Go I/O) simply run fn. This lets other goroutines run script code in the same tree while the holder is blocked.
func (*Environment) SetAvailableLibrariesCallback ¶
func (e *Environment) SetAvailableLibrariesCallback(fn func() []LibraryInfo)
SetAvailableLibrariesCallback sets the available libraries callback for this environment. GetAvailableLibrariesCallback walks up the scope chain, so setting on any env makes it available to that env and all enclosed children.
func (*Environment) SetCachedSlot ¶ added in v0.7.1
func (e *Environment) SetCachedSlot(idx int, name string, val Object) bool
SetCachedSlot stores val at the given slot index after validating that the slot name matches. Returns false if the cache is stale, falling through to the full Set path.
func (*Environment) SetCurrentModule ¶ added in v0.4.0
func (e *Environment) SetCurrentModule(module string)
SetCurrentModule sets the current module path for relative import resolution
func (*Environment) SetErrorWriter ¶ added in v0.21.0
func (e *Environment) SetErrorWriter(w io.Writer)
SetErrorWriter sets a custom writer for error/diagnostic output (sys.stderr)
func (*Environment) SetGlobal ¶
func (e *Environment) SetGlobal(name string, val Object) Object
SetGlobal sets a variable in the global (outermost) environment
func (*Environment) SetImportCallback ¶
func (e *Environment) SetImportCallback(fn func(string) error)
SetImportCallback sets a context-free import callback for backwards compatibility. New code should use SetImportCallbackWithContext so caller cancellation and values are preserved through imports.
func (*Environment) SetImportCallbackWithContext ¶ added in v0.23.0
func (e *Environment) SetImportCallbackWithContext(fn func(context.Context, string) error)
SetImportCallbackWithContext sets the context-aware import callback for this environment. GetImportCallbackWithContext walks up the scope chain, so the callback is available to enclosed environments.
func (*Environment) SetInParent ¶
func (e *Environment) SetInParent(name string, val Object) bool
SetInParent sets a variable in the parent environment (for nonlocal)
func (*Environment) SetInputReader ¶
func (e *Environment) SetInputReader(r io.Reader)
SetInputReader sets a custom reader for input
func (*Environment) SetOutputWriter ¶
func (e *Environment) SetOutputWriter(w io.Writer)
SetOutputWriter sets a custom writer for output
func (*Environment) SetResourceGuard ¶ added in v0.31.0
func (e *Environment) SetResourceGuard(guard *ResourceGuard)
SetResourceGuard gives the interpreter that owns e's lock a resource guard. Set it before the interpreter runs; environments sharing the lock share the guard.
func (*Environment) SetSlotByIndex ¶ added in v0.7.1
func (e *Environment) SetSlotByIndex(idx int, val Object) bool
SetSlotByIndex stores val in the given local slot index when valid.
func (*Environment) SetupSlots ¶ added in v0.7.1
func (e *Environment) SetupSlots(slotIndex map[string]int, slotNames []string)
SetupSlots configures slot-based variable access on this environment.
func (*Environment) SnapshotCallables ¶ added in v0.6.3
func (e *Environment) SnapshotCallables() *CallableSnapshot
SnapshotCallables reads callable and scalar bindings from this environment into a self-contained snapshot. No references to the source Environment's maps are retained, so it is safe to pass the snapshot to another goroutine. Module-level scalars (int, float, bool, str, None) are included because handler functions legitimately reference module constants; they are immutable value objects, so sharing them cannot create cross-task races. Mutable globals (lists, dicts, instances, classes) are deliberately excluded — data must be passed via task args.
func (*Environment) StoreEnvContext ¶ added in v0.20.0
func (e *Environment) StoreEnvContext(base, derived context.Context)
StoreEnvContext memoises derived as the result of attaching this environment to base, so a later CachedEnvContext(base) can skip the allocation.
Nothing is stored when base's dynamic type is not comparable, because the lookup compares contexts with ==. That guard is what makes the comparison safe: a stored base is always of a comparable type, so if an incoming context has a different (possibly non-comparable) type the comparison fails on the type word alone and never reaches the values.
type Error ¶
type Error struct {
Message string
Line int
File string
Function string
// ExceptionType names the Python exception this error corresponds to, e.g.
// "ZeroDivisionError". It lets `except <Type>:` match a runtime error
// precisely instead of the try handler having to guess the type from the
// message text. Empty means "unclassified": the handler falls back to
// inferring a type, and the error is still caught by `except Exception`.
//
// Errors remain Errors rather than Exceptions on purpose — Error is the
// evaluator's propagation signal, recognised by the object.IsError checks
// threaded through expression evaluation — so setting this changes only how
// an except clause matches, not how the value travels.
ExceptionType string
}
func AsErrorObj ¶
AsErrorObj returns the object as an Error, or nil/false if not
func NewMemoryError ¶ added in v0.31.0
NewMemoryError returns an error that `except MemoryError` catches.
func (*Error) CoerceFloat ¶
func (*Error) CoerceString ¶
func (*Error) Type ¶
func (e *Error) Type() ObjectType
type EvalFn ¶ added in v0.27.2
type EvalFn func(ctx context.Context, env *Environment) Object
EvalFn is a compiled AST node: a closure that evaluates the node in env. Compiled closures are immutable after construction and safe to share between goroutines, exactly like the AST they are built from.
type Exception ¶
type Exception struct {
Message string
ExceptionType string // Exception type for identification (e.g., "SystemExit", "ValueError", etc.)
Code int // Exit code for SystemExit; ignored for other exception types
// Args holds the constructor arguments for exceptions built from user
// exception classes, so `e.args` matches Python.
Args []Object
// TypeChain names the user exception class hierarchy a custom exception
// was raised through (["MyError", "ValueError"] for
// class MyError(ValueError)), so except clauses and isinstance match
// base classes of user exception classes.
TypeChain []string
// OriginInstance keeps the user exception class instance a raise
// converted from, so custom attributes and methods (e.code) remain
// reachable on the caught exception.
OriginInstance *Instance
// Raised distinguishes an exception that is actively propagating (produced
// by a `raise` or by an operation that failed) from one that is merely a
// value (constructed via `ValueError("x")`, bound by `except ... as e`, or
// stored in a variable). Only a raised exception unwinds the call stack;
// a value exception is passed around like any other object. This mirrors
// Python, where constructing an exception does not raise it.
Raised bool
}
func AsException ¶
AsException returns the object as an Exception, or nil/false if not
func NewSystemExit ¶
NewSystemExit creates a new SystemExit exception with the given code and message
func (*Exception) CoerceFloat ¶
func (*Exception) CoerceString ¶
func (*Exception) GetExitCode ¶
GetExitCode returns the exit code for SystemExit exceptions For non-SystemExit exceptions, returns 0 (the Code field is ignored)
func (*Exception) IsPermissionError ¶ added in v0.3.2
func (*Exception) IsSystemExit ¶
IsSystemExit returns true if this is a SystemExit exception
func (*Exception) Type ¶
func (ex *Exception) Type() ObjectType
type Float ¶
type Float struct {
// contains filtered or unexported fields
}
func (*Float) CoerceFloat ¶
func (*Float) CoerceString ¶
func (*Float) FloatValue ¶ added in v0.8.0
func (*Float) Type ¶
func (f *Float) Type() ObjectType
type FloatArray ¶ added in v0.6.3
func NewFloatArray1D ¶ added in v0.6.3
func NewFloatArray1D(data []float64) *FloatArray
func NewFloatArray2D ¶ added in v0.6.3
func NewFloatArray2D(data []float64, rows, cols int) *FloatArray
func (*FloatArray) AsBool ¶ added in v0.6.3
func (fa *FloatArray) AsBool() (bool, Object)
func (*FloatArray) AsDict ¶ added in v0.6.3
func (fa *FloatArray) AsDict() (map[string]Object, Object)
func (*FloatArray) AsFloat ¶ added in v0.6.3
func (fa *FloatArray) AsFloat() (float64, Object)
func (*FloatArray) AsInt ¶ added in v0.6.3
func (fa *FloatArray) AsInt() (int64, Object)
func (*FloatArray) AsList ¶ added in v0.6.3
func (fa *FloatArray) AsList() ([]Object, Object)
func (*FloatArray) AsString ¶ added in v0.6.3
func (fa *FloatArray) AsString() (string, Object)
func (*FloatArray) CoerceFloat ¶ added in v0.6.3
func (fa *FloatArray) CoerceFloat() (float64, Object)
func (*FloatArray) CoerceInt ¶ added in v0.6.3
func (fa *FloatArray) CoerceInt() (int64, Object)
func (*FloatArray) CoerceString ¶ added in v0.6.3
func (fa *FloatArray) CoerceString() (string, Object)
func (*FloatArray) Cols ¶ added in v0.6.3
func (fa *FloatArray) Cols() int
func (*FloatArray) FloatArrayData ¶ added in v0.6.3
func (fa *FloatArray) FloatArrayData() ([]float64, []int, bool)
func (*FloatArray) Inspect ¶ added in v0.6.3
func (fa *FloatArray) Inspect() string
func (*FloatArray) Is2D ¶ added in v0.6.3
func (fa *FloatArray) Is2D() bool
func (*FloatArray) PrettyPrint ¶ added in v0.6.3
func (fa *FloatArray) PrettyPrint() string
func (*FloatArray) Row ¶ added in v0.6.3
func (fa *FloatArray) Row(i int) []float64
func (*FloatArray) Rows ¶ added in v0.6.3
func (fa *FloatArray) Rows() int
func (*FloatArray) ToList ¶ added in v0.6.3
func (fa *FloatArray) ToList() *List
func (*FloatArray) Type ¶ added in v0.6.3
func (fa *FloatArray) Type() ObjectType
type Function ¶
type Function struct {
Name string
Parameters []*ast.Identifier
DefaultValues map[string]ast.Expression
Variadic *ast.Identifier // *args parameter
Kwargs *ast.Identifier // **kwargs parameter
KeywordOnlyStart int // 1-based index where keyword-only params start; 0 means none
// PositionalOnly is the number of leading parameters that cannot be
// passed by keyword (before a '/' marker); 0 means no marker.
PositionalOnly int
Body *ast.BlockStatement
Env *Environment
LocalSlots map[string]int
LocalSlotNames []string
ParamSlotIndexes []int
ReuseCallEnv bool
// CompiledDefaults holds the compiled form of each DefaultValues entry,
// built once at definition time so calls that fill in a default do not
// walk the AST.
CompiledDefaults map[string]EvalFn
// ResolvedDefaults holds the VALUE of each default, evaluated once at
// definition time in the defining scope, as Python does. Index i aligns
// with Parameters[i]; a nil slot means the parameter has no default. A
// slice rather than a map: one allocation per definition, and the call
// path already walks parameters by index.
ResolvedDefaults []Object
// CompiledBody memoises the body closure, which is compiled on the first
// call and cached on Body, the AST node. The evaluator fills it in only
// when CompilerOwned is set.
CompiledBody EvalFn
// CompilerOwned marks function objects the evaluator's compiler created.
// Each belongs to one interpreter tree, whose execution is serialised, so
// the evaluator may memoise into CompiledBody. Objects assembled elsewhere
// may be shared between trees and are never written after construction.
CompilerOwned bool
// GeneratorPlan is the evaluator's compiled resumable plan for a
// generator function (body contains yield; opaque here, a
// *evaluator.genPlan). Non-nil marks a generator: calling one
// constructs a generator instead of running the body.
GeneratorPlan any
}
func (*Function) CoerceFloat ¶
func (*Function) CoerceString ¶
func (*Function) Type ¶
func (f *Function) Type() ObjectType
type FunctionBuilder ¶
type FunctionBuilder struct {
// contains filtered or unexported fields
}
FunctionBuilder provides a fluent API for creating individual scriptling functions. It allows registering a single typed Go function that is automatically wrapped to handle conversion between Go types and scriptling Objects.
Example usage:
fb := NewFunctionBuilder()
fb.Function(func(a, b int) int { return a + b })
fn := fb.Build()
p.RegisterFunc("add", fn)
func NewFunctionBuilder ¶
func NewFunctionBuilder() *FunctionBuilder
NewFunctionBuilder creates a new FunctionBuilder for building individual functions.
func (*FunctionBuilder) Build ¶
Build creates and returns the BuiltinFunction from this builder. The returned function can be passed directly to RegisterFunc().
func (*FunctionBuilder) Function ¶
func (fb *FunctionBuilder) Function(fn interface{}) *FunctionBuilder
Function registers a typed Go function with the builder. The function must be a Go function with typed parameters. Supported signatures are the same as LibraryBuilder.Function().
Example:
fb.Function(func(a, b int) int { return a + b })
func (*FunctionBuilder) FunctionWithHelp ¶
func (fb *FunctionBuilder) FunctionWithHelp(fn interface{}, helpText string) *FunctionBuilder
FunctionWithHelp registers a function with help text. Help text is displayed when users call help() on the function.
Example:
fb.FunctionWithHelp(func(x float64) float64 {
return math.Sqrt(x)
}, "sqrt(x) - Return the square root of x")
type FunctionSignature ¶
type FunctionSignature struct {
// contains filtered or unexported fields
}
FunctionSignature holds pre-computed function analysis
type Instance ¶
func NewInstance ¶ added in v0.15.0
NewInstance creates an empty instance of the given class. Use the field accessor methods (SetField, GetField, …) to populate it. Every instance is created here so its memory is accounted: instances that reference only each other are held by no counted container.
func NewInstanceWithData ¶ added in v0.15.0
NewInstanceWithData is like NewInstanceWithFields but also attaches an opaque native-data value to the instance.
func NewInstanceWithFields ¶ added in v0.15.0
NewInstanceWithFields creates an instance of the given class pre-populated with the supplied fields. The map is consumed (copied into the instance's storage); a nil map yields an empty instance.
func NewReceiverInstance ¶ added in v0.23.0
NewReceiverInstance returns an instance of class whose typed receiver is client — exactly what a ClassBuilder constructor produces. Library factory functions (connect/open) use it to hand scripts an instance of a typed-receiver class directly, without going through the constructor path.
func (*Instance) CoerceFloat ¶
func (*Instance) CoerceString ¶
func (*Instance) DeleteField ¶ added in v0.15.0
DeleteField removes the named field if present.
func (*Instance) Field ¶ added in v0.15.0
Field returns the value of the named field, or nil if it is not set. It is a convenience for callers that immediately type-assert or coerce a field known to exist; use GetField when you need to distinguish "absent" from "nil".
func (*Instance) FieldCount ¶ added in v0.15.0
FieldCount returns the number of set fields.
func (*Instance) FieldsSnapshot ¶ added in v0.15.0
FieldsSnapshot returns a new map containing a copy of all set fields. Use it where a standalone map is needed (serialization, AsDict); mutating the result does not affect the instance.
func (*Instance) GetBoundMethod ¶ added in v0.5.6
func (i *Instance) GetBoundMethod(name string, method Object) *BoundMethod
func (*Instance) GetField ¶ added in v0.15.0
GetField returns the value of the named field and whether it was set.
func (*Instance) InvalidateBoundMethod ¶ added in v0.5.6
func (*Instance) RangeFields ¶ added in v0.15.0
RangeFields calls fn for each set field in insertion order (the order the fields were first assigned) and stops early if fn returns false.
func (*Instance) SetField ¶ added in v0.15.0
SetField sets the named field, allocating backing storage on first use.
func (*Instance) Type ¶
func (i *Instance) Type() ObjectType
type InstanceReprFunc ¶ added in v0.28.0
InstanceReprFunc renders an instance nested in a container, normally by calling its __repr__. A non-nil Object return is a raised error that aborts the rendering.
type Integer ¶
type Integer struct {
// contains filtered or unexported fields
}
func NewInteger ¶
NewInteger returns a cached integer for small values, or a new Integer for larger values
func (*Integer) CoerceFloat ¶
func (*Integer) CoerceString ¶
func (*Integer) Type ¶
func (i *Integer) Type() ObjectType
type Iterator ¶
type Iterator struct {
// contains filtered or unexported fields
}
Iterator represents a Python-style iterator
func NewEnumerateIterator ¶
EnumerateIterator creates an iterator of (index, value) tuples. Iterator inputs are pulled lazily so infinite iterators can be enumerated.
func NewInfiniteIterator ¶ added in v0.28.0
NewInfiniteIterator creates an iterator that never ends.
func NewIterator ¶
NewIterator creates an iterator with a custom next function This allows creating iterators that can call functions with proper context
func NewRangeIterator ¶
RangeIterator creates an iterator for range(start, stop, step). Range is the one lazy iterator with a known length (Python defines len() for it and nothing else lazy), so the count is computed up front.
func NewReversedIterator ¶
ReversedIterator creates an iterator that returns elements in reverse order
func NewStrictZipIterator ¶ added in v0.28.0
NewStrictZipIterator is zip(..., strict=True): inputs of different lengths raise ValueError when the shortest one runs out.
func NewZipIterator ¶
ZipIterator creates an iterator that zips multiple iterables together. Iterator inputs are pulled lazily, left to right, stopping at the first exhausted input (Python semantics). An error or raised exception yielded by an input is passed through unwrapped so the consumer propagates it.
func (*Iterator) CoerceFloat ¶
func (*Iterator) CoerceString ¶
func (*Iterator) Len ¶ added in v0.27.0
Len returns the iterator's length when statically known (range iterators).
func (*Iterator) RangeRemaining ¶ added in v0.28.0
RangeRemaining reports, for a range iterator, the values it has yet to produce: next, next+step, ... (n of them). ok is false for other iterators.
func (*Iterator) SetTypeName ¶ added in v0.32.0
SetTypeName sets the iterator's type name, Python's name for it ("map", "list_iterator"), and returns the iterator. Share one string per name rather than allocating one per iterator.
func (*Iterator) Type ¶
func (it *Iterator) Type() ObjectType
type Kwargs ¶
Kwargs is a special type for functions that accept keyword arguments. It wraps the raw kwargs map and provides helper methods for extracting values.
func (Kwargs) MustGetBool ¶
MustGetBool extracts a boolean keyword argument, ignoring errors.
func (Kwargs) MustGetFloat ¶
MustGetFloat extracts a float keyword argument, ignoring errors.
func (Kwargs) MustGetInt ¶
MustGetInt extracts an integer keyword argument, ignoring errors.
func (Kwargs) MustGetList ¶
MustGetList extracts a list keyword argument, ignoring errors.
type LambdaFunction ¶
type LambdaFunction struct {
Parameters []*ast.Identifier
DefaultValues map[string]ast.Expression
Variadic *ast.Identifier // *args parameter
Kwargs *ast.Identifier // **kwargs parameter
KeywordOnlyStart int // 1-based index where keyword-only params start; 0 means none
// PositionalOnly is the number of leading parameters that cannot be
// passed by keyword (before a '/' marker); 0 means no marker.
PositionalOnly int
Body ast.Expression
Env *Environment
LocalSlots map[string]int
LocalSlotNames []string
ParamSlotIndexes []int
// CompiledBody is the compiled form of Body, set when the lambda is
// compiled. The evaluator compiles and stores it on first call for
// lambdas assembled elsewhere.
CompiledBody EvalFn
// CompiledDefaults holds the compiled form of each DefaultValues entry,
// built once at definition time so calls that fill in a default do not
// walk the AST.
CompiledDefaults map[string]EvalFn
// ResolvedDefaults holds the VALUE of each default, evaluated once at
// definition time in the defining scope, as Python does. Index i aligns
// with Parameters[i]; a nil slot means the parameter has no default.
ResolvedDefaults []Object
}
func (*LambdaFunction) AsBool ¶
func (lf *LambdaFunction) AsBool() (bool, Object)
func (*LambdaFunction) AsFloat ¶
func (lf *LambdaFunction) AsFloat() (float64, Object)
func (*LambdaFunction) AsInt ¶
func (lf *LambdaFunction) AsInt() (int64, Object)
func (*LambdaFunction) AsList ¶
func (lf *LambdaFunction) AsList() ([]Object, Object)
func (*LambdaFunction) AsString ¶
func (lf *LambdaFunction) AsString() (string, Object)
func (*LambdaFunction) CoerceFloat ¶
func (lf *LambdaFunction) CoerceFloat() (float64, Object)
func (*LambdaFunction) CoerceInt ¶
func (lf *LambdaFunction) CoerceInt() (int64, Object)
func (*LambdaFunction) CoerceString ¶
func (lf *LambdaFunction) CoerceString() (string, Object)
func (*LambdaFunction) Inspect ¶
func (lf *LambdaFunction) Inspect() string
func (*LambdaFunction) Type ¶
func (lf *LambdaFunction) Type() ObjectType
type Library ¶
type Library struct {
// contains filtered or unexported fields
}
Library represents a pre-built collection of builtin functions and constants
func NewLibrary ¶
func NewLibrary(name string, functions map[string]*Builtin, constants map[string]Object, description string) *Library
NewLibrary creates a new library with functions, optional constants, and optional description
func (*Library) CachedDict ¶
CachedDict returns nil (caching removed). Kept for test compatibility.
func (*Library) CoerceFloat ¶
func (*Library) CoerceString ¶
func (*Library) Description ¶
Description returns the library's description
func (*Library) GetDict ¶
GetDict builds and returns a fresh Dict representation of this library. Returns a new dict each time so callers (including concurrent goroutines) never share mutable state.
func (*Library) InstanceData ¶
InstanceData returns the instance-specific data for this library
func (*Library) Instantiate ¶
Instantiate creates a new library instance with instance-specific data Functions are wrapped to inject the instance data into the context
func (*Library) Type ¶
func (l *Library) Type() ObjectType
type LibraryBuilder ¶
type LibraryBuilder struct {
// contains filtered or unexported fields
}
LibraryBuilder provides a fluent API for creating scriptling libraries. It allows registering typed Go functions that are automatically wrapped to handle conversion between Go types and scriptling Objects.
Example usage:
lib := NewLibraryBuilder("mylib", "My custom library")
lib.Function("connect", func(host string, port int) error {
// Connect to host:port
return nil
})
lib.Function("disconnect", func() error {
// Disconnect
return nil
})
lib.Constant("VERSION", "1.0.0")
library := lib.Build()
func NewLibraryBuilder ¶
func NewLibraryBuilder(name, description string) *LibraryBuilder
NewLibraryBuilder creates a new LibraryBuilder with the given name and description.
func (*LibraryBuilder) Alias ¶
func (b *LibraryBuilder) Alias(alias, originalName string) *LibraryBuilder
Alias creates an alias for an existing function.
Example:
builder.Function("add", func(a, b int) int { return a + b })
builder.Alias("sum", "add") // "sum" is now an alias for "add"
func (*LibraryBuilder) Build ¶
func (b *LibraryBuilder) Build() *Library
Build creates and returns the Library from this builder. After calling Build(), the builder should not be used further.
func (*LibraryBuilder) Clear ¶
func (b *LibraryBuilder) Clear() *LibraryBuilder
Clear removes all registered functions and constants.
func (*LibraryBuilder) Constant ¶
func (b *LibraryBuilder) Constant(name string, value interface{}) *LibraryBuilder
Constant registers a constant value with the given name. The value is automatically converted to a scriptling Object. Supported types: string, int, int64, float64, bool, nil
Example:
builder.Constant("VERSION", "1.0.0")
builder.Constant("MAX_CONNECTIONS", 100)
builder.Constant("DEBUG", true)
func (*LibraryBuilder) ConstantCount ¶
func (b *LibraryBuilder) ConstantCount() int
ConstantCount returns the number of registered constants.
func (*LibraryBuilder) Description ¶
func (b *LibraryBuilder) Description(desc string) *LibraryBuilder
Description sets or updates the library description.
func (*LibraryBuilder) Function ¶
func (b *LibraryBuilder) Function(name string, fn interface{}) *LibraryBuilder
Function registers a function with the given name. The function must be a Go function with typed parameters. Parameters can be: string, int, int64, float64, bool, []any, map[string]any Return values can be: any of the above types, or error
Example:
builder.Function("add", func(a, b int) int { return a + b })
builder.Function("greet", func(name string) string { return "Hello, " + name })
builder.Function("connect", func(host string, port int) error { ... })
func (*LibraryBuilder) FunctionCount ¶
func (b *LibraryBuilder) FunctionCount() int
FunctionCount returns the number of registered functions.
func (*LibraryBuilder) FunctionFromVariadic ¶
func (b *LibraryBuilder) FunctionFromVariadic(name string, fn interface{}) *LibraryBuilder
FunctionFromVariadic registers a variadic function that accepts a variable number of arguments. This is useful for functions like print() that can take any number of arguments.
Example:
builder.FunctionFromVariadic("print_all", func(args ...any) {
for _, arg := range args {
fmt.Println(arg)
}
})
func (*LibraryBuilder) FunctionFromVariadicWithHelp ¶
func (b *LibraryBuilder) FunctionFromVariadicWithHelp(name string, fn interface{}, helpText string) *LibraryBuilder
FunctionFromVariadicWithHelp registers a variadic function with help text.
func (*LibraryBuilder) FunctionWithHelp ¶
func (b *LibraryBuilder) FunctionWithHelp(name string, fn interface{}, helpText string) *LibraryBuilder
FunctionWithHelp registers a function with the given name and help text. The function must be a Go function with typed parameters. Help text is displayed when users call help() on the function.
Example:
builder.FunctionWithHelp("sqrt", func(x float64) float64 {
return math.Sqrt(x)
}, "sqrt(x) - Return the square root of x")
func (*LibraryBuilder) GetConstantNames ¶
func (b *LibraryBuilder) GetConstantNames() []string
GetConstantNames returns a sorted list of registered constant names.
func (*LibraryBuilder) GetDescription ¶
func (b *LibraryBuilder) GetDescription() string
GetDescription returns the current library description.
func (*LibraryBuilder) GetFunctionNames ¶
func (b *LibraryBuilder) GetFunctionNames() []string
GetFunctionNames returns a sorted list of registered function names.
func (*LibraryBuilder) HasConstant ¶
func (b *LibraryBuilder) HasConstant(name string) bool
HasConstant checks if a constant with the given name has been registered.
func (*LibraryBuilder) HasFunction ¶
func (b *LibraryBuilder) HasFunction(name string) bool
HasFunction checks if a function with the given name has been registered.
func (*LibraryBuilder) Merge ¶
func (b *LibraryBuilder) Merge(other *LibraryBuilder) *LibraryBuilder
Merge merges another builder's functions and constants into this one. If there are conflicts, the other builder's values take precedence.
func (*LibraryBuilder) RemoveConstant ¶
func (b *LibraryBuilder) RemoveConstant(name string) *LibraryBuilder
RemoveConstant removes a constant by name.
func (*LibraryBuilder) RemoveFunction ¶
func (b *LibraryBuilder) RemoveFunction(name string) *LibraryBuilder
RemoveFunction removes a function by name.
func (*LibraryBuilder) String ¶
func (b *LibraryBuilder) String() string
String returns a string representation of the builder's state.
func (*LibraryBuilder) SubLibrary ¶
func (b *LibraryBuilder) SubLibrary(name string, lib *Library) *LibraryBuilder
SubLibrary embeds a library as a named constant in the parent, enabling attribute-style access: `import parent as p; p.sub.func()`.
Note: for `import parent.sub` to work, the sub-library must also be registered independently via RegisterLibrary using its full dotted name.
Example:
subLib := NewLibraryBuilder("mylib.sub", "Sub utilities").Function(...).Build()
p.RegisterLibrary(subLib) // enables: import mylib.sub as sub
builder.SubLibrary("sub", subLib) // enables: import mylib as m; m.sub.func()
type LibraryInfo ¶
LibraryInfo contains information about available libraries
type LibraryRegistrar ¶
type LibraryRegistrar interface {
RegisterLibrary(lib *Library)
}
LibraryRegistrar is an interface for registering libraries. This allows external libraries to register themselves without circular imports.
type List ¶
type List struct {
Elements []Object
}
func (*List) CoerceFloat ¶
func (*List) CoerceString ¶
func (*List) Type ¶
func (l *List) Type() ObjectType
type Null ¶
type Null struct{}
func (*Null) CoerceFloat ¶
func (*Null) CoerceString ¶
func (*Null) Type ¶
func (n *Null) Type() ObjectType
type Object ¶
type Object interface {
Type() ObjectType
Inspect() string
// Type-safe accessor methods (strict type checking)
AsString() (string, Object)
AsInt() (int64, Object)
AsFloat() (float64, Object)
AsBool() (bool, Object)
AsList() ([]Object, Object)
AsDict() (map[string]Object, Object)
// Coercion methods (loose type conversion with best effort)
CoerceString() (string, Object)
CoerceInt() (int64, Object)
CoerceFloat() (float64, Object)
}
func AcquireArgs ¶ added in v0.20.0
func AcquireArgs(env *Environment, n int) []Object
AcquireArgs returns a []Object of length n for a call's argument list, reusing a buffer from the tree's per-root free-list when one of sufficient capacity is available. The returned slice is BORROWED: the caller must return it via ReleaseArgs once the callee has returned, and no callee may retain the slice past its own call (the interpreter's builtins, user-function binding, and varargs collection all satisfy this — varargs copies, params read by index). Uses the same lock-free, GIL-serialized contract as AcquireCallEnvironment.
func CheckAlloc ¶ added in v0.31.0
CheckAlloc reports whether the interpreter on the calling goroutine may create a value of n bytes: within its value limit and, when it has a memory limit, within the room left (after a collection, if needed). It returns nil when it may, or a MemoryError to hand back to the script. Call it before a large allocation whose size depends on script input.
func CheckAllocFor ¶ added in v0.31.0
CheckAllocFor is CheckAlloc naming what is being created ("joined string", "http response body") in the error.
func CheckElements ¶ added in v0.31.0
CheckElements is CheckAlloc for a container of n element slots.
func CheckRoom ¶ added in v0.31.0
CheckRoom checks only the memory headroom for n bytes about to be held at once (say, a value and the buffer it is built from), without applying the value limit. CheckAllocFor covers both for a single value.
func CheckSlots ¶ added in v0.31.0
CheckSlots applies only the value limit to a container of n element slots, for a container that already exists and is about to grow by one: its memory is already counted, so only the growth is checked for room, by the caller.
func CheckString ¶ added in v0.31.0
CheckString is CheckValue for a string that is evaluated often, such as a literal: inlinable, so with no value limit set it costs one atomic load.
func CheckValue ¶ added in v0.31.0
CheckValue applies the value limit of the interpreter on the calling goroutine to a value an operation has just produced: a string, bytes value, list, tuple, dict or set larger than the limit gives a MemoryError, anything else nil. Containers count one element slot per entry. Operations that know their result size up front should use CheckAlloc instead; this is the backstop for those that do not (encoders, library functions), which can only overshoot by the factor one call expands by.
func CloneObject ¶ added in v0.5.2
CloneObject returns a deep copy of mutable Scriptling objects. Immutable/scalar types (Null, Boolean, Integer, Float, String, Builtin, Function, LambdaFunction, Class, Error, Exception) are returned as-is. Mutable containers (List, Dict, Set, Tuple, Instance) are recursively cloned. Opaque Instance.NativeData is not cloned because there is no generic way to duplicate native Go state safely.
func CoerceWireString ¶ added in v0.21.0
CoerceWireString coerces obj to its machine-facing string form, for wire formats and protocol payloads (query params, messages, tool responses). It behaves like CoerceString except booleans render in their lowercase wire form ("true"/"false") rather than the Python display form ("True"/"False").
func Compare ¶ added in v0.33.0
Compare orders a and b as sorted() does: negative, zero or positive, or an error to propagate (a TypeError for values that cannot be ordered).
func Equal ¶ added in v0.33.0
Equal reports whether a == b as a script would see it. The second return is an error to propagate (a raising __eq__, or a RecursionError).
func InspectRepr ¶ added in v0.28.0
func InspectRepr(obj Object, instanceRepr InstanceReprFunc) (string, Object)
InspectRepr renders a container as Python's repr() does: nested strings are quoted, and nested instances are rendered by instanceRepr (their default representation when it is nil). Non-containers render via Inspect.
func IterableToSlice ¶
IterableToSlice converts any iterable object (List, Tuple, String, Iterator, Set) to a slice of Objects. Returns (elements, ok) where ok is true if the conversion succeeded. For strings, each character becomes a String object. For iterators, this consumes the iterator. For dicts, returns the keys (like Python's list(dict)).
func ReadAllLimited ¶ added in v0.31.0
ReadAllLimited reads r to the end within the limits of the interpreter on the calling goroutine: the result may not pass its value limit, and its buffer must fit in its memory limit (after a collection, if needed). The buffer is charged to the interpreter as it grows. what names the data in the error, which is a MemoryError object; err reports read failures.
type ObjectType ¶
type ObjectType int
const ( INTEGER_OBJ ObjectType = iota FLOAT_OBJ BOOLEAN_OBJ STRING_OBJ NULL_OBJ RETURN_OBJ BREAK_OBJ CONTINUE_OBJ FUNCTION_OBJ LAMBDA_OBJ BUILTIN_OBJ LIST_OBJ TUPLE_OBJ DICT_OBJ ERROR_OBJ EXCEPTION_OBJ CLASS_OBJ INSTANCE_OBJ SUPER_OBJ ITERATOR_OBJ DICT_KEYS_OBJ DICT_VALUES_OBJ DICT_ITEMS_OBJ SET_OBJ SLICE_OBJ PROPERTY_OBJ STATICMETHOD_OBJ CLASSMETHOD_OBJ FLOAT_ARRAY_OBJ BYTES_OBJ SENTINEL_OBJ )
func (ObjectType) String ¶
func (ot ObjectType) String() string
String returns the string representation of the ObjectType
type Property ¶ added in v0.2.0
type Property struct {
Getter Object // Function to call when the attribute is accessed
Setter Object // Function to call when the attribute is assigned (nil = read-only)
}
Property wraps a getter (and optional setter) for use with @property.
func (*Property) CoerceFloat ¶ added in v0.2.0
func (*Property) CoerceString ¶ added in v0.2.0
func (*Property) Type ¶ added in v0.2.0
func (p *Property) Type() ObjectType
type ResourceGuard ¶ added in v0.31.0
type ResourceGuard struct {
// contains filtered or unexported fields
}
ResourceGuard holds one interpreter's limits and memory accounting.
func CurrentGuard ¶ added in v0.31.0
func CurrentGuard() *ResourceGuard
CurrentGuard returns the guard of the interpreter running on the calling goroutine, or nil when none is.
func NewResourceGuard ¶ added in v0.31.0
func NewResourceGuard() *ResourceGuard
NewResourceGuard returns a guard whose limits all follow the process defaults.
func (*ResourceGuard) CopyLimits ¶ added in v0.31.0
func (g *ResourceGuard) CopyLimits(from *ResourceGuard)
CopyLimits gives g the same limit settings as from: explicit limits are copied and limits following the defaults keep following them. Accounting is not copied.
func (*ResourceGuard) MaxBackgroundTasks ¶ added in v0.33.0
func (g *ResourceGuard) MaxBackgroundTasks() int64
MaxBackgroundTasks returns the background task limit in force, 0 when there is none.
func (*ResourceGuard) MaxValueBytes ¶ added in v0.31.0
func (g *ResourceGuard) MaxValueBytes() int64
MaxValueBytes returns the value limit in force, 0 when there is none.
func (*ResourceGuard) MemoryLimit ¶ added in v0.31.0
func (g *ResourceGuard) MemoryLimit() int64
MemoryLimit returns the memory limit in force, 0 when there is none.
func (*ResourceGuard) SetMaxBackgroundTasks ¶ added in v0.33.0
func (g *ResourceGuard) SetMaxBackgroundTasks(n int64)
SetMaxBackgroundTasks sets how many background tasks this interpreter may have queued or running at once. 0 means no limit and InheritLimit (or any negative value) follows the process default.
func (*ResourceGuard) SetMaxValueBytes ¶ added in v0.31.0
func (g *ResourceGuard) SetMaxValueBytes(n int64)
SetMaxValueBytes sets this interpreter's value limit in bytes. 0 means no limit and InheritLimit (or any negative value) follows the process default.
func (*ResourceGuard) SetMemoryLimit ¶ added in v0.31.0
func (g *ResourceGuard) SetMemoryLimit(n int64)
SetMemoryLimit sets this interpreter's memory limit in bytes. 0 means no limit and InheritLimit (or any negative value) follows the process default.
Set limits between calls. A changed limit is enforced for calls that start after the change; a call already running when no memory limit was in force is not registered for cancellation, and a lower limit is checked against memory the interpreter already holds when the next call starts.
func (*ResourceGuard) StartRun ¶ added in v0.31.0
StartRun registers a top-level run so the guard can cancel it if the interpreter goes over its memory limit. It returns the context the run must use and the run to end when it is over. With no memory limit in force it returns ctx unchanged and a nil run, and costs nothing more.
func (*ResourceGuard) StartTask ¶ added in v0.33.0
func (g *ResourceGuard) StartTask() (end func(), err error)
StartTask accounts for a background task the interpreter is about to queue or start, and returns the function that ends it, to be called exactly once when the task is no longer queued or running. The task counts against the background task limit, and TaskBytes is held against the memory limit for its lifetime. It refuses with ErrTaskLimitExceeded when the task limit is reached and with ErrMemoryLimitExceeded when the charge takes the interpreter over its memory limit (its runs are then cancelled, as for any allocation over the limit).
func (*ResourceGuard) Usage ¶ added in v0.31.0
func (g *ResourceGuard) Usage() ResourceUsage
Usage returns a snapshot of the guard's accounting.
type ResourceUsage ¶ added in v0.31.0
type ResourceUsage struct {
// MemoryBytes is the estimated memory currently held.
MemoryBytes int64
// PeakMemoryBytes is the highest MemoryBytes seen.
PeakMemoryBytes int64
// AllocatedBytes is the estimated total allocated since creation,
// including memory since freed.
AllocatedBytes int64
// MemoryLimitCancellations counts runs stopped for exceeding the memory
// limit.
MemoryLimitCancellations uint64
// BackgroundTasks is the number of background tasks queued or running.
BackgroundTasks int64
}
ResourceUsage is a snapshot of one interpreter's resource accounting.
type ReturnValue ¶
type ReturnValue struct {
Value Object
// contains filtered or unexported fields
}
func AcquireReturnValue ¶ added in v0.15.0
func AcquireReturnValue(env *Environment, val Object) *ReturnValue
AcquireReturnValue returns a *ReturnValue wrapping val, reusing one from the tree's per-root free-list when available. The wrapper remembers its root so ReleaseReturnValue can return it without the caller passing the environment. Uses the same lock-free, GIL-serialized contract as AcquireCallEnvironment.
func (*ReturnValue) AsBool ¶
func (rv *ReturnValue) AsBool() (bool, Object)
func (*ReturnValue) AsFloat ¶
func (rv *ReturnValue) AsFloat() (float64, Object)
func (*ReturnValue) AsInt ¶
func (rv *ReturnValue) AsInt() (int64, Object)
func (*ReturnValue) AsList ¶
func (rv *ReturnValue) AsList() ([]Object, Object)
func (*ReturnValue) AsString ¶
func (rv *ReturnValue) AsString() (string, Object)
func (*ReturnValue) CoerceFloat ¶
func (rv *ReturnValue) CoerceFloat() (float64, Object)
func (*ReturnValue) CoerceInt ¶
func (rv *ReturnValue) CoerceInt() (int64, Object)
func (*ReturnValue) CoerceString ¶
func (rv *ReturnValue) CoerceString() (string, Object)
func (*ReturnValue) Inspect ¶
func (rv *ReturnValue) Inspect() string
func (*ReturnValue) Type ¶
func (rv *ReturnValue) Type() ObjectType
type Run ¶ added in v0.31.0
type Run struct {
// contains filtered or unexported fields
}
Run is one top-level execution registered on a guard, and the context the execution runs under: the context it was started from plus the guard's cancellation. The guard cancels a run by moving its generation on, which the evaluator sees at its next periodic check and Err reports; Done is the parent's channel, so work blocked on it finishes its current operation before it is stopped. That keeps a run to one small allocation.
func RunFromContext ¶ added in v0.31.0
RunFromContext returns the run ctx belongs to, nil when it belongs to none.
func (*Run) Cancelled ¶ added in v0.31.0
Cancelled reports whether the guard has cancelled the run for its memory limit.
func (*Run) Done ¶ added in v0.31.0
func (r *Run) Done() <-chan struct{}
Done is the parent's channel: the guard's cancellation is reported by Err and seen by the evaluator's periodic check, not by a channel.
func (*Run) End ¶ added in v0.31.0
func (r *Run) End()
End ends the run. A nil run (no memory limit) ends nothing.
type ScriptCallable ¶ added in v0.15.0
type ScriptCallable interface {
ScriptCall(ctx context.Context, args []Object, kwargs map[string]Object) Object
}
ScriptCallable is implemented by Go types stored inside a ClientWrapper whose instances should be callable from scriptling code (e.g. plugin callbacks). When the evaluator encounters a ClientWrapper whose Client implements this interface, it delegates the call to ScriptCall instead of returning an error.
type Sentinel ¶ added in v0.29.0
type Sentinel struct {
Name string
// Repr overrides Inspect when non-empty; empty means "use Name".
Repr string
}
Sentinel is a unique do-nothing value created by the sentinel() builtin (PEP 661). Each call returns a distinct object that is equal only to itself, so `value is MISSING` is the intended check. repr defaults to the name, which is the point of the feature: a readable marker in logs and the REPL instead of an opaque object address.
func NewSentinel ¶ added in v0.29.0
func (*Sentinel) CoerceFloat ¶ added in v0.29.0
func (*Sentinel) CoerceString ¶ added in v0.29.0
func (*Sentinel) Type ¶ added in v0.29.0
func (s *Sentinel) Type() ObjectType
type Set ¶
type Set struct {
Elements map[string]Object
Frozen bool
// contains filtered or unexported fields
}
Set represents a set of unique objects. A frozen set (Python frozenset) is a Set with Frozen set: it rejects mutation, hashes by content, and prints as frozenset(...). The algebra methods below carry the receiver's frozenness to their result, so frozen | set stays frozen and set | frozen stays mutable, matching Python's left-operand rule.
func NewFrozenSet ¶ added in v0.29.0
func NewFrozenSet() *Set
NewFrozenSet creates a new empty frozen Set (Python frozenset).
func (*Set) AddKeyed ¶ added in v0.3.2
AddKeyed adds an element with a pre-computed key (used when __hash__ is involved)
func (*Set) CoerceFloat ¶
func (*Set) CoerceString ¶
func (*Set) ContainsKeyed ¶ added in v0.3.2
ContainsKeyed checks membership using a pre-computed key
func (*Set) CreateIterator ¶
CreateIterator returns an iterator for the set
func (*Set) Difference ¶
Difference returns a new set with elements in s but not in other
func (*Set) InPlaceDifference ¶ added in v0.27.0
InPlaceDifference removes other's elements from s (Python's s -= other).
func (*Set) InPlaceIntersection ¶ added in v0.27.0
InPlaceIntersection keeps only elements of s that are also in other (Python's s &= other).
func (*Set) InPlaceSymmetricDifference ¶ added in v0.27.0
InPlaceSymmetricDifference keeps elements in exactly one of s and other (Python's s ^= other).
func (*Set) InPlaceUnion ¶ added in v0.27.0
InPlaceUnion merges other into s (Python's s |= other). Aliases of s observe the update.
func (*Set) Intersection ¶
Intersection returns a new set with elements common to both sets
func (*Set) IsSuperset ¶
IsSuperset checks if s is a superset of other
func (*Set) SymmetricDifference ¶
SymmetricDifference returns a new set with elements in either s or other but not both
func (*Set) Type ¶
func (s *Set) Type() ObjectType
type Slice ¶
type Slice struct {
Start *Integer // nil means None (default start)
End *Integer // nil means None (default end)
Step *Integer // nil means None (default step = 1)
}
func (*Slice) CoerceFloat ¶
func (*Slice) CoerceString ¶
func (*Slice) Type ¶
func (s *Slice) Type() ObjectType
type StaticMethod ¶ added in v0.2.0
type StaticMethod struct {
Fn Object
}
StaticMethod wraps a function for use with @staticmethod. When called on an instance, self is not prepended.
func (*StaticMethod) AsBool ¶ added in v0.2.0
func (s *StaticMethod) AsBool() (bool, Object)
func (*StaticMethod) AsDict ¶ added in v0.2.0
func (s *StaticMethod) AsDict() (map[string]Object, Object)
func (*StaticMethod) AsFloat ¶ added in v0.2.0
func (s *StaticMethod) AsFloat() (float64, Object)
func (*StaticMethod) AsInt ¶ added in v0.2.0
func (s *StaticMethod) AsInt() (int64, Object)
func (*StaticMethod) AsList ¶ added in v0.2.0
func (s *StaticMethod) AsList() ([]Object, Object)
func (*StaticMethod) AsString ¶ added in v0.2.0
func (s *StaticMethod) AsString() (string, Object)
func (*StaticMethod) CoerceFloat ¶ added in v0.2.0
func (s *StaticMethod) CoerceFloat() (float64, Object)
func (*StaticMethod) CoerceInt ¶ added in v0.2.0
func (s *StaticMethod) CoerceInt() (int64, Object)
func (*StaticMethod) CoerceString ¶ added in v0.2.0
func (s *StaticMethod) CoerceString() (string, Object)
func (*StaticMethod) Inspect ¶ added in v0.2.0
func (s *StaticMethod) Inspect() string
func (*StaticMethod) Type ¶ added in v0.2.0
func (s *StaticMethod) Type() ObjectType
type String ¶
type String struct {
// contains filtered or unexported fields
}
func NewSubstring ¶ added in v0.31.0
NewSubstring returns a String for sub, a substring of src. A Go substring shares its source's memory, so a short piece of a long string would keep the whole source alive while the memory accounting charged only the piece. While accounting is on, a substring that would hold on to at least detachWaste bytes more than it uses is copied; otherwise this is NewString.
func (*String) CoerceFloat ¶
func (*String) CoerceString ¶
func (*String) StringValue ¶ added in v0.8.0
func (*String) Type ¶
func (s *String) Type() ObjectType
type Super ¶
func (*Super) CoerceFloat ¶
func (*Super) CoerceString ¶
func (*Super) Type ¶
func (s *Super) Type() ObjectType
type Tuple ¶
type Tuple struct {
Elements []Object
}
func (*Tuple) CoerceFloat ¶
func (*Tuple) CoerceString ¶
func (*Tuple) Type ¶
func (t *Tuple) Type() ObjectType