Vile runtime for V hosts
The scheme module compiles reader documents through their public API and
executes them in an instruction VM. It does not depend on the CLI.
The language combines an R5RS foundation with selected R6RS/R7RS extensions.
There is one dialect shared by both frontends, with no standards-selection modes.
Current extensions include when, unless, letrec*, case-lambda, case
receiver clauses, multiple-value binding/definition forms, delay-force,
promise?, make-promise, make-parameter, parameterize, sequence operations,
enumeration types and immutable enumeration sets, and self-evaluating
immutable vector constants. See the
syntax and examples.
VM.eval_alt(source)!Value selects the independent alt reader for calls such as
f(a, b), optional infix arithmetic, evaluated vector literals [a, b], and
{ ... } bodies. It also accepts if condition { ... } else { ... },
while condition { ... }, for(init, condition, step) { ... },
fn(x) { ... }, and xs[i] / xs[i] = value.
These lower to existing Scheme forms and procedures.
It shares the same compiler, VM, globals, closures, limits, and native callbacks
with eval. A host can mix the two entry points in one VM:
mut vm := scheme.new()
vm.eval_alt('define(square(x), x * x)') or { panic(err) }
result := vm.eval('(square 7)') or { panic(err) }
assert result.as_integer() or { panic(err) } == 49
See the Vile syntax grammar for grouping and list
notation. reader.read_alt(source)!Document exposes the lowered flat arena
without evaluating it, including original source locations. Ordinary eval
continues to call the Scheme reader directly. Scheme's read consumes Scheme
data; load chooses the source frontend by the loaded filename's extension.
Standard binding and declaration forms use the same call/tuple notation. A trailing comma keeps a one-element formal or binding list from becoming grouping:
define-values((a,b),values(20,22))
let-values((((x,y),values(a,b)),),x+y)
define-record-type(point,fields(mutable(x),y))
p := make-point(a,b)
Libraries also use calls and tuples, with R7RS-small declarations and import sets:
define-library((example,math),export(square),import((scheme,base)),{
square(x) := x*x
})
import(rename((example,math),(square,sq)))
sq(7)
The paired frontend fixtures include complete examples for records, macros, parameters, multiple values, and selected libraries.
return(value) / (return value) exits the nearest source procedure. Binding
helpers retain the enclosing return target; named let introduces a procedure
boundary. Returns preserve multiple values and restore dynamic bindings, and
continuation replay retains the activation's original target. Deferred
expressions cannot return across their delay boundary. The default environment
and (vile base) provide this optional syntax. See the
Vile syntax examples for the full scope rules.
break / (break) exits the nearest for, while, or do loop with an
unspecified value, skipping pending body and step expressions. Procedure and
deferred-expression boundaries block a break; binding helpers retain its loop
target. Parameter bindings are restored, and continuations retain the original
target on replay. The default environment and (vile base) export this optional
syntax. Loops without loop controls reserve no exit-marker slots or marker
instructions; controlled loops initialize hidden exit state once per invocation.
continue / (continue) resumes the nearest loop's complete step sequence
with the current iteration's bindings and restored dynamic parameters. A
continue in a step restarts all steps, discarding partial step arguments.
for lowering carries its step as a do effect-only binding (() step);
this contributes no initializer, variable, parameter, or environment slot.
It survives ordinary read/write and syntax-rules transformations. Multiple
effect-only and named bindings run their steps in binding order.
Compiler-owned empty binding scopes call their function directly, without a temporary procedure object. Continue recycles abandoned, unescaped helper activations through the existing cache. Actual closures, promises, and saved continuations preserve their lexical ancestors before any activation is reused.
Keywords
#:name is a self-evaluating keyword, distinct from the symbol name.
Both frontends accept keywords as arguments, vector elements, and standalone
values. The default environment and (vile keywords) provide keyword?,
symbol->keyword, and keyword->symbol. Imports and reexports use the same
R7RS-small declaration forms as other binding collections.
Keyword names follow the existing identifier case-folding and Unicode rules;
#!no-fold-case preserves case. Bars and escapes permit empty, numeric,
whitespace-containing, and other unusual names: #:||, #:|123|, and
#:|space name|. Comments, whitespace, and directives may follow the prefix;
the next retained token must be a symbol. A label may name a keyword datum
(#1=#:name), but the prefix does not accept
a label reference in place of its name.
For hosts, scheme.keyword(name)!Value takes an exact case-sensitive UTF-8
name and owns a copy. Value.keyword_name()!string returns an independent
string. Scheme conversions between symbols and keywords retain the same
immutable payload without allocation. Equal names compare equal under eq?,
eqv?, and equal?, including across VMs; symbols remain a separate type.
Storage follows the normal allocator lifetime rules. Keyword literals are a
GOOPS prerequisite; they do not enable keyword argument binding by themselves.
Source files
VM.eval_file(path)!Value is a host entry that loads .vile as Vile syntax and
other extensions as Scheme, evaluates top-level forms in order, and returns the
last value. VM.eval_file_as(path, .scheme) or .vile forces a frontend.
Host paths resolve against the process directory. Returned closures retain
their own source and filename even after the host releases the path string.
Scheme (load filename) / Vile load(filename) uses the interaction
environment, or accepts an explicit environment as its second argument.
It returns unspecified. Relative loads resolve against the calling source
file; a closure keeps its defining file as the base even when invoked later.
Scheme datum eval inherits that base. Load does not change the process
directory, current ports, or a caller's lexical bindings.
Source is parsed completely before execution. Top-level forms then compile
when reached, allowing loaded macros to affect later forms. Staging uses VM
instructions and the existing continuation stack, so loaded code can capture
continuations, cross dynamic-wind, or escape reentrant V callbacks. Execution
and macro-expansion budgets are shared across Scheme load/eval on the same
machine; a public V entry retains its own budgets.
File failures are EvalErrors with source_path, line, column, and offset when
available. File reader errors use this wrapper so an unfinished loaded file
does not accidentally request more REPL input. Direct string eval retains
the reader's original error types. The loading example
uses a separate Vile config file.
Within this checkout:
import scheme
mut vm := scheme.new()
vm.eval('(define (square x) (* x x))') or { panic(err) }
square := vm.lookup('square') or { panic(err) }
result := vm.call(square, [scheme.integer(7)]) or { panic(err) }
assert result.as_integer() or { panic(err) } == 49
From another project, use import vile.scheme; its short name is scheme.
Add this checkout's parent to V's search path, or install the repository in
V's module directory:
v -cc gcc -path '/path/to/vile/parent|/path/to/vile/parent/vile|@vlib|@vmodules' run host.v
The toolchain includes V's strings.Buffer and arena additions, including
arena.Allocator.run for restoring a captured allocation domain. Boehm
builds also require the builtin GCWeakReference API for GOOPS. The default
Boehm collector manages runtime payloads and closure/environment cycles. A host can instead use the standard V arena module with -gc none
for a whole VM region, as described below. A persistent VM still needs GC or
another host lifetime strategy; arenas do not collect individual unreachable
objects within a live region.
Source reader state and host names
Ordinary eval, eval_alt, and file entries start independently with R5RS case
folding. Both frontends support Unicode17 identifiers, #!fold-case /
#!no-fold-case, long booleans, nested/datum comments, escapes, bytevector literals
and shared/cyclic datum notation. Reader examples
describe the selected grammar. #!r6rs does not change the dialect or R7RS-small
library machinery.
For a REPL or another stream of source fragments, keep caller-owned state:
mut state := scheme.SourceReadState{}
vm.eval_with_read_state('#!no-fold-case (define MiXeD 42)', .scheme, mut state)!
value := vm.eval_with_read_state('MiXeD', .scheme, mut state)!
assert value.as_integer()! == 42
Use .vile for Vile source; .auto without a filename means Scheme. Parsing
happens once. Successful parsing commits the final mode before execution, even
if evaluation later fails. A fatal parser error commits exactly the consumed
reader state. Incomplete input keeps the initial mode so the complete pending
source can be retried. reader.failure_state(err) exposes final mode and consumed
byte offset separately from the diagnostic location; reader.failure_cause(err)
unwraps a rare non-syntax cause. Normal lexer/reader error types remain intact.
V host symbol, define, lookup, register, define_in, lookup_in, and
import_bindings accept optional fold_case:false. Names are still complete
source identifier spellings; use bars/hex escapes for empty, spaced or NUL names.
Existing calls retain their default folding. For borrowed input Readers,
InputOptions.fold_case sets the initial port mode; subsequent directives persist
across reads and consumed input errors.
Source literals are immutable; datum read produces mutable owned containers.
Aliases preserve pair/vector/string/bytevector identity.
That identity survives staged begin forms and library initialization. Independent
outer source datums and discovered library declarations have separate literal
owners. Nested includes share their containing caller's owner; they do not add
per-included-root reclamation. Runtime graph assembly
publishes no partially filled cached container after a conversion failure. Its
worklist and validation scratch use lexical standard arenas; published values
retain the caller's normal GC/arena owner. Cached graph literals need no adapter
or scratch allocation. Cyclic executable syntax, quasiquote templates and finite
syntax-rules transformer grammar fail with located errors; captured cyclic data
can still be quoted by a macro. These checks follow actual keyword bindings.
write/write-shared use readable symbol and string escapes. A case-sensitive
symbol emits one #!no-fold-case directive when first needed, preserving exact
names without prewalking or copying the finished output. display retains raw
symbol/string output. Canonical output is Scheme datum notation in both modes.
Host cancellation
VM.with_context[T](mut ctx T, work scheme.EvaluationFn)!Value runs a host
callback with cooperative cancellation. EvaluationFn has type
fn (mut scheme.VM) !scheme.Value; it can call any evaluation frontend, evaluate
files, invoke procedures, or perform several operations. The generic context
protocol uses done() chan int and err() IError, as supplied by V's context
module. Custom context methods must be accessible from the calling module.
Ordinary VM users need no context import; the runtime adapter does not import
that module.
import context
import scheme
import time
mut background := context.background()
mut ctx, cancel := context.with_timeout(mut background, 100 * time.millisecond)
defer { cancel() }
mut vm := scheme.new_with_options(scheme.Options{ max_steps: 0 }) or { panic(err) }
value := vm.with_context(mut ctx, fn (mut vm scheme.VM) !scheme.Value {
return vm.eval('(let loop () (loop))')
}) or {
if err is scheme.CancellationRequest {
println(err.msg())
return
}
panic(err)
}
Cancellation returns a typed scheme.CancellationRequest; its .reason is the
context's error. scheme.is_control_transfer(err) recognizes cancellation,
continuation transfers, and exit requests. Native callbacks should propagate
these requests when handling errors. Cancellation abandons the evaluation without
running additional user Scheme dynamic-wind after procedures. Private managed
file extents still close and entry-local dynamic bindings are discarded as on
ordinary V errors, including
file resources retained during a pending normal exit. Earlier side effects
remain; cancellation does not roll back changes or close unmanaged host resources.
The scope checks cancellation before work, at every public execution entry,
between VM instructions, and after successful work. An already canceled entry
stops before parsing, file reading, datum compilation, argument validation, or
applying a native procedure. Host management operations such as define, lookup,
and closing ports remain usable for cleanup after cancellation. An error returned
by work takes precedence over the final check and is propagated unchanged. Cancellation does not interrupt parsing,
compilation, file reading, a blocking writer, or native work while it runs.
A deadline is therefore a cooperative stop request, not a hard execution limit.
Existing instruction/frame/expansion budgets retain their own behavior.
Allocation/resource limits remain separate work.
Nested scopes observe their own signal and every active parent, even when the contexts are otherwise independent. An inner cancellation can be caught by uncanceled outer work; canceling an active parent also stops its child scopes. Native reentry inherits the active scope. Saved Scheme continuations do not capture it: later invocation uses the scope active at that time. The previous scope is restored on success, errors, cancellation, exits, and continuation transfers. A VM still belongs to one host thread at a time; a cancellation thread signals the context rather than accessing the VM.
The context object is borrowed live for the callback, so custom mutable contexts
report their current error after their stable done channel closes. Keep the
context and its signal alive until the callback returns, and synchronize
concurrent context updates according to its own protocol. The done channel is
cached once per scope; err() is queried only after closure. Replacing the
context or its signal while the callback is active breaks that protocol.
For -gc none, create contexts, done channels, timer machinery, and cancel
callbacks outside the VM arena. A standard context timer/propagation goroutine
can outlive cancel(); calling cancel does not prove that it is safe to free an
arena containing that context. Initialize any custom lazy host context storage
outside the VM region too. Keep host context storage alive for all its users.
As with other errors, format cancellation diagnostics while their allocations
are live, pop the VM arena, copy out required text, then reset/free it. The
context host example demonstrates this order:
v -cc gcc -gc none run examples/context_host
v -cc gcc test scheme/evaluation_control_test.v examples/context_host
The implementation chooses a separate cancellable instruction loop once at
entry. The ordinary loop has no per-instruction cancellation polling. The
cancellable loop polls cached channels through the standard atomic closed
operation, without locking a context or allocating while signals remain open.
Only the existing lazy system state gains a control pointer; VM, Machine,
Options, and continuation layouts stay unchanged. Tests cover nesting, native
reentry, saved continuations, both frontends, file entries, pending exit cleanup,
threaded cancellation/deadlines, live custom errors, independent host exports,
and repeated GC/free arena scopes. This is host cancellation, not Scheme
exception handling or another language profile.
Bounded VMs
scheme.new_bounded(options, arena.ChunkLimits{max_live_bytes: ..., max_total_bytes: ...})
creates a VM in an owned arena. Initialization, reading, compilation, execution,
and nested scratch arenas draw from the same hard backing-chunk limits.
chunk_usage() reports the successful live, peak live, and cumulative reservations.
The counters include chunk headers and storage retained across arena resets.
import arena
import scheme
fn main() {
mut vm := scheme.new_bounded(scheme.Options{}, arena.ChunkLimits{
max_live_bytes: 32 * 1024 * 1024
})!
defer { vm.close() or { panic(err) } }
answer := vm.eval('(+ 20 22)')!
assert answer.as_integer()! == 42
}
Use the handle on a single host thread. Use eval for Scheme source and
eval_alt for Vile source. Both share the same bindings and limit. Use
call to invoke a saved procedure. A run callback has
access to the ordinary VM API and can reenter evaluation. Values and ordinary
VM errors belong to the arena until close(). Native code that explicitly
selects another allocator, starts threads, or allocates through C owns that
memory separately. Arena control blocks and allocator metadata are also outside
the chunk totals.
A refused chunk returns a ResourceLimitRequest with kind .vm_chunk_bytes.
Physical backing allocation failure returns .vm_allocation. The VM can recover
from a denial while reading a document or a host-supplied identifier, applying
a built-in primitive, preparing a host call, or allocating a new evaluation
activation before its entry is published. Recovery also covers source-driver
construction, staged compilation, and host-datum conversion before their
functions enter the evaluator. Ordinary closure activation and call-frame
reservation recover before the callee enters. Cached environments keep their
existing storage when it covers the required slots. Ordinary variable publication in the root or a
writable namespace also recovers, including its declaration location for macro
hygiene. Definitions that replace a syntax keyword or transformer follow the
general mutation path.
Earlier bindings, cyclic literals, procedural macros and saved closures remain usable within the remaining budget. Successful reservations continue to count toward the cumulative limit. Temporary reader, Unicode, quasiquote and procedural-macro arenas restore the caller's allocator during allocation-failure unwinding. Failed graph conversion removes unpublished memo entries before another attempt can reuse them. Compiler list-scope cleanup releases scratch without allocating a replacement map.
An interruption elsewhere, including inside an arbitrary native callback from a
procedural macro, closes the VM's owned descriptors and disables further
evaluation on that handle. close() releases its arena. Normal close flushes
pending file writes. An allocation failure during deferred GOOPS initialization
also quarantines the handle; it does not retry over partially published metadata.
Cooperative arena usage
VM.with_arena_usage_limit(region &arena.Arena, limit i64, work EvaluationFn)!Value
runs synchronous host work with an opt-in, sampled arena usage threshold. The
borrowed arena must be the current innermost arena when the scope begins and
remain alive throughout the scope. The limit must be nonnegative. Zero adds no
controller and disables this additional threshold; active parent controls still
apply. A positive limit is absolute region.used(), including existing data,
VM construction, controller setup, parser/compiler allocations in that region,
alignment, and host allocations charged there. It is not extra space granted at
entry. Equality with the threshold is allowed; a strictly larger observation
returns typed ArenaUsageLimitRequest with scalar .limit and .used fields.
The observation is recorded before constructing the request or cleaning up.
import arena
import scheme
mut region := arena.new()
region.push()
mut vm := scheme.new()
limit := i64(region.used()) + 128 * 1024
result := vm.with_arena_usage_limit(®ion, limit, fn (mut vm scheme.VM) !scheme.Value {
return vm.eval('(make-bytevector 1048576)')
}) or {
if err is scheme.ArenaUsageLimitRequest {
println('observed ${err.used} bytes; threshold ${err.limit}')
}
scheme.unspecified()
}
region.pop()
// Consume/copy any required result or diagnostic while its region is live.
region.free()
The executable host example formats requests
while live, pops the region, copies required text into the restored host allocator,
and only then resets/frees the region. Its exported .used/.limit fields are
scalars. A returned Value or IError still contains borrowed allocations:
copying the error interface header does not export the object behind it.
Checks run before host work, at all public execution entries before parsing,
file reading, environment/datum validation or native application, between VM
instructions, and after successful work. Parsing, compilation, file reading,
formatting, a native callback, or one large arithmetic operation may overshoot
before returning. A native operation may finish an external side effect before
the next check. A callback's returned error, exit or continuation transfer keeps
precedence over the successful-return postcheck. As with cancellation, usage
aborts run no additional Scheme dynamic-wind after procedures, while private
managed-file extents and pending normal-exit file snapshots still close. Earlier
side effects remain. Management operations such as define, lookup and closing
ports remain available for cleanup. is_control_transfer(err) recognizes both
host requests as well as exits and continuation transfers.
Scopes nest with cancellation and other usage scopes in one private chain. Every active ancestor is checked; a larger child threshold cannot bypass its parent. If several controls are triggered, the innermost triggered node wins. Different target arenas remain independent, and parents need not remain the current arena while a child is pushed. Native reentry inherits the chain; saved Scheme continuations do not capture it. Previous controls restore on every returned path. The scope neither pushes/pops nor resets/frees its arena. Do not reset/free any arena holding the VM, live values, controllers or errors while work still needs them. A VM still belongs to one host thread at a time.
This is not a hard memory cap, cumulative allocation counter, peak counter,
OOM recovery guarantee, RSS limit or sandbox. used() counts consumed bump storage,
not reserved capacity. The allocator can shrink its latest allocation, so a
native allocation can exceed the threshold and shrink again between polls without
being observed. Nested private arenas (including compiler scratch), other
allocators/threads, mapped memory and OS resource handles are excluded. Sampling
traverses the standard arena's chunks: checking the control chain costs
O(sum of active target chunk counts) per poll. Error construction and resource
cleanup may allocate further. Hard allocation/resource controls remain separate
work; no allocator is replaced and no failure escapes through longjmp.
Enabled scopes allocate their private controller (and lazy system state when needed). Disabled scopes add neither. Below-threshold polling allocates nothing; only arena-kind nodes query statistics, and only cancellation-kind nodes poll a cached channel. Arena nodes use an explicit nil channel default, avoiding V's implicit channel construction. The ordinary instruction loop gains no per-step polls: the existing entry branch selects the separate controlled loop. VM, Machine, Options and continuation layouts are unchanged; only cold controller storage grows.
with_context now pairs the live borrowed context pointer with a static generic
reason function. The private type-erasure invariant is established together at
construction; only that function interprets the pointer as its original type.
It uses no captured V closure, environment, trampoline or global callback registry.
Both concrete custom contexts and context interfaces keep their live identities.
Tests exercise 256 reset/free cycles with static work callbacks and no closure
prewarming, alongside the existing mutable-context checks.
Host-provided capturing V callbacks have their own lifetimes. Construct them in
appropriate long-lived host storage before entering a short VM arena. The current
V capturing-closure runtime's global bookkeeping is not arena-aware: first
initialization or growth inside an arena can leave global pointers into freed
storage. Public builtin.closure.Lifetime facilities can manage callback contexts
where applicable, but do not by themselves make that global bookkeeping
arena-aware. The VM does not retain its borrowed work callback after the scope.
Noncapturing static callbacks, as in the runnable example, avoid this issue.
Contexts/channels/timer machinery must still live outside short VM arenas when
asynchronous users can outlive cancellation, as described above.
v -cc gcc -gc none run examples/arena_usage_host
v -cc gcc test scheme/arena_usage_test.v scheme/arena_usage_entry_test.v \
scheme/arena_usage_nested_test.v scheme/arena_usage_file_test.v \
scheme/arena_usage_host_test.v scheme/arena_usage_context_region_test.v \
examples/arena_usage_host
Owned file quotas
Options.max_open_files bounds simultaneous file reservations for one VM. Its default,
none, is unlimited; an explicit zero prevents acquiring an owned descriptor. The quota
persists across evaluations, native reentry, contexts and Scheme continuations.
import scheme
mut vm := scheme.new_with_options(scheme.Options{
max_open_files: 8
}) or { panic(err) }
All owned text, binary and combined file constructors reserve capacity before opening or truncating a file. Transcoded wrappers and duplex halves share their underlying stream's single charge; capacity returns when that stream closes, including a failed flush or close. Failed construction rolls back both the reservation and any descriptor already acquired. Boehm finalizers release the same charge once. Arena-backed streams still require explicit close before their arena is reset.
Source reads through eval_file, load, inclusion, library imports and file-based
cond-expand probes use transient reservations. A completed read releases its slot before
parsing and execution, allowing sequential includes with a one-file quota. Cached libraries
need no new descriptor. Initial standard streams, memory/custom ports, borrowed host
Readers/Writers and file work performed directly by a native host callback are not owned
by this counter.
A rejected reservation returns ResourceLimitRequest with .kind == .open_files, .limit,
.used and .requested scalar fields. Preserve this host control through
scheme.is_control_transfer(err): it aborts managed file extents without running Scheme
winders. Existing retained ports remain charged and can be explicitly closed before reuse.
In particular, a port retained after escaping call-with-input-file or
call-with-output-file stays open until closed; managed with-input-from-file and
with-output-to-file extents close on escape.
The quota checks only descriptor acquisition. It does not add instruction-loop polling.
Compiler list allocation limits
Hosts can configure Options.compile_list_limits with CompileListLimits{max_live_bytes: n, max_total_bytes: m}. Each limit is optional. Zero allows only empty decoded lists.
A cached list shares its original NodeId array. For an uncached proper list the compiler
counts its elements, checks both bounds and allocates the exact payload once in its
scratch arena. Nested compilations share the VM counters. Leaving a compilation
releases its live charge, including on failure. The cumulative charge lasts for the VM's
lifetime and starts after initialization of the built-in library.
vm.compile_list_usage() returns the live, peak and cumulative payload byte counts
when accounting is enabled. Rejected requests report .compile_list_live_bytes or
.compile_list_total_bytes through the existing ResourceLimitRequest. Failure to
allocate the payload reports .compile_list_allocation. The scope covers decoded list
buffers. Arena chunk overhead, the arena control block, maps, source text, and other VM
and host allocations are outside its accounting.
For a separate Vile process on a Linux host with a delegated cgroup v2 memory
controller, the service manager can also enforce a process-group memory policy.
For example, systemd-run --user --scope -p MemoryMax=256M -p MemorySwapMax=0 ./vile script.scm
places the interpreter in a limited scope from launch. Charged memory includes file
cache and kernel memory. Reclaim and OOM termination affect the worker, so the
supervising host belongs outside the scope. The kernel permits temporary overshoot.
See the kernel memory controller
and systemd resource controls.
GC-free host regions
The executable arena host example uses V's
existing scoped allocator. The host creates an arena.Arena, pushes it before
scheme.new(), and keeps it active throughout evaluation, callbacks, and
formatting. With -gc none, all normal V allocations on that thread belong to the region,
including the VM, reader documents, environments, cyclic data, and captured
continuations. The lexer and reader require no allocator changes.
The example pops the arena with defer, then clones the formatted result into
the restored host allocator before calling reset() or free(). It converts
errors to text while the region is live, copies out that text after popping,
and preserves ExitRequest.status and .emergency as scalar fields. It never
returns a VM, Value, or IError across destruction of its region: cloning a
container of handles does not copy their reachable Scheme objects. Release
exported strings explicitly when the receiving host also uses -gc none.
Run it and its lifetime tests from this checkout:
v -cc gcc -gc none run examples/arena_host
v -cc gcc -gc none test examples/arena_host
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 \
v -cc gcc -gc none -cflags '-fsanitize=address,undefined -fno-omit-frame-pointer' \
-ldflags '-fsanitize=address,undefined' test examples/arena_host
The sanitizer command checks invalid accesses and undefined behavior. Leak checking is disabled because the V test harness uses process-lifetime allocations without GC; the tests independently assert bounded region capacity over 64 identical VM scopes and steady-state stability after warmup, plus zero used bytes after each reset. They also cover nested arenas, retained sources/closures, multishot continuations, native reentry, borrowed writers, errors, typed exits, and file cleanup before reset.
Arena pushes nest. After an inner arena is popped, a clone is allocated in the outer arena if one remains active. It therefore survives the inner reset, but must be copied again after the outer pop to survive the outer reset. A region must remain live for every Scheme value, closure, continuation, native capture, and outstanding host call that refers into it. Keep VM operations in its active region; extending an old VM under a different active allocator can give its objects mixed lifetimes. Do not retain callback arguments, values, errors, or other arena allocations in longer lived host state. Initialize host global caches before pushing if their lazy initialization allocates memory.
Borrowed readers and writers must outlive their Scheme ports. A host-owned array, map, or string builder that grows during an arena scope can acquire arena-backed storage, even if the container was created before the push. Reserve enough capacity before entering, use fixed host storage as the writer test does, or copy any retained storage after popping. Callbacks must consume borrowed buffers before returning. Spawned threads do not inherit an active arena; finish all work using its objects before releasing the region.
Bulk memory cleanup does not close OS file descriptors or flush output.
Arena-owned file streams cannot have individual Boehm finalizers, because they
are stored inside a larger allocation. Close their descriptors before reset.
Prefer
with-input-from-file / with-output-to-file managed extents for region-scoped
files; their selection and closure unwind before the host regains control,
including runtime errors and typed exits. Explicitly close or flush any other
owned file port before reset, including ports retained after a continuation
escape from call-with-input-file / call-with-output-file. Borrowed ports do
not close their host resource. The host remains responsible for that resource.
Compiler list decoding also uses V's arena allocator in bounded compilation
scopes. Only temporary arrays of scalar reader node IDs enter this scratch
region. Constants, diagnostics, generated syntax, closures, and emitted
instructions retain their ordinary owners. The compiler clears decoding views
and frees scratch on every return, including errors and nested empty forms.
The arena is created lazily: scalar expressions and empty lists create no
scratch region. A used region reserves an initial 1 KiB chunk, so small list
forms can require more transient capacity than individually allocated buffers.
This bounds temporary ownership; it does not collect a persistent VM's values.
Enumerations
The selected R6RS enumeration extension provides make-enumeration,
enum-set-universe, enum-set-indexer, enum-set-constructor, enum-set->list,
enum-set-member?, enum-set-subset?, enum-set=?, enum-set-union,
enum-set-intersection, enum-set-difference, enum-set-complement,
enum-set-projection, and define-enumeration. The binding collections
(vile enums) and (rnrs enums) export the same bindings through R7RS-small's
library and import machinery. These are extensions in the shared
R5RS-based dialect, with its existing symbol case folding and V errors.
(define-enumeration color (red green blue) colors)
(color red) ; red, without evaluating a variable
(enum-set->list (colors blue red)) ; (red blue)
(enum-set->list (enum-set-complement (colors red))) ; (green blue)
(define universe (make-enumeration '(red green blue red)))
(define select (enum-set-constructor universe))
((enum-set-indexer universe) 'green) ; 1
(enum-set->list (select '(blue red))) ; (red blue)
Canonical order follows each symbol's first appearance, and duplicate members
collapse. Every make-enumeration call and executed define-enumeration
declaration creates a distinct enumeration type. The syntax works at top level
and in bodies, validates member names during compilation, and preserves hygiene
through macros and library imports. Its constructor forms retain the type from
their declaration execution, including in escaping closures and continuations.
Union, intersection, and difference require the same type. Subset and equality
also work across types: subset requires both inclusion of the first universe
in the second universe and inclusion of its selected members. Equality therefore
requires equal universes as symbol sets, even for two empty member sets.
Projection uses the second argument's universe and type, regardless of which
members that argument selects. Enumeration sets are immutable, portable data
handles; generated indexer and constructor procedures belong to their VM like
other procedures. The indexer accepts any value and returns #f for anything
outside its universe.
Both frontends share these bindings. Vile syntax uses ordinary calls and tuple notation for the declaration's member list, including the trailing comma for a singleton list. No reader changes or separate enumeration grammar are needed:
define-enumeration(color, (red, green, blue), colors)
enum-set->list(colors(blue, red))
e := make-enumeration('(red, green, blue))
c := enum-set-constructor(e)
enum-set->list(c('(blue,)))
Runtime sets share explicitly owned universe/index metadata. Up to 64 members
fit in one set object's inline word; larger universes add a private word array.
Predicates and unchanged set operations allocate no result storage, and compiled
constructor syntax shares immutable precomputed membership words. Value retains
its existing size. Formatting emits opaque #<enum-set> text; use
enum-set->list for members. V hosts use VM.lookup / VM.call with the same
procedures and can pass sets between VMs while retaining normal region lifetimes.
scheme/testdata/generate_enumeration_sets.py creates 81 independent Python
integer/set fixtures across empty, small, and 63/64/65/127/128/129-member universes.
Tests also cover canonical order, cross-type universe semantics, malformed and
circular lists, macros, imports, shadowing, continuation reentry, GC, native host
calls, and repeated -gc none arena scopes. The arena allocation check measures
the operations directly after preparing arguments, excluding VM entry overhead.
Reference: R6RS enumeration library.
Hashtables
The runtime provides the selected R6RS hashtable procedures through both
frontends and the public VM.lookup / VM.call interface. (vile hashtables)
and (rnrs hashtables) are unversioned aliases for the same bindings; they do
not select a separate language mode.
make-eq-hashtable and make-eqv-hashtable use the existing dialect's eq? and
eqv? semantics. Both currently share the same comparison implementation;
separately allocated same-name symbols compare equal, exact and inexact numbers
remain distinct, and signed inexact zeros compare equal. make-hashtable takes
an explicit hash procedure and equivalence procedure. Hash results must be
non-negative exact integers of any supported size;
equivalence and update procedures return one value. All tables carry their
creating VM's ownership token, including copies and tables with builtin equality.
Keys and values share their payloads; callback procedures must belong to that VM.
The operations are hashtable?, hashtable-size, hashtable-ref,
hashtable-set!, hashtable-delete!, hashtable-contains?, hashtable-update!,
hashtable-copy, hashtable-clear!, hashtable-keys, and hashtable-entries.
Inspection uses hashtable-equivalence-function, hashtable-hash-function, and
hashtable-mutable?. Missing references use the supplied default. Entries returns
matching key/value vectors as two values, with unspecified order. Their containers
are independent snapshots. A copy is immutable unless its optional argument is
true; copied associations have independent storage and share key/value payloads.
Optional non-negative capacity hints are checked before native map-index narrowing.
Storage uses V's map[u64]int for bucket heads and an owned entry array. Deletion
clears both scanned handles before a slot is reused. Clear preserves reusable
storage unless a new capacity is requested; copying compacts live associations.
Ordinary eq/eqv lookups and replacements allocate no operation state. Custom
callbacks and update procedures run through an existing-machine bridge, sharing
parameters, winders, exits, continuation behavior, and instruction budgets.
Captured returns copy only fixed private progress state. A stale equivalence
candidate is searched again against current table contents. Each updater return
commits its returned value through a fresh lookup without rerunning the updater.
The standard purity precondition applies: hash/equivalence procedures and an updater must not mutate their target table, and structural/string keys must not change while stored. Custom-table mutations are diagnosed while one of that table's callbacks is active, including native reentry. Eq/eqv mutations remain free of callback-frame scans; updater purity there is a caller precondition. Fresh commit lookup protects storage even if that precondition is violated. A nonlocal escape discards active callback state without leaving a global busy flag.
equal-hash, string-hash, string-ci-hash, and symbol-hash are included.
String hashes follow their corresponding comparators' decoded rune streams;
case-insensitive hashing uses the same per-rune lowercase mapping. Structural
hashing follows equal?, including raw string bytes and opaque object identity.
Canonical big integers and rational components use the same sign/magnitude
word stream as small exact values, through immutable public-header views. Hashing
observes at most 2048 low u32 words per component while also encoding the full word
count; a cutoff marker distinguishes truncated streams. This bounds public bit
indices below 65536 and work independently of operand size. Large exact numbers
with the same sign, bit-length word count and observed prefix can collide.
Nonnegative hash callback integers reduce modulo 2^64 for the bucket index without
lossy host integer conversions. Existing small scalar hash paths still allocate
no buffers.
Pairs/vectors use deterministic ordered unfolding with 64 stack frames and a
1024-node visit cap. Sharing and cycle addresses never affect the result, so
coinductively equal cyclic graphs hash alike. Deep or long keys with identical
observed prefixes can collide; equivalence checks resolve collisions. Simple
keys and bounded structural traversal allocate no hash buffers. Long string and
bytevector leaves are still read in full. The host owns the entire runtime graph
when using an arena and must keep that region alive until all table values and
saved callbacks have finished; no per-table allocator or lifetime registry exists.
Reference: R6RS hashtables, chapter 13.
Specialized arithmetic
All 108 computational procedures from the corrected R6RS arithmetic libraries
share this dialect: 45 fixnum, 46 flonum and 17 exact-bitwise procedures. Import
(rnrs arithmetic fixnums), (rnrs arithmetic flonums), or
(rnrs arithmetic bitwise); matching (vile arithmetic ...) and concise
(vile fixnums) / (vile flonums) / (vile bitwise) collections refer to the
same pristine bindings. Imports are unversioned. Root shadowing preserves those
library and version 5 report-environment identities.
Fixnums are inline exact integers in[-2^63,2^63−1]; fixnum-width returns 64.
fx+, fx-, fx* and left shifts report overflow even though general arithmetic
promotes. Euclidean fxdiv/fxmod use a nonnegative remainder for either divisor
sign; centered fxdiv0/fxmod0 use[-|divisor|/2,|divisor|/2), including the
negative half tie. The three carry operations return the centered low signed word
and the signed carry satisfying total = low + 2^64 * carry. Their arithmetic
uses fixed words without temporary bignums; paired Scheme results use the
existing fresh multiple-value container.
Corrected fixnum domains matter: fxbit-set? accepts any nonnegative fixnum
index and sign-extends at 63 and above; fxcopy-bit accepts indices below 63.
Fields satisfy 0<=start<=end<64. Rotation counts may equal field width, including
zero-width/zero-count. Copy-field procedures copy the low source bits. Negative
bit counts are the complement of the count of the complemented input, rather
than the machine word population count.
Exact bitwise-* procedures accept canonical small and arbitrary-size exact
integers. They use infinite two's-complement semantics; arithmetic right shifts
of negative values round down. Inputs remain immutable. Small operations use
word kernels; large operations borrow public immutable math.big headers and
use its public APIs through signed adapters. Counts/indices never wrap or pass
through the lossy host .int() conversion. Storage-producing operations check
a portable storage ceiling of 2^31−2 result bits, reserving one bit so
mask/complement intermediates also remain within 2^31−1 bits. This ceiling
fits both the public u32 index API and 32-bit signed bit-length arithmetic;
the current compiler represents V int as 64 bits.
Requests beyond that representational limit report an error. Far bit queries,
huge right shifts, zero left shifts, and empty fields have their mathematical
results without allocating huge storage. Rotation reduces its nonnegative count
modulo field width. Reversing a large field uses a linear temporary byte buffer.
Flonum procedures require actual inexact .real values, including integer-valued
ones; exact inputs are rejected except by real->flonum / fixnum->flonum.
Rounding/transcendental functions operate directly on f64. Round uses ties to
even and preserves negative zero; division by signedzero follows IEEE infinity/
NaN behavior. Min/max propagate NaNs and choose−0/+0 respectively on zero ties.
fldiv families accept fractional flonums; boundary/large quotient cases fall
back to the existing exact engine to check mathematical representability.
When no representable pair meets the corrected division equations, these
procedures return NaNs. Numerator/denominator use binary64 decomposition,
including infinite denominators for subnormal ratios whose exact denominator
exceeds f64 range. real->flonum retains the existing shared conversion range
error when a finite exact input overflows; this is an explicit selected-dialect
limitation relative to the report's strongest closest-flonum wording.
The six R6RS no-infinity/no-NaN condition bindings are deferred with the broader condition hierarchy; this runtime represents infinities/NaNs and uses its existing located errors for argument/range failures. These selected collections do not introduce a new exception hierarchy or language profile.
The alt frontend shares these procedures. Its existing scanner splits embedded
+, * and / in names such as fx+ or fx+/carry; define a punctuation-safe
alias from Scheme or the host before calling those from alt source. Ordinary
names such as fx<=?, flfloor and bitwise-and work directly. Lexer/reader
rules are unchanged.
scheme/testdata/generate_arithmetic.py independently generates stored integer,
Fraction and binary64 fixtures; regenerate with Python 3. Focused tests include
all exports, errors, continuation/native reentry, allocation and owned regions.
Reference: corrected R6RS arithmetic
and official errata.
List utilities and sorting
The runtime provides find, memp, assp, for-all, exists, filter,
partition, remp, remove, remv, remq, fold-left, fold-right, cons*,
list-sort, vector-sort, and vector-sort!. They are ordinary procedures in
both frontends, callable through VM.lookup / VM.call too.
find returns the matching element, memp the matching tail, and assp the
matching association pair. Searches and multi-list predicates inspect only the
prefix needed to obtain the answer. Existing member, assoc, and their
eq?/eqv? variants follow that consumed-prefix rule too. Invalid tails after
an early match do not cause an error. Misses still validate the traversed chain,
and circular misses are diagnosed. Custom-search input-spine mutation remains
an error when detected.
for-all returns #f on the first false predicate result, or the final result;
exists returns the first true result or #f. Empty inputs return #t and #f
respectively. Lists must have equal lengths where traversal reaches their ends.
Their final predicate calls are proper tail calls. Other callback positions
require a single value. Predicates/combiners must not mutate input list structure.
filter/remp preserve input order and share element values, with independent
result spines. partition returns the selected and rejected lists as two values.
fold-left passes the accumulator first and traverses left to right;
fold-right passes it last and combines from right to left. Full traversals
require proper lists of equal length. cons* links all but its last argument
into a fresh pair chain ending at that argument; one argument is returned directly.
Sort comparators accept two elements and provide a strict ordering. All three
sorts are stable and perform O(n log n) comparisons. Non-destructive forms
preserve the input and share element payloads. Trivial list sorts may return
the original list. vector-sort! requires a mutable vector and commits its own
changes only after comparisons complete, returning unspecified.
Callbacks run on the calling machine, sharing instruction budgets, dynamic parameters, winders, and nonlocal control. Native reentry, exit requests, and saved continuations retain the same contracts as other callbacks. Earlier non-destructive results are not changed by later continuation returns. Sorts reuse two arrays on the ordinary path; captured comparisons use frozen prefixes and persistent suffixes rather than cloning whole arrays on each return. Left folds keep bounded driver storage; right folds retain an input snapshot.
(vile lists) and (rnrs lists) are aliases for the selected list binding
collection, as are (vile sorting) and (rnrs sorting) for sorting. They
share pristine binding identities and use the same R7RS-small import machinery.
Versioned R6RS imports and separate standards modes are outside this dialect.
cons* needs the callable-alias spelling shown in the top-level README for Vile
syntax; source/reader grammar remains unchanged.
Independent stable-order fixtures come from Python's sort:
scheme/testdata/generate_list_sort.py regenerates list_sort.tsv. Tests cover
both directions, all three sort procedures, duplicate-key stability and element
identity. bench/list_allocations.v reports allocation totals without timings.
References: R6RS list procedures, sorting.
Formatting shared data
scheme.write(value)!string and scheme.display(value)!string format cyclic
pairs/vectors using datum labels. scheme.write_shared(value)!string preserves
acyclic pair/vector sharing too, and scheme.write_simple(value)!string rejects cycles and
never emits labels. These return owned text; mutations of the formatted values
do not change previously returned strings.
Scheme write-shared / write-simple accept the same optional textual output
port as write, including current-port parameterization and borrowed V writers.
Labels are local to each formatting call. Shared list tails use dotted notation
where a definition/reference is needed. Records remain opaque, so self-references
inside records are not traversed.
Ordinary write/display keep the existing traversal for acyclic values. A cycle
retries through a graph scan and labeled emission; write-shared starts with the
graph scan. Flat list tails iterate in both passes, without a copied array of
children. Nested data retains the existing 512-level printing limit. Source and
port readers accept the resulting labels; shared strings/bytevectors are also
preserved by write-shared.
The optional independent identity/cycle check uses Guile's SRFI-38 reader:
python3 scheme/testdata/check_shared_print.py ./vile
bench/print_allocations.v compares ordinary acyclic formatting allocations
without timing. Its warm-up and source evaluation happen before measurement.
Port positions
port-has-port-position?, port-position, port-has-set-port-position!?, and
set-port-position! are available in the default environment and the selected
(vile io ports) / (rnrs io ports) collections. They support memory ports,
owned seekable files, and capable V host Readers/Writers. Closed-port capability
queries return false; position operations validate ownership, open state, and
reentry before using the resource.
Binary positions are nonnegative byte offsets. Lookahead leaves the logical position unchanged. Input getters subtract unread buffered bytes; output getters include pending writes. Output seeking flushes first. Sparse binary memory output does not reserve or extend storage until a nonempty write; intervening bytes are zero-filled when the write extends the buffer.
Textual positions are opaque, port-specific Value tokens. Retain the returned
token and pass it back to the same port. Input tokens preserve case directives
and source coordinates, including CRLF state. Memory string output tokens denote
character coordinates; restoring a token after earlier Unicode widths change
still addresses the same character position. Overwrites replace characters and
preserve the remaining suffix. get-output-string and get-output-bytevector
continue to return independent snapshots of all accumulated data.
mut vm := scheme.new()
input := vm.open_input_bytevector(scheme.bytevector([u8(10), 20]))!
saved := vm.port_position(input)!
assert vm.read_u8(input)!.as_integer()! == 10
vm.set_port_position(input, saved)!
assert vm.read_u8(input)!.as_integer()! == 10
A borrowed host Reader or Writer may implement PortPositionGetter with
port_position() !i64, PortPositionSetter with set_port_position(i64) !, or
both. These methods describe its underlying byte cursor, including buffering it
owns. Vile adjusts only its own buffer. The methods follow the synchronous
Reader/Writer lifetime rules and run with the port's reentry guard active.
Buffered input is cleared only after a successful setter; a failed host setter
must preserve its own cursor if subsequent reads are to continue from that point.
Seek support retains the single memory-input snapshot until the port closes. Streaming input buffers continue to release large completed frames. Tokens use ordinary result allocation; the host must retain their allocator while using them.
System interfaces
command-line, get-environment-variable, and get-environment-variables
provide process context. Argument strings and environment strings are immutable;
the environment alist and its entry pairs are immutable too. Each command-line
call returns a fresh list spine. Missing environment variables return #f, while
an empty value returns "". System text must be valid UTF-8, and OS names/paths
must not contain NUL bytes.
V hosts can supply independent snapshots instead of process arguments or the live OS environment. Arrays, maps, keys, and values are copied at VM construction; explicitly empty overrides remain empty:
mut vm := scheme.new_with_options(scheme.Options{
arguments: ['my-program', 'input.dat']
environment: {'MODE': 'test'}
}) or { panic(err) }
file-exists? and delete-file resolve paths against the process directory, as
file ports do. delete-file returns unspecified and fails if deletion fails.
current-jiffy returns an exact monotonic nanosecond count from a fixed per-VM
epoch; jiffies-per-second is 1000000000. current-second returns inexact TAI
seconds using the OS TAI clock where available, or UTC plus 37 seconds otherwise.
Options.tai_utc_offset supplies a finite UTC offset explicitly, overriding the
OS TAI clock. The UTC approximation requires updating when leap seconds change.
exit runs outstanding Scheme winders from inner to outer before requesting
termination. emergency-exit skips them. Both abandon their Scheme continuation.
Omitted status and #t mean 0, #f means 1, and an exact integer is preserved as
the requested status. Other status types are errors in this dialect.
By default, neither procedure terminates the V process: evaluation returns a
scheme.ExitRequest carrying status and emergency. Native callbacks must
propagate it, just like continuation transfers; scheme.is_control_transfer(err)
recognizes both. A host may catch the request and continue using the VM. Returning
to the host releases private file extents even for emergency requests; it does
not invoke skipped user Scheme winders.
Options.exit_handler accepts a function of type
fn (mut scheme.VM, scheme.ExitRequest) !. Normal exit closes managed file
extents after winding completes, then invokes the hook. An after procedure that
cancels the pending exit leaves call-with-file/port resources open for resumption.
Custom ports managed by call-with-port close on the exiting Scheme machine.
Closer continuations retain the remaining cleanup and exit hook; replay does
not repeat a physical close already attempted. A closer's exit can supersede
the status while retaining outer managed resources. Ordinary close errors allow
the remaining cleanup to finish with the original status. Host cancellation,
arena-limit requests, and exhausted execution budgets still abort evaluation.
Emergency exit invokes the hook immediately. A returning hook is followed by the typed
request, never by a return to the calling Scheme expression. Hooks may reenter
the VM and propagate continuation transfers or errors. A continuation jump from
an after procedure can cancel a pending exit; saved continuations can also resume
exit winding later. Existing execution budgets remain in force while winding.
The CLI explicitly uses exit_handler: scheme.terminate_process. V hosts can opt
into the same behavior. It calls OS exit normally and _Exit/_exit for an
emergency, using the low eight bits of integer statuses. Emergency termination
therefore skips V cleanup and buffered-output flushing. Close or flush file ports
explicitly when their lifetime extends beyond a managed file extent.
The procedures are also exported by (scheme process-context), (scheme file),
and (scheme time), as applicable. See the
R7RS system interface.
Native functions
import scheme
fn double(mut vm scheme.VM, args []scheme.Value) !scheme.Value {
scheme.check_arity('double', args.len, 1, 1)!
plus := vm.lookup('+')!
return vm.call(plus, [args[0], args[0]])
}
fn main() {
mut vm := scheme.new()
vm.register('double', double) or { panic(err) }
value := vm.eval('(double 21)') or { panic(err) }
println(value.as_integer() or { panic(err) }) // 42
}
Native callbacks can capture V state, return ordinary V errors, and reenter the
same VM through eval or call. Clone the argument array if retaining its
container; individual Value handles can be retained directly. Execution registers and continuation frames
belong to each invocation, so a nested evaluation preserves its caller's state.
Errors from native callbacks are located at their Scheme call sites. An error
already located in a nested Scheme evaluation keeps its original location.
A native producer can return scheme.values(items), which copies the item
container; a single item returns directly and zero results need no heap box.
call-with-values invokes native and Scheme producers on the same machine and
tail-calls the consumer with their results.
Continuations can be retained by V hosts and invoked repeatedly in later
eval/call entries. They capture Scheme execution state, not V stack frames.
An escape to a still-active Scheme invocation unwinds reentrant V callbacks via
a control-transfer error. Propagate it unchanged; ! already does this. A
callback that handles errors itself can recognize it with
scheme.is_control_transfer(err). Continuations belong to their creating VM.
Each reentrant eval/call starts its own Scheme continuation and wind stack.
An escape to an active parent entry runs the inner entry's exit callbacks before
propagating control to the parent. V callback frames are not captured or replayed.
The standard I/O procedures use ports. A host can select its own Reader/Writer
without replacing Scheme procedures; display, write, and newline also
accept an explicit port.
Run the complete example with:
v -cc gcc run examples/embed
It prints 5050, 42, and 5/6 on separate lines.
Ports and host I/O
VM.input_port(reader, read_size: 4096, binary: false)!Value and
VM.output_port(writer, binary: false)!Value borrow V io.Reader/io.Writer
resources. Set binary: true to expose raw byte I/O. Both default to textual
UTF-8; input/output direction and textual/binary mode are checked before I/O.
Use set_input_port/set_output_port/set_error_port to select current ports;
the initial defaults share the process's C stdin/stdout/stderr streams and are
created lazily. current-input-port, current-output-port, and
current-error-port are parameter objects. Their Scheme setters and the V host
setters update the same visible dynamic location; outside evaluation they update
the default. parameterize restores selections on return, errors, and continuation
transfers, including nested host evaluation. Rebinding a public procedure name
does not change which canonical parameter implicit I/O uses.
Closing a borrowed port invalidates its Scheme wrapper and releases the host interface; it does not close the host resource. Ports belong to their creating VM, including when passed explicitly.
A Reader must consume the borrowed destination during read, without retaining
it, resizing it, or reentering an operation on that port. Short reads work;
zero or io.Eof/os.Eof means permanent EOF. Set read_size: 1 for an interactive
Reader that waits for its entire requested buffer. A Writer must consume its
borrowed bytes before returning. Positive short writes are retried; invalid
counts are errors. A callback may reenter the VM using another port. Propagate
control-transfer errors unchanged, just as with other native callbacks.
open-input-string snapshots its input into one owned read buffer.
open-output-string accumulates bytes, and get-output-string returns an
independent mutable snapshot, also available after closing the port. The public
V methods are open_input_string(text)!Value, open_output_string()!Value, and
get_output_string(port)!Value. String ports support the ordinary character and
datum operations. port?, textual-port?, binary-port?, the two
*-port-open? predicates, and close-port expose port state. Modes remain
observable after close. Input and output ports each have a single mode.
read-line recognizes LF, CR, and CRLF without including the terminator.
read-string counts Unicode characters, returns a shorter string at EOF, and
returns an empty string for a zero count without requesting input. write-string
accepts optional character ranges. These share the same cursor as read and
read-char. V hosts can use read_line(port)!Value and
read_string(port, count)!Value.
flush-output-port and VM.flush_output_port(port)! flush owned file buffers
and standard streams without closing them. Host Writers can implement
scheme.OutputFlusher with flush()!; explicit flush and close call this
capability and propagate failures. A Writer without it has no Vile-owned pending
bytes, so explicit flush is a no-op. Busy-port guards also apply during flushing.
Bytevectors and binary I/O
scheme.bytevector(bytes) copies the live bytes of a V array;
Value.bytevector_items()![]u8 returns an independent copy. Scheme bytevectors
use fixed byte storage, support structural equal?, and print as #u8(...).
Constructors and bytevector-copy/bytevector-append produce mutable values;
bytevector-copy! handles overlapping ranges without temporary storage.
Snapshots copy live bytes rather than spare array capacity. string->utf8
indexes characters, utf8->string indexes bytes, and both validate the selected
UTF-8 range. Both frontends accept immutable #u8(...) / #vu8(...) literals;
port reads construct mutable bytevectors from the same notation.
open_input_bytevector(value)!Value snapshots a bytevector into a binary input
port. open_output_bytevector()!Value accumulates raw bytes, and
get_output_bytevector(port)!Value returns an independent snapshot, also after
close. open_binary_input_file(path)!Value and
open_binary_output_file(path)!Value use the same descriptor ownership,
buffering, flushing, finalization, and call-with-port rules as textual files.
V hosts can call read_u8(port)!Value, peek_u8(port)!Value,
u8_ready(port)!bool, read_bytevector(port, count)!Value,
read_bytevector_into(port, target, start, end)!Value,
write_u8(port, byte)!, and write_bytevector(port, source, start, end)!.
Read results are byte integers, bytevectors, or EOF as appropriate;
read_bytevector_into returns the number written or EOF. Empty ranges/counts
return zero/empty bytevectors without requesting input, but still validate port
mode, openness, ownership, and destination mutability. Fresh-result reads grow
with bytes actually received instead of allocating an arbitrary requested count.
read-bytevector! drains existing lookahead, then borrows the final bytevector's
storage directly for Reader calls, respecting read_size. Writers borrow source
ranges directly and retry positive short writes. Neither operation resizes a
Scheme bytevector. The same synchronous borrowing, reentry, and control-transfer
contracts apply as for text I/O. u8-ready? uses the optional ReadyReader
capability and becomes true after one available byte, regardless of encoding.
On POSIX, owned binary files support this protocol. Initial standard input is
textual. Current ports can be rebound to binary ports with ordinary parameterize.
Public read, read_char, peek_char, and char_ready methods operate on a
port handle and share one cursor. read frames one complete datum, then uses the
canonical lexer/reader. Plain standalone numbers and ASCII names retain an
arena-free shortcut; escaped/barred/Unicode names use canonical decoding.
Read data is mutable and owns its decoded storage. Long frames release oversized
buffers after conversion. scheme.write(value)!string and
scheme.display(value)!string format values without performing I/O. Port
display borrows direct string bytes and encodes characters on the stack; a
short-writing host callback can trigger GC without invalidating that borrow.
On POSIX, char-ready? supports standard input and owned files, including partial
UTF-8 arriving through a pipe. It preserves C stdio read-ahead on stdin and
restores descriptor flags before returning. Hosts must serialize access to the
same input resource. A custom Reader can implement scheme.ReadyReader:
read_ready(mut bytes []u8)!int must not wait, returning -1 when temporarily
unavailable, 0 at EOF, or a positive byte count. Without this capability, readiness
can answer from complete buffered characters or known EOF; otherwise it reports
an unsupported-operation error. Nonblocking file readiness is currently unsupported
on Windows.
open-input-file/open-output-file and their public V methods own descriptors.
Files use binary mode and UTF-8 characters; output creation truncates an existing
file. Owned input uses short descriptor reads, and owned output batches small
writes in a lazy 4 KiB buffer. Closing output flushes it, reports write failures,
and closes the descriptor even if flushing fails. Boehm also registers a
best-effort finalizer for otherwise unreachable owned files; explicit close is
the deterministic resource boundary.
call-with-port and call-with-input-file/call-with-output-file close after the callback actually
returns, preserving all its values. A continuation escape keeps that port open
so resumption can use it. The optional with-input-from-file/with-output-to-file
restore the enclosing default and close on every exit; resuming one may select
its already closed port. File redirection uses the same parameter locations as
parameterize; captured mutations survive reentry, and enclosing locations are
restored on exit. Ordinary runtime errors restore file-controller selections and close their
files at the host entry boundary; this cleanup does not invoke Scheme
dynamic-wind callbacks. Nested host entry cleanup preserves its parent's ports.
Records
define-record-type supports the existing R7RS form and the selected
R6RS record syntax and procedures
in both frontends and the combined report/null environments. The R7RS form has
an explicit constructor list and predicate identifier; constructor fields may be
a reordered subset, with omitted fields initially unspecified. Its duplicate
field, binding and constructor-field checks are unchanged. The R6RS form has a
type identifier or (type constructor predicate) name specification followed by
clauses. It supports field abbreviations and explicit operation names, inheritance,
protocols, sealed, opaque, both nongenerative forms, and parent-rtd.
Duplicate R6RS field names are allowed when the generated bindings are distinct.
Shorthand names inherit the type identifier's hygienic context.
The unversioned (rnrs records procedural), (rnrs records inspection) and
(rnrs records syntactic) libraries, and corresponding (vile records ...)
aliases, expose the selected report interfaces: seven procedural operations,
ten inspection operations, and three main syntax forms plus nine auxiliary
keywords. Prefix/rename imports preserve clause identity. Canonical clause words
are accepted when unbound in the combined dialect; ordinary variables with
those names still work outside clauses and shadow direct clause uses. The
syntactic descriptor queries identify the actual local/global definition binding,
including renamed imports and separate definitions with the same nongenerative
UID. They do not use a printable-name registry.
Generative declarations create a fresh descriptor on each execution. A compatible nongenerative UID reuses its descriptor within a VM; incompatible declarations fail. An omitted UID has one detached token per expanded occurrence, with its public symbol materialized on first execution. Plain source recompilation and compiled continuation replay preserve that token; a genuinely new transformer expansion creates fresh occurrences. The VM retains reader-occurrence tokens and claimed UID descriptors until VM/arena release. Generated staged occurrences carry only token handles in a lazy sidecar, which compiled code discards after emission. No compiler Scope or source graph enters these registries.
Each R6RS definition has its own constructor descriptor and protocol, even when
its RTD is shared. Protocol callbacks run on the existing machine: a child's
n captures parent arguments and returns p; calling p prepares and invokes
the parent protocol. The base initializer allocates the final descendant record
with all descendant fields initialized, so parent protocols can inspect/mutate
it. Captures before allocation replay with new records; captures after allocation
share the existing record and its field locations. Native reentry follows the
VM's existing host-entry boundaries, cancellation, exit and file-cleanup rules.
An R7RS declaration keeps its original constructor; its canonical default R6RS
constructor descriptor is cached lazily only when queried or used as a parent.
Record headers and fixed-size fields share one scanned allocation. Accessors,
mutators and predicates keep private descriptor/index data and operate on matching
descendants without argument copies, activations, field-name lookup or allocation.
Inspection field-name vectors are immutable and contain only a type's own fields.
Opaque records reject Scheme record-rtd and return false from record?; explicit
type predicates and operations remain usable. Records and descriptors compare by
identity and print opaquely. Plain RTDs/records are portable between VMs;
constructor descriptors, protocols and generated operations enforce VM ownership.
Cold compiler metadata associates definition locations and introduction contexts. Introduced alias keys use an existing unique expansion-family prefix plus the canonical raw name. Family prefixes borrow their existing key storage; ordinary alias and frozen-identifier layouts remain unchanged. First-level source freezing keeps a nil context sidecar. Only non-default contexts create temporary interning maps and a detached tree-local integer sidecar, preserving distinct introduced families and foreign use-site scopes without retaining compiler scopes. A tree adds one optional pointer; private keys are longer, with no alias-map clone or retained expansion graph.
V hosts can inspect Value.record_type()!Value,
Value.record_type_name()!string (on a descriptor),
Value.record_field_names()![]string (on a descriptor), and
Value.record_fields()![]Value. Host field snapshots include inherited fields
in ancestor-first order. Names and containers are copied; compound field handles
remain shared. These snapshots cannot resize records or replace immutable fields.
Use VM.call with generated procedures for normal type-checked operations.
Staged top-level macro output can define a private name after a function referring to it was compiled. Deferred global references retain that identifier's identity, cache a definition-site fallback until a private binding appears. When that binding belongs to the executing namespace, they become ordinary global instructions and release their temporary metadata. Cross-namespace references retain their origin and cached slot. Compilers borrow the VM and global name table only while compiling; compiled functions and staged drivers release those borrows.
Scheme eval and environments
Scheme eval accepts a datum and an environment specifier. For example,
(eval '(* 6 7) (scheme-report-environment 5)) returns 42.
scheme-report-environment has the pristine standard bindings even after a
program replaces root variables or syntax names. null-environment has syntax
and no variable bindings. Both are immutable, cached environments; global
assignment and definitions there are errors. Lexical bindings and internal
definitions work normally. interaction-environment selects this VM's mutable
root environment, where evaluated definitions persist.
For V hosts, report_environment(5), null_environment(5), and
interaction_environment() return specifiers for eval_value(datum, specifier).
Specifiers belong to their creating VM. The returned procedures can be called
normally through VM.call or Scheme. Runtime symbol names retain their case;
source names follow the selected reader case state. Empty and NUL-containing
source identifiers use an internal key encoding that keeps them distinct from
private compiler names; their public symbol spelling is unchanged.
Datum evaluation constructs compiler syntax directly, without formatting or reparsing. A single identity/state table preserves shared/cyclic literal data; context-aware guards reject circular executable syntax. Flat list conversion iterates and nested syntax has a checked limit of 512. Compiled procedures discard their generated syntax; staged top-level groups retain the forms that still need compilation. Macro lookup borrows the VM's binding table during compilation and uses a private overlay for new definitions, avoiding a whole-table copy for every form. Emitted procedures release that view. Immutable report/null specifier caches avoid accumulating a fresh global environment on every call. Pristine standard values are saved lazily when a root binding is first replaced.
Scheme eval runs through a private bytecode bridge on its caller's existing
machine. Tail calls, multiple values, continuations, dynamic extents, and execution
budgets therefore include the surrounding Scheme computation. The public V
eval_value method starts a host entry, like eval(source), so it does not
capture V callback stack frames.
Isolated namespaces for V hosts
new_environment() creates a mutable namespace with the core syntax and no
procedure bindings. Use import_bindings(into, from, names) to import selected
bindings; the map keys are source names and the values are destination names.
Both environment specifiers must belong to the same VM. For example:
mut vm := scheme.new()
root := vm.interaction_environment()!
state := vm.new_environment()!
vm.import_bindings(state, root, { '+': 'add' })!
vm.eval_in('(define counter 40) (define (next) (set! counter (add counter 1)) counter)', state)!
next := vm.lookup_in(state, 'next')!
assert vm.call(next, [])!.as_integer()! == 41
eval_in(source, environment), eval_alt_in(source, environment), and
eval_file_in(path, environment) select a namespace for source evaluation.
File evaluation detects .vile / .scm and retains diagnostic paths.
define_in(environment, name, value) and lookup_in(environment, name) are the
corresponding host binding operations. Existing eval_value and Scheme eval
also accept these specifiers. The ordinary root entry points keep their existing
behavior. Namespace entries share the VM's parameter and continuation rules.
Variable imports alias the same stable location: changes made by the source namespace are visible through every imported name. Imported names cannot be assigned or redefined by Scheme or host binding APIs; mutating the data held in an imported binding remains possible. Conflicting imports and invalid names reject the entire batch before changing the destination. Identical imports can be repeated. Imported syntax can be renamed and re-exported; private globals, macro literals, nested generated macros, and generated definitions preserve their binding identities across namespace boundaries.
These namespaces are persistent VM state. Their global slots are retained for the VM's lifetime; namespace unloading is not implemented.
Libraries
define-library registers a named library with export, import, begin,
include, include-ci, include-library-declarations, and cond-expand declarations. Its body runs on first import, after all dependencies initialize.
Library namespaces start empty and receive syntax and procedures through their
imports. Both frontends use the same registry and binding locations. Definitions
with duplicate library names are errors; scheme and (vile base) are reserved.
only, except, prefix, and parallel rename import sets compose inside out.
Identical repeated imports are permitted; conflicting bindings reject the whole
destination import batch. Library initializers can have effects before a later
import validation error. Root source imports can replace existing interaction
bindings. Older compiled references and macro literals retain their original
locations; ordinary redefinition updates the current location. Imported names
are protected after import, including in the interaction environment. The V
import_bindings API additionally rejects conflicts with existing destination names.
File lookup maps (example state 1) to example/state/1 plus .sld, .scm, or
.vile, in that order. Search uses the caller's directory, the library root
that discovered its source file, paths added by VM.add_library_path(path)!,
and the process directory. Identifier components preserve ASCII letters, digits,
-, and _; other bytes are percent-encoded using lowercase hexadecimal.
A leading digit in an identifier is encoded to distinguish
it from an integer component. Lookup never changes the process directory.
Files loaded as libraries contain only define-library declarations, and their
complete declaration batch is validated before registration.
The corrected R7RS export catalogs select implemented bindings from the pristine
report namespace. Missing facilities remain on the checklist, and a standard
library with no implemented exports is unavailable. (vile base) exports all
installed procedures and shared syntax.
Scheme environment accepts quoted import sets, for example
(environment '(scheme base) '(only (scheme write) write)). It returns an
immutable specifier for eval, with only the imported bindings. The V equivalent
is VM.environment(import_sets []Value)!Value; ordinary datum values specify
the import sets. eval_in, eval_alt_in, eval_file_in, and eval_value accept
these specifiers. The version-5 report/null environment APIs retain their behavior.
(rnrs eval) and (vile eval) expose the same pristine eval and environment
procedures as (scheme eval). These unversioned aliases select a useful R6RS
API without introducing another evaluator or dialect. Import-set transformations,
read-only imported bindings, user libraries, continuations, multiple values, and
host ownership retain the shared machinery. The R5RS environment-specifier API
remains available. Library syntax and imports follow R7RS-small; no R6RS
library forms, versioned references, or expansion/run phase declarations are
planned. Failures use Vile's existing host errors.
Initialization uses private bytecode drivers and ordinary dynamic extents on the calling machine. Instruction and macro budgets, dynamic parameters, native reentry, and continuations include the library computation. Dependency graph planning is iterative and detects cycles before any new initializer runs. An initializer escaped by a continuation is suspended until its saved continuation resumes. A host error marks an unfinished initializer failed; unrelated work in the VM remains usable, and a saved continuation can resume it. Repeated continuation reentry retains the same library locations. Completed instances release their initializer and declaration templates. Persistent variable exports store only names and slots; syntax exports retain the context needed for hygiene.
Source inclusion and conditional expansion
(include "file.scm" ...) replaces itself with the files' forms in textual order,
using the surrounding lexical scope. It works at top level, in definition bodies,
and in expression positions; definitions still require a definition context.
Top-level forms remain staged, so an included macro is available to subsequent
forms. Empty inclusions return an unspecified value; the final included expression
preserves tail calls and multiple values. Continuations resume the saved position
without repeating earlier forms.
VM.add_include_path(path)! adds an owned absolute search directory, ignoring
repeated paths. Lookup tries the containing source directory, host include paths,
then the process directory. Absolute names bypass the search list. .vile files
select Vile syntax; other suffixes select Scheme. include-ci uses folded
identifiers initially, matching the shared dialect's default. Directives within
each included source can change its subsequent reader state. Strings and source
positions are not rewritten.
Active ancestry checks reject cycles, including symbolic-link aliases. Static
inclusions and conditional expansions count toward max_expansions, including
library declarations parsed during dependency resolution.
Library include/include-ci declarations add body forms. The
include-library-declarations form splices declaration files instead, allowing
shared import/export clauses. cond-expand selects either body forms or library
declarations according to its context. Included import sets retain both their
own source directory and the containing library's discovery root.
cond-expand evaluates feature requirements statically: an identifier, (and ...),
(or ...), (not requirement), or (library (name ...)). Boolean combinations
short-circuit. The first matching clause is selected; a final else is optional.
Unselected forms are not expanded or included. Feature identifiers are independent
of variable values, while the outer cond-expand keyword remains shadowable.
Library requirements test registered or discoverable declarations without
publishing or initializing discovered user libraries. Imports subsequently
validate dependencies, exports, and initialization.
(features) returns a cached immutable list shared within the VM. It contains
vile, vile-0.0.0, ieee-float, and supported OS/architecture identifiers.
Complete-report and unbounded-arithmetic flags are not advertised. Replacing
the public features binding does not change static feature selection.
See R7RS feature identifiers.
Included documents keep their original reader arenas. A lazy compiler registry assigns disjoint positive node ranges and translates links into those arenas; it copies no reader cells. Staging and library templates share this registry. Instructions retain their existing 32-bit origin field; cold error and relative-path lookups recover the originating document. Compilation errors retain concrete filename/line diagnostics even after expansion scratch is discarded. Ordinary execution has no per-inclusion dispatch or allocation.
Values and lifetime
VM.eval(source)!Valueparses the entire input first, then evaluates forms in order. It returns the last result; empty input yields an unspecified value.Value.as_values()copies the result container for zero, one, or several results. An ordinary value represents a single result without boxing. Definitions persist between calls. A later evaluation error does not roll back forms already evaluated. Reader/UTF-8 failure prevents any evaluation. Invalid executable subforms compile to failure instructions, preserving short-circuit behavior and errors only in branches that actually execute.VM.define(name, value)!andVM.lookup(name)!Valueaccess global bindings. Names are complete source identifiers, normalized by the reader.VM.call(procedure, args)!Valuecalls a procedure using V values directly. Procedures belong to their creating VM. Independent VMs have independent globals; executing a foreign procedure returns an error. Data values can be deliberately passed between VMs. Shared mutable data requires synchronization if those VMs run concurrently.- Values are copyable, GC-traced 16-byte handles on this 64-bit build, with
inline scalars. A tag selects one integer, float, or ordinary pointer in a
union. Pair payloads occupy 32 bytes. Constructors cover
booleans, exact integers/rationals, inexact reals, Unicode characters,
strings, symbols, pairs, lists and vectors.
Value{}is unspecified. - Pairs, vectors and strings have shared mutable locations. Literal compound
objects and strings returned by
symbol->stringreject mutation.as_string,symbol_name,vector_itemsandlist_itemsreturn independent containers; elements of copied containers still share their payloads. evalretains its own copy of source used by closures. A host can release its original source after the call. Returned values and closures remain live through their handles; a VM does not retain every temporary result forever.scheme.write(value)!stringprints a value. Flat lists print iteratively; nested data has a checked printing limit of 512. Cyclic pairs and vectors use datum labels; shared acyclic substructures print normally.write_sharedlabels acyclic sharing too, whilewrite_simplerejects cycles. Procedures and unspecified values have diagnostic representations rather than readable literals.
One VM is used serially. Use independent VMs per thread or synchronize access.
Evaluator and current language scope
The compiler emits fixed-width 16-byte instructions with constant pools and
source locations. Local variables resolve once to (lexical depth, slot)
addresses. Parameters, internal definitions, and binding forms use contiguous
value arrays, with no per-environment hash maps. Global instructions cache stable indices into
a VM-owned value array. Known locations resolve during compilation; forward
references resolve on first use. Resolved assignments use direct cached slots.
Redefinition updates the existing slot, so
Scheme and native hosts can replace bindings without invalidating compiled code.
Indices remain valid when the global value array grows.
Local name maps are compilation scratch; compiled functions keep only a slot
count, rather than retaining a second array of parameter and binding names.
Arguments and intermediate values share one privately owned operand stack.
Pushing into available capacity writes a Value directly; growth uses the normal
array allocation path. Primitive results overwrite their callable's existing
slot, while discarded argument slots are cleared. Primitives borrow
an argument view; a closure call copies arguments directly into its local slots.
Only non-tail Scheme calls push a 32-byte return frame on this 64-bit build.
Tail calls replace function/environment registers and reuse the current operand
stack segment. Direct, mutual, named-let, and apply tail calls are tested
through 100,000 iterations with at most 16 return frames. Dead stack handles and
return frames are cleared so unused capacity does not retain GC objects.
The compiler propagates capture requirements through nested functions. A procedure that needs no enclosing bindings shares a VM-owned procedure object and retains no unused scope; an empty activation with no capture needs no environment object. Creating a capturing closure marks its environment as escaped. Tail calls can reuse an unescaped activation with the same slot count. On return, the machine can cache up to 32 small unescaped activations, partitioned by slot count (0..7), for later calls. It clears their old values and uses the inactive parent field only as a free-list link. Captured environments stay distinct and GC-managed, preserving lexical mutation and closures retained by V hosts. Code that creates escaping closures still allocates their environments; this is not general escape analysis.
Common two-integer primitive calls bypass argument-array views and variadic folding, retaining exact arithmetic and overflow checks. Trusted instructions and private stack ranges use direct array access; user-provided types, vector indices, arity, VM ownership, and execution budgets remain checked. Lexical parent traversal and generic calls still have runtime costs. The runtime has no JIT. Control bridges retain separate, bounded source metadata for errors while keeping return frames at 32 bytes. Continuations mark every captured activation as escaped before retaining execution state, including caller frames without lexical closures. Multi-shot invocation restores the live operand prefix and return frames into private buffers, preserving captured binding locations while reusing buffer capacity. Jumps keep the current step count, so they cannot reset an invocation budget.
Integer addition/subtraction, multiplication, negation, and comparison have
checked direct paths. Rationals retain their general normalization and exact
comparison paths. length and list? scan with constant scratch space and
detect circular lists. Strings cache their character count, making string-length
constant time. ASCII indexing is constant time; other UTF-8 indexing scans to the
requested character without a temporary rune array. Character replacement writes
in place when its encoded width stays the same and copies the buffer once when
the width changes. Exported host strings are independent copies.
Implemented forms: quote, if, begin, lambda, procedure/variable define,
set!, let, named let, let*, letrec, and, or, case, do,
quasiquote, delay, delay-force, define-record-type, and cond, including
test-only clauses and => receivers. Closures capture lexical bindings, including
assignment. Lambda parameters can be fixed, dotted, or a rest-only identifier.
Operand evaluation currently proceeds left to right. do installs step values
in parallel and preserves distinct iteration bindings when closures escape.
Quasiquote supports nested unquotes, list/vector splicing, and dotted tails;
static templates and suffixes remain constants. Vector splicing allocates the
result array directly.
Primitives include arithmetic/comparisons, apply, mutable pairs/vectors,
values, call-with-values, call-with-current-continuation (call/cc),
dynamic-wind, force, promise?, make-promise, make-parameter, map, for-each,
composed pair accessors, list searches/conversions,
Unicode character predicates
and comparisons, mutable strings, substrings, case-insensitive string comparisons,
symbol conversions, equality and type predicates. Structural equality handles
cyclic mutable graphs.
Promises evaluate lazily, memoize the first completed result even under recursive
forcing, and release their thunk and captured scope after completion.
delay-force expects a promise and flattens forcing chains iteratively on the
existing force bridge. Promises use one allocation each; union by rank and
iterative path compression keep shared aliases attached to the winning state
without retaining a chain of pending continuations. Retired states clear their
thunk and environment, and reuse the result payload for the forwarding link;
the flags and rank fit existing padding, preserving the original object size.
Saved continuations keep the original thunk's
finish action in immutable bytecode, even when its shared state has advanced to
a different kind of thunk. make-promise evaluates its argument eagerly and
returns an existing promise unchanged. Promises retain VM ownership; forcing a
promise from a different VM reports an error. force requires a promise and
passes through zero or multiple memoized values as an extension.
Iteration uses advancing list cursors; captured continuations preserve private iteration
state, and partial mapped results remain safe across repeated reentry.
List, vector, and string iteration stop at the shortest input. Circular list
inputs are permitted when another input is finite. Vector/string mapping
preallocates result storage and passes callback arguments directly on the value
stack. Once a continuation captures an iteration, the filled prefix stays frozen
and later results use a persistent suffix; returning through captured callbacks
does not clone the whole result buffer at each step. Final results remain fresh
and independent across reentry. String cursors advance by UTF-8 byte offsets;
mutation revisions trigger a character-index rescan only after an input changes.
The revisions also cover edits made before a saved callback is resumed.
Mapped character output reserves its exact UTF-8 byte count in strings.Buffer
and transfers the completed allocation, with no intermediate string per character
or final builder copy.
Sequence ranges use character indexes for strings and element indexes for
vectors. Copies are shallow and fresh; in-place copies preserve source values
under overlap. Equal-width string copies use memmove, and operations that change
UTF-8 width build a replacement buffer while keeping both old ranges rooted.
member and assoc keep their direct two-argument search and use a lazily
cached VM bridge for custom comparison procedures. Comparator continuations
preserve the pending candidate and advancing tail without recursive V calls.
dynamic-wind uses persistent extent identities to run exit callbacks from
inside out and entry callbacks from outside in. Transitions execute on the same
machine and keep multiple body results intact. Pending entries and exit counts
live on the existing operand stack, making transition traversal linear in nesting
depth without allocating a separate path container. Ordinary errors abort the current
entry; they do not promise to run after callbacks.
Only #f is false. () requires quotation in expression position; vector
constants evaluate to immutable data. Variables can shadow built-in syntax keywords, including the auxiliary
identifiers of cond and quasiquote. Host definitions and top-level variable
definitions can also install such bindings.
Parameters are first-class procedures: zero arguments read the current value; one argument converts and updates it, returning an unspecified value. A parameter retains its default value and optional converter. Each running machine carries a persistent chain of temporary binding locations. Continuations share those locations, so mutations remain visible on reentry; closures read whichever binding is active when called. Promises likewise use the dynamic context of the first force, independently of where they were created.
parameterize evaluates parameter/value expressions left to right in the outer
context, then validates the parameter objects and applies converters left to
right. It installs bindings only after every conversion succeeds. Its body has
the same internal-definition rules as other binding bodies and preserves all
returned values. Duplicate parameter objects use the last binding.
Parameter transitions use tagged contexts in the existing wind-frame layout,
with no Scheme callback procedures allocated for entry or exit. Wind transfers
restore contexts before running the corresponding Scheme callbacks. Native V
reentry inherits the active bindings across eval, eval_alt, eval_value,
eval_file, eval_file_as, and call; finishing or aborting an entry discards
its temporary bindings. Saved child continuations retain their inherited context
and install that base before destination winders run in a later host entry.
Getters and updates without a converter allocate no argument packet or helper
procedure. Converter calls use the current machine; a VM-owned bridge handles
updates, while parameterize compiles conversion steps directly into bytecode.
Captured converter continuations detach private pending arguments before mutation.
define-syntax, let-syntax, and letrec-syntax accept hygienic syntax-rules
transformers or expressions that produce transformer procedures. A procedural
transformer receives one syntax object and returns syntax for the replacement.
Its initializer runs in the existing VM and cannot capture runtime lexical
variables. For example:
(define-syntax twice
(lambda (form)
(syntax-case form ()
((_ expression)
#'(let ((value expression)) (+ value value))))))
(twice 21) ; => 42
syntax-case matches syntax objects and partially unwrapped datum structures.
A clause contains a pattern, an optional fender expression, and a result
expression. syntax (also #') substitutes pattern variables into a hygienic
template; with-syntax binds additional patterns. quasisyntax (#``) supports unsyntax (#,) and unsyntax-splicing (#,@`). Nested and ragged repetitions
retain their capture dimensions rather than copying subtrees.
The selected (vile syntax-case) library, also available through the unversioned
(rnrs syntax-case) alias, uses the existing R7RS library loader. It exports
these forms together with identifier?, bound-identifier=?,
free-identifier=?, syntax->datum, datum->syntax, and
generate-temporaries. Syntax values can pass through the V embedding API as
opaque Value objects. Their graphs preserve sharing and cycles; the usual
arena lifetime requirements still apply.
syntax-rules patterns support literals matched by binding identity, dotted
tails, vectors, and nested repetitions. A repeated subpattern can have a fixed
suffix, including before an improper final cdr; one repetition is allowed per
pattern sequence. Templates support multiple repetition groups and check that
variables driving the same group have matching lengths.
The shared dialect adopts the R7RS pattern-language choices: _ matches any
input without capturing it, unless listed as a literal. This replaces the older
R5RS interpretation of _ as a pattern variable. (syntax-rules marker (literals ...) rules ...) selects a custom ellipsis identifier; the default is ....
Listing the active marker among the literals disables its repetition role.
Custom marker recognition preserves hygienic identifier identity. The template
(marker template) suppresses ellipsis interpretation throughout that template,
while retaining ordinary pattern substitution and hygiene; (marker marker)
therefore emits one marker identifier. The pattern's initial keyword is ignored,
including when it is spelled _ or .... These choices apply together in one
dialect, without language profiles.
Introduced identifiers keep definition-site bindings; captured identifiers
preserve their use-site context through composed expansions. Quoted identifiers
retain their source names. Local syntax bindings disappear after compilation. Top-level transformers
persist across eval calls, with installation occurring at the definition's
execution point, so a preceding runtime failure prevents later installation.
Expansion uses a private flat syntax arena and emits ordinary bytecode; macro
matching and renaming do not run during procedure execution.
Definitions produced by macros participate in the surrounding body's definition
group. Discovery proceeds from left to right, deferring initializers and closure
compilation until every local slot is reserved. Group-level begin forms splice
into the body, including after expressions. Initializers execute in source order;
reading a local before its initializer runs reports an error. Duplicate definitions
and keyword shadowing that prevents recognition of the group report errors. Source locations
are resolved into instruction metadata before all generated syntax is discarded.
Trailing repetitions stream through the input once. Fixed suffixes use a
preliminary pair count; matching needs no backtracking, extra input lists, or
retained suffix-index maps. Wildcard-only repetitions need no capture values or
coordinate paths. See
R7RS section 4.3.2
for the selected pattern and ellipsis-escape grammar.
Nested templates align a variable's captured dimensions with its innermost
ellipses; additional outer repetitions reuse the captured sequence.
Exact arithmetic retains inline signed-64-bit integers and boxed small rationals,
then promotes to V math.big integers and larger exact rationals as needed.
Results normalize back to small representations whenever possible. Denominators
are positive and fractions reduced; zero and denominator-one results become
integers. Arithmetic preserves exactness rather than silently wrapping or
converting overflowing exact operands to floats. The 16-byte Value layout and
small-rational layout are unchanged. Existing small comparison, rounding,
conversion, and integer-division paths remain in use. Variadic all-small sums
retain their two-word stack accumulator, so a large intermediate that cancels
back to a small result does not allocate big integers per term; products still
recognize a later zero after validating every argument.
Numeric literals support radix and exactness prefixes, rationals, decimals and
R5RS exponent markers. Both frontends use the same exact runtime. Unspecified
numeric digits select zero and imply inexactness unless an exactness prefix
explicitly overrides it. Exact decimal scales are checked, never saturated to
a different numeric value. Scale magnitudes above the standard library's u32
power argument are rejected. Nontrivial exact powers with exponents outside the
signed-64-bit iteration range report a computation limit; bases zero and ±1
retain their defined results for arbitrary exact integer exponents. Actual
allocation and computation remain limited by available resources. Native numeric
work, like other native callbacks, is outside the Scheme instruction counter.
This does not add a numeric resource-budget API.
Inexact values still use V f64. Mixed comparisons compare the actual binary
float with the exact value, without rounding the exact operand first.
Exact-to-inexact rational conversion rounds directly, including subnormals and
ties to even; small fractions keep their existing hardware-division path. Every
finite float can be converted to an exact integer or rational. Nonfinite exact
conversion remains an error. Approximate evaluation still uses f64: when an
exact operand has no supported inexact conversion, a V error reports the range
restriction. This applies to approximate roots/transcendentals as well as
explicit inexact conversion; exact perfect-square roots remain exact.
The numeric library includes signs/parity, min/max, integer division, GCD/LCM,
rounding with ties to even, rationalization, exactness conversions, powers, roots,
and real transcendental functions. exact/inexact alias the earlier exactness
conversions; exact-integer?, square, and exact-integer-sqrt extend this set.
The square-root procedure returns exact root/remainder values. log accepts an
optional base, and exact rational logarithms near one retain their small difference.
Big rationalization uses an iterative continued-fraction accumulator, without
the small path's fixed coefficient storage limit.
V hosts can construct large values with integer_from_big(big.Integer) and
rational_from_big(numerator, denominator)!Value. They snapshot retained caller
limbs. Value.as_big_integer() and .as_big_rational() return independent limbs
in the currently active allocator. The existing as_integer() / as_rational()
remain checked signed-64-bit interfaces; large values report range errors.
Lengths, indices, Unicode characters, and ExitRequest.status keep their host
bounds. Internal arithmetic borrows immutable headers, and internal sign views
use public V value updates rather than reading or changing private math.big
limbs. Public copies remain explicit. Under -gc none, pop a host region before
calling an owned accessor to export a still-live value, then reset/free the region.
Copying a Value or a borrowed big-integer header alone does not export its graph.
A persistent VM still requires GC or its own lifetime strategy.
The independent Python fixture in scheme/testdata/bignum_cases.tsv covers 1,241
integer/Fraction/IEEE cases, including signed-64-bit boundaries, cross-cancellation,
exact rounding, roots, powers, radix round trips, and subnormal conversion. Its
generate_bignum_cases.py generator uses Python standard-library arithmetic and
a fixed seed, without reading Vile results. Generate into a separate directory
with --output to inspect its full JSON provenance alongside the TSV. Focused
host tests also check snapshots across arena resets, reentrant callbacks,
continuations, GC retention, checked scales, and allocation-free small paths.
number->string and string->number support radices 2, 8, 10, and 16, with
explicit input prefixes overriding the supplied default radix. Invalid or
unsupported strings return #f. Decimal float output has a decimal point and
uses the minimum significant digits needed for a round trip. Other radices use
inexact integer/fraction notation, preserving every finite float, including
subnormals and signed zero. Results are fresh mutable strings. Decimal string
conversions accept signed +inf.0, -inf.0, +nan.0, and -nan.0, with case-insensitive
spelling and valid radix/exactness prefixes. Exact nonfinite notation and
nondecimal nonfinite notation are rejected. Writing/displaying nonfinite reals
uses these spellings. finite?, infinite?, and nan? classify the supported
real numeric tower. Scheme comparison predicates return false for NaNs; the
private ordering helper still rejects unordered operands. NaNs propagate through
min, max, and sqrt. Exact conversion of nonfinite values reports an error.
Complex values extend this tower; see the component and branch rules below.
Complex numbers
Complex numbers use the same exact arithmetic and bignum promotion in each
component. make-rectangular, make-polar, real-part, imag-part, magnitude,
and angle are available in the shared dialect and (scheme complex) imports.
Exact integer powers and rational perfect square roots remain exact, including
negative real roots: (sqrt -4) is 0+2i, and (sqrt 3+4i) is 2+1i.
Other complex transcendental results use the host libm's inexact approximation.
Real-only operations such as ordering, abs, rounding, min/max and rationalization
reject non-real arguments; integer division families keep their integer domain.
finite?, infinite? and nan? inspect both components. Numeric = compares
components using the existing exact/float comparison rules; eqv?, equal? and
hash tables also preserve exactness. NaNs are unequal under numeric equality.
This is one R5RS-based representation choice: apply inexact contagion, then collapse
every zero imaginary component to its scalar real component. Thus 1+0i becomes
1, 1+0.0i becomes 1.0, (real? 1+0.0i) is true, and imaginary signed-zero
branch-side information is lost. It follows R5RS 6.2,
including the principal log angle in (-pi, pi], rather than R6RS/R7RS's distinct
inexact-zero-imaginary representation. Existing scalar signed zeros still compare
eqv?, and their numeric hashes agree. On the real cuts, (asin 2) has negative
imaginary part and (acos 2) positive imaginary part; on the imaginary cuts,
(real-part (atan -2i)) is -pi/2. These are deliberate R5RS formula boundaries,
not the default signed-zero side chosen by Python cmath or C99 libm.
angle at zero, atan at +i/-i, division by zero, exact log(0), and the
existing log(-0.0) case are errors. log(+0.0) retains -inf.0.
The readers accept finite rectangular and polar spellings,
including signed +i/-i, fractions, exponents and radix prefixes. Bare i is an
identifier; bare 2i is invalid. #e polar literals are exact only when provable
(zero radius or zero angle); otherwise they report an unsupported exact result,
instead of making a rounded trigonometric answer exact. make-polar may produce
inexact components even for exact inputs. number->string emits rectangular form,
with full decimal roundtrips and exact/binary-rational radices 2, 8, 10 and 16.
Nonfinite rectangular forms, such as 1+inf.0i, work in source, ports and
string->number; they require decimal radix and cannot be made exact.
Inexact payloads reuse V math.complex.Complex, with two inline floats and no
component array. Exact payloads hold two immutable numeric handles. Exact arithmetic
borrows those handles; it does not snapshot input limbs on each operation.
Public complex_value(real Value, imaginary Value)!Value and
Value.as_complex_parts()!(Value,Value) instead return independent boxed component
snapshots in the currently active allocator, including scalar normalization.
Pop the source arena before exporting, and free it only after snapshots are made.
Scalar accessors such as as_real() reject non-real values. As with all Value
handles, VM/continuation results themselves cannot outlive their allocation region.
The inexact transcendental adapter uses standard C99 cexp/clog/trigonometric /
principal root/power functions with scalar inputs and a two-double stack result;
it has no heap or shared result buffer. Construction copies the standard two-real
complex representation, avoiding nonfinite contamination from re + im*I.
MSVC uses its documented _Dcomplex/_Cbuild CRT equivalents instead of _Complex;
that branch is documented but was not executed on this Linux validation host.
GCC and Clang builds are checked. Exact integer powers remain in V. Division scales
finite operands using V math.frexp/scalbn; extreme exponent gaps and tiny products
use an exact-binary rational fallback before final float rounding. Multiplication
also recovers subnormal products and overflowing cancellation with that cold path.
Near-cancelled inexact product sums recover the two product-rounding residuals
using the C backend's single-rounded math.fma. Multiplication and normalized
division share this helper; ordinary sums avoid the extra FMA calls. Division
keeps its existing checks on all four products. With both operand maxima scaled
into [1/2,1), those checks bound a near-cancelled product pair around 2^-512
or larger, so its at-most106-bit residuals remain normal. A separate tiny-sum
threshold and exact-zero certificate would duplicate that existing recovery.
The deterministic generate_complex_compensation.py fixture adds12,385 Python
Fraction cases, including epsilon-squared components, both numerator diagonals,
rescued tiny quotients, and the guarded physical forms of generic FMA-underflow
examples. Its component error gate is 4e-13*abs(expected) +8*minsubnormal, not
a correctly-rounded-result promise.
Regular unboxed libm calls and division use no arena storage; non-real results
allocate their immutable payload. Big exact work and exceptional fallbacks
legitimately allocate. No speed or correctly-rounded complex-function claim is made.
The existing f64 conversion/resource bounds remain: component conversion may fail
when no finite inexact representation is supported, and nontrivial exact powers
with exponents beyond the host iteration range report a computation limit. Huge
integer powers of +i/-i use their four-value cycle. Transcendental accuracy and
nonfinite exceptional results depend on the host libm; full IEEE Annex-G behavior
is not promised. Finite inputs producing an unsupported NaN transcendental result
report a typed EvalError. The deterministic Python complex fixture independently
covers Fraction-pair exact operations and cmath values with explicit R5RS cut
adaptations; host lifetime, hash, macro, continuation and cancellation tests share
both frontends. No new numeric resource-budget API or Scheme exception forms are
introduced.
Source/port readers accept signed decimal infinity/NaN spellings directly, including supported complex components, using the same runtime number parser.
floor/ and truncate/ return quotient/remainder values; their scalar variants
include floor-quotient, floor-remainder, truncate-quotient, and
truncate-remainder. Existing quotient, remainder, and modulo bindings keep
the corresponding semantics. All division-family operands must be integers in this dialect, including
inexact integral floats; nonintegral rational operands remain errors. Small
exact integer scalar operations need no result container, and signed-minimum
division is guarded before C division. Mixed
integer inputs retain their actual integer values, including exact operands
beyond the float's precision, before rounding inexact outputs. Big exact integers and integral floats outside signed-64-bit range use
large-integer division before canonicalizing exact results or rounding inexact
outputs. gcd and lcm also reduce integer magnitudes exactly before the
final inexact conversion. An unrepresentable finite inexact result raises the
usual range error. A zero operand gives lcm zero after every argument passes
integer validation. Paired division results own a fresh two-value container. Big arithmetic, parsing,
formatting, GCD, and division can allocate standard-library temporary storage;
these paths do not promise zero allocations.
Both frontends use these procedures. Slash remains an infix operator in Vile
syntax, so use a callable alias for a slash-suffixed name; a V host can define
floor-pair from vm.lookup('floor/')!, or datum eval can supply it. Scalar
names such as floor-quotient are ordinary calls in both frontends.
The runtime implements R5RS syntax, control, data, ports, and evaluation with
an exact integer/rational tower, exact rational-component complex values, and f64 inexact real/complex values. R5RS permits a limited numeric tower and
range;
transcript procedures remain unsupported; complex values follow the rules above.
Nonblocking file readiness currently requires POSIX.
Internal definitions in bodies (including begin groups) reserve local slots before resolving references, supporting forward and mutual recursion.
Definitions are accepted at top level and anywhere in procedure and binding
bodies in both syntaxes. A body containing only declarations, ending with a
declaration, or empty after splicing begin groups returns an unspecified value.
Definitions remain invalid in expression operands and do commands. Compiler
failures remain executable errors, so
an unselected branch does not run them.
Limits, errors and tests
import scheme
mut vm := scheme.new_with_options(scheme.Options{
max_steps: 1000000
max_frames: 10000
max_expansions: 10000
}) or { panic(err) }
Those are the defaults. Zero disables the corresponding limit; negative limits
are rejected. max_expansions bounds macro transformations per eval, independently
of the execution budget. Expanded expressions and transformer patterns/templates
also have a fixed nesting limit of 512 to protect the native compiler stack.
Steps count dispatched instructions and procedure applications, excluding
parsing, compilation, and work inside primitives/native callbacks. Counts differ
from the earlier syntax-tree evaluator, so budgets may need adjustment. Each reentrant
eval/call has its own budget. These limits are not a wall-clock or memory
budget. After an error the same VM can be evaluated again.
Built-in GOOPS definitions initialize on first use in both heap and arena VMs.
The bootstrap uses the VM's captured allocator, even when a borrowed arena is
current or the VM's arena is inactive, then restores the caller's allocator.
The host must keep the VM's allocation domain alive. Bootstrap uses bounded
internal defaults and restores the caller's options. Subsequent make and
define-class evaluations include Scheme initialization methods in the caller's
step and frame budgets. Construction can require more frames than later slot access.
Runtime errors are scheme.EvalError, with message, byte offset, line and column.
Host-only calls have no source location. Lexer/reader failures keep their original
types. Runtime code does not turn expected language errors into V panics.
Run tests with assertions enabled:
v -cc gcc test scheme
v -cc gcc test scheme_test.v
Do not use -prod for correctness tests: the current compiler strips assertions
even from test files. Use -cflags -O3 if optimized C tests are desired.
Newer numeric tests add 2,444 Python integer-arithmetic division references and
698 independent integer square-root references. They cover sign combinations,
integer limits, mixed precision, huge integral floats, signed zero, multiple
values, NaNs/infinities, and mutable result ownership. Regenerate with
python3 scheme/testdata/generate_extended_numbers.py. The allocation-only
bench/numeric_extensions.v separates scalar operations from paired results;
it reports no timings.
Numeric I/O tests include 1,585 independent exact-fraction/IEEE rounding cases,
minimum decimal digit counts, all four radix round trips, and integer-limit
regressions. Regenerate the stored fixture with
python3 scheme/testdata/generate_numeric_io.py; ordinary V tests need no Python.
The tests also execute 184 examples adapted from Chibi Scheme's independent
R5RS corpus, with its license, source revision, and five later-language exclusions
recorded in testdata/chibi-r5rs-notes.txt. A separate fixture checks all 188
required procedures for the supported numeric tower in both root and report
environments. Environment tests cover mutable root definitions, pristine report
bindings, syntax isolation, tail calls through eval, continuation capture across
eval, native reentry, shared/cyclic data, source locations, and GC.
Exact variadic arithmetic also has 450 stored Python arbitrary-integer oracle
cases covering cancellation, zero/sign changes, and true out-of-range results.
Regenerate them with python3 scheme/testdata/generate_integer_folds.py.
Runtime operations and identifier classification/folding share pinned
Unicode17.0.0 data. char-titlecase, char-foldcase,
char-title-case?, char-general-category, digit-value, full string
upper/lower/title/foldcase and all four string-normalize-* forms are available.
Existing character predicates and case-insensitive comparisons use the same
version. char-numeric? recognizes decimal digits (Nd), so digit-value returns
0–9 or #f; superscript numbers and Roman numerals are not decimal digits.
char-alphabetic?, upper/lower-case predicates and whitespace use their Unicode
properties. Characters use simple scalar case maps; strings can expand, such as
sharp S to SS/ss. Casing is locale-independent and titlecase follows Unicode
word boundaries and the corrected R6RS examples (r6rs becomes R6rs).
string-ci comparisons and string-ci-hash consume one shared full-fold stream.
They allocate no folded strings and preserve an ASCII branch. Folding does not
normalize: composed and decomposed accents remain different until an explicit
normalization call. NFD/NFC use canonical decomposition/composition; NFKD/NFKC
also apply compatibility mappings. Embedded NUL is preserved. Malformed host
UTF8 follows the existing decoder, replacing each invalid byte with U+FFFD in
folding, casing and normalization.
Changed transformations return independent mutable strings. An unchanged result
may return the original Value, preserving its read-only status. Export a region
result with as_string() after popping the region and before resetting/freeing
it, as for other host strings. Temporary buffers never own escaping outputs or
errors. Category symbols preserve Unicode spelling, e.g. Ll; compare with
(string->symbol "Ll") under this dialect's identifier-folding reader.
The complete22-name (scheme char) catalog and29-name selected (vile unicode) /
(rnrs unicode) collections share pristine procedures with the normal global
bindings. Versioned imports and standards modes are not added. Sources/licenses,
offline regeneration and exact Unicode conformance fixtures are documented in
tools/unicode. Native transforms, like other native
callbacks, do not add instruction-budget preemption.
Selected computational bytevector extensions
(vile bytevectors) and (rnrs bytevectors) are unversioned aliases for the
same selected 58 bindings. They add the endianness syntax (big and little),
native-endianness, byte equality/filling, signed bytes, integer/list encoding,
16/32/64-bit signed/unsigned and IEEE single/double access, and UTF16/32 conversion.
Explicit endian accesses allow unaligned offsets. Native accesses require an
offset divisible by the field width, including floating-point access. Every
store validates bounds, endianness, mutability and the complete value before
writing; bytevectors remain fixed-size. Generic integer widths are positive
and limited to the existing arithmetic storage ceiling (268435455 bytes).
Results promote to bignums only when necessary, including unsigned 64-bit values.
The shared dialect keeps its existing make-bytevector unsigned fill domain,
its destination/source/start/end bytevector-copy! convention, and its strict
malformed UTF8 decoder. These three conflicting names are omitted from the
selected library; they remain available from the shared base. New
bytevector-fill! accepts -128..255; signed stores and integer/list conversions
retain their declared signed or unsigned domains. No profile switch is added.
string->utf16 and string->utf32 default to big endian and emit no BOM.
utf16->string and utf32->string require a supplied fallback byte order; an
initial BOM overrides it and is removed unless the optional mandatory argument
is true. A mandatory BOM is decoded as an ordinary character in the supplied
order. Invalid/incomplete encodings produce U+FFFD. UTF16 consumes one complete
invalid surrogate unit; a high surrogate followed only by a partial unit
consumes that tail together as one replacement. Other partial trailing units
produce one replacement. UTF32 consumes one invalid complete unit, or the final
partial unit. Noncharacters are valid scalar values; no normalization occurs.
Malformed host UTF8 strings use V's per-invalid-byte replacement behavior during
encoding, consistent with the Unicode runtime. The existing UTF8 conversion
procedure continues to reject malformed input.
Typed scalar operations and padded immediate reads allocate no operation storage with prepared arguments. Stores preserve full host offsets even beyond C int's range: validated bounded views keep standard binary store indices small, and generic/u8 stores use checked pointer indexing. Borrowed integer input views carry their exact length, avoiding the current compiler's max_i32 array-end sentinel. Sparse Linux/amd64 tests reserve virtual address space while touching a few pages to cover these boundary cases without a huge heap buffer. Big integer reads own their result limbs; reversed/negative large input uses a freed lexical standard arena scratch buffer. Large stores borrow immutable magnitude headers and stream bytes. UTF conversion sizes once and writes one owned output buffer, with no intermediate rune/unit arrays; changed-string output retains V Buffer's small promoted owner header. Host exports copy out before an owning arena is reset or freed.
The shared reader supports #u8(...) and #vu8(...) literals. Whole-value and
attached port transcoders are supplied by the selected I/O collection below.
Custom Scheme ports remain pending.
Immutable codecs and whole-value transcoders
(vile io ports) and (rnrs io ports) export the same selected bindings.
The thirteen codec/transcoder bindings are latin-1-codec, utf-8-codec, utf-16-codec,
native-eol-style, native-transcoder, make-transcoder, transcoder-codec,
transcoder-eol-style, transcoder-error-handling-mode, bytevector->string,
string->bytevector, and the eol-style / error-handling-mode syntax forms.
The collection also exports the eighteen get/put procedures, four position
procedures, transcoded-port, port-transcoder, and the seven memory-port
extensions, six file-option/buffering bindings, three standard binary stream
constructors and thirteen common port bindings below, for 66 bindings in total.
Custom Scheme ports, combined input/output ports and the remaining file APIs
remain pending.
Libraries use the existing R7RS-small loader and unversioned names.
The binary procedures are get-u8, lookahead-u8, get-bytevector-n,
get-bytevector-n!, get-bytevector-some, get-bytevector-all, put-u8, and
put-bytevector. Textual procedures are get-char, lookahead-char,
get-string-n, get-string-n!, get-string-all, get-line, get-datum,
put-char, put-string, and put-datum. Each requires the port as its first
argument. Optional output ranges use a start and a count; string ranges count
Unicode characters. For example, (put-string out "Aλ😀Z" 1 2) writes λ😀.
get-bytevector-some returns an available buffered chunk after the first
successful read. The *-all procedures read through EOF. Empty reads return EOF,
while an explicit zero-count read returns an empty result or zero for *-n!.
get-line stops at LF and consumes it; other characters remain in the result.
The existing read-line API recognizes its documented broader line endings.
The V host API adds read_bytevector_some(port) and
read_string_into(port, target, start, count). String input constructs one final
UTF-8 replacement buffer, preserving the target's character length. A failed
read does not publish an incomplete replacement. A callback that mutates the
target causes a V error and its mutation is preserved. Port busy guards clear
on every exit.
Output string ranges borrow their UTF-8 backing through synchronous writes and
retries, including callbacks that replace the source string's backing storage.
The usual host/arena ownership rules apply to results and mutations.
Codecs and transcoders are immutable inline values. Equal option triples are
eqv?/equal?; their printers produce descriptive nonreadable forms. V hosts
have CodecKind, EolStyle, ErrorHandlingMode, codec_value,
transcoder_value, Value.as_codec and Value.as_transcoder. These handles
contain only scalar options and can be copied out of an arena before reset/free
without exporting a pointer graph. Returned strings and bytevectors instead
require the normal owned snapshot/export rules.
make-transcoder defaults to the platform's native EOL (LF on Unix, CRLF on
Windows) and replace. native-transcoder selects UTF8, that EOL, and replace.
The seven EOL styles are lf, cr, crlf, nel, crnel, ls, and none.
none preserves every scalar. Other input styles normalize CR, LF, CRLF, NEL,
CRNEL and LS to LF; U+2029 remains ordinary content. Output expands only LF to
the chosen ending. The three error modes are ignore, raise (existing
EvalError) and replace; Latin1 output replacement is ?, Unicode input
replacement is U+FFFD. A selected EOL such as LS can itself be unencodable in
Latin1 and follows that same mode. No normalization or case conversion occurs.
UTF8 retains initial U+FEFF and emits no signature. UTF16 consumes an initial BE/LE BOM, otherwise reads BE, and emits BOM-free BE. Later U+FEFF is content. Consequently a leading U+FEFF in BOM-free UTF16 output is interpreted as a BOM when decoded again; these conversions are deliberately not always bijective.
Malformed UTF8 leads consume one byte. A valid lead followed by a partial
continuation prefix consumes that prefix and leaves the next noncontinuation;
EOF truncation consumes the remaining prefix. Complete scalar-range violations
consume the entire sequence. UTF16 consumes an invalid high surrogate while
retaining the next nonlow complete unit; stray lows consume one unit. An odd
tail is a separate malformed piece, including after a high surrogate. This is
the explicitly selected transcoder policy; existing utf16->string retains its
previous replacement consumption, and existing strict utf8->string stays
strict. Encoding malformed V-host UTF8 string bytes follows the runtime's
existing per-invalid-byte U+FFFD character semantics before codec/EOL conversion.
The reusable decoder reports scalar / need-input / finished / malformed separately. A nonfinal prefix or CR does not prematurely produce replacement or LF. It retains four bytes in a scalar word and at most one decoded lookahead; it retains no borrowed refill buffer. Invalid input is consumed before a raised decoding error, while any next valid unit stays queued. Whole conversions size first and fill one owned output; no intermediate rune/unit arrays are built. The existing Buffer owner promotion remains a small separate string-output cost. A thin private UTF8 scalar wrapper reuses the pinned Unicode backend; its local C view avoids a compiler-induced heap promotion of mutable V structs with fixed-array fields. Optional accessor symbols are prepared once in cold PortState; immediate constructors and prepared cursor/accessor work allocate no operation storage. Port metadata stores attached transcoder options in one byte; Value, VM and Machine layouts are unchanged by attaching ports. Cold PortState holds the optional accessor symbol cache.
Attached port transcoders
(transcoded-port binary-port transcoder) returns a textual port in the same
direction. It transfers the binary resource and unread bytes to the new port,
and closes the original binary handle. A failed argument check leaves that
handle usable. port-transcoder returns the associated immutable options,
including after close, or #f for a port without an attached transcoder.
V hosts use VM.transcoded_port(binary, options)!Value and
VM.port_transcoder(port)!Value.
(define raw (open-input-bytevector #u8(65 206 187 13 10)))
(define text (transcoded-port raw
(make-transcoder (utf-8-codec) (eol-style lf)
(error-handling-mode raise))))
(get-string-all text) ; => "Aλ\n"
Input uses the same codec and newline policies as whole-value conversion. Multibyte units, BOMs and CR pairs can cross buffer boundaries, including one-byte reads. The adapter publishes available output before requesting more input, and readiness checks use the underlying nonblocking capability. A raised decoding error consumes the malformed unit; later input remains readable. Attached textual ports currently report no position or seek capability.
Closing an attached port closes an owned file, even if output flushing fails.
Borrowed V Readers and Writers retain their existing ownership policy. The old
binary memory-output handle still supports get-output-bytevector snapshots.
An output failure retains only the unsent encoded suffix of its current batch;
the next write or flush retries that suffix first. It does not replay the
unencoded remainder of a failed text write.
Resource transfer moves buffer headers without copying their bytes. Prepared input reuses the port buffers and inline decoder state; healthy output encodes through a 4096-byte stack batch. Only output I/O failures need a lazy retry buffer. Callers must retain the allocator backing the port and its resource state under the usual host ownership rules.
Memory-port constructors, extractors, and collectors
open-bytevector-input-port snapshots its bytevector and accepts an optional
transcoder or #f; it returns a binary port by default. open-string-input-port
snapshots its string into a textual port. Both reuse the existing memory-input
implementation. port-eof? tests either input mode through lookahead: it can
request input and report decoding errors, but does not consume a valid next
byte or character.
open-bytevector-output-port accepts an optional transcoder or #f and returns
two values: the output port and a zero-argument extraction procedure.
open-string-output-port returns the same pair for textual string output.
Each extraction transfers the accumulated storage to an independent mutable
result and resets the port to empty at position zero. Later writes use fresh
storage. String extraction adds a NUL terminator in spare capacity; a completely
full buffer is copied to an exactly sized string to avoid doubling its capacity
for one terminator. Extraction also
works after close; repeated empty extraction returns
an empty string or bytevector. Encoded output extracts the encoded bytes.
(define-values (out take) (open-string-output-port))
(put-string out "Aλ")
(take) ; => "Aλ"
(put-string out "B")
(take) ; => "B"
call-with-string-output-port calls a procedure with a fresh textual memory
port. It discards the callback's return values, returns the accumulated string,
and closes the port when the callback returns. call-with-bytevector-output-port
does the same for bytes, with an optional transcoder or #f. Unlike extraction,
collecting the final result preserves the port's accumulated content for its
existing snapshot API. Both use the same machine, wind controls, host-error
cleanup, and continuation machinery as call-with-port.
An escaping callback keeps its port open until an actual return. Reentry uses the same port and accumulated content; a prior return leaves that port closed. Captured callbacks can return multiple times, but writes after a prior close fail under the ordinary closed-port rules. Extractors capture only their own resource handles and an immutable instruction bridge. They retain no VM or first-caller cache; normal host arena-lifetime rules still apply. An extracted value can have its header in the calling arena and transferred bytes in the port's earlier arena. Keep both alive while using the result, or use the normal host export/copy facilities before releasing either arena.
Selected file constructors and buffering
open-file-input-port and open-file-output-port take a filename and optional
file-options, buffer-mode, and transcoder arguments, in that order. They return
binary ports by default; supplying a transcoder returns an attached textual
port. Every argument is validated before opening, creating, or truncating a
file. The existing open-output-file keeps its R5RS truncate-or-create behavior.
(file-options ...) produces an immutable enumeration set over no-create,
no-fail, and no-truncate; ordinary enum-set operations work on these values.
Duplicate options collapse. Other enumeration sets with compatible universes
are accepted. Unknown universe members are errors. Literal option names ignore
lexical variables with those names; file-options itself remains shadowable.
The default output constructor creates a new file atomically and fails if it
exists. no-create requires an existing file. no-fail permits an existing
file. Either option permits truncation unless no-truncate is also supplied.
no-truncate preserves an accepted existing file and starts at byte zero,
without append behavior. Input accepts these flags but ignores their effects.
File permissions follow the platform's ordinary creation permissions and umask.
(buffer-mode block), (buffer-mode none), and (buffer-mode line) return
their literal symbols; buffer-mode? recognizes them. Block mode is the default.
Unbuffered file output writes directly to the descriptor; unbuffered input
requests one byte at a time while still retaining lookahead needed for decoding.
Line input currently uses block read-ahead. Line output flushes after a write
containing LF, including when a transcoder converts that LF to another ending.
Capacity-driven writes may flush earlier. The flush occurs after bytes have
been accepted, so an explicit flush retry does not duplicate an encoded batch.
output-port-buffer-mode returns the selected mode, also after close. Borrowed
host Writers and memory output ports report none: Vile adds no output buffer
to those resources. The host Writer can still implement its own buffering.
V hosts use VM.open_file_input_port(path, FilePortOptions{}) and
VM.open_file_output_port(path, FilePortOptions{}); named option fields are
no_create, no_fail, no_truncate, buffer_mode, and transcoder.
Binary constructors retain buffered logical position and seeking support. Attached textual ports retain the documented transcoder position limits. Closing releases owned descriptors even after a flush failure; borrowed host resources follow their existing policy. File-option sets and mode symbols are immutable process-lifetime data, so prepared option checks and mode queries need no per-call allocation or first-caller cache.
Standard binary streams and common port exports
standard-input-port, standard-output-port, and standard-error-port return
fresh binary wrappers for the process standard streams. They ignore dynamic
current-port parameters and public name rebindings. Each wrapper has independent
lookahead, EOF and close state. Closing a wrapper flushes its output where
needed and leaves the process standard resource available to other wrappers.
V hosts have matching VM.standard_input_port, VM.standard_output_port and
VM.standard_error_port methods.
On POSIX, fresh wrappers share the stable owner's existing C stdio resources, preserving C read-ahead when alternating textual and binary input. Input asks for one byte at a time so interactive reads do not wait for a full block. Lookahead cached in one wrapper belongs to that wrapper. Windows input also shares C stdin read-ahead; its locked C read temporarily suppresses CRT byte translation and restores the descriptor mode before returning to V. Bytes already transformed by an earlier native text read retain that buffering behavior. Windows output uses owned binary descriptor duplicates, with no change to the process output descriptor's mode. Closing those ports closes only the duplicate. Binary output drains earlier C stdio output before writing its bytes.
The selected ports libraries also export the existing port?, input-port?,
output-port?, binary-port?, textual-port?, close-port, call-with-port,
current-input-port, current-output-port, current-error-port, eof-object,
eof-object?, and flush-output-port. These are pristine binding aliases of
the shared procedures and parameters. They keep their original control,
continuation and ownership behavior under the same R7RS-small import machinery.
Extended formals and setters
(vile optargs) exports lambda* and define* through the same R7RS-small
library mechanism as other Vile extensions. A signature can contain required
parameters, #:optional parameters, #:key parameters, and a dotted or
#:rest parameter. Optional and keyword defaults run only when absent, in
declaration order. An omitted parameter without a default is #f.
Repeated keywords use the last value. Unknown keywords are errors unless
#:allow-other-keys appears in the signature. When a rest parameter exists,
the original keyword pairs remain in its list.
Vile syntax accepts the same markers in function signatures, for example
sum(a, #:optional, (b, 5)) := a + b and
fn(a, #:key, (b, 7)) { a + b }. Ordinary signatures keep the existing
fixed-arity function path. Calls to extended functions bind from the VM stack
without copying the argument packet; a rest list is constructed only when a
rest parameter is declared.
(vile setters) exports make-procedure-with-setter and setter. A wrapped
procedure calls its getter using the existing call and tail-call path. Scheme
(set! (accessor arg) value) and Vile accessor(arg) = value invoke its setter
with the evaluated arguments followed by the value, then return an unspecified
result. A bare variable assignment continues to use the ordinary assignment
path. These are prerequisites for the remaining GOOPS class and generic APIs.
GOOPS class core
The built-in protocol methods share their compiled source and read-only instructions across VMs. Each VM owns its binding caches, procedures, classes and methods. Rebinding a protocol affects that VM's later calls.
(vile goops) exposes the builtin class hierarchy, class-of, is-a?,
instance?, and class name, superclass, and precedence queries. define-class
or make-class constructs a class; make constructs its instances.
slot-ref, slot-set!, slot-bound?, and slot-exists? operate on slots.
class-slot-ref and class-slot-set! access #:class or
#:each-subclass slots directly through a class, without an instance. Class
slot assignment returns an unspecified value.
class-of identifies a syntax object as <syntax>. A file port has class
<file-input-port>, <file-output-port>, or <file-input-output-port>
according to its open directions. The class persists through transcoding and
closing. The exported integers min-fixnum and max-fixnum give Vile's
fixnum bounds.
For example:
(import (vile goops))
(define-class <point> (<object>)
(x #:init-keyword #:x)
(y #:init-value 0))
(define p (make <point> #:x 4))
(slot-set! p 'y 7)
(list (slot-ref p 'x) (slot-ref p 'y)) ; (4 7)
Instances use one scanned allocation containing the object header and their
instance-allocated slot values. #:allocation #:class gives a slot one shared
cell across instances and subclasses; redefining the slot in a subclass gives
it separate storage. Class metadata is created once per class. User classes are not
placed in the VM's builtin class registry, so a class created in a temporary
host arena does not leave a stale registry entry when that arena is released.
#:init-value is evaluated once when a class is defined. #:init-form is
evaluated for each instance lacking that slot's init keyword, or once at class
definition for a class-allocated slot.
#:allocation #:each-subclass gives each class in the inheritance chain a
separate shared cell. Its initializer runs when each class is defined, and
instances of the same class share that cell.
#:getter and #:setter on a define-class slot create or extend generic
functions in the definition's lexical scope. #:accessor creates a callable
getter with a setter, so generalized set! works:
(import (vile goops) (vile setters))
(define-class <counter> ()
(count #:init-value 0 #:getter get-count #:accessor count))
(define c (make <counter>))
(set! (count c) 3)
(get-count c) ; 3
Direct make-class accepts an existing generic for #:getter or #:setter.
For #:accessor, pass a procedure with a generic getter and generic setter.
These generated methods use the same class-based dispatch as define-method.
Generated accessors are instances of <accessor>, a subclass of
<generic-with-setter> and <generic>. Generic name/method queries and
add-method! accept accessors directly; define-method extends the getter.
make-accessor creates an empty accessor and an independent generic setter.
make <generic-with-setter> and make <accessor> accept #:name and an
optional #:setter; their default setter is #f. Setter lookup and generalized
assignment use the supplied setter.
#:allocation #:virtual reserves no instance field. Supply both #:slot-ref
and #:slot-set! procedures; the first receives the instance, and the second
receives the instance and new value. Slot operations and generated accessors
call them. Virtual slot init values, init forms, and init keywords are applied
through the setter when an instance is made. A virtual slot write returns its
setter's result. Ordinary virtual reads and writes reuse the current VM call
stack, so they do not allocate a nested machine for each access. Virtual
slot-bound? uses a reusable VM bridge on that stack, including when its
getter captures a continuation.
A make-class slot accessor can also be a make-procedure-with-setter
wrapper whose getter and setter are generics. Slot methods extend the contained
generics while the wrapper keeps its identity. This is a Vile compatibility
extension; Guile 3.0.11 rejects that wrapper as a slot accessor.
The generic API is available through (vile goops): define-generic,
define-method, make-generic, make <method>, add-method!, generic-function-name,
generic-function-methods, method-specializers, method-procedure, and
method-generic-function. Dispatch chooses the most specific applicable
method using class precedence. A newly added method replaces an earlier one
with the same specializers. define-method accepts fixed and dotted rest
argument lists; it creates a generic if needed and retains an existing ordinary
procedure as a fallback method. make <generic> also creates a callable
generic. Missing or false names use cache-miss. Protocol constructors permit
well-formed extension keyword/value pairs, while malformed pairs and invalid
callback values report errors. Replacing a method retains its generic-function
metadata but removes it from the active class dependents.
make-extended-generic links generic method sets. Parent calls include child
methods; a child sees its ancestors and descendants, excluding its siblings.
Shared paths contribute each method once, and cyclic relations report an error.
With Boehm, reverse links, the class and method registry, and the metaclass
cache use collector weak references for heap targets. A lookup temporarily
retains a live target. Arena targets use lifetime tokens, so the host must
synchronize lookups with arena reset and free. The aggregate-method and
ordered-applicability caches retain their recorded dependencies. Dispatching
on a class can therefore keep it alive through a warmed generic.
The boehm_leak build keeps ordinary tracing for heap targets. Standard
Boehm builds require working disappearing links. Failure to allocate or
register a link stops the process, including when the collector is configured
for runtime leak detection. Extended relations that would expose a method
from a shorter-lived arena are rejected before publication.
Direct methods, extends, and extended-by changes affect the next dispatch.
Guile 3.0.11 can repeat methods through shared descendants and retain a cached
procedure after a direct metadata edit. Vile applies those edits immediately and
invokes each method once.
ensure-accessor preserves the original generic's class and method container
and returns an accessor sharing its method objects. An accessor with a generic
setter is reused. ensure-generic retains a procedure-with-setter's setter;
ensure-accessor ensures that wrapper's setter is generic. Extended upgrades
move the parent's reverse edge to the new accessor and preserve descendant
views. Guile 3.0.11 drops the descendant constructor keyword during this upgrade;
Vile retains those edges, consistent with its directional method traversal.
Extended lookup reuses a method list until a related generic changes. A call
from a borrowed arena can read the owner's prepared list; otherwise its entry
keeps temporary lookup storage and releases it on return. Escaped next-method
procedures retain independent lists. This cache stores method identities;
method factories and public protocol procedures keep their existing behavior.
A call to a subclass of <generic> obtains ordered methods from
compute-applicable-methods and a callable from compute-effective-method.
The latter uses compute-specialized-effective-method for specialized method
classes. The argument-type vector contains classes at specialized positions
and #f at unused rest positions. Each user method factory runs once when
constructing a chain, from the least to the most specific method. Repeated
calls reuse the callable. Exact <generic> calls use the standard builder
when methods have factories, and enter plain method bodies directly otherwise.
Method edits, class layout or precedence changes, accessor target replacement,
related generic changes, and replacement of a dispatch hook invalidate the
affected cached decisions. Factory side effects can capture continuations or
reenter the VM. A completed construction publishes its cache entry only while
its dependencies still match. A borrowed entry keeps temporary results on its
current machine. An escaped next procedure keeps the chain that constructed it.
The public apply-generic and apply-methods protocols remain available for
explicit calls.
primitive-generic-generic returns the extensible generic for a supported
primitive. Calling it on a numeric primitive enables extensions. Existing
aliases and compiled callers retain the same procedure identity and observe new
methods. The enabled primitive has class <primitive-generic>, a subclass of
<procedure>. Calling its generic directly runs the selected method for any
applicable argument classes. Calling the primitive uses its builtin operation
within its native domain and dispatches extension cases through the generic.
Variadic arithmetic reduces pairwise. Comparisons stop at the first false
result and otherwise return the final comparison's value. Numeric equality
presents an extended operand before its builtin numeric counterpart. The
one-argument extension paths for gcd and lcm delegate to abs.
enable-primitive-generic! installs fresh empty generics on its arguments.
The supported extension points include arithmetic, ordering, numeric division
and conversion procedures, equal?, setter, write, and display.
Extended equality compares distinct GOOPS objects of the same class, including
objects nested in shared and cyclic data. Each equality callback runs on the
current machine. Mutations to later elements are visible as traversal resumes.
A method body can call next-method with its current or explicit
arguments. It remains callable after the method returns and keeps the method
chain from the original dispatch. Calls to methods that do not use it keep
the direct dispatch path. Plain method-procedure values take only the method's
declared arguments. A method using lexical next-method instead exposes #f
there and a make-procedure factory that accepts the next callable and returns
a bound procedure. Implicit next calls read current required/optional bindings,
including optional defaults and later assignments, and preserve the original
keyword tail or current rest binding. Explicit arguments replace that packet.
Custom method factories run on the current evaluator and can capture and resume
continuations. method* and define-method* use the same optional,
keyword, and rest argument syntax as lambda*; class specializers apply to
required parameters. An instance of <applicable-struct> (or a subclass) is
callable through its inherited procedure slot. It satisfies procedure?
even before that slot is bound; calling an unbound slot reports an error. The
slot can be supplied with #:procedure to make or changed with slot-set!.
Applicable calls use the existing tail-call and continuation path and can be
passed to callbacks. Construction and layout extension use the metaobject
protocols described below.
class constructs a class expression from a superclass list, bare or configured
slots, and class keyword options such as #:name and #:metaclass. Its getter,
setter, and accessor options evaluate expressions naming existing generics.
standard-define-class provides the standard define-class form, including
bare slots and class options. Definition forms create their slot accessor
bindings in the surrounding scope.
method constructs an unattached method with fixed or dotted rest parameters;
method* adds optional and keyword parameters. Both retain lexical bindings,
method formals, and body metadata. define-accessor creates a named accessor
with its setter generic. Repeating it replaces an existing accessor with an
empty one; upgrading an ordinary procedure or generic retains its methods or
fallback behavior and preserves an existing setter.
define-extended-generic names a generic extending one parent or a list of
parents. Parent accessors also contribute their setter generics.
define-extended-generics (name ...) #:prefix (prefix ...) defines each name
from the corresponding prefixed parents, in prefix order. Prefix references
use the lexical context of the unprefixed name. This implements the bulk
form's intended expansion; Guile 3.0.11 exports it but fails to expand its
nonempty examples because of errors in its macro pattern and template.
define-class invokes class-redefinition when its binding already exists.
Following Guile, ordinary classes replace that binding and leave existing
instances and retained class handles intact. Classes made with
make-class and #:metaclass <redefinable-class> instead keep their identity;
their redefinable descendants are rebuilt with the same retained identities. Existing
instances migrate lazily on class, dispatch, or slot operations. Bound instance
and virtual slots are copied by name, removed slots disappear, and added slots
use their initializers. New shared and per-subclass cells are initialized once
when rebuilding the class, rather than for each migrated instance.
Migration calls change-class and update-instance-for-different-class on the
current evaluator. Hooks can inspect the old layout, use continuations, or
reenter the VM from V. Failed or canceled entries release the migration guard;
completed updates remain committed. Replaying an initializer continuation keeps
the current layout, and a superseded target reports an error instead of
installing stale storage. User hook side effects and class redefinitions already
performed before an error are retained. Constructors reject an instance whose
class belongs to a shorter-lived arena before allocating or initializing it;
same-arena and VM-root classes remain usable in borrowed evaluations.
The same lifetime rule applies to superclasses, precedence entries, replacement
classes, method specializers (including a dotted rest class), and slot definitions
retained by a class or accessor method. A rejected edit preserves the existing
metadata. Each method owns its specializer array, so the list supplied to
construct or edit it may be temporary.
The allocated migration copy becomes the previous view passed to the update
hook, with independent field storage. Each physical allocation keeps its arena
owner. Initializer replay writes the current layout through its copy plan;
it does not share storage with the escaped previous view. A changed class or
foreign allocation domain is rejected before the copy can publish a layout.
Class, slot, method and generic metaobjects can migrate to another layout in
their representation family. Ordinary objects can also change to method
objects and back. Aliases, method lists and identity-based keys retain the
same public object. A previously built effective procedure continues to work
for its cached argument classes after a method becomes ordinary. A fresh
dispatch that examines the non-method entry reports an error. A method
installed and called from a custom allocator also retains its warmed
procedure after the default migration exchanges its public fields.
The GOOPS benchmark measures slot reads,
construction, ordinary and method role changes, and generic cloning. Build
with v -cc clang -prod -gc none -o goops-bench bench/goops_migration.v
from the repository root. Run ./goops-bench for all workloads or pass
workload names to select them. Each row gives the name, iteration count,
elapsed nanoseconds and bytes consumed in the arena after warm-up.
Set a class's print slot to a procedure of two arguments to print its
instances. It receives the object and the textual output port. It can write to
that port, capture a continuation or call back into Scheme. Compound output
preserves pair and vector labels around custom printers. The V functions
scheme.write and scheme.display provide their VM-independent diagnostic
representations. Call the VM's write or display binding to run user code.
Set instance-finalizer to a procedure of one argument before allocating an
instance to register it for finalization. The VM looks up the current callback
on the instance's class when it runs. Set the slot to #f to disable it.
Boehm schedules unreachable instances for the next outer evaluation in the VM's
allocation domain. The collector callback only enqueues work. For manually
managed instances, call vm.finalize_instances()! before releasing their
arena. This also drains queued collector work. Each registration runs at most
once. If a callback raises an error, a later drain resumes with the remaining
registrations. Objects created during a drain can be finalized by a subsequent
call.
GOOPS metaobject protocols
Construction uses make-instance, allocate-instance and initialize generics.
Custom methods run on the current evaluator, so callbacks, tail calls and
continuations follow the same control path as ordinary Scheme calls. Standard
constructor methods keep the native fast path until their applicable methods
change; edits through accessor aliases invalidate that decision too.
Custom metaclasses can specialize compute-cpl, compute-slots,
direct-slot-definition-class, compute-direct-slot-definition,
effective-slot-definition-class, compute-effective-slot-definition, and
compute-get-n-set. Slot method generation uses compute-getter-method and
compute-setter-method. ensure-metaclass and ensure-metaclass-with-supers
resolve compatible metaclasses, retaining ownership and class identity.
Class, slot, generic and method metadata have native slot representations.
Property accessors remain extensible generics; direct slot-set! and protocol
writes share mutation validation. A newly supplied effective definition must
belong to the active mutation domain before its storage or accessor cells change.
shallow-clone and deep-clone are extensible generics for ordinary and
native GOOPS objects. Copying a generic preserves the method entries'
public identities and original registration. Cloning a user-defined class
constructs a fresh class with its metaclass, parents and direct slots. The
new class computes its own precedence list, effective layout and accessors.
Deep cloning preserves cycles and sharing between recursively cloned instance
fields. Other field values, including lists of method specializers, stay shared.
The public direct-methods and direct-subclasses class fields can be
replaced independently of the private dependency registry. Later method or
class publication updates those public lists. Each field grows through its
owner's allocator. Its entries follow the same collector and arena lifetime
rules as the registry. Private class-redefinition ownership checks include
registered dependencies omitted from a public field.
GOOPS dispatch hooks
(vile goops) exports generic no-applicable-method, no-next-method,
and no-method hooks. Their default methods raise runtime errors and take
two arguments: the generic and a list of application arguments. As in current
Guile dispatch, a missing application invokes no-applicable-method even when
the generic has no methods, and retries the original application when the hook
returns. A hook can install a method before returning or exit through a
continuation. A hook that returns without making a method applicable keeps
retrying, subject to the VM instruction budget.
A missing next-method invokes no-next-method with the current arguments,
or explicit replacements passed to next-method. Its result is returned
directly, including multiple values. Hooks run on the current evaluator and
receive the public accessor identity for accessor calls. no-method is
available for explicit protocol calls; ordinary missing applications use
no-applicable-method.
GOOPS slot hooks
slot-missing and slot-unbound are customizable generics in (vile goops).
Missing instance reads call (slot-missing class object name); missing writes
add the attempted new value. The default write method delegates to the read
method. A missing slot-bound? call uses the missing-slot hook and returns
whether its result is bound; #f is a bound value. slot-exists? returns
#f without invoking a hook. Requests on builtin values can be customized
with a method specialized for their class.
An unbound instance field calls (slot-unbound object). An unbound shared or
virtual slot calls (slot-unbound class object name). Missing or unbound
class-slot operations call the respective hook with (class name). Class
slot writes use the same two-argument missing-slot protocol. Hook results
are returned to the caller; hooks may also exit or resume through continuations.
Calls run on the current evaluator. Reusable bridges handle missing reads,
bound checks and virtual reads without a nested machine per operation.
GOOPS slot reflection
class-direct-slots and class-slots return lists of <slot> objects;
class-slot-definition looks up an effective definition by symbol name and
returns #f when absent. Direct and effective definitions have separate
identity, including inherited definitions. Repeated lookups return the same
slot object, while the list queries return fresh list spines.
slot-definition-name, slot-definition-options, and
slot-definition-allocation expose the recorded metadata. Getter, setter,
accessor, init-keyword, and init-thunk queries use the corresponding
slot-definition- prefix and return #f when absent. slot-init-function
looks up the initializer thunk by class and slot name, failing for an unknown
slot. In a class slot specification, an init-value gets a constant thunk; an
init-form keeps its unevaluated form and a thunk capturing the defining lexical
environment.
slot-definition-init-value and slot-definition-init-form return an immutable
(unbound) singleton when absent. It is ordinary Scheme data. Storing that
singleton into a slot makes the slot unbound; a separately constructed list
containing the symbol unbound remains a bound value. Property queries reuse
metadata created with the class and allocate no new result objects.
make <slot> creates a standalone slot definition. It records the supplied
keyword/value list, including extension options, and uses the first value of a
repeated keyword. It does not synthesize a thunk for #:init-value or evaluate
#:init-form; supply #:init-thunk for instance or virtual initialization.
A class-allocated slot can use an init-value directly. A thunk must accept zero
arguments when its closure arity is known; native callbacks check their own
arguments when called.
Both make-class and make <class> accept prebuilt slot definitions. Each
prebuilt object retains its identity in class-direct-slots; effective and
inherited definitions are separate objects. Class layout allocates its own
shared storage without modifying the source slot. Reusing the same definition
in two defining classes creates independent class-allocated cells.
Effective-definition retargeting and raw-accessor construction follow the same
arena mutation rule as slot-set!: every definition being modified must belong
to the currently selected allocator. A class slots replacement validates all
its definitions before retargeting any of them, so an ownership error leaves
the existing class layout and all supplied definitions unchanged. Custom
compute-effective-slot-definition methods must return a definition in the
current mutation domain. An older definition can still be read, reused as a
direct-slot specification, or used as the source of inherited shared storage;
its existing getters remain callable while its owning arena stays alive.
(define x (make <slot> #:name 'x #:init-thunk (lambda () 42)))
(define <box>
(make <class> #:name '<box> #:dsupers (list <object>) #:slots (list x)))
(slot-ref (make <box>) 'x) ; 42
(eq? x (car (class-direct-slots <box>))) ; #t
The low-level make <class> keeps the supplied direct-superclass list; its
unsupplied name is ???. make-class continues to add <object> when needed.
Slot metadata can be changed through its native fields, subject to the arena
mutation rules above. Installing an effective layout validates the complete set
before retargeting any canonical definition. Retained slot handles and raw
accessors keep the storage they describe.