Documentation
¶
Overview ¶
ADDING A NEW PROMOTED OP
Promoted ops inline hot primitives directly in the VM dispatch loop, bypassing arity check, arg binding, and indirect function call. Each promoted op has a non-tail and tail variant.
The 34 switch cases in Run() are deliberately hand-unrolled: Go compiles them to a jump table. A table-driven approach was benchmarked and rejected (~1.5% geo mean regression). See plans/2026-04-05-structural-reduction.md.
Edit sites (3 files):
- opcode.go — add OpXxx + OpXxxTail constants; add two opcodeTable entries with operandKind: OperandCachedBinding
- machine_context.go — add two case branches in Run() (non-tail + tail), each calling execPromoted(mc, instr, name, arity, tail, inlineFn)
- call_promoted.go — implement inlineXxx function; add case in promotedOpForName() (or call_promoted_arithmetic.go for numeric ops)
No changes needed in native_template.go or disassemble.go — both use opcodeTable[op].operandKind metadata to handle OperandCachedBinding generically. The peephole optimizer (peephole.go) also needs no changes — it uses promotedOpForName() to discover promoted ops generically.
Package machine implements the Scheme virtual machine, compiler, and macro expander.
The machine package is the core execution engine for Wile, providing:
Compilation Pipeline ¶
Scheme source undergoes three phases:
- Expansion: macro-expand via [ExpanderTimeContinuation]
- Compilation: generate bytecode via [CompileTimeContinuation]
- Execution: run bytecode via MachineContext
Virtual Machine ¶
The VM is a stack-based bytecode virtual machine with:
- MachineContext: execution state (value register, eval stack, environment, PC)
- MachineContext.Run: main execution loop
- NativeTemplate: compiled bytecode container
- MachineClosure: first-class procedure representation
Continuations ¶
- MachineContinuation: captured continuation state for call/cc
- ComposableContinuation: delimited continuations for prompts
- dynamic-wind support via wind/unwind stacks
Macro System ¶
Implements R7RS hygienic macros with Flatt's "sets of scopes" model:
- [ExpanderTimeContinuation]: macro expansion driver
- syntax-rules pattern matching via internal/match
- syntax-case with fenders and procedural macros
Foreign Functions ¶
Go functions are exposed as ForeignFunction implementations:
type ForeignFunction func(CallContext) error
CallContext is the narrow interface (7 methods) that extensions depend on. The ForeignClosure type wraps these for the VM.
Index ¶
- Variables
- func DecodeLocalIndex(arg int32) (slot, depth int)
- func DisassembleString(tpl *NativeTemplate) string
- func EncodeLocalIndex(li *environment.LocalIndex) int32
- func FindCommonWindingPrefix(current, target WindingStack) int
- func GraftContinuation(segment, target *MachineContinuation)
- func ReleaseSubContext(mc *MachineContext)
- func ReleaseTopLevelContext(mc *MachineContext)
- type BarrierToken
- type Breakpoint
- type BreakpointID
- type CallContext
- type CapturedContinuation
- type CaseLambdaClosure
- func (p *CaseLambdaClosure) AcceptsArity(n int) bool
- func (p *CaseLambdaClosure) Clauses() []*MachineClosure
- func (p *CaseLambdaClosure) Doc() string
- func (p *CaseLambdaClosure) EqualTo(o values.Value) bool
- func (p *CaseLambdaClosure) FindMatchingClause(argCount int) (*MachineClosure, bool)
- func (p *CaseLambdaClosure) IsVoid() bool
- func (p *CaseLambdaClosure) Name() string
- func (p *CaseLambdaClosure) SchemeString() string
- type ClausesWrapper
- type Closure
- type ComposableContinuation
- func (p *ComposableContinuation) AcceptsArity(n int) bool
- func (p *ComposableContinuation) AcquireSegment() *MachineContinuation
- func (p *ComposableContinuation) BarrierValid() *BarrierToken
- func (p *ComposableContinuation) Cont() *MachineContinuation
- func (p *ComposableContinuation) EqualTo(o values.Value) bool
- func (p *ComposableContinuation) IsVoid() bool
- func (p *ComposableContinuation) SchemeString() string
- func (p *ComposableContinuation) ThreadID() uint64
- func (p *ComposableContinuation) WindingStack() WindingStack
- type ContinuationMarkSet
- func (p *ContinuationMarkSet) EqualTo(o values.Value) bool
- func (p *ContinuationMarkSet) First(key, defaultVal values.Value) values.Value
- func (p *ContinuationMarkSet) IsVoid() bool
- func (p *ContinuationMarkSet) SchemeString() string
- func (p *ContinuationMarkSet) ToList(key values.Value) values.Tuple
- func (p *ContinuationMarkSet) ToListStar(keys []values.Value, noneVal values.Value) values.Tuple
- type Debugger
- func (p *Debugger) Breakpoints() []*Breakpoint
- func (p *Debugger) CheckBreakpoint(mc *MachineContext) *Breakpoint
- func (p *Debugger) Continue()
- func (p *Debugger) DisableBreakpoint(id BreakpointID) bool
- func (p *Debugger) EnableBreakpoint(id BreakpointID) bool
- func (p *Debugger) IsStepping() bool
- func (p *Debugger) OnBreak(fn func(mc *MachineContext, bp *Breakpoint))
- func (p *Debugger) RemoveBreakpoint(id BreakpointID) bool
- func (p *Debugger) SetBreakpoint(file string, line, column int) BreakpointID
- func (p *Debugger) ShouldStep(mc *MachineContext) bool
- func (p *Debugger) StepInto()
- func (p *Debugger) StepOut(mc *MachineContext)
- func (p *Debugger) StepOver(mc *MachineContext)
- func (p *Debugger) TriggerBreak(mc *MachineContext, bp *Breakpoint)
- type DisassembledInstruction
- type DisassembledTemplate
- type DynamicWindFrame
- type EditPlan
- func (p *EditPlan) AddLiteral(v values.Value) int32
- func (p *EditPlan) Apply() int
- func (p *EditPlan) Delete(start, end int)
- func (p *EditPlan) HasEdits() bool
- func (p *EditPlan) Insert(at int, instrs []Instruction, src uint32)
- func (p *EditPlan) Replace(start, end int, instrs []Instruction, src uint32)
- type ErrExceptionEscape
- type ErrPromptAbort
- type ExceptionHandler
- type ExpanderCtx
- type ForeignClosure
- func (p *ForeignClosure) AcceptsArity(n int) bool
- func (p *ForeignClosure) Doc() string
- func (p *ForeignClosure) Env() *environment.EnvironmentFrame
- func (p *ForeignClosure) EqualTo(o values.Value) bool
- func (p *ForeignClosure) Fn() ForeignFunction
- func (p *ForeignClosure) IsVariadic() bool
- func (p *ForeignClosure) IsVoid() bool
- func (p *ForeignClosure) Name() string
- func (p *ForeignClosure) ParameterCount() int
- func (p *ForeignClosure) SchemeString() string
- func (p *ForeignClosure) SetDoc(doc string)
- func (p *ForeignClosure) SetName(name string)
- func (p *ForeignClosure) SetValidator(v ForeignFunction)
- func (p *ForeignClosure) Validator() ForeignFunction
- type ForeignFunction
- type FreeIdResolution
- type FreeList
- type InlinedOperation
- type Instruction
- type LiteralIndex
- type MachineClosure
- func (p *MachineClosure) AcceptsArity(n int) bool
- func (p *MachineClosure) Copy() *MachineClosure
- func (p *MachineClosure) Doc() string
- func (p *MachineClosure) Env() *environment.EnvironmentFrame
- func (p *MachineClosure) EqualTo(o values.Value) bool
- func (p *MachineClosure) IsVoid() bool
- func (p *MachineClosure) Name() string
- func (p *MachineClosure) SchemeString() string
- func (p *MachineClosure) Template() *NativeTemplate
- type MachineContext
- func AcquireTopLevelContext(ctx context.Context, tpl *NativeTemplate, env *environment.EnvironmentFrame) *MachineContext
- func NewMachineContext(ctx context.Context, cont *MachineContinuation) *MachineContext
- func NewMachineContextFromMachineClosure(ctx context.Context, cls *MachineClosure) *MachineContext
- func NewThreadSubContext(params SubContextParams, thread *values.Thread) *MachineContext
- func (p *MachineContext) Apply(mcls *MachineClosure, vs ...values.Value) (*MachineContext, error)
- func (p *MachineContext) ApplyCallable(callable values.Value, args ...values.Value) (*MachineContext, error)
- func (p *MachineContext) ApplyCaseLambda(clcls *CaseLambdaClosure, vs ...values.Value) (*MachineContext, error)
- func (p *MachineContext) Arg(index int) values.Value
- func (p *MachineContext) Authorizer() security.Authorizer
- func (p *MachineContext) BarrierValid() *BarrierToken
- func (p *MachineContext) CallDepth() int
- func (p *MachineContext) CaptureStackTrace(maxDepth int) StackTrace
- func (p *MachineContext) CaptureSubContextParams() SubContextParams
- func (p *MachineContext) CollectContinuationMarks(tag *PromptTag) *ContinuationMarkSet
- func (p *MachineContext) Context() context.Context
- func (p *MachineContext) Counters() VMCounters
- func (p *MachineContext) CurrentContinuation() *MachineContinuation
- func (p *MachineContext) CurrentLocation() *values.DebugLocation
- func (p *MachineContext) CurrentSource() *syntax.SourceContext
- func (p *MachineContext) Debugger() *Debugger
- func (p *MachineContext) DeleteMark(key values.Value)
- func (p *MachineContext) EnvironmentFrame() *environment.EnvironmentFrame
- func (p *MachineContext) Error(msg string) *SchemeError
- func (p *MachineContext) EscapeCont() *MachineContinuation
- func (p *MachineContext) Evals() *Stack
- func (p *MachineContext) ExceptionHandler() *ExceptionHandler
- func (p *MachineContext) ExpanderContext() ExpanderCtx
- func (p *MachineContext) FindPrompt(tag *PromptTag) (*MachineContinuation, bool)
- func (p *MachineContext) FormatStackTrace(maxDepth int) string
- func (p *MachineContext) GetImmediateMark(key values.Value) values.Value
- func (p *MachineContext) GetMark(key values.Value) values.Value
- func (p *MachineContext) GetValue() values.Value
- func (p *MachineContext) GetValues() MultipleValues
- func (p *MachineContext) MaxCallDepth() uint64
- func (p *MachineContext) MaxStackSize() uint64
- func (p *MachineContext) NewSubContext() *MachineContext
- func (p *MachineContext) NewSubContextWithTemplate(tpl *NativeTemplate, env *environment.EnvironmentFrame) *MachineContext
- func (p *MachineContext) NewSubContextWithWinding(windingStack WindingStack) *MachineContext
- func (p *MachineContext) PC() int
- func (p *MachineContext) Parent() *MachineContinuation
- func (p *MachineContext) ParentMC() *MachineContext
- func (p *MachineContext) PopContinuation() (*MachineContinuation, error)
- func (p *MachineContext) PopExceptionHandler() *ExceptionHandler
- func (p *MachineContext) PopWindingFrame() *DynamicWindFrame
- func (p *MachineContext) PromptTag() *PromptTag
- func (p *MachineContext) PushExceptionHandler(handler values.Callable)
- func (p *MachineContext) PushWindingFrame(frame *DynamicWindFrame)
- func (p *MachineContext) ResolveParameterValue(param *Parameter) values.Value
- func (p *MachineContext) Restore(cont *MachineContinuation)
- func (p *MachineContext) RestoreAndRelease(cont *MachineContinuation)
- func (p *MachineContext) RestoreWithWinding(cont *MachineContinuation, targetStack WindingStack) error
- func (p *MachineContext) RestoreWithWindingFrom(cont *MachineContinuation, sourceStack, targetStack WindingStack) error
- func (p *MachineContext) RewindTo(target WindingStack, commonDepth int) error
- func (p *MachineContext) Run() error
- func (p *MachineContext) RunWithEscapeHandling() error
- func (p *MachineContext) SaveContinuation(off int) error
- func (p *MachineContext) SetBarrierValid(v *BarrierToken)
- func (p *MachineContext) SetContext(ctx context.Context)
- func (p *MachineContext) SetDebugger(d *Debugger)
- func (p *MachineContext) SetEscapeCont(cont *MachineContinuation)
- func (p *MachineContext) SetExceptionHandler(h *ExceptionHandler)
- func (p *MachineContext) SetExpanderContext(ctx ExpanderCtx)
- func (p *MachineContext) SetMark(key, val values.Value)
- func (p *MachineContext) SetMaxCallDepth(n uint64)
- func (p *MachineContext) SetMaxStackSize(n uint64)
- func (p *MachineContext) SetPC(v int)
- func (p *MachineContext) SetPromptTag(tag *PromptTag)
- func (p *MachineContext) SetThread(t *values.Thread)
- func (p *MachineContext) SetValue(v values.Value)
- func (p *MachineContext) SetValues(vs ...values.Value)
- func (p *MachineContext) SetWindingStack(stack WindingStack)
- func (p *MachineContext) SliceContinuationAt(prompt *MachineContinuation) *MachineContinuation
- func (p *MachineContext) Template() *NativeTemplate
- func (p *MachineContext) Thread() *values.Thread
- func (p *MachineContext) ThreadID() uint64
- func (p *MachineContext) UnwindTo(commonDepth int) error
- func (p *MachineContext) WindingStack() WindingStack
- func (p *MachineContext) WrapError(err error, msg string) *SchemeError
- type MachineContinuation
- func NewMachineContinuation(parent *MachineContinuation, tpl *NativeTemplate, ...) *MachineContinuation
- func NewMachineContinuationFromMachineContext(mc *MachineContext, off int) *MachineContinuation
- func NewMachineContinuationWithPrompt(parent *MachineContinuation, tpl *NativeTemplate, ...) *MachineContinuation
- func (p *MachineContinuation) CallDepth() int
- func (p *MachineContinuation) Copy() *MachineContinuation
- func (p *MachineContinuation) DeepCopy() *MachineContinuation
- func (p *MachineContinuation) EnvironmentFrame() *environment.EnvironmentFrame
- func (p *MachineContinuation) EqualTo(o values.Value) bool
- func (p *MachineContinuation) IsVoid() bool
- func (p *MachineContinuation) MarkChainShared()
- func (p *MachineContinuation) PC() int
- func (p *MachineContinuation) Parent() *MachineContinuation
- func (p *MachineContinuation) PromptHandler() Closure
- func (p *MachineContinuation) PromptTag() *PromptTag
- func (p *MachineContinuation) PushValues(v ...values.Value)
- func (p *MachineContinuation) SchemeString() string
- func (p *MachineContinuation) SetPC(v int)
- func (p *MachineContinuation) SetPromptHandler(h Closure)
- func (p *MachineContinuation) SetPromptTag(t *PromptTag)
- func (p *MachineContinuation) Template() *NativeTemplate
- func (p *MachineContinuation) ThreadID() uint64
- type MacroEvaluator
- type MultipleValues
- type NamedCallable
- type NativeTemplate
- func (p *NativeTemplate) AppendCachedBinding(bd *environment.Binding) int32
- func (p *NativeTemplate) AppendInstruction(instr Instruction)
- func (p *NativeTemplate) AppendInstructionWithSource(src *syntax.SourceContext, instr Instruction)
- func (p *NativeTemplate) AppendOperations(ops ...Operation)
- func (p *NativeTemplate) AppendOperationsWithSource(src *syntax.SourceContext, ops ...Operation)
- func (p *NativeTemplate) AppendSideTableOp(op InlinedOperation) Instruction
- func (p *NativeTemplate) CachedBindings() []*environment.Binding
- func (p *NativeTemplate) Code() []Instruction
- func (p *NativeTemplate) CodeLen() int
- func (p *NativeTemplate) Copy() *NativeTemplate
- func (p *NativeTemplate) DeduplicateLiteral(v values.Value) values.Value
- func (p *NativeTemplate) Doc() string
- func (p *NativeTemplate) EqualTo(o values.Value) bool
- func (p *NativeTemplate) IncrementParameterCount()
- func (p *NativeTemplate) IsVariadic() bool
- func (p *NativeTemplate) IsVoid() bool
- func (p *NativeTemplate) Literals() MultipleValues
- func (p *NativeTemplate) MaybeAppendLiteral(v values.Value) LiteralIndex
- func (p *NativeTemplate) Name() string
- func (p *NativeTemplate) Operations() Operations
- func (p *NativeTemplate) Optimize()
- func (p *NativeTemplate) ParameterCount() int
- func (p *NativeTemplate) PatchInstructionArg(codeIdx int, arg int32)
- func (p *NativeTemplate) SchemeString() string
- func (p *NativeTemplate) SetDoc(doc string)
- func (p *NativeTemplate) SetName(name string)
- func (p *NativeTemplate) SetVariadic()
- func (p *NativeTemplate) SideTable() []InlinedOperation
- func (p *NativeTemplate) SourceAt(pc int) *syntax.SourceContext
- func (p *NativeTemplate) ValueCount() int
- type OpCode
- type OperandKind
- type Operation
- type OperationApply
- type OperationBase
- type OperationBindPatternVars
- type OperationBranchOffsetImmediate
- type OperationBranchOnFalseValueOffsetImmediate
- type OperationBuildSyntaxList
- type OperationClearSyntaxCaseInput
- type OperationDrop
- type OperationForeignFunctionCall
- type OperationLoadCachedBinding
- type OperationLoadGlobalByGlobalIndexLiteralIndexImmediate
- type OperationLoadLiteralByLiteralIndexImmediate
- type OperationLoadLocalByLocalIndexImmediate
- type OperationLoadVoid
- type OperationMakeCaseLambdaClosure
- type OperationMakeClosure
- type OperationPeekK
- type OperationPop
- type OperationPopEnv
- type OperationPopWind
- type OperationPull
- type OperationPush
- type OperationPushEnv
- type OperationPushWind
- type OperationRestoreContMark
- type OperationRestoreContinuation
- type OperationSaveContMark
- type OperationSaveContinuationOffsetImmediate
- type OperationSetContMark
- type OperationStoreGlobalByGlobalIndexLiteralIndexImmediate
- type OperationStoreLocalByLocalIndexImmediate
- type OperationStoreSyntaxCaseInput
- type OperationSyntaxCaseMatch
- type OperationSyntaxCaseNoMatch
- type OperationSyntaxRulesTransform
- type OperationSyntaxTemplateExpand
- type OperationUnpackListToStack
- type Operations
- type Parameter
- func (p *Parameter) AcceptsArity(n int) bool
- func (p *Parameter) Converter() Closure
- func (p *Parameter) EqualTo(v values.Value) bool
- func (p *Parameter) HasConverter() bool
- func (p *Parameter) IsVoid() bool
- func (p *Parameter) SchemeString() string
- func (p *Parameter) SetValue(v values.Value)
- func (p *Parameter) Value() values.Value
- type Pool
- type PoolHandle
- type PoolManager
- type PoolSnapshot
- type PromptTag
- type SchemeError
- type Stack
- func (p Stack) AsList() values.Tuple
- func (p *Stack) Clear()
- func (p Stack) Copy() *Stack
- func (p *Stack) Drain() []values.Value
- func (p Stack) IsVoid() bool
- func (p Stack) Len() int
- func (p Stack) PeekK(i int) values.Value
- func (p *Stack) Pop() values.Value
- func (p *Stack) PopAll() []values.Value
- func (p *Stack) PopN(n int) []values.Value
- func (p *Stack) Pull() values.Value
- func (p *Stack) PullDrain() (values.Value, []values.Value)
- func (p *Stack) Push(v values.Value)
- func (p *Stack) PushAll(vs []values.Value)
- func (p Stack) SchemeString() string
- func (p Stack) String() string
- type StackFrame
- type StackTrace
- type StepMode
- type SubContextParams
- type SyntaxCaseClause
- type SyntaxRulesClause
- type VMCounters
- type WindingStack
Constants ¶
This section is empty.
Variables ¶
var DefaultPromptTag = NewPromptTag("default")
DefaultPromptTag is the default prompt tag installed at the top of execution.
var ErrBindingNotFound = werr.NewStaticError("binding not found")
var ErrInvalidGlobalIndex = werr.NewStaticError("literal is not a global index")
var ErrInvalidLiteralIndex = werr.NewStaticError("invalid literal index")
var ErrInvalidProgramCounter = werr.NewStaticError("invalid program counter")
var ErrLocalIndexOverflow = werr.NewStaticError("local index overflow")
ErrLocalIndexOverflow signals that a De Bruijn index slot or depth exceeds the int16 encoding range (-32768..32767). EncodeLocalIndex panics with this sentinel when the bytecode format cannot represent the index.
var ErrMachineDoNotAdvancePC = werr.NewStaticError("machine do not advance PC: operation did not advance program counter")
Functions ¶
func DecodeLocalIndex ¶ added in v1.4.0
DecodeLocalIndex unpacks slot and depth from a bit-packed Instruction.Arg.
func DisassembleString ¶ added in v1.10.5
func DisassembleString(tpl *NativeTemplate) string
DisassembleString produces a columnar human-readable listing from a NativeTemplate.
func EncodeLocalIndex ¶ added in v1.4.0
func EncodeLocalIndex(li *environment.LocalIndex) int32
EncodeLocalIndex packs a LocalIndex's slot and depth into a single int32 for storage in Instruction.Arg. Slot occupies the low 16 bits; depth occupies the high 16 bits. Both values must fit in int16 range (max 32767).
De Bruijn indices (de Bruijn 1972). Variables are addressed by numeric coordinates, eliminating name lookup at runtime.
addr(x) = (slot, depth), where: depth = number of enclosing λ-binders from use to definition slot = index within the binding array at that depth Encoding: Arg = (depth << 16) | (slot & 0xFFFF) Invariant: the same variable always has the same (slot, depth) regardless of its name. Alpha-equivalence is a non-issue at runtime. Constrains: GetLocalBindingBySlotDepth / SetLocalValueBySlotDepth (runtime access walks depth parent pointers, indexes by slot), linked closures (parent chain must match compile-time depth). Constrained by: resolveLocal (compile-time computation of depth by walking the EnvironmentFrame parent chain).
See BIBLIOGRAPHY.md "De Bruijn Indices / Lexical Addressing".
func FindCommonWindingPrefix ¶
func FindCommonWindingPrefix(current, target WindingStack) int
FindCommonWindingPrefix finds the longest common prefix of two winding stacks. Returns the index where they diverge (0 means no common frames).
func GraftContinuation ¶
func GraftContinuation(segment, target *MachineContinuation)
GraftContinuation walks the segment chain to its bottom frame and sets its parent to target, effectively splicing the segment onto the target chain.
func ReleaseSubContext ¶ added in v1.4.0
func ReleaseSubContext(mc *MachineContext)
ReleaseSubContext zeros the MachineContext and returns it to the pool. Exported because call sites live in other packages (registry/, extensions/).
func ReleaseTopLevelContext ¶ added in v1.5.0
func ReleaseTopLevelContext(mc *MachineContext)
ReleaseTopLevelContext zeros the MachineContext and returns it to the pool. Exported because the primary call sites live in the root wile package (engine.go).
Types ¶
type BarrierToken ¶ added in v1.4.0
type BarrierToken struct {
// contains filtered or unexported fields
}
BarrierToken is an opaque identity for a with-continuation-barrier scope. Each call to call-with-continuation-barrier creates a fresh token. Barrier crossing is detected by pointer identity comparison: if the capture-time token differs from the invocation-time token, the continuation would cross a barrier boundary.
nil means "not inside any barrier."
The _ field ensures non-zero struct size. Go may return the same pointer for all zero-sized allocations (runtime.zerobase), which would defeat pointer identity comparison.
func NewBarrierToken ¶ added in v1.4.0
func NewBarrierToken() *BarrierToken
NewBarrierToken creates a fresh barrier identity token.
type Breakpoint ¶
type Breakpoint struct {
ID BreakpointID
File string
Line int
Column int // 0 = any column on line
Enabled bool
HitCount int
}
Breakpoint represents a source-level breakpoint.
type CallContext ¶ added in v1.10.7
type CallContext interface {
// Arg returns the argument at the given positional index.
// For variadic functions, the last parameter index holds the rest list.
Arg(index int) values.Value
// SetValue sets the single return value.
SetValue(v values.Value)
// SetValues sets multiple return values for R7RS values/call-with-values.
SetValues(vs ...values.Value)
// Authorizer returns the security authorizer for permission checks.
Authorizer() security.Authorizer
// Context returns the Go context for cancellation and timeout.
Context() context.Context
// EnvironmentFrame returns the current lexical environment frame.
EnvironmentFrame() *environment.EnvironmentFrame
// Thread returns the SRFI-18 thread object (nil for primordial thread).
Thread() *values.Thread
}
type CapturedContinuation ¶ added in v1.7.0
type CapturedContinuation struct {
// contains filtered or unexported fields
}
CapturedContinuation is the value returned by call/cc to Scheme code. It is both callable (invoking it escapes to the captured point) and introspectable (continuation-marks can extract marks from its chain).
This replaces the opaque ForeignClosure that call/cc previously returned. The escape logic (thread check, barrier check, compose-then-abort) now lives in applyCapturedContinuation rather than inside a Go closure.
func NewCapturedContinuation ¶ added in v1.7.0
func NewCapturedContinuation( cc *ComposableContinuation, threadID uint64, barrierValid *BarrierToken, ) *CapturedContinuation
NewCapturedContinuation creates a captured continuation value from a composable continuation segment and the safety context at capture time.
func (*CapturedContinuation) AcceptsArity ¶ added in v1.7.0
func (p *CapturedContinuation) AcceptsArity(n int) bool
AcceptsArity reports whether this continuation can be called with n arguments. Escape continuations accept exactly 1 argument — the value to resume with.
func (*CapturedContinuation) ComposableContinuation ¶ added in v1.7.0
func (p *CapturedContinuation) ComposableContinuation() *ComposableContinuation
ComposableContinuation returns the underlying composable continuation, which carries the MachineContinuation chain for mark extraction.
func (*CapturedContinuation) EqualTo ¶ added in v1.7.0
func (p *CapturedContinuation) EqualTo(o values.Value) bool
func (*CapturedContinuation) IsVoid ¶ added in v1.7.0
func (p *CapturedContinuation) IsVoid() bool
func (*CapturedContinuation) SchemeString ¶ added in v1.7.0
func (p *CapturedContinuation) SchemeString() string
type CaseLambdaClosure ¶
type CaseLambdaClosure struct {
// contains filtered or unexported fields
}
CaseLambdaClosure dispatches to the first clause whose arity matches the argument count. Each clause is a MachineClosure with its own template and captured environment.
func NewCaseLambdaClosure ¶
func NewCaseLambdaClosure(closures []*MachineClosure) *CaseLambdaClosure
func (*CaseLambdaClosure) AcceptsArity ¶ added in v1.5.0
func (p *CaseLambdaClosure) AcceptsArity(n int) bool
AcceptsArity reports whether any clause in this case-lambda can accept n arguments.
func (*CaseLambdaClosure) Clauses ¶
func (p *CaseLambdaClosure) Clauses() []*MachineClosure
func (*CaseLambdaClosure) Doc ¶ added in v1.10.7
func (p *CaseLambdaClosure) Doc() string
Doc returns the documentation from the first clause's template, or "" if no clauses.
func (*CaseLambdaClosure) EqualTo ¶
func (p *CaseLambdaClosure) EqualTo(o values.Value) bool
EqualTo implements Scheme equality for case-lambda closures. Two void closures (nil receivers) are considered equal to each other. Non-void closures are equal only if they have the same number of clauses and each corresponding clause is EqualTo its counterpart.
func (*CaseLambdaClosure) FindMatchingClause ¶
func (p *CaseLambdaClosure) FindMatchingClause(argCount int) (*MachineClosure, bool)
FindMatchingClause finds the first clause that matches the given argument count. It returns the matching closure and true when a clause can accept exactly argCount arguments (for fixed-arity clauses) or at least argCount arguments (for variadic clauses). If the receiver is nil or no clause matches, it returns nil, false.
func (*CaseLambdaClosure) IsVoid ¶
func (p *CaseLambdaClosure) IsVoid() bool
IsVoid reports whether this value represents the absence of a case-lambda closure. A nil receiver is treated as a distinguished "void" closure value, used as a sentinel to mean "no closure" rather than an error.
func (*CaseLambdaClosure) Name ¶ added in v1.10.7
func (p *CaseLambdaClosure) Name() string
Name returns the name from the first clause's template, or "" if no clauses.
func (*CaseLambdaClosure) SchemeString ¶
func (p *CaseLambdaClosure) SchemeString() string
SchemeString returns the Scheme-readable representation of a case-lambda closure. Note that the void value (nil receiver) still prints as a case-lambda closure; callers must use IsVoid to distinguish the sentinel.
type ClausesWrapper ¶ added in v1.10.5
type ClausesWrapper struct {
Clauses []*SyntaxRulesClause
}
ClausesWrapper wraps a slice of SyntaxRulesClause as a values.Value for storage in NativeTemplate literals.
func (*ClausesWrapper) EqualTo ¶ added in v1.10.5
func (p *ClausesWrapper) EqualTo(other values.Value) bool
func (*ClausesWrapper) IsVoid ¶ added in v1.10.5
func (p *ClausesWrapper) IsVoid() bool
func (*ClausesWrapper) SchemeString ¶ added in v1.10.5
func (p *ClausesWrapper) SchemeString() string
type Closure ¶ added in v1.5.0
type Closure interface {
values.Callable
NamedCallable
// contains filtered or unexported methods
}
Closure is a callable that can be directly applied — either a compiled Scheme closure (*MachineClosure) or a Go foreign function (*ForeignClosure). Distinguished from other Callable types (CaseLambdaClosure, Parameter, ComposableContinuation) which have different application semantics.
type ComposableContinuation ¶
type ComposableContinuation struct {
// contains filtered or unexported fields
}
ComposableContinuation is a callable value wrapping a delimited continuation segment (a chain of MachineContinuation frames) plus the captured winding stack. When applied, it splices its frames onto the current continuation, effectively composing the captured computation with the current one.
This implements Racket-style composable continuations as described in Flatt, Yu, Findler, Felleisen "Adding Delimited and Composable Control to a Production Programming Environment" (ICFP 2007).
func NewComposableContinuation ¶
func NewComposableContinuation(cont *MachineContinuation, windingStack WindingStack, threadID uint64, barrierValid *BarrierToken) *ComposableContinuation
NewComposableContinuation creates a composable continuation from a continuation chain segment and the winding stack captured at the point of capture. barrierValid is mc.BarrierValid() at capture time; nil means the capture happened outside any with-continuation-barrier.
func (*ComposableContinuation) AcceptsArity ¶ added in v1.5.0
func (p *ComposableContinuation) AcceptsArity(n int) bool
AcceptsArity reports whether this composable continuation can be called with n arguments. Composable continuations accept exactly 1 argument — the value to resume with.
func (*ComposableContinuation) AcquireSegment ¶ added in v1.6.0
func (p *ComposableContinuation) AcquireSegment() *MachineContinuation
AcquireSegment returns the continuation segment for grafting.
First invocation marks the segment shared and returns it directly, avoiding a DeepCopy. Shared marking ensures RestoreAndRelease preserves frame evals for potential re-invocation.
Subsequent invocations reset the bottom frame's parent to nil (undoing GraftContinuation's mutation from the prior invocation) and deep-copy from the preserved shared frames.
This optimizes one-shot continuations (the common case in Schelog-style backtracking), eliminating O(depth) frame allocations per invocation.
func (*ComposableContinuation) BarrierValid ¶ added in v1.4.0
func (p *ComposableContinuation) BarrierValid() *BarrierToken
BarrierValid returns the barrier identity token captured when this continuation was created. Used by applyComposableContinuation to detect barrier crossings.
func (*ComposableContinuation) Cont ¶
func (p *ComposableContinuation) Cont() *MachineContinuation
func (*ComposableContinuation) EqualTo ¶
func (p *ComposableContinuation) EqualTo(o values.Value) bool
func (*ComposableContinuation) IsVoid ¶
func (p *ComposableContinuation) IsVoid() bool
func (*ComposableContinuation) SchemeString ¶
func (p *ComposableContinuation) SchemeString() string
func (*ComposableContinuation) ThreadID ¶ added in v1.1.0
func (p *ComposableContinuation) ThreadID() uint64
func (*ComposableContinuation) WindingStack ¶
func (p *ComposableContinuation) WindingStack() WindingStack
type ContinuationMarkSet ¶ added in v1.7.0
type ContinuationMarkSet struct {
// contains filtered or unexported fields
}
ContinuationMarkSet is an immutable snapshot of continuation marks collected from a walk of the continuation chain.
The frames slice contains per-frame mark slices, nearest frame first. Only frames with non-nil marks are included. Each frame is a []markEntry searched with eqIdentity (eq? semantics).
func CollectMarksFromContinuation ¶ added in v1.7.0
func CollectMarksFromContinuation(cont *MachineContinuation, tag *PromptTag) *ContinuationMarkSet
CollectMarksFromContinuation walks a captured MachineContinuation chain and builds a ContinuationMarkSet snapshot. Used by the (continuation-marks cont) primitive to extract marks from a continuation captured via call/cc.
Starts from cont (nearest frame) and walks parent links, stopping at the first frame whose promptTag matches tag (inclusive). Pass DefaultPromptTag for an unbounded walk.
func (*ContinuationMarkSet) EqualTo ¶ added in v1.7.0
func (p *ContinuationMarkSet) EqualTo(o values.Value) bool
func (*ContinuationMarkSet) First ¶ added in v1.7.0
func (p *ContinuationMarkSet) First(key, defaultVal values.Value) values.Value
First returns the value for key from the nearest frame, or defaultVal if no frame contains the key. Uses eq? semantics (eqIdentity) for key comparison.
func (*ContinuationMarkSet) IsVoid ¶ added in v1.7.0
func (p *ContinuationMarkSet) IsVoid() bool
func (*ContinuationMarkSet) SchemeString ¶ added in v1.7.0
func (p *ContinuationMarkSet) SchemeString() string
func (*ContinuationMarkSet) ToList ¶ added in v1.7.0
func (p *ContinuationMarkSet) ToList(key values.Value) values.Tuple
ToList returns a list of values for key across all frames, nearest first. Returns the empty list if no frame contains the key. Uses eq? semantics (eqIdentity) for key comparison.
func (*ContinuationMarkSet) ToListStar ¶ added in v1.7.0
ToListStar returns a list of vectors for multiple keys across all frames. Each vector corresponds to a frame that has at least one of the requested keys. Vector positions correspond to the keys slice; noneVal fills missing keys. Uses eq? semantics (eqIdentity) for key comparison.
Racket §10.5: continuation-mark-set->list*
type Debugger ¶
type Debugger struct {
// contains filtered or unexported fields
}
Debugger manages breakpoints and stepping.
func (*Debugger) Breakpoints ¶
func (p *Debugger) Breakpoints() []*Breakpoint
Breakpoints returns all breakpoints.
func (*Debugger) CheckBreakpoint ¶
func (p *Debugger) CheckBreakpoint(mc *MachineContext) *Breakpoint
CheckBreakpoint checks if execution should break at current location.
func (*Debugger) DisableBreakpoint ¶
func (p *Debugger) DisableBreakpoint(id BreakpointID) bool
DisableBreakpoint disables a breakpoint.
func (*Debugger) EnableBreakpoint ¶
func (p *Debugger) EnableBreakpoint(id BreakpointID) bool
EnableBreakpoint enables a breakpoint.
func (*Debugger) IsStepping ¶
IsStepping returns whether the debugger is in stepping mode.
func (*Debugger) OnBreak ¶
func (p *Debugger) OnBreak(fn func(mc *MachineContext, bp *Breakpoint))
OnBreak sets the callback for when a breakpoint is hit.
func (*Debugger) RemoveBreakpoint ¶
func (p *Debugger) RemoveBreakpoint(id BreakpointID) bool
RemoveBreakpoint removes a breakpoint.
func (*Debugger) SetBreakpoint ¶
func (p *Debugger) SetBreakpoint(file string, line, column int) BreakpointID
SetBreakpoint adds a breakpoint at the given source location.
func (*Debugger) ShouldStep ¶
func (p *Debugger) ShouldStep(mc *MachineContext) bool
ShouldStep checks if we should break due to stepping.
func (*Debugger) StepOut ¶
func (p *Debugger) StepOut(mc *MachineContext)
StepOut enables step-out mode.
func (*Debugger) StepOver ¶
func (p *Debugger) StepOver(mc *MachineContext)
StepOver enables step-over mode.
func (*Debugger) TriggerBreak ¶
func (p *Debugger) TriggerBreak(mc *MachineContext, bp *Breakpoint)
TriggerBreak calls the break callback if set.
type DisassembledInstruction ¶ added in v1.10.5
type DisassembledInstruction struct {
PC int
Op string
Arg int32
HasArg bool // true when Arg is meaningful (distinguishes unused from Arg=0)
Slot int // decoded slot for local ops; -1 when not applicable
Depth int // decoded depth for local ops; -1 when not applicable
Target int // absolute PC for branch/save ops; -1 when not applicable
Literal string // SchemeString() of resolved literal; "" when not applicable
Binding string // name of cached binding's value; "" when not applicable
SideOp string // String() of InlinedOperation; "" when not applicable
Source string // "file:line:col" or ""
}
DisassembledInstruction holds the annotation for a single bytecode instruction.
type DisassembledTemplate ¶ added in v1.10.5
type DisassembledTemplate struct {
Name string
ParamCount int
IsVariadic bool
Doc string
Literals []string // SchemeString() of each literal
Bindings []string // name of each cached binding
Instructions []DisassembledInstruction
}
DisassembledTemplate holds the annotated disassembly of a NativeTemplate.
func Disassemble ¶ added in v1.10.5
func Disassemble(tpl *NativeTemplate) DisassembledTemplate
Disassemble walks the template's bytecode and produces a DisassembledTemplate with annotations resolved per opcode category.
type DynamicWindFrame ¶
type DynamicWindFrame struct {
Before Closure // Called when entering this extent
After Closure // Called when exiting this extent
ID uint64 // Unique identifier for extent matching
}
DynamicWindFrame represents a single dynamic-wind extent. Each frame tracks the before/after thunks for one dynamic-wind call.
R7RS §6.10: dynamic-wind establishes a dynamic extent during which the before and after thunks are called whenever control enters or exits.
Continuation-wind interaction (Friedman & Haynes 1985, Clinger et al. 1999). The winding stack W is separate from continuation chain K.
W = [w₁, w₂, ...wₙ] where wᵢ = (before_i, after_i, id_i)
On continuation invocation from Wsrc to Wtgt:
prefix = FindCommonWindingPrefix(Wsrc, Wtgt)
UnwindTo(prefix): call after_n, after_{n-1}, ... (innermost first)
RewindTo(Wtgt): call before_{prefix+1}, ... (outermost first)
Invariant: W is captured by value at call/cc time (copied into
ComposableContinuation), NOT stored per continuation frame.
W belongs to the dynamic extent, not the lexical continuation.
Constrains: RestoreWithWindingFrom (must compute prefix and run
thunks in correct order). Sub-contexts inherit W from their parent
via NewSubContext; NewSubContextWithWinding overrides for truncated
stacks during unwind/exception cleanup.
Constrained by: CESK model (W is NOT part of K — it is orthogonal
state). PushWind/PopWind opcodes maintain W during normal execution.
See BIBLIOGRAPHY.md "Dynamic-Wind" and "Continuation-Wind Interaction".
func NewDynamicWindFrame ¶
func NewDynamicWindFrame(before, after Closure) *DynamicWindFrame
NewDynamicWindFrame creates a new winding frame with a unique ID.
type EditPlan ¶ added in v1.5.0
type EditPlan struct {
// contains filtered or unexported fields
}
EditPlan collects non-overlapping bytecode edits for a NativeTemplate. Edits are applied in a single pass via Apply, which rewrites code, sourceRefs, and branch offsets, then garbage-collects unreferenced sideTable entries.
Apply remaps these Arg categories automatically:
- PC offsets: Branch, BranchOnFalseValue, SaveContinuation
- SideTable indices: Complex (unreferenced entries are GC'd)
These are stable across Apply and not touched:
- Literal pool indices: LoadLiteral, LoadGlobal, StoreGlobal, PushLiteral, PushGlobal
- Local indices: LoadLocal, StoreLocal, PushLocal
- Stack offsets: PeekK
func NewEditPlan ¶ added in v1.5.0
func NewEditPlan(tpl *NativeTemplate) *EditPlan
NewEditPlan creates a new edit plan for the given template.
func (*EditPlan) AddLiteral ¶ added in v1.5.0
AddLiteral adds a value to the template's literal pool, with deduplication. Returns the index suitable for use in Instruction.Arg fields that reference the literal pool (OpLoadLiteral, OpLoadGlobal, OpStoreGlobal).
func (*EditPlan) Apply ¶ added in v1.5.0
Apply rewrites the template according to all accumulated edits:
- Sorts and validates edits (panics on overlap)
- Builds a PC remap from old positions to new positions
- Fixes branch offsets for surviving original instructions
- Rebuilds code + sourceRefs, splicing in replacements
- Garbage-collects unreferenced sideTable entries, remaps OpComplex.Arg
Returns the net change in instruction count (negative means code shrunk).
type ErrExceptionEscape ¶
type ErrExceptionEscape struct {
Condition values.Value // The raised condition/object
Continuable bool // Whether handler can return
Continuation *MachineContinuation // Return point for continuable exceptions
Handled bool // Set true after handler processes it
WindingStack WindingStack // Winding stack at raise point (for proper unwinding)
Source *syntax.SourceContext // Source location where exception was raised
StackTrace StackTrace // VM stack trace at raise point
}
ErrExceptionEscape signals an exception being raised through the call stack. It is used by raise and raise-continuable to propagate exceptions to handlers.
func (*ErrExceptionEscape) Error ¶
func (p *ErrExceptionEscape) Error() string
Error implements the error interface.
When Source is present and the condition is a NativeError, produces clean human-readable output like "file:5:3: error: division by zero". For non-NativeError conditions with Source, produces "file:5:3: exception: foo". When no Source is set, falls back to the original format for backward compat.
func (*ErrExceptionEscape) Unwrap ¶ added in v1.3.0
func (p *ErrExceptionEscape) Unwrap() error
Unwrap returns the underlying error when the condition implements the error interface (e.g., *NativeError). This enables errors.Is/errors.As to traverse through ErrExceptionEscape into the wrapped error chain, supporting sentinel matching like errors.Is(err, werr.ErrDivisionByZero) from Go callers.
type ErrPromptAbort ¶
ErrPromptAbort signals an abort to the nearest continuation prompt matching the given tag. It propagates up through Run() and is caught by RunWithEscapeHandling() or by call-with-continuation-prompt sub-contexts.
When caught, the handler finds the matching prompt frame, unwinds dynamic-wind extents, and invokes the prompt's handler with the abort values.
func (*ErrPromptAbort) Error ¶
func (p *ErrPromptAbort) Error() string
type ExceptionHandler ¶
type ExceptionHandler struct {
// contains filtered or unexported fields
}
ExceptionHandler represents an installed exception handler. Handlers form a linked list (stack) for dynamic exception handling. When an exception is raised, handlers are invoked in reverse order of installation (most recent first).
func NewExceptionHandler ¶
func NewExceptionHandler(handler values.Callable, parent *ExceptionHandler) *ExceptionHandler
NewExceptionHandler creates a new exception handler with the given handler procedure and parent handler.
func (*ExceptionHandler) Handler ¶
func (p *ExceptionHandler) Handler() values.Callable
Handler returns the handler procedure.
func (*ExceptionHandler) Parent ¶
func (p *ExceptionHandler) Parent() *ExceptionHandler
Parent returns the previous handler in the chain.
type ExpanderCtx ¶ added in v1.10.5
type ExpanderCtx interface {
Env() *environment.EnvironmentFrame
Expand(syntax.SyntaxValue) (syntax.SyntaxValue, error)
ExpandOnce(syntax.SyntaxValue) (syntax.SyntaxValue, bool, error)
IntroductionScope() *syntax.Scope
SetIntroductionScope(*syntax.Scope)
UseSiteScope() *syntax.Scope
SetUseSiteScope(*syntax.Scope)
}
ExpanderCtx abstracts the macro expansion context so that code needing expansion capabilities can depend on this interface rather than the concrete ExpanderContext. This enables the future machine/compilation sub-package to provide ExpanderContext without circular imports back to machine/.
type ForeignClosure ¶ added in v1.5.0
type ForeignClosure struct {
// contains filtered or unexported fields
}
ForeignClosure wraps a Go function as a directly-callable Scheme procedure. Unlike MachineClosure, it holds the ForeignFunction directly and bypasses the bytecode VM — no template, no opcodes, no VM loop iteration.
func NewForeignClosure ¶
func NewForeignClosure(env *environment.EnvironmentFrame, pcnt int, variadic bool, fn ForeignFunction) *ForeignClosure
func (*ForeignClosure) AcceptsArity ¶ added in v1.5.0
func (p *ForeignClosure) AcceptsArity(n int) bool
AcceptsArity reports whether this closure can be called with n arguments.
func (*ForeignClosure) Doc ¶ added in v1.10.3
func (p *ForeignClosure) Doc() string
func (*ForeignClosure) Env ¶ added in v1.5.0
func (p *ForeignClosure) Env() *environment.EnvironmentFrame
func (*ForeignClosure) EqualTo ¶ added in v1.5.0
func (p *ForeignClosure) EqualTo(o values.Value) bool
EqualTo uses identity semantics — two foreign closures are equal only if they are the same pointer.
func (*ForeignClosure) Fn ¶ added in v1.5.0
func (p *ForeignClosure) Fn() ForeignFunction
func (*ForeignClosure) IsVariadic ¶ added in v1.5.0
func (p *ForeignClosure) IsVariadic() bool
func (*ForeignClosure) IsVoid ¶ added in v1.5.0
func (p *ForeignClosure) IsVoid() bool
func (*ForeignClosure) Name ¶ added in v1.5.0
func (p *ForeignClosure) Name() string
func (*ForeignClosure) ParameterCount ¶ added in v1.5.0
func (p *ForeignClosure) ParameterCount() int
func (*ForeignClosure) SchemeString ¶ added in v1.5.0
func (p *ForeignClosure) SchemeString() string
func (*ForeignClosure) SetDoc ¶ added in v1.10.3
func (p *ForeignClosure) SetDoc(doc string)
func (*ForeignClosure) SetName ¶ added in v1.5.0
func (p *ForeignClosure) SetName(name string)
func (*ForeignClosure) SetValidator ¶ added in v1.10.3
func (p *ForeignClosure) SetValidator(v ForeignFunction)
SetValidator installs a contract validation function that runs before the implementation. Called during registration when contract enforcement is enabled.
func (*ForeignClosure) Validator ¶ added in v1.10.3
func (p *ForeignClosure) Validator() ForeignFunction
Validator returns the installed contract validator, or nil if none.
type ForeignFunction ¶
type ForeignFunction func(mc CallContext) error
ForeignFunction is the signature for Go-implemented Scheme primitives. The CallContext provides access to arguments, the value register, and the cancellation context (via mc.Context()).
Most implementations only need CallContext methods (Arg, SetValue, SetValues, Authorizer, Context, EnvironmentFrame, Thread). Implementations that need full VM access (sub-context creation, continuation manipulation) should type-assert to *MachineContext.
type FreeIdResolution ¶
type FreeIdResolution struct {
Global *environment.GlobalIndex
LocalScopes []*syntax.Scope
HasLocalBinding bool
LibScope *syntax.Scope
}
FreeIdResolution records how a free identifier in a syntax-rules template was bound at macro definition time. The match package uses this during template expansion to preserve hygiene.
Implements localScopesProvider, globalBindingProvider, hasLocalBindingProvider, and libraryScopeProvider from the match package.
func (*FreeIdResolution) GetGlobal ¶
func (p *FreeIdResolution) GetGlobal() *environment.GlobalIndex
GetGlobal implements the globalBindingProvider interface.
func (*FreeIdResolution) GetHasLocalBinding ¶
func (p *FreeIdResolution) GetHasLocalBinding() bool
GetHasLocalBinding implements the hasLocalBindingProvider interface.
func (*FreeIdResolution) GetLibraryScope ¶ added in v1.6.0
func (p *FreeIdResolution) GetLibraryScope() *syntax.Scope
GetLibraryScope implements the libraryScopeProvider interface.
func (*FreeIdResolution) GetLocalScopes ¶
func (p *FreeIdResolution) GetLocalScopes() []*syntax.Scope
GetLocalScopes implements the localScopesProvider interface.
type FreeList ¶ added in v1.9.1
type FreeList[T any] struct { // contains filtered or unexported fields }
FreeList[T] is a type-safe, observable object pool backed by a mutex-guarded slice instead of sync.Pool. Unlike sync.Pool, the freelist is NOT cleared by the garbage collector, so recycled objects (and any capacity they retain) persist across GC cycles.
Use FreeList when the GC feedback loop makes sync.Pool ineffective: high allocation rates trigger frequent GC, which clears sync.Pool, causing more allocations. FreeList breaks this loop at the cost of no automatic shrinkage.
func NewFreeList ¶ added in v1.9.1
NewFreeList creates a FreeList[T] with the given name, constructor, and reset function. The freelist starts enabled.
func (*FreeList[T]) Acquire ¶ added in v1.9.1
func (p *FreeList[T]) Acquire() *T
Acquire returns a recycled object from the freelist. If the freelist is empty or disabled, it calls newFn to allocate a new object.
func (*FreeList[T]) Drain ¶ added in v1.9.1
func (p *FreeList[T]) Drain()
Drain clears all cached objects from the freelist.
func (*FreeList[T]) Release ¶ added in v1.9.1
func (p *FreeList[T]) Release(v *T)
Release resets the object and appends it to the freelist. If disabled, the object is discarded after reset.
func (*FreeList[T]) SetEnabled ¶ added in v1.9.1
SetEnabled toggles the freelist on or off. When disabled, Acquire calls newFn directly and Release discards after reset.
func (*FreeList[T]) Stats ¶ added in v1.9.1
func (p *FreeList[T]) Stats() PoolSnapshot
Stats returns a point-in-time snapshot of the freelist's counters.
type InlinedOperation ¶ added in v1.4.0
type InlinedOperation interface {
Operation
Apply(mc *MachineContext) (*MachineContext, error)
}
InlinedOperation is the interface for operations dispatched through the side table via OpComplex. These operations carry their own Apply method because the Run() loop delegates to them rather than inlining the logic.
type Instruction ¶ added in v1.4.0
Instruction is a single VM instruction for the switch-dispatch loop. Op selects the operation; Arg carries an immediate operand whose meaning depends on Op:
- Zero-operand ops (Push, Pop, ...): Arg is unused (0).
- Single-operand ops (Branch, LoadLiteral, ...): Arg is the offset, index, or depth.
- Two-operand ops (LoadLocal, StoreLocal): Arg is bit-packed (slot in low 16, depth in high 16).
- OpComplex: Arg is the index into the template's sideTable.
Size: 8 bytes (uint16 Op + 2 bytes padding + int32 Arg).
func (Instruction) String ¶ added in v1.4.0
func (instr Instruction) String() string
String returns a human-readable representation of the instruction.
type LiteralIndex ¶
type LiteralIndex int
type MachineClosure ¶
type MachineClosure struct {
// contains filtered or unexported fields
}
Linked closure (Church 1936, Landin 1964, Cardelli 1983). A closure is a pair of compiled code and the lexical environment at definition time.
closure = ⟨λ, E⟩, where: λ = template — compiled bytecode (NativeTemplate) E = env — pointer to enclosing EnvironmentFrame Access cost: O(1) creation (capture pointer), O(depth) free variable lookup (traverse parent chain). Flat closures invert this trade-off. Invariant: E is a live pointer into the frame chain, not a copy. Mutations via set! are visible through the closure because the closure shares the frame, not a snapshot. Constrains: OperationMakeClosure (must link E to runtime parent), Apply (always copies E to prevent aliasing and thread races). Constrained by: de Bruijn addressing (free vars addressed by slot,depth in E's chain), CESK model (E is the environment component).
See BIBLIOGRAPHY.md "Linked Closure Representation".
func NewClosureWithTemplate ¶
func NewClosureWithTemplate(tpl *NativeTemplate, env *environment.EnvironmentFrame) *MachineClosure
func NewVMForeignClosure ¶ added in v1.5.0
func NewVMForeignClosure(env *environment.EnvironmentFrame, pcnt int, variadic bool, fn ForeignFunction) *MachineClosure
NewVMForeignClosure creates a *MachineClosure backed by a ForeignFunction via a bytecode template (OpForeignFunctionCall + OpRestoreContinuation). Use this instead of NewForeignClosure for foreign functions that do nested VM execution (sub-context + Run), where the iterative VM loop prevents Go stack growth that applyForeign would cause.
func (*MachineClosure) AcceptsArity ¶ added in v1.5.0
func (p *MachineClosure) AcceptsArity(n int) bool
AcceptsArity reports whether this closure can be called with n arguments. Fixed-arity closures require exactly paramCount args; variadic closures require at least paramCount-1 (the rest parameter collects the remainder).
func (*MachineClosure) Copy ¶
func (p *MachineClosure) Copy() *MachineClosure
func (*MachineClosure) Doc ¶ added in v1.10.7
func (p *MachineClosure) Doc() string
Doc returns the closure's documentation string from its compiled template.
func (*MachineClosure) Env ¶ added in v1.5.0
func (p *MachineClosure) Env() *environment.EnvironmentFrame
Env returns the closure's captured environment.
func (*MachineClosure) IsVoid ¶
func (p *MachineClosure) IsVoid() bool
func (*MachineClosure) Name ¶ added in v1.10.7
func (p *MachineClosure) Name() string
Name returns the closure's name from its compiled template.
func (*MachineClosure) SchemeString ¶
func (p *MachineClosure) SchemeString() string
func (*MachineClosure) Template ¶
func (p *MachineClosure) Template() *NativeTemplate
type MachineContext ¶
type MachineContext struct {
// contains filtered or unexported fields
}
MachineContext represents the execution context of a virtual machine. It holds the current environment, values, evaluation stack, continuation, and program counter. It is created from a MachineContinuation and can be modified during execution.
func AcquireTopLevelContext ¶ added in v1.5.0
func AcquireTopLevelContext(ctx context.Context, tpl *NativeTemplate, env *environment.EnvironmentFrame) *MachineContext
AcquireTopLevelContext returns a pooled MachineContext initialized for top-level execution (no parent continuation). This eliminates the intermediate MachineContinuation allocation that NewMachineContinuation + NewMachineContext would otherwise perform when parent is nil.
The caller MUST call ReleaseTopLevelContext after Run returns.
func NewMachineContext ¶
func NewMachineContext(ctx context.Context, cont *MachineContinuation) *MachineContext
NewMachineContext creates a new machine context with the given context and continuation. The context enables cancellation/timeout support in the VM loop. For callers that don't need cancellation, pass context.Background().
func NewMachineContextFromMachineClosure ¶
func NewMachineContextFromMachineClosure(ctx context.Context, cls *MachineClosure) *MachineContext
func NewThreadSubContext ¶ added in v1.3.0
func NewThreadSubContext(params SubContextParams, thread *values.Thread) *MachineContext
NewThreadSubContext creates a sub-context for a thread using previously captured parent state. Unlike NewSubContext, this doesn't access the parent MachineContext fields, making it safe to call from a different goroutine. The thread parameter should be the new thread object, which provides the thread identity for the new context.
This function is specifically designed for SRFI-18 thread creation. For other uses of sub-contexts (like map, for-each, dynamic-wind), use NewSubContext instead.
func (*MachineContext) Apply ¶
func (p *MachineContext) Apply(mcls *MachineClosure, vs ...values.Value) (*MachineContext, error)
func (*MachineContext) ApplyCallable ¶ added in v1.2.0
func (p *MachineContext) ApplyCallable(callable values.Value, args ...values.Value) (*MachineContext, error)
ApplyCallable dispatches a procedure call to the appropriate handler based on the callee's concrete type. This is the unified entry point for all Scheme procedure application, symmetric with OperationApply.
Supported callable types:
- *MachineClosure: standard Scheme lambda
- *ForeignClosure: Go foreign function (direct call, no bytecode)
- *CaseLambdaClosure: R7RS case-lambda (§4.2.9)
- *Parameter: R7RS parameter object (§4.2.6)
- *ComposableContinuation: delimited continuation
Precondition: p.ctx must be set (always true for contexts created via NewMachineContext or NewSubContext).
func (*MachineContext) ApplyCaseLambda ¶
func (p *MachineContext) ApplyCaseLambda(clcls *CaseLambdaClosure, vs ...values.Value) (*MachineContext, error)
ApplyCaseLambda applies a case-lambda closure by finding the matching clause.
func (*MachineContext) Authorizer ¶ added in v1.7.0
func (p *MachineContext) Authorizer() security.Authorizer
Authorizer returns the security authorizer from this context's namespace, or nil if none is set.
func (*MachineContext) BarrierValid ¶ added in v1.4.0
func (p *MachineContext) BarrierValid() *BarrierToken
BarrierValid returns the barrier validity flag for the current context. Non-nil means execution is inside a with-continuation-barrier; the pointer identity distinguishes which barrier. Nil means no active barrier.
Escape closures and composable continuations use this to detect barrier crossings: if the capture-time pointer differs from the invocation-time pointer, the continuation would cross a barrier boundary.
func (*MachineContext) CallDepth ¶
func (p *MachineContext) CallDepth() int
CallDepth returns the depth of the current continuation stack.
func (*MachineContext) CaptureStackTrace ¶
func (p *MachineContext) CaptureStackTrace(maxDepth int) StackTrace
CaptureStackTrace walks the continuation chain and builds a stack trace.
func (*MachineContext) CaptureSubContextParams ¶ added in v1.3.0
func (p *MachineContext) CaptureSubContextParams() SubContextParams
CaptureSubContextParams extracts the state needed to create a sub-context in a different goroutine. This is used by thread creation to avoid race conditions when accessing the parent MachineContext from a child goroutine (T4 from architectural review).
Call this in the parent goroutine before creating the child goroutine, then pass the result to NewThreadSubContext in the child goroutine.
func (*MachineContext) CollectContinuationMarks ¶ added in v1.7.0
func (p *MachineContext) CollectContinuationMarks(tag *PromptTag) *ContinuationMarkSet
CollectContinuationMarks walks the continuation chain and builds a ContinuationMarkSet snapshot. Collects marks from the current frame and all continuation frames up to and including the nearest frame with a matching promptTag.
func (*MachineContext) Context ¶
func (p *MachineContext) Context() context.Context
Context returns the context for this machine context.
func (*MachineContext) Counters ¶ added in v1.1.0
func (p *MachineContext) Counters() VMCounters
Counters returns a snapshot of the performance counters for this context.
func (*MachineContext) CurrentContinuation ¶
func (p *MachineContext) CurrentContinuation() *MachineContinuation
func (*MachineContext) CurrentLocation ¶ added in v1.13.14
func (p *MachineContext) CurrentLocation() *values.DebugLocation
CurrentLocation returns the current source location as a values.DebugLocation, or nil if no source info is available. Implements values.DebugState.
func (*MachineContext) CurrentSource ¶
func (p *MachineContext) CurrentSource() *syntax.SourceContext
CurrentSource returns the source location for the current execution point. When the current template has no source (e.g., inside a foreign function), walks up the continuation chain to find the nearest call site with source info. Continuation PCs are return addresses (one past the call), so pc-1 gives the call site.
func (*MachineContext) Debugger ¶
func (p *MachineContext) Debugger() *Debugger
Debugger returns the attached debugger, or nil if none.
func (*MachineContext) DeleteMark ¶ added in v1.7.0
func (p *MachineContext) DeleteMark(key values.Value)
DeleteMark removes the continuation mark for key from the current frame. Nils the slice when empty to maintain the "nil = zero-cost" invariant. Uses eq? semantics for key comparison. Deletion uses swap-with-last for O(1) removal; insertion order is not preserved.
func (*MachineContext) EnvironmentFrame ¶
func (p *MachineContext) EnvironmentFrame() *environment.EnvironmentFrame
func (*MachineContext) Error ¶
func (p *MachineContext) Error(msg string) *SchemeError
Error creates a SchemeError with the current source location and stack trace.
func (*MachineContext) EscapeCont ¶
func (p *MachineContext) EscapeCont() *MachineContinuation
EscapeCont returns the escape continuation for this context. This is set by foreign functions (like dynamic-wind) that need call/cc inside their sub-contexts to know where to continue after completion.
func (*MachineContext) Evals ¶ added in v1.10.5
func (p *MachineContext) Evals() *Stack
Evals returns the eval stack for inspection (primarily for testing).
func (*MachineContext) ExceptionHandler ¶
func (p *MachineContext) ExceptionHandler() *ExceptionHandler
ExceptionHandler returns the current exception handler chain.
func (*MachineContext) ExpanderContext ¶
func (p *MachineContext) ExpanderContext() ExpanderCtx
ExpanderContext returns the expander context, or nil if not in expansion context.
func (*MachineContext) FindPrompt ¶
func (p *MachineContext) FindPrompt(tag *PromptTag) (*MachineContinuation, bool)
FindPrompt walks the continuation chain to find the nearest frame with a matching prompt tag. Also checks the context's own prompt tag (set by call-with-continuation-prompt on sub-contexts). Returns the matching frame and true, or nil and false.
When the prompt is on the context itself (not a continuation frame), returns nil and true — the caller should treat this as "prompt at the boundary of this sub-context" and slice the entire continuation chain.
func (*MachineContext) FormatStackTrace ¶ added in v1.13.14
func (p *MachineContext) FormatStackTrace(maxDepth int) string
FormatStackTrace returns a human-readable stack trace string. Implements values.DebugState.
func (*MachineContext) GetImmediateMark ¶ added in v1.7.0
func (p *MachineContext) GetImmediateMark(key values.Value) values.Value
GetImmediateMark returns the nearest mark for key, checking the current frame first, then the immediately saved continuation frame.
This is the correct lookup for call-with-immediate-continuation-mark: in tail position, with-continuation-mark sets the mark on the live frame (mc.marks); in non-tail position, SaveContinuation moves mc.marks to mc.cont and nils the live frame. Both cases are handled here.
func (*MachineContext) GetMark ¶ added in v1.7.0
func (p *MachineContext) GetMark(key values.Value) values.Value
GetMark returns the continuation mark for key on the current frame, or nil if no mark is set. Uses eq? semantics for key comparison. Invariant: nil is used exclusively as the "not found" sentinel. Mark values are always non-nil Scheme values (GetValue never returns nil); SetMark must never be called with a nil val, as nil would be indistinguishable from absent.
func (*MachineContext) GetValue ¶
func (p *MachineContext) GetValue() values.Value
GetValue returns the first (or only) value from the value register. Returns Void if the register is empty.
func (*MachineContext) GetValues ¶
func (p *MachineContext) GetValues() MultipleValues
GetValues returns all values from the value register as a MultipleValues slice. For the single-value case this allocates a one-element slice; callers on the hot path should use GetValue instead.
func (*MachineContext) MaxCallDepth ¶ added in v1.3.0
func (p *MachineContext) MaxCallDepth() uint64
MaxCallDepth returns the maximum call depth limit. 0 means unlimited.
func (*MachineContext) MaxStackSize ¶ added in v1.13.14
func (p *MachineContext) MaxStackSize() uint64
MaxStackSize returns the maximum eval stack size limit. 0 means unlimited.
func (*MachineContext) NewSubContext ¶
func (p *MachineContext) NewSubContext() *MachineContext
NewSubContext creates a new MachineContext for running sub-calls (e.g., apply, map, for-each). The sub-context shares the global environment but has a fresh call stack, eval stack, and value register. This allows foreign functions to call Scheme closures without corrupting the parent context's state.
The parent's dynamic-wind winding stack is inherited automatically so that continuations captured inside the sub-context preserve the enclosing dynamic-wind context. For the rare sites that need a different stack (unwind truncation, exception cleanup), use NewSubContextWithWinding.
Note: Sub-contexts have isolated continuation chains (cont = nil). When call/cc captures a continuation inside a sub-context, it captures mc.Parent() which refers to the sub-context's chain (nil). For continuations to escape back to the outer context, the escape error propagates up through the call stack and is handled by RunWithEscapeHandling at the top level.
The parentMC field tracks the parent context, allowing call/cc to find an outer continuation for proper R7RS continuation semantics when captured inside sub-contexts.
The escapeCont field is inherited, allowing nested sub-contexts to know where execution should continue after their completion (set by dynamic-wind and similar constructs).
func (*MachineContext) NewSubContextWithTemplate ¶ added in v1.13.14
func (p *MachineContext) NewSubContextWithTemplate( tpl *NativeTemplate, env *environment.EnvironmentFrame, ) *MachineContext
NewSubContextWithTemplate creates a sub-context configured to execute the given template in the given environment. This is the correct way for primitives like eval and load to create execution contexts — it propagates all parent fields automatically via NewSubContext, preventing the "forgotten field" bug class that NewMachineContext + manual setters is vulnerable to.
The template and env override NewSubContext's defaults (nil template, parent's TopLevel env). pc starts at 0 (pool zero-value).
func (*MachineContext) NewSubContextWithWinding ¶ added in v1.10.5
func (p *MachineContext) NewSubContextWithWinding(windingStack WindingStack) *MachineContext
NewSubContextWithWinding creates a sub-context with an explicit winding stack instead of inheriting the parent's. Use this only when the sub-context must run with a winding stack that differs from the parent — for example, a truncated stack during unwind (machine_context_winding.go) or exception cleanup (prim_exceptions.go). All other sub-context creation should use NewSubContext.
func (*MachineContext) PC ¶
func (p *MachineContext) PC() int
func (*MachineContext) Parent ¶
func (p *MachineContext) Parent() *MachineContinuation
func (*MachineContext) ParentMC ¶
func (p *MachineContext) ParentMC() *MachineContext
ParentMC returns the parent machine context (for sub-contexts), or nil for top-level contexts.
func (*MachineContext) PopContinuation ¶
func (p *MachineContext) PopContinuation() (*MachineContinuation, error)
PopContinuation pops the current continuation from the machine context and returns it. It restores the machine context to the state saved in the popped continuation. Returns ErrContinuationUnderflow if callDepth would go below zero (compiler bug).
Note: Unlike Restore(), we do NOT copy evals here because PopContinuation is used for normal function return where the continuation is consumed once. Restore() is used for continuation re-entry (call/cc) where the same continuation may be invoked multiple times, requiring the copy to prevent stack corruption.
func (*MachineContext) PopExceptionHandler ¶
func (p *MachineContext) PopExceptionHandler() *ExceptionHandler
PopExceptionHandler pops the current exception handler from the stack and returns it. Returns nil if no handler is installed.
func (*MachineContext) PopWindingFrame ¶
func (p *MachineContext) PopWindingFrame() *DynamicWindFrame
PopWindingFrame removes the innermost frame from the winding stack.
func (*MachineContext) PromptTag ¶
func (p *MachineContext) PromptTag() *PromptTag
PromptTag returns the prompt tag for this context, or nil.
func (*MachineContext) PushExceptionHandler ¶
func (p *MachineContext) PushExceptionHandler(handler values.Callable)
PushExceptionHandler pushes a new exception handler onto the handler stack.
func (*MachineContext) PushWindingFrame ¶
func (p *MachineContext) PushWindingFrame(frame *DynamicWindFrame)
PushWindingFrame adds a frame to the winding stack.
func (*MachineContext) ResolveParameterValue ¶ added in v1.7.0
func (p *MachineContext) ResolveParameterValue(param *Parameter) values.Value
ResolveParameterValue returns the effective value of a parameter, checking continuation marks (from parameterize) before falling back to the base value. This is the Go-side equivalent of calling the parameter with 0 args.
func (*MachineContext) Restore ¶
func (p *MachineContext) Restore(cont *MachineContinuation)
func (*MachineContext) RestoreAndRelease ¶ added in v1.4.0
func (p *MachineContext) RestoreAndRelease(cont *MachineContinuation)
RestoreAndRelease is the fast path for normal function return. It transfers the continuation's state into the MachineContext (like Restore) but avoids copying evals — instead it transfers ownership directly and pools the consumed frame. This is safe because normal return consumes the frame exactly once; call/cc and escape paths must use Restore (which copies).
Shared frames (marked by MarkChainShared during call/cc capture) cannot be pooled because a captured continuation may re-invoke them. For shared frames, evals are copied (like Restore) and the frame is left for GC instead of pooling.
The sequence for unshared frames:
- Release mc's current evals to the stack pool (it's dead after restore)
- Transfer cont's evals directly to mc (no copy)
- Nil cont.evals so releaseContinuation won't double-release it
- Pool the consumed continuation frame
func (*MachineContext) RestoreWithWinding ¶
func (p *MachineContext) RestoreWithWinding(cont *MachineContinuation, targetStack WindingStack) error
RestoreWithWinding restores a continuation with proper dynamic-wind handling. It unwinds from the current dynamic extent, rewinds to the target extent, then restores the machine state.
If cont is nil (continuation captured in a sub-context), we still perform the winding operations but don't restore machine state - the caller should handle continued execution appropriately.
func (*MachineContext) RestoreWithWindingFrom ¶
func (p *MachineContext) RestoreWithWindingFrom(cont *MachineContinuation, sourceStack, targetStack WindingStack) error
RestoreWithWindingFrom restores a continuation with proper dynamic-wind handling, using an explicit source winding stack instead of the current context's stack.
This is needed when the escape originated from a sub-context that has a different winding stack than the context where RestoreWithWinding is called. For example, when call/cc captures inside a sub-context and the escape propagates up, the source winding stack (where the escape happened) may have frames that the top-level context doesn't know about.
Parameters:
- cont: The continuation to restore to
- sourceStack: The winding stack where the escape originated (for unwinding)
- targetStack: The winding stack to restore to (for rewinding)
func (*MachineContext) RewindTo ¶
func (p *MachineContext) RewindTo(target WindingStack, commonDepth int) error
RewindTo runs before thunks from common ancestor to target depth. Returns error if any before thunk fails.
func (*MachineContext) Run ¶
func (p *MachineContext) Run() error
Run executes the VM loop starting from the current pc. The pc is NOT reset here - callers are responsible for ensuring the correct initial pc:
- NewMachineContext copies pc from the continuation (typically 0 for fresh execution)
- Apply sets pc = 0 for fresh closure invocation
- Restore sets pc from the saved continuation for resumption
This design allows continuation resumption (e.g., raise-continuable) to work correctly by preserving the pc set by Restore rather than unconditionally resetting to 0.
Dispatch: Run always uses switch-dispatch over integer opcodes.
Context cancellation: The loop checks p.ctx.Done() every 1024 ops, allowing preemption via context.WithTimeout or context.WithCancel. This enables:
- Test timeouts that actually stop execution
- REPL interrupt support (Ctrl+C)
- Resource management for long-running computations
Run executes the VM loop using switch-dispatch with integer opcodes. Hot-path operations (Wave 1-3) are inlined as switch cases; complex operations (closures, macros, FFI) are dispatched via OpComplex to the template's sideTable.
Set the context via SetContext() before calling Run().
func (*MachineContext) RunWithEscapeHandling ¶
func (p *MachineContext) RunWithEscapeHandling() error
RunWithEscapeHandling runs the VM loop, handling continuation escapes that weren't caught by an enclosing call/cc. This is used at the top level (REPL and file execution) to catch continuations invoked outside their original dynamic extent.
When a continuation captured inside a foreign function (like dynamic-wind's thunk) is invoked from outside, the escape error propagates up. This method catches it and restores the continuation with proper dynamic-wind handling.
For continuations captured inside sub-contexts (like dynamic-wind thunks):
- Continuation: the inner state (inside the thunk)
- EscapeCont: the outer continuation (after the original sub-context would have completed)
After the inner execution completes and unwinds, if there's a pending escape continuation, execution continues from there.
When execution completes normally (Run returns nil), any remaining frames on the winding stack are unwound (after thunks are called).
func (*MachineContext) SaveContinuation ¶
func (p *MachineContext) SaveContinuation(off int) error
SaveContinuation pushes a new continuation onto the machine context with the given offset to the current program counter. Returns ErrCallDepthExceeded if the call depth limit has been reached.
Note: callDepth is incremented BEFORE calling NewMachineContinuationFromMachineContext. The continuation's own callDepth is derived from mc.cont (the parent pointer), not from mc.callDepth, so this pre-increment does not affect the continuation's cached depth. See the comment on NewMachineContinuationFromMachineContext for why this matters.
func (*MachineContext) SetBarrierValid ¶ added in v1.4.0
func (p *MachineContext) SetBarrierValid(v *BarrierToken)
SetBarrierValid sets the barrier identity token on this context. Called by PrimCallWithContinuationBarrier to mark the sub-context as inside a barrier.
func (*MachineContext) SetContext ¶
func (p *MachineContext) SetContext(ctx context.Context)
SetContext sets the context for this machine context. This should be called before Run() to enable context cancellation/timeout.
func (*MachineContext) SetDebugger ¶
func (p *MachineContext) SetDebugger(d *Debugger)
SetDebugger attaches a debugger to this context.
func (*MachineContext) SetEscapeCont ¶
func (p *MachineContext) SetEscapeCont(cont *MachineContinuation)
SetEscapeCont sets the escape continuation for this context.
func (*MachineContext) SetExceptionHandler ¶
func (p *MachineContext) SetExceptionHandler(h *ExceptionHandler)
SetExceptionHandler sets the exception handler chain.
func (*MachineContext) SetExpanderContext ¶
func (p *MachineContext) SetExpanderContext(ctx ExpanderCtx)
SetExpanderContext sets the expander context for this machine context. This is called when invoking macro transformers to enable syntax-local-* primitives.
func (*MachineContext) SetMark ¶ added in v1.7.0
func (p *MachineContext) SetMark(key, val values.Value)
SetMark sets a continuation mark on the current frame using eq? semantics. Updates an existing entry with the same key, or appends a new one.
func (*MachineContext) SetMaxCallDepth ¶ added in v1.3.0
func (p *MachineContext) SetMaxCallDepth(n uint64)
SetMaxCallDepth sets the maximum call depth limit. 0 means unlimited.
func (*MachineContext) SetMaxStackSize ¶ added in v1.13.14
func (p *MachineContext) SetMaxStackSize(n uint64)
SetMaxStackSize sets the maximum eval stack size limit. 0 means unlimited.
func (*MachineContext) SetPC ¶
func (p *MachineContext) SetPC(v int)
SetPC sets the program counter. Used by PrimCallCC for inline lambda execution.
func (*MachineContext) SetPromptTag ¶
func (p *MachineContext) SetPromptTag(tag *PromptTag)
SetPromptTag sets the prompt tag on this context. Used by call-with-continuation-prompt to mark sub-contexts as prompt boundaries.
func (*MachineContext) SetThread ¶ added in v1.1.0
func (p *MachineContext) SetThread(t *values.Thread)
SetThread sets the SRFI-18 thread identity on this context. Both the thread object and its ID are stored for efficient comparison.
func (*MachineContext) SetValue ¶
func (p *MachineContext) SetValue(v values.Value)
SetValue stores a single value in the value register without allocating. This is the hot path: every LoadLocal, LoadGlobal, LoadLiteral, Pull, Pop, MakeClosure, etc. goes through here.
func (*MachineContext) SetValues ¶
func (p *MachineContext) SetValues(vs ...values.Value)
SetValues sets the value register. For a single value this uses the zero-allocation fast path (singleValue); for multiple values it falls back to the multiValues slice.
func (*MachineContext) SetWindingStack ¶
func (p *MachineContext) SetWindingStack(stack WindingStack)
SetWindingStack sets the winding stack. Used by tests; production code should prefer NewSubContextWithWinding for override sites.
func (*MachineContext) SliceContinuationAt ¶
func (p *MachineContext) SliceContinuationAt(prompt *MachineContinuation) *MachineContinuation
SliceContinuationAt deep-copies the continuation chain segment from p.cont down to (but not including) the prompt frame. The returned chain's bottom frame has parent = nil, making it a standalone segment suitable for composable continuation capture.
func (*MachineContext) Template ¶
func (p *MachineContext) Template() *NativeTemplate
func (*MachineContext) Thread ¶ added in v1.1.0
func (p *MachineContext) Thread() *values.Thread
Thread returns the SRFI-18 thread object for this context, or nil for the primordial thread.
func (*MachineContext) ThreadID ¶ added in v1.1.0
func (p *MachineContext) ThreadID() uint64
ThreadID returns the SRFI-18 thread ID for this context. 0 means the primordial thread (main goroutine).
func (*MachineContext) UnwindTo ¶
func (p *MachineContext) UnwindTo(commonDepth int) error
UnwindTo runs after thunks from innermost to the common ancestor. Returns error if any after thunk fails.
func (*MachineContext) WindingStack ¶
func (p *MachineContext) WindingStack() WindingStack
WindingStack returns the current winding stack.
func (*MachineContext) WrapError ¶
func (p *MachineContext) WrapError(err error, msg string) *SchemeError
WrapError wraps an existing error with the current source location and stack trace.
type MachineContinuation ¶
type MachineContinuation struct {
// contains filtered or unexported fields
}
func NewMachineContinuation ¶
func NewMachineContinuation(parent *MachineContinuation, tpl *NativeTemplate, env *environment.EnvironmentFrame) *MachineContinuation
NewMachineContinuation creates a new machine continuation with the given parent, template, environment frame, and initial values.
func NewMachineContinuationFromMachineContext ¶
func NewMachineContinuationFromMachineContext(mc *MachineContext, off int) *MachineContinuation
NewMachineContinuationFromMachineContext creates a new machine continuation from the given machine context and an offset to the program counter. The new continuation inherits the environment, template, and evaluation stack from the machine context.
callDepth derivation: the new frame's parent is mc.cont, so its depth is derived from mc.cont's cached depth — NOT from mc.callDepth. These values differ because SaveContinuation pre-increments mc.callDepth before calling this function, but other callers do not:
- SaveContinuation: mc.callDepth already incremented → mc.callDepth != chain length
- PrimCallCC sub-context path (prim_control.go): mc.callDepth == 0, mc.cont == nil
- PrimDynamicWind escape cont (prim_control.go): mc.callDepth == chain length
Using mc.callDepth - 1 would underflow to -1 in the PrimCallCC case (mc.callDepth == 0). The parent-pointer formula is correct for all callers and immune to underflow.
func NewMachineContinuationWithPrompt ¶
func NewMachineContinuationWithPrompt(parent *MachineContinuation, tpl *NativeTemplate, env *environment.EnvironmentFrame, tag *PromptTag, handler Closure) *MachineContinuation
NewMachineContinuationWithPrompt creates a continuation frame that acts as a continuation prompt. The tag identifies the prompt for abort/capture, and the handler is invoked when an abort reaches this prompt.
func (*MachineContinuation) CallDepth ¶
func (p *MachineContinuation) CallDepth() int
CallDepth returns the depth of the continuation stack. The depth is cached in each frame at creation time, so this is O(1).
func (*MachineContinuation) Copy ¶
func (p *MachineContinuation) Copy() *MachineContinuation
func (*MachineContinuation) DeepCopy ¶
func (p *MachineContinuation) DeepCopy() *MachineContinuation
DeepCopy creates a deep copy of the entire continuation chain. Each frame in the chain is copied, with parent pointers updated to point to the copied frames. This is needed for composable continuations which must be safely re-invoked multiple times.
func (*MachineContinuation) EnvironmentFrame ¶
func (p *MachineContinuation) EnvironmentFrame() *environment.EnvironmentFrame
func (*MachineContinuation) IsVoid ¶
func (p *MachineContinuation) IsVoid() bool
func (*MachineContinuation) MarkChainShared ¶ added in v1.4.0
func (p *MachineContinuation) MarkChainShared()
MarkChainShared marks every frame in the continuation chain as shared. Shared frames are not pooled by RestoreAndRelease — their evals are copied instead of transferred, preserving them for re-invocation.
Early-exits when a frame is already shared: all ancestors must already be shared from a prior capture (sharing propagates toward the root).
func (*MachineContinuation) PC ¶
func (p *MachineContinuation) PC() int
func (*MachineContinuation) Parent ¶
func (p *MachineContinuation) Parent() *MachineContinuation
func (*MachineContinuation) PromptHandler ¶
func (p *MachineContinuation) PromptHandler() Closure
func (*MachineContinuation) PromptTag ¶
func (p *MachineContinuation) PromptTag() *PromptTag
func (*MachineContinuation) PushValues ¶
func (p *MachineContinuation) PushValues(v ...values.Value)
PushValues appends values to the continuation's value register. If the register currently holds a single value, it is promoted to the multi-value representation before appending. This promote-then-append pattern avoids losing the existing single value when transitioning to the multi-value path.
func (*MachineContinuation) SchemeString ¶
func (p *MachineContinuation) SchemeString() string
func (*MachineContinuation) SetPC ¶
func (p *MachineContinuation) SetPC(v int)
func (*MachineContinuation) SetPromptHandler ¶
func (p *MachineContinuation) SetPromptHandler(h Closure)
func (*MachineContinuation) SetPromptTag ¶
func (p *MachineContinuation) SetPromptTag(t *PromptTag)
func (*MachineContinuation) Template ¶
func (p *MachineContinuation) Template() *NativeTemplate
func (*MachineContinuation) ThreadID ¶ added in v1.1.0
func (p *MachineContinuation) ThreadID() uint64
type MacroEvaluator ¶ added in v1.10.5
type MacroEvaluator interface {
// EvalTemplate evaluates a compiled template in the given environment
// and returns the resulting value. Used by compileAndEvalLambdaTransformer
// for define-syntax lambda transformers at compile time.
EvalTemplate(ctx context.Context, tpl *NativeTemplate, env *environment.EnvironmentFrame) (values.Value, error)
// InvokeTransformer calls a closure as a macro transformer.
// expanderCtx is set on the VM context for auxiliary syntax
// hygiene (R7RS Section 4.3.2); nil is valid when no hygiene context
// is needed (e.g. ExpandOnce). args are passed to Apply — one arg for
// syntax-rules/lambda transformers, three for ER macros (form, rename,
// compare). On success, the caller receives the MachineContext with the
// result in the value register and must call ReleaseSubContext when done.
InvokeTransformer(ctx context.Context, cls Closure, expanderCtx ExpanderCtx, args ...values.Value) (*MachineContext, error)
}
MacroEvaluator abstracts VM execution for the compiler and expander so that compile-time evaluation and transformer invocation can be tested and wired without depending on the concrete MachineContext construction path.
func NewVMMacroEvaluator ¶ added in v1.10.5
func NewVMMacroEvaluator() MacroEvaluator
NewVMMacroEvaluator returns a MacroEvaluator backed by the real VM.
type MultipleValues ¶
MultipleValues represents multiple return values from a function.
func NewMultipleValues ¶
func NewMultipleValues(values ...values.Value) MultipleValues
NewMultipleValues creates a new MultipleValues from the given values.
func (MultipleValues) Copy ¶
func (p MultipleValues) Copy() MultipleValues
Copy creates a copy of the MultipleValues.
func (MultipleValues) EqualTo ¶
func (p MultipleValues) EqualTo(o values.Value) bool
EqualTo checks if the MultipleValues is equal to another value.
func (MultipleValues) IsVoid ¶
func (p MultipleValues) IsVoid() bool
IsVoid returns true if the MultipleValues represents 'void' - either
func (MultipleValues) Len ¶
func (p MultipleValues) Len() int
Len returns the number of values in the MultipleValues.
func (MultipleValues) SchemeString ¶
func (p MultipleValues) SchemeString() string
SchemeString returns the Scheme representation of the MultipleValues.
type NamedCallable ¶ added in v1.13.14
NamedCallable is implemented by callable values that carry a name and documentation string. MachineClosure, ForeignClosure, and CaseLambdaClosure all satisfy this interface.
type NativeTemplate ¶
type NativeTemplate struct {
// contains filtered or unexported fields
}
func NewEmptyNativeTemplate ¶ added in v1.2.0
func NewEmptyNativeTemplate() *NativeTemplate
NewEmptyNativeTemplate creates a new NativeTemplate with default empty parameters. This is used when a template is initialized without any known parameters or operations yet.
func NewNativeTemplate ¶
func NewNativeTemplate(pcnt int, vcnt int, vd bool, operations ...Operation) *NativeTemplate
func (*NativeTemplate) AppendCachedBinding ¶ added in v1.5.0
func (p *NativeTemplate) AppendCachedBinding(bd *environment.Binding) int32
AppendCachedBinding adds a *Binding to the cached bindings array, deduplicating by pointer identity. Returns the index for use as an OpLoadCachedBinding/OpPushCachedBinding operand.
func (*NativeTemplate) AppendInstruction ¶ added in v1.4.0
func (p *NativeTemplate) AppendInstruction(instr Instruction)
AppendInstruction appends a single instruction with no source attribution.
func (*NativeTemplate) AppendInstructionWithSource ¶ added in v1.4.0
func (p *NativeTemplate) AppendInstructionWithSource(src *syntax.SourceContext, instr Instruction)
AppendInstructionWithSource appends a single instruction to the integer-dispatch bytecode and tags it with the given source context.
func (*NativeTemplate) AppendOperations ¶
func (p *NativeTemplate) AppendOperations(ops ...Operation)
AppendOperations appends operations with no source attribution (index 0 = nil). Converts operations to instructions using AppendOperationsWithSource.
func (*NativeTemplate) AppendOperationsWithSource ¶ added in v1.4.0
func (p *NativeTemplate) AppendOperationsWithSource(src *syntax.SourceContext, ops ...Operation)
AppendOperationsWithSource converts operations to instructions and tags each with the given source. Wave 1-3 operations become direct switch cases; complex operations go through the sideTable and are dispatched via OpComplex. This is a public method for test use.
func (*NativeTemplate) AppendSideTableOp ¶ added in v1.4.0
func (p *NativeTemplate) AppendSideTableOp(op InlinedOperation) Instruction
AppendSideTableOp adds a complex operation to the side table and returns an OpComplex instruction that references it.
func (*NativeTemplate) CachedBindings ¶ added in v1.10.5
func (p *NativeTemplate) CachedBindings() []*environment.Binding
CachedBindings returns the compile-time resolved bindings array. Used by the disassembler to annotate binding references.
func (*NativeTemplate) Code ¶ added in v1.4.0
func (p *NativeTemplate) Code() []Instruction
Code returns the integer-dispatch bytecode slice.
func (*NativeTemplate) CodeLen ¶ added in v1.4.0
func (p *NativeTemplate) CodeLen() int
CodeLen returns the current code[] length (number of instructions emitted).
func (*NativeTemplate) Copy ¶
func (p *NativeTemplate) Copy() *NativeTemplate
func (*NativeTemplate) DeduplicateLiteral ¶
func (p *NativeTemplate) DeduplicateLiteral(v values.Value) values.Value
DeduplicateLiteral deduplicates the given value using the template's literal pool. For composite values (pairs and vectors), all elements are deduplicated recursively. Returns the deduplicated value.
func (*NativeTemplate) Doc ¶ added in v1.10.3
func (p *NativeTemplate) Doc() string
func (*NativeTemplate) IncrementParameterCount ¶ added in v1.10.5
func (p *NativeTemplate) IncrementParameterCount()
IncrementParameterCount adds one to the parameter count.
func (*NativeTemplate) IsVariadic ¶
func (p *NativeTemplate) IsVariadic() bool
func (*NativeTemplate) IsVoid ¶
func (p *NativeTemplate) IsVoid() bool
func (*NativeTemplate) Literals ¶ added in v1.5.0
func (p *NativeTemplate) Literals() MultipleValues
Literals returns the literals pool.
func (*NativeTemplate) MaybeAppendLiteral ¶
func (p *NativeTemplate) MaybeAppendLiteral(v values.Value) LiteralIndex
func (*NativeTemplate) Name ¶
func (p *NativeTemplate) Name() string
func (*NativeTemplate) Operations ¶
func (p *NativeTemplate) Operations() Operations
Operations reconstructs the operation sequence from the bytecode. Converts Instructions back to Operation values for compatibility with existing code that expects Operations (e.g., tests, EqualTo).
func (*NativeTemplate) Optimize ¶ added in v1.5.0
func (p *NativeTemplate) Optimize()
Optimize performs a peephole optimization pass on the template's bytecode. It removes dead instructions identified by pattern-matching rules, fixes branch offsets to account for removed instructions, and compacts the code and source reference arrays in parallel.
Superinstruction formation (Ertl & Gregg 2003). Fusing adjacent instructions reduces dispatch overhead in the Run() switch loop.
Fusions:
Load* + Push → Push* (eliminates 1 dispatch)
Pull + Apply → PullApply (eliminates 1 dispatch)
SaveCont + PushCachedBinding ... PullApply
→ CallForeignCached (eliminates ~5 dispatches)
Cost model: each fusion saves one (fetch opcode + switch branch).
In switch-dispatch interpreters, dispatch dominates execution time.
Invariant: fusions must not change observable semantics. Branch
offsets are recomputed after compaction.
Constrains: Run() must implement fused opcodes with identical
semantics to the original sequence.
Constrained by: must preserve semantic equivalence of fused
instruction sequences.
See BIBLIOGRAPHY.md "Superinstruction Formation".
After compacting its own code, Optimize recurses into any *NativeTemplate values in the literals pool (lambda closures compiled as sub-templates).
Idempotent: a second call finds nothing to remove.
func (*NativeTemplate) ParameterCount ¶
func (p *NativeTemplate) ParameterCount() int
func (*NativeTemplate) PatchInstructionArg ¶ added in v1.4.0
func (p *NativeTemplate) PatchInstructionArg(codeIdx int, arg int32)
PatchInstructionArg updates the Arg field of the instruction at code[codeIdx]. Used for patching branch offsets and continuation save offsets after the target PC is known.
func (*NativeTemplate) SchemeString ¶
func (p *NativeTemplate) SchemeString() string
func (*NativeTemplate) SetDoc ¶ added in v1.10.3
func (p *NativeTemplate) SetDoc(doc string)
func (*NativeTemplate) SetName ¶
func (p *NativeTemplate) SetName(name string)
func (*NativeTemplate) SetVariadic ¶ added in v1.10.5
func (p *NativeTemplate) SetVariadic()
SetVariadic marks this template as accepting a variadic rest argument.
func (*NativeTemplate) SideTable ¶ added in v1.4.0
func (p *NativeTemplate) SideTable() []InlinedOperation
SideTable returns the complex operations referenced by OpComplex instructions.
func (*NativeTemplate) SourceAt ¶
func (p *NativeTemplate) SourceAt(pc int) *syntax.SourceContext
SourceAt returns the source location for the operation at pc. Returns nil if pc is out of bounds or no source was recorded. O(1) lookup via the parallel sourceRefs array.
func (*NativeTemplate) ValueCount ¶
func (p *NativeTemplate) ValueCount() int
type OpCode ¶ added in v1.4.0
type OpCode uint16
OpCode is an integer opcode for the switch-dispatch VM loop. Operations migrated from interface dispatch to integer dispatch get a dedicated OpCode. Complex operations that remain as interface values use OpComplex with a side table index.
Adding a new opcode requires changes in:
- opcode.go — add OpXxx constant and entry in opcodeTable (name + metadata flags)
- machine_context.go Run() — add dispatch case in the main switch
- native_template.go — add cases in both operationToInstruction() and instructionToOperation()
- operation_xxx.go — create new operation type (or add to existing file)
- compile_*.go — add compiler method to emit the new opcode
- Relevant _test.go files
- peephole.go — if the new op participates in fusion/chaining (e.g. loadToFusedPush)
For promoted primitive ops specifically, see the guide comment at the top of call_promoted.go — promoted ops have a different (smaller) set of edit sites.
const ( OpInvalid OpCode = iota // Wave 1: zero-operand operations OpPush OpPop OpPull OpLoadVoid OpDrop OpPopEnv OpApply OpUnpackListToStack OpRestoreContinuation // Wave 2: single-operand operations (Arg = offset, index, or depth) OpBranchOnFalseValue OpBranch OpSaveContinuation OpLoadLiteral OpLoadGlobal OpStoreGlobal OpPeekK OpPushEnv // Push new env frame with Arg local slots // Wave 3: two-operand operations (Arg = bit-packed slot|depth) OpLoadLocal OpStoreLocal // Wave 4: fused push operations (Arg = same as unfused Load variant) OpPushLiteral // LoadLiteral + Push OpPushGlobal // LoadGlobal + Push OpPushLocal // LoadLocal + Push // Wave 5: fused call operations (zero-operand) OpPullApply // Pull + Apply // Wave 5: promoted complex operations (zero-operand) OpMakeClosure // MakeClosure (was OpComplex) // Wave 6: cached binding operations (Arg = index into cachedBindings) OpLoadCachedBinding // Load from compile-time resolved *Binding OpPushCachedBinding // LoadCachedBinding + Push (fused) // Wave 7: direct foreign call operations (Arg = index into cachedBindings) // Emitted by peephole only — compiler never produces these. OpCallForeignCached // Non-tail: call ForeignClosure, then mc.pc++ OpCallForeignCachedTail // Tail: call ForeignClosure, then returnImmediate() // Wave 8: general call fusion (Arg = same encoding as PushLocal/PushCachedBinding) // Fused PushLocal/PushCachedBinding + PullApply for non-foreign callables. // Emitted by peephole only — compiler never produces these. OpCallLocal // Resolve local binding, drain args, ApplyCallable OpCallCachedBinding // Resolve cached binding, drain args, ApplyCallable // Wave 9: promoted primitive operations (Arg = index into cachedBindings) // Inline the hot primitive logic directly, bypassing arity check, arg // binding, and indirect function call. Emitted by peephole only when // the cached binding holds a known promoted ForeignClosure. OpEqQ // Non-tail inlined eq? OpEqQTail // Tail inlined eq? OpVectorQ // Non-tail inlined vector? OpVectorQTail // Tail inlined vector? OpVectorRef // Non-tail inlined vector-ref OpVectorRefTail // Tail inlined vector-ref OpNullQ // Non-tail inlined null? OpNullQTail // Tail inlined null? OpPairQ // Non-tail inlined pair? OpPairQTail // Tail inlined pair? OpCar // Non-tail inlined car OpCarTail // Tail inlined car OpCdr // Non-tail inlined cdr OpCdrTail // Tail inlined cdr OpAdd // Non-tail inlined 2-arg + OpAddTail // Tail inlined 2-arg + OpSub // Non-tail inlined 2-arg - OpSubTail // Tail inlined 2-arg - OpNumLt // Non-tail inlined 2-arg < OpNumLtTail // Tail inlined 2-arg < OpNumLe // Non-tail inlined 2-arg <= OpNumLeTail // Tail inlined 2-arg <= OpNumGt // Non-tail inlined 2-arg > OpNumGtTail // Tail inlined 2-arg > OpNumGe // Non-tail inlined 2-arg >= OpNumGeTail // Tail inlined 2-arg >= OpNumEq // Non-tail inlined 2-arg = OpNumEqTail // Tail inlined 2-arg = OpCons // Non-tail inlined cons OpConsTail // Tail inlined cons OpMul // Non-tail inlined 2-arg * OpMulTail // Tail inlined 2-arg * OpDiv // Non-tail inlined 2-arg / OpDivTail // Tail inlined 2-arg / // Fallback: dispatch to sideTable[Arg] OpComplex )
type OperandKind ¶ added in v1.10.7
type OperandKind uint8
OperandKind classifies what an opcode's Arg field means. Used by cold-path consumers (Disassemble, instructionToOperation) to avoid re-deriving operand semantics in per-opcode switch branches.
const ( // OperandNone means Arg is unused (zero-operand ops). OperandNone OperandKind = iota // OperandRaw means Arg is a meaningful integer but needs no resolution // (e.g., PushEnv slot count, PeekK depth). OperandRaw // OperandLiteralIdx means Arg indexes into the literals pool. OperandLiteralIdx // OperandLocalIdx means Arg is a bit-packed (slot, depth) pair. OperandLocalIdx // OperandBranchOffset means Arg is a relative PC offset. OperandBranchOffset // OperandCachedBinding means Arg indexes into cachedBindings. OperandCachedBinding // OperandSideTable means Arg indexes into the side table. OperandSideTable )
type Operation ¶
Operation is the base interface for all bytecode operations. Every operation is also a values.Value so it can appear in the literals pool and be printed. Operations that are inlined into the Run() switch loop only need this base interface. Operations dispatched through the side table (OpComplex) must additionally implement InlinedOperation.
type OperationApply ¶
type OperationApply struct {
OperationBase
}
OperationApply is the bytecode operation that dispatches procedure calls. The compiler emits it after pushing arguments onto the eval stack and placing the callee in the value register. Apply pops all arguments and delegates to MachineContext.ApplyCallable, which handles the five callable types (MachineClosure, ForeignClosure, CaseLambdaClosure, Parameter, ComposableContinuation).
func NewOperationApply ¶
func NewOperationApply() *OperationApply
NewOperationApply returns a new apply operation.
type OperationBase ¶ added in v1.3.0
type OperationBase struct {
// contains filtered or unexported fields
}
OperationBase provides default SchemeString, IsVoid, and String methods for VM operations. Embed as the first field in operation structs. EqualTo is intentionally not provided: Go requires per-type assertions.
func NewOperationBase ¶ added in v1.3.0
func NewOperationBase(opName string) OperationBase
NewOperationBase creates an OperationBase with the given Scheme name. The name is used as: "#<" + opName + ">".
func NewOperationBaseWithGoName ¶ added in v1.3.0
func NewOperationBaseWithGoName(opName, goName string) OperationBase
NewOperationBaseWithGoName creates an OperationBase with both a Scheme name and a separate Go fmt.Stringer name.
func (OperationBase) IsVoid ¶ added in v1.3.0
func (p OperationBase) IsVoid() bool
IsVoid returns false; operations are never void. Unlike other values.Value implementations, this does not handle nil receivers — operations are bytecode instructions constructed by the compiler and stored in NativeTemplate slices; they are never nil.
func (OperationBase) SchemeString ¶ added in v1.3.0
func (p OperationBase) SchemeString() string
SchemeString returns the Scheme representation of the operation.
func (OperationBase) String ¶ added in v1.3.0
func (p OperationBase) String() string
String returns the Go string representation of the operation.
type OperationBindPatternVars ¶
type OperationBindPatternVars struct {
OperationBase
PatternVars []string // Ordered list for consistent indexing
}
OperationBindPatternVars binds pattern variables from the last match into a new local environment frame that is pushed onto the current environment.
This operation creates a new environment frame with local slots for each pattern variable, binds the matched values, and makes this the current environment.
func NewOperationBindPatternVars ¶
func NewOperationBindPatternVars(patternVars map[string]struct{}) *OperationBindPatternVars
func (*OperationBindPatternVars) Apply ¶
func (p *OperationBindPatternVars) Apply(mc *MachineContext) (*MachineContext, error)
type OperationBranchOffsetImmediate ¶
type OperationBranchOffsetImmediate struct {
OperationBase
Offset int
}
func NewOperationBranchOffsetImmediate ¶
func NewOperationBranchOffsetImmediate(offset int) *OperationBranchOffsetImmediate
func (*OperationBranchOffsetImmediate) EqualTo ¶
func (p *OperationBranchOffsetImmediate) EqualTo(o values.Value) bool
func (*OperationBranchOffsetImmediate) SchemeString ¶
func (p *OperationBranchOffsetImmediate) SchemeString() string
SchemeString overrides OperationBase to include offset value.
type OperationBranchOnFalseValueOffsetImmediate ¶ added in v1.4.0
type OperationBranchOnFalseValueOffsetImmediate struct {
OperationBase
Offset int
}
OperationBranchOnFalseValueOffsetImmediate branches if the value register is #f. This reads directly from the value register instead of popping from the eval stack, eliminating the Push instruction that would otherwise be needed.
Peephole optimization (Aho et al., Compilers §8.9): examines a small window of generated instructions and replaces inefficient patterns. Here, the Push+BranchOnFalse+Pop sequence is replaced with a single BranchOnFalseValue that reads the value register directly. See BIBLIOGRAPHY.md "Peephole Optimization".
func NewOperationBranchOnFalseValueOffsetImmediate ¶ added in v1.4.0
func NewOperationBranchOnFalseValueOffsetImmediate(offset int) *OperationBranchOnFalseValueOffsetImmediate
func (*OperationBranchOnFalseValueOffsetImmediate) EqualTo ¶ added in v1.4.0
func (p *OperationBranchOnFalseValueOffsetImmediate) EqualTo(o values.Value) bool
func (*OperationBranchOnFalseValueOffsetImmediate) SchemeString ¶ added in v1.4.0
func (p *OperationBranchOnFalseValueOffsetImmediate) SchemeString() string
SchemeString overrides OperationBase to include offset value.
type OperationBuildSyntaxList ¶
type OperationBuildSyntaxList struct {
OperationBase
Count int
}
OperationBuildSyntaxList builds a syntax list from elements on the eval stack. n elements are popped from the stack (in reverse order) and consed into a list.
func NewOperationBuildSyntaxList ¶
func NewOperationBuildSyntaxList(count int) *OperationBuildSyntaxList
NewOperationBuildSyntaxList creates a new OperationBuildSyntaxList.
func (*OperationBuildSyntaxList) Apply ¶
func (p *OperationBuildSyntaxList) Apply(mc *MachineContext) (*MachineContext, error)
Apply implements the Operation interface.
type OperationClearSyntaxCaseInput ¶
type OperationClearSyntaxCaseInput struct {
OperationBase
}
OperationClearSyntaxCaseInput clears the per-context syntax-case state. This is called at the end of a syntax-case form.
func NewOperationClearSyntaxCaseInput ¶
func NewOperationClearSyntaxCaseInput() *OperationClearSyntaxCaseInput
func (*OperationClearSyntaxCaseInput) Apply ¶
func (p *OperationClearSyntaxCaseInput) Apply(mc *MachineContext) (*MachineContext, error)
type OperationDrop ¶
type OperationDrop struct {
OperationBase
}
OperationDrop removes the top value from the eval stack without affecting the value register. This is used when we need to clean up the stack but preserve the current result.
func NewOperationDrop ¶
func NewOperationDrop() *OperationDrop
type OperationForeignFunctionCall ¶
type OperationForeignFunctionCall struct {
OperationBase
Function ForeignFunction
}
OperationForeignFunctionCall executes a Go function within the VM loop. Used for foreign closures that do nested VM execution (sub-context + Run), where the iterative VM loop prevents Go stack growth. Leaf primitives use ForeignClosure + applyForeign instead.
func NewOperationForeignFunctionCall ¶
func NewOperationForeignFunctionCall(ffn ForeignFunction) *OperationForeignFunctionCall
func (*OperationForeignFunctionCall) Apply ¶
func (p *OperationForeignFunctionCall) Apply(mc *MachineContext) (rmc *MachineContext, rerr error)
type OperationLoadCachedBinding ¶ added in v1.5.0
type OperationLoadCachedBinding struct {
OperationBase
BindingIndex int32
}
OperationLoadCachedBinding loads a global variable from a compile-time resolved *Binding pointer, bypassing the runtime environment lookup path used by OpLoadGlobal.
func NewOperationLoadCachedBinding ¶ added in v1.5.0
func NewOperationLoadCachedBinding(idx int32) *OperationLoadCachedBinding
NewOperationLoadCachedBinding creates a new cached binding load operation.
func (*OperationLoadCachedBinding) EqualTo ¶ added in v1.5.0
func (p *OperationLoadCachedBinding) EqualTo(o values.Value) bool
EqualTo returns true if both operations have the same binding index.
func (*OperationLoadCachedBinding) SchemeString ¶ added in v1.5.0
func (p *OperationLoadCachedBinding) SchemeString() string
SchemeString returns the Scheme representation of the operation.
type OperationLoadGlobalByGlobalIndexLiteralIndexImmediate ¶
type OperationLoadGlobalByGlobalIndexLiteralIndexImmediate struct {
OperationBase
LiteralIndex LiteralIndex
}
OperationLoadGlobalByGlobalIndexLiteralIndexImmediate loads a global variable using an index from the literals pool.
func NewOperationLoadGlobalByGlobalIndexLiteralIndexImmediate ¶
func NewOperationLoadGlobalByGlobalIndexLiteralIndexImmediate(li LiteralIndex) *OperationLoadGlobalByGlobalIndexLiteralIndexImmediate
NewOperationLoadGlobalByGlobalIndexLiteralIndexImmediate creates a new global load operation.
func (*OperationLoadGlobalByGlobalIndexLiteralIndexImmediate) EqualTo ¶
func (p *OperationLoadGlobalByGlobalIndexLiteralIndexImmediate) EqualTo(o values.Value) bool
EqualTo returns true if both operations have the same literal index.
func (*OperationLoadGlobalByGlobalIndexLiteralIndexImmediate) SchemeString ¶
func (p *OperationLoadGlobalByGlobalIndexLiteralIndexImmediate) SchemeString() string
SchemeString returns the Scheme representation of the operation.
type OperationLoadLiteralByLiteralIndexImmediate ¶
type OperationLoadLiteralByLiteralIndexImmediate struct {
OperationBase
LiteralIndex LiteralIndex
}
OperationLoadLiteralByLiteralIndexImmediate loads a literal value from the literals pool.
func NewOperationLoadLiteralByLiteralIndexImmediate ¶
func NewOperationLoadLiteralByLiteralIndexImmediate(li LiteralIndex) *OperationLoadLiteralByLiteralIndexImmediate
NewOperationLoadLiteralByLiteralIndexImmediate creates a new literal load operation.
func (*OperationLoadLiteralByLiteralIndexImmediate) EqualTo ¶
func (p *OperationLoadLiteralByLiteralIndexImmediate) EqualTo(o values.Value) bool
EqualTo returns true if both operations have the same literal index.
func (*OperationLoadLiteralByLiteralIndexImmediate) SchemeString ¶
func (p *OperationLoadLiteralByLiteralIndexImmediate) SchemeString() string
SchemeString returns the Scheme representation of the operation.
type OperationLoadLocalByLocalIndexImmediate ¶
type OperationLoadLocalByLocalIndexImmediate struct {
OperationBase
LocalIndex *environment.LocalIndex
}
func NewOperationLoadLocalByLocalIndexImmediate ¶
func NewOperationLoadLocalByLocalIndexImmediate(li *environment.LocalIndex) *OperationLoadLocalByLocalIndexImmediate
func (*OperationLoadLocalByLocalIndexImmediate) EqualTo ¶
func (p *OperationLoadLocalByLocalIndexImmediate) EqualTo(o values.Value) bool
func (*OperationLoadLocalByLocalIndexImmediate) SchemeString ¶
func (p *OperationLoadLocalByLocalIndexImmediate) SchemeString() string
type OperationLoadVoid ¶
type OperationLoadVoid struct {
OperationBase
}
func NewOperationLoadVoid ¶
func NewOperationLoadVoid() *OperationLoadVoid
type OperationMakeCaseLambdaClosure ¶
type OperationMakeCaseLambdaClosure struct {
OperationBase
// contains filtered or unexported fields
}
OperationMakeCaseLambdaClosure creates a case-lambda closure from multiple closures. Stack layout (top to bottom): closure_n, closure_n-1, ..., closure_1 The closureCount immediate specifies how many closures to pop.
func NewOperationMakeCaseLambdaClosure ¶
func NewOperationMakeCaseLambdaClosure(closureCount int) *OperationMakeCaseLambdaClosure
func (*OperationMakeCaseLambdaClosure) Apply ¶
func (p *OperationMakeCaseLambdaClosure) Apply(mc *MachineContext) (*MachineContext, error)
type OperationMakeClosure ¶
type OperationMakeClosure struct {
OperationBase
}
func NewOperationMakeClosure ¶
func NewOperationMakeClosure() *OperationMakeClosure
func (*OperationMakeClosure) Apply ¶
func (p *OperationMakeClosure) Apply(mc *MachineContext) (*MachineContext, error)
type OperationPeekK ¶
type OperationPeekK struct {
OperationBase
Depth int
}
func NewOperationPeekK ¶
func NewOperationPeekK(depth int) *OperationPeekK
func (*OperationPeekK) SchemeString ¶
func (p *OperationPeekK) SchemeString() string
SchemeString overrides OperationBase to include depth value.
type OperationPop ¶
type OperationPop struct {
OperationBase
}
func NewOperationPop ¶
func NewOperationPop() *OperationPop
type OperationPopEnv ¶
type OperationPopEnv struct {
OperationBase
}
OperationPopEnv unconditionally restores the parent environment. It pops one level from the environment chain (restoring the parent environment).
This is used in syntax-case fender evaluation to restore the environment when the fender returns false, before branching to the next clause.
func NewOperationPopEnv ¶
func NewOperationPopEnv() *OperationPopEnv
type OperationPopWind ¶
type OperationPopWind struct {
OperationBase
}
OperationPopWind pops the innermost dynamic-wind frame from the winding stack. This operation does NOT call the after thunk - that is done explicitly in the bytecode stream to ensure proper continuation semantics.
The frame is simply removed from the winding stack. If a continuation captured inside the dynamic extent is later restored, the RestoreWithWinding mechanism will handle running the appropriate before/after thunks.
R7RS §6.10: dynamic-wind establishes a dynamic extent during which the before and after thunks are called whenever control enters or exits.
func NewOperationPopWind ¶
func NewOperationPopWind() *OperationPopWind
func (*OperationPopWind) Apply ¶
func (*OperationPopWind) Apply(mc *MachineContext) (*MachineContext, error)
type OperationPull ¶
type OperationPull struct {
OperationBase
}
func NewOperationPull ¶
func NewOperationPull() *OperationPull
type OperationPush ¶
type OperationPush struct {
OperationBase
}
func NewOperationPush ¶
func NewOperationPush() *OperationPush
type OperationPushEnv ¶ added in v1.9.4
type OperationPushEnv struct {
OperationBase
SlotCount int
}
OperationPushEnv allocates a new environment frame with the specified number of local binding slots and chains it to the current environment. Paired with OpPopEnv which restores the parent.
func NewOperationPushEnv ¶ added in v1.9.4
func NewOperationPushEnv(slotCount int) *OperationPushEnv
type OperationPushWind ¶
type OperationPushWind struct {
OperationBase
}
OperationPushWind creates a dynamic-wind frame and pushes it onto the winding stack. It expects the stack to contain [before, thunk, after] where:
- before is at PeekK(2) - the before thunk
- thunk is at PeekK(1) - the main thunk (not used by this operation)
- after is at PeekK(0) - the after thunk
The frame is created from the before and after closures and pushed onto the winding stack. The stack is not modified.
R7RS §6.10: dynamic-wind establishes a dynamic extent during which the before and after thunks are called whenever control enters or exits.
func NewOperationPushWind ¶
func NewOperationPushWind() *OperationPushWind
func (*OperationPushWind) Apply ¶
func (*OperationPushWind) Apply(mc *MachineContext) (*MachineContext, error)
type OperationRestoreContMark ¶ added in v1.7.0
type OperationRestoreContMark struct {
OperationBase
}
OperationRestoreContMark restores the previous mark value after body evaluation. Paired with OperationSaveContMark.
Pre: eval stack = [..., key, old_val_or_sentinel] Post: eval stack = [...], marks[key] restored or deleted, pc++
func NewOperationRestoreContMark ¶ added in v1.7.0
func NewOperationRestoreContMark() *OperationRestoreContMark
func (*OperationRestoreContMark) Apply ¶ added in v1.7.0
func (*OperationRestoreContMark) Apply(mc *MachineContext) (*MachineContext, error)
type OperationRestoreContinuation ¶
type OperationRestoreContinuation struct {
OperationBase
}
func NewOperationRestoreContinuation ¶
func NewOperationRestoreContinuation() *OperationRestoreContinuation
type OperationSaveContMark ¶ added in v1.7.0
type OperationSaveContMark struct {
OperationBase
}
OperationSaveContMark saves the previous mark value and sets a new one. Used in non-tail position, paired with OperationRestoreContMark.
Pre: eval stack = [..., key], value register = val Post: eval stack = [..., key, old_val_or_sentinel], marks[key] = val, pc++
func NewOperationSaveContMark ¶ added in v1.7.0
func NewOperationSaveContMark() *OperationSaveContMark
func (*OperationSaveContMark) Apply ¶ added in v1.7.0
func (*OperationSaveContMark) Apply(mc *MachineContext) (*MachineContext, error)
type OperationSaveContinuationOffsetImmediate ¶
type OperationSaveContinuationOffsetImmediate struct {
OperationBase
Offset int
}
func NewOperationSaveContinuationOffsetImmediate ¶
func NewOperationSaveContinuationOffsetImmediate(off int) *OperationSaveContinuationOffsetImmediate
func (*OperationSaveContinuationOffsetImmediate) EqualTo ¶
func (p *OperationSaveContinuationOffsetImmediate) EqualTo(o values.Value) bool
func (*OperationSaveContinuationOffsetImmediate) SchemeString ¶
func (p *OperationSaveContinuationOffsetImmediate) SchemeString() string
SchemeString overrides OperationBase to include offset value.
type OperationSetContMark ¶ added in v1.7.0
type OperationSetContMark struct {
OperationBase
}
OperationSetContMark sets a continuation mark on the current frame. Used in tail position where no restore is needed.
Pre: eval stack = [..., key], value register = val Post: eval stack = [...], marks[key] = val, pc++
func NewOperationSetContMark ¶ added in v1.7.0
func NewOperationSetContMark() *OperationSetContMark
func (*OperationSetContMark) Apply ¶ added in v1.7.0
func (*OperationSetContMark) Apply(mc *MachineContext) (*MachineContext, error)
type OperationStoreGlobalByGlobalIndexLiteralIndexImmediate ¶
type OperationStoreGlobalByGlobalIndexLiteralIndexImmediate struct {
OperationBase
LiteralIndex LiteralIndex
}
OperationStoreGlobalByGlobalIndexLiteralIndexImmediate stores a value to a global variable using an index from the literals pool.
func NewOperationStoreGlobalByGlobalIndexLiteralIndexImmediate ¶
func NewOperationStoreGlobalByGlobalIndexLiteralIndexImmediate(liti LiteralIndex) *OperationStoreGlobalByGlobalIndexLiteralIndexImmediate
NewOperationStoreGlobalByGlobalIndexLiteralIndexImmediate creates a new global store operation.
func (*OperationStoreGlobalByGlobalIndexLiteralIndexImmediate) EqualTo ¶
func (p *OperationStoreGlobalByGlobalIndexLiteralIndexImmediate) EqualTo(o values.Value) bool
func (*OperationStoreGlobalByGlobalIndexLiteralIndexImmediate) SchemeString ¶
func (p *OperationStoreGlobalByGlobalIndexLiteralIndexImmediate) SchemeString() string
SchemeString returns the Scheme representation of the operation.
type OperationStoreLocalByLocalIndexImmediate ¶
type OperationStoreLocalByLocalIndexImmediate struct {
OperationBase
LocalIndex *environment.LocalIndex
}
func NewOperationStoreLocalByLocalIndexImmediate ¶
func NewOperationStoreLocalByLocalIndexImmediate(li *environment.LocalIndex) *OperationStoreLocalByLocalIndexImmediate
func (*OperationStoreLocalByLocalIndexImmediate) EqualTo ¶
func (p *OperationStoreLocalByLocalIndexImmediate) EqualTo(o values.Value) bool
func (*OperationStoreLocalByLocalIndexImmediate) SchemeString ¶
func (p *OperationStoreLocalByLocalIndexImmediate) SchemeString() string
type OperationStoreSyntaxCaseInput ¶
type OperationStoreSyntaxCaseInput struct {
OperationBase
}
OperationStoreSyntaxCaseInput stores the value register into the per-context syntaxCaseState for use by OperationSyntaxCaseMatch.
func NewOperationStoreSyntaxCaseInput ¶
func NewOperationStoreSyntaxCaseInput() *OperationStoreSyntaxCaseInput
func (*OperationStoreSyntaxCaseInput) Apply ¶
func (p *OperationStoreSyntaxCaseInput) Apply(mc *MachineContext) (*MachineContext, error)
type OperationSyntaxCaseMatch ¶
type OperationSyntaxCaseMatch struct {
OperationBase
}
OperationSyntaxCaseMatch performs pattern matching for syntax-case.
Expects:
- Value register: syntaxCaseClause with compiled pattern
- Per-context syntaxCaseState.input: input syntax object (set by OperationStoreSyntaxCaseInput)
Results:
- If match succeeds: value register = #t, pattern bindings stored in context
- If match fails: value register = #f
func NewOperationSyntaxCaseMatch ¶
func NewOperationSyntaxCaseMatch() *OperationSyntaxCaseMatch
func (*OperationSyntaxCaseMatch) Apply ¶
func (p *OperationSyntaxCaseMatch) Apply(mc *MachineContext) (*MachineContext, error)
type OperationSyntaxCaseNoMatch ¶
type OperationSyntaxCaseNoMatch struct {
OperationBase
}
OperationSyntaxCaseNoMatch is emitted at the end of syntax-case when no clause matches.
func NewOperationSyntaxCaseNoMatch ¶
func NewOperationSyntaxCaseNoMatch() *OperationSyntaxCaseNoMatch
func (*OperationSyntaxCaseNoMatch) Apply ¶
func (p *OperationSyntaxCaseNoMatch) Apply(mc *MachineContext) (*MachineContext, error)
type OperationSyntaxRulesTransform ¶
type OperationSyntaxRulesTransform struct {
OperationBase
}
OperationSyntaxRulesTransform is a VM operation that performs macro expansion.
Execution context:
- Value register: contains clausesWrapper with compiled pattern/template pairs
- Local parameter 0: contains the input form (the macro invocation)
The operation is part of the transformer closure created by CompileSyntaxRules.
func NewOperationSyntaxRulesTransform ¶
func NewOperationSyntaxRulesTransform() *OperationSyntaxRulesTransform
func (*OperationSyntaxRulesTransform) Apply ¶
func (p *OperationSyntaxRulesTransform) Apply(mc *MachineContext) (*MachineContext, error)
type OperationSyntaxTemplateExpand ¶
type OperationSyntaxTemplateExpand struct {
OperationBase
}
OperationSyntaxTemplateExpand expands a syntax template using the current pattern variable bindings. This is used for templates containing ellipsis, which require runtime expansion rather than compile-time code generation.
The template is stored in the value register (loaded from literals). The result is the expanded syntax object, left in the value register.
func NewOperationSyntaxTemplateExpand ¶
func NewOperationSyntaxTemplateExpand() *OperationSyntaxTemplateExpand
func (*OperationSyntaxTemplateExpand) Apply ¶
func (p *OperationSyntaxTemplateExpand) Apply(mc *MachineContext) (*MachineContext, error)
type OperationUnpackListToStack ¶ added in v1.5.0
type OperationUnpackListToStack struct {
OperationBase
}
OperationUnpackListToStack reads a proper list from the value register and pushes each element to the eval stack in order. Used by compiled (apply proc arg1 ... args) to flatten the final arg list onto the stack before Pull + OpApply.
Errors if the value is not a proper list (improper list or non-list).
func NewOperationUnpackListToStack ¶ added in v1.5.0
func NewOperationUnpackListToStack() *OperationUnpackListToStack
NewOperationUnpackListToStack returns a new unpack-list-to-stack operation.
type Operations ¶
type Operations []Operation
func NewOperations ¶
func NewOperations(ops ...Operation) Operations
func (Operations) AsList ¶
func (p Operations) AsList() values.Tuple
func (Operations) Copy ¶
func (p Operations) Copy() Operations
func (Operations) IsVoid ¶
func (p Operations) IsVoid() bool
func (Operations) Len ¶
func (p Operations) Len() int
func (Operations) SchemeString ¶
func (p Operations) SchemeString() string
type Parameter ¶
type Parameter struct {
// contains filtered or unexported fields
}
Parameter represents an R7RS parameter object. Parameters are dynamically-scoped variables that can be temporarily rebound using parameterize. They act as procedures:
- (param) returns the current value
- (param val) sets the current value (after applying converter if present)
func NewParameter ¶
NewParameter creates a new parameter with the given initial value and optional converter. The converter should be a procedure that takes one argument and returns the converted value. Pass nil for converter if no conversion is needed.
func (*Parameter) AcceptsArity ¶ added in v1.5.0
AcceptsArity reports whether this parameter can be called with n arguments. Parameters accept 0 args (get current value) or 1 arg (set value).
func (*Parameter) EqualTo ¶
EqualTo uses identity comparison for parameters. Two parameters are equal only if they are the same object.
func (*Parameter) HasConverter ¶
HasConverter returns true if the parameter has a converter procedure.
func (*Parameter) SchemeString ¶
SchemeString returns the Scheme representation of the parameter.
type Pool ¶ added in v1.5.0
type Pool[T any] struct { // contains filtered or unexported fields }
Pool[T] is a type-safe, observable object pool backed by sync.Pool. It wraps sync.Pool with atomic counters (acquires, releases, misses) and an enable/disable toggle for debugging or benchmarking.
func NewPool ¶ added in v1.5.0
NewPool creates a Pool[T] with the given name, constructor, and reset function. The pool starts enabled.
func (*Pool[T]) Acquire ¶ added in v1.5.0
func (p *Pool[T]) Acquire() *T
Acquire returns an object from the pool. If the pool is disabled, it calls newFn directly (bypassing sync.Pool).
func (*Pool[T]) Drain ¶ added in v1.5.0
func (p *Pool[T]) Drain()
Drain is a no-op on individual pools. Use PoolManager.DrainAll to trigger a GC-assisted drain across all pools.
func (*Pool[T]) Release ¶ added in v1.5.0
func (p *Pool[T]) Release(v *T)
Release resets the object and returns it to the pool. If the pool is disabled, the object is discarded after reset.
func (*Pool[T]) SetEnabled ¶ added in v1.5.0
SetEnabled toggles the pool on or off. When disabled, Acquire calls newFn directly and Release discards after reset, useful for benchmarking or debugging.
func (*Pool[T]) Stats ¶ added in v1.5.0
func (p *Pool[T]) Stats() PoolSnapshot
Stats returns a point-in-time snapshot of the pool's counters.
type PoolHandle ¶ added in v1.5.0
type PoolHandle interface {
Name() string
Stats() PoolSnapshot
Drain()
SetEnabled(bool)
}
PoolHandle is the type-erased interface that PoolManager uses to observe and control heterogeneous pools.
type PoolManager ¶ added in v1.5.0
type PoolManager struct {
// contains filtered or unexported fields
}
PoolManager tracks a collection of PoolHandle instances for unified observation and control.
func NewPoolManager ¶ added in v1.5.0
func NewPoolManager() *PoolManager
NewPoolManager creates an empty PoolManager.
func (*PoolManager) AllStats ¶ added in v1.5.0
func (p *PoolManager) AllStats() []PoolSnapshot
AllStats returns a snapshot of every registered pool's counters.
func (*PoolManager) DrainAll ¶ added in v1.5.0
func (p *PoolManager) DrainAll()
DrainAll triggers a garbage collection, which clears all sync.Pool instances, then calls Drain on each registered pool.
func (*PoolManager) Register ¶ added in v1.5.0
func (p *PoolManager) Register(h PoolHandle)
Register adds a pool to the manager.
func (*PoolManager) SetAllEnabled ¶ added in v1.5.0
func (p *PoolManager) SetAllEnabled(on bool)
SetAllEnabled sets the enabled flag on every registered pool.
func (*PoolManager) String ¶ added in v1.5.0
func (p *PoolManager) String() string
String returns a tabular summary of all registered pools.
type PoolSnapshot ¶ added in v1.5.0
type PoolSnapshot struct {
Name string
Acquires uint64
Releases uint64
Misses uint64
InFlight uint64
}
PoolSnapshot is a point-in-time view of a pool's counters.
type PromptTag ¶
type PromptTag struct {
// contains filtered or unexported fields
}
PromptTag is an opaque identity value for delimited continuation prompts. Equality is pointer identity (each tag is unique). Follows the Racket model of continuation prompt tags.
See: Flatt, Yu, Findler, Felleisen "Adding Delimited and Composable Control to a Production Programming Environment" (ICFP 2007).
func NewPromptTag ¶
NewPromptTag creates a new prompt tag with an optional name for debugging.
func (*PromptTag) SchemeString ¶
type SchemeError ¶
type SchemeError struct {
Message string
Source *syntax.SourceContext // Where error occurred
StackTrace string // Formatted stack trace
Cause error // Underlying error (if any)
}
SchemeError is a runtime error with Scheme-level stack trace.
func NewSchemeError ¶
func NewSchemeError(msg string, source *syntax.SourceContext, stackTrace string) *SchemeError
func NewSchemeErrorWithCause ¶
func NewSchemeErrorWithCause(msg string, source *syntax.SourceContext, stackTrace string, cause error) *SchemeError
func (*SchemeError) EqualTo ¶
func (p *SchemeError) EqualTo(o values.Value) bool
EqualTo compares for equality.
func (*SchemeError) Error ¶
func (p *SchemeError) Error() string
func (*SchemeError) IsVoid ¶
func (p *SchemeError) IsVoid() bool
IsVoid returns false (errors are not void).
func (*SchemeError) SchemeString ¶
func (p *SchemeError) SchemeString() string
SchemeString returns the Scheme representation.
func (*SchemeError) Unwrap ¶
func (p *SchemeError) Unwrap() error
type Stack ¶
func (Stack) AsList ¶
AsList converts the stack to a Scheme list (values.Tuple). The list is in stack order (first pushed = first element).
func (*Stack) Drain ¶ added in v1.5.0
Drain returns a view of all stack elements and resets the stack to empty. The returned slice shares the stack's backing array — it is valid only until the next mutation (Push, PushAll, or any append). Callers must finish reading before any stack mutation.
Unlike PopAll (which copies into a new slice), Drain is zero-allocation. Use Drain when the caller consumes values immediately (e.g., binding arguments in Apply); use PopAll when the caller needs to own the slice.
func (Stack) PeekK ¶
PeekK returns the kth value from the top of the stack without removing it. `K` is zero-based, so PeekK(0) returns the top value. `K` is used for methods that need a numeric index.
func (*Stack) PopAll ¶
PopAll removes and returns all values from the stack. The caller gets exclusive ownership of the returned slice. The stack retains its backing array for reuse (avoids re-allocation on subsequent pushes). References in the retained portion are cleared so the GC can collect the values.
func (*Stack) PopN ¶ added in v1.4.0
PopN removes and returns the top n values from the stack. Values are returned in stack order (top-most element last). This is more efficient than calling Pop() n times.
func (*Stack) Pull ¶
Pull removes and returns the bottom value from the stack. In the SECD model (Landin 1964), the procedure is evaluated first but needed last. Pull retrieves it from the bottom after all arguments have been pushed on top. See BIBLIOGRAPHY.md "Stack-Based Virtual Machines".
func (*Stack) PullDrain ¶ added in v1.10.5
PullDrain removes and returns the bottom value (position 0) as the first return, and all remaining values as the second return. The stack is cleared. This is O(1) — no element shifting, just slice header arithmetic.
The returned args slice shares the stack's backing array (same contract as Drain). Valid only until the next stack mutation.
func (Stack) SchemeString ¶
SchemeString returns a Scheme-like string representation of the stack.
type StackFrame ¶
type StackFrame struct {
FunctionName string // Function name (or "<anonymous>")
CallSite *syntax.SourceContext // Where the call was made
CurrentLoc *syntax.SourceContext // Current execution point
}
StackFrame represents one frame in a Scheme stack trace.
func (*StackFrame) String ¶
func (p *StackFrame) String() string
String formats the frame for display.
type StackTrace ¶
type StackTrace []StackFrame
StackTrace is a list of stack frames.
func (StackTrace) String ¶
func (p StackTrace) String() string
String formats the entire stack trace.
type SubContextParams ¶ added in v1.3.0
type SubContextParams struct {
Ctx context.Context
Env *environment.EnvironmentFrame
ParentMC *MachineContext
EscapeCont *MachineContinuation
ExceptionHandler *ExceptionHandler
MaxCallDepth uint64
MaxStackSize uint64
WindingStack WindingStack
}
SubContextParams holds the parent state needed to create a thread's sub-context. This is used to avoid race conditions when creating sub-contexts across goroutine boundaries.
type SyntaxCaseClause ¶ added in v1.10.5
type SyntaxCaseClause struct {
Bytecode []match.SyntaxCommand
PatternVars map[string]struct{}
EllipsisVars map[int]map[string]struct{}
EllipsisDepths map[int]int
}
SyntaxCaseClause wraps compiled pattern info for a syntax-case clause. Created by the compiler, consumed by OperationSyntaxCaseMatch at runtime.
func (*SyntaxCaseClause) EqualTo ¶ added in v1.10.5
func (p *SyntaxCaseClause) EqualTo(other values.Value) bool
func (*SyntaxCaseClause) IsVoid ¶ added in v1.10.5
func (p *SyntaxCaseClause) IsVoid() bool
func (*SyntaxCaseClause) SchemeString ¶ added in v1.10.5
func (p *SyntaxCaseClause) SchemeString() string
type SyntaxRulesClause ¶
type SyntaxRulesClause struct {
Template syntax.SyntaxValue
Bytecode []match.SyntaxCommand
Matcher *match.SyntaxMatcher
PatternVars map[string]struct{}
PatternVarSyntax map[string]*syntax.SyntaxSymbol
EllipsisVars map[int]map[string]struct{}
FreeIds map[string]*FreeIdResolution
Ellipsis string
LiteralSyntax map[string]*syntax.SyntaxSymbol
}
SyntaxRulesClause represents a single compiled pattern-template pair in a syntax-rules form. Created by the compiler, consumed by OperationSyntaxRulesTransform at runtime.
type VMCounters ¶ added in v1.1.0
type VMCounters struct {
OpsExecuted uint64
ClosuresApplied uint64
EnvsCopied uint64
BindingsCopied uint64
ContinuationsSaved uint64
ContinuationsRestored uint64
StackDrains uint64
StackElementsDrained uint64
ForeignCalls uint64
SubContextsCreated uint64
StackPoolReleases uint64
SubContextPoolReleases uint64
// Pool effectiveness under call/cc:
// ratio = SharedFrameRestores / (SharedFrameRestores + ContinuationPoolReleases)
// 0.0 = no call/cc impact (all frames recycled via pool)
// 1.0 = all frames shared (no recycling, pure GC pressure)
// > 0.5 = pool losing more than it saves; consider profiling GC pauses
ContinuationPoolReleases uint64
EnvFramePoolReleases uint64
InlineEvalsSaved uint64 // SaveContinuation used inline slots instead of stack pool
// Stack depth instrumentation (ongoing monitoring; prior cap-tuning investigation
// showed cap-8 is sufficient for observed workloads)
StackMaxDepth uint64
StackDepth0to2 uint64 // depth 0-2: fits trivially
StackDepth3to4 uint64 // depth 3-4: typical calls
StackDepth5to8 uint64 // depth 5-8: fits in pool cap 8
StackDepth9to16 uint64 // depth 9-16: requires 1 growth from cap 8
StackDepth17p uint64 // depth 17+: requires 2+ growths
// contains filtered or unexported fields
}
VMCounters holds performance counters for a single MachineContext execution. All counters are plain uint64 — no atomics needed because each MachineContext is single-goroutine. Sub-contexts have their own counters (not aggregated into the parent).
func (VMCounters) CallHistogram ¶ added in v1.7.0
func (p VMCounters) CallHistogram() string
CallHistogram returns a formatted histogram of per-callee call counts (both foreign primitives and named Scheme procedures), sorted by frequency (descending). Returns empty string when profiling is disabled.
func (VMCounters) OpcodeHistogram ¶ added in v1.6.0
func (p VMCounters) OpcodeHistogram() string
OpcodeHistogram returns a formatted histogram of opcode hit counts, sorted by frequency (descending). Only opcodes with non-zero hits are included.
func (*VMCounters) RecordCall ¶ added in v1.7.0
func (p *VMCounters) RecordCall(name string)
RecordCall increments the call count for the named callee (foreign primitive or Scheme-defined procedure). No-op when profiling is disabled (nil map).
func (*VMCounters) RecordStackDepth ¶ added in v1.4.0
func (p *VMCounters) RecordStackDepth(n int)
RecordStackDepth updates the depth histogram and max tracker.
func (VMCounters) String ¶ added in v1.1.0
func (p VMCounters) String() string
String returns a tabular summary of all counters.
type WindingStack ¶
type WindingStack []*DynamicWindFrame
WindingStack tracks the current dynamic-wind context. It's a slice of frames from outermost to innermost.
func (WindingStack) Copy ¶
func (p WindingStack) Copy() WindingStack
Copy creates a shallow copy of the winding stack.
func (WindingStack) Depth ¶
func (p WindingStack) Depth() int
Depth returns the number of active dynamic-wind frames.
func (*WindingStack) Pop ¶
func (p *WindingStack) Pop() *DynamicWindFrame
Pop removes the innermost frame from the winding stack.
func (*WindingStack) Push ¶
func (p *WindingStack) Push(frame *DynamicWindFrame)
Push adds a frame to the winding stack.
Source Files
¶
- arity.go
- barrier_token.go
- call_context.go
- call_foreign_cached.go
- call_promoted.go
- call_promoted_arithmetic.go
- captured_continuation.go
- case_lambda_closure.go
- closure.go
- composable_continuation.go
- continuation_mark_set.go
- counters.go
- debugger.go
- disassemble.go
- doc.go
- dynamic_wind.go
- edit_plan.go
- exception_escape.go
- exception_handler.go
- expander_ctx.go
- foreign_closure.go
- instruction.go
- machine_closure.go
- machine_context.go
- machine_context_apply.go
- machine_context_continuation.go
- machine_context_subcontext.go
- machine_context_winding.go
- machine_continuation.go
- macro_evaluator.go
- multiple_values.go
- native_template.go
- opcode.go
- operation.go
- operation_build_syntax.go
- operation_cont_mark.go
- operation_helpers.go
- operation_syntax_case.go
- operation_syntax_rules_transform.go
- operations.go
- operations_call.go
- operations_closure.go
- operations_control.go
- operations_load_store.go
- operations_stack.go
- operations_winding.go
- parameter.go
- peephole.go
- pool.go
- pool_generic.go
- prompt_abort.go
- prompt_tag.go
- scheme_error.go
- stack.go
- stack_frame.go
- syntax_bridge_types.go
- util.go
- vm_state.go