OCaml bootstrapper Phase 2: HTML renderer, SX server, Python bridge

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-15 23:28:48 +00:00
parent 16fa813d6d
commit 313f7d6be1
18 changed files with 2541 additions and 191 deletions

View File

@@ -22,7 +22,7 @@ let skip_whitespace_and_comments s =
let rec go () =
if at_end s then ()
else match s.src.[s.pos] with
| ' ' | '\t' | '\n' | '\r' | ',' -> advance s; go ()
| ' ' | '\t' | '\n' | '\r' -> advance s; go ()
| ';' ->
while s.pos < s.len && s.src.[s.pos] <> '\n' do advance s done;
if s.pos < s.len then advance s;
@@ -63,6 +63,7 @@ let read_string s =
let ubuf = Buffer.create 4 in
Buffer.add_utf_8_uchar ubuf (Uchar.of_int code);
Buffer.add_string buf (Buffer.contents ubuf)
| '`' -> Buffer.add_char buf '`'
| _ -> Buffer.add_char buf '\\'; Buffer.add_char buf esc);
go ()
end else begin
@@ -91,6 +92,30 @@ let rec read_value s : value =
| '"' -> String (read_string s)
| '\'' -> advance s; List [Symbol "quote"; read_value s]
| '`' -> advance s; List [Symbol "quasiquote"; read_value s]
| '#' when s.pos + 1 < s.len && s.src.[s.pos + 1] = ';' ->
(* Datum comment: #; discards next expression *)
advance s; advance s;
ignore (read_value s);
read_value s
| '#' when s.pos + 1 < s.len && s.src.[s.pos + 1] = '\'' ->
(* Quote shorthand: #'expr -> (quote expr) *)
advance s; advance s;
List [Symbol "quote"; read_value s]
| '#' when s.pos + 1 < s.len && s.src.[s.pos + 1] = '|' ->
(* Raw string: #|...| — ends at next | *)
advance s; advance s;
let buf = Buffer.create 64 in
let rec go () =
if at_end s then raise (Parse_error "Unterminated raw string");
let c = s.src.[s.pos] in
advance s;
if c = '|' then
String (Buffer.contents buf)
else begin
Buffer.add_char buf c;
go ()
end
in go ()
| '~' when s.pos + 1 < s.len && s.src.[s.pos + 1] = '@' ->
advance s; advance s; (* skip ~@ *)
List [Symbol "splice-unquote"; read_value s]

View File

@@ -20,6 +20,10 @@ let get_primitive name =
let as_number = function
| Number n -> n
| Bool true -> 1.0
| Bool false -> 0.0
| Nil -> 0.0
| String s -> (match float_of_string_opt s with Some n -> n | None -> Float.nan)
| v -> raise (Eval_error ("Expected number, got " ^ type_of v))
let as_string = function
@@ -28,6 +32,8 @@ let as_string = function
let as_list = function
| List l -> l
| ListRef r -> !r
| Nil -> []
| v -> raise (Eval_error ("Expected list, got " ^ type_of v))
let as_bool = function
@@ -116,18 +122,40 @@ let () =
| _ -> Nil);
(* === Comparison === *)
(* Normalize ListRef to List for structural equality *)
let rec normalize_for_eq = function
| ListRef { contents = items } -> List (List.map normalize_for_eq items)
| List items -> List (List.map normalize_for_eq items)
| v -> v
in
register "=" (fun args ->
match args with [a; b] -> Bool (a = b) | _ -> raise (Eval_error "=: 2 args"));
match args with
| [a; b] -> Bool (normalize_for_eq a = normalize_for_eq b)
| _ -> raise (Eval_error "=: 2 args"));
register "!=" (fun args ->
match args with [a; b] -> Bool (a <> b) | _ -> raise (Eval_error "!=: 2 args"));
match args with
| [a; b] -> Bool (normalize_for_eq a <> normalize_for_eq b)
| _ -> raise (Eval_error "!=: 2 args"));
register "<" (fun args ->
match args with [a; b] -> Bool (as_number a < as_number b) | _ -> raise (Eval_error "<: 2 args"));
match args with
| [String a; String b] -> Bool (a < b)
| [a; b] -> Bool (as_number a < as_number b)
| _ -> raise (Eval_error "<: 2 args"));
register ">" (fun args ->
match args with [a; b] -> Bool (as_number a > as_number b) | _ -> raise (Eval_error ">: 2 args"));
match args with
| [String a; String b] -> Bool (a > b)
| [a; b] -> Bool (as_number a > as_number b)
| _ -> raise (Eval_error ">: 2 args"));
register "<=" (fun args ->
match args with [a; b] -> Bool (as_number a <= as_number b) | _ -> raise (Eval_error "<=: 2 args"));
match args with
| [String a; String b] -> Bool (a <= b)
| [a; b] -> Bool (as_number a <= as_number b)
| _ -> raise (Eval_error "<=: 2 args"));
register ">=" (fun args ->
match args with [a; b] -> Bool (as_number a >= as_number b) | _ -> raise (Eval_error ">=: 2 args"));
match args with
| [String a; String b] -> Bool (a >= b)
| [a; b] -> Bool (as_number a >= as_number b)
| _ -> raise (Eval_error ">=: 2 args"));
(* === Logic === *)
register "not" (fun args ->
@@ -143,7 +171,7 @@ let () =
register "boolean?" (fun args ->
match args with [Bool _] -> Bool true | [_] -> Bool false | _ -> raise (Eval_error "boolean?: 1 arg"));
register "list?" (fun args ->
match args with [List _] -> Bool true | [_] -> Bool false | _ -> raise (Eval_error "list?: 1 arg"));
match args with [List _] | [ListRef _] -> Bool true | [_] -> Bool false | _ -> raise (Eval_error "list?: 1 arg"));
register "dict?" (fun args ->
match args with [Dict _] -> Bool true | [_] -> Bool false | _ -> raise (Eval_error "dict?: 1 arg"));
register "symbol?" (fun args ->
@@ -152,7 +180,8 @@ let () =
match args with [Keyword _] -> Bool true | [_] -> Bool false | _ -> raise (Eval_error "keyword?: 1 arg"));
register "empty?" (fun args ->
match args with
| [List []] -> Bool true | [List _] -> Bool false
| [List []] | [ListRef { contents = [] }] -> Bool true
| [List _] | [ListRef _] -> Bool false
| [String ""] -> Bool true | [String _] -> Bool false
| [Dict d] -> Bool (Hashtbl.length d = 0)
| [Nil] -> Bool true
@@ -240,7 +269,8 @@ let () =
| _ -> raise (Eval_error "split: 2 args"));
register "join" (fun args ->
match args with
| [String sep; List items] -> String (String.concat sep (List.map to_string items))
| [String sep; (List items | ListRef { contents = items })] ->
String (String.concat sep (List.map to_string items))
| _ -> raise (Eval_error "join: 2 args"));
register "replace" (fun args ->
match args with
@@ -271,48 +301,58 @@ let () =
| _ -> raise (Eval_error "char-from-code: 1 arg"));
(* === Collections === *)
register "list" (fun args -> List args);
register "list" (fun args -> ListRef (ref args));
register "len" (fun args ->
match args with
| [List l] -> Number (float_of_int (List.length l))
| [List l] | [ListRef { contents = l }] -> Number (float_of_int (List.length l))
| [String s] -> Number (float_of_int (String.length s))
| [Dict d] -> Number (float_of_int (Hashtbl.length d))
| [Nil] -> Number 0.0
| _ -> raise (Eval_error "len: 1 arg"));
register "first" (fun args ->
match args with
| [List (x :: _)] -> x | [List []] -> Nil
| [List (x :: _)] | [ListRef { contents = x :: _ }] -> x
| [List []] | [ListRef { contents = [] }] -> Nil | [Nil] -> Nil
| _ -> raise (Eval_error "first: 1 list arg"));
register "rest" (fun args ->
match args with
| [List (_ :: xs)] -> List xs | [List []] -> List []
| [List (_ :: xs)] | [ListRef { contents = _ :: xs }] -> List xs
| [List []] | [ListRef { contents = [] }] -> List [] | [Nil] -> List []
| _ -> raise (Eval_error "rest: 1 list arg"));
register "last" (fun args ->
match args with
| [List l] -> (match List.rev l with x :: _ -> x | [] -> Nil)
| [List l] | [ListRef { contents = l }] ->
(match List.rev l with x :: _ -> x | [] -> Nil)
| _ -> raise (Eval_error "last: 1 list arg"));
register "nth" (fun args ->
match args with
| [List l; Number n] -> (try List.nth l (int_of_float n) with _ -> Nil)
| [List l; Number n] | [ListRef { contents = l }; Number n] ->
(try List.nth l (int_of_float n) with _ -> Nil)
| _ -> raise (Eval_error "nth: list and number"));
register "cons" (fun args ->
match args with
| [x; List l] -> List (x :: l)
| [x; List l] | [x; ListRef { contents = l }] -> List (x :: l)
| [x; Nil] -> List [x]
| _ -> raise (Eval_error "cons: value and list"));
register "append" (fun args ->
let all = List.concat_map (fun a -> as_list a) args in
List all);
register "reverse" (fun args ->
match args with [List l] -> List (List.rev l) | _ -> raise (Eval_error "reverse: 1 list"));
match args with
| [List l] | [ListRef { contents = l }] -> List (List.rev l)
| _ -> raise (Eval_error "reverse: 1 list"));
register "flatten" (fun args ->
let rec flat = function
| List items -> List.concat_map flat items
| List items | ListRef { contents = items } -> List.concat_map flat items
| x -> [x]
in
match args with [List l] -> List (List.concat_map flat l) | _ -> raise (Eval_error "flatten: 1 list"));
match args with
| [List l] | [ListRef { contents = l }] -> List (List.concat_map flat l)
| _ -> raise (Eval_error "flatten: 1 list"));
register "concat" (fun args -> List (List.concat_map as_list args));
register "contains?" (fun args ->
match args with
| [List l; item] -> Bool (List.mem item l)
| [List l; item] | [ListRef { contents = l }; item] -> Bool (List.mem item l)
| [String s; String sub] ->
let rec find i =
if i + String.length sub > String.length s then false
@@ -329,14 +369,25 @@ let () =
let s = int_of_float start and e = int_of_float stop in
let len = max 0 (e - s) in
List (List.init len (fun i -> Number (float_of_int (s + i))))
| _ -> raise (Eval_error "range: 1-2 args"));
| [Number start; Number stop; Number step] ->
let s = start and e = stop and st = step in
if st = 0.0 then List []
else
let items = ref [] in
let i = ref s in
if st > 0.0 then
(while !i < e do items := Number !i :: !items; i := !i +. st done)
else
(while !i > e do items := Number !i :: !items; i := !i +. st done);
List (List.rev !items)
| _ -> raise (Eval_error "range: 1-3 args"));
register "slice" (fun args ->
match args with
| [List l; Number start] ->
| [(List l | ListRef { contents = l }); Number start] ->
let i = max 0 (int_of_float start) in
let rec drop n = function _ :: xs when n > 0 -> drop (n-1) xs | l -> l in
List (drop i l)
| [List l; Number start; Number end_] ->
| [(List l | ListRef { contents = l }); Number start; Number end_] ->
let i = max 0 (int_of_float start) and j = int_of_float end_ in
let len = List.length l in
let j = min j len in
@@ -358,19 +409,21 @@ let () =
| _ -> raise (Eval_error "slice: 2-3 args"));
register "sort" (fun args ->
match args with
| [List l] -> List (List.sort compare l)
| [List l] | [ListRef { contents = l }] -> List (List.sort compare l)
| _ -> raise (Eval_error "sort: 1 list"));
register "zip" (fun args ->
match args with
| [List a; List b] ->
| [a; b] ->
let la = as_list a and lb = as_list b in
let rec go l1 l2 acc = match l1, l2 with
| x :: xs, y :: ys -> go xs ys (List [x; y] :: acc)
| _ -> List.rev acc
in List (go a b [])
in List (go la lb [])
| _ -> raise (Eval_error "zip: 2 lists"));
register "zip-pairs" (fun args ->
match args with
| [List l] ->
| [v] ->
let l = as_list v in
let rec go = function
| a :: b :: rest -> List [a; b] :: go rest
| _ -> []
@@ -378,7 +431,7 @@ let () =
| _ -> raise (Eval_error "zip-pairs: 1 list"));
register "take" (fun args ->
match args with
| [List l; Number n] ->
| [(List l | ListRef { contents = l }); Number n] ->
let rec take_n i = function
| x :: xs when i > 0 -> x :: take_n (i-1) xs
| _ -> []
@@ -386,7 +439,7 @@ let () =
| _ -> raise (Eval_error "take: list and number"));
register "drop" (fun args ->
match args with
| [List l; Number n] ->
| [(List l | ListRef { contents = l }); Number n] ->
let rec drop_n i = function
| _ :: xs when i > 0 -> drop_n (i-1) xs
| l -> l
@@ -394,7 +447,7 @@ let () =
| _ -> raise (Eval_error "drop: list and number"));
register "chunk-every" (fun args ->
match args with
| [List l; Number n] ->
| [(List l | ListRef { contents = l }); Number n] ->
let size = int_of_float n in
let rec go = function
| [] -> []
@@ -412,7 +465,7 @@ let () =
| _ -> raise (Eval_error "chunk-every: list and number"));
register "unique" (fun args ->
match args with
| [List l] ->
| [(List l | ListRef { contents = l })] ->
let seen = Hashtbl.create 16 in
let result = List.filter (fun x ->
let key = inspect x in
@@ -435,7 +488,8 @@ let () =
match args with
| [Dict d; String k] -> dict_get d k
| [Dict d; Keyword k] -> dict_get d k
| [List l; Number n] -> (try List.nth l (int_of_float n) with _ -> Nil)
| [List l; Number n] | [ListRef { contents = l }; Number n] ->
(try List.nth l (int_of_float n) with _ -> Nil)
| _ -> raise (Eval_error "get: dict+key or list+index"));
register "has-key?" (fun args ->
match args with

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,435 @@
(** HTML renderer for SX values.
Extracted from run_tests.ml — renders an SX expression tree to an
HTML string, expanding components and macros along the way.
Depends on [Sx_ref.eval_expr] for evaluating sub-expressions
during rendering (keyword arg values, conditionals, etc.). *)
open Sx_types
(* ====================================================================== *)
(* Tag / attribute registries *)
(* ====================================================================== *)
let html_tags = [
"html"; "head"; "body"; "title"; "meta"; "link"; "script"; "style"; "noscript";
"header"; "nav"; "main"; "section"; "article"; "aside"; "footer";
"h1"; "h2"; "h3"; "h4"; "h5"; "h6"; "hgroup";
"div"; "p"; "blockquote"; "pre"; "figure"; "figcaption"; "address"; "hr";
"ul"; "ol"; "li"; "dl"; "dt"; "dd"; "menu";
"a"; "span"; "em"; "strong"; "small"; "b"; "i"; "u"; "s"; "sub"; "sup";
"mark"; "del"; "ins"; "q"; "cite"; "dfn"; "abbr"; "code"; "var"; "samp";
"kbd"; "data"; "time"; "ruby"; "rt"; "rp"; "bdi"; "bdo"; "wbr"; "br";
"table"; "thead"; "tbody"; "tfoot"; "tr"; "th"; "td"; "caption"; "colgroup"; "col";
"form"; "input"; "textarea"; "select"; "option"; "optgroup"; "button"; "label";
"fieldset"; "legend"; "datalist"; "output"; "progress"; "meter";
"details"; "summary"; "dialog";
"img"; "video"; "audio"; "source"; "picture"; "canvas"; "iframe"; "embed"; "object"; "param";
"svg"; "path"; "circle"; "rect"; "line"; "polyline"; "polygon"; "ellipse";
"g"; "defs"; "use"; "text"; "tspan"; "clipPath"; "mask"; "pattern";
"linearGradient"; "radialGradient"; "stop"; "filter"; "feBlend"; "feFlood";
"feGaussianBlur"; "feOffset"; "feMerge"; "feMergeNode"; "feComposite";
"template"; "slot";
]
let void_elements = [
"area"; "base"; "br"; "col"; "embed"; "hr"; "img"; "input";
"link"; "meta"; "param"; "source"; "track"; "wbr"
]
let boolean_attrs = [
"async"; "autofocus"; "autoplay"; "checked"; "controls"; "default";
"defer"; "disabled"; "formnovalidate"; "hidden"; "inert"; "ismap";
"loop"; "multiple"; "muted"; "nomodule"; "novalidate"; "open";
"playsinline"; "readonly"; "required"; "reversed"; "selected"
]
let is_html_tag name = List.mem name html_tags
let is_void name = List.mem name void_elements
let is_boolean_attr name = List.mem name boolean_attrs
(* ====================================================================== *)
(* HTML escaping *)
(* ====================================================================== *)
let escape_html s =
let buf = Buffer.create (String.length s) in
String.iter (function
| '&' -> Buffer.add_string buf "&amp;"
| '<' -> Buffer.add_string buf "&lt;"
| '>' -> Buffer.add_string buf "&gt;"
| '"' -> Buffer.add_string buf "&quot;"
| c -> Buffer.add_char buf c) s;
Buffer.contents buf
(* ====================================================================== *)
(* Attribute rendering *)
(* ====================================================================== *)
let render_attrs attrs =
let buf = Buffer.create 64 in
Hashtbl.iter (fun k v ->
if is_boolean_attr k then begin
if sx_truthy v then begin
Buffer.add_char buf ' ';
Buffer.add_string buf k
end
end else if not (is_nil v) then begin
Buffer.add_char buf ' ';
Buffer.add_string buf k;
Buffer.add_string buf "=\"";
Buffer.add_string buf (escape_html (value_to_string v));
Buffer.add_char buf '"'
end) attrs;
Buffer.contents buf
(* ====================================================================== *)
(* HTML renderer *)
(* ====================================================================== *)
(* Forward ref — resolved at setup time *)
let render_to_html_ref : (value -> env -> string) ref =
ref (fun _expr _env -> "")
let render_to_html expr env = !render_to_html_ref expr env
let render_children children env =
String.concat "" (List.map (fun c -> render_to_html c env) children)
(** Parse keyword attrs and positional children from an element call's args.
Attrs are evaluated; children are returned UNEVALUATED for render dispatch. *)
let parse_element_args args env =
let attrs = Hashtbl.create 8 in
let children = ref [] in
let skip = ref false in
let len = List.length args in
List.iteri (fun idx arg ->
if !skip then skip := false
else match arg with
| Keyword k when idx + 1 < len ->
let v = Sx_ref.eval_expr (List.nth args (idx + 1)) (Env env) in
Hashtbl.replace attrs k v;
skip := true
| Spread pairs ->
List.iter (fun (k, v) -> Hashtbl.replace attrs k v) pairs
| _ ->
children := arg :: !children
) args;
(attrs, List.rev !children)
let render_html_element tag args env =
let (attrs, children) = parse_element_args args env in
let attr_str = render_attrs attrs in
if is_void tag then
"<" ^ tag ^ attr_str ^ " />"
else
let content = String.concat ""
(List.map (fun c -> render_to_html c env) children) in
"<" ^ tag ^ attr_str ^ ">" ^ content ^ "</" ^ tag ^ ">"
let render_component comp args env =
match comp with
| Component c ->
let kwargs = Hashtbl.create 8 in
let children_exprs = ref [] in
let skip = ref false in
let len = List.length args in
List.iteri (fun idx arg ->
if !skip then skip := false
else match arg with
| Keyword k when idx + 1 < len ->
let v = Sx_ref.eval_expr (List.nth args (idx + 1)) (Env env) in
Hashtbl.replace kwargs k v;
skip := true
| _ ->
children_exprs := arg :: !children_exprs
) args;
let children = List.rev !children_exprs in
let local = env_merge c.c_closure env in
List.iter (fun p ->
let v = match Hashtbl.find_opt kwargs p with Some v -> v | None -> Nil in
ignore (env_bind local p v)
) c.c_params;
if c.c_has_children then begin
let rendered_children = String.concat ""
(List.map (fun c -> render_to_html c env) children) in
ignore (env_bind local "children" (RawHTML rendered_children))
end;
render_to_html c.c_body local
| _ -> ""
let expand_macro (m : macro) args _env =
let local = env_extend m.m_closure in
let params = m.m_params in
let rec bind_params ps as' =
match ps, as' with
| [], rest ->
(match m.m_rest_param with
| Some rp -> ignore (env_bind local rp (List rest))
| None -> ())
| p :: ps_rest, a :: as_rest ->
ignore (env_bind local p a);
bind_params ps_rest as_rest
| _ :: _, [] ->
List.iter (fun p -> ignore (env_bind local p Nil)) (List.rev ps)
in
bind_params params args;
Sx_ref.eval_expr m.m_body (Env local)
let rec do_render_to_html (expr : value) (env : env) : string =
match expr with
| Nil -> ""
| Bool true -> "true"
| Bool false -> "false"
| Number n ->
if Float.is_integer n then string_of_int (int_of_float n)
else Printf.sprintf "%g" n
| String s -> escape_html s
| Keyword k -> escape_html k
| RawHTML s -> s
| Symbol s ->
let v = Sx_ref.eval_expr (Symbol s) (Env env) in
do_render_to_html v env
| List [] | ListRef { contents = [] } -> ""
| List (head :: args) | ListRef { contents = head :: args } ->
render_list_to_html head args env
| _ ->
let v = Sx_ref.eval_expr expr (Env env) in
do_render_to_html v env
and render_list_to_html head args env =
match head with
| Symbol "<>" ->
render_children args env
| Symbol tag when is_html_tag tag ->
render_html_element tag args env
| Symbol "if" ->
let cond_val = Sx_ref.eval_expr (List.hd args) (Env env) in
if sx_truthy cond_val then
(if List.length args > 1 then do_render_to_html (List.nth args 1) env else "")
else
(if List.length args > 2 then do_render_to_html (List.nth args 2) env else "")
| Symbol "when" ->
let cond_val = Sx_ref.eval_expr (List.hd args) (Env env) in
if sx_truthy cond_val then
String.concat "" (List.map (fun e -> do_render_to_html e env) (List.tl args))
else ""
| Symbol "cond" ->
render_cond args env
| Symbol "case" ->
let v = Sx_ref.eval_expr (List (head :: args)) (Env env) in
do_render_to_html v env
| Symbol ("let" | "let*") ->
render_let args env
| Symbol ("begin" | "do") ->
let rec go = function
| [] -> ""
| [last] -> do_render_to_html last env
| e :: rest ->
ignore (Sx_ref.eval_expr e (Env env));
go rest
in go args
| Symbol ("define" | "defcomp" | "defmacro" | "defisland") ->
ignore (Sx_ref.eval_expr (List (head :: args)) (Env env));
""
| Symbol "map" ->
render_map args env false
| Symbol "map-indexed" ->
render_map args env true
| Symbol "filter" ->
let v = Sx_ref.eval_expr (List (head :: args)) (Env env) in
do_render_to_html v env
| Symbol "for-each" ->
render_for_each args env
| Symbol name ->
(try
let v = env_get env name in
(match v with
| Component _ -> render_component v args env
| Macro m ->
let expanded = expand_macro m args env in
do_render_to_html expanded env
| _ ->
let result = Sx_ref.eval_expr (List (head :: args)) (Env env) in
do_render_to_html result env)
with Eval_error _ ->
let result = Sx_ref.eval_expr (List (head :: args)) (Env env) in
do_render_to_html result env)
| _ ->
let result = Sx_ref.eval_expr (List (head :: args)) (Env env) in
do_render_to_html result env
and render_cond args env =
let as_list = function List l | ListRef { contents = l } -> Some l | _ -> None in
let is_scheme = List.for_all (fun a -> match as_list a with
| Some items when List.length items = 2 -> true
| _ -> false) args
in
if is_scheme then begin
let rec go = function
| [] -> ""
| clause :: rest ->
(match as_list clause with
| Some [test; body] ->
let is_else = match test with
| Keyword "else" -> true
| Symbol "else" | Symbol ":else" -> true
| _ -> false
in
if is_else then do_render_to_html body env
else
let v = Sx_ref.eval_expr test (Env env) in
if sx_truthy v then do_render_to_html body env
else go rest
| _ -> "")
in go args
end else begin
let rec go = function
| [] -> ""
| [_] -> ""
| test :: body :: rest ->
let is_else = match test with
| Keyword "else" -> true
| Symbol "else" | Symbol ":else" -> true
| _ -> false
in
if is_else then do_render_to_html body env
else
let v = Sx_ref.eval_expr test (Env env) in
if sx_truthy v then do_render_to_html body env
else go rest
in go args
end
and render_let args env =
let as_list = function List l | ListRef { contents = l } -> Some l | _ -> None in
let bindings_expr = List.hd args in
let body = List.tl args in
let local = env_extend env in
let bindings = match as_list bindings_expr with Some l -> l | None -> [] in
let is_scheme = match bindings with
| (List _ :: _) | (ListRef _ :: _) -> true
| _ -> false
in
if is_scheme then
List.iter (fun b ->
match as_list b with
| Some [Symbol name; expr] | Some [String name; expr] ->
let v = Sx_ref.eval_expr expr (Env local) in
ignore (env_bind local name v)
| _ -> ()
) bindings
else begin
let rec go = function
| [] -> ()
| (Symbol name) :: expr :: rest | (String name) :: expr :: rest ->
let v = Sx_ref.eval_expr expr (Env local) in
ignore (env_bind local name v);
go rest
| _ -> ()
in go bindings
end;
let rec render_body = function
| [] -> ""
| [last] -> do_render_to_html last local
| e :: rest ->
ignore (Sx_ref.eval_expr e (Env local));
render_body rest
in render_body body
and render_map args env indexed =
let (fn_val, coll_val) = match args with
| [a; b] ->
let va = Sx_ref.eval_expr a (Env env) in
let vb = Sx_ref.eval_expr b (Env env) in
(match va, vb with
| (Lambda _ | NativeFn _), _ -> (va, vb)
| _, (Lambda _ | NativeFn _) -> (vb, va)
| _ -> (va, vb))
| _ -> (Nil, Nil)
in
let items = match coll_val with List l | ListRef { contents = l } -> l | _ -> [] in
String.concat "" (List.mapi (fun i item ->
let call_args = if indexed then [Number (float_of_int i); item] else [item] in
match fn_val with
| Lambda l ->
let local = env_extend l.l_closure in
List.iter2 (fun p a -> ignore (env_bind local p a))
l.l_params call_args;
do_render_to_html l.l_body local
| _ ->
let result = Sx_runtime.sx_call fn_val call_args in
do_render_to_html result env
) items)
and render_for_each args env =
let (fn_val, coll_val) = match args with
| [a; b] ->
let va = Sx_ref.eval_expr a (Env env) in
let vb = Sx_ref.eval_expr b (Env env) in
(match va, vb with
| (Lambda _ | NativeFn _), _ -> (va, vb)
| _, (Lambda _ | NativeFn _) -> (vb, va)
| _ -> (va, vb))
| _ -> (Nil, Nil)
in
let items = match coll_val with List l | ListRef { contents = l } -> l | _ -> [] in
String.concat "" (List.map (fun item ->
match fn_val with
| Lambda l ->
let local = env_extend l.l_closure in
List.iter2 (fun p a -> ignore (env_bind local p a))
l.l_params [item];
do_render_to_html l.l_body local
| _ ->
let result = Sx_runtime.sx_call fn_val [item] in
do_render_to_html result env
) items)
(* ====================================================================== *)
(* Setup — bind render primitives in an env and wire up the ref *)
(* ====================================================================== *)
let setup_render_env env =
render_to_html_ref := do_render_to_html;
let bind name fn =
ignore (env_bind env name (NativeFn (name, fn)))
in
bind "render-html" (fun args ->
match args with
| [String src] ->
let exprs = Sx_parser.parse_all src in
let expr = match exprs with
| [e] -> e
| [] -> Nil
| _ -> List (Symbol "do" :: exprs)
in
String (render_to_html expr env)
| [expr] ->
String (render_to_html expr env)
| [expr; Env e] ->
String (render_to_html expr e)
| _ -> String "");
bind "render-to-html" (fun args ->
match args with
| [String src] ->
let exprs = Sx_parser.parse_all src in
let expr = match exprs with
| [e] -> e
| [] -> Nil
| _ -> List (Symbol "do" :: exprs)
in
String (render_to_html expr env)
| [expr] ->
String (render_to_html expr env)
| [expr; Env e] ->
String (render_to_html expr e)
| _ -> String "")

View File

@@ -35,6 +35,7 @@ let sx_str args =
(** Convert a value to a list. *)
let sx_to_list = function
| List l -> l
| ListRef r -> !r
| Nil -> []
| v -> raise (Eval_error ("Expected list, got " ^ type_of v))
@@ -60,6 +61,7 @@ let sx_apply f args_list =
let sx_append_b lst item =
match lst with
| List items -> List (items @ [item])
| ListRef r -> r := !r @ [item]; lst (* mutate in place, return same ref *)
| _ -> raise (Eval_error ("append!: expected list, got " ^ type_of lst))
(** Mutable dict-set — set key in dict, return value. *)
@@ -74,7 +76,8 @@ let get_val container key =
match container, key with
| Dict d, String k -> dict_get d k
| Dict d, Keyword k -> dict_get d k
| List l, Number n -> (try List.nth l (int_of_float n) with _ -> Nil)
| (List l | ListRef { contents = l }), Number n ->
(try List.nth l (int_of_float n) with _ -> Nil)
| _ -> raise (Eval_error ("get: unsupported " ^ type_of container ^ " / " ^ type_of key))
(** Register get as a primitive override — transpiled code calls (get d k). *)
@@ -82,7 +85,12 @@ let () =
Sx_primitives.register "get" (fun args ->
match args with
| [c; k] -> get_val c k
| _ -> raise (Eval_error "get: 2 args"))
| [c; k; default] ->
(try
let v = get_val c k in
if v = Nil then default else v
with _ -> default)
| _ -> raise (Eval_error "get: 2-3 args"))
(* ====================================================================== *)
@@ -195,8 +203,9 @@ let sx_emit a b = prim_call "emit!" [a; b]
let sx_emitted a = prim_call "emitted" [a]
let sx_context a b = prim_call "context" [a; b]
(* Trampoline — evaluate thunks iteratively *)
let trampoline v = v (* CEK machine doesn't use tree-walk thunks *)
(* Trampoline — forward-declared in sx_ref.ml, delegates to CEK eval_expr *)
(* This is a stub; the real trampoline is wired up in sx_ref.ml after eval_expr is defined *)
let trampoline v = v
(* Value-returning type predicates — the transpiled code passes these through
sx_truthy, so they need to return Bool, not OCaml bool. *)

View File

@@ -36,6 +36,7 @@ and value =
| Spread of (string * value) list
| SxExpr of string (** Opaque SX wire-format string — aser output. *)
| Env of env (** First-class environment — used by CEK machine state dicts. *)
| ListRef of value list ref (** Mutable list — JS-style array for append! *)
(** Mutable string-keyed table (SX dicts support [dict-set!]). *)
and dict = (string, value) Hashtbl.t
@@ -117,9 +118,30 @@ let rec env_set env name v =
| None -> Hashtbl.replace env.bindings name v; Nil
let env_merge base overlay =
let e = { bindings = Hashtbl.copy base.bindings; parent = base.parent } in
Hashtbl.iter (fun k v -> Hashtbl.replace e.bindings k v) overlay.bindings;
e
(* If base and overlay are the same env (physical equality) or overlay
is a descendant of base, just extend base — no copying needed.
This prevents set! inside lambdas from modifying shadow copies. *)
if base == overlay then
{ bindings = Hashtbl.create 16; parent = Some base }
else begin
(* Check if overlay is a descendant of base *)
let rec is_descendant e depth =
if depth > 100 then false
else if e == base then true
else match e.parent with Some p -> is_descendant p (depth + 1) | None -> false
in
if is_descendant overlay 0 then
{ bindings = Hashtbl.create 16; parent = Some base }
else begin
(* General case: extend base, copy ONLY overlay bindings that don't
exist anywhere in the base chain (avoids shadowing closure bindings). *)
let e = { bindings = Hashtbl.create 16; parent = Some base } in
Hashtbl.iter (fun k v ->
if not (env_has base k) then Hashtbl.replace e.bindings k v
) overlay.bindings;
e
end
end
(** {1 Value extraction helpers} *)
@@ -131,7 +153,7 @@ let value_to_string = function
| Nil -> "" | _ -> "<value>"
let value_to_string_list = function
| List items -> List.map value_to_string items
| List items | ListRef { contents = items } -> List.map value_to_string items
| _ -> []
let value_to_bool = function
@@ -197,7 +219,7 @@ let type_of = function
| String _ -> "string"
| Symbol _ -> "symbol"
| Keyword _ -> "keyword"
| List _ -> "list"
| List _ | ListRef _ -> "list"
| Dict _ -> "dict"
| Lambda _ -> "lambda"
| Component _ -> "component"
@@ -344,7 +366,7 @@ let rec inspect = function
| String s -> Printf.sprintf "%S" s
| Symbol s -> s
| Keyword k -> ":" ^ k
| List items ->
| List items | ListRef { contents = items } ->
"(" ^ String.concat " " (List.map inspect items) ^ ")"
| Dict d ->
let pairs = Hashtbl.fold (fun k v acc ->