|
x-engine-c v0.2.13
The C engine for x-lang
|
Evaluator with TCO trampoline. More...
#include "x-eval.h"#include "x-env.h"#include "x-tco.h"#include "x-toplevel.h"#include "x-obj.h"#include "x-prim.h"#include "x-type.h"#include "x-alist.h"#include "x-type/ptr.h"#include "x-type/str.h"#include "x-type/list.h"#include "x-type/err.h"#include "x-type/symbol.h"#include "x-token.h"#include <setjmp.h>#include "x-type/prim.h"#include "x-eval-layout.h"Macros | |
| #define | nil NULL |
| #define | pair(X, Y) (x_mkspair(p_base, X_OBJ_FLAG_NONE, (X), (Y))) |
| #define | atom(X) (x_mksatom(p_base, X_OBJ_FLAG_NONE, (X))) |
| #define | X_EVAL_BUILD_TREE |
Variables | |
| static x_satom_t | x_type_prim_type_name_hook |
| static x_satom_t | x_type_prim_units_hook |
| static x_satom_t | x_type_prim_length_hook |
| static x_satom_t | s_bare_code = x_obj_set(NULL, X_OBJ_FLAG_NONE, { .s = NULL }) |
| static x_satom_t | s_bare_subject = x_obj_set(NULL, X_OBJ_FLAG_NONE, { .s = NULL }) |
| static x_spair_t | s_bare_err |
| static x_satom_t | x_eval_error_hook |
| static x_satom_t | x_type_heap_mark_hook |
| static x_satom_t | x_type_heap_free_hook |
Evaluator with TCO trampoline.
| #define atom | ( | X | ) | (x_mksatom(p_base, X_OBJ_FLAG_NONE, (X))) |
| #define nil NULL |
| #define pair | ( | X, | |
| Y | |||
| ) | (x_mkspair(p_base, X_OBJ_FLAG_NONE, (X), (Y))) |
| #define X_EVAL_BUILD_TREE |
Evaluate an expression with tail-call optimization.
Dispatches to the expression's type-level eval handler. If the handler sets a TCO tail expression on p_base, the trampoline loop re-evaluates without growing the C stack. On exit, restores the environment from the saved TCO snapshot.
| p_base | x_obj_t* – Base (execution context) |
| p_args | x_obj_t* – (expression . env) pair |
Outermost detection. The local trampolining flag starts at 0. When a TCO tail expression is first detected on p_base, this x_eval instance sets trampolining = 1, claiming ownership of the trampoline loop. Any nested x_eval called during handler dispatch will see tco_expr as cleared (this instance clears it before goto) and will therefore NOT enter the trampoline – it returns normally and its result is discarded in favor of the deferred tail expression.
tco_expr / tco_env lifecycle.
tco_env cleared: Each iteration clears tco_env on p_base after snapshotting it into the local p_tco_env_save. This prevents nested x_eval calls from seeing stale env state.
p_tco_env_save snapshot.
Used only at exit: the outermost x_eval makes it current.
Nested x_eval calls do NOT restore env. Only the instance where trampolining == 1 executes the env restore block. This is critical: a recursive x_eval (e.g. from evaluating a sub-expression inside a primitive) must not interfere with the outer trampoline's env management.
Evaluate a single expression.
Wraps p_arg in a stack-allocated (atom . nil) pair and passes it through x_eval, which unwraps and evaluates the inner expression.
| p_base | x_obj_t* – Base (execution context) |
| p_arg | x_obj_t* – Expression to evaluate |
Evaluate a body (list of expressions) sequentially, returning the last result.
Each expression is rooted on the eval-list before evaluation so the GC does not collect the remaining body. No tail-call optimization.
| p_base | x_obj_t* – Base (execution context) |
| p_body | x_obj_t* – List of body expressions |
Evaluate a body with full tail-call optimization.
Non-tail expressions are evaluated normally. The tail (last) expression is stored in the TCO expr slot instead of being evaluated directly, and the caller's saved environment is captured in tco-env so the trampoline can restore it after the tail call.
On early exit (nil tail) or empty body, pops the save-stack and makes the environment it held current again.
| p_base | x_obj_t* – Base (execution context) |
| p_body | x_obj_t* – List of body expressions |
Save-stack protocol. The caller (fn/let dispatch) pushes the environment it is leaving onto save_stack BEFORE calling this function (x_tco_env_save), so it can be made current again after the tail call completes.
tco_env capture. When the tail expression is reached (last element of body), this function checks whether tco_env is still nil. If so, it copies the save-stack top into tco_env, providing the env snapshot that x_eval's trampoline will use for restoration. If tco_env is already set (by a prior TCO iteration), the existing value is kept.
Save-stack pop. After capturing tco_env (or on early exit), the save-stack is popped. On the normal tail-call path this is a simple pop (the trampoline in x_eval handles restore). On early exit (nil tail or empty body), this function does a full restore from the popped frame before returning, since no trampoline iteration will follow.
Push a buffer onto the buffer stack.
| p_base | x_obj_t* – Base (execution context) |
| p_buffer | x_obj_t* – Buffer object to push |
Signal an error with a message and optional object context.
If an error handler is installed (via guard), builds a combined error string with line number, restores the saved environment, and longjmps to the handler. Otherwise, writes the error to stderr via the low-level x_error function.
| p_base | x_obj_t* – Base (execution context) |
| message | x_char_t* – Error message string |
| p_obj | x_obj_t* – Object associated with the error (may be NULL) |
Zero-allocation error path. When a handler is installed, the message string pointer is stored directly in a static atom (no malloc, no x_mkstrown). Message strings from C callers are always string literals (static storage), so they survive the longjmp. The guard handler in x-lang receives the bare message; x-lang code can add line/symbol context via (base) if needed.
longjmp protocol. The error value is stored in the handler's error slot, then the environment the handler saved at guard installation time is made current again. Finally, longjmp transfers control to the setjmp site in x_prim_guard. This unwinds all C frames between the error site and the guard – any local state in those frames is lost.
error). Returning instead would resume the raising primitive mid-operation with a garbage value – at boot, where no guard is installed yet and the harness discards stderr, that silently corrupted the load (the class-call trap).Evaluate each element of a list, returning a new list of results.
Recursively evaluates via x_eval_arg, rooting the tail on the eval-list GC root so the garbage collector does not free remaining arguments while evaluating the current one.
| p_base | x_obj_t* – Base (execution context) |
| p_args | x_obj_t* – List of unevaluated expressions |
GC rooting protocol. Before evaluating the current element, the entire remaining arg list is pushed onto eval_list (a GC root on p_base) as a stack-allocated pair. This prevents the collector from freeing the rest of the list while x_eval_arg runs (which may trigger GC). After evaluation, the root is popped. The push/pop is O(1) per element, but the recursion itself is O(n) in C stack depth – one frame per list element. This is acceptable for argument lists (typically short) but would overflow on very long lists.
Read and evaluate all expressions from the current buffer.
Loops calling x_token_read until EOF, evaluating each expression via x_eval. Returns the result of the last expression.
| p_base | x_obj_t* – Base (execution context) |
| p_args | x_obj_t* – Unused |
Reads from the buffer at the top of the buffer stack (x_base_field_buffer). The caller is responsible for pushing the desired buffer before calling this function (via x_eval_buffer_push) and popping it afterward. Each read expression is wrapped in a stack-allocated (atom . nil) eval-args pair and passed to x_eval, which runs the full evaluator including the TCO trampoline. The result of each expression is discarded except the last.
cat lib/x.x - | ./x-bin). The core loop reads through the buffer/fd stack; the optional include primitive (X_INCLUDE, x-cli.c) additionally opens files via x_sys_open and pushes them onto the same stack.Create and initialize a full x-lang base object atop x-expr.
Calls x_base_make (x-expr layer) with default file descriptors and hooks, then fills in the type-system-specific slots: env-group (the current environment and the root), ctrl-group (save-stack, error-handler, TCO slots), io-state (line counter, boolean caches), extended profile counters, and project extras (eval-list, token-cache, mark/free hooks, mark-roots).
| p_base | x_obj_t* – Parent base (or NULL for root) |
| p_args | x_obj_t* – Unused |
x-expr vs x-lang layers. x_base_make (x-expr) allocates the base tree skeleton: heap group (pools, GC state), file descriptors, buffer stack, type-alist slot, profile head (1 counter for GC cycles), and hook slots. It leaves env, ctrl, io-state, and extras as nil. This function fills all of those in, giving the base its full evaluator personality.
Base tree nodes carry X_OBJ_FLAG_SHARED (set by x-expr's x_base_make). The SHARED flag tells the GC mark phase that these spine nodes are allocated from the base's own pool and must be marked but never freed – they are structurally permanent for the lifetime of the base.
Env-group layout:
env-root: the base's root environment, whose bindings are a tree and whose parent is nil
Ctrl-group layout:
Profile counters (9 additional beyond x-expr's GC counter): evals, TCO hits, lookups, BST lookups, and internal metrics.
p_base is non-NULL (child base), boolean caches (#t/#f) are inherited from the parent so all bases in a tree share the same singleton boolean objects.Defer an operative body's tail to the outer trampoline (TCO).
Evaluates the non-tail body forms synchronously, then stores the tail form in tco_expr and the caller's environment in tco_env. Deliberately does NOT push the save-stack – operatives stay invisible to it, so a procedure whose tail is an operative call still owns its own restore. The trampoline keeps the outermost environment it is handed and makes it current at exit, which for an operative is the caller's: a def the body evaluated in the caller's environment is IN that environment, so there is nothing to decide about keeping or shedding a chain head.
| p_base | x_obj_t* – Base (execution context) |
| p_body | x_obj_t* – Operative body (sequence of forms) |
| p_caller | x_obj_t* – The caller's environment, current on return |
Read the argument at an already-navigated spine position.
| p_base | Base (execution context). |
| p_pos | A spine position (the result of an x_1/x_11 peek). |
p_pos, or nil if the list ended there.The raw positional macros (x_011 and friends) navigate first/rest UNCHECKED, which is their contract – so a caller peeking PAST the arity a guarded walk covered used to read the atom a dotted tail ends with as a pair (#487). This is that peek, done safely: nil when the list ended, the element when the position is a cell, and the ruled catchable raise on anything else.
Raise unless p_obj is a spine cell that first/rest may navigate.
| p_base | Base (execution context). |
| p_obj | The spine position about to be walked (never nil). |
Improper-spine guard (#69, ruled). A first/rest walk is only meaningful for an object whose TYPE DECLARES pair units – the same shape contract the collector's payload walk trusts (x_type_prim_heap_mark). The test is STRUCTURAL, not a type-identity list: any reader personality's spine type participates by declaring pair units (the reader and the evaluator need not be symmetric), and two shapes are cells by construction – raw stack cells (NULL type slot) and heap pairs tagged with the built-in pair static (the x_mkspair product; #296). The static's own type slot is NULL, so the registered-type probe could never accept it – omitting it made every C-built spine handed to an applicative in a minimal base raise spuriously. A dotted tail lands here as a non-cell and raises a catchable error in place of the segfault it replaces – (list 1 . 5), and bare-x-core (f 1.5) where the float module is absent and 1.5 reads as a dotted pair; the tail atom is atom-tagged or registered-typed, so neither shape re-admits it.
|
static |
TCO trampoline: repeatedly evaluate deferred tail expressions.
After a TCO-aware body defers its tail expression, this loop evaluates it. If that evaluation itself defers another tail call, the loop continues until no more TCO expressions remain.
On exit, makes the environment saved in tco-env current again.
| p_base | x_obj_t* – Base (execution context) |
| p_result | x_obj_t* – Initial result (from non-tail evaluation) |
Look up a type struct in the base's type alist by name.
Searches for a (name . type_struct) entry matching the first element of p_args. Returns the bare type struct (unwrapped from the alist entry), or NULL if not found.
| p_base | x_obj_t* – Base (execution context) |
| p_args | x_obj_t* – Pair whose first is the type name to look up |
Add a type struct to the base's type alist.
Wraps the type struct as a (name . type_struct) pair for alist keying and prepends it to the type alist.
| p_base | x_obj_t* – Base (execution context) |
| p_args | x_obj_t* – Type struct to register |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |