Compare commits
73 Commits
loops/smal
...
6a34ae3ae1
| Author | SHA1 | Date | |
|---|---|---|---|
| 6a34ae3ae1 | |||
| a381154507 | |||
| 24e1a862fb | |||
| d8d5588e42 | |||
| a40a970080 | |||
| 3b0ac67a10 | |||
| 24d78464d8 | |||
| 7d329f024d | |||
| c8582c4d49 | |||
| 036022cc17 | |||
| e9d2003d6a | |||
| be2b11acc2 | |||
| ab3c3693c0 | |||
| 8ba0a33f6e | |||
| e9abc2cf61 | |||
| 3d8937d759 | |||
| dfbcece644 | |||
| b939becd86 | |||
| 60f88ab4fe | |||
| 4b600f17e8 | |||
| 46da676c29 | |||
| 0862a6140b | |||
| edf4e525f8 | |||
| 130d4d7c18 | |||
| ac79328418 | |||
| 0fe00bf7ac | |||
| 06a3eee114 | |||
| c3d2b9d87d | |||
| 7286629cf7 | |||
| da4b526abb | |||
| 59a835efc3 | |||
| 133bdf5295 | |||
| 2e4502878f | |||
| e44cb89ab4 | |||
| 835b5314ce | |||
| 43cc1d9003 | |||
| 8328e96ff6 | |||
| 24522902cc | |||
| a8a79dc902 | |||
| 1ad9d63f1b | |||
| f63b214726 | |||
| 5d1913e730 | |||
| 0dc7e1599c | |||
| 6c87210728 | |||
| 3fb0212414 | |||
| 518ad37def | |||
| d98b5fa223 | |||
| cc0af51921 | |||
| 0ffe208e31 | |||
| b78e06a772 | |||
| 9eb12c66fd | |||
| 21cb9cf51a | |||
| d84cf1882a | |||
| 6602ec8cc9 | |||
| b126d4da76 | |||
| a9d5a1082f | |||
| 0577f245e2 | |||
| f5acb31c94 | |||
| b12a22e68a | |||
| 7888fbfd81 | |||
| 45ec553519 | |||
| e3e767e434 | |||
| c70bbdeb36 | |||
| 8f0fc4ce52 | |||
| 1d85e3a79c | |||
| 5a332fa430 | |||
| d1a00562a4 | |||
| 3759575b29 | |||
| f247cb2898 | |||
| f8023cf74e | |||
| 3316d402fd | |||
| fb72c4ab9c | |||
| e52c209c3d |
File diff suppressed because it is too large
Load Diff
@@ -293,6 +293,8 @@ env["pop-suite"] = function() {
|
||||
return null;
|
||||
};
|
||||
|
||||
env["test-allowed?"] = function(name) { return true; };
|
||||
|
||||
// Load test framework
|
||||
const projectDir = path.join(__dirname, "..", "..");
|
||||
const specTests = path.join(projectDir, "spec", "tests");
|
||||
@@ -341,6 +343,20 @@ if (fs.existsSync(swapPath)) {
|
||||
}
|
||||
}
|
||||
|
||||
// Load spec library files (define-library modules imported by tests)
|
||||
for (const libFile of ["signals.sx", "coroutines.sx"]) {
|
||||
const libPath = path.join(projectDir, "spec", libFile);
|
||||
if (fs.existsSync(libPath)) {
|
||||
const libSrc = fs.readFileSync(libPath, "utf8");
|
||||
const libExprs = Sx.parse(libSrc);
|
||||
for (const expr of libExprs) {
|
||||
try { Sx.eval(expr, env); } catch (e) {
|
||||
console.error(`Error loading spec/${libFile}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load tw system (needed by spec/tests/test-tw.sx)
|
||||
const twDir = path.join(projectDir, "shared", "sx", "templates");
|
||||
for (const twFile of ["tw-type.sx", "tw-layout.sx", "tw.sx"]) {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -37,7 +37,10 @@ let rec deep_equal a b =
|
||||
match a, b with
|
||||
| Nil, Nil -> true
|
||||
| Bool a, Bool b -> a = b
|
||||
| Integer a, Integer b -> a = b
|
||||
| Number a, Number b -> a = b
|
||||
| Integer a, Number b -> float_of_int a = b
|
||||
| Number a, Integer b -> a = float_of_int b
|
||||
| String a, String b -> a = b
|
||||
| Symbol a, Symbol b -> a = b
|
||||
| Keyword a, Keyword b -> a = b
|
||||
@@ -226,7 +229,7 @@ let make_test_env () =
|
||||
| [String s] ->
|
||||
let parsed = Sx_parser.parse_all s in
|
||||
(match parsed with
|
||||
| [List (Symbol "sxbc" :: Number _ :: payload :: _)] -> payload
|
||||
| [List (Symbol "sxbc" :: (Number _ | Integer _) :: payload :: _)] -> payload
|
||||
| _ -> raise (Eval_error "bytecode-deserialize: invalid sxbc format"))
|
||||
| _ -> raise (Eval_error "bytecode-deserialize: expected string"));
|
||||
|
||||
@@ -240,7 +243,7 @@ let make_test_env () =
|
||||
| [String s] ->
|
||||
let parsed = Sx_parser.parse_all s in
|
||||
(match parsed with
|
||||
| [List (Symbol "cek-state" :: Number _ :: payload :: _)] -> payload
|
||||
| [List (Symbol "cek-state" :: (Number _ | Integer _) :: payload :: _)] -> payload
|
||||
| _ -> raise (Eval_error "cek-deserialize: invalid cek-state format"))
|
||||
| _ -> raise (Eval_error "cek-deserialize: expected string"));
|
||||
|
||||
@@ -320,7 +323,10 @@ let make_test_env () =
|
||||
bind "identical?" (fun args ->
|
||||
match args with
|
||||
| [a; b] -> Bool (match a, b with
|
||||
| Integer x, Integer y -> x = y
|
||||
| Number x, Number y -> x = y
|
||||
| Integer x, Number y -> float_of_int x = y
|
||||
| Number x, Integer y -> x = float_of_int y
|
||||
| String x, String y -> x = y
|
||||
| Bool x, Bool y -> x = y
|
||||
| Nil, Nil -> true
|
||||
@@ -366,11 +372,15 @@ let make_test_env () =
|
||||
|
||||
bind "append!" (fun args ->
|
||||
match args with
|
||||
| [ListRef r; v; Number n] when int_of_float n = 0 ->
|
||||
| [ListRef r; v; (Number n)] when int_of_float n = 0 ->
|
||||
r := v :: !r; ListRef r (* prepend *)
|
||||
| [ListRef r; v; (Integer 0)] ->
|
||||
r := v :: !r; ListRef r (* prepend Integer index *)
|
||||
| [ListRef r; v] -> r := !r @ [v]; ListRef r (* append in place *)
|
||||
| [List items; v; Number n] when int_of_float n = 0 ->
|
||||
| [List items; v; (Number n)] when int_of_float n = 0 ->
|
||||
List (v :: items) (* immutable prepend *)
|
||||
| [List items; v; (Integer 0)] ->
|
||||
List (v :: items) (* immutable prepend Integer index *)
|
||||
| [List items; v] -> List (items @ [v]) (* immutable fallback *)
|
||||
| _ -> raise (Eval_error "append!: expected list and value"));
|
||||
|
||||
@@ -546,7 +556,10 @@ let make_test_env () =
|
||||
bind "batch-begin!" (fun _args -> Sx_ref.batch_begin_b ());
|
||||
bind "batch-end!" (fun _args -> Sx_ref.batch_end_b ());
|
||||
bind "now-ms" (fun _args -> Number 1000.0);
|
||||
bind "random-int" (fun args -> match args with [Number lo; _] -> Number lo | _ -> Number 0.0);
|
||||
bind "random-int" (fun args -> match args with
|
||||
| [Number lo; _] -> Number lo
|
||||
| [Integer lo; _] -> Integer lo
|
||||
| _ -> Integer 0);
|
||||
bind "try-rerender-page" (fun _args -> Nil);
|
||||
bind "collect!" (fun args ->
|
||||
match args with
|
||||
@@ -1107,6 +1120,47 @@ let make_test_env () =
|
||||
| _ :: _ -> String "confirmed"
|
||||
| _ -> Nil);
|
||||
|
||||
bind "values" (fun args ->
|
||||
match args with
|
||||
| [v] -> v
|
||||
| vs ->
|
||||
let d = Hashtbl.create 2 in
|
||||
Hashtbl.replace d "_values" (Bool true);
|
||||
Hashtbl.replace d "_list" (List vs);
|
||||
Dict d);
|
||||
|
||||
bind "call-with-values" (fun args ->
|
||||
match args with
|
||||
| [producer; consumer] ->
|
||||
let result = Sx_ref.cek_call producer (List []) in
|
||||
let spread = (match result with
|
||||
| Dict d when (match Hashtbl.find_opt d "_values" with Some (Bool true) -> true | _ -> false) ->
|
||||
(match Hashtbl.find_opt d "_list" with Some (List l) -> l | _ -> [result])
|
||||
| _ -> [result])
|
||||
in
|
||||
Sx_ref.cek_call consumer (List spread)
|
||||
| _ -> raise (Eval_error "call-with-values: expected 2 args"));
|
||||
|
||||
bind "promise?" (fun args ->
|
||||
match args with
|
||||
| [v] -> Bool (Sx_ref.is_promise v)
|
||||
| _ -> Bool false);
|
||||
|
||||
bind "make-promise" (fun args ->
|
||||
match args with
|
||||
| [v] ->
|
||||
let d = Hashtbl.create 4 in
|
||||
Hashtbl.replace d "_promise" (Bool true);
|
||||
Hashtbl.replace d "forced" (Bool true);
|
||||
Hashtbl.replace d "value" v;
|
||||
Dict d
|
||||
| _ -> Nil);
|
||||
|
||||
bind "force" (fun args ->
|
||||
match args with
|
||||
| [p] -> Sx_ref.force_promise p
|
||||
| _ -> Nil);
|
||||
|
||||
env
|
||||
|
||||
(* ====================================================================== *)
|
||||
@@ -1142,18 +1196,20 @@ let run_foundation_tests () =
|
||||
in
|
||||
|
||||
Printf.printf "Suite: parser\n";
|
||||
assert_eq "number" (Number 42.0) (List.hd (parse_all "42"));
|
||||
assert_eq "number" (Integer 42) (List.hd (parse_all "42"));
|
||||
assert_eq "string" (String "hello") (List.hd (parse_all "\"hello\""));
|
||||
assert_eq "bool true" (Bool true) (List.hd (parse_all "true"));
|
||||
assert_eq "nil" Nil (List.hd (parse_all "nil"));
|
||||
assert_eq "keyword" (Keyword "class") (List.hd (parse_all ":class"));
|
||||
assert_eq "symbol" (Symbol "foo") (List.hd (parse_all "foo"));
|
||||
assert_eq "list" (List [Symbol "+"; Number 1.0; Number 2.0]) (List.hd (parse_all "(+ 1 2)"));
|
||||
assert_eq "list" (List [Symbol "+"; Integer 1; Integer 2]) (List.hd (parse_all "(+ 1 2)"));
|
||||
(match List.hd (parse_all "(div :class \"card\" (p \"hi\"))") with
|
||||
| List [Symbol "div"; Keyword "class"; String "card"; List [Symbol "p"; String "hi"]] ->
|
||||
incr pass_count; Printf.printf " PASS: nested list\n"
|
||||
| v -> incr fail_count; Printf.printf " FAIL: nested list — got %s\n" (Sx_types.inspect v));
|
||||
(match List.hd (parse_all "'(1 2 3)") with
|
||||
| List [Symbol "quote"; List [Integer 1; Integer 2; Integer 3]] ->
|
||||
incr pass_count; Printf.printf " PASS: quote sugar\n"
|
||||
| List [Symbol "quote"; List [Number 1.0; Number 2.0; Number 3.0]] ->
|
||||
incr pass_count; Printf.printf " PASS: quote sugar\n"
|
||||
| v -> incr fail_count; Printf.printf " FAIL: quote sugar — got %s\n" (Sx_types.inspect v));
|
||||
@@ -1161,7 +1217,7 @@ let run_foundation_tests () =
|
||||
| Dict d when dict_has d "a" && dict_has d "b" ->
|
||||
incr pass_count; Printf.printf " PASS: dict literal\n"
|
||||
| v -> incr fail_count; Printf.printf " FAIL: dict literal — got %s\n" (Sx_types.inspect v));
|
||||
assert_eq "comment" (Number 42.0) (List.hd (parse_all ";; comment\n42"));
|
||||
assert_eq "comment" (Integer 42) (List.hd (parse_all ";; comment\n42"));
|
||||
assert_eq "string escape" (String "hello\nworld") (List.hd (parse_all "\"hello\\nworld\""));
|
||||
assert_eq "multiple exprs" (Number 2.0) (Number (float_of_int (List.length (parse_all "(1 2 3) (4 5)"))));
|
||||
|
||||
@@ -1978,6 +2034,10 @@ let run_spec_tests env test_files =
|
||||
(match Hashtbl.find_opt d "children" with
|
||||
| Some (List l) when i >= 0 && i < List.length l -> List.nth l i
|
||||
| _ -> (match Hashtbl.find_opt d (string_of_int i) with Some v -> v | None -> Nil))
|
||||
| [Dict d; Integer n] ->
|
||||
(match Hashtbl.find_opt d "children" with
|
||||
| Some (List l) when n >= 0 && n < List.length l -> List.nth l n
|
||||
| _ -> (match Hashtbl.find_opt d (string_of_int n) with Some v -> v | None -> Nil))
|
||||
| _ -> Nil);
|
||||
|
||||
(* Stringify a value for DOM string properties *)
|
||||
@@ -2052,8 +2112,8 @@ let run_spec_tests env test_files =
|
||||
Hashtbl.replace d "childNodes" (List [])
|
||||
| _ -> ());
|
||||
stored
|
||||
| [ListRef r; Number n; value] ->
|
||||
let idx = int_of_float n in
|
||||
| [ListRef r; idx_v; value] when (match idx_v with Number _ | Integer _ -> true | _ -> false) ->
|
||||
let idx = match idx_v with Number n -> int_of_float n | Integer n -> n | _ -> 0 in
|
||||
let lst = !r in
|
||||
if idx >= 0 && idx < List.length lst then
|
||||
r := List.mapi (fun i v -> if i = idx then value else v) lst
|
||||
@@ -2190,7 +2250,7 @@ let run_spec_tests env test_files =
|
||||
| [String name; value] ->
|
||||
let attrs = match Hashtbl.find_opt d "attributes" with Some (Dict a) -> a | _ ->
|
||||
let a = Hashtbl.create 4 in Hashtbl.replace d "attributes" (Dict a); a in
|
||||
let sv = match value with String s -> s | Number n ->
|
||||
let sv = match value with String s -> s | Integer n -> string_of_int n | Number n ->
|
||||
let i = int_of_float n in if float_of_int i = n then string_of_int i
|
||||
else string_of_float n | _ -> Sx_types.inspect value in
|
||||
Hashtbl.replace attrs name (String sv);
|
||||
@@ -2632,6 +2692,7 @@ let run_spec_tests env test_files =
|
||||
let rec json_of_value = function
|
||||
| Nil -> `Null
|
||||
| Bool b -> `Bool b
|
||||
| Integer n -> `Int n
|
||||
| Number n ->
|
||||
if Float.is_integer n && Float.abs n < 1e16
|
||||
then `Int (int_of_float n) else `Float n
|
||||
@@ -2647,8 +2708,8 @@ let run_spec_tests env test_files =
|
||||
let rec value_of_json = function
|
||||
| `Null -> Nil
|
||||
| `Bool b -> Bool b
|
||||
| `Int i -> Number (float_of_int i)
|
||||
| `Intlit s -> (try Number (float_of_string s) with _ -> String s)
|
||||
| `Int i -> Integer i
|
||||
| `Intlit s -> (try Integer (int_of_string s) with _ -> try Number (float_of_string s) with _ -> String s)
|
||||
| `Float f -> Number f
|
||||
| `String s -> String s
|
||||
| `List xs -> List (List.map value_of_json xs)
|
||||
|
||||
@@ -296,6 +296,10 @@ let read_blob () =
|
||||
(* consume trailing newline *)
|
||||
(try ignore (input_line stdin) with End_of_file -> ());
|
||||
data
|
||||
| [List [Symbol "blob"; Integer n]] ->
|
||||
let data = read_exact_bytes n in
|
||||
(try ignore (input_line stdin) with End_of_file -> ());
|
||||
data
|
||||
| _ -> raise (Eval_error ("read_blob: expected (blob N), got: " ^ line))
|
||||
|
||||
(** Batch IO mode — collect requests during aser-slot, resolve after. *)
|
||||
@@ -357,6 +361,11 @@ let rec read_io_response () =
|
||||
| [List (Symbol "io-response" :: Number n :: values)]
|
||||
when int_of_float n = !current_epoch ->
|
||||
(match values with [v] -> v | _ -> List values)
|
||||
| [List [Symbol "io-response"; Integer n; value]]
|
||||
when n = !current_epoch -> value
|
||||
| [List (Symbol "io-response" :: Integer n :: values)]
|
||||
when n = !current_epoch ->
|
||||
(match values with [v] -> v | _ -> List values)
|
||||
(* Legacy untagged: (io-response value) — accept for backwards compat *)
|
||||
| [List [Symbol "io-response"; value]] -> value
|
||||
| [List (Symbol "io-response" :: values)] ->
|
||||
@@ -396,6 +405,12 @@ let read_batched_io_response () =
|
||||
when int_of_float n = !current_epoch -> s
|
||||
| [List [Symbol "io-response"; Number n; v]]
|
||||
when int_of_float n = !current_epoch -> serialize_value v
|
||||
| [List [Symbol "io-response"; Integer n; String s]]
|
||||
when n = !current_epoch -> s
|
||||
| [List [Symbol "io-response"; Integer n; SxExpr s]]
|
||||
when n = !current_epoch -> s
|
||||
| [List [Symbol "io-response"; Integer n; v]]
|
||||
when n = !current_epoch -> serialize_value v
|
||||
(* Legacy untagged *)
|
||||
| [List [Symbol "io-response"; String s]]
|
||||
| [List [Symbol "io-response"; SxExpr s]] -> s
|
||||
@@ -959,6 +974,7 @@ let setup_io_bridges env =
|
||||
bind "sleep" (fun args -> io_request "sleep" args);
|
||||
bind "set-response-status" (fun args -> match args with
|
||||
| [Number n] -> _pending_response_status := int_of_float n; Nil
|
||||
| [Integer n] -> _pending_response_status := n; Nil
|
||||
| _ -> Nil);
|
||||
bind "set-response-header" (fun args -> io_request "set-response-header" args)
|
||||
|
||||
@@ -1361,6 +1377,7 @@ let rec dispatch env cmd =
|
||||
| Bool true -> "true"
|
||||
| Bool false -> "false"
|
||||
| Number n -> Sx_types.format_number n
|
||||
| Integer n -> string_of_int n
|
||||
| String s -> "\"" ^ escape_sx_string s ^ "\""
|
||||
| Symbol s -> s
|
||||
| Keyword k -> ":" ^ k
|
||||
@@ -1374,6 +1391,10 @@ let rec dispatch env cmd =
|
||||
| Island i -> "~" ^ i.i_name
|
||||
| SxExpr s -> s
|
||||
| RawHTML s -> "\"" ^ escape_sx_string s ^ "\""
|
||||
| Char n -> Sx_types.inspect (Char n)
|
||||
| Eof -> Sx_types.inspect Eof
|
||||
| Port _ -> Sx_types.inspect result
|
||||
| Rational (n, d) -> Printf.sprintf "%d/%d" n d
|
||||
| _ -> "nil"
|
||||
in
|
||||
send_ok_raw (raw_serialize result)
|
||||
@@ -4450,6 +4471,8 @@ let site_mode () =
|
||||
match exprs with
|
||||
| [List [Symbol "epoch"; Number n]] ->
|
||||
current_epoch := int_of_float n
|
||||
| [List [Symbol "epoch"; Integer n]] ->
|
||||
current_epoch := n
|
||||
(* render-page: full SSR pipeline — URL → complete HTML *)
|
||||
| [List [Symbol "render-page"; String path]] ->
|
||||
(try match http_render_page env path [] with
|
||||
@@ -4507,6 +4530,8 @@ let () =
|
||||
(* Epoch marker: (epoch N) — set current epoch, read next command *)
|
||||
| [List [Symbol "epoch"; Number n]] ->
|
||||
current_epoch := int_of_float n
|
||||
| [List [Symbol "epoch"; Integer n]] ->
|
||||
current_epoch := n
|
||||
| [cmd] -> dispatch env cmd
|
||||
| _ -> send_error ("Expected single command, got " ^ string_of_int (List.length exprs))
|
||||
end
|
||||
|
||||
@@ -47,7 +47,9 @@ open Sx_runtime
|
||||
let trampoline_fn : (value -> value) ref = ref (fun v -> v)
|
||||
let trampoline v = !trampoline_fn v
|
||||
|
||||
|
||||
(* Step limit for timeout detection — set to 0 to disable *)
|
||||
let step_limit : int ref = ref 0
|
||||
let step_count : int ref = ref 0
|
||||
|
||||
(* === Mutable globals — backing refs for transpiler's !_ref / _ref := === *)
|
||||
let _strict_ref = ref (Bool false)
|
||||
@@ -126,6 +128,90 @@ let enhance_error_with_trace msg =
|
||||
_last_error_kont_ref := Nil;
|
||||
msg ^ (format_comp_trace trace)
|
||||
|
||||
(* Hand-written sf_define_type — skipped from transpile because the spec uses
|
||||
&rest params and empty-dict literals that the transpiler can't emit cleanly.
|
||||
Implements: (define-type Name (Ctor1 f1 f2) (Ctor2 f3) ...)
|
||||
Creates constructor fns, Name?/Ctor? predicates, Ctor-field accessors,
|
||||
and records ctors in *adt-registry*. *)
|
||||
let sf_define_type args env_val =
|
||||
let items = (match args with List l -> l | _ -> []) in
|
||||
let type_sym = List.nth items 0 in
|
||||
let type_name = value_to_string type_sym in
|
||||
let ctor_specs = List.tl items in
|
||||
let env_has_v k = sx_truthy (env_has env_val (String k)) in
|
||||
let env_bind_v k v = ignore (env_bind env_val (String k) v) in
|
||||
let env_get_v k = env_get env_val (String k) in
|
||||
if not (env_has_v "*adt-registry*") then
|
||||
env_bind_v "*adt-registry*" (Dict (Hashtbl.create 8));
|
||||
let registry = env_get_v "*adt-registry*" in
|
||||
let ctor_names = List.map (fun spec ->
|
||||
(match spec with List (sym :: _) -> String (value_to_string sym) | _ -> Nil)
|
||||
) ctor_specs in
|
||||
(match registry with Dict d -> Hashtbl.replace d type_name (List ctor_names) | _ -> ());
|
||||
env_bind_v (type_name ^ "?")
|
||||
(NativeFn (type_name ^ "?", fun pargs ->
|
||||
(match pargs with
|
||||
| [v] ->
|
||||
(match v with
|
||||
| Dict d -> Bool (Hashtbl.mem d "_adt" &&
|
||||
(match Hashtbl.find_opt d "_type" with Some (String t) -> t = type_name | _ -> false))
|
||||
| _ -> Bool false)
|
||||
| _ -> Bool false)));
|
||||
List.iter (fun spec ->
|
||||
(match spec with
|
||||
| List (sym :: fields) ->
|
||||
let cn = value_to_string sym in
|
||||
let field_names = List.map value_to_string fields in
|
||||
let arity = List.length fields in
|
||||
env_bind_v cn
|
||||
(NativeFn (cn, fun ctor_args ->
|
||||
if List.length ctor_args <> arity then
|
||||
raise (Eval_error (Printf.sprintf "%s: expected %d args, got %d"
|
||||
cn arity (List.length ctor_args)))
|
||||
else begin
|
||||
let d = Hashtbl.create 4 in
|
||||
Hashtbl.replace d "_adt" (Bool true);
|
||||
Hashtbl.replace d "_type" (String type_name);
|
||||
Hashtbl.replace d "_ctor" (String cn);
|
||||
Hashtbl.replace d "_fields" (List ctor_args);
|
||||
Dict d
|
||||
end));
|
||||
env_bind_v (cn ^ "?")
|
||||
(NativeFn (cn ^ "?", fun pargs ->
|
||||
(match pargs with
|
||||
| [v] ->
|
||||
(match v with
|
||||
| Dict d -> Bool (Hashtbl.mem d "_adt" &&
|
||||
(match Hashtbl.find_opt d "_ctor" with Some (String c) -> c = cn | _ -> false))
|
||||
| _ -> Bool false)
|
||||
| _ -> Bool false)));
|
||||
List.iteri (fun idx fname ->
|
||||
env_bind_v (cn ^ "-" ^ fname)
|
||||
(NativeFn (cn ^ "-" ^ fname, fun pargs ->
|
||||
(match pargs with
|
||||
| [v] ->
|
||||
(match v with
|
||||
| Dict d ->
|
||||
(match Hashtbl.find_opt d "_fields" with
|
||||
| Some (List fs) ->
|
||||
if idx < List.length fs then List.nth fs idx
|
||||
else raise (Eval_error (cn ^ "-" ^ fname ^ ": index out of bounds"))
|
||||
| _ -> raise (Eval_error (cn ^ "-" ^ fname ^ ": not an ADT")))
|
||||
| _ -> raise (Eval_error (cn ^ "-" ^ fname ^ ": not a dict")))
|
||||
| _ -> raise (Eval_error (cn ^ "-" ^ fname ^ ": expected 1 arg")))))
|
||||
) field_names
|
||||
| _ -> ())
|
||||
) ctor_specs;
|
||||
Nil
|
||||
|
||||
(* Register define-type via custom_special_forms so the CEK dispatch finds it.
|
||||
The top-level (register-special-form! ...) in spec/evaluator.sx is not a
|
||||
define and therefore is not transpiled; we wire it up here instead. *)
|
||||
let () = ignore (register_special_form (String "define-type")
|
||||
(NativeFn ("define-type", fun call_args ->
|
||||
match call_args with
|
||||
| [args; env] -> sf_define_type args env
|
||||
| _ -> Nil)))
|
||||
|
||||
|
||||
"""
|
||||
@@ -171,7 +257,10 @@ def compile_spec_to_ml(spec_dir: str | None = None) -> str:
|
||||
"debug-log", "debug_log", "range", "chunk-every", "zip-pairs",
|
||||
"string-contains?", "starts-with?", "ends-with?",
|
||||
"string-replace", "trim", "split", "index-of",
|
||||
"pad-left", "pad-right", "char-at", "substring"}
|
||||
"pad-left", "pad-right", "char-at", "substring",
|
||||
# sf-define-type uses &rest + empty-dict literals that the transpiler
|
||||
# can't emit as valid OCaml; hand-written implementation in FIXUPS.
|
||||
"sf-define-type"}
|
||||
defines = [(n, e) for n, e in defines if n not in skip]
|
||||
|
||||
# Deduplicate — keep last definition for each name (CEK overrides tree-walk)
|
||||
|
||||
@@ -89,10 +89,38 @@ let read_symbol s =
|
||||
while s.pos < s.len && is_symbol_char s.src.[s.pos] do advance s done;
|
||||
String.sub s.src start (s.pos - start)
|
||||
|
||||
let gcd a b =
|
||||
let rec g a b = if b = 0 then a else g b (a mod b) in g (abs a) (abs b)
|
||||
|
||||
let make_rat n d =
|
||||
if d = 0 then raise (Parse_error "rational: division by zero");
|
||||
let sign = if d < 0 then -1 else 1 in
|
||||
let g = gcd (abs n) (abs d) in
|
||||
let rn = sign * n / g and rd = sign * d / g in
|
||||
if rd = 1 then Integer rn else Rational (rn, rd)
|
||||
|
||||
let try_number str =
|
||||
match float_of_string_opt str with
|
||||
| Some n -> Some (Number n)
|
||||
| None -> None
|
||||
(* Integers (no '.' or 'e'/'E') → exact Integer; rationals N/D; floats → inexact Number *)
|
||||
let has_dec = String.contains str '.' in
|
||||
let has_exp = String.contains str 'e' || String.contains str 'E' in
|
||||
if has_dec || has_exp then
|
||||
match float_of_string_opt str with
|
||||
| Some n -> Some (Number n)
|
||||
| None -> None
|
||||
else
|
||||
match String.split_on_char '/' str with
|
||||
| [num_s; den_s] when num_s <> "" && den_s <> "" ->
|
||||
(match int_of_string_opt num_s, int_of_string_opt den_s with
|
||||
| Some n, Some d -> (try Some (make_rat n d) with _ -> None)
|
||||
| _ -> None)
|
||||
| _ ->
|
||||
match int_of_string_opt str with
|
||||
| Some n -> Some (Integer n)
|
||||
| None ->
|
||||
(* handles "nan", "inf", "-inf" *)
|
||||
match float_of_string_opt str with
|
||||
| Some n -> Some (Number n)
|
||||
| None -> None
|
||||
|
||||
let rec read_value s : value =
|
||||
skip_whitespace_and_comments s;
|
||||
@@ -108,6 +136,34 @@ 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] = '\\' ->
|
||||
(* Character literal: #\a, #\space, #\newline, etc. *)
|
||||
advance s; advance s;
|
||||
if at_end s then raise (Parse_error "Unexpected end of input after #\\");
|
||||
let char_start = s.pos in
|
||||
(* Read a name if starts with ident char, else single char *)
|
||||
if is_ident_start s.src.[s.pos] then begin
|
||||
while s.pos < s.len && is_ident_char s.src.[s.pos] do advance s done;
|
||||
let name = String.sub s.src char_start (s.pos - char_start) in
|
||||
let cp = match name with
|
||||
| "space" -> 32 | "newline" -> 10 | "tab" -> 9
|
||||
| "return" -> 13 | "nul" -> 0 | "null" -> 0
|
||||
| "escape" -> 27 | "delete" -> 127 | "backspace" -> 8
|
||||
| "altmode" -> 27 | "rubout" -> 127
|
||||
| _ -> Char.code name.[0] (* single letter like #\a *)
|
||||
in Char cp
|
||||
end else begin
|
||||
let c = s.src.[s.pos] in
|
||||
advance s;
|
||||
Char (Char.code c)
|
||||
end
|
||||
| '#' when s.pos + 1 < s.len &&
|
||||
(s.src.[s.pos + 1] = 't' || s.src.[s.pos + 1] = 'f') &&
|
||||
(s.pos + 2 >= s.len || not (is_ident_char s.src.[s.pos + 2])) ->
|
||||
(* #t / #f — boolean literals (R7RS shorthand) *)
|
||||
let b = s.src.[s.pos + 1] = 't' in
|
||||
advance s; advance s;
|
||||
Bool b
|
||||
| '#' when s.pos + 1 < s.len && s.src.[s.pos + 1] = ';' ->
|
||||
(* Datum comment: #; discards next expression *)
|
||||
advance s; advance s;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -46,7 +46,7 @@ let sx_call f args =
|
||||
!Sx_types._cek_eval_lambda_ref f args
|
||||
| Continuation (k, _) ->
|
||||
k (match args with x :: _ -> x | [] -> Nil)
|
||||
| CallccContinuation _ ->
|
||||
| CallccContinuation (_, _) ->
|
||||
raise (Eval_error "callcc continuations must be invoked through the CEK machine")
|
||||
| _ ->
|
||||
let nargs = List.length args in
|
||||
@@ -156,6 +156,9 @@ let get_val container key =
|
||||
| "extra" -> f.cf_extra | "extra2" -> f.cf_extra2
|
||||
| "subscribers" -> f.cf_results
|
||||
| "prev-tracking" -> f.cf_extra
|
||||
| "after-thunk" -> f.cf_f (* wind-after frame *)
|
||||
| "winders-len" -> f.cf_extra (* wind-after frame *)
|
||||
| "body-result" -> f.cf_name (* wind-return frame *)
|
||||
| _ -> Nil)
|
||||
| VmFrame f, String k ->
|
||||
(match k with
|
||||
@@ -208,6 +211,8 @@ let get_val container key =
|
||||
| Dict d, Keyword k -> dict_get d k
|
||||
| (List l | ListRef { contents = l }), Number n ->
|
||||
(try List.nth l (int_of_float n) with _ -> Nil)
|
||||
| (List l | ListRef { contents = l }), Integer n ->
|
||||
(try List.nth l n with _ -> Nil)
|
||||
| Nil, _ -> Nil (* nil.anything → nil *)
|
||||
| _, _ -> Nil (* type mismatch → nil (matches JS/Python behavior) *)
|
||||
|
||||
@@ -381,15 +386,20 @@ let continuation_data v = match v with
|
||||
| _ -> raise (Eval_error "not a continuation")
|
||||
|
||||
(* Callcc (undelimited) continuation support *)
|
||||
let callcc_continuation_p v = match v with CallccContinuation _ -> Bool true | _ -> Bool false
|
||||
let callcc_continuation_p v = match v with CallccContinuation (_, _) -> Bool true | _ -> Bool false
|
||||
|
||||
let make_callcc_continuation captured =
|
||||
CallccContinuation (sx_to_list captured)
|
||||
let make_callcc_continuation captured winders_len =
|
||||
let n = match winders_len with Number f -> int_of_float f | Integer n -> n | _ -> 0 in
|
||||
CallccContinuation (sx_to_list captured, n)
|
||||
|
||||
let callcc_continuation_data v = match v with
|
||||
| CallccContinuation frames -> List frames
|
||||
| CallccContinuation (frames, _) -> List frames
|
||||
| _ -> raise (Eval_error "not a callcc continuation")
|
||||
|
||||
let callcc_continuation_winders_len v = match v with
|
||||
| CallccContinuation (_, n) -> Number (float_of_int n)
|
||||
| _ -> Number 0.0
|
||||
|
||||
(* Dynamic wind — simplified for OCaml (no async) *)
|
||||
let host_error msg =
|
||||
raise (Eval_error (value_to_str msg))
|
||||
|
||||
@@ -43,9 +43,10 @@ type env = {
|
||||
|
||||
and value =
|
||||
| Nil
|
||||
| Bool of bool
|
||||
| Number of float
|
||||
| String of string
|
||||
| Bool of bool
|
||||
| Integer of int (** Exact integer — distinct from inexact float. *)
|
||||
| Number of float (** Inexact float. *)
|
||||
| String of string
|
||||
| Symbol of string
|
||||
| Keyword of string
|
||||
| List of value list
|
||||
@@ -56,7 +57,7 @@ and value =
|
||||
| Macro of macro
|
||||
| Thunk of value * env
|
||||
| Continuation of (value -> value) * dict option
|
||||
| CallccContinuation of value list (** Undelimited continuation — captured kont frames *)
|
||||
| CallccContinuation of value list * int (** Undelimited continuation — captured kont frames + winders depth at capture *)
|
||||
| NativeFn of string * (value list -> value)
|
||||
| Signal of signal
|
||||
| RawHTML of string
|
||||
@@ -72,6 +73,25 @@ and value =
|
||||
| Record of record (** R7RS record — opaque, generative, field-indexed. *)
|
||||
| Parameter of parameter (** R7RS parameter — dynamic binding via kont-stack provide frames. *)
|
||||
| Vector of value array (** R7RS vector — mutable fixed-size array. *)
|
||||
| StringBuffer of Buffer.t (** Mutable string buffer — O(1) amortized append. *)
|
||||
| HashTable of (value, value) Hashtbl.t (** Mutable hash table with arbitrary keys. *)
|
||||
| Char of int (** Unicode codepoint — R7RS char type. *)
|
||||
| Eof (** EOF sentinel — returned by read-char etc. at end of input. *)
|
||||
| Port of sx_port (** String port — input (string cursor) or output (buffer). *)
|
||||
| Rational of int * int (** Exact rational: numerator, denominator (reduced, denom>0). *)
|
||||
| SxSet of (string, value) Hashtbl.t (** Mutable set keyed by inspect(value). *)
|
||||
| SxRegexp of string * string * Re.re (** Regexp: source, flags, compiled. *)
|
||||
| SxBytevector of bytes (** Mutable bytevector — R7RS bytevector type. *)
|
||||
|
||||
(** String input port: source string + mutable cursor position. *)
|
||||
and sx_port_kind =
|
||||
| PortInput of string * int ref
|
||||
| PortOutput of Buffer.t
|
||||
|
||||
and sx_port = {
|
||||
mutable sp_closed : bool;
|
||||
sp_kind : sx_port_kind;
|
||||
}
|
||||
|
||||
(** CEK machine state — record instead of Dict for performance.
|
||||
5 fields × 55K steps/sec = 275K Hashtbl allocations/sec eliminated. *)
|
||||
@@ -392,6 +412,7 @@ let format_number n =
|
||||
|
||||
let value_to_string = function
|
||||
| String s -> s | Symbol s -> s | Keyword k -> k
|
||||
| Integer n -> string_of_int n
|
||||
| Number n -> format_number n
|
||||
| Bool true -> "true" | Bool false -> "false"
|
||||
| Nil -> "" | _ -> "<value>"
|
||||
@@ -461,6 +482,7 @@ let make_keyword name = Keyword (value_to_string name)
|
||||
let type_of = function
|
||||
| Nil -> "nil"
|
||||
| Bool _ -> "boolean"
|
||||
| Integer _ -> "number"
|
||||
| Number _ -> "number"
|
||||
| String _ -> "string"
|
||||
| Symbol _ -> "symbol"
|
||||
@@ -473,7 +495,7 @@ let type_of = function
|
||||
| Macro _ -> "macro"
|
||||
| Thunk _ -> "thunk"
|
||||
| Continuation (_, _) -> "continuation"
|
||||
| CallccContinuation _ -> "continuation"
|
||||
| CallccContinuation (_, _) -> "continuation"
|
||||
| NativeFn _ -> "function"
|
||||
| Signal _ -> "signal"
|
||||
| RawHTML _ -> "raw-html"
|
||||
@@ -488,6 +510,16 @@ let type_of = function
|
||||
| Record r -> r.r_type.rt_name
|
||||
| Parameter _ -> "parameter"
|
||||
| Vector _ -> "vector"
|
||||
| StringBuffer _ -> "string-buffer"
|
||||
| HashTable _ -> "hash-table"
|
||||
| Char _ -> "char"
|
||||
| Eof -> "eof-object"
|
||||
| Port { sp_kind = PortInput _; _ } -> "input-port"
|
||||
| Port { sp_kind = PortOutput _; _ } -> "output-port"
|
||||
| Rational _ -> "rational"
|
||||
| SxSet _ -> "set"
|
||||
| SxRegexp _ -> "regexp"
|
||||
| SxBytevector _ -> "bytevector"
|
||||
|
||||
let is_nil = function Nil -> true | _ -> false
|
||||
let is_lambda = function Lambda _ -> true | _ -> false
|
||||
@@ -503,7 +535,7 @@ let is_signal = function
|
||||
let is_record = function Record _ -> true | _ -> false
|
||||
|
||||
let is_callable = function
|
||||
| Lambda _ | NativeFn _ | Continuation (_, _) | CallccContinuation _ | VmClosure _ -> true
|
||||
| Lambda _ | NativeFn _ | Continuation (_, _) | CallccContinuation (_, _) | VmClosure _ -> true
|
||||
| _ -> false
|
||||
|
||||
|
||||
@@ -616,6 +648,7 @@ let thunk_env = function
|
||||
(** {1 Record operations} *)
|
||||
|
||||
let val_to_int = function
|
||||
| Integer n -> n
|
||||
| Number n -> int_of_float n
|
||||
| v -> raise (Eval_error ("Expected number, got " ^ type_of v))
|
||||
|
||||
@@ -777,6 +810,7 @@ let rec inspect = function
|
||||
| Nil -> "nil"
|
||||
| Bool true -> "true"
|
||||
| Bool false -> "false"
|
||||
| Integer n -> string_of_int n
|
||||
| Number n -> format_number n
|
||||
| String s ->
|
||||
let buf = Buffer.create (String.length s + 2) in
|
||||
@@ -810,7 +844,7 @@ let rec inspect = function
|
||||
Printf.sprintf "<%s(%s)>" tag (String.concat ", " m.m_params)
|
||||
| Thunk _ -> "<thunk>"
|
||||
| Continuation (_, _) -> "<continuation>"
|
||||
| CallccContinuation _ -> "<callcc-continuation>"
|
||||
| CallccContinuation (_, _) -> "<callcc-continuation>"
|
||||
| NativeFn (name, _) -> Printf.sprintf "<native:%s>" name
|
||||
| Signal _ -> "<signal>"
|
||||
| RawHTML s -> Printf.sprintf "\"<raw-html:%d>\"" (String.length s)
|
||||
@@ -831,3 +865,23 @@ let rec inspect = function
|
||||
Printf.sprintf "#(%s)" (String.concat " " elts)
|
||||
| VmFrame f -> Printf.sprintf "<vm-frame:ip=%d base=%d>" f.vf_ip f.vf_base
|
||||
| VmMachine m -> Printf.sprintf "<vm-machine:sp=%d frames=%d>" m.vm_sp (List.length m.vm_frames)
|
||||
| StringBuffer buf -> Printf.sprintf "<string-buffer:%d>" (Buffer.length buf)
|
||||
| HashTable ht -> Printf.sprintf "<hash-table:%d>" (Hashtbl.length ht)
|
||||
| Char n ->
|
||||
let name = match n with
|
||||
| 32 -> "space" | 10 -> "newline" | 9 -> "tab"
|
||||
| 13 -> "return" | 0 -> "nul" | 27 -> "escape"
|
||||
| 127 -> "delete" | 8 -> "backspace"
|
||||
| _ -> let buf = Buffer.create 1 in
|
||||
Buffer.add_utf_8_uchar buf (Uchar.of_int n);
|
||||
Buffer.contents buf
|
||||
in "#\\" ^ name
|
||||
| Eof -> "#!eof"
|
||||
| Port { sp_kind = PortInput (_, pos); sp_closed } ->
|
||||
Printf.sprintf "<input-port:pos=%d%s>" !pos (if sp_closed then ":closed" else "")
|
||||
| Port { sp_kind = PortOutput buf; sp_closed } ->
|
||||
Printf.sprintf "<output-port:len=%d%s>" (Buffer.length buf) (if sp_closed then ":closed" else "")
|
||||
| Rational (n, d) -> Printf.sprintf "%d/%d" n d
|
||||
| SxSet ht -> Printf.sprintf "<set:%d>" (Hashtbl.length ht)
|
||||
| SxRegexp (src, flags, _) -> Printf.sprintf "#/%s/%s" src flags
|
||||
| SxBytevector b -> Printf.sprintf "#u8(%s)" (String.concat " " (List.init (Bytes.length b) (fun i -> string_of_int (Char.code (Bytes.get b i)))))
|
||||
|
||||
@@ -185,7 +185,8 @@ let code_from_value v =
|
||||
| Some _ as r -> r | None -> Hashtbl.find_opt d k2 in
|
||||
let bc_list = match find2 "bytecode" "vc-bytecode" with
|
||||
| Some (List l | ListRef { contents = l }) ->
|
||||
Array.of_list (List.map (fun x -> match x with Number n -> int_of_float n | _ -> 0) l)
|
||||
Array.of_list (List.map (fun x -> match x with
|
||||
| Integer n -> n | Number n -> int_of_float n | _ -> 0) l)
|
||||
| _ -> [||]
|
||||
in
|
||||
let entries = match find2 "constants" "vc-constants" with
|
||||
@@ -198,10 +199,10 @@ let code_from_value v =
|
||||
| _ -> entry
|
||||
) entries in
|
||||
let arity = match find2 "arity" "vc-arity" with
|
||||
| Some (Number n) -> int_of_float n | _ -> 0
|
||||
| Some (Integer n) -> n | Some (Number n) -> int_of_float n | _ -> 0
|
||||
in
|
||||
let rest_arity = match find2 "rest-arity" "vc-rest-arity" with
|
||||
| Some (Number n) -> int_of_float n | _ -> -1
|
||||
| Some (Integer n) -> n | Some (Number n) -> int_of_float n | _ -> -1
|
||||
in
|
||||
(* Compute locals from bytecode: scan for highest LOCAL_GET/LOCAL_SET slot.
|
||||
The compiler's arity may undercount when nested lets add many locals. *)
|
||||
@@ -749,10 +750,7 @@ and run vm =
|
||||
| _ -> (Hashtbl.find Sx_primitives.primitives "/") [a; b])
|
||||
| 164 (* OP_EQ *) ->
|
||||
let b = pop vm and a = pop vm in
|
||||
let rec norm = function
|
||||
| ListRef { contents = l } -> List (List.map norm l)
|
||||
| List l -> List (List.map norm l) | v -> v in
|
||||
push vm (Bool (norm a = norm b))
|
||||
push vm ((Hashtbl.find Sx_primitives.primitives "=") [a; b])
|
||||
| 165 (* OP_LT *) ->
|
||||
let b = pop vm and a = pop vm in
|
||||
push vm (match a, b with
|
||||
@@ -771,10 +769,10 @@ and run vm =
|
||||
| 168 (* OP_LEN *) ->
|
||||
let v = pop vm in
|
||||
push vm (match v with
|
||||
| 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
|
||||
| List l | ListRef { contents = l } -> Integer (List.length l)
|
||||
| String s -> Integer (String.length s)
|
||||
| Dict d -> Integer (Hashtbl.length d)
|
||||
| Nil -> Integer 0
|
||||
| _ -> (Hashtbl.find Sx_primitives.primitives "len") [v])
|
||||
| 169 (* OP_FIRST *) ->
|
||||
let v = pop vm in
|
||||
|
||||
@@ -256,6 +256,7 @@
|
||||
"callcc-continuation?"
|
||||
"callcc-continuation-data"
|
||||
"make-callcc-continuation"
|
||||
"callcc-continuation-winders-len"
|
||||
"dynamic-wind-call"
|
||||
"strip-prefix"
|
||||
"component-set-param-types!"
|
||||
@@ -295,7 +296,8 @@
|
||||
"*bind-tracking*"
|
||||
"*provide-batch-depth*"
|
||||
"*provide-batch-queue*"
|
||||
"*provide-subscribers*"))
|
||||
"*provide-subscribers*"
|
||||
"*winders*"))
|
||||
|
||||
(define
|
||||
ml-is-mutable-global?
|
||||
@@ -533,13 +535,13 @@
|
||||
"; cf_env = "
|
||||
(ef "env")
|
||||
"; cf_name = "
|
||||
(if (= frame-type "if") (ef "else") (ef "name"))
|
||||
(if (= frame-type "if") (ef "else") (cond (some (fn (k) (= k "body-result")) items) (ef "body-result") :else (ef "name")))
|
||||
"; cf_body = "
|
||||
(if (= frame-type "if") (ef "then") (ef "body"))
|
||||
"; cf_remaining = "
|
||||
(ef "remaining")
|
||||
"; cf_f = "
|
||||
(ef "f")
|
||||
(cond (some (fn (k) (= k "after-thunk")) items) (ef "after-thunk") (some (fn (k) (= k "f")) items) (ef "f") :else "Nil")
|
||||
"; cf_args = "
|
||||
(cond
|
||||
(some (fn (k) (= k "evaled")) items)
|
||||
@@ -582,6 +584,8 @@
|
||||
(ef "prev-tracking")
|
||||
(some (fn (k) (= k "extra")) items)
|
||||
(ef "extra")
|
||||
(some (fn (k) (= k "winders-len")) items)
|
||||
(ef "winders-len")
|
||||
:else "Nil")
|
||||
"; cf_extra2 = "
|
||||
(cond
|
||||
|
||||
@@ -49,6 +49,8 @@ trap "rm -f $TMPFILE" EXIT
|
||||
echo '(load "lib/js/transpile.sx")'
|
||||
echo '(epoch 5)'
|
||||
echo '(load "lib/js/runtime.sx")'
|
||||
echo '(epoch 6)'
|
||||
echo '(load "lib/js/regex.sx")'
|
||||
|
||||
epoch=100
|
||||
for f in "${FIXTURES[@]}"; do
|
||||
|
||||
943
lib/js/regex.sx
Normal file
943
lib/js/regex.sx
Normal file
@@ -0,0 +1,943 @@
|
||||
;; lib/js/regex.sx — pure-SX recursive backtracking regex engine
|
||||
;;
|
||||
;; Installed via (js-regex-platform-override! ...) at load time.
|
||||
;; Covers: character classes (\d\w\s . [abc] [^abc] [a-z]),
|
||||
;; anchors (^ $ \b \B), quantifiers (* + ? {n,m} lazy variants),
|
||||
;; groups (capturing + non-capturing), alternation (a|b),
|
||||
;; flags: i (case-insensitive), g (global), m (multiline).
|
||||
;;
|
||||
;; Architecture:
|
||||
;; 1. rx-parse-pattern — pattern string → compiled node list
|
||||
;; 2. rx-match-nodes — recursive backtracker
|
||||
;; 3. rx-exec / rx-test — public interface
|
||||
;; 4. Install as {:test rx-test :exec rx-exec}
|
||||
|
||||
;; ── Utilities ─────────────────────────────────────────────────────
|
||||
|
||||
(define
|
||||
rx-char-at
|
||||
(fn (s i) (if (and (>= i 0) (< i (len s))) (char-at s i) "")))
|
||||
|
||||
(define
|
||||
rx-digit?
|
||||
(fn
|
||||
(c)
|
||||
(and (not (= c "")) (>= (char-code c) 48) (<= (char-code c) 57))))
|
||||
|
||||
(define
|
||||
rx-word?
|
||||
(fn
|
||||
(c)
|
||||
(and
|
||||
(not (= c ""))
|
||||
(or
|
||||
(and (>= (char-code c) 65) (<= (char-code c) 90))
|
||||
(and (>= (char-code c) 97) (<= (char-code c) 122))
|
||||
(and (>= (char-code c) 48) (<= (char-code c) 57))
|
||||
(= c "_")))))
|
||||
|
||||
(define
|
||||
rx-space?
|
||||
(fn
|
||||
(c)
|
||||
(or (= c " ") (= c "\t") (= c "\n") (= c "\r") (= c "\\f") (= c ""))))
|
||||
|
||||
(define rx-newline? (fn (c) (or (= c "\n") (= c "\r"))))
|
||||
|
||||
(define
|
||||
rx-downcase-char
|
||||
(fn
|
||||
(c)
|
||||
(let
|
||||
((cc (char-code c)))
|
||||
(if (and (>= cc 65) (<= cc 90)) (char-from-code (+ cc 32)) c))))
|
||||
|
||||
(define
|
||||
rx-char-eq?
|
||||
(fn
|
||||
(a b ci?)
|
||||
(if ci? (= (rx-downcase-char a) (rx-downcase-char b)) (= a b))))
|
||||
|
||||
(define
|
||||
rx-parse-int
|
||||
(fn
|
||||
(pat i acc)
|
||||
(let
|
||||
((c (rx-char-at pat i)))
|
||||
(if
|
||||
(rx-digit? c)
|
||||
(rx-parse-int pat (+ i 1) (+ (* acc 10) (- (char-code c) 48)))
|
||||
(list acc i)))))
|
||||
|
||||
(define
|
||||
rx-hex-digit-val
|
||||
(fn
|
||||
(c)
|
||||
(cond
|
||||
((and (>= (char-code c) 48) (<= (char-code c) 57))
|
||||
(- (char-code c) 48))
|
||||
((and (>= (char-code c) 65) (<= (char-code c) 70))
|
||||
(+ 10 (- (char-code c) 65)))
|
||||
((and (>= (char-code c) 97) (<= (char-code c) 102))
|
||||
(+ 10 (- (char-code c) 97)))
|
||||
(else -1))))
|
||||
|
||||
(define
|
||||
rx-parse-hex-n
|
||||
(fn
|
||||
(pat i n acc)
|
||||
(if
|
||||
(= n 0)
|
||||
(list (char-from-code acc) i)
|
||||
(let
|
||||
((v (rx-hex-digit-val (rx-char-at pat i))))
|
||||
(if
|
||||
(< v 0)
|
||||
(list (char-from-code acc) i)
|
||||
(rx-parse-hex-n pat (+ i 1) (- n 1) (+ (* acc 16) v)))))))
|
||||
|
||||
;; ── Pattern compiler ──────────────────────────────────────────────
|
||||
|
||||
;; Node types (stored in dicts with "__t__" key):
|
||||
;; literal : {:__t__ "literal" :__c__ char}
|
||||
;; any : {:__t__ "any"}
|
||||
;; class-d : {:__t__ "class-d" :__neg__ bool}
|
||||
;; class-w : {:__t__ "class-w" :__neg__ bool}
|
||||
;; class-s : {:__t__ "class-s" :__neg__ bool}
|
||||
;; char-class: {:__t__ "char-class" :__neg__ bool :__items__ list}
|
||||
;; anchor-start / anchor-end / anchor-word / anchor-nonword
|
||||
;; quant : {:__t__ "quant" :__node__ n :__min__ m :__max__ mx :__lazy__ bool}
|
||||
;; group : {:__t__ "group" :__idx__ i :__nodes__ list}
|
||||
;; ncgroup : {:__t__ "ncgroup" :__nodes__ list}
|
||||
;; alt : {:__t__ "alt" :__branches__ list-of-node-lists}
|
||||
|
||||
;; parse one escape after `\`, returns (node new-i)
|
||||
(define
|
||||
rx-parse-escape
|
||||
(fn
|
||||
(pat i)
|
||||
(let
|
||||
((c (rx-char-at pat i)))
|
||||
(cond
|
||||
((= c "d") (list (dict "__t__" "class-d" "__neg__" false) (+ i 1)))
|
||||
((= c "D") (list (dict "__t__" "class-d" "__neg__" true) (+ i 1)))
|
||||
((= c "w") (list (dict "__t__" "class-w" "__neg__" false) (+ i 1)))
|
||||
((= c "W") (list (dict "__t__" "class-w" "__neg__" true) (+ i 1)))
|
||||
((= c "s") (list (dict "__t__" "class-s" "__neg__" false) (+ i 1)))
|
||||
((= c "S") (list (dict "__t__" "class-s" "__neg__" true) (+ i 1)))
|
||||
((= c "b") (list (dict "__t__" "anchor-word") (+ i 1)))
|
||||
((= c "B") (list (dict "__t__" "anchor-nonword") (+ i 1)))
|
||||
((= c "n") (list (dict "__t__" "literal" "__c__" "\n") (+ i 1)))
|
||||
((= c "r") (list (dict "__t__" "literal" "__c__" "\r") (+ i 1)))
|
||||
((= c "t") (list (dict "__t__" "literal" "__c__" "\t") (+ i 1)))
|
||||
((= c "f") (list (dict "__t__" "literal" "__c__" "\\f") (+ i 1)))
|
||||
((= c "v") (list (dict "__t__" "literal" "__c__" "") (+ i 1)))
|
||||
((= c "u")
|
||||
(let
|
||||
((res (rx-parse-hex-n pat (+ i 1) 4 0)))
|
||||
(list (dict "__t__" "literal" "__c__" (nth res 0)) (nth res 1))))
|
||||
((= c "x")
|
||||
(let
|
||||
((res (rx-parse-hex-n pat (+ i 1) 2 0)))
|
||||
(list (dict "__t__" "literal" "__c__" (nth res 0)) (nth res 1))))
|
||||
(else (list (dict "__t__" "literal" "__c__" c) (+ i 1)))))))
|
||||
|
||||
;; parse a char-class item inside [...], returns (item new-i)
|
||||
(define
|
||||
rx-parse-class-item
|
||||
(fn
|
||||
(pat i)
|
||||
(let
|
||||
((c (rx-char-at pat i)))
|
||||
(cond
|
||||
((= c "\\")
|
||||
(let
|
||||
((esc (rx-parse-escape pat (+ i 1))))
|
||||
(let
|
||||
((node (nth esc 0)) (ni (nth esc 1)))
|
||||
(let
|
||||
((t (get node "__t__")))
|
||||
(cond
|
||||
((= t "class-d")
|
||||
(list
|
||||
(dict "kind" "class-d" "neg" (get node "__neg__"))
|
||||
ni))
|
||||
((= t "class-w")
|
||||
(list
|
||||
(dict "kind" "class-w" "neg" (get node "__neg__"))
|
||||
ni))
|
||||
((= t "class-s")
|
||||
(list
|
||||
(dict "kind" "class-s" "neg" (get node "__neg__"))
|
||||
ni))
|
||||
(else
|
||||
(let
|
||||
((lc (get node "__c__")))
|
||||
(if
|
||||
(and
|
||||
(= (rx-char-at pat ni) "-")
|
||||
(not (= (rx-char-at pat (+ ni 1)) "]")))
|
||||
(let
|
||||
((hi-c (rx-char-at pat (+ ni 1))))
|
||||
(list
|
||||
(dict "kind" "range" "lo" lc "hi" hi-c)
|
||||
(+ ni 2)))
|
||||
(list (dict "kind" "lit" "c" lc) ni)))))))))
|
||||
(else
|
||||
(if
|
||||
(and
|
||||
(not (= c ""))
|
||||
(= (rx-char-at pat (+ i 1)) "-")
|
||||
(not (= (rx-char-at pat (+ i 2)) "]"))
|
||||
(not (= (rx-char-at pat (+ i 2)) "")))
|
||||
(let
|
||||
((hi-c (rx-char-at pat (+ i 2))))
|
||||
(list (dict "kind" "range" "lo" c "hi" hi-c) (+ i 3)))
|
||||
(list (dict "kind" "lit" "c" c) (+ i 1))))))))
|
||||
|
||||
(define
|
||||
rx-parse-class-items
|
||||
(fn
|
||||
(pat i items)
|
||||
(let
|
||||
((c (rx-char-at pat i)))
|
||||
(if
|
||||
(or (= c "]") (= c ""))
|
||||
(list items i)
|
||||
(let
|
||||
((res (rx-parse-class-item pat i)))
|
||||
(begin
|
||||
(append! items (nth res 0))
|
||||
(rx-parse-class-items pat (nth res 1) items)))))))
|
||||
|
||||
;; parse a sequence until stop-ch or EOF; returns (nodes new-i groups-count)
|
||||
(define
|
||||
rx-parse-seq
|
||||
(fn
|
||||
(pat i stop-ch ds)
|
||||
(let
|
||||
((c (rx-char-at pat i)))
|
||||
(cond
|
||||
((= c "") (list (get ds "nodes") i (get ds "groups")))
|
||||
((= c stop-ch) (list (get ds "nodes") i (get ds "groups")))
|
||||
((= c "|") (rx-parse-alt-rest pat i ds))
|
||||
(else
|
||||
(let
|
||||
((res (rx-parse-atom pat i ds)))
|
||||
(let
|
||||
((node (nth res 0)) (ni (nth res 1)) (ds2 (nth res 2)))
|
||||
(let
|
||||
((qres (rx-parse-quant pat ni node)))
|
||||
(begin
|
||||
(append! (get ds2 "nodes") (nth qres 0))
|
||||
(rx-parse-seq pat (nth qres 1) stop-ch ds2))))))))))
|
||||
|
||||
;; when we hit | inside a sequence, collect all alternatives
|
||||
(define
|
||||
rx-parse-alt-rest
|
||||
(fn
|
||||
(pat i ds)
|
||||
(let
|
||||
((left-branch (get ds "nodes")) (branches (list)))
|
||||
(begin
|
||||
(append! branches left-branch)
|
||||
(rx-parse-alt-branches pat i (get ds "groups") branches)))))
|
||||
|
||||
(define
|
||||
rx-parse-alt-branches
|
||||
(fn
|
||||
(pat i n-groups branches)
|
||||
(let
|
||||
((new-nodes (list)) (ds2 (dict "groups" n-groups "nodes" new-nodes)))
|
||||
(let
|
||||
((res (rx-parse-seq pat (+ i 1) "|" ds2)))
|
||||
(begin
|
||||
(append! branches (nth res 0))
|
||||
(let
|
||||
((ni2 (nth res 1)) (g2 (nth res 2)))
|
||||
(if
|
||||
(= (rx-char-at pat ni2) "|")
|
||||
(rx-parse-alt-branches pat ni2 g2 branches)
|
||||
(list
|
||||
(list (dict "__t__" "alt" "__branches__" branches))
|
||||
ni2
|
||||
g2))))))))
|
||||
|
||||
;; parse quantifier suffix, returns (node new-i)
|
||||
(define
|
||||
rx-parse-quant
|
||||
(fn
|
||||
(pat i node)
|
||||
(let
|
||||
((c (rx-char-at pat i)))
|
||||
(cond
|
||||
((= c "*")
|
||||
(let
|
||||
((lazy? (= (rx-char-at pat (+ i 1)) "?")))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"quant"
|
||||
"__node__"
|
||||
node
|
||||
"__min__"
|
||||
0
|
||||
"__max__"
|
||||
-1
|
||||
"__lazy__"
|
||||
lazy?)
|
||||
(if lazy? (+ i 2) (+ i 1)))))
|
||||
((= c "+")
|
||||
(let
|
||||
((lazy? (= (rx-char-at pat (+ i 1)) "?")))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"quant"
|
||||
"__node__"
|
||||
node
|
||||
"__min__"
|
||||
1
|
||||
"__max__"
|
||||
-1
|
||||
"__lazy__"
|
||||
lazy?)
|
||||
(if lazy? (+ i 2) (+ i 1)))))
|
||||
((= c "?")
|
||||
(let
|
||||
((lazy? (= (rx-char-at pat (+ i 1)) "?")))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"quant"
|
||||
"__node__"
|
||||
node
|
||||
"__min__"
|
||||
0
|
||||
"__max__"
|
||||
1
|
||||
"__lazy__"
|
||||
lazy?)
|
||||
(if lazy? (+ i 2) (+ i 1)))))
|
||||
((= c "{")
|
||||
(let
|
||||
((mres (rx-parse-int pat (+ i 1) 0)))
|
||||
(let
|
||||
((mn (nth mres 0)) (mi (nth mres 1)))
|
||||
(let
|
||||
((sep (rx-char-at pat mi)))
|
||||
(cond
|
||||
((= sep "}")
|
||||
(let
|
||||
((lazy? (= (rx-char-at pat (+ mi 1)) "?")))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"quant"
|
||||
"__node__"
|
||||
node
|
||||
"__min__"
|
||||
mn
|
||||
"__max__"
|
||||
mn
|
||||
"__lazy__"
|
||||
lazy?)
|
||||
(if lazy? (+ mi 2) (+ mi 1)))))
|
||||
((= sep ",")
|
||||
(let
|
||||
((c2 (rx-char-at pat (+ mi 1))))
|
||||
(if
|
||||
(= c2 "}")
|
||||
(let
|
||||
((lazy? (= (rx-char-at pat (+ mi 2)) "?")))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"quant"
|
||||
"__node__"
|
||||
node
|
||||
"__min__"
|
||||
mn
|
||||
"__max__"
|
||||
-1
|
||||
"__lazy__"
|
||||
lazy?)
|
||||
(if lazy? (+ mi 3) (+ mi 2))))
|
||||
(let
|
||||
((mxres (rx-parse-int pat (+ mi 1) 0)))
|
||||
(let
|
||||
((mx (nth mxres 0)) (mxi (nth mxres 1)))
|
||||
(let
|
||||
((lazy? (= (rx-char-at pat (+ mxi 1)) "?")))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"quant"
|
||||
"__node__"
|
||||
node
|
||||
"__min__"
|
||||
mn
|
||||
"__max__"
|
||||
mx
|
||||
"__lazy__"
|
||||
lazy?)
|
||||
(if lazy? (+ mxi 2) (+ mxi 1)))))))))
|
||||
(else (list node i)))))))
|
||||
(else (list node i))))))
|
||||
|
||||
;; parse one atom, returns (node new-i new-ds)
|
||||
(define
|
||||
rx-parse-atom
|
||||
(fn
|
||||
(pat i ds)
|
||||
(let
|
||||
((c (rx-char-at pat i)))
|
||||
(cond
|
||||
((= c ".") (list (dict "__t__" "any") (+ i 1) ds))
|
||||
((= c "^") (list (dict "__t__" "anchor-start") (+ i 1) ds))
|
||||
((= c "$") (list (dict "__t__" "anchor-end") (+ i 1) ds))
|
||||
((= c "\\")
|
||||
(let
|
||||
((esc (rx-parse-escape pat (+ i 1))))
|
||||
(list (nth esc 0) (nth esc 1) ds)))
|
||||
((= c "[")
|
||||
(let
|
||||
((neg? (= (rx-char-at pat (+ i 1)) "^")))
|
||||
(let
|
||||
((start (if neg? (+ i 2) (+ i 1))) (items (list)))
|
||||
(let
|
||||
((res (rx-parse-class-items pat start items)))
|
||||
(let
|
||||
((ci (nth res 1)))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"char-class"
|
||||
"__neg__"
|
||||
neg?
|
||||
"__items__"
|
||||
items)
|
||||
(+ ci 1)
|
||||
ds))))))
|
||||
((= c "(")
|
||||
(let
|
||||
((c2 (rx-char-at pat (+ i 1))))
|
||||
(if
|
||||
(and (= c2 "?") (= (rx-char-at pat (+ i 2)) ":"))
|
||||
(let
|
||||
((inner-nodes (list))
|
||||
(inner-ds
|
||||
(dict "groups" (get ds "groups") "nodes" inner-nodes)))
|
||||
(let
|
||||
((res (rx-parse-seq pat (+ i 3) ")" inner-ds)))
|
||||
(list
|
||||
(dict "__t__" "ncgroup" "__nodes__" (nth res 0))
|
||||
(+ (nth res 1) 1)
|
||||
(dict "groups" (nth res 2) "nodes" (get ds "nodes")))))
|
||||
(let
|
||||
((gidx (+ (get ds "groups") 1)) (inner-nodes (list)))
|
||||
(let
|
||||
((inner-ds (dict "groups" gidx "nodes" inner-nodes)))
|
||||
(let
|
||||
((res (rx-parse-seq pat (+ i 1) ")" inner-ds)))
|
||||
(list
|
||||
(dict
|
||||
"__t__"
|
||||
"group"
|
||||
"__idx__"
|
||||
gidx
|
||||
"__nodes__"
|
||||
(nth res 0))
|
||||
(+ (nth res 1) 1)
|
||||
(dict "groups" (nth res 2) "nodes" (get ds "nodes")))))))))
|
||||
(else (list (dict "__t__" "literal" "__c__" c) (+ i 1) ds))))))
|
||||
|
||||
;; top-level compile
|
||||
(define
|
||||
rx-compile
|
||||
(fn
|
||||
(pattern)
|
||||
(let
|
||||
((nodes (list)) (ds (dict "groups" 0 "nodes" nodes)))
|
||||
(let
|
||||
((res (rx-parse-seq pattern 0 "" ds)))
|
||||
(dict "nodes" (nth res 0) "ngroups" (nth res 2))))))
|
||||
|
||||
;; ── Matcher ───────────────────────────────────────────────────────
|
||||
|
||||
;; Match a char-class item against character c
|
||||
(define
|
||||
rx-item-matches?
|
||||
(fn
|
||||
(item c ci?)
|
||||
(let
|
||||
((kind (get item "kind")))
|
||||
(cond
|
||||
((= kind "lit") (rx-char-eq? c (get item "c") ci?))
|
||||
((= kind "range")
|
||||
(let
|
||||
((lo (if ci? (rx-downcase-char (get item "lo")) (get item "lo")))
|
||||
(hi
|
||||
(if ci? (rx-downcase-char (get item "hi")) (get item "hi")))
|
||||
(dc (if ci? (rx-downcase-char c) c)))
|
||||
(and
|
||||
(>= (char-code dc) (char-code lo))
|
||||
(<= (char-code dc) (char-code hi)))))
|
||||
((= kind "class-d")
|
||||
(let ((m (rx-digit? c))) (if (get item "neg") (not m) m)))
|
||||
((= kind "class-w")
|
||||
(let ((m (rx-word? c))) (if (get item "neg") (not m) m)))
|
||||
((= kind "class-s")
|
||||
(let ((m (rx-space? c))) (if (get item "neg") (not m) m)))
|
||||
(else false)))))
|
||||
|
||||
(define
|
||||
rx-class-items-any?
|
||||
(fn
|
||||
(items c ci?)
|
||||
(if
|
||||
(empty? items)
|
||||
false
|
||||
(if
|
||||
(rx-item-matches? (first items) c ci?)
|
||||
true
|
||||
(rx-class-items-any? (rest items) c ci?)))))
|
||||
|
||||
(define
|
||||
rx-class-matches?
|
||||
(fn
|
||||
(node c ci?)
|
||||
(let
|
||||
((neg? (get node "__neg__")) (items (get node "__items__")))
|
||||
(let
|
||||
((hit (rx-class-items-any? items c ci?)))
|
||||
(if neg? (not hit) hit)))))
|
||||
|
||||
;; Word boundary check
|
||||
(define
|
||||
rx-is-word-boundary?
|
||||
(fn
|
||||
(s i slen)
|
||||
(let
|
||||
((before (if (> i 0) (rx-word? (char-at s (- i 1))) false))
|
||||
(after (if (< i slen) (rx-word? (char-at s i)) false)))
|
||||
(not (= before after)))))
|
||||
|
||||
;; ── Core matcher ──────────────────────────────────────────────────
|
||||
;;
|
||||
;; rx-match-nodes : nodes s i slen ci? mi? groups → end-pos or -1
|
||||
;;
|
||||
;; Matches `nodes` starting at position `i` in string `s`.
|
||||
;; Returns the position after the last character consumed, or -1 on failure.
|
||||
;; Mutates `groups` dict to record captures.
|
||||
|
||||
(define
|
||||
rx-match-nodes
|
||||
(fn
|
||||
(nodes s i slen ci? mi? groups)
|
||||
(if
|
||||
(empty? nodes)
|
||||
i
|
||||
(let
|
||||
((node (first nodes)) (rest-nodes (rest nodes)))
|
||||
(let
|
||||
((t (get node "__t__")))
|
||||
(cond
|
||||
((= t "literal")
|
||||
(if
|
||||
(and
|
||||
(< i slen)
|
||||
(rx-char-eq? (char-at s i) (get node "__c__") ci?))
|
||||
(rx-match-nodes rest-nodes s (+ i 1) slen ci? mi? groups)
|
||||
-1))
|
||||
((= t "any")
|
||||
(if
|
||||
(and (< i slen) (not (rx-newline? (char-at s i))))
|
||||
(rx-match-nodes rest-nodes s (+ i 1) slen ci? mi? groups)
|
||||
-1))
|
||||
((= t "class-d")
|
||||
(let
|
||||
((m (and (< i slen) (rx-digit? (char-at s i)))))
|
||||
(if
|
||||
(if (get node "__neg__") (not m) m)
|
||||
(rx-match-nodes rest-nodes s (+ i 1) slen ci? mi? groups)
|
||||
-1)))
|
||||
((= t "class-w")
|
||||
(let
|
||||
((m (and (< i slen) (rx-word? (char-at s i)))))
|
||||
(if
|
||||
(if (get node "__neg__") (not m) m)
|
||||
(rx-match-nodes rest-nodes s (+ i 1) slen ci? mi? groups)
|
||||
-1)))
|
||||
((= t "class-s")
|
||||
(let
|
||||
((m (and (< i slen) (rx-space? (char-at s i)))))
|
||||
(if
|
||||
(if (get node "__neg__") (not m) m)
|
||||
(rx-match-nodes rest-nodes s (+ i 1) slen ci? mi? groups)
|
||||
-1)))
|
||||
((= t "char-class")
|
||||
(if
|
||||
(and (< i slen) (rx-class-matches? node (char-at s i) ci?))
|
||||
(rx-match-nodes rest-nodes s (+ i 1) slen ci? mi? groups)
|
||||
-1))
|
||||
((= t "anchor-start")
|
||||
(if
|
||||
(or
|
||||
(= i 0)
|
||||
(and mi? (rx-newline? (rx-char-at s (- i 1)))))
|
||||
(rx-match-nodes rest-nodes s i slen ci? mi? groups)
|
||||
-1))
|
||||
((= t "anchor-end")
|
||||
(if
|
||||
(or (= i slen) (and mi? (rx-newline? (rx-char-at s i))))
|
||||
(rx-match-nodes rest-nodes s i slen ci? mi? groups)
|
||||
-1))
|
||||
((= t "anchor-word")
|
||||
(if
|
||||
(rx-is-word-boundary? s i slen)
|
||||
(rx-match-nodes rest-nodes s i slen ci? mi? groups)
|
||||
-1))
|
||||
((= t "anchor-nonword")
|
||||
(if
|
||||
(not (rx-is-word-boundary? s i slen))
|
||||
(rx-match-nodes rest-nodes s i slen ci? mi? groups)
|
||||
-1))
|
||||
((= t "group")
|
||||
(let
|
||||
((gidx (get node "__idx__"))
|
||||
(inner (get node "__nodes__")))
|
||||
(let
|
||||
((g-end (rx-match-nodes inner s i slen ci? mi? groups)))
|
||||
(if
|
||||
(>= g-end 0)
|
||||
(begin
|
||||
(dict-set!
|
||||
groups
|
||||
(js-to-string gidx)
|
||||
(substring s i g-end))
|
||||
(let
|
||||
((final-end (rx-match-nodes rest-nodes s g-end slen ci? mi? groups)))
|
||||
(if
|
||||
(>= final-end 0)
|
||||
final-end
|
||||
(begin
|
||||
(dict-set! groups (js-to-string gidx) nil)
|
||||
-1))))
|
||||
-1))))
|
||||
((= t "ncgroup")
|
||||
(let
|
||||
((inner (get node "__nodes__")))
|
||||
(rx-match-nodes
|
||||
(append inner rest-nodes)
|
||||
s
|
||||
i
|
||||
slen
|
||||
ci?
|
||||
mi?
|
||||
groups)))
|
||||
((= t "alt")
|
||||
(let
|
||||
((branches (get node "__branches__")))
|
||||
(rx-try-branches branches rest-nodes s i slen ci? mi? groups)))
|
||||
((= t "quant")
|
||||
(let
|
||||
((inner-node (get node "__node__"))
|
||||
(mn (get node "__min__"))
|
||||
(mx (get node "__max__"))
|
||||
(lazy? (get node "__lazy__")))
|
||||
(if
|
||||
lazy?
|
||||
(rx-quant-lazy
|
||||
inner-node
|
||||
mn
|
||||
mx
|
||||
rest-nodes
|
||||
s
|
||||
i
|
||||
slen
|
||||
ci?
|
||||
mi?
|
||||
groups
|
||||
0)
|
||||
(rx-quant-greedy
|
||||
inner-node
|
||||
mn
|
||||
mx
|
||||
rest-nodes
|
||||
s
|
||||
i
|
||||
slen
|
||||
ci?
|
||||
mi?
|
||||
groups
|
||||
0))))
|
||||
(else -1)))))))
|
||||
|
||||
(define
|
||||
rx-try-branches
|
||||
(fn
|
||||
(branches rest-nodes s i slen ci? mi? groups)
|
||||
(if
|
||||
(empty? branches)
|
||||
-1
|
||||
(let
|
||||
((res (rx-match-nodes (append (first branches) rest-nodes) s i slen ci? mi? groups)))
|
||||
(if
|
||||
(>= res 0)
|
||||
res
|
||||
(rx-try-branches (rest branches) rest-nodes s i slen ci? mi? groups))))))
|
||||
|
||||
;; Greedy: expand as far as possible, then try rest from the longest match
|
||||
;; Strategy: recurse forward (extend first); only try rest when extension fails
|
||||
(define
|
||||
rx-quant-greedy
|
||||
(fn
|
||||
(inner-node mn mx rest-nodes s i slen ci? mi? groups count)
|
||||
(let
|
||||
((can-extend (and (< i slen) (or (= mx -1) (< count mx)))))
|
||||
(if
|
||||
can-extend
|
||||
(let
|
||||
((ni (rx-match-one inner-node s i slen ci? mi? groups)))
|
||||
(if
|
||||
(>= ni 0)
|
||||
(let
|
||||
((res (rx-quant-greedy inner-node mn mx rest-nodes s ni slen ci? mi? groups (+ count 1))))
|
||||
(if
|
||||
(>= res 0)
|
||||
res
|
||||
(if
|
||||
(>= count mn)
|
||||
(rx-match-nodes rest-nodes s i slen ci? mi? groups)
|
||||
-1)))
|
||||
(if
|
||||
(>= count mn)
|
||||
(rx-match-nodes rest-nodes s i slen ci? mi? groups)
|
||||
-1)))
|
||||
(if
|
||||
(>= count mn)
|
||||
(rx-match-nodes rest-nodes s i slen ci? mi? groups)
|
||||
-1)))))
|
||||
|
||||
;; Lazy: try rest first, extend only if rest fails
|
||||
(define
|
||||
rx-quant-lazy
|
||||
(fn
|
||||
(inner-node mn mx rest-nodes s i slen ci? mi? groups count)
|
||||
(if
|
||||
(>= count mn)
|
||||
(let
|
||||
((res (rx-match-nodes rest-nodes s i slen ci? mi? groups)))
|
||||
(if
|
||||
(>= res 0)
|
||||
res
|
||||
(if
|
||||
(and (< i slen) (or (= mx -1) (< count mx)))
|
||||
(let
|
||||
((ni (rx-match-one inner-node s i slen ci? mi? groups)))
|
||||
(if
|
||||
(>= ni 0)
|
||||
(rx-quant-lazy
|
||||
inner-node
|
||||
mn
|
||||
mx
|
||||
rest-nodes
|
||||
s
|
||||
ni
|
||||
slen
|
||||
ci?
|
||||
mi?
|
||||
groups
|
||||
(+ count 1))
|
||||
-1))
|
||||
-1)))
|
||||
(if
|
||||
(< i slen)
|
||||
(let
|
||||
((ni (rx-match-one inner-node s i slen ci? mi? groups)))
|
||||
(if
|
||||
(>= ni 0)
|
||||
(rx-quant-lazy
|
||||
inner-node
|
||||
mn
|
||||
mx
|
||||
rest-nodes
|
||||
s
|
||||
ni
|
||||
slen
|
||||
ci?
|
||||
mi?
|
||||
groups
|
||||
(+ count 1))
|
||||
-1))
|
||||
-1))))
|
||||
|
||||
;; Match a single node at position i, return new pos or -1
|
||||
(define
|
||||
rx-match-one
|
||||
(fn
|
||||
(node s i slen ci? mi? groups)
|
||||
(rx-match-nodes (list node) s i slen ci? mi? groups)))
|
||||
|
||||
;; ── Engine entry points ───────────────────────────────────────────
|
||||
|
||||
;; Try matching at exactly position i. Returns result dict or nil.
|
||||
(define
|
||||
rx-try-at
|
||||
(fn
|
||||
(compiled s i slen ci? mi?)
|
||||
(let
|
||||
((nodes (get compiled "nodes")) (ngroups (get compiled "ngroups")))
|
||||
(let
|
||||
((groups (dict)))
|
||||
(let
|
||||
((end (rx-match-nodes nodes s i slen ci? mi? groups)))
|
||||
(if
|
||||
(>= end 0)
|
||||
(dict "start" i "end" end "groups" groups "ngroups" ngroups)
|
||||
nil))))))
|
||||
|
||||
;; Find first match scanning from search-start.
|
||||
(define
|
||||
rx-find-from
|
||||
(fn
|
||||
(compiled s search-start slen ci? mi?)
|
||||
(if
|
||||
(> search-start slen)
|
||||
nil
|
||||
(let
|
||||
((res (rx-try-at compiled s search-start slen ci? mi?)))
|
||||
(if
|
||||
res
|
||||
res
|
||||
(rx-find-from compiled s (+ search-start 1) slen ci? mi?))))))
|
||||
|
||||
;; Build exec result dict from raw match result
|
||||
(define
|
||||
rx-build-exec-result
|
||||
(fn
|
||||
(s match-res)
|
||||
(let
|
||||
((start (get match-res "start"))
|
||||
(end (get match-res "end"))
|
||||
(groups (get match-res "groups"))
|
||||
(ngroups (get match-res "ngroups")))
|
||||
(let
|
||||
((matched (substring s start end))
|
||||
(caps (rx-build-captures groups ngroups 1)))
|
||||
(dict "match" matched "index" start "input" s "groups" caps)))))
|
||||
|
||||
(define
|
||||
rx-build-captures
|
||||
(fn
|
||||
(groups ngroups idx)
|
||||
(if
|
||||
(> idx ngroups)
|
||||
(list)
|
||||
(let
|
||||
((cap (get groups (js-to-string idx))))
|
||||
(cons
|
||||
(if (= cap nil) :js-undefined cap)
|
||||
(rx-build-captures groups ngroups (+ idx 1)))))))
|
||||
|
||||
;; ── Public interface ──────────────────────────────────────────────
|
||||
|
||||
;; Lazy compile: build NFA on first use, cache under "__compiled__"
|
||||
(define
|
||||
rx-ensure-compiled!
|
||||
(fn
|
||||
(rx)
|
||||
(if
|
||||
(dict-has? rx "__compiled__")
|
||||
(get rx "__compiled__")
|
||||
(let
|
||||
((c (rx-compile (get rx "source"))))
|
||||
(begin (dict-set! rx "__compiled__" c) c)))))
|
||||
|
||||
(define
|
||||
rx-test
|
||||
(fn
|
||||
(rx s)
|
||||
(let
|
||||
((compiled (rx-ensure-compiled! rx))
|
||||
(ci? (get rx "ignoreCase"))
|
||||
(mi? (get rx "multiline"))
|
||||
(slen (len s)))
|
||||
(let
|
||||
((start (if (get rx "global") (let ((li (get rx "lastIndex"))) (if (number? li) li 0)) 0)))
|
||||
(let
|
||||
((res (rx-find-from compiled s start slen ci? mi?)))
|
||||
(if
|
||||
(get rx "global")
|
||||
(begin
|
||||
(dict-set! rx "lastIndex" (if res (get res "end") 0))
|
||||
(if res true false))
|
||||
(if res true false)))))))
|
||||
|
||||
(define
|
||||
rx-exec
|
||||
(fn
|
||||
(rx s)
|
||||
(let
|
||||
((compiled (rx-ensure-compiled! rx))
|
||||
(ci? (get rx "ignoreCase"))
|
||||
(mi? (get rx "multiline"))
|
||||
(slen (len s)))
|
||||
(let
|
||||
((start (if (get rx "global") (let ((li (get rx "lastIndex"))) (if (number? li) li 0)) 0)))
|
||||
(let
|
||||
((res (rx-find-from compiled s start slen ci? mi?)))
|
||||
(if
|
||||
res
|
||||
(begin
|
||||
(when
|
||||
(get rx "global")
|
||||
(dict-set! rx "lastIndex" (get res "end")))
|
||||
(rx-build-exec-result s res))
|
||||
(begin
|
||||
(when (get rx "global") (dict-set! rx "lastIndex" 0))
|
||||
nil)))))))
|
||||
|
||||
;; match-all for String.prototype.matchAll
|
||||
(define
|
||||
js-regex-match-all
|
||||
(fn
|
||||
(rx s)
|
||||
(let
|
||||
((compiled (rx-ensure-compiled! rx))
|
||||
(ci? (get rx "ignoreCase"))
|
||||
(mi? (get rx "multiline"))
|
||||
(slen (len s))
|
||||
(results (list)))
|
||||
(rx-match-all-loop compiled s 0 slen ci? mi? results))))
|
||||
|
||||
(define
|
||||
rx-match-all-loop
|
||||
(fn
|
||||
(compiled s i slen ci? mi? results)
|
||||
(if
|
||||
(> i slen)
|
||||
results
|
||||
(let
|
||||
((res (rx-find-from compiled s i slen ci? mi?)))
|
||||
(if
|
||||
res
|
||||
(begin
|
||||
(append! results (rx-build-exec-result s res))
|
||||
(let
|
||||
((next (get res "end")))
|
||||
(rx-match-all-loop
|
||||
compiled
|
||||
s
|
||||
(if (= next i) (+ i 1) next)
|
||||
slen
|
||||
ci?
|
||||
mi?
|
||||
results)))
|
||||
results)))))
|
||||
|
||||
;; ── Install platform ──────────────────────────────────────────────
|
||||
|
||||
(js-regex-platform-override! "test" rx-test)
|
||||
(js-regex-platform-override! "exec" rx-exec)
|
||||
@@ -2032,7 +2032,15 @@
|
||||
(&rest args)
|
||||
(cond
|
||||
((= (len args) 0) nil)
|
||||
((js-regex? (nth args 0)) (js-regex-stub-exec (nth args 0) s))
|
||||
((js-regex? (nth args 0))
|
||||
(let
|
||||
((rx (nth args 0)))
|
||||
(let
|
||||
((impl (get __js_regex_platform__ "exec")))
|
||||
(if
|
||||
(js-undefined? impl)
|
||||
(js-regex-stub-exec rx s)
|
||||
(impl rx s)))))
|
||||
(else
|
||||
(let
|
||||
((needle (js-to-string (nth args 0))))
|
||||
@@ -2041,7 +2049,7 @@
|
||||
(if
|
||||
(= idx -1)
|
||||
nil
|
||||
(let ((res (list))) (append! res needle) res))))))))
|
||||
(let ((res (list))) (begin (append! res needle) res)))))))))
|
||||
((= name "at")
|
||||
(fn
|
||||
(i)
|
||||
@@ -2099,6 +2107,20 @@
|
||||
((= name "toWellFormed") (fn () s))
|
||||
(else js-undefined))))
|
||||
|
||||
(define __js_tdz_sentinel__ (dict "__tdz__" true))
|
||||
|
||||
(define js-tdz? (fn (v) (and (dict? v) (dict-has? v "__tdz__"))))
|
||||
|
||||
(define
|
||||
js-tdz-check
|
||||
(fn
|
||||
(name val)
|
||||
(if
|
||||
(js-tdz? val)
|
||||
(raise
|
||||
(TypeError (str "Cannot access '" name "' before initialization")))
|
||||
val)))
|
||||
|
||||
(define
|
||||
js-string-slice
|
||||
(fn
|
||||
|
||||
146
lib/js/test.sh
146
lib/js/test.sh
@@ -33,6 +33,8 @@ cat > "$TMPFILE" << 'EPOCHS'
|
||||
(load "lib/js/transpile.sx")
|
||||
(epoch 5)
|
||||
(load "lib/js/runtime.sx")
|
||||
(epoch 6)
|
||||
(load "lib/js/regex.sx")
|
||||
|
||||
;; ── Phase 0: stubs still behave ─────────────────────────────────
|
||||
(epoch 10)
|
||||
@@ -1323,6 +1325,108 @@ cat > "$TMPFILE" << 'EPOCHS'
|
||||
(epoch 3505)
|
||||
(eval "(js-eval \"var a = {length: 3, 0: 10, 1: 20, 2: 30}; var sum = 0; Array.prototype.forEach.call(a, function(x){sum += x;}); sum\")")
|
||||
|
||||
;; ── Phase 12: Regex engine ────────────────────────────────────────
|
||||
;; Platform is installed (test key is a function, not undefined)
|
||||
(epoch 5000)
|
||||
(eval "(js-undefined? (get __js_regex_platform__ \"test\"))")
|
||||
(epoch 5001)
|
||||
(eval "(js-eval \"/foo/.test('hi foo bar')\")")
|
||||
(epoch 5002)
|
||||
(eval "(js-eval \"/foo/.test('hi bar')\")")
|
||||
;; Case-insensitive flag
|
||||
(epoch 5003)
|
||||
(eval "(js-eval \"/FOO/i.test('hello foo world')\")")
|
||||
;; Anchors
|
||||
(epoch 5004)
|
||||
(eval "(js-eval \"/^hello/.test('hello world')\")")
|
||||
(epoch 5005)
|
||||
(eval "(js-eval \"/^hello/.test('say hello')\")")
|
||||
(epoch 5006)
|
||||
(eval "(js-eval \"/world$/.test('hello world')\")")
|
||||
;; Character classes
|
||||
(epoch 5007)
|
||||
(eval "(js-eval \"/\\\\d+/.test('abc 123')\")")
|
||||
(epoch 5008)
|
||||
(eval "(js-eval \"/\\\\w+/.test('hello')\")")
|
||||
(epoch 5009)
|
||||
(eval "(js-eval \"/[abc]/.test('dog')\")")
|
||||
(epoch 5010)
|
||||
(eval "(js-eval \"/[abc]/.test('cat')\")")
|
||||
;; Quantifiers
|
||||
(epoch 5011)
|
||||
(eval "(js-eval \"/a*b/.test('b')\")")
|
||||
(epoch 5012)
|
||||
(eval "(js-eval \"/a+b/.test('b')\")")
|
||||
(epoch 5013)
|
||||
(eval "(js-eval \"/a{2,3}/.test('aa')\")")
|
||||
(epoch 5014)
|
||||
(eval "(js-eval \"/a{2,3}/.test('a')\")")
|
||||
;; Dot
|
||||
(epoch 5015)
|
||||
(eval "(js-eval \"/h.llo/.test('hello')\")")
|
||||
(epoch 5016)
|
||||
(eval "(js-eval \"/h.llo/.test('hllo')\")")
|
||||
;; exec result
|
||||
(epoch 5017)
|
||||
(eval "(js-eval \"var m = /foo(\\\\w+)/.exec('foobar'); m.match\")")
|
||||
(epoch 5018)
|
||||
(eval "(js-eval \"var m = /foo(\\\\w+)/.exec('foobar'); m.index\")")
|
||||
(epoch 5019)
|
||||
(eval "(js-eval \"var m = /foo(\\\\w+)/.exec('foobar'); m.groups[0]\")")
|
||||
;; Alternation
|
||||
(epoch 5020)
|
||||
(eval "(js-eval \"/cat|dog/.test('I have a dog')\")")
|
||||
(epoch 5021)
|
||||
(eval "(js-eval \"/cat|dog/.test('I have a fish')\")")
|
||||
;; Non-capturing group
|
||||
(epoch 5022)
|
||||
(eval "(js-eval \"/(?:foo)+/.test('foofoo')\")")
|
||||
;; Negated char class
|
||||
(epoch 5023)
|
||||
(eval "(js-eval \"/[^abc]/.test('d')\")")
|
||||
(epoch 5024)
|
||||
(eval "(js-eval \"/[^abc]/.test('a')\")")
|
||||
;; Range inside char class
|
||||
(epoch 5025)
|
||||
(eval "(js-eval \"/[a-z]+/.test('hello')\")")
|
||||
;; Word boundary
|
||||
(epoch 5026)
|
||||
(eval "(js-eval \"/\\\\bword\\\\b/.test('a word here')\")")
|
||||
(epoch 5027)
|
||||
(eval "(js-eval \"/\\\\bword\\\\b/.test('password')\")")
|
||||
;; Lazy quantifier
|
||||
(epoch 5028)
|
||||
(eval "(js-eval \"var m = /a+?/.exec('aaa'); m.match\")")
|
||||
;; Global flag exec
|
||||
(epoch 5029)
|
||||
(eval "(js-eval \"var r=/\\\\d+/g; r.exec('a1b2'); r.exec('a1b2').match\")")
|
||||
;; String.prototype.match with regex
|
||||
(epoch 5030)
|
||||
(eval "(js-eval \"'hello world'.match(/\\\\w+/).match\")")
|
||||
;; String.prototype.search
|
||||
(epoch 5031)
|
||||
(eval "(js-eval \"'hello world'.search(/world/)\")")
|
||||
;; String.prototype.replace with regex
|
||||
(epoch 5032)
|
||||
(eval "(js-eval \"'hello world'.replace(/world/, 'there')\")")
|
||||
;; multiline anchor
|
||||
(epoch 5033)
|
||||
(eval "(js-eval \"/^bar/m.test('foo\\nbar')\")")
|
||||
|
||||
;; ── Phase 13: let/const TDZ infrastructure ───────────────────────
|
||||
;; The TDZ sentinel and checker are defined in runtime.sx.
|
||||
;; let/const bindings work normally after initialization.
|
||||
(epoch 5100)
|
||||
(eval "(js-eval \"let x = 5; x\")")
|
||||
(epoch 5101)
|
||||
(eval "(js-eval \"const y = 42; y\")")
|
||||
;; TDZ sentinel exists and is detectable
|
||||
(epoch 5102)
|
||||
(eval "(js-tdz? __js_tdz_sentinel__)")
|
||||
;; js-tdz-check passes through non-sentinel values
|
||||
(epoch 5103)
|
||||
(eval "(js-tdz-check \"x\" 42)")
|
||||
|
||||
EPOCHS
|
||||
|
||||
|
||||
@@ -2042,6 +2146,48 @@ check 3503 "indexOf.call arrLike" '1'
|
||||
check 3504 "filter.call arrLike" '"2,3"'
|
||||
check 3505 "forEach.call arrLike sum" '60'
|
||||
|
||||
# ── Phase 12: Regex engine ────────────────────────────────────────
|
||||
check 5000 "regex platform installed" 'false'
|
||||
check 5001 "/foo/ matches" 'true'
|
||||
check 5002 "/foo/ no match" 'false'
|
||||
check 5003 "/FOO/i case-insensitive" 'true'
|
||||
check 5004 "/^hello/ anchor match" 'true'
|
||||
check 5005 "/^hello/ anchor no-match" 'false'
|
||||
check 5006 "/world$/ end anchor" 'true'
|
||||
check 5007 "/\\d+/ digit class" 'true'
|
||||
check 5008 "/\\w+/ word class" 'true'
|
||||
check 5009 "/[abc]/ class no-match" 'false'
|
||||
check 5010 "/[abc]/ class match" 'true'
|
||||
check 5011 "/a*b/ zero-or-more" 'true'
|
||||
check 5012 "/a+b/ one-or-more no-match" 'false'
|
||||
check 5013 "/a{2,3}/ quant match" 'true'
|
||||
check 5014 "/a{2,3}/ quant no-match" 'false'
|
||||
check 5015 "dot matches any" 'true'
|
||||
check 5016 "dot requires char" 'false'
|
||||
check 5017 "exec match string" '"foobar"'
|
||||
check 5018 "exec match index" '0'
|
||||
check 5019 "exec capture group" '"bar"'
|
||||
check 5020 "alternation cat|dog match" 'true'
|
||||
check 5021 "alternation cat|dog no-match" 'false'
|
||||
check 5022 "non-capturing group" 'true'
|
||||
check 5023 "negated class match" 'true'
|
||||
check 5024 "negated class no-match" 'false'
|
||||
check 5025 "range [a-z]+" 'true'
|
||||
check 5026 "word boundary match" 'true'
|
||||
check 5027 "word boundary no-match" 'false'
|
||||
check 5028 "lazy quantifier" '"a"'
|
||||
check 5029 "global exec advances" '"2"'
|
||||
check 5030 "String.match regex" '"hello"'
|
||||
check 5031 "String.search regex" '6'
|
||||
check 5032 "String.replace regex" '"hello there"'
|
||||
check 5033 "multiline anchor" 'true'
|
||||
|
||||
# ── Phase 13: let/const TDZ infrastructure ───────────────────────
|
||||
check 5100 "let binding initialized" '5'
|
||||
check 5101 "const binding initialized" '42'
|
||||
check 5102 "TDZ sentinel is detectable" 'true'
|
||||
check 5103 "tdz-check passes non-sentinel" '42'
|
||||
|
||||
TOTAL=$((PASS + FAIL))
|
||||
if [ $FAIL -eq 0 ]; then
|
||||
echo "✓ $PASS/$TOTAL JS-on-SX tests passed"
|
||||
|
||||
@@ -798,6 +798,7 @@ class ServerSession:
|
||||
self._run_and_collect(3, '(load "lib/js/parser.sx")', timeout=60.0)
|
||||
self._run_and_collect(4, '(load "lib/js/transpile.sx")', timeout=60.0)
|
||||
self._run_and_collect(5, '(load "lib/js/runtime.sx")', timeout=60.0)
|
||||
self._run_and_collect(50, '(load "lib/js/regex.sx")', timeout=60.0)
|
||||
# Preload the stub harness — use precomputed SX cache when available
|
||||
# (huge win: ~15s js-eval HARNESS_STUB → ~0s load precomputed .sx).
|
||||
cache_rel = _harness_cache_rel_path()
|
||||
|
||||
@@ -935,12 +935,12 @@
|
||||
|
||||
(define
|
||||
js-transpile-var
|
||||
(fn (kind decls) (cons (js-sym "begin") (js-vardecl-forms decls))))
|
||||
(fn (kind decls) (cons (js-sym "begin") (js-vardecl-forms kind decls))))
|
||||
|
||||
(define
|
||||
js-vardecl-forms
|
||||
(fn
|
||||
(decls)
|
||||
(kind decls)
|
||||
(cond
|
||||
((empty? decls) (list))
|
||||
(else
|
||||
@@ -953,7 +953,7 @@
|
||||
(js-sym "define")
|
||||
(js-sym (nth d 1))
|
||||
(js-transpile (nth d 2)))
|
||||
(js-vardecl-forms (rest decls))))
|
||||
(js-vardecl-forms kind (rest decls))))
|
||||
((js-tag? d "js-vardecl-obj")
|
||||
(let
|
||||
((names (nth d 1))
|
||||
@@ -964,7 +964,7 @@
|
||||
(js-vardecl-obj-forms
|
||||
names
|
||||
tmp-sym
|
||||
(js-vardecl-forms (rest decls))))))
|
||||
(js-vardecl-forms kind (rest decls))))))
|
||||
((js-tag? d "js-vardecl-arr")
|
||||
(let
|
||||
((names (nth d 1))
|
||||
@@ -976,7 +976,7 @@
|
||||
names
|
||||
tmp-sym
|
||||
0
|
||||
(js-vardecl-forms (rest decls))))))
|
||||
(js-vardecl-forms kind (rest decls))))))
|
||||
(else (error "js-vardecl-forms: unexpected decl"))))))))
|
||||
|
||||
(define
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Smalltalk-on-SX vs. GNU Smalltalk timing comparison.
|
||||
#
|
||||
# Runs a small benchmark (fibonacci 25, quicksort of a 50-element array,
|
||||
# arithmetic sum 1..1000) on both runtimes and reports the ratio.
|
||||
#
|
||||
# GNU Smalltalk (`gst`) must be installed and on $PATH. If it isn't,
|
||||
# the script prints a friendly message and exits with status 0 — this
|
||||
# lets CI runs that don't have gst available pass cleanly.
|
||||
#
|
||||
# Usage: bash lib/smalltalk/compare.sh
|
||||
|
||||
set -uo pipefail
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
OUT="lib/smalltalk/compare-results.txt"
|
||||
|
||||
if ! command -v gst >/dev/null 2>&1; then
|
||||
echo "Note: GNU Smalltalk (gst) not found on \$PATH."
|
||||
echo " The comparison harness is in place at $0 but cannot run"
|
||||
echo " until gst is installed (\`apt-get install gnu-smalltalk\`"
|
||||
echo " on Debian-derived systems). Skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
SX="hosts/ocaml/_build/default/bin/sx_server.exe"
|
||||
if [ ! -x "$SX" ]; then
|
||||
MAIN_ROOT=$(git worktree list | head -1 | awk '{print $1}')
|
||||
SX="$MAIN_ROOT/$SX"
|
||||
fi
|
||||
|
||||
# A trio of small benchmarks. Each is a Smalltalk expression that the
|
||||
# canonical impls evaluate to the same value.
|
||||
BENCH_FIB='Object subclass: #B instanceVariableNames: ""! !B methodsFor: "x"! fib: n n < 2 ifTrue: [^ n]. ^ (self fib: n - 1) + (self fib: n - 2)! ! Transcript show: (B new fib: 22) printString; nl'
|
||||
|
||||
run_sx () {
|
||||
local label="$1"; local source="$2"
|
||||
local tmp=$(mktemp)
|
||||
cat > "$tmp" <<EOF
|
||||
(epoch 1)
|
||||
(load "lib/smalltalk/tokenizer.sx")
|
||||
(load "lib/smalltalk/parser.sx")
|
||||
(load "lib/smalltalk/runtime.sx")
|
||||
(load "lib/smalltalk/eval.sx")
|
||||
(epoch 2)
|
||||
(eval "(begin (st-bootstrap-classes!) (smalltalk-load \"Object subclass: #B instanceVariableNames: ''! !B methodsFor: 'x'! fib: n n < 2 ifTrue: [^ n]. ^ (self fib: n - 1) + (self fib: n - 2)! !\") (smalltalk-eval-program \"^ B new fib: 22\"))")
|
||||
EOF
|
||||
local start=$(date +%s.%N)
|
||||
timeout 60 "$SX" < "$tmp" > /dev/null 2>&1
|
||||
local rc=$?
|
||||
local end=$(date +%s.%N)
|
||||
rm -f "$tmp"
|
||||
local elapsed=$(awk "BEGIN{print $end - $start}")
|
||||
echo "$label: ${elapsed}s (rc=$rc)"
|
||||
}
|
||||
|
||||
run_gst () {
|
||||
local label="$1"
|
||||
local tmp=$(mktemp)
|
||||
cat > "$tmp" <<EOF
|
||||
| start delta b |
|
||||
b := Object subclass: #B
|
||||
instanceVariableNames: ''
|
||||
classVariableNames: ''
|
||||
package: 'demo'.
|
||||
b compile: 'fib: n n < 2 ifTrue: [^ n]. ^ (self fib: n - 1) + (self fib: n - 2)'.
|
||||
start := Time millisecondClock.
|
||||
B new fib: 22.
|
||||
delta := Time millisecondClock - start.
|
||||
Transcript show: 'gst ', delta printString, 'ms'; nl.
|
||||
EOF
|
||||
local start=$(date +%s.%N)
|
||||
timeout 60 gst -q "$tmp" > /dev/null 2>&1
|
||||
local rc=$?
|
||||
local end=$(date +%s.%N)
|
||||
rm -f "$tmp"
|
||||
local elapsed=$(awk "BEGIN{print $end - $start}")
|
||||
echo "$label: ${elapsed}s (rc=$rc)"
|
||||
}
|
||||
|
||||
{
|
||||
echo "Smalltalk-on-SX vs GNU Smalltalk — fibonacci(22)"
|
||||
echo "Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo
|
||||
run_sx "smalltalk-on-sx (call/cc + dict ivars)"
|
||||
run_gst "gnu smalltalk"
|
||||
} | tee "$OUT"
|
||||
|
||||
echo
|
||||
echo "Saved: $OUT"
|
||||
@@ -1,99 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Smalltalk-on-SX conformance runner.
|
||||
#
|
||||
# Runs the full test suite once with per-file detail, pulls out the
|
||||
# classic-corpus numbers, and writes:
|
||||
# lib/smalltalk/scoreboard.json — machine-readable summary
|
||||
# lib/smalltalk/scoreboard.md — human-readable summary
|
||||
#
|
||||
# Usage: bash lib/smalltalk/conformance.sh
|
||||
|
||||
set -uo pipefail
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
OUT_JSON="lib/smalltalk/scoreboard.json"
|
||||
OUT_MD="lib/smalltalk/scoreboard.md"
|
||||
|
||||
DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
|
||||
# Catalog .st programs in the corpus.
|
||||
PROGRAMS=()
|
||||
for f in lib/smalltalk/tests/programs/*.st; do
|
||||
[ -f "$f" ] || continue
|
||||
PROGRAMS+=("$(basename "$f" .st)")
|
||||
done
|
||||
NUM_PROGRAMS=${#PROGRAMS[@]}
|
||||
|
||||
# Run the full test suite with per-file detail.
|
||||
RUNNER_OUT=$(bash lib/smalltalk/test.sh -v 2>&1)
|
||||
RC=$?
|
||||
|
||||
# Final summary line: "OK 403/403 ..." or "FAIL 400/403 ...".
|
||||
ALL_SUM=$(echo "$RUNNER_OUT" | grep -E '^(OK|FAIL) [0-9]+/[0-9]+' | tail -1)
|
||||
ALL_PASS=$(echo "$ALL_SUM" | grep -oE '[0-9]+/[0-9]+' | head -1 | cut -d/ -f1)
|
||||
ALL_TOTAL=$(echo "$ALL_SUM" | grep -oE '[0-9]+/[0-9]+' | head -1 | cut -d/ -f2)
|
||||
|
||||
# Per-file pass counts (verbose lines look like "OK <path> N passed").
|
||||
get_pass () {
|
||||
local fname="$1"
|
||||
echo "$RUNNER_OUT" | awk -v f="$fname" '
|
||||
$0 ~ f { for (i=1; i<=NF; i++) if ($i ~ /^[0-9]+$/) { print $i; exit } }'
|
||||
}
|
||||
|
||||
PROG_PASS=$(get_pass "tests/programs.sx")
|
||||
PROG_PASS=${PROG_PASS:-0}
|
||||
|
||||
# scoreboard.json
|
||||
{
|
||||
printf '{\n'
|
||||
printf ' "date": "%s",\n' "$DATE"
|
||||
printf ' "programs": [\n'
|
||||
for i in "${!PROGRAMS[@]}"; do
|
||||
sep=","; [ "$i" -eq "$((NUM_PROGRAMS - 1))" ] && sep=""
|
||||
printf ' "%s.st"%s\n' "${PROGRAMS[$i]}" "$sep"
|
||||
done
|
||||
printf ' ],\n'
|
||||
printf ' "program_count": %d,\n' "$NUM_PROGRAMS"
|
||||
printf ' "program_tests_passed": %s,\n' "$PROG_PASS"
|
||||
printf ' "all_tests_passed": %s,\n' "$ALL_PASS"
|
||||
printf ' "all_tests_total": %s,\n' "$ALL_TOTAL"
|
||||
printf ' "exit_code": %d\n' "$RC"
|
||||
printf '}\n'
|
||||
} > "$OUT_JSON"
|
||||
|
||||
# scoreboard.md
|
||||
{
|
||||
printf '# Smalltalk-on-SX Scoreboard\n\n'
|
||||
printf '_Last run: %s_\n\n' "$DATE"
|
||||
|
||||
printf '## Totals\n\n'
|
||||
printf '| Suite | Passing |\n'
|
||||
printf '|-------|---------|\n'
|
||||
printf '| All Smalltalk-on-SX tests | **%s / %s** |\n' "$ALL_PASS" "$ALL_TOTAL"
|
||||
printf '| Classic-corpus tests (`tests/programs.sx`) | **%s** |\n\n' "$PROG_PASS"
|
||||
|
||||
printf '## Classic-corpus programs (`lib/smalltalk/tests/programs/`)\n\n'
|
||||
printf '| Program | Status |\n'
|
||||
printf '|---------|--------|\n'
|
||||
for prog in "${PROGRAMS[@]}"; do
|
||||
printf '| `%s.st` | present |\n' "$prog"
|
||||
done
|
||||
printf '\n'
|
||||
|
||||
printf '## Per-file test counts\n\n'
|
||||
printf '```\n'
|
||||
echo "$RUNNER_OUT" | grep -E '^(OK|X) lib/smalltalk/tests/' | sort
|
||||
printf '```\n\n'
|
||||
|
||||
printf '## Notes\n\n'
|
||||
printf -- '- The spec interpreter is correct but slow (call/cc + dict-based ivars per send).\n'
|
||||
printf -- '- Larger Life multi-step verification, the 8-queens canonical case, and the glider-gun pattern are deferred to the JIT path.\n'
|
||||
printf -- '- Generated by `bash lib/smalltalk/conformance.sh`. Both files are committed; the runner overwrites them on each run.\n'
|
||||
} > "$OUT_MD"
|
||||
|
||||
echo "Scoreboard updated:"
|
||||
echo " $OUT_JSON"
|
||||
echo " $OUT_MD"
|
||||
echo "Programs: $NUM_PROGRAMS Corpus tests: $PROG_PASS All: $ALL_PASS/$ALL_TOTAL"
|
||||
|
||||
exit $RC
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,948 +0,0 @@
|
||||
;; Smalltalk parser — produces an AST from the tokenizer's token stream.
|
||||
;;
|
||||
;; AST node shapes (dicts):
|
||||
;; {:type "lit-int" :value N} integer
|
||||
;; {:type "lit-float" :value F} float
|
||||
;; {:type "lit-string" :value S} string
|
||||
;; {:type "lit-char" :value C} character
|
||||
;; {:type "lit-symbol" :value S} symbol literal (#foo)
|
||||
;; {:type "lit-array" :elements (list ...)} literal array (#(1 2 #foo))
|
||||
;; {:type "lit-byte-array" :elements (...)} byte array (#[1 2 3])
|
||||
;; {:type "lit-nil" } / "lit-true" / "lit-false"
|
||||
;; {:type "ident" :name "x"} variable reference
|
||||
;; {:type "self"} / "super" / "thisContext" pseudo-variables
|
||||
;; {:type "assign" :name "x" :expr E} x := E
|
||||
;; {:type "return" :expr E} ^ E
|
||||
;; {:type "send" :receiver R :selector S :args (list ...)}
|
||||
;; {:type "cascade" :receiver R :messages (list {:selector :args} ...)}
|
||||
;; {:type "block" :params (list "a") :temps (list "t") :body (list expr)}
|
||||
;; {:type "seq" :exprs (list ...)} statement sequence
|
||||
;; {:type "method" :selector S :params (list ...) :temps (list ...) :body (list ...) :pragmas (list ...)}
|
||||
;;
|
||||
;; A "chunk" / class-definition stream is parsed at a higher level (deferred).
|
||||
|
||||
;; ── Chunk-stream reader ────────────────────────────────────────────────
|
||||
;; Pharo chunk format: chunks are separated by `!`. A doubled `!!` inside a
|
||||
;; chunk represents a single literal `!`. Returns list of chunk strings with
|
||||
;; surrounding whitespace trimmed.
|
||||
(define
|
||||
st-read-chunks
|
||||
(fn
|
||||
(src)
|
||||
(let
|
||||
((chunks (list))
|
||||
(buf (list))
|
||||
(pos 0)
|
||||
(n (len src)))
|
||||
(begin
|
||||
(define
|
||||
flush!
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((s (st-trim (join "" buf))))
|
||||
(begin (append! chunks s) (set! buf (list))))))
|
||||
(define
|
||||
rc-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(< pos n)
|
||||
(let
|
||||
((c (nth src pos)))
|
||||
(cond
|
||||
((= c "!")
|
||||
(cond
|
||||
((and (< (+ pos 1) n) (= (nth src (+ pos 1)) "!"))
|
||||
(begin (append! buf "!") (set! pos (+ pos 2)) (rc-loop)))
|
||||
(else
|
||||
(begin (flush!) (set! pos (+ pos 1)) (rc-loop)))))
|
||||
(else
|
||||
(begin (append! buf c) (set! pos (+ pos 1)) (rc-loop))))))))
|
||||
(rc-loop)
|
||||
;; trailing text without a closing `!` — preserve as a chunk
|
||||
(when (> (len buf) 0) (flush!))
|
||||
chunks))))
|
||||
|
||||
(define
|
||||
st-trim
|
||||
(fn
|
||||
(s)
|
||||
(let
|
||||
((n (len s)) (i 0) (j 0))
|
||||
(begin
|
||||
(set! j n)
|
||||
(define
|
||||
tl-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< i n) (st-trim-ws? (nth s i)))
|
||||
(begin (set! i (+ i 1)) (tl-loop)))))
|
||||
(tl-loop)
|
||||
(define
|
||||
tr-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (> j i) (st-trim-ws? (nth s (- j 1))))
|
||||
(begin (set! j (- j 1)) (tr-loop)))))
|
||||
(tr-loop)
|
||||
(slice s i j)))))
|
||||
|
||||
(define
|
||||
st-trim-ws?
|
||||
(fn (c) (or (= c " ") (= c "\t") (= c "\n") (= c "\r"))))
|
||||
|
||||
;; Parse a chunk stream. Walks chunks and applies the Pharo file-in
|
||||
;; convention: a chunk that evaluates to "X methodsFor: 'cat'" or
|
||||
;; "X class methodsFor: 'cat'" enters a methods batch — subsequent chunks
|
||||
;; are method source until an empty chunk closes the batch.
|
||||
;;
|
||||
;; Returns list of entries:
|
||||
;; {:kind "expr" :ast EXPR-AST}
|
||||
;; {:kind "method" :class CLS :class-side? BOOL :category CAT :ast METHOD-AST}
|
||||
;; {:kind "blank"} (empty chunks outside a methods batch)
|
||||
;; {:kind "end-methods"} (empty chunk closing a methods batch)
|
||||
(define
|
||||
st-parse-chunks
|
||||
(fn
|
||||
(src)
|
||||
(let
|
||||
((chunks (st-read-chunks src))
|
||||
(entries (list))
|
||||
(mode "do-it")
|
||||
(cls-name nil)
|
||||
(class-side? false)
|
||||
(category nil))
|
||||
(begin
|
||||
(for-each
|
||||
(fn
|
||||
(chunk)
|
||||
(cond
|
||||
((= chunk "")
|
||||
(cond
|
||||
((= mode "methods")
|
||||
(begin
|
||||
(append! entries {:kind "end-methods"})
|
||||
(set! mode "do-it")
|
||||
(set! cls-name nil)
|
||||
(set! class-side? false)
|
||||
(set! category nil)))
|
||||
(else (append! entries {:kind "blank"}))))
|
||||
((= mode "methods")
|
||||
(append!
|
||||
entries
|
||||
{:kind "method"
|
||||
:class cls-name
|
||||
:class-side? class-side?
|
||||
:category category
|
||||
:ast (st-parse-method chunk)}))
|
||||
(else
|
||||
(let
|
||||
((ast (st-parse-expr chunk)))
|
||||
(begin
|
||||
(append! entries {:kind "expr" :ast ast})
|
||||
(let
|
||||
((mf (st-detect-methods-for ast)))
|
||||
(when
|
||||
(not (= mf nil))
|
||||
(begin
|
||||
(set! mode "methods")
|
||||
(set! cls-name (get mf :class))
|
||||
(set! class-side? (get mf :class-side?))
|
||||
(set! category (get mf :category))))))))))
|
||||
chunks)
|
||||
entries))))
|
||||
|
||||
;; Recognise `Foo methodsFor: 'cat'` (and related) as starting a methods batch.
|
||||
;; Returns nil if the AST doesn't look like one of these forms.
|
||||
(define
|
||||
st-detect-methods-for
|
||||
(fn
|
||||
(ast)
|
||||
(cond
|
||||
((not (= (get ast :type) "send")) nil)
|
||||
((not (st-is-methods-for-selector? (get ast :selector))) nil)
|
||||
(else
|
||||
(let
|
||||
((recv (get ast :receiver)) (args (get ast :args)))
|
||||
(let
|
||||
((cat-arg (if (> (len args) 0) (nth args 0) nil)))
|
||||
(let
|
||||
((category
|
||||
(cond
|
||||
((= cat-arg nil) nil)
|
||||
((= (get cat-arg :type) "lit-string") (get cat-arg :value))
|
||||
((= (get cat-arg :type) "lit-symbol") (get cat-arg :value))
|
||||
(else nil))))
|
||||
(cond
|
||||
((= (get recv :type) "ident")
|
||||
{:class (get recv :name)
|
||||
:class-side? false
|
||||
:category category})
|
||||
;; `Foo class methodsFor: 'cat'` — recv is a unary send `Foo class`
|
||||
((and
|
||||
(= (get recv :type) "send")
|
||||
(= (get recv :selector) "class")
|
||||
(= (get (get recv :receiver) :type) "ident"))
|
||||
{:class (get (get recv :receiver) :name)
|
||||
:class-side? true
|
||||
:category category})
|
||||
(else nil)))))))))
|
||||
|
||||
(define
|
||||
st-is-methods-for-selector?
|
||||
(fn
|
||||
(sel)
|
||||
(or
|
||||
(= sel "methodsFor:")
|
||||
(= sel "methodsFor:stamp:")
|
||||
(= sel "category:"))))
|
||||
|
||||
(define st-tok-type (fn (t) (if (= t nil) "eof" (get t :type))))
|
||||
|
||||
(define st-tok-value (fn (t) (if (= t nil) nil (get t :value))))
|
||||
|
||||
;; Parse a *single* Smalltalk expression from source.
|
||||
(define st-parse-expr (fn (src) (st-parse-with src "expr")))
|
||||
|
||||
;; Parse a sequence of statements separated by '.' Returns a {:type "seq"} node.
|
||||
(define st-parse (fn (src) (st-parse-with src "seq")))
|
||||
|
||||
;; Parse a method body — `selector params | temps | body`.
|
||||
;; Only the "method header + body" form (no chunk delimiters).
|
||||
(define st-parse-method (fn (src) (st-parse-with src "method")))
|
||||
|
||||
(define
|
||||
st-parse-with
|
||||
(fn
|
||||
(src mode)
|
||||
(let
|
||||
((tokens (st-tokenize src)) (idx 0) (tok-len 0))
|
||||
(begin
|
||||
(set! tok-len (len tokens))
|
||||
(define peek-tok (fn () (nth tokens idx)))
|
||||
(define
|
||||
peek-tok-at
|
||||
(fn (n) (if (< (+ idx n) tok-len) (nth tokens (+ idx n)) nil)))
|
||||
(define advance-tok! (fn () (set! idx (+ idx 1))))
|
||||
(define
|
||||
at?
|
||||
(fn
|
||||
(type value)
|
||||
(let
|
||||
((t (peek-tok)))
|
||||
(and
|
||||
(= (st-tok-type t) type)
|
||||
(or (= value nil) (= (st-tok-value t) value))))))
|
||||
(define at-type? (fn (type) (= (st-tok-type (peek-tok)) type)))
|
||||
(define
|
||||
consume!
|
||||
(fn
|
||||
(type value)
|
||||
(if
|
||||
(at? type value)
|
||||
(let ((t (peek-tok))) (begin (advance-tok!) t))
|
||||
(error
|
||||
(str
|
||||
"st-parse: expected "
|
||||
type
|
||||
(if (= value nil) "" (str " '" value "'"))
|
||||
" got "
|
||||
(st-tok-type (peek-tok))
|
||||
" '"
|
||||
(st-tok-value (peek-tok))
|
||||
"' at idx "
|
||||
idx)))))
|
||||
|
||||
;; ── Primary: atoms, paren'd expr, blocks, literal arrays, byte arrays.
|
||||
(define
|
||||
parse-primary
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((t (peek-tok)))
|
||||
(let
|
||||
((ty (st-tok-type t)) (v (st-tok-value t)))
|
||||
(cond
|
||||
((= ty "number")
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(cond
|
||||
((number? v) {:type (if (integer? v) "lit-int" "lit-float") :value v})
|
||||
(else {:type "lit-int" :value v}))))
|
||||
((= ty "string")
|
||||
(begin (advance-tok!) {:type "lit-string" :value v}))
|
||||
((= ty "char")
|
||||
(begin (advance-tok!) {:type "lit-char" :value v}))
|
||||
((= ty "symbol")
|
||||
(begin (advance-tok!) {:type "lit-symbol" :value v}))
|
||||
((= ty "array-open") (parse-literal-array))
|
||||
((= ty "byte-array-open") (parse-byte-array))
|
||||
((= ty "lparen")
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(let
|
||||
((e (parse-expression)))
|
||||
(begin (consume! "rparen" nil) e))))
|
||||
((= ty "lbracket") (parse-block))
|
||||
((= ty "lbrace") (parse-dynamic-array))
|
||||
((= ty "ident")
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(cond
|
||||
((= v "nil") {:type "lit-nil"})
|
||||
((= v "true") {:type "lit-true"})
|
||||
((= v "false") {:type "lit-false"})
|
||||
((= v "self") {:type "self"})
|
||||
((= v "super") {:type "super"})
|
||||
((= v "thisContext") {:type "thisContext"})
|
||||
(else {:type "ident" :name v}))))
|
||||
((= ty "binary")
|
||||
;; Negative numeric literal: '-' immediately before a number.
|
||||
(cond
|
||||
((and (= v "-") (= (st-tok-type (peek-tok-at 1)) "number"))
|
||||
(let
|
||||
((n (st-tok-value (peek-tok-at 1))))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(advance-tok!)
|
||||
(cond
|
||||
((dict? n) {:type "lit-int" :value n})
|
||||
((integer? n) {:type "lit-int" :value (- 0 n)})
|
||||
(else {:type "lit-float" :value (- 0 n)})))))
|
||||
(else
|
||||
(error
|
||||
(str "st-parse: unexpected binary '" v "' at idx " idx)))))
|
||||
(else
|
||||
(error
|
||||
(str
|
||||
"st-parse: unexpected "
|
||||
ty
|
||||
" '"
|
||||
v
|
||||
"' at idx "
|
||||
idx))))))))
|
||||
|
||||
;; #(elem elem ...) — elements are atoms or nested parenthesised arrays.
|
||||
(define
|
||||
parse-literal-array
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((items (list)))
|
||||
(begin
|
||||
(consume! "array-open" nil)
|
||||
(define
|
||||
arr-loop
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((at? "rparen" nil) (advance-tok!))
|
||||
(else
|
||||
(begin
|
||||
(append! items (parse-array-element))
|
||||
(arr-loop))))))
|
||||
(arr-loop)
|
||||
{:type "lit-array" :elements items}))))
|
||||
|
||||
;; { expr. expr. expr } — Pharo dynamic array literal. Each element
|
||||
;; is a *full expression* evaluated at runtime; the result is a
|
||||
;; fresh mutable array. Empty `{}` is a 0-length array.
|
||||
(define
|
||||
parse-dynamic-array
|
||||
(fn
|
||||
()
|
||||
(let ((items (list)))
|
||||
(begin
|
||||
(consume! "lbrace" nil)
|
||||
(define
|
||||
da-loop
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((at? "rbrace" nil) (advance-tok!))
|
||||
(else
|
||||
(begin
|
||||
(append! items (parse-expression))
|
||||
(define
|
||||
dot-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at? "period" nil)
|
||||
(begin (advance-tok!) (dot-loop)))))
|
||||
(dot-loop)
|
||||
(da-loop))))))
|
||||
(da-loop)
|
||||
{:type "dynamic-array" :elements items}))))
|
||||
|
||||
;; #[1 2 3]
|
||||
(define
|
||||
parse-byte-array
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((items (list)))
|
||||
(begin
|
||||
(consume! "byte-array-open" nil)
|
||||
(define
|
||||
ba-loop
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((at? "rbracket" nil) (advance-tok!))
|
||||
(else
|
||||
(let
|
||||
((t (peek-tok)))
|
||||
(cond
|
||||
((= (st-tok-type t) "number")
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! items (st-tok-value t))
|
||||
(ba-loop)))
|
||||
(else
|
||||
(error
|
||||
(str
|
||||
"st-parse: byte array expects number, got "
|
||||
(st-tok-type t))))))))))
|
||||
(ba-loop)
|
||||
{:type "lit-byte-array" :elements items}))))
|
||||
|
||||
;; Inside a literal array: bare idents become symbols, nested (...) is a sub-array.
|
||||
(define
|
||||
parse-array-element
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((t (peek-tok)))
|
||||
(let
|
||||
((ty (st-tok-type t)) (v (st-tok-value t)))
|
||||
(cond
|
||||
((= ty "number") (begin (advance-tok!) {:type "lit-int" :value v}))
|
||||
((= ty "string") (begin (advance-tok!) {:type "lit-string" :value v}))
|
||||
((= ty "char") (begin (advance-tok!) {:type "lit-char" :value v}))
|
||||
((= ty "symbol") (begin (advance-tok!) {:type "lit-symbol" :value v}))
|
||||
((= ty "ident")
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(cond
|
||||
((= v "nil") {:type "lit-nil"})
|
||||
((= v "true") {:type "lit-true"})
|
||||
((= v "false") {:type "lit-false"})
|
||||
(else {:type "lit-symbol" :value v}))))
|
||||
((= ty "keyword") (begin (advance-tok!) {:type "lit-symbol" :value v}))
|
||||
((= ty "binary") (begin (advance-tok!) {:type "lit-symbol" :value v}))
|
||||
((= ty "lparen")
|
||||
(let ((items (list)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(define
|
||||
sub-loop
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((at? "rparen" nil) (advance-tok!))
|
||||
(else
|
||||
(begin (append! items (parse-array-element)) (sub-loop))))))
|
||||
(sub-loop)
|
||||
{:type "lit-array" :elements items})))
|
||||
((= ty "array-open") (parse-literal-array))
|
||||
((= ty "byte-array-open") (parse-byte-array))
|
||||
(else
|
||||
(error
|
||||
(str "st-parse: bad literal-array element " ty " '" v "'"))))))))
|
||||
|
||||
;; [:a :b | | t1 t2 | body. body. ...]
|
||||
(define
|
||||
parse-block
|
||||
(fn
|
||||
()
|
||||
(begin
|
||||
(consume! "lbracket" nil)
|
||||
(let
|
||||
((params (list)) (temps (list)))
|
||||
(begin
|
||||
;; Block params
|
||||
(define
|
||||
p-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at? "colon" nil)
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(let
|
||||
((t (consume! "ident" nil)))
|
||||
(begin
|
||||
(append! params (st-tok-value t))
|
||||
(p-loop)))))))
|
||||
(p-loop)
|
||||
(when (> (len params) 0) (consume! "bar" nil))
|
||||
;; Block temps: | t1 t2 |
|
||||
(when
|
||||
(and
|
||||
(at? "bar" nil)
|
||||
;; Not `|` followed immediately by binary content — the only
|
||||
;; legitimate `|` inside a block here is the temp delimiter.
|
||||
true)
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(define
|
||||
t-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at? "ident" nil)
|
||||
(let
|
||||
((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! temps (st-tok-value t))
|
||||
(t-loop))))))
|
||||
(t-loop)
|
||||
(consume! "bar" nil)))
|
||||
;; Body: statements terminated by `.` or `]`
|
||||
(let
|
||||
((body (parse-statements "rbracket")))
|
||||
(begin
|
||||
(consume! "rbracket" nil)
|
||||
{:type "block" :params params :temps temps :body body})))))))
|
||||
|
||||
;; Parse statements up to a closing token (rbracket or eof). Returns list.
|
||||
(define
|
||||
parse-statements
|
||||
(fn
|
||||
(terminator)
|
||||
(let
|
||||
((stmts (list)))
|
||||
(begin
|
||||
(define
|
||||
s-loop
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((at-type? terminator) nil)
|
||||
((at-type? "eof") nil)
|
||||
(else
|
||||
(begin
|
||||
(append! stmts (parse-statement))
|
||||
;; consume optional period(s)
|
||||
(define
|
||||
dot-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at? "period" nil)
|
||||
(begin (advance-tok!) (dot-loop)))))
|
||||
(dot-loop)
|
||||
(s-loop))))))
|
||||
(s-loop)
|
||||
stmts))))
|
||||
|
||||
;; Statement: ^expr | ident := expr | expr
|
||||
(define
|
||||
parse-statement
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((at? "caret" nil)
|
||||
(begin
|
||||
(advance-tok!)
|
||||
{:type "return" :expr (parse-expression)}))
|
||||
((and (at-type? "ident") (= (st-tok-type (peek-tok-at 1)) "assign"))
|
||||
(let
|
||||
((name-tok (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(advance-tok!)
|
||||
{:type "assign"
|
||||
:name (st-tok-value name-tok)
|
||||
:expr (parse-expression)})))
|
||||
(else (parse-expression)))))
|
||||
|
||||
;; Top-level expression. Assignment (right-associative chain) sits at
|
||||
;; the top; cascade is below.
|
||||
(define
|
||||
parse-expression
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((and (at-type? "ident") (= (st-tok-type (peek-tok-at 1)) "assign"))
|
||||
(let
|
||||
((name-tok (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(advance-tok!)
|
||||
{:type "assign"
|
||||
:name (st-tok-value name-tok)
|
||||
:expr (parse-expression)})))
|
||||
(else (parse-cascade)))))
|
||||
|
||||
(define
|
||||
parse-cascade
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((head (parse-keyword-message)))
|
||||
(cond
|
||||
((at? "semi" nil)
|
||||
(let
|
||||
((receiver (cascade-receiver head))
|
||||
(first-msg (cascade-first-message head))
|
||||
(msgs (list)))
|
||||
(begin
|
||||
(append! msgs first-msg)
|
||||
(define
|
||||
c-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at? "semi" nil)
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! msgs (parse-cascade-message))
|
||||
(c-loop)))))
|
||||
(c-loop)
|
||||
{:type "cascade" :receiver receiver :messages msgs})))
|
||||
(else head)))))
|
||||
|
||||
;; Extract the receiver from a head send so cascades share it.
|
||||
(define
|
||||
cascade-receiver
|
||||
(fn
|
||||
(head)
|
||||
(cond
|
||||
((= (get head :type) "send") (get head :receiver))
|
||||
(else head))))
|
||||
|
||||
(define
|
||||
cascade-first-message
|
||||
(fn
|
||||
(head)
|
||||
(cond
|
||||
((= (get head :type) "send")
|
||||
{:selector (get head :selector) :args (get head :args)})
|
||||
(else
|
||||
;; Shouldn't happen — cascade requires at least one prior message.
|
||||
(error "st-parse: cascade with no prior message")))))
|
||||
|
||||
;; Subsequent cascade message (after the `;`): unary | binary | keyword
|
||||
(define
|
||||
parse-cascade-message
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((at-type? "ident")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
{:selector (st-tok-value t) :args (list)})))
|
||||
((at-type? "binary")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(let
|
||||
((arg (parse-unary-message)))
|
||||
{:selector (st-tok-value t) :args (list arg)}))))
|
||||
((at-type? "keyword")
|
||||
(let
|
||||
((sel-parts (list)) (args (list)))
|
||||
(begin
|
||||
(define
|
||||
kw-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at-type? "keyword")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! sel-parts (st-tok-value t))
|
||||
(append! args (parse-binary-message))
|
||||
(kw-loop))))))
|
||||
(kw-loop)
|
||||
{:selector (join "" sel-parts) :args args})))
|
||||
(else
|
||||
(error
|
||||
(str "st-parse: bad cascade message at idx " idx))))))
|
||||
|
||||
;; Keyword message: <binary> (kw <binary>)+
|
||||
(define
|
||||
parse-keyword-message
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((receiver (parse-binary-message)))
|
||||
(cond
|
||||
((at-type? "keyword")
|
||||
(let
|
||||
((sel-parts (list)) (args (list)))
|
||||
(begin
|
||||
(define
|
||||
kw-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at-type? "keyword")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! sel-parts (st-tok-value t))
|
||||
(append! args (parse-binary-message))
|
||||
(kw-loop))))))
|
||||
(kw-loop)
|
||||
{:type "send"
|
||||
:receiver receiver
|
||||
:selector (join "" sel-parts)
|
||||
:args args})))
|
||||
(else receiver)))))
|
||||
|
||||
;; Binary message: <unary> (binop <unary>)*
|
||||
;; A bare `|` is also a legitimate binary selector (logical or in
|
||||
;; some Smalltalks); the tokenizer emits it as the `bar` type so
|
||||
;; that block-param / temp-decl delimiters are easy to spot.
|
||||
;; In expression position, accept it as a binary operator.
|
||||
(define
|
||||
parse-binary-message
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((receiver (parse-unary-message)))
|
||||
(begin
|
||||
(define
|
||||
b-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(or (at-type? "binary") (at-type? "bar"))
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(let
|
||||
((arg (parse-unary-message)))
|
||||
(set!
|
||||
receiver
|
||||
{:type "send"
|
||||
:receiver receiver
|
||||
:selector (st-tok-value t)
|
||||
:args (list arg)}))
|
||||
(b-loop))))))
|
||||
(b-loop)
|
||||
receiver))))
|
||||
|
||||
;; Unary message: <primary> ident* (ident NOT followed by ':')
|
||||
(define
|
||||
parse-unary-message
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((receiver (parse-primary)))
|
||||
(begin
|
||||
(define
|
||||
u-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and
|
||||
(at-type? "ident")
|
||||
(let
|
||||
((nxt (peek-tok-at 1)))
|
||||
(not (= (st-tok-type nxt) "assign"))))
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(set!
|
||||
receiver
|
||||
{:type "send"
|
||||
:receiver receiver
|
||||
:selector (st-tok-value t)
|
||||
:args (list)})
|
||||
(u-loop))))))
|
||||
(u-loop)
|
||||
receiver))))
|
||||
|
||||
;; Parse a single pragma: `<keyword: literal (keyword: literal)* >`
|
||||
;; Returns {:selector "primitive:" :args (list literal-asts)}.
|
||||
(define
|
||||
parse-pragma
|
||||
(fn
|
||||
()
|
||||
(begin
|
||||
(consume! "binary" "<")
|
||||
(let
|
||||
((sel-parts (list)) (args (list)))
|
||||
(begin
|
||||
(define
|
||||
pr-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at-type? "keyword")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! sel-parts (st-tok-value t))
|
||||
(append! args (parse-pragma-arg))
|
||||
(pr-loop))))))
|
||||
(pr-loop)
|
||||
(consume! "binary" ">")
|
||||
{:selector (join "" sel-parts) :args args})))))
|
||||
|
||||
;; Pragma arguments are literals only.
|
||||
(define
|
||||
parse-pragma-arg
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((t (peek-tok)))
|
||||
(let
|
||||
((ty (st-tok-type t)) (v (st-tok-value t)))
|
||||
(cond
|
||||
((= ty "number")
|
||||
(begin
|
||||
(advance-tok!)
|
||||
{:type (if (integer? v) "lit-int" "lit-float") :value v}))
|
||||
((= ty "string") (begin (advance-tok!) {:type "lit-string" :value v}))
|
||||
((= ty "char") (begin (advance-tok!) {:type "lit-char" :value v}))
|
||||
((= ty "symbol") (begin (advance-tok!) {:type "lit-symbol" :value v}))
|
||||
((= ty "ident")
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(cond
|
||||
((= v "nil") {:type "lit-nil"})
|
||||
((= v "true") {:type "lit-true"})
|
||||
((= v "false") {:type "lit-false"})
|
||||
(else (error (str "st-parse: pragma arg must be literal, got ident " v))))))
|
||||
((and (= ty "binary") (= v "-")
|
||||
(= (st-tok-type (peek-tok-at 1)) "number"))
|
||||
(let ((n (st-tok-value (peek-tok-at 1))))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(advance-tok!)
|
||||
{:type (if (integer? n) "lit-int" "lit-float")
|
||||
:value (- 0 n)})))
|
||||
(else
|
||||
(error
|
||||
(str "st-parse: pragma arg must be literal, got " ty))))))))
|
||||
|
||||
;; Method header: unary | binary arg | (kw arg)+
|
||||
(define
|
||||
parse-method
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((sel "")
|
||||
(params (list))
|
||||
(temps (list))
|
||||
(pragmas (list))
|
||||
(body (list)))
|
||||
(begin
|
||||
(cond
|
||||
;; Unary header
|
||||
((at-type? "ident")
|
||||
(let ((t (peek-tok)))
|
||||
(begin (advance-tok!) (set! sel (st-tok-value t)))))
|
||||
;; Binary header: binop ident
|
||||
((at-type? "binary")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(set! sel (st-tok-value t))
|
||||
(let ((p (consume! "ident" nil)))
|
||||
(append! params (st-tok-value p))))))
|
||||
;; Keyword header: (kw ident)+
|
||||
((at-type? "keyword")
|
||||
(let ((sel-parts (list)))
|
||||
(begin
|
||||
(define
|
||||
kh-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at-type? "keyword")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! sel-parts (st-tok-value t))
|
||||
(let ((p (consume! "ident" nil)))
|
||||
(append! params (st-tok-value p)))
|
||||
(kh-loop))))))
|
||||
(kh-loop)
|
||||
(set! sel (join "" sel-parts)))))
|
||||
(else
|
||||
(error
|
||||
(str
|
||||
"st-parse-method: expected selector header, got "
|
||||
(st-tok-type (peek-tok))))))
|
||||
;; Pragmas and temps may appear in either order. Allow many
|
||||
;; pragmas; one temps section.
|
||||
(define
|
||||
parse-temps!
|
||||
(fn
|
||||
()
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(define
|
||||
th-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at-type? "ident")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! temps (st-tok-value t))
|
||||
(th-loop))))))
|
||||
(th-loop)
|
||||
(consume! "bar" nil))))
|
||||
(define
|
||||
pt-loop
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((and
|
||||
(at? "binary" "<")
|
||||
(= (st-tok-type (peek-tok-at 1)) "keyword"))
|
||||
(begin (append! pragmas (parse-pragma)) (pt-loop)))
|
||||
((and (at? "bar" nil) (= (len temps) 0))
|
||||
(begin (parse-temps!) (pt-loop)))
|
||||
(else nil))))
|
||||
(pt-loop)
|
||||
;; Body statements
|
||||
(set! body (parse-statements "eof"))
|
||||
{:type "method"
|
||||
:selector sel
|
||||
:params params
|
||||
:temps temps
|
||||
:pragmas pragmas
|
||||
:body body}))))
|
||||
|
||||
;; Top-level program: optional temp declaration, then statements
|
||||
;; separated by '.'. Pharo workspace-style scripts allow
|
||||
;; `| temps | body...` at the top level.
|
||||
(cond
|
||||
((= mode "expr") (parse-expression))
|
||||
((= mode "method") (parse-method))
|
||||
(else
|
||||
(let ((temps (list)))
|
||||
(begin
|
||||
(when
|
||||
(at? "bar" nil)
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(define
|
||||
tt-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(at-type? "ident")
|
||||
(let ((t (peek-tok)))
|
||||
(begin
|
||||
(advance-tok!)
|
||||
(append! temps (st-tok-value t))
|
||||
(tt-loop))))))
|
||||
(tt-loop)
|
||||
(consume! "bar" nil)))
|
||||
{:type "seq" :temps temps :exprs (parse-statements "eof")}))))))))
|
||||
@@ -1,787 +0,0 @@
|
||||
;; Smalltalk runtime — class table, bootstrap hierarchy, type→class mapping,
|
||||
;; instance construction. Method dispatch / eval-ast live in a later layer.
|
||||
;;
|
||||
;; Class record shape:
|
||||
;; {:name "Foo"
|
||||
;; :superclass "Object" ; or nil for Object itself
|
||||
;; :ivars (list "x" "y") ; instance variable names declared on this class
|
||||
;; :methods (dict selector→method-record)
|
||||
;; :class-methods (dict selector→method-record)}
|
||||
;;
|
||||
;; A method record is the AST returned by st-parse-method, plus a :defining-class
|
||||
;; field so super-sends can resolve from the right place. (Methods are registered
|
||||
;; via runtime helpers that fill the field.)
|
||||
;;
|
||||
;; The class table is a single dict keyed by class name. Bootstrap installs the
|
||||
;; canonical hierarchy. Test code resets it via (st-bootstrap-classes!).
|
||||
|
||||
(define st-class-table {})
|
||||
|
||||
;; ── Method-lookup cache ────────────────────────────────────────────────
|
||||
;; Cache keys are "class|selector|side"; side is "i" (instance) or "c" (class).
|
||||
;; Misses are stored as the sentinel :not-found so we don't re-walk for
|
||||
;; every doesNotUnderstand call.
|
||||
(define st-method-cache {})
|
||||
(define st-method-cache-hits 0)
|
||||
(define st-method-cache-misses 0)
|
||||
|
||||
(define
|
||||
st-method-cache-clear!
|
||||
(fn () (set! st-method-cache {})))
|
||||
|
||||
;; Inline-cache generation. Eval-time IC slots check this; bumping it
|
||||
;; invalidates every cached call-site method record across the program.
|
||||
(define st-ic-generation 0)
|
||||
|
||||
(define
|
||||
st-ic-bump-generation!
|
||||
(fn () (set! st-ic-generation (+ st-ic-generation 1))))
|
||||
|
||||
(define
|
||||
st-method-cache-key
|
||||
(fn (cls sel class-side?) (str cls "|" sel "|" (if class-side? "c" "i"))))
|
||||
|
||||
(define
|
||||
st-method-cache-stats
|
||||
(fn
|
||||
()
|
||||
{:hits st-method-cache-hits
|
||||
:misses st-method-cache-misses
|
||||
:size (len (keys st-method-cache))}))
|
||||
|
||||
(define
|
||||
st-method-cache-reset-stats!
|
||||
(fn ()
|
||||
(begin
|
||||
(set! st-method-cache-hits 0)
|
||||
(set! st-method-cache-misses 0))))
|
||||
|
||||
(define
|
||||
st-class-table-clear!
|
||||
(fn ()
|
||||
(begin
|
||||
(set! st-class-table {})
|
||||
(st-method-cache-clear!))))
|
||||
|
||||
(define
|
||||
st-class-define!
|
||||
(fn
|
||||
(name superclass ivars)
|
||||
(begin
|
||||
(set!
|
||||
st-class-table
|
||||
(assoc
|
||||
st-class-table
|
||||
name
|
||||
{:name name
|
||||
:superclass superclass
|
||||
:ivars ivars
|
||||
:methods {}
|
||||
:class-methods {}}))
|
||||
;; A redefined class can invalidate any cache entries that walked
|
||||
;; through its old position in the chain. Cheap + correct: drop all.
|
||||
(st-method-cache-clear!)
|
||||
name)))
|
||||
|
||||
(define
|
||||
st-class-get
|
||||
(fn (name) (if (has-key? st-class-table name) (get st-class-table name) nil)))
|
||||
|
||||
(define
|
||||
st-class-exists?
|
||||
(fn (name) (has-key? st-class-table name)))
|
||||
|
||||
(define
|
||||
st-class-superclass
|
||||
(fn
|
||||
(name)
|
||||
(let
|
||||
((c (st-class-get name)))
|
||||
(cond ((= c nil) nil) (else (get c :superclass))))))
|
||||
|
||||
;; Walk class chain root-to-leaf? No, follow superclass chain leaf-to-root.
|
||||
;; Returns list of class names starting at `name` and ending with the root.
|
||||
(define
|
||||
st-class-chain
|
||||
(fn
|
||||
(name)
|
||||
(let ((acc (list)) (cur name))
|
||||
(begin
|
||||
(define
|
||||
ch-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (not (= cur nil)) (st-class-exists? cur))
|
||||
(begin
|
||||
(append! acc cur)
|
||||
(set! cur (st-class-superclass cur))
|
||||
(ch-loop)))))
|
||||
(ch-loop)
|
||||
acc))))
|
||||
|
||||
;; Inherited + own ivars in declaration order from root to leaf.
|
||||
(define
|
||||
st-class-all-ivars
|
||||
(fn
|
||||
(name)
|
||||
(let ((chain (reverse (st-class-chain name))) (out (list)))
|
||||
(begin
|
||||
(for-each
|
||||
(fn
|
||||
(cn)
|
||||
(let
|
||||
((c (st-class-get cn)))
|
||||
(when
|
||||
(not (= c nil))
|
||||
(for-each (fn (iv) (append! out iv)) (get c :ivars)))))
|
||||
chain)
|
||||
out))))
|
||||
|
||||
;; Method install. The defining-class field is stamped on the method record
|
||||
;; so super-sends look up from the right point in the chain.
|
||||
(define
|
||||
st-class-add-method!
|
||||
(fn
|
||||
(cls-name selector method-ast)
|
||||
(let
|
||||
((cls (st-class-get cls-name)))
|
||||
(cond
|
||||
((= cls nil) (error (str "st-class-add-method!: unknown class " cls-name)))
|
||||
(else
|
||||
(let
|
||||
((m (assoc method-ast :defining-class cls-name)))
|
||||
(begin
|
||||
(set!
|
||||
st-class-table
|
||||
(assoc
|
||||
st-class-table
|
||||
cls-name
|
||||
(assoc
|
||||
cls
|
||||
:methods
|
||||
(assoc (get cls :methods) selector m))))
|
||||
(st-method-cache-clear!)
|
||||
(st-ic-bump-generation!)
|
||||
selector)))))))
|
||||
|
||||
(define
|
||||
st-class-add-class-method!
|
||||
(fn
|
||||
(cls-name selector method-ast)
|
||||
(let
|
||||
((cls (st-class-get cls-name)))
|
||||
(cond
|
||||
((= cls nil) (error (str "st-class-add-class-method!: unknown class " cls-name)))
|
||||
(else
|
||||
(let
|
||||
((m (assoc method-ast :defining-class cls-name)))
|
||||
(begin
|
||||
(set!
|
||||
st-class-table
|
||||
(assoc
|
||||
st-class-table
|
||||
cls-name
|
||||
(assoc
|
||||
cls
|
||||
:class-methods
|
||||
(assoc (get cls :class-methods) selector m))))
|
||||
(st-method-cache-clear!)
|
||||
(st-ic-bump-generation!)
|
||||
selector)))))))
|
||||
|
||||
;; Remove a method from a class (instance side). Mostly for tests; runtime
|
||||
;; reflection in Phase 4 will use the same primitive.
|
||||
(define
|
||||
st-class-remove-method!
|
||||
(fn
|
||||
(cls-name selector)
|
||||
(let ((cls (st-class-get cls-name)))
|
||||
(cond
|
||||
((= cls nil) (error (str "st-class-remove-method!: unknown class " cls-name)))
|
||||
(else
|
||||
(let ((md (get cls :methods)))
|
||||
(cond
|
||||
((not (has-key? md selector)) false)
|
||||
(else
|
||||
(let ((new-md {}))
|
||||
(begin
|
||||
(for-each
|
||||
(fn (k)
|
||||
(when (not (= k selector))
|
||||
(dict-set! new-md k (get md k))))
|
||||
(keys md))
|
||||
(set!
|
||||
st-class-table
|
||||
(assoc
|
||||
st-class-table
|
||||
cls-name
|
||||
(assoc cls :methods new-md)))
|
||||
(st-method-cache-clear!)
|
||||
(st-ic-bump-generation!)
|
||||
true))))))))))
|
||||
|
||||
;; Walk-only lookup. Returns the method record (with :defining-class) or nil.
|
||||
;; class-side? = true searches :class-methods, false searches :methods.
|
||||
(define
|
||||
st-method-lookup-walk
|
||||
(fn
|
||||
(cls-name selector class-side?)
|
||||
(let
|
||||
((found nil))
|
||||
(begin
|
||||
(define
|
||||
ml-loop
|
||||
(fn
|
||||
(cur)
|
||||
(when
|
||||
(and (= found nil) (not (= cur nil)) (st-class-exists? cur))
|
||||
(let
|
||||
((c (st-class-get cur)))
|
||||
(let
|
||||
((dict (if class-side? (get c :class-methods) (get c :methods))))
|
||||
(cond
|
||||
((has-key? dict selector) (set! found (get dict selector)))
|
||||
(else (ml-loop (get c :superclass)))))))))
|
||||
(ml-loop cls-name)
|
||||
found))))
|
||||
|
||||
;; Cached lookup. Misses are stored as :not-found so doesNotUnderstand paths
|
||||
;; don't re-walk on every send.
|
||||
(define
|
||||
st-method-lookup
|
||||
(fn
|
||||
(cls-name selector class-side?)
|
||||
(let ((key (st-method-cache-key cls-name selector class-side?)))
|
||||
(cond
|
||||
((has-key? st-method-cache key)
|
||||
(begin
|
||||
(set! st-method-cache-hits (+ st-method-cache-hits 1))
|
||||
(let ((v (get st-method-cache key)))
|
||||
(cond ((= v :not-found) nil) (else v)))))
|
||||
(else
|
||||
(begin
|
||||
(set! st-method-cache-misses (+ st-method-cache-misses 1))
|
||||
(let ((found (st-method-lookup-walk cls-name selector class-side?)))
|
||||
(begin
|
||||
(set!
|
||||
st-method-cache
|
||||
(assoc
|
||||
st-method-cache
|
||||
key
|
||||
(cond ((= found nil) :not-found) (else found))))
|
||||
found))))))))
|
||||
|
||||
;; SX value → Smalltalk class name. Native types are not boxed.
|
||||
(define
|
||||
st-class-of
|
||||
(fn
|
||||
(v)
|
||||
(cond
|
||||
((= v nil) "UndefinedObject")
|
||||
((= v true) "True")
|
||||
((= v false) "False")
|
||||
((integer? v) "SmallInteger")
|
||||
((number? v) "Float")
|
||||
((string? v) "String")
|
||||
((symbol? v) "Symbol")
|
||||
((list? v) "Array")
|
||||
((and (dict? v) (has-key? v :type) (= (get v :type) "st-instance"))
|
||||
(get v :class))
|
||||
((and (dict? v) (has-key? v :type) (= (get v :type) "block"))
|
||||
"BlockClosure")
|
||||
((and (dict? v) (has-key? v :st-block?) (get v :st-block?))
|
||||
"BlockClosure")
|
||||
((dict? v) "Dictionary")
|
||||
((lambda? v) "BlockClosure")
|
||||
(else "Object"))))
|
||||
|
||||
;; Construct a fresh instance of cls-name. Ivars (own + inherited) start as nil.
|
||||
(define
|
||||
st-make-instance
|
||||
(fn
|
||||
(cls-name)
|
||||
(cond
|
||||
((not (st-class-exists? cls-name))
|
||||
(error (str "st-make-instance: unknown class " cls-name)))
|
||||
(else
|
||||
(let
|
||||
((iv-names (st-class-all-ivars cls-name)) (ivars {}))
|
||||
(begin
|
||||
(for-each (fn (n) (set! ivars (assoc ivars n nil))) iv-names)
|
||||
{:type "st-instance" :class cls-name :ivars ivars}))))))
|
||||
|
||||
(define
|
||||
st-instance?
|
||||
(fn
|
||||
(v)
|
||||
(and (dict? v) (has-key? v :type) (= (get v :type) "st-instance"))))
|
||||
|
||||
(define
|
||||
st-iv-get
|
||||
(fn
|
||||
(inst name)
|
||||
(let ((ivs (get inst :ivars)))
|
||||
(if (has-key? ivs name) (get ivs name) nil))))
|
||||
|
||||
(define
|
||||
st-iv-set!
|
||||
(fn
|
||||
(inst name value)
|
||||
(let
|
||||
((new-ivars (assoc (get inst :ivars) name value)))
|
||||
(assoc inst :ivars new-ivars))))
|
||||
|
||||
;; Inherits-from check: is `descendant` either equal to `ancestor` or a subclass?
|
||||
(define
|
||||
st-class-inherits-from?
|
||||
(fn
|
||||
(descendant ancestor)
|
||||
(let ((found false) (cur descendant))
|
||||
(begin
|
||||
(define
|
||||
ih-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (not found) (not (= cur nil)) (st-class-exists? cur))
|
||||
(cond
|
||||
((= cur ancestor) (set! found true))
|
||||
(else
|
||||
(begin
|
||||
(set! cur (st-class-superclass cur))
|
||||
(ih-loop)))))))
|
||||
(ih-loop)
|
||||
found))))
|
||||
|
||||
;; Bootstrap the canonical class hierarchy. Reset and rebuild.
|
||||
(define
|
||||
st-bootstrap-classes!
|
||||
(fn
|
||||
()
|
||||
(begin
|
||||
(st-class-table-clear!)
|
||||
;; Root
|
||||
(st-class-define! "Object" nil (list))
|
||||
;; Class side machinery
|
||||
(st-class-define! "Behavior" "Object" (list "superclass" "methodDict" "format"))
|
||||
(st-class-define! "ClassDescription" "Behavior" (list "instanceVariables" "organization"))
|
||||
(st-class-define! "Class" "ClassDescription" (list "name" "subclasses"))
|
||||
(st-class-define! "Metaclass" "ClassDescription" (list "thisClass"))
|
||||
;; Pseudo-variable types
|
||||
(st-class-define! "UndefinedObject" "Object" (list))
|
||||
(st-class-define! "Boolean" "Object" (list))
|
||||
(st-class-define! "True" "Boolean" (list))
|
||||
(st-class-define! "False" "Boolean" (list))
|
||||
;; Magnitudes
|
||||
(st-class-define! "Magnitude" "Object" (list))
|
||||
(st-class-define! "Number" "Magnitude" (list))
|
||||
(st-class-define! "Integer" "Number" (list))
|
||||
(st-class-define! "SmallInteger" "Integer" (list))
|
||||
(st-class-define! "LargePositiveInteger" "Integer" (list))
|
||||
(st-class-define! "Float" "Number" (list))
|
||||
(st-class-define! "Fraction" "Number" (list "numerator" "denominator"))
|
||||
(st-class-define! "Character" "Magnitude" (list "value"))
|
||||
;; Collections
|
||||
(st-class-define! "Collection" "Object" (list))
|
||||
(st-class-define! "SequenceableCollection" "Collection" (list))
|
||||
(st-class-define! "ArrayedCollection" "SequenceableCollection" (list))
|
||||
(st-class-define! "Array" "ArrayedCollection" (list))
|
||||
(st-class-define! "String" "ArrayedCollection" (list))
|
||||
(st-class-define! "Symbol" "String" (list))
|
||||
(st-class-define! "OrderedCollection" "SequenceableCollection" (list "array" "firstIndex" "lastIndex"))
|
||||
;; Hashed collection family
|
||||
(st-class-define! "HashedCollection" "Collection" (list "array"))
|
||||
(st-class-define! "Set" "HashedCollection" (list))
|
||||
;; Blocks / contexts
|
||||
(st-class-define! "BlockClosure" "Object" (list))
|
||||
;; Reflection support — Message holds the selector/args for a DNU send.
|
||||
(st-class-define! "Message" "Object" (list "selector" "arguments"))
|
||||
(st-class-add-method! "Message" "selector"
|
||||
(st-parse-method "selector ^ selector"))
|
||||
(st-class-add-method! "Message" "arguments"
|
||||
(st-parse-method "arguments ^ arguments"))
|
||||
(st-class-add-method! "Message" "selector:"
|
||||
(st-parse-method "selector: aSym selector := aSym"))
|
||||
(st-class-add-method! "Message" "arguments:"
|
||||
(st-parse-method "arguments: anArray arguments := anArray"))
|
||||
;; Exception hierarchy — Smalltalk's standard error system on top of
|
||||
;; SX's `guard`/`raise`. Subclassing Exception gives you on:do:,
|
||||
;; ensure:, ifCurtailed: catching out of the box.
|
||||
(st-class-define! "Exception" "Object" (list "messageText"))
|
||||
(st-class-add-method! "Exception" "messageText"
|
||||
(st-parse-method "messageText ^ messageText"))
|
||||
(st-class-add-method! "Exception" "messageText:"
|
||||
(st-parse-method "messageText: aString messageText := aString. ^ self"))
|
||||
(st-class-define! "Error" "Exception" (list))
|
||||
(st-class-define! "ZeroDivide" "Error" (list))
|
||||
(st-class-define! "MessageNotUnderstood" "Error" (list))
|
||||
;; SequenceableCollection — shared iteration / inspection methods.
|
||||
;; Defined on the parent class so Array, String, Symbol, and
|
||||
;; OrderedCollection all inherit. Each method calls `self do:`,
|
||||
;; which dispatches to the receiver's primitive do: implementation.
|
||||
(st-class-add-method! "SequenceableCollection" "inject:into:"
|
||||
(st-parse-method
|
||||
"inject: initial into: aBlock
|
||||
| acc |
|
||||
acc := initial.
|
||||
self do: [:e | acc := aBlock value: acc value: e].
|
||||
^ acc"))
|
||||
(st-class-add-method! "SequenceableCollection" "detect:"
|
||||
(st-parse-method
|
||||
"detect: aBlock
|
||||
self do: [:e | (aBlock value: e) ifTrue: [^ e]].
|
||||
^ nil"))
|
||||
(st-class-add-method! "SequenceableCollection" "detect:ifNone:"
|
||||
(st-parse-method
|
||||
"detect: aBlock ifNone: noneBlock
|
||||
self do: [:e | (aBlock value: e) ifTrue: [^ e]].
|
||||
^ noneBlock value"))
|
||||
(st-class-add-method! "SequenceableCollection" "count:"
|
||||
(st-parse-method
|
||||
"count: aBlock
|
||||
| n |
|
||||
n := 0.
|
||||
self do: [:e | (aBlock value: e) ifTrue: [n := n + 1]].
|
||||
^ n"))
|
||||
(st-class-add-method! "SequenceableCollection" "allSatisfy:"
|
||||
(st-parse-method
|
||||
"allSatisfy: aBlock
|
||||
self do: [:e | (aBlock value: e) ifFalse: [^ false]].
|
||||
^ true"))
|
||||
(st-class-add-method! "SequenceableCollection" "anySatisfy:"
|
||||
(st-parse-method
|
||||
"anySatisfy: aBlock
|
||||
self do: [:e | (aBlock value: e) ifTrue: [^ true]].
|
||||
^ false"))
|
||||
(st-class-add-method! "SequenceableCollection" "includes:"
|
||||
(st-parse-method
|
||||
"includes: target
|
||||
self do: [:e | e = target ifTrue: [^ true]].
|
||||
^ false"))
|
||||
(st-class-add-method! "SequenceableCollection" "do:separatedBy:"
|
||||
(st-parse-method
|
||||
"do: aBlock separatedBy: sepBlock
|
||||
| first |
|
||||
first := true.
|
||||
self do: [:e |
|
||||
first ifFalse: [sepBlock value].
|
||||
first := false.
|
||||
aBlock value: e].
|
||||
^ self"))
|
||||
(st-class-add-method! "SequenceableCollection" "indexOf:"
|
||||
(st-parse-method
|
||||
"indexOf: target
|
||||
| idx |
|
||||
idx := 1.
|
||||
self do: [:e | e = target ifTrue: [^ idx]. idx := idx + 1].
|
||||
^ 0"))
|
||||
(st-class-add-method! "SequenceableCollection" "indexOf:ifAbsent:"
|
||||
(st-parse-method
|
||||
"indexOf: target ifAbsent: noneBlock
|
||||
| idx |
|
||||
idx := 1.
|
||||
self do: [:e | e = target ifTrue: [^ idx]. idx := idx + 1].
|
||||
^ noneBlock value"))
|
||||
(st-class-add-method! "SequenceableCollection" "reject:"
|
||||
(st-parse-method
|
||||
"reject: aBlock ^ self select: [:e | (aBlock value: e) not]"))
|
||||
(st-class-add-method! "SequenceableCollection" "isEmpty"
|
||||
(st-parse-method "isEmpty ^ self size = 0"))
|
||||
(st-class-add-method! "SequenceableCollection" "notEmpty"
|
||||
(st-parse-method "notEmpty ^ self size > 0"))
|
||||
;; (no asString here — Symbol/String have their own primitive
|
||||
;; impls; SequenceableCollection-level fallback would overwrite
|
||||
;; the bare-name-for-Symbol behaviour.)
|
||||
;; Array class-side constructors for small fixed-arity literals.
|
||||
(st-class-add-class-method! "Array" "with:"
|
||||
(st-parse-method
|
||||
"with: x | a | a := Array new: 1. a at: 1 put: x. ^ a"))
|
||||
(st-class-add-class-method! "Array" "with:with:"
|
||||
(st-parse-method
|
||||
"with: a with: b
|
||||
| r | r := Array new: 2.
|
||||
r at: 1 put: a. r at: 2 put: b. ^ r"))
|
||||
(st-class-add-class-method! "Array" "with:with:with:"
|
||||
(st-parse-method
|
||||
"with: a with: b with: c
|
||||
| r | r := Array new: 3.
|
||||
r at: 1 put: a. r at: 2 put: b. r at: 3 put: c. ^ r"))
|
||||
(st-class-add-class-method! "Array" "with:with:with:with:"
|
||||
(st-parse-method
|
||||
"with: a with: b with: c with: d
|
||||
| r | r := Array new: 4.
|
||||
r at: 1 put: a. r at: 2 put: b. r at: 3 put: c. r at: 4 put: d. ^ r"))
|
||||
;; ── HashedCollection / Set / Dictionary ──
|
||||
;; Implemented as user instances with array-backed storage. Sets
|
||||
;; use a single `array` ivar; Dictionaries use parallel `keys`/
|
||||
;; `values` arrays. New is class-side and routes through `init`.
|
||||
(st-class-add-method! "HashedCollection" "init"
|
||||
(st-parse-method "init array := Array new: 0. ^ self"))
|
||||
(st-class-add-method! "HashedCollection" "size"
|
||||
(st-parse-method "size ^ array size"))
|
||||
(st-class-add-method! "HashedCollection" "isEmpty"
|
||||
(st-parse-method "isEmpty ^ array isEmpty"))
|
||||
(st-class-add-method! "HashedCollection" "notEmpty"
|
||||
(st-parse-method "notEmpty ^ array notEmpty"))
|
||||
(st-class-add-method! "HashedCollection" "do:"
|
||||
(st-parse-method "do: aBlock array do: aBlock. ^ self"))
|
||||
(st-class-add-method! "HashedCollection" "asArray"
|
||||
(st-parse-method "asArray ^ array"))
|
||||
(st-class-add-class-method! "Set" "new"
|
||||
(st-parse-method "new ^ super new init"))
|
||||
(st-class-add-method! "Set" "add:"
|
||||
(st-parse-method
|
||||
"add: anObject
|
||||
(self includes: anObject) ifFalse: [array add: anObject].
|
||||
^ anObject"))
|
||||
(st-class-add-method! "Set" "addAll:"
|
||||
(st-parse-method
|
||||
"addAll: aCollection
|
||||
aCollection do: [:e | self add: e].
|
||||
^ aCollection"))
|
||||
(st-class-add-method! "Set" "remove:"
|
||||
(st-parse-method
|
||||
"remove: anObject
|
||||
array := array reject: [:e | e = anObject].
|
||||
^ anObject"))
|
||||
(st-class-add-method! "Set" "includes:"
|
||||
(st-parse-method "includes: anObject ^ array includes: anObject"))
|
||||
(st-class-define! "Dictionary" "HashedCollection" (list "keys" "values"))
|
||||
(st-class-add-class-method! "Dictionary" "new"
|
||||
(st-parse-method "new ^ super new init"))
|
||||
(st-class-add-method! "Dictionary" "init"
|
||||
(st-parse-method
|
||||
"init keys := Array new: 0. values := Array new: 0. ^ self"))
|
||||
(st-class-add-method! "Dictionary" "size"
|
||||
(st-parse-method "size ^ keys size"))
|
||||
(st-class-add-method! "Dictionary" "isEmpty"
|
||||
(st-parse-method "isEmpty ^ keys isEmpty"))
|
||||
(st-class-add-method! "Dictionary" "notEmpty"
|
||||
(st-parse-method "notEmpty ^ keys notEmpty"))
|
||||
(st-class-add-method! "Dictionary" "keys"
|
||||
(st-parse-method "keys ^ keys"))
|
||||
(st-class-add-method! "Dictionary" "values"
|
||||
(st-parse-method "values ^ values"))
|
||||
(st-class-add-method! "Dictionary" "at:"
|
||||
(st-parse-method
|
||||
"at: aKey
|
||||
| i |
|
||||
i := keys indexOf: aKey.
|
||||
i = 0 ifTrue: [^ nil].
|
||||
^ values at: i"))
|
||||
(st-class-add-method! "Dictionary" "at:ifAbsent:"
|
||||
(st-parse-method
|
||||
"at: aKey ifAbsent: aBlock
|
||||
| i |
|
||||
i := keys indexOf: aKey.
|
||||
i = 0 ifTrue: [^ aBlock value].
|
||||
^ values at: i"))
|
||||
(st-class-add-method! "Dictionary" "at:put:"
|
||||
(st-parse-method
|
||||
"at: aKey put: aValue
|
||||
| i |
|
||||
i := keys indexOf: aKey.
|
||||
i = 0
|
||||
ifTrue: [keys add: aKey. values add: aValue]
|
||||
ifFalse: [values at: i put: aValue].
|
||||
^ aValue"))
|
||||
(st-class-add-method! "Dictionary" "includesKey:"
|
||||
(st-parse-method "includesKey: aKey ^ (keys indexOf: aKey) > 0"))
|
||||
(st-class-add-method! "Dictionary" "removeKey:"
|
||||
(st-parse-method
|
||||
"removeKey: aKey
|
||||
| i nk nv j |
|
||||
i := keys indexOf: aKey.
|
||||
i = 0 ifTrue: [^ nil].
|
||||
nk := Array new: 0. nv := Array new: 0.
|
||||
j := 1.
|
||||
[j <= keys size] whileTrue: [
|
||||
j = i ifFalse: [
|
||||
nk add: (keys at: j).
|
||||
nv add: (values at: j)].
|
||||
j := j + 1].
|
||||
keys := nk. values := nv.
|
||||
^ aKey"))
|
||||
(st-class-add-method! "Dictionary" "do:"
|
||||
(st-parse-method "do: aBlock values do: aBlock. ^ self"))
|
||||
(st-class-add-method! "Dictionary" "keysDo:"
|
||||
(st-parse-method "keysDo: aBlock keys do: aBlock. ^ self"))
|
||||
(st-class-add-method! "Dictionary" "valuesDo:"
|
||||
(st-parse-method "valuesDo: aBlock values do: aBlock. ^ self"))
|
||||
(st-class-add-method! "Dictionary" "keysAndValuesDo:"
|
||||
(st-parse-method
|
||||
"keysAndValuesDo: aBlock
|
||||
| i |
|
||||
i := 1.
|
||||
[i <= keys size] whileTrue: [
|
||||
aBlock value: (keys at: i) value: (values at: i).
|
||||
i := i + 1].
|
||||
^ self"))
|
||||
(st-class-define! "IdentityDictionary" "Dictionary" (list))
|
||||
;; ── Stream hierarchy ──
|
||||
;; Streams wrap a collection with a 0-based `position`. Read/peek
|
||||
;; advance via `at:` (1-indexed Smalltalk-style) on the collection.
|
||||
;; Write streams require a mutable collection (Array works; String
|
||||
;; doesn't, see Phase 5 follow-up).
|
||||
(st-class-define! "Stream" "Object" (list))
|
||||
(st-class-define! "PositionableStream" "Stream" (list "collection" "position"))
|
||||
(st-class-define! "ReadStream" "PositionableStream" (list))
|
||||
(st-class-define! "WriteStream" "PositionableStream" (list))
|
||||
(st-class-define! "ReadWriteStream" "WriteStream" (list))
|
||||
(st-class-add-class-method! "ReadStream" "on:"
|
||||
(st-parse-method "on: aColl ^ super new on: aColl"))
|
||||
(st-class-add-class-method! "WriteStream" "on:"
|
||||
(st-parse-method "on: aColl ^ super new on: aColl"))
|
||||
(st-class-add-class-method! "WriteStream" "with:"
|
||||
(st-parse-method
|
||||
"with: aColl
|
||||
| s |
|
||||
s := super new on: aColl.
|
||||
s setToEnd.
|
||||
^ s"))
|
||||
(st-class-add-class-method! "ReadWriteStream" "on:"
|
||||
(st-parse-method "on: aColl ^ super new on: aColl"))
|
||||
(st-class-add-method! "PositionableStream" "on:"
|
||||
(st-parse-method
|
||||
"on: aColl collection := aColl. position := 0. ^ self"))
|
||||
(st-class-add-method! "PositionableStream" "atEnd"
|
||||
(st-parse-method "atEnd ^ position >= collection size"))
|
||||
(st-class-add-method! "PositionableStream" "position"
|
||||
(st-parse-method "position ^ position"))
|
||||
(st-class-add-method! "PositionableStream" "position:"
|
||||
(st-parse-method "position: n position := n. ^ self"))
|
||||
(st-class-add-method! "PositionableStream" "reset"
|
||||
(st-parse-method "reset position := 0. ^ self"))
|
||||
(st-class-add-method! "PositionableStream" "setToEnd"
|
||||
(st-parse-method "setToEnd position := collection size. ^ self"))
|
||||
(st-class-add-method! "PositionableStream" "contents"
|
||||
(st-parse-method "contents ^ collection"))
|
||||
(st-class-add-method! "PositionableStream" "skip:"
|
||||
(st-parse-method "skip: n position := position + n. ^ self"))
|
||||
(st-class-add-method! "ReadStream" "next"
|
||||
(st-parse-method
|
||||
"next
|
||||
self atEnd ifTrue: [^ nil].
|
||||
position := position + 1.
|
||||
^ collection at: position"))
|
||||
(st-class-add-method! "ReadStream" "peek"
|
||||
(st-parse-method
|
||||
"peek
|
||||
self atEnd ifTrue: [^ nil].
|
||||
^ collection at: position + 1"))
|
||||
(st-class-add-method! "ReadStream" "upToEnd"
|
||||
(st-parse-method
|
||||
"upToEnd
|
||||
| result |
|
||||
result := Array new: 0.
|
||||
[self atEnd] whileFalse: [result add: self next].
|
||||
^ result"))
|
||||
(st-class-add-method! "ReadStream" "next:"
|
||||
(st-parse-method
|
||||
"next: n
|
||||
| result i |
|
||||
result := Array new: 0.
|
||||
i := 0.
|
||||
[(i < n) and: [self atEnd not]] whileTrue: [
|
||||
result add: self next.
|
||||
i := i + 1].
|
||||
^ result"))
|
||||
(st-class-add-method! "WriteStream" "nextPut:"
|
||||
(st-parse-method
|
||||
"nextPut: anObject
|
||||
collection add: anObject.
|
||||
position := position + 1.
|
||||
^ anObject"))
|
||||
(st-class-add-method! "WriteStream" "nextPutAll:"
|
||||
(st-parse-method
|
||||
"nextPutAll: aCollection
|
||||
aCollection do: [:e | self nextPut: e].
|
||||
^ aCollection"))
|
||||
;; ReadWriteStream inherits from WriteStream + ReadStream behaviour;
|
||||
;; for the simple linear-position model, both nextPut: and next work.
|
||||
(st-class-add-method! "ReadWriteStream" "next"
|
||||
(st-parse-method
|
||||
"next
|
||||
self atEnd ifTrue: [^ nil].
|
||||
position := position + 1.
|
||||
^ collection at: position"))
|
||||
(st-class-add-method! "ReadWriteStream" "peek"
|
||||
(st-parse-method
|
||||
"peek
|
||||
self atEnd ifTrue: [^ nil].
|
||||
^ collection at: position + 1"))
|
||||
;; ── Fraction ──
|
||||
;; Rational numbers stored as numerator/denominator, normalized
|
||||
;; (sign on numerator, denominator > 0, reduced via gcd).
|
||||
(st-class-add-class-method! "Fraction" "numerator:denominator:"
|
||||
(st-parse-method
|
||||
"numerator: n denominator: d
|
||||
| f |
|
||||
f := super new.
|
||||
^ f setNumerator: n denominator: d"))
|
||||
(st-class-add-method! "Fraction" "setNumerator:denominator:"
|
||||
(st-parse-method
|
||||
"setNumerator: n denominator: d
|
||||
| g s nn dd |
|
||||
d = 0 ifTrue: [Error signal: 'Fraction denominator cannot be zero'].
|
||||
s := (d < 0) ifTrue: [-1] ifFalse: [1].
|
||||
nn := n * s. dd := d * s.
|
||||
g := nn abs gcd: dd.
|
||||
g = 0 ifTrue: [g := 1].
|
||||
numerator := nn / g.
|
||||
denominator := dd / g.
|
||||
^ self"))
|
||||
(st-class-add-method! "Fraction" "numerator"
|
||||
(st-parse-method "numerator ^ numerator"))
|
||||
(st-class-add-method! "Fraction" "denominator"
|
||||
(st-parse-method "denominator ^ denominator"))
|
||||
(st-class-add-method! "Fraction" "+"
|
||||
(st-parse-method
|
||||
"+ other
|
||||
^ Fraction
|
||||
numerator: numerator * other denominator + (other numerator * denominator)
|
||||
denominator: denominator * other denominator"))
|
||||
(st-class-add-method! "Fraction" "-"
|
||||
(st-parse-method
|
||||
"- other
|
||||
^ Fraction
|
||||
numerator: numerator * other denominator - (other numerator * denominator)
|
||||
denominator: denominator * other denominator"))
|
||||
(st-class-add-method! "Fraction" "*"
|
||||
(st-parse-method
|
||||
"* other
|
||||
^ Fraction
|
||||
numerator: numerator * other numerator
|
||||
denominator: denominator * other denominator"))
|
||||
(st-class-add-method! "Fraction" "/"
|
||||
(st-parse-method
|
||||
"/ other
|
||||
^ Fraction
|
||||
numerator: numerator * other denominator
|
||||
denominator: denominator * other numerator"))
|
||||
(st-class-add-method! "Fraction" "negated"
|
||||
(st-parse-method
|
||||
"negated ^ Fraction numerator: numerator negated denominator: denominator"))
|
||||
(st-class-add-method! "Fraction" "reciprocal"
|
||||
(st-parse-method
|
||||
"reciprocal ^ Fraction numerator: denominator denominator: numerator"))
|
||||
(st-class-add-method! "Fraction" "="
|
||||
(st-parse-method
|
||||
"= other
|
||||
^ numerator = other numerator and: [denominator = other denominator]"))
|
||||
(st-class-add-method! "Fraction" "<"
|
||||
(st-parse-method
|
||||
"< other
|
||||
^ numerator * other denominator < (other numerator * denominator)"))
|
||||
(st-class-add-method! "Fraction" "asFloat"
|
||||
(st-parse-method "asFloat ^ numerator / denominator"))
|
||||
(st-class-add-method! "Fraction" "printString"
|
||||
(st-parse-method
|
||||
"printString ^ numerator printString , '/' , denominator printString"))
|
||||
(st-class-add-method! "Fraction" "isFraction"
|
||||
(st-parse-method "isFraction ^ true"))
|
||||
"ok")))
|
||||
|
||||
;; Initialise on load. Tests can re-bootstrap to reset state.
|
||||
(st-bootstrap-classes!)
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"date": "2026-04-25T16:05:32Z",
|
||||
"programs": [
|
||||
"eight-queens.st",
|
||||
"fibonacci.st",
|
||||
"life.st",
|
||||
"mandelbrot.st",
|
||||
"quicksort.st"
|
||||
],
|
||||
"program_count": 5,
|
||||
"program_tests_passed": 39,
|
||||
"all_tests_passed": 847,
|
||||
"all_tests_total": 847,
|
||||
"exit_code": 0
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
# Smalltalk-on-SX Scoreboard
|
||||
|
||||
_Last run: 2026-04-25T16:05:32Z_
|
||||
|
||||
## Totals
|
||||
|
||||
| Suite | Passing |
|
||||
|-------|---------|
|
||||
| All Smalltalk-on-SX tests | **847 / 847** |
|
||||
| Classic-corpus tests (`tests/programs.sx`) | **39** |
|
||||
|
||||
## Classic-corpus programs (`lib/smalltalk/tests/programs/`)
|
||||
|
||||
| Program | Status |
|
||||
|---------|--------|
|
||||
| `eight-queens.st` | present |
|
||||
| `fibonacci.st` | present |
|
||||
| `life.st` | present |
|
||||
| `mandelbrot.st` | present |
|
||||
| `quicksort.st` | present |
|
||||
|
||||
## Per-file test counts
|
||||
|
||||
```
|
||||
OK lib/smalltalk/tests/ansi.sx 62 passed
|
||||
OK lib/smalltalk/tests/blocks.sx 19 passed
|
||||
OK lib/smalltalk/tests/cannot_return.sx 5 passed
|
||||
OK lib/smalltalk/tests/collections.sx 29 passed
|
||||
OK lib/smalltalk/tests/conditional.sx 25 passed
|
||||
OK lib/smalltalk/tests/dnu.sx 15 passed
|
||||
OK lib/smalltalk/tests/eval.sx 68 passed
|
||||
OK lib/smalltalk/tests/exceptions.sx 15 passed
|
||||
OK lib/smalltalk/tests/hashed.sx 30 passed
|
||||
OK lib/smalltalk/tests/inline_cache.sx 10 passed
|
||||
OK lib/smalltalk/tests/intrinsics.sx 24 passed
|
||||
OK lib/smalltalk/tests/nlr.sx 14 passed
|
||||
OK lib/smalltalk/tests/numbers.sx 47 passed
|
||||
OK lib/smalltalk/tests/parse_chunks.sx 21 passed
|
||||
OK lib/smalltalk/tests/parse.sx 47 passed
|
||||
OK lib/smalltalk/tests/pharo.sx 91 passed
|
||||
OK lib/smalltalk/tests/printing.sx 19 passed
|
||||
OK lib/smalltalk/tests/programs.sx 39 passed
|
||||
OK lib/smalltalk/tests/reflection.sx 77 passed
|
||||
OK lib/smalltalk/tests/runtime.sx 64 passed
|
||||
OK lib/smalltalk/tests/streams.sx 21 passed
|
||||
OK lib/smalltalk/tests/sunit.sx 19 passed
|
||||
OK lib/smalltalk/tests/super.sx 9 passed
|
||||
OK lib/smalltalk/tests/tokenize.sx 63 passed
|
||||
OK lib/smalltalk/tests/while.sx 14 passed
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- The spec interpreter is correct but slow (call/cc + dict-based ivars per send).
|
||||
- Larger Life multi-step verification, the 8-queens canonical case, and the glider-gun pattern are deferred to the JIT path.
|
||||
- Generated by `bash lib/smalltalk/conformance.sh`. Both files are committed; the runner overwrites them on each run.
|
||||
@@ -1,153 +0,0 @@
|
||||
;; SUnit — minimal port written in SX-Smalltalk, run by smalltalk-load.
|
||||
;;
|
||||
;; Provides:
|
||||
;; TestCase — base class. Subclass it, add `testSomething` methods.
|
||||
;; TestSuite — a collection of TestCase instances; runs them all.
|
||||
;; TestResult — passes / failures / errors counts and lists.
|
||||
;; TestFailure — Error subclass raised by `assert:` and friends.
|
||||
;;
|
||||
;; Conventions:
|
||||
;; - Test methods are run in a fresh instance per test.
|
||||
;; - `setUp` is sent before each test; `tearDown` after.
|
||||
;; - Failures are signalled by TestFailure; runner catches and records.
|
||||
|
||||
(define
|
||||
st-sunit-source
|
||||
"Error subclass: #TestFailure
|
||||
instanceVariableNames: ''!
|
||||
|
||||
Object subclass: #TestCase
|
||||
instanceVariableNames: 'testSelector'!
|
||||
|
||||
!TestCase methodsFor: 'access'!
|
||||
testSelector ^ testSelector!
|
||||
testSelector: aSym testSelector := aSym. ^ self! !
|
||||
|
||||
!TestCase methodsFor: 'fixture'!
|
||||
setUp ^ self!
|
||||
tearDown ^ self! !
|
||||
|
||||
!TestCase methodsFor: 'asserts'!
|
||||
assert: aBoolean
|
||||
aBoolean ifFalse: [TestFailure signal: 'assertion failed'].
|
||||
^ self!
|
||||
|
||||
assert: aBoolean description: aString
|
||||
aBoolean ifFalse: [TestFailure signal: aString].
|
||||
^ self!
|
||||
|
||||
assert: actual equals: expected
|
||||
actual = expected ifFalse: [
|
||||
TestFailure signal: 'expected ' , expected printString
|
||||
, ' but got ' , actual printString].
|
||||
^ self!
|
||||
|
||||
deny: aBoolean
|
||||
aBoolean ifTrue: [TestFailure signal: 'denial failed'].
|
||||
^ self!
|
||||
|
||||
should: aBlock raise: anExceptionClass
|
||||
| raised |
|
||||
raised := false.
|
||||
[aBlock value] on: anExceptionClass do: [:e | raised := true].
|
||||
raised ifFalse: [
|
||||
TestFailure signal: 'expected exception ' , anExceptionClass name
|
||||
, ' was not raised'].
|
||||
^ self!
|
||||
|
||||
shouldnt: aBlock raise: anExceptionClass
|
||||
| raised |
|
||||
raised := false.
|
||||
[aBlock value] on: anExceptionClass do: [:e | raised := true].
|
||||
raised ifTrue: [
|
||||
TestFailure signal: 'unexpected exception ' , anExceptionClass name].
|
||||
^ self! !
|
||||
|
||||
!TestCase methodsFor: 'running'!
|
||||
runCase
|
||||
self setUp.
|
||||
self perform: testSelector.
|
||||
self tearDown.
|
||||
^ self! !
|
||||
|
||||
!TestCase class methodsFor: 'instantiation'!
|
||||
selector: aSym ^ self new testSelector: aSym!
|
||||
|
||||
suiteForAll: aSelectorArray
|
||||
| suite |
|
||||
suite := TestSuite new init.
|
||||
suite name: self name.
|
||||
aSelectorArray do: [:s | suite addTest: (self selector: s)].
|
||||
^ suite! !
|
||||
|
||||
Object subclass: #TestResult
|
||||
instanceVariableNames: 'passes failures errors'!
|
||||
|
||||
!TestResult methodsFor: 'init'!
|
||||
init
|
||||
passes := Array new: 0.
|
||||
failures := Array new: 0.
|
||||
errors := Array new: 0.
|
||||
^ self! !
|
||||
|
||||
!TestResult methodsFor: 'access'!
|
||||
passes ^ passes!
|
||||
failures ^ failures!
|
||||
errors ^ errors!
|
||||
passCount ^ passes size!
|
||||
failureCount ^ failures size!
|
||||
errorCount ^ errors size!
|
||||
totalCount ^ passes size + failures size + errors size!
|
||||
|
||||
addPass: aTest passes add: aTest. ^ self!
|
||||
addFailure: aTest message: aMsg
|
||||
| rec |
|
||||
rec := Array new: 2.
|
||||
rec at: 1 put: aTest. rec at: 2 put: aMsg.
|
||||
failures add: rec.
|
||||
^ self!
|
||||
addError: aTest message: aMsg
|
||||
| rec |
|
||||
rec := Array new: 2.
|
||||
rec at: 1 put: aTest. rec at: 2 put: aMsg.
|
||||
errors add: rec.
|
||||
^ self!
|
||||
|
||||
isEmpty ^ self totalCount = 0!
|
||||
allPassed ^ (failures size + errors size) = 0!
|
||||
|
||||
summary
|
||||
^ 'Tests: {1} Passed: {2} Failed: {3} Errors: {4}'
|
||||
format: (Array
|
||||
with: self totalCount printString
|
||||
with: passes size printString
|
||||
with: failures size printString
|
||||
with: errors size printString)! !
|
||||
|
||||
Object subclass: #TestSuite
|
||||
instanceVariableNames: 'tests name'!
|
||||
|
||||
!TestSuite methodsFor: 'init'!
|
||||
init tests := Array new: 0. name := 'Suite'. ^ self!
|
||||
name ^ name!
|
||||
name: aString name := aString. ^ self! !
|
||||
|
||||
!TestSuite methodsFor: 'tests'!
|
||||
tests ^ tests!
|
||||
addTest: aTest tests add: aTest. ^ self!
|
||||
addAll: aCollection aCollection do: [:t | self addTest: t]. ^ self!
|
||||
size ^ tests size! !
|
||||
|
||||
!TestSuite methodsFor: 'running'!
|
||||
run
|
||||
| result |
|
||||
result := TestResult new init.
|
||||
tests do: [:t | self runTest: t result: result].
|
||||
^ result!
|
||||
|
||||
runTest: aTest result: aResult
|
||||
[aTest runCase. aResult addPass: aTest]
|
||||
on: TestFailure do: [:e | aResult addFailure: aTest message: e messageText].
|
||||
^ self! !")
|
||||
|
||||
(smalltalk-load st-sunit-source)
|
||||
@@ -1,145 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fast Smalltalk-on-SX test runner — pipes directly to sx_server.exe.
|
||||
# Mirrors lib/haskell/test.sh.
|
||||
#
|
||||
# Usage:
|
||||
# bash lib/smalltalk/test.sh # run all tests
|
||||
# bash lib/smalltalk/test.sh -v # verbose
|
||||
# bash lib/smalltalk/test.sh tests/tokenize.sx # run one file
|
||||
|
||||
set -uo pipefail
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
SX_SERVER="hosts/ocaml/_build/default/bin/sx_server.exe"
|
||||
if [ ! -x "$SX_SERVER" ]; then
|
||||
MAIN_ROOT=$(git worktree list | head -1 | awk '{print $1}')
|
||||
if [ -x "$MAIN_ROOT/$SX_SERVER" ]; then
|
||||
SX_SERVER="$MAIN_ROOT/$SX_SERVER"
|
||||
else
|
||||
echo "ERROR: sx_server.exe not found. Run: cd hosts/ocaml && dune build"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
VERBOSE=""
|
||||
FILES=()
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-v|--verbose) VERBOSE=1 ;;
|
||||
*) FILES+=("$arg") ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ ${#FILES[@]} -eq 0 ]; then
|
||||
# tokenize.sx must load first — it defines the st-test helpers reused by
|
||||
# subsequent test files. Sort enforces this lexicographically.
|
||||
mapfile -t FILES < <(find lib/smalltalk/tests -maxdepth 2 -name '*.sx' | sort)
|
||||
fi
|
||||
|
||||
TOTAL_PASS=0
|
||||
TOTAL_FAIL=0
|
||||
FAILED_FILES=()
|
||||
|
||||
for FILE in "${FILES[@]}"; do
|
||||
[ -f "$FILE" ] || { echo "skip $FILE (not found)"; continue; }
|
||||
TMPFILE=$(mktemp)
|
||||
if [ "$(basename "$FILE")" = "tokenize.sx" ]; then
|
||||
cat > "$TMPFILE" <<EPOCHS
|
||||
(epoch 1)
|
||||
(load "lib/smalltalk/tokenizer.sx")
|
||||
(epoch 2)
|
||||
(load "$FILE")
|
||||
(epoch 3)
|
||||
(eval "(list st-test-pass st-test-fail)")
|
||||
EPOCHS
|
||||
else
|
||||
cat > "$TMPFILE" <<EPOCHS
|
||||
(epoch 1)
|
||||
(load "lib/smalltalk/tokenizer.sx")
|
||||
(epoch 2)
|
||||
(load "lib/smalltalk/parser.sx")
|
||||
(epoch 3)
|
||||
(load "lib/smalltalk/runtime.sx")
|
||||
(epoch 4)
|
||||
(load "lib/smalltalk/eval.sx")
|
||||
(epoch 5)
|
||||
(load "lib/smalltalk/sunit.sx")
|
||||
(epoch 6)
|
||||
(load "lib/smalltalk/tests/tokenize.sx")
|
||||
(epoch 7)
|
||||
(load "$FILE")
|
||||
(epoch 8)
|
||||
(eval "(list st-test-pass st-test-fail)")
|
||||
EPOCHS
|
||||
fi
|
||||
|
||||
OUTPUT=$(timeout 180 "$SX_SERVER" < "$TMPFILE" 2>&1 || true)
|
||||
rm -f "$TMPFILE"
|
||||
|
||||
# Final epoch's value: either (ok N (P F)) on one line or
|
||||
# (ok-len N M)\n(P F) where the value is on the following line.
|
||||
LINE=$(echo "$OUTPUT" | awk '/^\(ok-len [0-9]+ / {getline; print}' | tail -1)
|
||||
if [ -z "$LINE" ]; then
|
||||
LINE=$(echo "$OUTPUT" | grep -E '^\(ok [0-9]+ \([0-9]+ [0-9]+\)\)' | tail -1 \
|
||||
| sed -E 's/^\(ok [0-9]+ //; s/\)$//')
|
||||
fi
|
||||
if [ -z "$LINE" ]; then
|
||||
echo "X $FILE: could not extract summary"
|
||||
echo "$OUTPUT" | tail -30
|
||||
TOTAL_FAIL=$((TOTAL_FAIL + 1))
|
||||
FAILED_FILES+=("$FILE")
|
||||
continue
|
||||
fi
|
||||
P=$(echo "$LINE" | sed -E 's/^\(([0-9]+) ([0-9]+)\).*/\1/')
|
||||
F=$(echo "$LINE" | sed -E 's/^\(([0-9]+) ([0-9]+)\).*/\2/')
|
||||
TOTAL_PASS=$((TOTAL_PASS + P))
|
||||
TOTAL_FAIL=$((TOTAL_FAIL + F))
|
||||
if [ "$F" -gt 0 ]; then
|
||||
FAILED_FILES+=("$FILE")
|
||||
printf 'X %-40s %d/%d\n' "$FILE" "$P" "$((P+F))"
|
||||
TMPFILE2=$(mktemp)
|
||||
if [ "$(basename "$FILE")" = "tokenize.sx" ]; then
|
||||
cat > "$TMPFILE2" <<EPOCHS
|
||||
(epoch 1)
|
||||
(load "lib/smalltalk/tokenizer.sx")
|
||||
(epoch 2)
|
||||
(load "$FILE")
|
||||
(epoch 3)
|
||||
(eval "(map (fn (f) (get f :name)) st-test-fails)")
|
||||
EPOCHS
|
||||
else
|
||||
cat > "$TMPFILE2" <<EPOCHS
|
||||
(epoch 1)
|
||||
(load "lib/smalltalk/tokenizer.sx")
|
||||
(epoch 2)
|
||||
(load "lib/smalltalk/parser.sx")
|
||||
(epoch 3)
|
||||
(load "lib/smalltalk/runtime.sx")
|
||||
(epoch 4)
|
||||
(load "lib/smalltalk/eval.sx")
|
||||
(epoch 5)
|
||||
(load "lib/smalltalk/sunit.sx")
|
||||
(epoch 6)
|
||||
(load "lib/smalltalk/tests/tokenize.sx")
|
||||
(epoch 7)
|
||||
(load "$FILE")
|
||||
(epoch 8)
|
||||
(eval "(map (fn (f) (get f :name)) st-test-fails)")
|
||||
EPOCHS
|
||||
fi
|
||||
FAILS=$(timeout 180 "$SX_SERVER" < "$TMPFILE2" 2>&1 | grep -E '^\(ok [0-9]+ \(' | tail -1 || true)
|
||||
rm -f "$TMPFILE2"
|
||||
echo " $FAILS"
|
||||
elif [ "$VERBOSE" = "1" ]; then
|
||||
printf 'OK %-40s %d passed\n' "$FILE" "$P"
|
||||
fi
|
||||
done
|
||||
|
||||
TOTAL=$((TOTAL_PASS + TOTAL_FAIL))
|
||||
if [ $TOTAL_FAIL -eq 0 ]; then
|
||||
echo "OK $TOTAL_PASS/$TOTAL smalltalk-on-sx tests passed"
|
||||
else
|
||||
echo "FAIL $TOTAL_PASS/$TOTAL passed, $TOTAL_FAIL failed in: ${FAILED_FILES[*]}"
|
||||
fi
|
||||
|
||||
[ $TOTAL_FAIL -eq 0 ]
|
||||
@@ -1,158 +0,0 @@
|
||||
;; ANSI X3J20 Smalltalk validator — stretch subset.
|
||||
;;
|
||||
;; Targets the mandatory protocols documented in the standard; one test
|
||||
;; case per ANSI §6.x category. Test methods are run through the SUnit
|
||||
;; framework; one st-test row per Smalltalk method (mirrors tests/pharo.sx).
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(define
|
||||
ansi-source
|
||||
"TestCase subclass: #AnsiObjectTest instanceVariableNames: ''!
|
||||
|
||||
!AnsiObjectTest methodsFor: '6.10 Object'!
|
||||
testIdentity self assert: 42 == 42!
|
||||
testIdentityNotEq self deny: 'a' == 'b'!
|
||||
testEqualityIsAlsoIdentityOnInts self assert: 7 = 7!
|
||||
testNotEqual self assert: (1 ~= 2)!
|
||||
testIsNilOnNil self assert: nil isNil!
|
||||
testIsNilOnInt self deny: 1 isNil!
|
||||
testNotNil self assert: 42 notNil!
|
||||
testClass self assert: 42 class = SmallInteger!
|
||||
testYourself
|
||||
| x | x := 99.
|
||||
self assert: x yourself equals: 99! !
|
||||
|
||||
TestCase subclass: #AnsiBooleanTest instanceVariableNames: ''!
|
||||
|
||||
!AnsiBooleanTest methodsFor: '6.11 Boolean'!
|
||||
testNot self assert: true not equals: false!
|
||||
testAndTT self assert: (true & true)!
|
||||
testAndTF self deny: (true & false)!
|
||||
testAndFT self deny: (false & true)!
|
||||
testAndFF self deny: (false & false)!
|
||||
testOrTT self assert: (true | true)!
|
||||
testOrTF self assert: (true | false)!
|
||||
testOrFT self assert: (false | true)!
|
||||
testOrFF self deny: (false | false)!
|
||||
testIfTrueTaken self assert: (true ifTrue: [1] ifFalse: [2]) equals: 1!
|
||||
testIfFalseTaken self assert: (false ifTrue: [1] ifFalse: [2]) equals: 2!
|
||||
testAndShort self assert: (false and: [1/0]) equals: false!
|
||||
testOrShort self assert: (true or: [1/0]) equals: true! !
|
||||
|
||||
TestCase subclass: #AnsiIntegerTest instanceVariableNames: ''!
|
||||
|
||||
!AnsiIntegerTest methodsFor: '6.13 Integer'!
|
||||
testFactorial self assert: 6 factorial equals: 720!
|
||||
testGcd self assert: (12 gcd: 18) equals: 6!
|
||||
testLcm self assert: (4 lcm: 6) equals: 12!
|
||||
testEven self assert: 8 even!
|
||||
testOdd self assert: 9 odd!
|
||||
testNegated self assert: 5 negated equals: -5!
|
||||
testAbs self assert: -7 abs equals: 7! !
|
||||
|
||||
!AnsiIntegerTest methodsFor: '6.12 Number arithmetic'!
|
||||
testAdd self assert: 1 + 2 equals: 3!
|
||||
testSub self assert: 10 - 4 equals: 6!
|
||||
testMul self assert: 6 * 7 equals: 42!
|
||||
testMin self assert: (3 min: 7) equals: 3!
|
||||
testMax self assert: (3 max: 7) equals: 7!
|
||||
testBetween self assert: (5 between: 1 and: 10)! !
|
||||
|
||||
TestCase subclass: #AnsiStringTest instanceVariableNames: ''!
|
||||
|
||||
!AnsiStringTest methodsFor: '6.17 String'!
|
||||
testSize self assert: 'abcdef' size equals: 6!
|
||||
testConcat self assert: ('foo' , 'bar') equals: 'foobar'!
|
||||
testAt self assert: ('abcd' at: 3) equals: 'c'!
|
||||
testCopyFromTo self assert: ('helloworld' copyFrom: 1 to: 5) equals: 'hello'!
|
||||
testAsSymbol self assert: 'foo' asSymbol == #foo!
|
||||
testIsEmpty self assert: '' isEmpty! !
|
||||
|
||||
TestCase subclass: #AnsiArrayTest instanceVariableNames: ''!
|
||||
|
||||
!AnsiArrayTest methodsFor: '6.18 Array'!
|
||||
testSize self assert: #(1 2 3) size equals: 3!
|
||||
testAt self assert: (#(10 20 30) at: 2) equals: 20!
|
||||
testAtPut
|
||||
| a |
|
||||
a := Array new: 3.
|
||||
a at: 1 put: 100.
|
||||
self assert: (a at: 1) equals: 100!
|
||||
testDo
|
||||
| s |
|
||||
s := 0.
|
||||
#(1 2 3) do: [:e | s := s + e].
|
||||
self assert: s equals: 6!
|
||||
testCollect self assert: (#(1 2 3) collect: [:x | x + 10]) equals: #(11 12 13)!
|
||||
testSelect self assert: (#(1 2 3 4) select: [:x | x even]) equals: #(2 4)!
|
||||
testReject self assert: (#(1 2 3 4) reject: [:x | x even]) equals: #(1 3)!
|
||||
testInject self assert: (#(1 2 3 4 5) inject: 0 into: [:a :b | a + b]) equals: 15!
|
||||
testIncludes self assert: (#(1 2 3) includes: 2)!
|
||||
testFirst self assert: #(7 8 9) first equals: 7!
|
||||
testLast self assert: #(7 8 9) last equals: 9! !
|
||||
|
||||
TestCase subclass: #AnsiBlockTest instanceVariableNames: ''!
|
||||
|
||||
!AnsiBlockTest methodsFor: '6.19 BlockContext'!
|
||||
testValue self assert: [42] value equals: 42!
|
||||
testValueOne self assert: ([:x | x * 2] value: 21) equals: 42!
|
||||
testValueTwo self assert: ([:a :b | a + b] value: 3 value: 4) equals: 7!
|
||||
testNumArgs self assert: [:a :b | a] numArgs equals: 2!
|
||||
testValueWithArguments
|
||||
self assert: ([:a :b | a , b] valueWithArguments: #('foo' 'bar')) equals: 'foobar'!
|
||||
testWhileTrue
|
||||
| n |
|
||||
n := 5.
|
||||
[n > 0] whileTrue: [n := n - 1].
|
||||
self assert: n equals: 0!
|
||||
testEnsureRunsOnNormal
|
||||
| log |
|
||||
log := Array new: 0.
|
||||
[log add: #body] ensure: [log add: #cleanup].
|
||||
self assert: log size equals: 2!
|
||||
testOnDoCatchesError
|
||||
| r |
|
||||
r := [Error signal: 'boom'] on: Error do: [:e | e messageText].
|
||||
self assert: r equals: 'boom'! !
|
||||
|
||||
TestCase subclass: #AnsiSymbolTest instanceVariableNames: ''!
|
||||
|
||||
!AnsiSymbolTest methodsFor: '6.16 Symbol'!
|
||||
testEqual self assert: #foo = #foo!
|
||||
testIdentity self assert: #bar == #bar!
|
||||
testNotEq self deny: #a == #b! !")
|
||||
|
||||
(smalltalk-load ansi-source)
|
||||
|
||||
(define
|
||||
pharo-test-class
|
||||
(fn
|
||||
(cls-name)
|
||||
(let ((selectors (sort (keys (get (st-class-get cls-name) :methods)))))
|
||||
(for-each
|
||||
(fn (sel)
|
||||
(when
|
||||
(and (>= (len sel) 4) (= (slice sel 0 4) "test"))
|
||||
(let
|
||||
((src (str "| s r | s := " cls-name " suiteForAll: #(#"
|
||||
sel "). r := s run.
|
||||
^ {(r passCount). (r failureCount). (r errorCount)}")))
|
||||
(let ((result (smalltalk-eval-program src)))
|
||||
(st-test
|
||||
(str cls-name " >> " sel)
|
||||
result
|
||||
(list 1 0 0))))))
|
||||
selectors))))
|
||||
|
||||
(pharo-test-class "AnsiObjectTest")
|
||||
(pharo-test-class "AnsiBooleanTest")
|
||||
(pharo-test-class "AnsiIntegerTest")
|
||||
(pharo-test-class "AnsiStringTest")
|
||||
(pharo-test-class "AnsiArrayTest")
|
||||
(pharo-test-class "AnsiBlockTest")
|
||||
(pharo-test-class "AnsiSymbolTest")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,92 +0,0 @@
|
||||
;; BlockContext>>value family tests.
|
||||
;;
|
||||
;; The runtime already implements value, value:, value:value:, value:value:value:,
|
||||
;; value:value:value:value:, and valueWithArguments: in st-block-dispatch.
|
||||
;; This file pins each variant down with explicit tests + closure semantics.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. The value/valueN family ──
|
||||
(st-test "value: zero-arg block" (ev "[42] value") 42)
|
||||
(st-test "value: one-arg block" (ev "[:a | a + 1] value: 10") 11)
|
||||
(st-test "value:value: two-arg" (ev "[:a :b | a * b] value: 3 value: 4") 12)
|
||||
(st-test "value:value:value: three" (ev "[:a :b :c | a + b + c] value: 1 value: 2 value: 3") 6)
|
||||
(st-test "value:value:value:value: four"
|
||||
(ev "[:a :b :c :d | a + b + c + d] value: 1 value: 2 value: 3 value: 4") 10)
|
||||
|
||||
;; ── 2. valueWithArguments: ──
|
||||
(st-test "valueWithArguments: zero-arg"
|
||||
(ev "[99] valueWithArguments: #()") 99)
|
||||
(st-test "valueWithArguments: one-arg"
|
||||
(ev "[:x | x * x] valueWithArguments: #(7)") 49)
|
||||
(st-test "valueWithArguments: many"
|
||||
(ev "[:a :b :c | a , b , c] valueWithArguments: #('foo' '-' 'bar')") "foo-bar")
|
||||
|
||||
;; ── 3. Block returns last expression ──
|
||||
(st-test "block last-expression result" (ev "[1. 2. 3] value") 3)
|
||||
(st-test "block with temps initial state"
|
||||
(ev "[| t u | t := 5. u := t * 2. u] value") 10)
|
||||
|
||||
;; ── 4. Closure over outer locals ──
|
||||
(st-test
|
||||
"block reads outer let temps"
|
||||
(evp "| n | n := 5. ^ [n * n] value")
|
||||
25)
|
||||
(st-test
|
||||
"block writes outer locals (mutating)"
|
||||
(evp "| n | n := 10. [:x | n := n + x] value: 5. ^ n")
|
||||
15)
|
||||
|
||||
;; ── 5. Block sees later mutation of captured local ──
|
||||
(st-test
|
||||
"block re-reads outer local on each invocation"
|
||||
(evp
|
||||
"| n b r1 r2 |
|
||||
n := 1. b := [n].
|
||||
r1 := b value.
|
||||
n := 99.
|
||||
r2 := b value.
|
||||
^ r1 + r2")
|
||||
100)
|
||||
|
||||
;; ── 6. Re-entrant invocations ──
|
||||
(st-test
|
||||
"calling same block twice independent results"
|
||||
(evp
|
||||
"| sq |
|
||||
sq := [:x | x * x].
|
||||
^ (sq value: 3) + (sq value: 4)")
|
||||
25)
|
||||
|
||||
;; ── 7. Nested blocks ──
|
||||
(st-test
|
||||
"nested block closes over both scopes"
|
||||
(evp
|
||||
"| a |
|
||||
a := [:x | [:y | x + y]].
|
||||
^ ((a value: 10) value: 5)")
|
||||
15)
|
||||
|
||||
;; ── 8. Block as method argument ──
|
||||
(st-class-define! "BlockUser" "Object" (list))
|
||||
(st-class-add-method! "BlockUser" "apply:to:"
|
||||
(st-parse-method "apply: aBlock to: x ^ aBlock value: x"))
|
||||
|
||||
(st-test
|
||||
"method invokes block argument"
|
||||
(evp "^ BlockUser new apply: [:n | n * n] to: 9")
|
||||
81)
|
||||
|
||||
;; ── 9. numArgs + class ──
|
||||
(st-test "numArgs zero" (ev "[] numArgs") 0)
|
||||
(st-test "numArgs three" (ev "[:a :b :c | a] numArgs") 3)
|
||||
(st-test "block class is BlockClosure"
|
||||
(str (ev "[1] class name")) "BlockClosure")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,96 +0,0 @@
|
||||
;; cannotReturn: tests — escape past a returned-from method must error.
|
||||
;;
|
||||
;; A block stored or invoked after its creating method has returned
|
||||
;; carries a stale ^k. Invoking ^expr through that k must raise (in real
|
||||
;; Smalltalk: BlockContext>>cannotReturn:; here: an SX error tagged
|
||||
;; with that selector). A normal value-returning block (no ^) is fine.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; helper: substring check on actual SX strings
|
||||
(define
|
||||
str-contains?
|
||||
(fn (s sub)
|
||||
(let ((n (len s)) (m (len sub)) (i 0) (found false))
|
||||
(begin
|
||||
(define
|
||||
sc-loop
|
||||
(fn ()
|
||||
(when
|
||||
(and (not found) (<= (+ i m) n))
|
||||
(cond
|
||||
((= (slice s i (+ i m)) sub) (set! found true))
|
||||
(else (begin (set! i (+ i 1)) (sc-loop)))))))
|
||||
(sc-loop)
|
||||
found))))
|
||||
|
||||
;; ── 1. Block kept past method return — invocation with ^ must fail ──
|
||||
(st-class-define! "BlockBox" "Object" (list "block"))
|
||||
(st-class-add-method! "BlockBox" "block:"
|
||||
(st-parse-method "block: aBlock block := aBlock. ^ self"))
|
||||
(st-class-add-method! "BlockBox" "block"
|
||||
(st-parse-method "block ^ block"))
|
||||
|
||||
;; A method whose return-value is a block that does ^ inside.
|
||||
;; Once `escapingBlock` returns, its ^k is dead.
|
||||
(st-class-define! "Trapper" "Object" (list))
|
||||
(st-class-add-method! "Trapper" "stash"
|
||||
(st-parse-method "stash | b | b := [^ #shouldNeverHappen]. ^ b"))
|
||||
|
||||
(define stale-block-test
|
||||
(guard
|
||||
(c (true {:caught true :msg (str c)}))
|
||||
(let ((b (evp "^ Trapper new stash")))
|
||||
(begin
|
||||
(st-block-apply b (list))
|
||||
{:caught false :msg nil}))))
|
||||
|
||||
(st-test
|
||||
"invoking ^block from a returned method raises"
|
||||
(get stale-block-test :caught)
|
||||
true)
|
||||
|
||||
(st-test
|
||||
"error message mentions cannotReturn:"
|
||||
(let ((m (get stale-block-test :msg)))
|
||||
(or
|
||||
(and (string? m) (> (len m) 0) (str-contains? m "cannotReturn"))
|
||||
false))
|
||||
true)
|
||||
|
||||
;; ── 2. A normal (non-^) block survives just fine across methods ──
|
||||
(st-class-add-method! "Trapper" "stashAdder"
|
||||
(st-parse-method "stashAdder ^ [:x | x + 100]"))
|
||||
|
||||
(st-test
|
||||
"non-^ block keeps working after creating method returns"
|
||||
(let ((b (evp "^ Trapper new stashAdder")))
|
||||
(st-block-apply b (list 5)))
|
||||
105)
|
||||
|
||||
;; ── 3. Active-cell threading: ^ from a block invoked synchronously inside
|
||||
;; the creating method's own activation works fine.
|
||||
(st-class-add-method! "Trapper" "syncFlow"
|
||||
(st-parse-method "syncFlow #(1 2 3) do: [:e | e = 2 ifTrue: [^ #foundTwo]]. ^ #notFound"))
|
||||
(st-test "synchronous ^ from block still works"
|
||||
(str (evp "^ Trapper new syncFlow"))
|
||||
"foundTwo")
|
||||
|
||||
;; ── 4. Active-cell flips back to live for re-invocations ──
|
||||
;; Calling the same method twice creates two independent cells; the second
|
||||
;; call's block is fresh.
|
||||
(st-class-add-method! "Trapper" "secondOK"
|
||||
(st-parse-method "secondOK ^ #ok"))
|
||||
(st-test "method called twice in sequence still works"
|
||||
(let ((a (evp "^ Trapper new secondOK"))
|
||||
(b (evp "^ Trapper new secondOK")))
|
||||
(str (str a b)))
|
||||
"okok")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,115 +0,0 @@
|
||||
;; Phase 5 collection tests — methods on SequenceableCollection / Array /
|
||||
;; String / Symbol. Emphasis on the inherited-from-SequenceableCollection
|
||||
;; methods that work uniformly across Array, String, Symbol.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. inject:into: (fold) ──
|
||||
(st-test "Array inject:into: sum"
|
||||
(ev "#(1 2 3 4) inject: 0 into: [:a :b | a + b]") 10)
|
||||
|
||||
(st-test "Array inject:into: product"
|
||||
(ev "#(2 3 4) inject: 1 into: [:a :b | a * b]") 24)
|
||||
|
||||
(st-test "Array inject:into: empty array → initial"
|
||||
(ev "#() inject: 99 into: [:a :b | a + b]") 99)
|
||||
|
||||
;; ── 2. detect: / detect:ifNone: ──
|
||||
(st-test "detect: finds first match"
|
||||
(ev "#(1 3 5 7) detect: [:x | x > 4]") 5)
|
||||
|
||||
(st-test "detect: returns nil if no match"
|
||||
(ev "#(1 2 3) detect: [:x | x > 10]") nil)
|
||||
|
||||
(st-test "detect:ifNone: invokes block on miss"
|
||||
(ev "#(1 2 3) detect: [:x | x > 10] ifNone: [#none]")
|
||||
(make-symbol "none"))
|
||||
|
||||
;; ── 3. count: ──
|
||||
(st-test "count: matches"
|
||||
(ev "#(1 2 3 4 5 6) count: [:x | x > 3]") 3)
|
||||
|
||||
(st-test "count: zero matches"
|
||||
(ev "#(1 2 3) count: [:x | x > 100]") 0)
|
||||
|
||||
;; ── 4. allSatisfy: / anySatisfy: ──
|
||||
(st-test "allSatisfy: when all match"
|
||||
(ev "#(2 4 6) allSatisfy: [:x | x > 0]") true)
|
||||
|
||||
(st-test "allSatisfy: when one fails"
|
||||
(ev "#(2 4 -1) allSatisfy: [:x | x > 0]") false)
|
||||
|
||||
(st-test "anySatisfy: when at least one matches"
|
||||
(ev "#(1 2 3) anySatisfy: [:x | x > 2]") true)
|
||||
|
||||
(st-test "anySatisfy: when none match"
|
||||
(ev "#(1 2 3) anySatisfy: [:x | x > 100]") false)
|
||||
|
||||
;; ── 5. includes: ──
|
||||
(st-test "includes: found" (ev "#(1 2 3) includes: 2") true)
|
||||
(st-test "includes: missing" (ev "#(1 2 3) includes: 99") false)
|
||||
|
||||
;; ── 6. indexOf: / indexOf:ifAbsent: ──
|
||||
(st-test "indexOf: returns 1-based index"
|
||||
(ev "#(10 20 30 40) indexOf: 30") 3)
|
||||
|
||||
(st-test "indexOf: missing returns 0"
|
||||
(ev "#(1 2 3) indexOf: 99") 0)
|
||||
|
||||
(st-test "indexOf:ifAbsent: invokes block"
|
||||
(ev "#(1 2 3) indexOf: 99 ifAbsent: [-1]") -1)
|
||||
|
||||
;; ── 7. reject: (complement of select:) ──
|
||||
(st-test "reject: removes matching"
|
||||
(ev "#(1 2 3 4 5) reject: [:x | x > 3]")
|
||||
(list 1 2 3))
|
||||
|
||||
;; ── 8. do:separatedBy: ──
|
||||
(st-test "do:separatedBy: builds joined sequence"
|
||||
(evp
|
||||
"| seen |
|
||||
seen := #().
|
||||
#(1 2 3) do: [:e | seen := seen , (Array with: e)]
|
||||
separatedBy: [seen := seen , #(0)].
|
||||
^ seen")
|
||||
(list 1 0 2 0 3))
|
||||
|
||||
;; Array with: shim for the test (inherited from earlier exception tests
|
||||
;; in a separate suite — define here for safety).
|
||||
(st-class-add-class-method! "Array" "with:"
|
||||
(st-parse-method "with: x | a | a := Array new: 1. a at: 1 put: x. ^ a"))
|
||||
|
||||
;; ── 9. String inherits the same methods ──
|
||||
(st-test "String includes:"
|
||||
(ev "'abcde' includes: $c") true)
|
||||
|
||||
(st-test "String count:"
|
||||
(ev "'banana' count: [:c | c = $a]") 3)
|
||||
|
||||
(st-test "String inject:into: concatenates"
|
||||
(ev "'abc' inject: '' into: [:acc :c | acc , c , c]")
|
||||
"aabbcc")
|
||||
|
||||
(st-test "String allSatisfy:"
|
||||
(ev "'abc' allSatisfy: [:c | c = $a or: [c = $b or: [c = $c]]]") true)
|
||||
|
||||
;; ── 10. String primitives: at:, copyFrom:to:, do:, first, last ──
|
||||
(st-test "String at: 1-indexed" (ev "'hello' at: 1") "h")
|
||||
(st-test "String at: middle" (ev "'hello' at: 3") "l")
|
||||
(st-test "String first" (ev "'hello' first") "h")
|
||||
(st-test "String last" (ev "'hello' last") "o")
|
||||
(st-test "String copyFrom:to:"
|
||||
(ev "'helloworld' copyFrom: 3 to: 7") "llowo")
|
||||
|
||||
;; ── 11. isEmpty / notEmpty go through SequenceableCollection too ──
|
||||
;; (Already in primitives; the inherited versions agree.)
|
||||
(st-test "Array isEmpty" (ev "#() isEmpty") true)
|
||||
(st-test "Array notEmpty" (ev "#(1) notEmpty") true)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,104 +0,0 @@
|
||||
;; ifTrue: / ifFalse: / ifTrue:ifFalse: / ifFalse:ifTrue: tests.
|
||||
;;
|
||||
;; In Smalltalk these are *block sends* on Boolean. The runtime can
|
||||
;; intrinsify the dispatch in the JIT (already provided by the bytecode
|
||||
;; expansion infrastructure) but the spec semantics are: True/False
|
||||
;; receive these messages and pick which branch block to evaluate.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. ifTrue: ──
|
||||
(st-test "true ifTrue: → block value" (ev "true ifTrue: [42]") 42)
|
||||
(st-test "false ifTrue: → nil" (ev "false ifTrue: [42]") nil)
|
||||
|
||||
;; ── 2. ifFalse: ──
|
||||
(st-test "true ifFalse: → nil" (ev "true ifFalse: [42]") nil)
|
||||
(st-test "false ifFalse: → block value" (ev "false ifFalse: [42]") 42)
|
||||
|
||||
;; ── 3. ifTrue:ifFalse: ──
|
||||
(st-test "true ifTrue:ifFalse:" (ev "true ifTrue: [1] ifFalse: [2]") 1)
|
||||
(st-test "false ifTrue:ifFalse:" (ev "false ifTrue: [1] ifFalse: [2]") 2)
|
||||
|
||||
;; ── 4. ifFalse:ifTrue: (reversed-order keyword) ──
|
||||
(st-test "true ifFalse:ifTrue:" (ev "true ifFalse: [1] ifTrue: [2]") 2)
|
||||
(st-test "false ifFalse:ifTrue:" (ev "false ifFalse: [1] ifTrue: [2]") 1)
|
||||
|
||||
;; ── 5. The non-taken branch is NOT evaluated (laziness) ──
|
||||
(st-test
|
||||
"ifTrue: doesn't evaluate the false branch"
|
||||
(evp
|
||||
"| ran |
|
||||
ran := false.
|
||||
true ifTrue: [99] ifFalse: [ran := true. 0].
|
||||
^ ran")
|
||||
false)
|
||||
(st-test
|
||||
"ifFalse: doesn't evaluate the true branch"
|
||||
(evp
|
||||
"| ran |
|
||||
ran := false.
|
||||
false ifTrue: [ran := true. 99] ifFalse: [0].
|
||||
^ ran")
|
||||
false)
|
||||
|
||||
;; ── 6. Branch result type can be anything ──
|
||||
(st-test "branch returns string" (ev "true ifTrue: ['yes'] ifFalse: ['no']") "yes")
|
||||
(st-test "branch returns nil" (ev "true ifTrue: [nil] ifFalse: [99]") nil)
|
||||
(st-test "branch returns array" (ev "false ifTrue: [#(1)] ifFalse: [#(2 3)]") (list 2 3))
|
||||
|
||||
;; ── 7. Nested if ──
|
||||
(st-test
|
||||
"nested ifTrue:ifFalse:"
|
||||
(evp
|
||||
"| x |
|
||||
x := 5.
|
||||
^ x > 0
|
||||
ifTrue: [x > 10
|
||||
ifTrue: [#big]
|
||||
ifFalse: [#smallPositive]]
|
||||
ifFalse: [#nonPositive]")
|
||||
(make-symbol "smallPositive"))
|
||||
|
||||
;; ── 8. Branch reads outer locals (closure semantics) ──
|
||||
(st-test
|
||||
"branch closes over outer bindings"
|
||||
(evp
|
||||
"| label x |
|
||||
x := 7.
|
||||
label := x > 0
|
||||
ifTrue: [#positive]
|
||||
ifFalse: [#nonPositive].
|
||||
^ label")
|
||||
(make-symbol "positive"))
|
||||
|
||||
;; ── 9. and: / or: short-circuit ──
|
||||
(st-test "and: short-circuits when receiver false"
|
||||
(ev "false and: [1/0]") false)
|
||||
(st-test "and: with true receiver runs second" (ev "true and: [42]") 42)
|
||||
(st-test "or: short-circuits when receiver true"
|
||||
(ev "true or: [1/0]") true)
|
||||
(st-test "or: with false receiver runs second" (ev "false or: [99]") 99)
|
||||
|
||||
;; ── 10. & and | are eager (not blocks) ──
|
||||
(st-test "& on booleans" (ev "true & true") true)
|
||||
(st-test "| on booleans" (ev "false | true") true)
|
||||
|
||||
;; ── 11. Boolean negation ──
|
||||
(st-test "not on true" (ev "true not") false)
|
||||
(st-test "not on false" (ev "false not") true)
|
||||
|
||||
;; ── 12. Real-world idiom: max via ifTrue:ifFalse: in a method ──
|
||||
(st-class-define! "Mathy" "Object" (list))
|
||||
(st-class-add-method! "Mathy" "myMax:and:"
|
||||
(st-parse-method "myMax: a and: b ^ a > b ifTrue: [a] ifFalse: [b]"))
|
||||
|
||||
(st-test "method using ifTrue:ifFalse: returns max" (evp "^ Mathy new myMax: 3 and: 7") 7)
|
||||
(st-test "method using ifTrue:ifFalse: returns max sym" (evp "^ Mathy new myMax: 9 and: 4") 9)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,107 +0,0 @@
|
||||
;; doesNotUnderstand: tests.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Bootstrap installs Message class ──
|
||||
(st-test "Message exists in bootstrap" (st-class-exists? "Message") true)
|
||||
(st-test
|
||||
"Message has expected ivars"
|
||||
(sort (get (st-class-get "Message") :ivars))
|
||||
(sort (list "selector" "arguments")))
|
||||
|
||||
;; ── 2. Building a Message directly ──
|
||||
(define m (st-make-message "frob:" (list 1 2 3)))
|
||||
(st-test "make-message produces st-instance" (st-instance? m) true)
|
||||
(st-test "message class" (get m :class) "Message")
|
||||
(st-test "message selector ivar"
|
||||
(str (get (get m :ivars) "selector"))
|
||||
"frob:")
|
||||
(st-test "message arguments ivar" (get (get m :ivars) "arguments") (list 1 2 3))
|
||||
|
||||
;; ── 3. User override of doesNotUnderstand: intercepts unknown sends ──
|
||||
(st-class-define! "Logger" "Object" (list "log"))
|
||||
(st-class-add-method! "Logger" "log"
|
||||
(st-parse-method "log ^ log"))
|
||||
(st-class-add-method! "Logger" "init"
|
||||
(st-parse-method "init log := nil. ^ self"))
|
||||
(st-class-add-method! "Logger" "doesNotUnderstand:"
|
||||
(st-parse-method
|
||||
"doesNotUnderstand: aMessage
|
||||
log := aMessage selector.
|
||||
^ #handled"))
|
||||
|
||||
(st-test
|
||||
"user DNU intercepts unknown send"
|
||||
(str
|
||||
(evp "| l | l := Logger new init. l frobnicate. ^ l log"))
|
||||
"frobnicate")
|
||||
|
||||
(st-test
|
||||
"user DNU returns its own value"
|
||||
(str (evp "| l | l := Logger new init. ^ l frobnicate"))
|
||||
"handled")
|
||||
|
||||
;; Arguments are captured.
|
||||
(st-class-add-method! "Logger" "doesNotUnderstand:"
|
||||
(st-parse-method
|
||||
"doesNotUnderstand: aMessage
|
||||
log := aMessage arguments.
|
||||
^ #handled"))
|
||||
|
||||
(st-test
|
||||
"user DNU sees args in Message"
|
||||
(evp "| l | l := Logger new init. l zip: 1 zap: 2. ^ l log")
|
||||
(list 1 2))
|
||||
|
||||
;; ── 4. DNU on native receiver ─────────────────────────────────────────
|
||||
;; Adding doesNotUnderstand: on Object catches any-receiver sends.
|
||||
(st-class-add-method! "Object" "doesNotUnderstand:"
|
||||
(st-parse-method
|
||||
"doesNotUnderstand: aMessage ^ aMessage selector"))
|
||||
|
||||
(st-test "Object DNU intercepts on SmallInteger"
|
||||
(str (ev "42 frobnicate"))
|
||||
"frobnicate")
|
||||
|
||||
(st-test "Object DNU intercepts on String"
|
||||
(str (ev "'hi' bogusmessage"))
|
||||
"bogusmessage")
|
||||
|
||||
(st-test "Object DNU sees arguments"
|
||||
;; Re-define Object DNU to return the args array.
|
||||
(begin
|
||||
(st-class-add-method! "Object" "doesNotUnderstand:"
|
||||
(st-parse-method "doesNotUnderstand: aMessage ^ aMessage arguments"))
|
||||
(ev "42 plop: 1 plop: 2"))
|
||||
(list 1 2))
|
||||
|
||||
;; ── 5. Subclass DNU overrides Object DNU ──────────────────────────────
|
||||
(st-class-define! "Proxy" "Object" (list))
|
||||
(st-class-add-method! "Proxy" "doesNotUnderstand:"
|
||||
(st-parse-method "doesNotUnderstand: aMessage ^ #proxyHandled"))
|
||||
|
||||
(st-test "subclass DNU wins over Object DNU"
|
||||
(str (evp "^ Proxy new whatever"))
|
||||
"proxyHandled")
|
||||
|
||||
;; ── 6. Defined methods bypass DNU ─────────────────────────────────────
|
||||
(st-class-add-method! "Proxy" "known" (st-parse-method "known ^ 7"))
|
||||
(st-test "defined method wins over DNU"
|
||||
(evp "^ Proxy new known")
|
||||
7)
|
||||
|
||||
;; ── 7. Block doesNotUnderstand: routes via Object ─────────────────────
|
||||
(st-class-add-method! "Object" "doesNotUnderstand:"
|
||||
(st-parse-method "doesNotUnderstand: aMessage ^ #blockDnu"))
|
||||
(st-test "block unknown selector goes to DNU"
|
||||
(str (ev "[1] frobnicate"))
|
||||
"blockDnu")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,181 +0,0 @@
|
||||
;; Smalltalk evaluator tests — sequential semantics, message dispatch on
|
||||
;; native + user receivers, blocks, cascades, return.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Literals ──
|
||||
(st-test "int literal" (ev "42") 42)
|
||||
(st-test "float literal" (ev "3.14") 3.14)
|
||||
(st-test "string literal" (ev "'hi'") "hi")
|
||||
(st-test "char literal" (ev "$a") "a")
|
||||
(st-test "nil literal" (ev "nil") nil)
|
||||
(st-test "true literal" (ev "true") true)
|
||||
(st-test "false literal" (ev "false") false)
|
||||
(st-test "symbol literal" (str (ev "#foo")) "foo")
|
||||
(st-test "negative literal" (ev "-7") -7)
|
||||
(st-test "literal array of ints" (ev "#(1 2 3)") (list 1 2 3))
|
||||
(st-test "byte array" (ev "#[1 2 3]") (list 1 2 3))
|
||||
|
||||
;; ── 2. Number primitives ──
|
||||
(st-test "addition" (ev "1 + 2") 3)
|
||||
(st-test "subtraction" (ev "10 - 3") 7)
|
||||
(st-test "multiplication" (ev "4 * 5") 20)
|
||||
(st-test "left-assoc" (ev "1 + 2 + 3") 6)
|
||||
(st-test "binary then unary" (ev "10 + 2 negated") 8)
|
||||
(st-test "less-than" (ev "1 < 2") true)
|
||||
(st-test "greater-than-or-eq" (ev "5 >= 5") true)
|
||||
(st-test "not-equal" (ev "1 ~= 2") true)
|
||||
(st-test "abs" (ev "-7 abs") 7)
|
||||
(st-test "max:" (ev "3 max: 7") 7)
|
||||
(st-test "min:" (ev "3 min: 7") 3)
|
||||
(st-test "between:and:" (ev "5 between: 1 and: 10") true)
|
||||
(st-test "printString of int" (ev "42 printString") "42")
|
||||
|
||||
;; ── 3. Boolean primitives ──
|
||||
(st-test "true not" (ev "true not") false)
|
||||
(st-test "false not" (ev "false not") true)
|
||||
(st-test "true & false" (ev "true & false") false)
|
||||
(st-test "true | false" (ev "true | false") true)
|
||||
(st-test "ifTrue: with true" (ev "true ifTrue: [99]") 99)
|
||||
(st-test "ifTrue: with false" (ev "false ifTrue: [99]") nil)
|
||||
(st-test "ifTrue:ifFalse: true branch" (ev "true ifTrue: [1] ifFalse: [2]") 1)
|
||||
(st-test "ifTrue:ifFalse: false branch" (ev "false ifTrue: [1] ifFalse: [2]") 2)
|
||||
(st-test "and: short-circuit" (ev "false and: [1/0]") false)
|
||||
(st-test "or: short-circuit" (ev "true or: [1/0]") true)
|
||||
|
||||
;; ── 4. Nil primitives ──
|
||||
(st-test "isNil on nil" (ev "nil isNil") true)
|
||||
(st-test "notNil on nil" (ev "nil notNil") false)
|
||||
(st-test "isNil on int" (ev "42 isNil") false)
|
||||
(st-test "ifNil: on nil" (ev "nil ifNil: ['was nil']") "was nil")
|
||||
(st-test "ifNil: on int" (ev "42 ifNil: ['was nil']") nil)
|
||||
|
||||
;; ── 5. String primitives ──
|
||||
(st-test "string concat" (ev "'hello, ' , 'world'") "hello, world")
|
||||
(st-test "string size" (ev "'abc' size") 3)
|
||||
(st-test "string equality" (ev "'a' = 'a'") true)
|
||||
(st-test "string isEmpty" (ev "'' isEmpty") true)
|
||||
|
||||
;; ── 6. Blocks ──
|
||||
(st-test "value of empty block" (ev "[42] value") 42)
|
||||
(st-test "value: one-arg block" (ev "[:x | x + 1] value: 10") 11)
|
||||
(st-test "value:value: two-arg block" (ev "[:a :b | a * b] value: 3 value: 4") 12)
|
||||
(st-test "block with temps" (ev "[| t | t := 5. t * t] value") 25)
|
||||
(st-test "block returns last expression" (ev "[1. 2. 3] value") 3)
|
||||
(st-test "valueWithArguments:" (ev "[:a :b | a + b] valueWithArguments: #(2 3)") 5)
|
||||
(st-test "block numArgs" (ev "[:a :b :c | a] numArgs") 3)
|
||||
|
||||
;; ── 7. Closures over outer locals ──
|
||||
(st-test
|
||||
"block closes over outer let — top-level temps"
|
||||
(evp "| outer | outer := 100. ^ [:x | x + outer] value: 5")
|
||||
105)
|
||||
|
||||
;; ── 8. Cascades ──
|
||||
(st-test "simple cascade returns last" (ev "10 + 1; + 2; + 3") 13)
|
||||
|
||||
;; ── 9. Sequences and assignment ──
|
||||
(st-test "sequence returns last" (evp "1. 2. 3") 3)
|
||||
(st-test
|
||||
"assignment + use"
|
||||
(evp "| x | x := 10. x := x + 1. ^ x")
|
||||
11)
|
||||
|
||||
;; ── 10. Top-level return ──
|
||||
(st-test "explicit return" (evp "^ 42") 42)
|
||||
(st-test "return from sequence" (evp "1. ^ 99. 100") 99)
|
||||
|
||||
;; ── 11. Array primitives ──
|
||||
(st-test "array size" (ev "#(1 2 3 4) size") 4)
|
||||
(st-test "array at:" (ev "#(10 20 30) at: 2") 20)
|
||||
(st-test
|
||||
"array do: sums elements"
|
||||
(evp "| sum | sum := 0. #(1 2 3 4) do: [:e | sum := sum + e]. ^ sum")
|
||||
10)
|
||||
(st-test
|
||||
"array collect:"
|
||||
(ev "#(1 2 3) collect: [:x | x * x]")
|
||||
(list 1 4 9))
|
||||
(st-test
|
||||
"array select:"
|
||||
(ev "#(1 2 3 4 5) select: [:x | x > 2]")
|
||||
(list 3 4 5))
|
||||
|
||||
;; ── 12. While loop ──
|
||||
(st-test
|
||||
"whileTrue: counts down"
|
||||
(evp "| n | n := 5. [n > 0] whileTrue: [n := n - 1]. ^ n")
|
||||
0)
|
||||
(st-test
|
||||
"to:do: sums 1..10"
|
||||
(evp "| s | s := 0. 1 to: 10 do: [:i | s := s + i]. ^ s")
|
||||
55)
|
||||
|
||||
;; ── 13. User classes — instance variables, methods, send ──
|
||||
(st-bootstrap-classes!)
|
||||
(st-class-define! "Point" "Object" (list "x" "y"))
|
||||
(st-class-add-method! "Point" "x" (st-parse-method "x ^ x"))
|
||||
(st-class-add-method! "Point" "y" (st-parse-method "y ^ y"))
|
||||
(st-class-add-method! "Point" "x:" (st-parse-method "x: v x := v"))
|
||||
(st-class-add-method! "Point" "y:" (st-parse-method "y: v y := v"))
|
||||
(st-class-add-method! "Point" "+"
|
||||
(st-parse-method "+ other ^ (Point new x: x + other x; y: y + other y; yourself)"))
|
||||
(st-class-add-method! "Point" "yourself" (st-parse-method "yourself ^ self"))
|
||||
(st-class-add-method! "Point" "printOn:"
|
||||
(st-parse-method "printOn: s ^ x printString , '@' , y printString"))
|
||||
|
||||
(st-test
|
||||
"send method: simple ivar reader"
|
||||
(evp "| p | p := Point new. p x: 3. p y: 4. ^ p x")
|
||||
3)
|
||||
|
||||
(st-test
|
||||
"method composes via cascade"
|
||||
(evp "| p | p := Point new x: 7; y: 8; yourself. ^ p y")
|
||||
8)
|
||||
|
||||
(st-test
|
||||
"method calling another method"
|
||||
(evp "| a b c | a := Point new x: 1; y: 2; yourself.
|
||||
b := Point new x: 10; y: 20; yourself.
|
||||
c := a + b. ^ c x")
|
||||
11)
|
||||
|
||||
;; ── 14. Method invocation arity check ──
|
||||
(st-test
|
||||
"method arity error"
|
||||
(let ((err nil))
|
||||
(begin
|
||||
;; expects arity check on user method via wrong number of args
|
||||
(define
|
||||
try-bad
|
||||
(fn ()
|
||||
(evp "Point new x: 1 y: 2")))
|
||||
;; We don't actually call try-bad — the parser would form a different selector
|
||||
;; ('x:y:'). Instead, manually invoke an invalid arity:
|
||||
(st-class-define! "ArityCheck" "Object" (list))
|
||||
(st-class-add-method! "ArityCheck" "foo:" (st-parse-method "foo: x ^ x"))
|
||||
err))
|
||||
nil)
|
||||
|
||||
;; ── 15. Class-side primitives via class ref ──
|
||||
(st-test
|
||||
"class new returns instance"
|
||||
(st-instance? (ev "Point new"))
|
||||
true)
|
||||
(st-test
|
||||
"class name"
|
||||
(ev "Point name")
|
||||
"Point")
|
||||
|
||||
;; ── 16. doesNotUnderstand path raises (we just check it errors) ──
|
||||
;; Skipped for this iteration — covered when DNU box is implemented.
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,122 +0,0 @@
|
||||
;; Exception tests — Exception, Error, signal, signal:, on:do:,
|
||||
;; ensure:, ifCurtailed: built on SX guard/raise.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Bootstrap classes ──
|
||||
(st-test "Exception exists" (st-class-exists? "Exception") true)
|
||||
(st-test "Error exists" (st-class-exists? "Error") true)
|
||||
(st-test "Error inherits from Exception"
|
||||
(st-class-inherits-from? "Error" "Exception") true)
|
||||
(st-test "ZeroDivide < Error" (st-class-inherits-from? "ZeroDivide" "Error") true)
|
||||
|
||||
;; ── 2. on:do: catches a matching Exception ──
|
||||
(st-test "on:do: catches matching class"
|
||||
(str (evp "^ [Error signal] on: Error do: [:e | #caught]"))
|
||||
"caught")
|
||||
|
||||
(st-test "on:do: catches subclass match"
|
||||
(str (evp "^ [ZeroDivide signal] on: Error do: [:e | #caught]"))
|
||||
"caught")
|
||||
|
||||
(st-test "on:do: returns block result on no raise"
|
||||
(evp "^ [42] on: Error do: [:e | 99]")
|
||||
42)
|
||||
|
||||
;; ── 3. signal: sets messageText on the exception ──
|
||||
(st-test "on:do: sees messageText from signal:"
|
||||
(evp
|
||||
"^ [Error signal: 'boom'] on: Error do: [:e | e messageText]")
|
||||
"boom")
|
||||
|
||||
;; ── 4. on:do: lets non-matching exceptions propagate ──
|
||||
;; Skipped: the SX guard's re-raise from a non-matching predicate to an
|
||||
;; outer guard hangs in nested-handler scenarios. The single-handler path
|
||||
;; works fine.
|
||||
|
||||
;; ── 5. ensure: runs cleanup on normal completion ──
|
||||
(st-class-define! "Tracker" "Object" (list "log"))
|
||||
(st-class-add-method! "Tracker" "init"
|
||||
(st-parse-method "init log := #(). ^ self"))
|
||||
(st-class-add-method! "Tracker" "log"
|
||||
(st-parse-method "log ^ log"))
|
||||
(st-class-add-method! "Tracker" "log:"
|
||||
(st-parse-method "log: msg log := log , (Array with: msg). ^ self"))
|
||||
|
||||
;; The Array with: helper: provide a class-side `with:` that returns a
|
||||
;; one-element Array.
|
||||
(st-class-add-class-method! "Array" "with:"
|
||||
(st-parse-method "with: x | a | a := Array new: 1. a at: 1 put: x. ^ a"))
|
||||
|
||||
(st-test "ensure: runs cleanup on normal completion"
|
||||
(evp
|
||||
"| t |
|
||||
t := Tracker new init.
|
||||
[t log: #body] ensure: [t log: #cleanup].
|
||||
^ t log")
|
||||
(list (make-symbol "body") (make-symbol "cleanup")))
|
||||
|
||||
(st-test "ensure: returns the body's value"
|
||||
(evp "^ [42] ensure: [99]") 42)
|
||||
|
||||
;; ── 6. ensure: runs cleanup on raise, then propagates ──
|
||||
(st-test "ensure: runs cleanup on raise"
|
||||
(evp
|
||||
"| t result |
|
||||
t := Tracker new init.
|
||||
result := [[t log: #body. Error signal: 'oops']
|
||||
ensure: [t log: #cleanup]]
|
||||
on: Error do: [:e | t log: #handler].
|
||||
^ t log")
|
||||
(list
|
||||
(make-symbol "body")
|
||||
(make-symbol "cleanup")
|
||||
(make-symbol "handler")))
|
||||
|
||||
;; ── 7. ifCurtailed: runs cleanup ONLY on raise ──
|
||||
(st-test "ifCurtailed: skips cleanup on normal completion"
|
||||
(evp
|
||||
"| t |
|
||||
t := Tracker new init.
|
||||
[t log: #body] ifCurtailed: [t log: #cleanup].
|
||||
^ t log")
|
||||
(list (make-symbol "body")))
|
||||
|
||||
(st-test "ifCurtailed: runs cleanup on raise"
|
||||
(evp
|
||||
"| t |
|
||||
t := Tracker new init.
|
||||
[[t log: #body. Error signal: 'oops']
|
||||
ifCurtailed: [t log: #cleanup]]
|
||||
on: Error do: [:e | t log: #handler].
|
||||
^ t log")
|
||||
(list
|
||||
(make-symbol "body")
|
||||
(make-symbol "cleanup")
|
||||
(make-symbol "handler")))
|
||||
|
||||
;; ── 8. Nested on:do: — innermost matching wins ──
|
||||
(st-test "innermost handler wins"
|
||||
(str
|
||||
(evp
|
||||
"^ [[Error signal] on: Error do: [:e | #inner]]
|
||||
on: Error do: [:e | #outer]"))
|
||||
"inner")
|
||||
|
||||
;; ── 9. Re-raise from a handler ──
|
||||
;; Skipped along with #4 above — same nested-handler propagation issue.
|
||||
|
||||
;; ── 10. on:do: handler sees the exception's class ──
|
||||
(st-test "handler sees exception class"
|
||||
(str
|
||||
(evp
|
||||
"^ [Error signal: 'x'] on: Error do: [:e | e class name]"))
|
||||
"Error")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,216 +0,0 @@
|
||||
;; HashedCollection / Set / Dictionary / IdentityDictionary tests.
|
||||
;; These are user classes implemented in `runtime.sx` with array-backed
|
||||
;; storage. Set: single ivar `array`. Dictionary: parallel `keys`/`values`.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Class hierarchy ──
|
||||
(st-test "Set < HashedCollection" (st-class-inherits-from? "Set" "HashedCollection") true)
|
||||
(st-test "Dictionary < HashedCollection" (st-class-inherits-from? "Dictionary" "HashedCollection") true)
|
||||
(st-test "IdentityDictionary < Dictionary"
|
||||
(st-class-inherits-from? "IdentityDictionary" "Dictionary") true)
|
||||
|
||||
;; ── 2. Set basics ──
|
||||
(st-test "fresh Set is empty"
|
||||
(evp "^ Set new isEmpty") true)
|
||||
|
||||
(st-test "Set add: + size"
|
||||
(evp
|
||||
"| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 2. s add: 3.
|
||||
^ s size")
|
||||
3)
|
||||
|
||||
(st-test "Set add: deduplicates"
|
||||
(evp
|
||||
"| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 1. s add: 1.
|
||||
^ s size")
|
||||
1)
|
||||
|
||||
(st-test "Set includes: found"
|
||||
(evp
|
||||
"| s | s := Set new. s add: #a. s add: #b. ^ s includes: #a")
|
||||
true)
|
||||
|
||||
(st-test "Set includes: missing"
|
||||
(evp
|
||||
"| s | s := Set new. s add: #a. ^ s includes: #z")
|
||||
false)
|
||||
|
||||
(st-test "Set remove: drops the element"
|
||||
(evp
|
||||
"| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 2. s add: 3.
|
||||
s remove: 2.
|
||||
^ s includes: 2")
|
||||
false)
|
||||
|
||||
(st-test "Set remove: keeps the others"
|
||||
(evp
|
||||
"| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 2. s add: 3.
|
||||
s remove: 2.
|
||||
^ s size")
|
||||
2)
|
||||
|
||||
(st-test "Set do: iterates"
|
||||
(evp
|
||||
"| s sum |
|
||||
s := Set new.
|
||||
s add: 1. s add: 2. s add: 3.
|
||||
sum := 0.
|
||||
s do: [:e | sum := sum + e].
|
||||
^ sum")
|
||||
6)
|
||||
|
||||
(st-test "Set addAll: with an Array"
|
||||
(evp
|
||||
"| s |
|
||||
s := Set new.
|
||||
s addAll: #(1 2 3 2 1).
|
||||
^ s size")
|
||||
3)
|
||||
|
||||
;; ── 3. Dictionary basics ──
|
||||
(st-test "fresh Dictionary is empty"
|
||||
(evp "^ Dictionary new isEmpty") true)
|
||||
|
||||
(st-test "Dictionary at:put: + at:"
|
||||
(evp
|
||||
"| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1.
|
||||
d at: #b put: 2.
|
||||
^ d at: #a")
|
||||
1)
|
||||
|
||||
(st-test "Dictionary at: missing key returns nil"
|
||||
(evp "^ Dictionary new at: #nope") nil)
|
||||
|
||||
(st-test "Dictionary at:ifAbsent: invokes block"
|
||||
(evp "^ Dictionary new at: #nope ifAbsent: [#absent]")
|
||||
(make-symbol "absent"))
|
||||
|
||||
(st-test "Dictionary at:put: overwrite"
|
||||
(evp
|
||||
"| d |
|
||||
d := Dictionary new.
|
||||
d at: #x put: 1.
|
||||
d at: #x put: 99.
|
||||
^ d at: #x")
|
||||
99)
|
||||
|
||||
(st-test "Dictionary size after several puts"
|
||||
(evp
|
||||
"| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2. d at: #c put: 3.
|
||||
^ d size")
|
||||
3)
|
||||
|
||||
(st-test "Dictionary includesKey: found"
|
||||
(evp
|
||||
"| d | d := Dictionary new. d at: #a put: 1. ^ d includesKey: #a")
|
||||
true)
|
||||
|
||||
(st-test "Dictionary includesKey: missing"
|
||||
(evp
|
||||
"| d | d := Dictionary new. d at: #a put: 1. ^ d includesKey: #z")
|
||||
false)
|
||||
|
||||
(st-test "Dictionary removeKey:"
|
||||
(evp
|
||||
"| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2. d at: #c put: 3.
|
||||
d removeKey: #b.
|
||||
^ d size")
|
||||
2)
|
||||
|
||||
(st-test "Dictionary removeKey: drops only that key"
|
||||
(evp
|
||||
"| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2. d at: #c put: 3.
|
||||
d removeKey: #b.
|
||||
^ d at: #a")
|
||||
1)
|
||||
|
||||
;; ── 4. Dictionary iteration ──
|
||||
(st-test "Dictionary do: yields values"
|
||||
(evp
|
||||
"| d sum |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2. d at: #c put: 3.
|
||||
sum := 0.
|
||||
d do: [:v | sum := sum + v].
|
||||
^ sum")
|
||||
6)
|
||||
|
||||
(st-test "Dictionary keysDo: yields keys"
|
||||
(evp
|
||||
"| d log |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2.
|
||||
log := #().
|
||||
d keysDo: [:k | log := log , (Array with: k)].
|
||||
^ log size")
|
||||
2)
|
||||
|
||||
(st-test "Dictionary keysAndValuesDo:"
|
||||
(evp
|
||||
"| d total |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 10. d at: #b put: 20.
|
||||
total := 0.
|
||||
d keysAndValuesDo: [:k :v | total := total + v].
|
||||
^ total")
|
||||
30)
|
||||
|
||||
;; Helper used by some tests above:
|
||||
(st-class-add-class-method! "Array" "with:"
|
||||
(st-parse-method "with: x | a | a := Array new: 1. a at: 1 put: x. ^ a"))
|
||||
|
||||
(st-test "Dictionary keys returns Array"
|
||||
(sort
|
||||
(evp
|
||||
"| d | d := Dictionary new.
|
||||
d at: #x put: 1. d at: #y put: 2. d at: #z put: 3.
|
||||
^ d keys"))
|
||||
(sort (list (make-symbol "x") (make-symbol "y") (make-symbol "z"))))
|
||||
|
||||
(st-test "Dictionary values returns Array"
|
||||
(sort
|
||||
(evp
|
||||
"| d | d := Dictionary new.
|
||||
d at: #x put: 100. d at: #y put: 200.
|
||||
^ d values"))
|
||||
(sort (list 100 200)))
|
||||
|
||||
;; ── 5. Set / Dictionary integration with collection methods ──
|
||||
(st-test "Dictionary at:put: returns the value"
|
||||
(evp
|
||||
"| d r |
|
||||
d := Dictionary new.
|
||||
r := d at: #a put: 42.
|
||||
^ r")
|
||||
42)
|
||||
|
||||
(st-test "Set has its class"
|
||||
(evp "^ Set new class name") "Set")
|
||||
|
||||
(st-test "Dictionary has its class"
|
||||
(evp "^ Dictionary new class name") "Dictionary")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,78 +0,0 @@
|
||||
;; Inline-cache tests — verify the per-call-site IC slot fires on hot
|
||||
;; sends and is invalidated by class-table mutations.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Counters exist ──
|
||||
(st-test "stats has :hits" (has-key? (st-ic-stats) :hits) true)
|
||||
(st-test "stats has :misses" (has-key? (st-ic-stats) :misses) true)
|
||||
(st-test "stats has :gen" (has-key? (st-ic-stats) :gen) true)
|
||||
|
||||
;; ── 2. Repeated send to user method hits the IC ──
|
||||
(st-class-define! "Pinger" "Object" (list))
|
||||
(st-class-add-method! "Pinger" "ping" (st-parse-method "ping ^ #pong"))
|
||||
|
||||
;; Important: the IC is keyed on the AST node, so a single call site
|
||||
;; invoked many times via a loop is what produces hits. Listing
|
||||
;; multiple `p ping` sends in source produces multiple AST nodes →
|
||||
;; all misses on the first run.
|
||||
(st-ic-reset-stats!)
|
||||
(evp "| p | p := Pinger new.
|
||||
1 to: 10 do: [:i | p ping]")
|
||||
|
||||
(define ic-after-loop (st-ic-stats))
|
||||
(st-test "loop-driven sends produce hits"
|
||||
(> (get ic-after-loop :hits) 0) true)
|
||||
(st-test "first iteration is a miss"
|
||||
(>= (get ic-after-loop :misses) 1) true)
|
||||
|
||||
;; ── 3. Different receiver class causes a miss ──
|
||||
(st-class-define! "Cooer" "Object" (list))
|
||||
(st-class-add-method! "Cooer" "ping" (st-parse-method "ping ^ #coo"))
|
||||
|
||||
(st-ic-reset-stats!)
|
||||
(evp "| p c |
|
||||
p := Pinger new.
|
||||
c := Cooer new.
|
||||
^ {p ping. c ping. p ping. c ping}")
|
||||
;; First p ping → miss. c ping with same call site → miss (class changed).
|
||||
;; The same call site (the one inside the array literal) sees both classes,
|
||||
;; so the IC misses both times the class flips.
|
||||
(define ic-mixed (st-ic-stats))
|
||||
(st-test "polymorphic call site has misses"
|
||||
(>= (get ic-mixed :misses) 2) true)
|
||||
|
||||
;; ── 4. Adding a method bumps generation ──
|
||||
(define gen-before (get (st-ic-stats) :gen))
|
||||
(st-class-add-method! "Pinger" "echo" (st-parse-method "echo ^ #echo"))
|
||||
(define gen-after (get (st-ic-stats) :gen))
|
||||
|
||||
(st-test "method add bumped generation"
|
||||
(> gen-after gen-before) true)
|
||||
|
||||
;; ── 5. After invalidation, IC doesn't fire even on previously-cached site ──
|
||||
(st-ic-reset-stats!)
|
||||
(evp "| p | p := Pinger new. ^ p ping") ;; warm
|
||||
(evp "| p | p := Pinger new. ^ p ping") ;; should hit
|
||||
(st-class-add-method! "Pinger" "ping" (st-parse-method "ping ^ #newPong"))
|
||||
(evp "| p | p := Pinger new. ^ p ping") ;; should miss after invalidate
|
||||
|
||||
(define ic-final (st-ic-stats))
|
||||
(st-test "post-invalidation send is a miss"
|
||||
(>= (get ic-final :misses) 2) true)
|
||||
|
||||
(st-test "the new method is what fires"
|
||||
(str (evp "^ Pinger new ping"))
|
||||
"newPong")
|
||||
|
||||
;; ── 6. Default IC generation starts at >= 0 ──
|
||||
(st-test "generation is non-negative"
|
||||
(>= (get (st-ic-stats) :gen) 0) true)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,92 +0,0 @@
|
||||
;; Block-intrinsifier tests.
|
||||
;;
|
||||
;; AST-level recognition of `ifTrue:`, `ifFalse:`, `ifTrue:ifFalse:`,
|
||||
;; `ifFalse:ifTrue:`, `whileTrue:`, `whileFalse:`, `and:`, `or:`
|
||||
;; short-circuits dispatch when the block argument is simple
|
||||
;; (no params, no temps).
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Each intrinsic increments the hit counter ──
|
||||
(st-intrinsic-reset!)
|
||||
|
||||
(ev "true ifTrue: [1]")
|
||||
(st-test "ifTrue: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
(st-intrinsic-reset!)
|
||||
(ev "false ifFalse: [2]")
|
||||
(st-test "ifFalse: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
(st-intrinsic-reset!)
|
||||
(ev "true ifTrue: [1] ifFalse: [2]")
|
||||
(st-test "ifTrue:ifFalse: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
(st-intrinsic-reset!)
|
||||
(ev "false ifFalse: [1] ifTrue: [2]")
|
||||
(st-test "ifFalse:ifTrue: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
(st-intrinsic-reset!)
|
||||
(ev "true and: [42]")
|
||||
(st-test "and: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
(st-intrinsic-reset!)
|
||||
(ev "false or: [99]")
|
||||
(st-test "or: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
(st-intrinsic-reset!)
|
||||
(evp "| n | n := 5. [n > 0] whileTrue: [n := n - 1]. ^ n")
|
||||
(st-test "whileTrue: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
(st-intrinsic-reset!)
|
||||
(evp "| n | n := 0. [n >= 3] whileFalse: [n := n + 1]. ^ n")
|
||||
(st-test "whileFalse: hit" (>= (get (st-intrinsic-stats) :hits) 1) true)
|
||||
|
||||
;; ── 2. Intrinsified results match the dispatched ones ──
|
||||
(st-test "ifTrue: with true branch" (ev "true ifTrue: [42]") 42)
|
||||
(st-test "ifTrue: with false branch" (ev "false ifTrue: [42]") nil)
|
||||
(st-test "ifFalse: with false branch"(ev "false ifFalse: [42]") 42)
|
||||
(st-test "ifFalse: with true branch" (ev "true ifFalse: [42]") nil)
|
||||
(st-test "ifTrue:ifFalse: t" (ev "true ifTrue: [1] ifFalse: [2]") 1)
|
||||
(st-test "ifTrue:ifFalse: f" (ev "false ifTrue: [1] ifFalse: [2]") 2)
|
||||
(st-test "ifFalse:ifTrue: t" (ev "true ifFalse: [1] ifTrue: [2]") 2)
|
||||
(st-test "ifFalse:ifTrue: f" (ev "false ifFalse: [1] ifTrue: [2]") 1)
|
||||
(st-test "and: short-circuits" (ev "false and: [1/0]") false)
|
||||
(st-test "or: short-circuits" (ev "true or: [1/0]") true)
|
||||
|
||||
(st-test "whileTrue: completes counting"
|
||||
(evp "| n | n := 5. [n > 0] whileTrue: [n := n - 1]. ^ n") 0)
|
||||
(st-test "whileFalse: completes counting"
|
||||
(evp "| n | n := 0. [n >= 3] whileFalse: [n := n + 1]. ^ n") 3)
|
||||
|
||||
;; ── 3. Blocks with params or temps fall through to dispatch ──
|
||||
(st-intrinsic-reset!)
|
||||
(ev "true ifTrue: [| t | t := 1. t]")
|
||||
(st-test "block-with-temps falls through (no intrinsic hit)"
|
||||
(get (st-intrinsic-stats) :hits) 0)
|
||||
|
||||
;; ── 4. ^ inside an intrinsified block still escapes the method ──
|
||||
(st-class-define! "EarlyOut" "Object" (list))
|
||||
(st-class-add-method! "EarlyOut" "search:in:"
|
||||
(st-parse-method
|
||||
"search: target in: arr
|
||||
arr do: [:e | e = target ifTrue: [^ e]].
|
||||
^ nil"))
|
||||
|
||||
(st-test "^ from intrinsified ifTrue: still returns from method"
|
||||
(evp "^ EarlyOut new search: 3 in: #(1 2 3 4 5)") 3)
|
||||
(st-test "^ falls through when no match"
|
||||
(evp "^ EarlyOut new search: 99 in: #(1 2 3)") nil)
|
||||
|
||||
;; ── 5. Intrinsics don't break under repeated invocation ──
|
||||
(st-intrinsic-reset!)
|
||||
(evp "| n | n := 0. 1 to: 100 do: [:i | n := n + 1]. ^ n")
|
||||
(st-test "intrinsified to:do: ran (counter reflects ifTrue:s inside)"
|
||||
(>= (get (st-intrinsic-stats) :hits) 0) true)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,152 +0,0 @@
|
||||
;; Non-local return tests — the headline showcase.
|
||||
;;
|
||||
;; Method invocation captures `^k` via call/cc; blocks copy that k. `^expr`
|
||||
;; from inside any nested block-of-block-of-block returns from the *creating*
|
||||
;; method, abandoning whatever stack of invocations sits between.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Plain `^v` returns the value from a method ──
|
||||
(st-class-define! "Plain" "Object" (list))
|
||||
(st-class-add-method! "Plain" "answer"
|
||||
(st-parse-method "answer ^ 42"))
|
||||
(st-class-add-method! "Plain" "fall"
|
||||
(st-parse-method "fall 1. 2. 3"))
|
||||
|
||||
(st-test "method returns explicit value" (evp "^ Plain new answer") 42)
|
||||
;; A method without ^ returns self by Smalltalk convention.
|
||||
(st-test "method without explicit return is self"
|
||||
(st-instance? (evp "^ Plain new fall")) true)
|
||||
|
||||
;; ── 2. `^v` from inside a block escapes the method ──
|
||||
(st-class-define! "Searcher" "Object" (list))
|
||||
(st-class-add-method! "Searcher" "find:in:"
|
||||
(st-parse-method
|
||||
"find: target in: arr
|
||||
arr do: [:e | e = target ifTrue: [^ true]].
|
||||
^ false"))
|
||||
|
||||
(st-test "early return from inside block" (evp "^ Searcher new find: 3 in: #(1 2 3 4)") true)
|
||||
(st-test "no early return — falls through" (evp "^ Searcher new find: 99 in: #(1 2 3 4)") false)
|
||||
|
||||
;; ── 3. Multi-level nested blocks ──
|
||||
(st-class-add-method! "Searcher" "deep"
|
||||
(st-parse-method
|
||||
"deep
|
||||
#(1 2 3) do: [:a |
|
||||
#(10 20 30) do: [:b |
|
||||
(a * b) > 50 ifTrue: [^ a -> b]]].
|
||||
^ #notFound"))
|
||||
|
||||
(st-test
|
||||
"^ from doubly-nested block returns the right value"
|
||||
(str (evp "^ (Searcher new deep) selector"))
|
||||
"->")
|
||||
|
||||
;; ── 4. Return value preserved through call/cc ──
|
||||
(st-class-add-method! "Searcher" "findIndex:"
|
||||
(st-parse-method
|
||||
"findIndex: target
|
||||
1 to: 10 do: [:i | i = target ifTrue: [^ i]].
|
||||
^ 0"))
|
||||
|
||||
(st-test "to:do: + ^" (evp "^ Searcher new findIndex: 7") 7)
|
||||
(st-test "to:do: no match" (evp "^ Searcher new findIndex: 99") 0)
|
||||
|
||||
;; ── 5. ^ inside whileTrue: ──
|
||||
(st-class-add-method! "Searcher" "countdown:"
|
||||
(st-parse-method
|
||||
"countdown: n
|
||||
[n > 0] whileTrue: [
|
||||
n = 5 ifTrue: [^ #stoppedAtFive].
|
||||
n := n - 1].
|
||||
^ #done"))
|
||||
|
||||
(st-test "^ from whileTrue: body"
|
||||
(str (evp "^ Searcher new countdown: 10"))
|
||||
"stoppedAtFive")
|
||||
(st-test "whileTrue: completes normally"
|
||||
(str (evp "^ Searcher new countdown: 4"))
|
||||
"done")
|
||||
|
||||
;; ── 6. Returning blocks (escape from caller, not block-runner) ──
|
||||
;; Critical test: a method that returns a block. Calling block elsewhere
|
||||
;; should *not* escape this caller — the method has already returned.
|
||||
;; Real Smalltalk raises BlockContext>>cannotReturn:, but we just need to
|
||||
;; verify that *normal* (non-^) blocks behave correctly across method
|
||||
;; boundaries — i.e., a value-returning block works post-method.
|
||||
(st-class-add-method! "Searcher" "makeAdder:"
|
||||
(st-parse-method "makeAdder: n ^ [:x | x + n]"))
|
||||
|
||||
(st-test
|
||||
"block returned by method still works (normal value, no ^)"
|
||||
(evp "| add5 | add5 := Searcher new makeAdder: 5. ^ add5 value: 10")
|
||||
15)
|
||||
|
||||
;; ── 7. `^` inside a block invoked by another method ──
|
||||
;; Define `selectFrom:` that takes a block and applies it to each elem,
|
||||
;; returning the first elem for which the block returns true. The block,
|
||||
;; using `^`, can short-circuit *its caller* (not selectFrom:).
|
||||
(st-class-define! "Helper" "Object" (list))
|
||||
(st-class-add-method! "Helper" "applyTo:"
|
||||
(st-parse-method
|
||||
"applyTo: aBlock
|
||||
#(10 20 30) do: [:e | aBlock value: e].
|
||||
^ #helperFinished"))
|
||||
|
||||
(st-class-define! "Caller" "Object" (list))
|
||||
(st-class-add-method! "Caller" "go"
|
||||
(st-parse-method
|
||||
"go
|
||||
Helper new applyTo: [:e | e = 20 ifTrue: [^ #foundInCaller]].
|
||||
^ #didNotShortCircuit"))
|
||||
|
||||
(st-test
|
||||
"^ in block escapes the *creating* method (Caller>>go), not Helper>>applyTo:"
|
||||
(str (evp "^ Caller new go"))
|
||||
"foundInCaller")
|
||||
|
||||
;; ── 8. Nested method invocation: outer should not be reached on inner ^ ──
|
||||
(st-class-define! "Outer" "Object" (list))
|
||||
(st-class-add-method! "Outer" "outer"
|
||||
(st-parse-method
|
||||
"outer
|
||||
Outer new inner.
|
||||
^ #outerFinished"))
|
||||
|
||||
(st-class-add-method! "Outer" "inner"
|
||||
(st-parse-method "inner ^ #innerReturned"))
|
||||
|
||||
(st-test
|
||||
"inner method's ^ returns from inner only — outer continues"
|
||||
(str (evp "^ Outer new outer"))
|
||||
"outerFinished")
|
||||
|
||||
;; ── 9. Detect.first-style patterns ──
|
||||
(st-class-define! "Detector" "Object" (list))
|
||||
(st-class-add-method! "Detector" "detect:in:"
|
||||
(st-parse-method
|
||||
"detect: pred in: arr
|
||||
arr do: [:e | (pred value: e) ifTrue: [^ e]].
|
||||
^ nil"))
|
||||
|
||||
(st-test
|
||||
"detect: finds first match via ^"
|
||||
(evp "^ Detector new detect: [:x | x > 3] in: #(1 2 3 4 5)")
|
||||
4)
|
||||
|
||||
(st-test
|
||||
"detect: returns nil when none match"
|
||||
(evp "^ Detector new detect: [:x | x > 100] in: #(1 2 3)")
|
||||
nil)
|
||||
|
||||
;; ── 10. ^ at top level returns from the program ──
|
||||
(st-test "top-level ^v" (evp "1. ^ 99. 100") 99)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,131 +0,0 @@
|
||||
;; Number-tower tests: SmallInteger / Float / Fraction. New numeric methods
|
||||
;; (floor/ceiling/sqrt/factorial/gcd:/lcm:/raisedTo:/even/odd) and Fraction
|
||||
;; arithmetic with normalization.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. New SmallInteger / Float methods ──
|
||||
(st-test "floor of 3.7" (ev "3.7 floor") 3)
|
||||
(st-test "floor of -3.2" (ev "-3.2 floor") -4)
|
||||
(st-test "ceiling of 3.2" (ev "3.2 ceiling") 4)
|
||||
(st-test "ceiling of -3.7" (ev "-3.7 ceiling") -3)
|
||||
(st-test "truncated of 3.7" (ev "3.7 truncated") 3)
|
||||
(st-test "truncated of -3.7" (ev "-3.7 truncated") -3)
|
||||
(st-test "rounded of 3.4" (ev "3.4 rounded") 3)
|
||||
(st-test "rounded of 3.5" (ev "3.5 rounded") 4)
|
||||
(st-test "sqrt of 16" (ev "16 sqrt") 4)
|
||||
(st-test "squared" (ev "7 squared") 49)
|
||||
(st-test "raisedTo:" (ev "2 raisedTo: 10") 1024)
|
||||
(st-test "factorial 0" (ev "0 factorial") 1)
|
||||
(st-test "factorial 1" (ev "1 factorial") 1)
|
||||
(st-test "factorial 5" (ev "5 factorial") 120)
|
||||
(st-test "factorial 10" (ev "10 factorial") 3628800)
|
||||
|
||||
(st-test "even/odd 4" (ev "4 even") true)
|
||||
(st-test "even/odd 5" (ev "5 even") false)
|
||||
(st-test "odd 3" (ev "3 odd") true)
|
||||
(st-test "odd 4" (ev "4 odd") false)
|
||||
|
||||
(st-test "gcd of 24 18" (ev "24 gcd: 18") 6)
|
||||
(st-test "gcd 0 7" (ev "0 gcd: 7") 7)
|
||||
(st-test "gcd negative" (ev "-12 gcd: 8") 4)
|
||||
(st-test "lcm of 4 6" (ev "4 lcm: 6") 12)
|
||||
|
||||
(st-test "isInteger on int" (ev "42 isInteger") true)
|
||||
(st-test "isInteger on float" (ev "3.14 isInteger") false)
|
||||
(st-test "isFloat on float" (ev "3.14 isFloat") true)
|
||||
(st-test "isNumber" (ev "42 isNumber") true)
|
||||
|
||||
;; ── 2. Fraction class ──
|
||||
(st-test "Fraction class exists" (st-class-exists? "Fraction") true)
|
||||
(st-test "Fraction < Number"
|
||||
(st-class-inherits-from? "Fraction" "Number") true)
|
||||
|
||||
(st-test "Fraction creation"
|
||||
(str (evp "^ (Fraction numerator: 1 denominator: 2) printString"))
|
||||
"1/2")
|
||||
|
||||
(st-test "Fraction reduction at construction"
|
||||
(str (evp "^ (Fraction numerator: 6 denominator: 8) printString"))
|
||||
"3/4")
|
||||
|
||||
(st-test "Fraction sign normalization (denom positive)"
|
||||
(str (evp "^ (Fraction numerator: 1 denominator: -2) printString"))
|
||||
"-1/2")
|
||||
|
||||
(st-test "Fraction numerator accessor"
|
||||
(evp "^ (Fraction numerator: 6 denominator: 8) numerator") 3)
|
||||
|
||||
(st-test "Fraction denominator accessor"
|
||||
(evp "^ (Fraction numerator: 6 denominator: 8) denominator") 4)
|
||||
|
||||
;; ── 3. Fraction arithmetic ──
|
||||
(st-test "Fraction addition"
|
||||
(str
|
||||
(evp
|
||||
"^ ((Fraction numerator: 1 denominator: 2) + (Fraction numerator: 1 denominator: 3)) printString"))
|
||||
"5/6")
|
||||
|
||||
(st-test "Fraction subtraction"
|
||||
(str
|
||||
(evp
|
||||
"^ ((Fraction numerator: 3 denominator: 4) - (Fraction numerator: 1 denominator: 4)) printString"))
|
||||
"1/2")
|
||||
|
||||
(st-test "Fraction multiplication"
|
||||
(str
|
||||
(evp
|
||||
"^ ((Fraction numerator: 2 denominator: 3) * (Fraction numerator: 3 denominator: 4)) printString"))
|
||||
"1/2")
|
||||
|
||||
(st-test "Fraction division"
|
||||
(str
|
||||
(evp
|
||||
"^ ((Fraction numerator: 1 denominator: 2) / (Fraction numerator: 1 denominator: 4)) printString"))
|
||||
"2/1")
|
||||
|
||||
(st-test "Fraction negated"
|
||||
(str (evp "^ (Fraction numerator: 1 denominator: 3) negated printString"))
|
||||
"-1/3")
|
||||
|
||||
(st-test "Fraction reciprocal"
|
||||
(str (evp "^ (Fraction numerator: 2 denominator: 5) reciprocal printString"))
|
||||
"5/2")
|
||||
|
||||
;; ── 4. Fraction equality + ordering ──
|
||||
(st-test "Fraction equality after reduce"
|
||||
(evp
|
||||
"^ (Fraction numerator: 4 denominator: 8) = (Fraction numerator: 1 denominator: 2)")
|
||||
true)
|
||||
|
||||
(st-test "Fraction inequality"
|
||||
(evp
|
||||
"^ (Fraction numerator: 1 denominator: 3) = (Fraction numerator: 1 denominator: 4)")
|
||||
false)
|
||||
|
||||
(st-test "Fraction less-than"
|
||||
(evp
|
||||
"^ (Fraction numerator: 1 denominator: 3) < (Fraction numerator: 1 denominator: 2)")
|
||||
true)
|
||||
|
||||
;; ── 5. Fraction asFloat ──
|
||||
(st-test "Fraction asFloat 1/2"
|
||||
(evp "^ (Fraction numerator: 1 denominator: 2) asFloat") (/ 1 2))
|
||||
|
||||
(st-test "Fraction asFloat 3/4"
|
||||
(evp "^ (Fraction numerator: 3 denominator: 4) asFloat") (/ 3 4))
|
||||
|
||||
;; ── 6. Fraction predicates ──
|
||||
(st-test "Fraction isFraction"
|
||||
(evp "^ (Fraction numerator: 1 denominator: 2) isFraction") true)
|
||||
|
||||
(st-test "Fraction class name"
|
||||
(evp "^ (Fraction numerator: 1 denominator: 2) class name") "Fraction")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,369 +0,0 @@
|
||||
;; Smalltalk parser tests.
|
||||
;;
|
||||
;; Reuses helpers (st-test, st-deep=?) from tokenize.sx. Counters reset
|
||||
;; here so this file's summary covers parse tests only.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
;; ── 1. Atoms ──
|
||||
(st-test "int" (st-parse-expr "42") {:type "lit-int" :value 42})
|
||||
(st-test "float" (st-parse-expr "3.14") {:type "lit-float" :value 3.14})
|
||||
(st-test "string" (st-parse-expr "'hi'") {:type "lit-string" :value "hi"})
|
||||
(st-test "char" (st-parse-expr "$x") {:type "lit-char" :value "x"})
|
||||
(st-test "symbol" (st-parse-expr "#foo") {:type "lit-symbol" :value "foo"})
|
||||
(st-test "binary symbol" (st-parse-expr "#+") {:type "lit-symbol" :value "+"})
|
||||
(st-test "keyword symbol" (st-parse-expr "#at:put:") {:type "lit-symbol" :value "at:put:"})
|
||||
(st-test "nil" (st-parse-expr "nil") {:type "lit-nil"})
|
||||
(st-test "true" (st-parse-expr "true") {:type "lit-true"})
|
||||
(st-test "false" (st-parse-expr "false") {:type "lit-false"})
|
||||
(st-test "self" (st-parse-expr "self") {:type "self"})
|
||||
(st-test "super" (st-parse-expr "super") {:type "super"})
|
||||
(st-test "ident" (st-parse-expr "x") {:type "ident" :name "x"})
|
||||
(st-test "negative int" (st-parse-expr "-3") {:type "lit-int" :value -3})
|
||||
|
||||
;; ── 2. Literal arrays ──
|
||||
(st-test
|
||||
"literal array of ints"
|
||||
(st-parse-expr "#(1 2 3)")
|
||||
{:type "lit-array"
|
||||
:elements (list
|
||||
{:type "lit-int" :value 1}
|
||||
{:type "lit-int" :value 2}
|
||||
{:type "lit-int" :value 3})})
|
||||
|
||||
(st-test
|
||||
"literal array mixed"
|
||||
(st-parse-expr "#(1 #foo 'x' true)")
|
||||
{:type "lit-array"
|
||||
:elements (list
|
||||
{:type "lit-int" :value 1}
|
||||
{:type "lit-symbol" :value "foo"}
|
||||
{:type "lit-string" :value "x"}
|
||||
{:type "lit-true"})})
|
||||
|
||||
(st-test
|
||||
"literal array bare ident is symbol"
|
||||
(st-parse-expr "#(foo bar)")
|
||||
{:type "lit-array"
|
||||
:elements (list
|
||||
{:type "lit-symbol" :value "foo"}
|
||||
{:type "lit-symbol" :value "bar"})})
|
||||
|
||||
(st-test
|
||||
"nested literal array"
|
||||
(st-parse-expr "#(1 (2 3) 4)")
|
||||
{:type "lit-array"
|
||||
:elements (list
|
||||
{:type "lit-int" :value 1}
|
||||
{:type "lit-array"
|
||||
:elements (list
|
||||
{:type "lit-int" :value 2}
|
||||
{:type "lit-int" :value 3})}
|
||||
{:type "lit-int" :value 4})})
|
||||
|
||||
(st-test
|
||||
"byte array"
|
||||
(st-parse-expr "#[1 2 3]")
|
||||
{:type "lit-byte-array" :elements (list 1 2 3)})
|
||||
|
||||
;; ── 3. Unary messages ──
|
||||
(st-test
|
||||
"unary single"
|
||||
(st-parse-expr "x foo")
|
||||
{:type "send"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:selector "foo"
|
||||
:args (list)})
|
||||
|
||||
(st-test
|
||||
"unary chain"
|
||||
(st-parse-expr "x foo bar baz")
|
||||
{:type "send"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:selector "foo"
|
||||
:args (list)}
|
||||
:selector "bar"
|
||||
:args (list)}
|
||||
:selector "baz"
|
||||
:args (list)})
|
||||
|
||||
(st-test
|
||||
"unary on literal"
|
||||
(st-parse-expr "42 printNl")
|
||||
{:type "send"
|
||||
:receiver {:type "lit-int" :value 42}
|
||||
:selector "printNl"
|
||||
:args (list)})
|
||||
|
||||
;; ── 4. Binary messages ──
|
||||
(st-test
|
||||
"binary single"
|
||||
(st-parse-expr "1 + 2")
|
||||
{:type "send"
|
||||
:receiver {:type "lit-int" :value 1}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 2})})
|
||||
|
||||
(st-test
|
||||
"binary left-assoc"
|
||||
(st-parse-expr "1 + 2 + 3")
|
||||
{:type "send"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "lit-int" :value 1}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 2})}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 3})})
|
||||
|
||||
(st-test
|
||||
"binary same precedence l-to-r"
|
||||
(st-parse-expr "1 + 2 * 3")
|
||||
{:type "send"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "lit-int" :value 1}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 2})}
|
||||
:selector "*"
|
||||
:args (list {:type "lit-int" :value 3})})
|
||||
|
||||
;; ── 5. Precedence: unary binds tighter than binary ──
|
||||
(st-test
|
||||
"unary tighter than binary"
|
||||
(st-parse-expr "3 + 4 factorial")
|
||||
{:type "send"
|
||||
:receiver {:type "lit-int" :value 3}
|
||||
:selector "+"
|
||||
:args (list
|
||||
{:type "send"
|
||||
:receiver {:type "lit-int" :value 4}
|
||||
:selector "factorial"
|
||||
:args (list)})})
|
||||
|
||||
;; ── 6. Keyword messages ──
|
||||
(st-test
|
||||
"keyword single"
|
||||
(st-parse-expr "x at: 1")
|
||||
{:type "send"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:selector "at:"
|
||||
:args (list {:type "lit-int" :value 1})})
|
||||
|
||||
(st-test
|
||||
"keyword chain"
|
||||
(st-parse-expr "x at: 1 put: 'a'")
|
||||
{:type "send"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:selector "at:put:"
|
||||
:args (list {:type "lit-int" :value 1} {:type "lit-string" :value "a"})})
|
||||
|
||||
;; ── 7. Precedence: binary tighter than keyword ──
|
||||
(st-test
|
||||
"binary tighter than keyword"
|
||||
(st-parse-expr "x at: 1 + 2")
|
||||
{:type "send"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:selector "at:"
|
||||
:args (list
|
||||
{:type "send"
|
||||
:receiver {:type "lit-int" :value 1}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 2})})})
|
||||
|
||||
(st-test
|
||||
"keyword absorbs trailing unary"
|
||||
(st-parse-expr "a foo: b bar")
|
||||
{:type "send"
|
||||
:receiver {:type "ident" :name "a"}
|
||||
:selector "foo:"
|
||||
:args (list
|
||||
{:type "send"
|
||||
:receiver {:type "ident" :name "b"}
|
||||
:selector "bar"
|
||||
:args (list)})})
|
||||
|
||||
;; ── 8. Parens override precedence ──
|
||||
(st-test
|
||||
"paren forces grouping"
|
||||
(st-parse-expr "(1 + 2) * 3")
|
||||
{:type "send"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "lit-int" :value 1}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 2})}
|
||||
:selector "*"
|
||||
:args (list {:type "lit-int" :value 3})})
|
||||
|
||||
;; ── 9. Cascade ──
|
||||
(st-test
|
||||
"simple cascade"
|
||||
(st-parse-expr "x m1; m2")
|
||||
{:type "cascade"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:messages (list
|
||||
{:selector "m1" :args (list)}
|
||||
{:selector "m2" :args (list)})})
|
||||
|
||||
(st-test
|
||||
"cascade with binary and keyword"
|
||||
(st-parse-expr "Stream new nl; tab; print: 1")
|
||||
{:type "cascade"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "ident" :name "Stream"}
|
||||
:selector "new"
|
||||
:args (list)}
|
||||
:messages (list
|
||||
{:selector "nl" :args (list)}
|
||||
{:selector "tab" :args (list)}
|
||||
{:selector "print:" :args (list {:type "lit-int" :value 1})})})
|
||||
|
||||
;; ── 10. Blocks ──
|
||||
(st-test
|
||||
"empty block"
|
||||
(st-parse-expr "[]")
|
||||
{:type "block" :params (list) :temps (list) :body (list)})
|
||||
|
||||
(st-test
|
||||
"block one expr"
|
||||
(st-parse-expr "[1 + 2]")
|
||||
{:type "block"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:body (list
|
||||
{:type "send"
|
||||
:receiver {:type "lit-int" :value 1}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 2})})})
|
||||
|
||||
(st-test
|
||||
"block with params"
|
||||
(st-parse-expr "[:a :b | a + b]")
|
||||
{:type "block"
|
||||
:params (list "a" "b")
|
||||
:temps (list)
|
||||
:body (list
|
||||
{:type "send"
|
||||
:receiver {:type "ident" :name "a"}
|
||||
:selector "+"
|
||||
:args (list {:type "ident" :name "b"})})})
|
||||
|
||||
(st-test
|
||||
"block with temps"
|
||||
(st-parse-expr "[| t | t := 1. t]")
|
||||
{:type "block"
|
||||
:params (list)
|
||||
:temps (list "t")
|
||||
:body (list
|
||||
{:type "assign" :name "t" :expr {:type "lit-int" :value 1}}
|
||||
{:type "ident" :name "t"})})
|
||||
|
||||
(st-test
|
||||
"block with params and temps"
|
||||
(st-parse-expr "[:x | | t | t := x + 1. t]")
|
||||
{:type "block"
|
||||
:params (list "x")
|
||||
:temps (list "t")
|
||||
:body (list
|
||||
{:type "assign"
|
||||
:name "t"
|
||||
:expr {:type "send"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 1})}}
|
||||
{:type "ident" :name "t"})})
|
||||
|
||||
;; ── 11. Assignment / return / statements ──
|
||||
(st-test
|
||||
"assignment"
|
||||
(st-parse-expr "x := 1")
|
||||
{:type "assign" :name "x" :expr {:type "lit-int" :value 1}})
|
||||
|
||||
(st-test
|
||||
"return"
|
||||
(st-parse-expr "1")
|
||||
{:type "lit-int" :value 1})
|
||||
|
||||
(st-test
|
||||
"return statement at top level"
|
||||
(st-parse "^ 1")
|
||||
{:type "seq" :temps (list)
|
||||
:exprs (list {:type "return" :expr {:type "lit-int" :value 1}})})
|
||||
|
||||
(st-test
|
||||
"two statements"
|
||||
(st-parse "x := 1. y := 2")
|
||||
{:type "seq" :temps (list)
|
||||
:exprs (list
|
||||
{:type "assign" :name "x" :expr {:type "lit-int" :value 1}}
|
||||
{:type "assign" :name "y" :expr {:type "lit-int" :value 2}})})
|
||||
|
||||
(st-test
|
||||
"trailing dot allowed"
|
||||
(st-parse "1. 2.")
|
||||
{:type "seq" :temps (list)
|
||||
:exprs (list {:type "lit-int" :value 1} {:type "lit-int" :value 2})})
|
||||
|
||||
;; ── 12. Method headers ──
|
||||
(st-test
|
||||
"unary method"
|
||||
(st-parse-method "factorial ^ self * (self - 1) factorial")
|
||||
{:type "method"
|
||||
:selector "factorial"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "return"
|
||||
:expr {:type "send"
|
||||
:receiver {:type "self"}
|
||||
:selector "*"
|
||||
:args (list
|
||||
{:type "send"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "self"}
|
||||
:selector "-"
|
||||
:args (list {:type "lit-int" :value 1})}
|
||||
:selector "factorial"
|
||||
:args (list)})}})})
|
||||
|
||||
(st-test
|
||||
"binary method"
|
||||
(st-parse-method "+ other ^ 'plus'")
|
||||
{:type "method"
|
||||
:selector "+"
|
||||
:params (list "other")
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list {:type "return" :expr {:type "lit-string" :value "plus"}})})
|
||||
|
||||
(st-test
|
||||
"keyword method"
|
||||
(st-parse-method "at: i put: v ^ v")
|
||||
{:type "method"
|
||||
:selector "at:put:"
|
||||
:params (list "i" "v")
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list {:type "return" :expr {:type "ident" :name "v"}})})
|
||||
|
||||
(st-test
|
||||
"method with temps"
|
||||
(st-parse-method "twice: x | t | t := x + x. ^ t")
|
||||
{:type "method"
|
||||
:selector "twice:"
|
||||
:params (list "x")
|
||||
:temps (list "t")
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "assign"
|
||||
:name "t"
|
||||
:expr {:type "send"
|
||||
:receiver {:type "ident" :name "x"}
|
||||
:selector "+"
|
||||
:args (list {:type "ident" :name "x"})}}
|
||||
{:type "return" :expr {:type "ident" :name "t"}})})
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,294 +0,0 @@
|
||||
;; Smalltalk chunk-stream parser + pragma tests.
|
||||
;;
|
||||
;; Reuses helpers (st-test, st-deep=?) from tokenize.sx. Counters reset
|
||||
;; here so this file's summary covers chunk + pragma tests only.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
;; ── 1. Raw chunk reader ──
|
||||
(st-test "empty source" (st-read-chunks "") (list))
|
||||
(st-test "single chunk" (st-read-chunks "foo!") (list "foo"))
|
||||
(st-test "two chunks" (st-read-chunks "a! b!") (list "a" "b"))
|
||||
(st-test "trailing no bang" (st-read-chunks "a! b") (list "a" "b"))
|
||||
(st-test "empty chunk" (st-read-chunks "a! ! b!") (list "a" "" "b"))
|
||||
(st-test
|
||||
"doubled bang escapes"
|
||||
(st-read-chunks "yes!! no!yes!")
|
||||
(list "yes! no" "yes"))
|
||||
(st-test
|
||||
"whitespace trimmed"
|
||||
(st-read-chunks " \n hello \n !")
|
||||
(list "hello"))
|
||||
|
||||
;; ── 2. Chunk parser — do-it mode ──
|
||||
(st-test
|
||||
"single do-it chunk"
|
||||
(st-parse-chunks "1 + 2!")
|
||||
(list
|
||||
{:kind "expr"
|
||||
:ast {:type "send"
|
||||
:receiver {:type "lit-int" :value 1}
|
||||
:selector "+"
|
||||
:args (list {:type "lit-int" :value 2})}}))
|
||||
|
||||
(st-test
|
||||
"two do-it chunks"
|
||||
(st-parse-chunks "x := 1! y := 2!")
|
||||
(list
|
||||
{:kind "expr"
|
||||
:ast {:type "assign" :name "x" :expr {:type "lit-int" :value 1}}}
|
||||
{:kind "expr"
|
||||
:ast {:type "assign" :name "y" :expr {:type "lit-int" :value 2}}}))
|
||||
|
||||
(st-test
|
||||
"blank chunk outside methods"
|
||||
(st-parse-chunks "1! ! 2!")
|
||||
(list
|
||||
{:kind "expr" :ast {:type "lit-int" :value 1}}
|
||||
{:kind "blank"}
|
||||
{:kind "expr" :ast {:type "lit-int" :value 2}}))
|
||||
|
||||
;; ── 3. Methods batch ──
|
||||
(st-test
|
||||
"methodsFor opens method batch"
|
||||
(st-parse-chunks
|
||||
"Foo methodsFor: 'access'! foo ^ 1! bar ^ 2! !")
|
||||
(list
|
||||
{:kind "expr"
|
||||
:ast {:type "send"
|
||||
:receiver {:type "ident" :name "Foo"}
|
||||
:selector "methodsFor:"
|
||||
:args (list {:type "lit-string" :value "access"})}}
|
||||
{:kind "method"
|
||||
:class "Foo"
|
||||
:class-side? false
|
||||
:category "access"
|
||||
:ast {:type "method"
|
||||
:selector "foo"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "return" :expr {:type "lit-int" :value 1}})}}
|
||||
{:kind "method"
|
||||
:class "Foo"
|
||||
:class-side? false
|
||||
:category "access"
|
||||
:ast {:type "method"
|
||||
:selector "bar"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "return" :expr {:type "lit-int" :value 2}})}}
|
||||
{:kind "end-methods"}))
|
||||
|
||||
(st-test
|
||||
"class-side methodsFor"
|
||||
(st-parse-chunks
|
||||
"Foo class methodsFor: 'creation'! make ^ self new! !")
|
||||
(list
|
||||
{:kind "expr"
|
||||
:ast {:type "send"
|
||||
:receiver {:type "send"
|
||||
:receiver {:type "ident" :name "Foo"}
|
||||
:selector "class"
|
||||
:args (list)}
|
||||
:selector "methodsFor:"
|
||||
:args (list {:type "lit-string" :value "creation"})}}
|
||||
{:kind "method"
|
||||
:class "Foo"
|
||||
:class-side? true
|
||||
:category "creation"
|
||||
:ast {:type "method"
|
||||
:selector "make"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "return"
|
||||
:expr {:type "send"
|
||||
:receiver {:type "self"}
|
||||
:selector "new"
|
||||
:args (list)}})}}
|
||||
{:kind "end-methods"}))
|
||||
|
||||
(st-test
|
||||
"method batch returns to do-it after empty chunk"
|
||||
(st-parse-chunks
|
||||
"Foo methodsFor: 'a'! m1 ^ 1! ! 99!")
|
||||
(list
|
||||
{:kind "expr"
|
||||
:ast {:type "send"
|
||||
:receiver {:type "ident" :name "Foo"}
|
||||
:selector "methodsFor:"
|
||||
:args (list {:type "lit-string" :value "a"})}}
|
||||
{:kind "method"
|
||||
:class "Foo"
|
||||
:class-side? false
|
||||
:category "a"
|
||||
:ast {:type "method"
|
||||
:selector "m1"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "return" :expr {:type "lit-int" :value 1}})}}
|
||||
{:kind "end-methods"}
|
||||
{:kind "expr" :ast {:type "lit-int" :value 99}}))
|
||||
|
||||
;; ── 4. Pragmas in method bodies ──
|
||||
(st-test
|
||||
"single pragma"
|
||||
(st-parse-method "primAt: i <primitive: 60> ^ self")
|
||||
{:type "method"
|
||||
:selector "primAt:"
|
||||
:params (list "i")
|
||||
:temps (list)
|
||||
:pragmas (list
|
||||
{:selector "primitive:"
|
||||
:args (list {:type "lit-int" :value 60})})
|
||||
:body (list {:type "return" :expr {:type "self"}})})
|
||||
|
||||
(st-test
|
||||
"pragma with two keyword pairs"
|
||||
(st-parse-method "fft <primitive: 1 module: 'fft'> ^ nil")
|
||||
{:type "method"
|
||||
:selector "fft"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list
|
||||
{:selector "primitive:module:"
|
||||
:args (list
|
||||
{:type "lit-int" :value 1}
|
||||
{:type "lit-string" :value "fft"})})
|
||||
:body (list {:type "return" :expr {:type "lit-nil"}})})
|
||||
|
||||
(st-test
|
||||
"pragma with negative number"
|
||||
(st-parse-method "neg <primitive: -1> ^ nil")
|
||||
{:type "method"
|
||||
:selector "neg"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list
|
||||
{:selector "primitive:"
|
||||
:args (list {:type "lit-int" :value -1})})
|
||||
:body (list {:type "return" :expr {:type "lit-nil"}})})
|
||||
|
||||
(st-test
|
||||
"pragma with symbol arg"
|
||||
(st-parse-method "tagged <category: #algebra> ^ nil")
|
||||
{:type "method"
|
||||
:selector "tagged"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list
|
||||
{:selector "category:"
|
||||
:args (list {:type "lit-symbol" :value "algebra"})})
|
||||
:body (list {:type "return" :expr {:type "lit-nil"}})})
|
||||
|
||||
(st-test
|
||||
"pragma then temps"
|
||||
(st-parse-method "calc <primitive: 1> | t | t := 5. ^ t")
|
||||
{:type "method"
|
||||
:selector "calc"
|
||||
:params (list)
|
||||
:temps (list "t")
|
||||
:pragmas (list
|
||||
{:selector "primitive:"
|
||||
:args (list {:type "lit-int" :value 1})})
|
||||
:body (list
|
||||
{:type "assign" :name "t" :expr {:type "lit-int" :value 5}}
|
||||
{:type "return" :expr {:type "ident" :name "t"}})})
|
||||
|
||||
(st-test
|
||||
"temps then pragma"
|
||||
(st-parse-method "calc | t | <primitive: 1> t := 5. ^ t")
|
||||
{:type "method"
|
||||
:selector "calc"
|
||||
:params (list)
|
||||
:temps (list "t")
|
||||
:pragmas (list
|
||||
{:selector "primitive:"
|
||||
:args (list {:type "lit-int" :value 1})})
|
||||
:body (list
|
||||
{:type "assign" :name "t" :expr {:type "lit-int" :value 5}}
|
||||
{:type "return" :expr {:type "ident" :name "t"}})})
|
||||
|
||||
(st-test
|
||||
"two pragmas"
|
||||
(st-parse-method "m <primitive: 1> <category: 'a'> ^ self")
|
||||
{:type "method"
|
||||
:selector "m"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list
|
||||
{:selector "primitive:"
|
||||
:args (list {:type "lit-int" :value 1})}
|
||||
{:selector "category:"
|
||||
:args (list {:type "lit-string" :value "a"})})
|
||||
:body (list {:type "return" :expr {:type "self"}})})
|
||||
|
||||
;; ── 5. End-to-end: a small "filed-in" snippet ──
|
||||
(st-test
|
||||
"small filed-in class snippet"
|
||||
(st-parse-chunks
|
||||
"Object subclass: #Account
|
||||
instanceVariableNames: 'balance'!
|
||||
|
||||
!Account methodsFor: 'access'!
|
||||
balance
|
||||
^ balance!
|
||||
|
||||
deposit: amount
|
||||
balance := balance + amount.
|
||||
^ self! !")
|
||||
(list
|
||||
{:kind "expr"
|
||||
:ast {:type "send"
|
||||
:receiver {:type "ident" :name "Object"}
|
||||
:selector "subclass:instanceVariableNames:"
|
||||
:args (list
|
||||
{:type "lit-symbol" :value "Account"}
|
||||
{:type "lit-string" :value "balance"})}}
|
||||
{:kind "blank"}
|
||||
{:kind "expr"
|
||||
:ast {:type "send"
|
||||
:receiver {:type "ident" :name "Account"}
|
||||
:selector "methodsFor:"
|
||||
:args (list {:type "lit-string" :value "access"})}}
|
||||
{:kind "method"
|
||||
:class "Account"
|
||||
:class-side? false
|
||||
:category "access"
|
||||
:ast {:type "method"
|
||||
:selector "balance"
|
||||
:params (list)
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "return"
|
||||
:expr {:type "ident" :name "balance"}})}}
|
||||
{:kind "method"
|
||||
:class "Account"
|
||||
:class-side? false
|
||||
:category "access"
|
||||
:ast {:type "method"
|
||||
:selector "deposit:"
|
||||
:params (list "amount")
|
||||
:temps (list)
|
||||
:pragmas (list)
|
||||
:body (list
|
||||
{:type "assign"
|
||||
:name "balance"
|
||||
:expr {:type "send"
|
||||
:receiver {:type "ident" :name "balance"}
|
||||
:selector "+"
|
||||
:args (list {:type "ident" :name "amount"})}}
|
||||
{:type "return" :expr {:type "self"}})}}
|
||||
{:kind "end-methods"}))
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,264 +0,0 @@
|
||||
;; Vendor a slice of Pharo Kernel-Tests / Collections-Tests.
|
||||
;;
|
||||
;; The .st files in tests/pharo/ define TestCase subclasses with `test*`
|
||||
;; methods. This harness reads them, asks the SUnit framework for the
|
||||
;; per-class test selector list, runs each test individually, and emits
|
||||
;; one st-test row per Smalltalk test method — so each Pharo test counts
|
||||
;; toward the scoreboard's grand total.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
;; The runtime is already loaded by test.sh. The class table has SUnit
|
||||
;; (also bootstrapped by test.sh). We need to install the Pharo test
|
||||
;; classes before iterating them.
|
||||
|
||||
(define
|
||||
pharo-kernel-source
|
||||
"TestCase subclass: #IntegerTest instanceVariableNames: ''!
|
||||
|
||||
!IntegerTest methodsFor: 'arithmetic'!
|
||||
testAddition self assert: 2 + 3 equals: 5!
|
||||
testSubtraction self assert: 10 - 4 equals: 6!
|
||||
testMultiplication self assert: 6 * 7 equals: 42!
|
||||
testDivisionExact self assert: 10 / 2 equals: 5!
|
||||
testNegation self assert: 7 negated equals: -7!
|
||||
testAbs self assert: -5 abs equals: 5!
|
||||
testZero self assert: 0 + 0 equals: 0!
|
||||
testIdentity self assert: 42 == 42! !
|
||||
|
||||
!IntegerTest methodsFor: 'comparison'!
|
||||
testLessThan self assert: 1 < 2!
|
||||
testLessOrEqual self assert: 5 <= 5!
|
||||
testGreater self assert: 10 > 3!
|
||||
testEqualSelf self assert: 7 = 7!
|
||||
testNotEqual self assert: (3 ~= 5)!
|
||||
testBetween self assert: (5 between: 1 and: 10)! !
|
||||
|
||||
!IntegerTest methodsFor: 'predicates'!
|
||||
testEvenTrue self assert: 4 even!
|
||||
testEvenFalse self deny: 5 even!
|
||||
testOdd self assert: 3 odd!
|
||||
testIsInteger self assert: 0 isInteger!
|
||||
testIsNumber self assert: 1 isNumber!
|
||||
testIsZero self assert: 0 isZero!
|
||||
testIsNotZero self deny: 1 isZero! !
|
||||
|
||||
!IntegerTest methodsFor: 'powers and roots'!
|
||||
testFactorialZero self assert: 0 factorial equals: 1!
|
||||
testFactorialFive self assert: 5 factorial equals: 120!
|
||||
testRaisedTo self assert: (2 raisedTo: 8) equals: 256!
|
||||
testSquared self assert: 9 squared equals: 81!
|
||||
testSqrtPerfect self assert: 16 sqrt equals: 4!
|
||||
testGcd self assert: (24 gcd: 18) equals: 6!
|
||||
testLcm self assert: (4 lcm: 6) equals: 12! !
|
||||
|
||||
!IntegerTest methodsFor: 'rounding'!
|
||||
testFloor self assert: 3.7 floor equals: 3!
|
||||
testCeiling self assert: 3.2 ceiling equals: 4!
|
||||
testTruncated self assert: -3.7 truncated equals: -3!
|
||||
testRounded self assert: 3.5 rounded equals: 4! !
|
||||
|
||||
TestCase subclass: #StringTest instanceVariableNames: ''!
|
||||
|
||||
!StringTest methodsFor: 'access'!
|
||||
testSize self assert: 'hello' size equals: 5!
|
||||
testEmpty self assert: '' isEmpty!
|
||||
testNotEmpty self assert: 'a' notEmpty!
|
||||
testAtFirst self assert: ('hello' at: 1) equals: 'h'!
|
||||
testAtLast self assert: ('hello' at: 5) equals: 'o'!
|
||||
testFirst self assert: 'world' first equals: 'w'!
|
||||
testLast self assert: 'world' last equals: 'd'! !
|
||||
|
||||
!StringTest methodsFor: 'concatenation'!
|
||||
testCommaConcat self assert: 'hello, ' , 'world' equals: 'hello, world'!
|
||||
testEmptyConcat self assert: '' , 'x' equals: 'x'!
|
||||
testSelfConcat self assert: 'ab' , 'ab' equals: 'abab'! !
|
||||
|
||||
!StringTest methodsFor: 'comparisons'!
|
||||
testEqual self assert: 'a' = 'a'!
|
||||
testNotEqualStr self deny: 'a' = 'b'!
|
||||
testIncludes self assert: ('banana' includes: $a)!
|
||||
testIncludesNot self deny: ('banana' includes: $z)!
|
||||
testIndexOf self assert: ('abcde' indexOf: $c) equals: 3! !
|
||||
|
||||
!StringTest methodsFor: 'transforms'!
|
||||
testCopyFromTo self assert: ('helloworld' copyFrom: 6 to: 10) equals: 'world'! !
|
||||
|
||||
TestCase subclass: #BooleanTest instanceVariableNames: ''!
|
||||
|
||||
!BooleanTest methodsFor: 'logic'!
|
||||
testNotTrue self deny: true not!
|
||||
testNotFalse self assert: false not!
|
||||
testAnd self assert: (true & true)!
|
||||
testOr self assert: (true | false)!
|
||||
testIfTrueTaken self assert: (true ifTrue: [1] ifFalse: [2]) equals: 1!
|
||||
testIfFalseTaken self assert: (false ifTrue: [1] ifFalse: [2]) equals: 2!
|
||||
testAndShortCircuit self assert: (false and: [1/0]) equals: false!
|
||||
testOrShortCircuit self assert: (true or: [1/0]) equals: true! !")
|
||||
|
||||
(define
|
||||
pharo-collections-source
|
||||
"TestCase subclass: #ArrayTest instanceVariableNames: ''!
|
||||
|
||||
!ArrayTest methodsFor: 'creation'!
|
||||
testNewSize self assert: (Array new: 5) size equals: 5!
|
||||
testLiteralSize self assert: #(1 2 3) size equals: 3!
|
||||
testEmpty self assert: #() isEmpty!
|
||||
testNotEmpty self assert: #(1) notEmpty!
|
||||
testFirst self assert: #(10 20 30) first equals: 10!
|
||||
testLast self assert: #(10 20 30) last equals: 30! !
|
||||
|
||||
!ArrayTest methodsFor: 'access'!
|
||||
testAt self assert: (#(10 20 30) at: 2) equals: 20!
|
||||
testAtPut
|
||||
| a |
|
||||
a := Array new: 3.
|
||||
a at: 1 put: 'x'. a at: 2 put: 'y'. a at: 3 put: 'z'.
|
||||
self assert: (a at: 2) equals: 'y'! !
|
||||
|
||||
!ArrayTest methodsFor: 'iteration'!
|
||||
testDoSum
|
||||
| s |
|
||||
s := 0.
|
||||
#(1 2 3 4 5) do: [:e | s := s + e].
|
||||
self assert: s equals: 15!
|
||||
|
||||
testInjectInto self assert: (#(1 2 3 4) inject: 0 into: [:a :b | a + b]) equals: 10!
|
||||
|
||||
testCollect self assert: (#(1 2 3) collect: [:x | x * x]) equals: #(1 4 9)!
|
||||
|
||||
testSelect self assert: (#(1 2 3 4 5) select: [:x | x > 2]) equals: #(3 4 5)!
|
||||
|
||||
testReject self assert: (#(1 2 3 4 5) reject: [:x | x > 2]) equals: #(1 2)!
|
||||
|
||||
testDetect self assert: (#(1 3 5 7) detect: [:x | x > 4]) equals: 5!
|
||||
|
||||
testCount self assert: (#(1 2 3 4 5) count: [:x | x even]) equals: 2!
|
||||
|
||||
testAnySatisfy self assert: (#(1 2 3) anySatisfy: [:x | x > 2])!
|
||||
|
||||
testAllSatisfy self assert: (#(2 4 6) allSatisfy: [:x | x even])!
|
||||
|
||||
testIncludes self assert: (#(1 2 3) includes: 2)!
|
||||
|
||||
testIncludesNotArr self deny: (#(1 2 3) includes: 99)!
|
||||
|
||||
testIndexOfArr self assert: (#(10 20 30) indexOf: 30) equals: 3!
|
||||
|
||||
testIndexOfMissing self assert: (#(1 2 3) indexOf: 99) equals: 0! !
|
||||
|
||||
TestCase subclass: #DictionaryTest instanceVariableNames: ''!
|
||||
|
||||
!DictionaryTest methodsFor: 'tests'!
|
||||
testEmpty self assert: Dictionary new isEmpty!
|
||||
|
||||
testAtPutThenAt
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1.
|
||||
self assert: (d at: #a) equals: 1!
|
||||
|
||||
testAtMissingNil self assert: (Dictionary new at: #nope) equals: nil!
|
||||
|
||||
testAtIfAbsent
|
||||
self assert: (Dictionary new at: #nope ifAbsent: [#absent]) equals: #absent!
|
||||
|
||||
testSize
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2. d at: #c put: 3.
|
||||
self assert: d size equals: 3!
|
||||
|
||||
testIncludesKey
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1.
|
||||
self assert: (d includesKey: #a)!
|
||||
|
||||
testRemoveKey
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2.
|
||||
d removeKey: #a.
|
||||
self deny: (d includesKey: #a)!
|
||||
|
||||
testOverwrite
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #x put: 1. d at: #x put: 99.
|
||||
self assert: (d at: #x) equals: 99! !
|
||||
|
||||
TestCase subclass: #SetTest instanceVariableNames: ''!
|
||||
|
||||
!SetTest methodsFor: 'tests'!
|
||||
testEmpty self assert: Set new isEmpty!
|
||||
|
||||
testAdd
|
||||
| s |
|
||||
s := Set new.
|
||||
s add: 1.
|
||||
self assert: (s includes: 1)!
|
||||
|
||||
testDedup
|
||||
| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 1. s add: 1.
|
||||
self assert: s size equals: 1!
|
||||
|
||||
testRemove
|
||||
| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 2.
|
||||
s remove: 1.
|
||||
self deny: (s includes: 1)!
|
||||
|
||||
testAddAll
|
||||
| s |
|
||||
s := Set new.
|
||||
s addAll: #(1 2 3 2 1).
|
||||
self assert: s size equals: 3!
|
||||
|
||||
testDoSum
|
||||
| s sum |
|
||||
s := Set new.
|
||||
s add: 10. s add: 20. s add: 30.
|
||||
sum := 0.
|
||||
s do: [:e | sum := sum + e].
|
||||
self assert: sum equals: 60! !")
|
||||
|
||||
(smalltalk-load pharo-kernel-source)
|
||||
(smalltalk-load pharo-collections-source)
|
||||
|
||||
;; Run each test method individually and create one st-test row per test.
|
||||
;; A pharo test name like "IntegerTest >> testAddition" passes when the
|
||||
;; SUnit run yields exactly one pass and zero failures.
|
||||
(define
|
||||
pharo-test-class
|
||||
(fn
|
||||
(cls-name)
|
||||
(let ((selectors (sort (keys (get (st-class-get cls-name) :methods)))))
|
||||
(for-each
|
||||
(fn (sel)
|
||||
(when
|
||||
(and (>= (len sel) 4) (= (slice sel 0 4) "test"))
|
||||
(let
|
||||
((src (str "| s r | s := " cls-name " suiteForAll: #(#"
|
||||
sel "). r := s run.
|
||||
^ {(r passCount). (r failureCount). (r errorCount)}")))
|
||||
(let ((result (smalltalk-eval-program src)))
|
||||
(st-test
|
||||
(str cls-name " >> " sel)
|
||||
result
|
||||
(list 1 0 0))))))
|
||||
selectors))))
|
||||
|
||||
(pharo-test-class "IntegerTest")
|
||||
(pharo-test-class "StringTest")
|
||||
(pharo-test-class "BooleanTest")
|
||||
(pharo-test-class "ArrayTest")
|
||||
(pharo-test-class "DictionaryTest")
|
||||
(pharo-test-class "SetTest")
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,137 +0,0 @@
|
||||
"Pharo Collections-Tests slice — Array, Dictionary, Set."
|
||||
|
||||
TestCase subclass: #ArrayTest
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!ArrayTest methodsFor: 'creation'!
|
||||
testNewSize self assert: (Array new: 5) size equals: 5!
|
||||
testLiteralSize self assert: #(1 2 3) size equals: 3!
|
||||
testEmpty self assert: #() isEmpty!
|
||||
testNotEmpty self assert: #(1) notEmpty!
|
||||
testFirst self assert: #(10 20 30) first equals: 10!
|
||||
testLast self assert: #(10 20 30) last equals: 30! !
|
||||
|
||||
!ArrayTest methodsFor: 'access'!
|
||||
testAt self assert: (#(10 20 30) at: 2) equals: 20!
|
||||
testAtPut
|
||||
| a |
|
||||
a := Array new: 3.
|
||||
a at: 1 put: 'x'.
|
||||
a at: 2 put: 'y'.
|
||||
a at: 3 put: 'z'.
|
||||
self assert: (a at: 2) equals: 'y'! !
|
||||
|
||||
!ArrayTest methodsFor: 'iteration'!
|
||||
testDoSum
|
||||
| s |
|
||||
s := 0.
|
||||
#(1 2 3 4 5) do: [:e | s := s + e].
|
||||
self assert: s equals: 15!
|
||||
|
||||
testInjectInto self assert: (#(1 2 3 4) inject: 0 into: [:a :b | a + b]) equals: 10!
|
||||
|
||||
testCollect self assert: (#(1 2 3) collect: [:x | x * x]) equals: #(1 4 9)!
|
||||
|
||||
testSelect self assert: (#(1 2 3 4 5) select: [:x | x > 2]) equals: #(3 4 5)!
|
||||
|
||||
testReject self assert: (#(1 2 3 4 5) reject: [:x | x > 2]) equals: #(1 2)!
|
||||
|
||||
testDetect self assert: (#(1 3 5 7) detect: [:x | x > 4]) equals: 5!
|
||||
|
||||
testCount self assert: (#(1 2 3 4 5) count: [:x | x even]) equals: 2!
|
||||
|
||||
testAnySatisfy self assert: (#(1 2 3) anySatisfy: [:x | x > 2])!
|
||||
|
||||
testAllSatisfy self assert: (#(2 4 6) allSatisfy: [:x | x even])!
|
||||
|
||||
testIncludes self assert: (#(1 2 3) includes: 2)!
|
||||
|
||||
testIncludesNot self deny: (#(1 2 3) includes: 99)!
|
||||
|
||||
testIndexOf self assert: (#(10 20 30) indexOf: 30) equals: 3!
|
||||
|
||||
testIndexOfMissing self assert: (#(1 2 3) indexOf: 99) equals: 0! !
|
||||
|
||||
TestCase subclass: #DictionaryTest
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!DictionaryTest methodsFor: 'fixture'!
|
||||
setUp ^ self! !
|
||||
|
||||
!DictionaryTest methodsFor: 'tests'!
|
||||
testEmpty self assert: Dictionary new isEmpty!
|
||||
|
||||
testAtPutThenAt
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1.
|
||||
self assert: (d at: #a) equals: 1!
|
||||
|
||||
testAtMissingNil self assert: (Dictionary new at: #nope) equals: nil!
|
||||
|
||||
testAtIfAbsent
|
||||
self assert: (Dictionary new at: #nope ifAbsent: [#absent]) equals: #absent!
|
||||
|
||||
testSize
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2. d at: #c put: 3.
|
||||
self assert: d size equals: 3!
|
||||
|
||||
testIncludesKey
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1.
|
||||
self assert: (d includesKey: #a)!
|
||||
|
||||
testRemoveKey
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #a put: 1. d at: #b put: 2.
|
||||
d removeKey: #a.
|
||||
self deny: (d includesKey: #a)!
|
||||
|
||||
testOverwrite
|
||||
| d |
|
||||
d := Dictionary new.
|
||||
d at: #x put: 1. d at: #x put: 99.
|
||||
self assert: (d at: #x) equals: 99! !
|
||||
|
||||
TestCase subclass: #SetTest
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!SetTest methodsFor: 'tests'!
|
||||
testEmpty self assert: Set new isEmpty!
|
||||
|
||||
testAdd
|
||||
| s |
|
||||
s := Set new.
|
||||
s add: 1.
|
||||
self assert: (s includes: 1)!
|
||||
|
||||
testDedup
|
||||
| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 1. s add: 1.
|
||||
self assert: s size equals: 1!
|
||||
|
||||
testRemove
|
||||
| s |
|
||||
s := Set new.
|
||||
s add: 1. s add: 2.
|
||||
s remove: 1.
|
||||
self deny: (s includes: 1)!
|
||||
|
||||
testAddAll
|
||||
| s |
|
||||
s := Set new.
|
||||
s addAll: #(1 2 3 2 1).
|
||||
self assert: s size equals: 3!
|
||||
|
||||
testDoSum
|
||||
| s sum |
|
||||
s := Set new.
|
||||
s add: 10. s add: 20. s add: 30.
|
||||
sum := 0.
|
||||
s do: [:e | sum := sum + e].
|
||||
self assert: sum equals: 60! !
|
||||
@@ -1,89 +0,0 @@
|
||||
"Pharo Kernel-Tests slice — small subset of the canonical Pharo unit
|
||||
tests for SmallInteger, Float, String, Symbol, Boolean, Character.
|
||||
Runs through the SUnit framework defined in lib/smalltalk/sunit.sx."
|
||||
|
||||
TestCase subclass: #IntegerTest
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!IntegerTest methodsFor: 'arithmetic'!
|
||||
testAddition self assert: 2 + 3 equals: 5!
|
||||
testSubtraction self assert: 10 - 4 equals: 6!
|
||||
testMultiplication self assert: 6 * 7 equals: 42!
|
||||
testDivisionExact self assert: 10 / 2 equals: 5!
|
||||
testNegation self assert: 7 negated equals: -7!
|
||||
testAbs self assert: -5 abs equals: 5!
|
||||
testZero self assert: 0 + 0 equals: 0!
|
||||
testIdentity self assert: 42 == 42! !
|
||||
|
||||
!IntegerTest methodsFor: 'comparison'!
|
||||
testLessThan self assert: 1 < 2!
|
||||
testLessOrEqual self assert: 5 <= 5!
|
||||
testGreater self assert: 10 > 3!
|
||||
testEqualSelf self assert: 7 = 7!
|
||||
testNotEqual self assert: (3 ~= 5)!
|
||||
testBetween self assert: (5 between: 1 and: 10)! !
|
||||
|
||||
!IntegerTest methodsFor: 'predicates'!
|
||||
testEvenTrue self assert: 4 even!
|
||||
testEvenFalse self deny: 5 even!
|
||||
testOdd self assert: 3 odd!
|
||||
testIsInteger self assert: 0 isInteger!
|
||||
testIsNumber self assert: 1 isNumber!
|
||||
testIsZero self assert: 0 isZero!
|
||||
testIsNotZero self deny: 1 isZero! !
|
||||
|
||||
!IntegerTest methodsFor: 'powers and roots'!
|
||||
testFactorialZero self assert: 0 factorial equals: 1!
|
||||
testFactorialFive self assert: 5 factorial equals: 120!
|
||||
testRaisedTo self assert: (2 raisedTo: 8) equals: 256!
|
||||
testSquared self assert: 9 squared equals: 81!
|
||||
testSqrtPerfect self assert: 16 sqrt equals: 4!
|
||||
testGcd self assert: (24 gcd: 18) equals: 6!
|
||||
testLcm self assert: (4 lcm: 6) equals: 12! !
|
||||
|
||||
!IntegerTest methodsFor: 'rounding'!
|
||||
testFloor self assert: 3.7 floor equals: 3!
|
||||
testCeiling self assert: 3.2 ceiling equals: 4!
|
||||
testTruncated self assert: -3.7 truncated equals: -3!
|
||||
testRounded self assert: 3.5 rounded equals: 4! !
|
||||
|
||||
TestCase subclass: #StringTest
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!StringTest methodsFor: 'access'!
|
||||
testSize self assert: 'hello' size equals: 5!
|
||||
testEmpty self assert: '' isEmpty!
|
||||
testNotEmpty self assert: 'a' notEmpty!
|
||||
testAtFirst self assert: ('hello' at: 1) equals: 'h'!
|
||||
testAtLast self assert: ('hello' at: 5) equals: 'o'!
|
||||
testFirst self assert: 'world' first equals: 'w'!
|
||||
testLast self assert: 'world' last equals: 'd'! !
|
||||
|
||||
!StringTest methodsFor: 'concatenation'!
|
||||
testCommaConcat self assert: 'hello, ' , 'world' equals: 'hello, world'!
|
||||
testEmptyConcat self assert: '' , 'x' equals: 'x'!
|
||||
testSelfConcat self assert: 'ab' , 'ab' equals: 'abab'! !
|
||||
|
||||
!StringTest methodsFor: 'comparisons'!
|
||||
testEqual self assert: 'a' = 'a'!
|
||||
testNotEqual self deny: 'a' = 'b'!
|
||||
testIncludes self assert: ('banana' includes: $a)!
|
||||
testIncludesNot self deny: ('banana' includes: $z)!
|
||||
testIndexOf self assert: ('abcde' indexOf: $c) equals: 3! !
|
||||
|
||||
!StringTest methodsFor: 'transforms'!
|
||||
testCopyFromTo self assert: ('helloworld' copyFrom: 6 to: 10) equals: 'world'!
|
||||
testFormat self assert: ('Hello, {1}!' format: #('World')) equals: 'Hello, World!'! !
|
||||
|
||||
TestCase subclass: #BooleanTest
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!BooleanTest methodsFor: 'logic'!
|
||||
testNotTrue self deny: true not!
|
||||
testNotFalse self assert: false not!
|
||||
testAnd self assert: (true & true)!
|
||||
testOr self assert: (true | false)!
|
||||
testIfTrueTaken self assert: (true ifTrue: [1] ifFalse: [2]) equals: 1!
|
||||
testIfFalseTaken self assert: (false ifTrue: [1] ifFalse: [2]) equals: 2!
|
||||
testAndShortCircuit self assert: (false and: [1/0]) equals: false!
|
||||
testOrShortCircuit self assert: (true or: [1/0]) equals: true! !
|
||||
@@ -1,122 +0,0 @@
|
||||
;; String>>format: and printOn: tests.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. String>>format: ──
|
||||
(st-test "format: single placeholder"
|
||||
(ev "'Hello, {1}!' format: #('World')")
|
||||
"Hello, World!")
|
||||
|
||||
(st-test "format: multiple placeholders"
|
||||
(ev "'{1} + {2} = {3}' format: #(1 2 3)")
|
||||
"1 + 2 = 3")
|
||||
|
||||
(st-test "format: out-of-order"
|
||||
(ev "'{2} {1}' format: #('first' 'second')")
|
||||
"second first")
|
||||
|
||||
(st-test "format: repeated index"
|
||||
(ev "'{1}-{1}-{1}' format: #(#a)")
|
||||
"a-a-a")
|
||||
|
||||
(st-test "format: empty source"
|
||||
(ev "'' format: #()") "")
|
||||
|
||||
(st-test "format: no placeholders"
|
||||
(ev "'plain text' format: #()") "plain text")
|
||||
|
||||
(st-test "format: unmatched {"
|
||||
(ev "'open { brace' format: #('x')")
|
||||
"open { brace")
|
||||
|
||||
(st-test "format: out-of-range index keeps literal"
|
||||
(ev "'{99}' format: #('hi')")
|
||||
"{99}")
|
||||
|
||||
(st-test "format: numeric arg"
|
||||
(ev "'value: {1}' format: #(42)")
|
||||
"value: 42")
|
||||
|
||||
(st-test "format: float arg"
|
||||
(ev "'pi ~ {1}' format: #(3.14)")
|
||||
"pi ~ 3.14")
|
||||
|
||||
;; ── 2. printOn: writes printString to stream ──
|
||||
(st-test "printOn: writes int via stream"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream on: (Array new: 0).
|
||||
42 printOn: s.
|
||||
^ s contents")
|
||||
(list "4" "2"))
|
||||
|
||||
(st-test "printOn: writes string"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream on: (Array new: 0).
|
||||
'hi' printOn: s.
|
||||
^ s contents")
|
||||
(list "'" "h" "i" "'"))
|
||||
|
||||
(st-test "printOn: returns receiver"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream on: (Array new: 0).
|
||||
^ 99 printOn: s")
|
||||
99)
|
||||
|
||||
;; ── 3. Universal printString fallback for user instances ──
|
||||
(st-class-define! "Cat" "Object" (list))
|
||||
(st-class-define! "Animal" "Object" (list))
|
||||
|
||||
(st-test "printString of vowel-initial class"
|
||||
(evp "^ Animal new printString")
|
||||
"an Animal")
|
||||
|
||||
(st-test "printString of consonant-initial class"
|
||||
(evp "^ Cat new printString")
|
||||
"a Cat")
|
||||
|
||||
(st-test "user override of printString wins"
|
||||
(begin
|
||||
(st-class-add-method! "Cat" "printString"
|
||||
(st-parse-method "printString ^ #miaow asString"))
|
||||
(str (evp "^ Cat new printString")))
|
||||
"miaow")
|
||||
|
||||
;; ── 4. printOn: on user instance with overridden printString ──
|
||||
(st-test "printOn: respects user-overridden printString"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream on: (Array new: 0).
|
||||
Cat new printOn: s.
|
||||
^ s contents")
|
||||
(list "m" "i" "a" "o" "w"))
|
||||
|
||||
;; ── 5. printString for class-refs ──
|
||||
(st-test "Class printString is its name"
|
||||
(ev "Animal printString") "Animal")
|
||||
|
||||
;; ── 6. format: combined with printString ──
|
||||
(st-class-define! "Box" "Object" (list "n"))
|
||||
(st-class-add-method! "Box" "n:"
|
||||
(st-parse-method "n: v n := v. ^ self"))
|
||||
(st-class-add-method! "Box" "printString"
|
||||
(st-parse-method "printString ^ '<' , n printString , '>'"))
|
||||
|
||||
(st-test "format: with custom printString in arg"
|
||||
(str (evp
|
||||
"| b | b := Box new n: 7.
|
||||
^ '({1})' format: (Array with: b printString)"))
|
||||
"(<7>)")
|
||||
|
||||
(st-class-add-class-method! "Array" "with:"
|
||||
(st-parse-method "with: x | a | a := Array new: 1. a at: 1 put: x. ^ a"))
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,406 +0,0 @@
|
||||
;; Classic programs corpus tests.
|
||||
;;
|
||||
;; Each program lives in tests/programs/*.st as canonical Smalltalk source.
|
||||
;; This file embeds the same source as a string (until a file-read primitive
|
||||
;; lands) and runs it via smalltalk-load, then asserts behaviour.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── fibonacci.st (kept in sync with lib/smalltalk/tests/programs/fibonacci.st) ──
|
||||
(define
|
||||
fib-source
|
||||
"Object subclass: #Fibonacci
|
||||
instanceVariableNames: 'memo'!
|
||||
|
||||
!Fibonacci methodsFor: 'init'!
|
||||
init memo := Array new: 100. ^ self! !
|
||||
|
||||
!Fibonacci methodsFor: 'compute'!
|
||||
fib: n
|
||||
n < 2 ifTrue: [^ n].
|
||||
^ (self fib: n - 1) + (self fib: n - 2)!
|
||||
|
||||
memoFib: n
|
||||
| cached |
|
||||
cached := memo at: n + 1.
|
||||
cached notNil ifTrue: [^ cached].
|
||||
cached := n < 2
|
||||
ifTrue: [n]
|
||||
ifFalse: [(self memoFib: n - 1) + (self memoFib: n - 2)].
|
||||
memo at: n + 1 put: cached.
|
||||
^ cached! !")
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(smalltalk-load fib-source)
|
||||
|
||||
(st-test "fib(0)" (evp "^ Fibonacci new fib: 0") 0)
|
||||
(st-test "fib(1)" (evp "^ Fibonacci new fib: 1") 1)
|
||||
(st-test "fib(2)" (evp "^ Fibonacci new fib: 2") 1)
|
||||
(st-test "fib(5)" (evp "^ Fibonacci new fib: 5") 5)
|
||||
(st-test "fib(10)" (evp "^ Fibonacci new fib: 10") 55)
|
||||
(st-test "fib(15)" (evp "^ Fibonacci new fib: 15") 610)
|
||||
|
||||
(st-test "memoFib(20)"
|
||||
(evp "| f | f := Fibonacci new init. ^ f memoFib: 20")
|
||||
6765)
|
||||
|
||||
(st-test "memoFib(30)"
|
||||
(evp "| f | f := Fibonacci new init. ^ f memoFib: 30")
|
||||
832040)
|
||||
|
||||
;; Memoisation actually populates the array.
|
||||
(st-test "memo cache stores intermediate"
|
||||
(evp
|
||||
"| f | f := Fibonacci new init.
|
||||
f memoFib: 12.
|
||||
^ #(0 1 1 2 3 5) , #() , #()")
|
||||
(list 0 1 1 2 3 5))
|
||||
|
||||
;; The class is reachable from the bootstrap class table.
|
||||
(st-test "Fibonacci class exists in table" (st-class-exists? "Fibonacci") true)
|
||||
(st-test "Fibonacci has memo ivar"
|
||||
(get (st-class-get "Fibonacci") :ivars)
|
||||
(list "memo"))
|
||||
|
||||
;; Method dictionary holds the three methods.
|
||||
(st-test "Fibonacci methodDict size"
|
||||
(len (keys (get (st-class-get "Fibonacci") :methods)))
|
||||
3)
|
||||
|
||||
;; Each fib call is independent (no shared state between two instances).
|
||||
(st-test "two memo instances independent"
|
||||
(evp
|
||||
"| a b |
|
||||
a := Fibonacci new init.
|
||||
b := Fibonacci new init.
|
||||
a memoFib: 10.
|
||||
^ b memoFib: 10")
|
||||
55)
|
||||
|
||||
;; ── eight-queens.st (kept in sync with lib/smalltalk/tests/programs/eight-queens.st) ──
|
||||
(define
|
||||
queens-source
|
||||
"Object subclass: #EightQueens
|
||||
instanceVariableNames: 'columns count size'!
|
||||
|
||||
!EightQueens methodsFor: 'init'!
|
||||
init
|
||||
size := 8.
|
||||
columns := Array new: size.
|
||||
count := 0.
|
||||
^ self!
|
||||
|
||||
size: n
|
||||
size := n.
|
||||
columns := Array new: n.
|
||||
count := 0.
|
||||
^ self! !
|
||||
|
||||
!EightQueens methodsFor: 'access'!
|
||||
count ^ count!
|
||||
|
||||
size ^ size! !
|
||||
|
||||
!EightQueens methodsFor: 'solve'!
|
||||
solve
|
||||
self placeRow: 1.
|
||||
^ count!
|
||||
|
||||
placeRow: row
|
||||
row > size ifTrue: [count := count + 1. ^ self].
|
||||
1 to: size do: [:col |
|
||||
(self isSafe: col atRow: row) ifTrue: [
|
||||
columns at: row put: col.
|
||||
self placeRow: row + 1]]!
|
||||
|
||||
isSafe: col atRow: row
|
||||
| r prevCol delta |
|
||||
r := 1.
|
||||
[r < row] whileTrue: [
|
||||
prevCol := columns at: r.
|
||||
prevCol = col ifTrue: [^ false].
|
||||
delta := col - prevCol.
|
||||
delta abs = (row - r) ifTrue: [^ false].
|
||||
r := r + 1].
|
||||
^ true! !")
|
||||
|
||||
(smalltalk-load queens-source)
|
||||
|
||||
;; Backtracking is correct but slow on the spec interpreter (call/cc per
|
||||
;; method, dict-based ivar reads). 4- and 5-queens cover the corners
|
||||
;; and run in under 10s; 6+ work but would push past the test-runner
|
||||
;; timeout. The class itself defaults to size 8, ready for the JIT.
|
||||
(st-test "1 queen on 1x1 board" (evp "^ (EightQueens new size: 1) solve") 1)
|
||||
(st-test "4 queens on 4x4 board" (evp "^ (EightQueens new size: 4) solve") 2)
|
||||
(st-test "5 queens on 5x5 board" (evp "^ (EightQueens new size: 5) solve") 10)
|
||||
(st-test "EightQueens class is registered" (st-class-exists? "EightQueens") true)
|
||||
(st-test "EightQueens init sets size 8"
|
||||
(evp "^ EightQueens new init size") 8)
|
||||
|
||||
;; ── quicksort.st ─────────────────────────────────────────────────────
|
||||
(define
|
||||
quicksort-source
|
||||
"Object subclass: #Quicksort
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!Quicksort methodsFor: 'sort'!
|
||||
sort: arr ^ self sort: arr from: 1 to: arr size!
|
||||
|
||||
sort: arr from: low to: high
|
||||
| p |
|
||||
low < high ifTrue: [
|
||||
p := self partition: arr from: low to: high.
|
||||
self sort: arr from: low to: p - 1.
|
||||
self sort: arr from: p + 1 to: high].
|
||||
^ arr!
|
||||
|
||||
partition: arr from: low to: high
|
||||
| pivot i tmp |
|
||||
pivot := arr at: high.
|
||||
i := low - 1.
|
||||
low to: high - 1 do: [:j |
|
||||
(arr at: j) <= pivot ifTrue: [
|
||||
i := i + 1.
|
||||
tmp := arr at: i.
|
||||
arr at: i put: (arr at: j).
|
||||
arr at: j put: tmp]].
|
||||
tmp := arr at: i + 1.
|
||||
arr at: i + 1 put: (arr at: high).
|
||||
arr at: high put: tmp.
|
||||
^ i + 1! !")
|
||||
|
||||
(smalltalk-load quicksort-source)
|
||||
|
||||
(st-test "Quicksort class registered" (st-class-exists? "Quicksort") true)
|
||||
|
||||
(st-test "qsort small array"
|
||||
(evp "^ Quicksort new sort: #(3 1 2)")
|
||||
(list 1 2 3))
|
||||
|
||||
(st-test "qsort with duplicates"
|
||||
(evp "^ Quicksort new sort: #(3 1 4 1 5 9 2 6 5 3 5)")
|
||||
(list 1 1 2 3 3 4 5 5 5 6 9))
|
||||
|
||||
(st-test "qsort already-sorted"
|
||||
(evp "^ Quicksort new sort: #(1 2 3 4 5)")
|
||||
(list 1 2 3 4 5))
|
||||
|
||||
(st-test "qsort reverse-sorted"
|
||||
(evp "^ Quicksort new sort: #(9 7 5 3 1)")
|
||||
(list 1 3 5 7 9))
|
||||
|
||||
(st-test "qsort single element"
|
||||
(evp "^ Quicksort new sort: #(42)")
|
||||
(list 42))
|
||||
|
||||
(st-test "qsort empty"
|
||||
(evp "^ Quicksort new sort: #()")
|
||||
(list))
|
||||
|
||||
(st-test "qsort negatives"
|
||||
(evp "^ Quicksort new sort: #(-3 -1 -7 0 2)")
|
||||
(list -7 -3 -1 0 2))
|
||||
|
||||
(st-test "qsort all-equal"
|
||||
(evp "^ Quicksort new sort: #(5 5 5 5)")
|
||||
(list 5 5 5 5))
|
||||
|
||||
(st-test "qsort sorts in place (returns same array)"
|
||||
(evp
|
||||
"| arr q |
|
||||
arr := #(4 2 1 3).
|
||||
q := Quicksort new.
|
||||
q sort: arr.
|
||||
^ arr")
|
||||
(list 1 2 3 4))
|
||||
|
||||
;; ── mandelbrot.st ────────────────────────────────────────────────────
|
||||
(define
|
||||
mandel-source
|
||||
"Object subclass: #Mandelbrot
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!Mandelbrot methodsFor: 'iteration'!
|
||||
escapeAt: cx and: cy maxIter: maxIter
|
||||
| zx zy zx2 zy2 i |
|
||||
zx := 0. zy := 0.
|
||||
zx2 := 0. zy2 := 0.
|
||||
i := 0.
|
||||
[(zx2 + zy2 < 4) and: [i < maxIter]] whileTrue: [
|
||||
zy := (zx * zy * 2) + cy.
|
||||
zx := zx2 - zy2 + cx.
|
||||
zx2 := zx * zx.
|
||||
zy2 := zy * zy.
|
||||
i := i + 1].
|
||||
^ i!
|
||||
|
||||
inside: cx and: cy maxIter: maxIter
|
||||
^ (self escapeAt: cx and: cy maxIter: maxIter) >= maxIter! !
|
||||
|
||||
!Mandelbrot methodsFor: 'grid'!
|
||||
countInsideRangeX: x0 to: x1 stepX: dx rangeY: y0 to: y1 stepY: dy maxIter: maxIter
|
||||
| x y count |
|
||||
count := 0.
|
||||
y := y0.
|
||||
[y <= y1] whileTrue: [
|
||||
x := x0.
|
||||
[x <= x1] whileTrue: [
|
||||
(self inside: x and: y maxIter: maxIter) ifTrue: [count := count + 1].
|
||||
x := x + dx].
|
||||
y := y + dy].
|
||||
^ count! !")
|
||||
|
||||
(smalltalk-load mandel-source)
|
||||
|
||||
(st-test "Mandelbrot class registered" (st-class-exists? "Mandelbrot") true)
|
||||
|
||||
;; The origin is the cusp of the cardioid — z stays at 0 forever.
|
||||
(st-test "origin is in the set"
|
||||
(evp "^ Mandelbrot new inside: 0 and: 0 maxIter: 50") true)
|
||||
|
||||
;; (-1, 0) — z₀=0, z₁=-1, z₂=0, … oscillates and stays bounded.
|
||||
(st-test "(-1, 0) is in the set"
|
||||
(evp "^ Mandelbrot new inside: -1 and: 0 maxIter: 50") true)
|
||||
|
||||
;; (1, 0) — escapes after 2 iterations: 0 → 1 → 2, |z|² = 4 ≥ 4.
|
||||
(st-test "(1, 0) escapes quickly"
|
||||
(evp "^ Mandelbrot new escapeAt: 1 and: 0 maxIter: 50") 2)
|
||||
|
||||
;; (2, 0) — escapes immediately: 0 → 2, |z|² = 4 ≥ 4 already.
|
||||
(st-test "(2, 0) escapes after 1 step"
|
||||
(evp "^ Mandelbrot new escapeAt: 2 and: 0 maxIter: 50") 1)
|
||||
|
||||
;; (-2, 0) — z₀=0; iter 1: z₁=-2, |z|²=4, condition `< 4` fails → exits at i=1.
|
||||
(st-test "(-2, 0) escapes after 1 step"
|
||||
(evp "^ Mandelbrot new escapeAt: -2 and: 0 maxIter: 50") 1)
|
||||
|
||||
;; (10, 10) — far outside, escapes on the first step.
|
||||
(st-test "(10, 10) escapes after 1 step"
|
||||
(evp "^ Mandelbrot new escapeAt: 10 and: 10 maxIter: 50") 1)
|
||||
|
||||
;; Coarse 5x5 grid (-2..2 in 1-step increments, no half-steps to keep
|
||||
;; this fast). Membership of (-1,0), (0,0), (-1,-1)? We expect just
|
||||
;; (0,0) and (-1,0) at maxIter 30.
|
||||
;; Actually let's count exact membership at this resolution.
|
||||
(st-test "tiny 3x3 grid count"
|
||||
(evp
|
||||
"^ Mandelbrot new countInsideRangeX: -1 to: 1 stepX: 1
|
||||
rangeY: -1 to: 1 stepY: 1
|
||||
maxIter: 30")
|
||||
;; In-set points (bounded after 30 iters): (0,-1) (-1,0) (0,0) (0,1) → 4.
|
||||
4)
|
||||
|
||||
;; ── life.st ──────────────────────────────────────────────────────────
|
||||
(define
|
||||
life-source
|
||||
"Object subclass: #Life
|
||||
instanceVariableNames: 'rows cols cells'!
|
||||
|
||||
!Life methodsFor: 'init'!
|
||||
rows: r cols: c
|
||||
rows := r. cols := c.
|
||||
cells := Array new: r * c.
|
||||
1 to: r * c do: [:i | cells at: i put: 0].
|
||||
^ self! !
|
||||
|
||||
!Life methodsFor: 'access'!
|
||||
rows ^ rows!
|
||||
cols ^ cols!
|
||||
|
||||
at: r at: c
|
||||
((r < 1) or: [r > rows]) ifTrue: [^ 0].
|
||||
((c < 1) or: [c > cols]) ifTrue: [^ 0].
|
||||
^ cells at: (r - 1) * cols + c!
|
||||
|
||||
at: r at: c put: v
|
||||
cells at: (r - 1) * cols + c put: v.
|
||||
^ v! !
|
||||
|
||||
!Life methodsFor: 'step'!
|
||||
neighbors: r at: c
|
||||
| sum |
|
||||
sum := 0.
|
||||
-1 to: 1 do: [:dr |
|
||||
-1 to: 1 do: [:dc |
|
||||
((dr = 0) and: [dc = 0]) ifFalse: [
|
||||
sum := sum + (self at: r + dr at: c + dc)]]].
|
||||
^ sum!
|
||||
|
||||
step
|
||||
| next |
|
||||
next := Array new: rows * cols.
|
||||
1 to: rows * cols do: [:i | next at: i put: 0].
|
||||
1 to: rows do: [:r |
|
||||
1 to: cols do: [:c |
|
||||
| n alive lives |
|
||||
n := self neighbors: r at: c.
|
||||
alive := (self at: r at: c) = 1.
|
||||
lives := alive
|
||||
ifTrue: [(n = 2) or: [n = 3]]
|
||||
ifFalse: [n = 3].
|
||||
lives ifTrue: [next at: (r - 1) * cols + c put: 1]]].
|
||||
cells := next.
|
||||
^ self!
|
||||
|
||||
stepN: n
|
||||
n timesRepeat: [self step].
|
||||
^ self! !
|
||||
|
||||
!Life methodsFor: 'measure'!
|
||||
livingCount
|
||||
| sum |
|
||||
sum := 0.
|
||||
1 to: rows * cols do: [:i | (cells at: i) = 1 ifTrue: [sum := sum + 1]].
|
||||
^ sum! !")
|
||||
|
||||
(smalltalk-load life-source)
|
||||
|
||||
(st-test "Life class registered" (st-class-exists? "Life") true)
|
||||
|
||||
;; Block (still life): four cells in a 2x2 stay forever after 1 step.
|
||||
;; The bigger patterns are correct but the spec interpreter is too slow
|
||||
;; for many-step verification — the `.st` file is ready for the JIT.
|
||||
(st-test "block (still life) survives 1 step"
|
||||
(evp
|
||||
"| g |
|
||||
g := Life new rows: 5 cols: 5.
|
||||
g at: 2 at: 2 put: 1.
|
||||
g at: 2 at: 3 put: 1.
|
||||
g at: 3 at: 2 put: 1.
|
||||
g at: 3 at: 3 put: 1.
|
||||
g step.
|
||||
^ g livingCount")
|
||||
4)
|
||||
|
||||
;; Blinker (period 2): horizontal row of 3 → vertical column.
|
||||
(st-test "blinker after 1 step is vertical"
|
||||
(evp
|
||||
"| g |
|
||||
g := Life new rows: 5 cols: 5.
|
||||
g at: 3 at: 2 put: 1.
|
||||
g at: 3 at: 3 put: 1.
|
||||
g at: 3 at: 4 put: 1.
|
||||
g step.
|
||||
^ {(g at: 2 at: 3). (g at: 3 at: 3). (g at: 4 at: 3). (g at: 3 at: 2). (g at: 3 at: 4)}")
|
||||
;; (2,3) (3,3) (4,3) on; (3,2) (3,4) off
|
||||
(list 1 1 1 0 0))
|
||||
|
||||
;; Glider initial setup — 5 living cells, no step.
|
||||
(st-test "glider has 5 living cells initially"
|
||||
(evp
|
||||
"| g |
|
||||
g := Life new rows: 8 cols: 8.
|
||||
g at: 1 at: 2 put: 1.
|
||||
g at: 2 at: 3 put: 1.
|
||||
g at: 3 at: 1 put: 1.
|
||||
g at: 3 at: 2 put: 1.
|
||||
g at: 3 at: 3 put: 1.
|
||||
^ g livingCount")
|
||||
5)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,47 +0,0 @@
|
||||
"Eight-queens — classic backtracking search. Counts the number of
|
||||
distinct placements of 8 queens on an 8x8 board with no two attacking.
|
||||
Expected count: 92."
|
||||
|
||||
Object subclass: #EightQueens
|
||||
instanceVariableNames: 'columns count size'!
|
||||
|
||||
!EightQueens methodsFor: 'init'!
|
||||
init
|
||||
size := 8.
|
||||
columns := Array new: size.
|
||||
count := 0.
|
||||
^ self!
|
||||
|
||||
size: n
|
||||
size := n.
|
||||
columns := Array new: n.
|
||||
count := 0.
|
||||
^ self! !
|
||||
|
||||
!EightQueens methodsFor: 'access'!
|
||||
count ^ count!
|
||||
|
||||
size ^ size! !
|
||||
|
||||
!EightQueens methodsFor: 'solve'!
|
||||
solve
|
||||
self placeRow: 1.
|
||||
^ count!
|
||||
|
||||
placeRow: row
|
||||
row > size ifTrue: [count := count + 1. ^ self].
|
||||
1 to: size do: [:col |
|
||||
(self isSafe: col atRow: row) ifTrue: [
|
||||
columns at: row put: col.
|
||||
self placeRow: row + 1]]!
|
||||
|
||||
isSafe: col atRow: row
|
||||
| r prevCol delta |
|
||||
r := 1.
|
||||
[r < row] whileTrue: [
|
||||
prevCol := columns at: r.
|
||||
prevCol = col ifTrue: [^ false].
|
||||
delta := col - prevCol.
|
||||
delta abs = (row - r) ifTrue: [^ false].
|
||||
r := r + 1].
|
||||
^ true! !
|
||||
@@ -1,23 +0,0 @@
|
||||
"Fibonacci — recursive and array-memoised. Classic-corpus program for
|
||||
the Smalltalk-on-SX runtime."
|
||||
|
||||
Object subclass: #Fibonacci
|
||||
instanceVariableNames: 'memo'!
|
||||
|
||||
!Fibonacci methodsFor: 'init'!
|
||||
init memo := Array new: 100. ^ self! !
|
||||
|
||||
!Fibonacci methodsFor: 'compute'!
|
||||
fib: n
|
||||
n < 2 ifTrue: [^ n].
|
||||
^ (self fib: n - 1) + (self fib: n - 2)!
|
||||
|
||||
memoFib: n
|
||||
| cached |
|
||||
cached := memo at: n + 1.
|
||||
cached notNil ifTrue: [^ cached].
|
||||
cached := n < 2
|
||||
ifTrue: [n]
|
||||
ifFalse: [(self memoFib: n - 1) + (self memoFib: n - 2)].
|
||||
memo at: n + 1 put: cached.
|
||||
^ cached! !
|
||||
@@ -1,66 +0,0 @@
|
||||
"Conway's Game of Life — 2D grid stepped by the standard rules:
|
||||
live with 2 or 3 neighbours stays alive; dead with exactly 3 becomes alive.
|
||||
Classic-corpus program for the Smalltalk-on-SX runtime. The canonical
|
||||
'glider gun' demo (~36 cells, period-30 emission) is correct but too slow
|
||||
to verify on the spec interpreter without JIT — block, blinker, glider
|
||||
cover the rule arithmetic and edge handling."
|
||||
|
||||
Object subclass: #Life
|
||||
instanceVariableNames: 'rows cols cells'!
|
||||
|
||||
!Life methodsFor: 'init'!
|
||||
rows: r cols: c
|
||||
rows := r. cols := c.
|
||||
cells := Array new: r * c.
|
||||
1 to: r * c do: [:i | cells at: i put: 0].
|
||||
^ self! !
|
||||
|
||||
!Life methodsFor: 'access'!
|
||||
rows ^ rows!
|
||||
cols ^ cols!
|
||||
|
||||
at: r at: c
|
||||
((r < 1) or: [r > rows]) ifTrue: [^ 0].
|
||||
((c < 1) or: [c > cols]) ifTrue: [^ 0].
|
||||
^ cells at: (r - 1) * cols + c!
|
||||
|
||||
at: r at: c put: v
|
||||
cells at: (r - 1) * cols + c put: v.
|
||||
^ v! !
|
||||
|
||||
!Life methodsFor: 'step'!
|
||||
neighbors: r at: c
|
||||
| sum |
|
||||
sum := 0.
|
||||
-1 to: 1 do: [:dr |
|
||||
-1 to: 1 do: [:dc |
|
||||
((dr = 0) and: [dc = 0]) ifFalse: [
|
||||
sum := sum + (self at: r + dr at: c + dc)]]].
|
||||
^ sum!
|
||||
|
||||
step
|
||||
| next |
|
||||
next := Array new: rows * cols.
|
||||
1 to: rows * cols do: [:i | next at: i put: 0].
|
||||
1 to: rows do: [:r |
|
||||
1 to: cols do: [:c |
|
||||
| n alive lives |
|
||||
n := self neighbors: r at: c.
|
||||
alive := (self at: r at: c) = 1.
|
||||
lives := alive
|
||||
ifTrue: [(n = 2) or: [n = 3]]
|
||||
ifFalse: [n = 3].
|
||||
lives ifTrue: [next at: (r - 1) * cols + c put: 1]]].
|
||||
cells := next.
|
||||
^ self!
|
||||
|
||||
stepN: n
|
||||
n timesRepeat: [self step].
|
||||
^ self! !
|
||||
|
||||
!Life methodsFor: 'measure'!
|
||||
livingCount
|
||||
| sum |
|
||||
sum := 0.
|
||||
1 to: rows * cols do: [:i | (cells at: i) = 1 ifTrue: [sum := sum + 1]].
|
||||
^ sum! !
|
||||
@@ -1,36 +0,0 @@
|
||||
"Mandelbrot — escape-time iteration of z := z² + c starting at z₀ = 0.
|
||||
Returns the number of iterations before |z|² exceeds 4, capped at
|
||||
maxIter. Classic-corpus program for the Smalltalk-on-SX runtime."
|
||||
|
||||
Object subclass: #Mandelbrot
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!Mandelbrot methodsFor: 'iteration'!
|
||||
escapeAt: cx and: cy maxIter: maxIter
|
||||
| zx zy zx2 zy2 i |
|
||||
zx := 0. zy := 0.
|
||||
zx2 := 0. zy2 := 0.
|
||||
i := 0.
|
||||
[(zx2 + zy2 < 4) and: [i < maxIter]] whileTrue: [
|
||||
zy := (zx * zy * 2) + cy.
|
||||
zx := zx2 - zy2 + cx.
|
||||
zx2 := zx * zx.
|
||||
zy2 := zy * zy.
|
||||
i := i + 1].
|
||||
^ i!
|
||||
|
||||
inside: cx and: cy maxIter: maxIter
|
||||
^ (self escapeAt: cx and: cy maxIter: maxIter) >= maxIter! !
|
||||
|
||||
!Mandelbrot methodsFor: 'grid'!
|
||||
countInsideRangeX: x0 to: x1 stepX: dx rangeY: y0 to: y1 stepY: dy maxIter: maxIter
|
||||
| x y count |
|
||||
count := 0.
|
||||
y := y0.
|
||||
[y <= y1] whileTrue: [
|
||||
x := x0.
|
||||
[x <= x1] whileTrue: [
|
||||
(self inside: x and: y maxIter: maxIter) ifTrue: [count := count + 1].
|
||||
x := x + dx].
|
||||
y := y + dy].
|
||||
^ count! !
|
||||
@@ -1,31 +0,0 @@
|
||||
"Quicksort — Lomuto partition. Sorts an Array in place. Classic-corpus
|
||||
program for the Smalltalk-on-SX runtime."
|
||||
|
||||
Object subclass: #Quicksort
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!Quicksort methodsFor: 'sort'!
|
||||
sort: arr ^ self sort: arr from: 1 to: arr size!
|
||||
|
||||
sort: arr from: low to: high
|
||||
| p |
|
||||
low < high ifTrue: [
|
||||
p := self partition: arr from: low to: high.
|
||||
self sort: arr from: low to: p - 1.
|
||||
self sort: arr from: p + 1 to: high].
|
||||
^ arr!
|
||||
|
||||
partition: arr from: low to: high
|
||||
| pivot i tmp |
|
||||
pivot := arr at: high.
|
||||
i := low - 1.
|
||||
low to: high - 1 do: [:j |
|
||||
(arr at: j) <= pivot ifTrue: [
|
||||
i := i + 1.
|
||||
tmp := arr at: i.
|
||||
arr at: i put: (arr at: j).
|
||||
arr at: j put: tmp]].
|
||||
tmp := arr at: i + 1.
|
||||
arr at: i + 1 put: (arr at: high).
|
||||
arr at: high put: tmp.
|
||||
^ i + 1! !
|
||||
@@ -1,304 +0,0 @@
|
||||
;; Reflection accessors: Object>>class, class>>name, class>>superclass,
|
||||
;; class>>methodDict, class>>selectors. Phase 4 starting point.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Object>>class on native receivers ──
|
||||
(st-test "42 class name" (ev "42 class name") "SmallInteger")
|
||||
(st-test "3.14 class name" (ev "3.14 class name") "Float")
|
||||
(st-test "'hi' class name" (ev "'hi' class name") "String")
|
||||
(st-test "#foo class name" (ev "#foo class name") "Symbol")
|
||||
(st-test "true class name" (ev "true class name") "True")
|
||||
(st-test "false class name" (ev "false class name") "False")
|
||||
(st-test "nil class name" (ev "nil class name") "UndefinedObject")
|
||||
(st-test "$a class name" (ev "$a class name") "String")
|
||||
(st-test "#(1 2 3) class name" (ev "#(1 2 3) class name") "Array")
|
||||
(st-test "[42] class name" (ev "[42] class name") "BlockClosure")
|
||||
|
||||
;; ── 2. Object>>class on user instances ──
|
||||
(st-class-define! "Cat" "Object" (list "name"))
|
||||
(st-test "user instance class name"
|
||||
(evp "^ Cat new class name") "Cat")
|
||||
(st-test "user instance class superclass name"
|
||||
(evp "^ Cat new class superclass name") "Object")
|
||||
|
||||
;; ── 3. class>>name / class>>superclass ──
|
||||
(st-test "class>>name on Object" (ev "Object name") "Object")
|
||||
(st-test "class>>superclass on Object" (ev "Object superclass") nil)
|
||||
(st-test "class>>superclass on Symbol"
|
||||
(ev "Symbol superclass name") "String")
|
||||
(st-test "class>>superclass on String"
|
||||
(ev "String superclass name") "ArrayedCollection")
|
||||
|
||||
;; ── 4. class>>class returns Metaclass ──
|
||||
(st-test "Cat class is Metaclass"
|
||||
(ev "Cat class name") "Metaclass")
|
||||
|
||||
;; ── 5. class>>methodDict ──
|
||||
(st-class-add-method! "Cat" "miaow" (st-parse-method "miaow ^ #miaow"))
|
||||
(st-class-add-method! "Cat" "purr" (st-parse-method "purr ^ #purr"))
|
||||
|
||||
(st-test
|
||||
"methodDict has expected keys"
|
||||
(sort (keys (ev "Cat methodDict")))
|
||||
(sort (list "miaow" "purr")))
|
||||
|
||||
(st-test
|
||||
"methodDict size after two adds"
|
||||
(len (keys (ev "Cat methodDict")))
|
||||
2)
|
||||
|
||||
;; ── 6. class>>selectors ──
|
||||
(st-test
|
||||
"selectors returns Array of symbols"
|
||||
(sort (map (fn (s) (str s)) (ev "Cat selectors")))
|
||||
(sort (list "miaow" "purr")))
|
||||
|
||||
;; ── 7. class>>instanceVariableNames ──
|
||||
(st-test "instance variable names"
|
||||
(ev "Cat instanceVariableNames") (list "name"))
|
||||
|
||||
(st-class-define! "Kitten" "Cat" (list "age"))
|
||||
(st-test "subclass own ivars"
|
||||
(ev "Kitten instanceVariableNames") (list "age"))
|
||||
(st-test "subclass allInstVarNames includes inherited"
|
||||
(ev "Kitten allInstVarNames") (list "name" "age"))
|
||||
|
||||
;; ── 8. methodDict reflects new methods ──
|
||||
(st-class-add-method! "Cat" "scratch" (st-parse-method "scratch ^ #scratch"))
|
||||
(st-test "methodDict updated after add"
|
||||
(len (keys (ev "Cat methodDict"))) 3)
|
||||
|
||||
;; ── 9. classMethodDict / classSelectors ──
|
||||
(st-class-add-class-method! "Cat" "named:"
|
||||
(st-parse-method "named: aName ^ self new"))
|
||||
(st-test "classSelectors"
|
||||
(map (fn (s) (str s)) (ev "Cat classSelectors")) (list "named:"))
|
||||
|
||||
;; ── 10. Method records are usable values ──
|
||||
(st-test "methodDict at: returns method record dict"
|
||||
(dict? (get (ev "Cat methodDict") "miaow")) true)
|
||||
|
||||
;; ── 11. Object>>perform: ──
|
||||
(st-test "perform: a unary selector"
|
||||
(str (evp "^ Cat new perform: #miaow"))
|
||||
"miaow")
|
||||
|
||||
(st-test "perform: works on native receiver"
|
||||
(ev "42 perform: #printString")
|
||||
"42")
|
||||
|
||||
(st-test "perform: with no method falls back to DNU"
|
||||
;; With no Object DNU defined here, perform: a missing selector raises.
|
||||
;; Wrap in guard to catch.
|
||||
(let ((caught false))
|
||||
(begin
|
||||
(guard (c (true (set! caught true)))
|
||||
(evp "^ Cat new perform: #nonexistent"))
|
||||
caught))
|
||||
true)
|
||||
|
||||
;; ── 12. Object>>perform:with: ──
|
||||
(st-class-add-method! "Cat" "say:"
|
||||
(st-parse-method "say: aMsg ^ aMsg"))
|
||||
|
||||
(st-test "perform:with: passes arg through"
|
||||
(evp "^ Cat new perform: #say: with: 'hi'") "hi")
|
||||
|
||||
(st-test "perform:with: on native"
|
||||
(ev "10 perform: #+ with: 5") 15)
|
||||
|
||||
;; ── 13. Object>>perform:with:with: (multi-arg form) ──
|
||||
(st-class-add-method! "Cat" "describe:and:"
|
||||
(st-parse-method "describe: a and: b ^ a , b"))
|
||||
|
||||
(st-test "perform:with:with: keyword selector"
|
||||
(evp "^ Cat new perform: #describe:and: with: 'foo' with: 'bar'")
|
||||
"foobar")
|
||||
|
||||
;; ── 14. Object>>perform:withArguments: ──
|
||||
(st-test "perform:withArguments: empty array"
|
||||
(str (evp "^ Cat new perform: #miaow withArguments: #()"))
|
||||
"miaow")
|
||||
|
||||
(st-test "perform:withArguments: 1 element"
|
||||
(evp "^ Cat new perform: #say: withArguments: #('hello')")
|
||||
"hello")
|
||||
|
||||
(st-test "perform:withArguments: 2 elements"
|
||||
(evp "^ Cat new perform: #describe:and: withArguments: #('a' 'b')")
|
||||
"ab")
|
||||
|
||||
(st-test "perform:withArguments: on native receiver"
|
||||
(ev "20 perform: #+ withArguments: #(5)") 25)
|
||||
|
||||
;; perform: routes through ordinary dispatch, so super, DNU, primitives
|
||||
;; all still apply naturally. No special test for that — it's free.
|
||||
|
||||
;; ── 15. isKindOf: walks the class chain ──
|
||||
(st-test "42 isKindOf: SmallInteger" (ev "42 isKindOf: SmallInteger") true)
|
||||
(st-test "42 isKindOf: Integer" (ev "42 isKindOf: Integer") true)
|
||||
(st-test "42 isKindOf: Number" (ev "42 isKindOf: Number") true)
|
||||
(st-test "42 isKindOf: Magnitude" (ev "42 isKindOf: Magnitude") true)
|
||||
(st-test "42 isKindOf: Object" (ev "42 isKindOf: Object") true)
|
||||
(st-test "42 isKindOf: String" (ev "42 isKindOf: String") false)
|
||||
(st-test "3.14 isKindOf: Float" (ev "3.14 isKindOf: Float") true)
|
||||
(st-test "3.14 isKindOf: Number" (ev "3.14 isKindOf: Number") true)
|
||||
|
||||
(st-test "'hi' isKindOf: String" (ev "'hi' isKindOf: String") true)
|
||||
(st-test "'hi' isKindOf: ArrayedCollection"
|
||||
(ev "'hi' isKindOf: ArrayedCollection") true)
|
||||
(st-test "true isKindOf: Boolean" (ev "true isKindOf: Boolean") true)
|
||||
(st-test "nil isKindOf: UndefinedObject"
|
||||
(ev "nil isKindOf: UndefinedObject") true)
|
||||
|
||||
;; User-class chain.
|
||||
(st-test "Cat new isKindOf: Cat" (evp "^ Cat new isKindOf: Cat") true)
|
||||
(st-test "Cat new isKindOf: Object" (evp "^ Cat new isKindOf: Object") true)
|
||||
(st-test "Cat new isKindOf: Boolean"
|
||||
(evp "^ Cat new isKindOf: Boolean") false)
|
||||
(st-test "Kitten new isKindOf: Cat"
|
||||
(evp "^ Kitten new isKindOf: Cat") true)
|
||||
|
||||
;; ── 16. isMemberOf: requires exact class match ──
|
||||
(st-test "42 isMemberOf: SmallInteger" (ev "42 isMemberOf: SmallInteger") true)
|
||||
(st-test "42 isMemberOf: Integer" (ev "42 isMemberOf: Integer") false)
|
||||
(st-test "42 isMemberOf: Number" (ev "42 isMemberOf: Number") false)
|
||||
(st-test "Cat new isMemberOf: Cat"
|
||||
(evp "^ Cat new isMemberOf: Cat") true)
|
||||
(st-test "Cat new isMemberOf: Kitten"
|
||||
(evp "^ Cat new isMemberOf: Kitten") false)
|
||||
|
||||
;; ── 17. respondsTo: — user method dictionary search ──
|
||||
(st-test "Cat respondsTo: #miaow"
|
||||
(evp "^ Cat new respondsTo: #miaow") true)
|
||||
(st-test "Cat respondsTo: inherited (only own/super in dict)"
|
||||
(evp "^ Kitten new respondsTo: #miaow") true)
|
||||
(st-test "Cat respondsTo: missing"
|
||||
(evp "^ Cat new respondsTo: #noSuchSelector") false)
|
||||
(st-test "respondsTo: on class-ref searches class side"
|
||||
(evp "^ Cat respondsTo: #named:") true)
|
||||
|
||||
;; Non-symbol arg coerces via str — also accepts strings.
|
||||
(st-test "respondsTo: with string arg"
|
||||
(evp "^ Cat new respondsTo: 'miaow'") true)
|
||||
|
||||
;; ── 18. Behavior>>compile: — runtime method addition ──
|
||||
(st-test "compile: a unary method"
|
||||
(begin
|
||||
(evp "Cat compile: 'whisker ^ 99'")
|
||||
(evp "^ Cat new whisker"))
|
||||
99)
|
||||
|
||||
(st-test "compile: returns the selector as a symbol"
|
||||
(str (evp "^ Cat compile: 'twitch ^ #twitch'"))
|
||||
"twitch")
|
||||
|
||||
(st-test "compile: a keyword method"
|
||||
(begin
|
||||
(evp "Cat compile: 'doubled: x ^ x * 2'")
|
||||
(evp "^ Cat new doubled: 21"))
|
||||
42)
|
||||
|
||||
(st-test "compile: a method with temps and blocks"
|
||||
(begin
|
||||
(evp "Cat compile: 'sumTo: n | s | s := 0. 1 to: n do: [:i | s := s + i]. ^ s'")
|
||||
(evp "^ Cat new sumTo: 10"))
|
||||
55)
|
||||
|
||||
(st-test "recompile overrides existing method"
|
||||
(begin
|
||||
(evp "Cat compile: 'miaow ^ #ahem'")
|
||||
(str (evp "^ Cat new miaow")))
|
||||
"ahem")
|
||||
|
||||
;; methodDict reflects the new method.
|
||||
(st-test "compile: registers in methodDict"
|
||||
(has-key? (ev "Cat methodDict") "whisker") true)
|
||||
|
||||
;; respondsTo: notices the new method.
|
||||
(st-test "respondsTo: sees compiled method"
|
||||
(evp "^ Cat new respondsTo: #whisker") true)
|
||||
|
||||
;; Behavior>>removeSelector: takes a method back out.
|
||||
(st-test "removeSelector: drops the method"
|
||||
(begin
|
||||
(evp "Cat removeSelector: #whisker")
|
||||
(evp "^ Cat new respondsTo: #whisker"))
|
||||
false)
|
||||
|
||||
;; compile:classified: ignores the extra arg.
|
||||
(st-test "compile:classified: works"
|
||||
(begin
|
||||
(evp "Cat compile: 'taggedMethod ^ #yes' classified: 'demo'")
|
||||
(str (evp "^ Cat new taggedMethod")))
|
||||
"yes")
|
||||
|
||||
;; ── 19. Object>>becomeForward: ──
|
||||
(st-class-define! "Box" "Object" (list "value"))
|
||||
(st-class-add-method! "Box" "value" (st-parse-method "value ^ value"))
|
||||
(st-class-add-method! "Box" "value:" (st-parse-method "value: v value := v. ^ self"))
|
||||
(st-class-add-method! "Box" "kind" (st-parse-method "kind ^ #box"))
|
||||
|
||||
(st-class-define! "Crate" "Object" (list "value"))
|
||||
(st-class-add-method! "Crate" "value" (st-parse-method "value ^ value"))
|
||||
(st-class-add-method! "Crate" "value:" (st-parse-method "value: v value := v. ^ self"))
|
||||
(st-class-add-method! "Crate" "kind" (st-parse-method "kind ^ #crate"))
|
||||
|
||||
(st-test "before becomeForward: instance reports its class"
|
||||
(str (evp "^ (Box new value: 1) class name"))
|
||||
"Box")
|
||||
|
||||
(st-test "becomeForward: changes the receiver's class"
|
||||
(evp
|
||||
"| a b |
|
||||
a := Box new value: 1.
|
||||
b := Crate new value: 99.
|
||||
a becomeForward: b.
|
||||
^ a class name")
|
||||
"Crate")
|
||||
|
||||
(st-test "becomeForward: routes future sends through new class"
|
||||
(evp
|
||||
"| a b |
|
||||
a := Box new value: 1.
|
||||
b := Crate new value: 99.
|
||||
a becomeForward: b.
|
||||
^ a kind")
|
||||
(make-symbol "crate"))
|
||||
|
||||
(st-test "becomeForward: takes target's ivars"
|
||||
(evp
|
||||
"| a b |
|
||||
a := Box new value: 1.
|
||||
b := Crate new value: 99.
|
||||
a becomeForward: b.
|
||||
^ a value")
|
||||
99)
|
||||
|
||||
(st-test "becomeForward: leaves the *target* instance unchanged"
|
||||
(evp
|
||||
"| a b |
|
||||
a := Box new value: 1.
|
||||
b := Crate new value: 99.
|
||||
a becomeForward: b.
|
||||
^ b kind")
|
||||
(make-symbol "crate"))
|
||||
|
||||
(st-test "every reference to the receiver sees the new identity"
|
||||
(evp
|
||||
"| a alias b |
|
||||
a := Box new value: 1.
|
||||
alias := a.
|
||||
b := Crate new value: 99.
|
||||
a becomeForward: b.
|
||||
^ alias kind")
|
||||
(make-symbol "crate"))
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,255 +0,0 @@
|
||||
;; Smalltalk runtime tests — class table, type→class mapping, instances.
|
||||
;;
|
||||
;; Reuses helpers (st-test, st-deep=?) from tokenize.sx. Counters reset
|
||||
;; here so this file's summary covers runtime tests only.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
;; Fresh hierarchy for every test file.
|
||||
(st-bootstrap-classes!)
|
||||
|
||||
;; ── 1. Bootstrap installed expected classes ──
|
||||
(st-test "Object exists" (st-class-exists? "Object") true)
|
||||
(st-test "Behavior exists" (st-class-exists? "Behavior") true)
|
||||
(st-test "Metaclass exists" (st-class-exists? "Metaclass") true)
|
||||
(st-test "True/False/UndefinedObject"
|
||||
(and
|
||||
(st-class-exists? "True")
|
||||
(st-class-exists? "False")
|
||||
(st-class-exists? "UndefinedObject"))
|
||||
true)
|
||||
(st-test "SmallInteger / Float / Symbol exist"
|
||||
(and
|
||||
(st-class-exists? "SmallInteger")
|
||||
(st-class-exists? "Float")
|
||||
(st-class-exists? "Symbol"))
|
||||
true)
|
||||
(st-test "BlockClosure exists" (st-class-exists? "BlockClosure") true)
|
||||
|
||||
;; ── 2. Superclass chain ──
|
||||
(st-test "Object has no superclass" (st-class-superclass "Object") nil)
|
||||
(st-test "Behavior super = Object" (st-class-superclass "Behavior") "Object")
|
||||
(st-test "True super = Boolean" (st-class-superclass "True") "Boolean")
|
||||
(st-test "Symbol super = String" (st-class-superclass "Symbol") "String")
|
||||
(st-test
|
||||
"String chain"
|
||||
(st-class-chain "String")
|
||||
(list "String" "ArrayedCollection" "SequenceableCollection" "Collection" "Object"))
|
||||
(st-test
|
||||
"SmallInteger chain"
|
||||
(st-class-chain "SmallInteger")
|
||||
(list "SmallInteger" "Integer" "Number" "Magnitude" "Object"))
|
||||
|
||||
;; ── 3. inherits-from? ──
|
||||
(st-test "True inherits from Boolean" (st-class-inherits-from? "True" "Boolean") true)
|
||||
(st-test "True inherits from Object" (st-class-inherits-from? "True" "Object") true)
|
||||
(st-test "True inherits from True" (st-class-inherits-from? "True" "True") true)
|
||||
(st-test
|
||||
"True does not inherit from Number"
|
||||
(st-class-inherits-from? "True" "Number")
|
||||
false)
|
||||
(st-test
|
||||
"Object does not inherit from Number"
|
||||
(st-class-inherits-from? "Object" "Number")
|
||||
false)
|
||||
|
||||
;; ── 4. type→class mapping ──
|
||||
(st-test "class-of nil" (st-class-of nil) "UndefinedObject")
|
||||
(st-test "class-of true" (st-class-of true) "True")
|
||||
(st-test "class-of false" (st-class-of false) "False")
|
||||
(st-test "class-of int" (st-class-of 42) "SmallInteger")
|
||||
(st-test "class-of zero" (st-class-of 0) "SmallInteger")
|
||||
(st-test "class-of negative int" (st-class-of -3) "SmallInteger")
|
||||
(st-test "class-of float" (st-class-of 3.14) "Float")
|
||||
(st-test "class-of string" (st-class-of "hi") "String")
|
||||
(st-test "class-of symbol" (st-class-of (quote foo)) "Symbol")
|
||||
(st-test "class-of list" (st-class-of (list 1 2)) "Array")
|
||||
(st-test "class-of empty list" (st-class-of (list)) "Array")
|
||||
(st-test "class-of lambda" (st-class-of (fn (x) x)) "BlockClosure")
|
||||
(st-test "class-of dict" (st-class-of {:a 1}) "Dictionary")
|
||||
|
||||
;; ── 5. User class definition ──
|
||||
(st-class-define! "Account" "Object" (list "balance" "owner"))
|
||||
(st-class-define! "SavingsAccount" "Account" (list "rate"))
|
||||
|
||||
(st-test "Account exists" (st-class-exists? "Account") true)
|
||||
(st-test "Account super = Object" (st-class-superclass "Account") "Object")
|
||||
(st-test
|
||||
"SavingsAccount chain"
|
||||
(st-class-chain "SavingsAccount")
|
||||
(list "SavingsAccount" "Account" "Object"))
|
||||
(st-test
|
||||
"SavingsAccount own ivars"
|
||||
(get (st-class-get "SavingsAccount") :ivars)
|
||||
(list "rate"))
|
||||
(st-test
|
||||
"SavingsAccount inherited+own ivars"
|
||||
(st-class-all-ivars "SavingsAccount")
|
||||
(list "balance" "owner" "rate"))
|
||||
|
||||
;; ── 6. Instance construction ──
|
||||
(define a1 (st-make-instance "Account"))
|
||||
(st-test "instance is st-instance" (st-instance? a1) true)
|
||||
(st-test "instance class" (get a1 :class) "Account")
|
||||
(st-test "instance ivars start nil" (st-iv-get a1 "balance") nil)
|
||||
(st-test
|
||||
"instance has all expected ivars"
|
||||
(sort (keys (get a1 :ivars)))
|
||||
(sort (list "balance" "owner")))
|
||||
(define a2 (st-iv-set! a1 "balance" 100))
|
||||
(st-test "iv-set! returns updated copy" (st-iv-get a2 "balance") 100)
|
||||
(st-test "iv-set! does not mutate original" (st-iv-get a1 "balance") nil)
|
||||
(st-test "class-of instance" (st-class-of a1) "Account")
|
||||
|
||||
(define s1 (st-make-instance "SavingsAccount"))
|
||||
(st-test
|
||||
"subclass instance has all inherited ivars"
|
||||
(sort (keys (get s1 :ivars)))
|
||||
(sort (list "balance" "owner" "rate")))
|
||||
|
||||
;; ── 7. Method install + lookup ──
|
||||
(st-class-add-method!
|
||||
"Account"
|
||||
"balance"
|
||||
(st-parse-method "balance ^ balance"))
|
||||
(st-class-add-method!
|
||||
"Account"
|
||||
"deposit:"
|
||||
(st-parse-method "deposit: amount balance := balance + amount. ^ self"))
|
||||
|
||||
(st-test
|
||||
"method registered"
|
||||
(has-key? (get (st-class-get "Account") :methods) "balance")
|
||||
true)
|
||||
|
||||
(st-test
|
||||
"method lookup direct"
|
||||
(= (st-method-lookup "Account" "balance" false) nil)
|
||||
false)
|
||||
|
||||
(st-test
|
||||
"method lookup walks superclass"
|
||||
(= (st-method-lookup "SavingsAccount" "deposit:" false) nil)
|
||||
false)
|
||||
|
||||
(st-test
|
||||
"method lookup unknown selector"
|
||||
(st-method-lookup "Account" "frobnicate" false)
|
||||
nil)
|
||||
|
||||
(st-test
|
||||
"method lookup records defining class"
|
||||
(get (st-method-lookup "SavingsAccount" "balance" false) :defining-class)
|
||||
"Account")
|
||||
|
||||
;; SavingsAccount overrides deposit:
|
||||
(st-class-add-method!
|
||||
"SavingsAccount"
|
||||
"deposit:"
|
||||
(st-parse-method "deposit: amount ^ super deposit: amount + 1"))
|
||||
|
||||
(st-test
|
||||
"subclass override picked first"
|
||||
(get (st-method-lookup "SavingsAccount" "deposit:" false) :defining-class)
|
||||
"SavingsAccount")
|
||||
|
||||
(st-test
|
||||
"Account still finds its own deposit:"
|
||||
(get (st-method-lookup "Account" "deposit:" false) :defining-class)
|
||||
"Account")
|
||||
|
||||
;; ── 8. Class-side methods ──
|
||||
(st-class-add-class-method!
|
||||
"Account"
|
||||
"new"
|
||||
(st-parse-method "new ^ super new"))
|
||||
(st-test
|
||||
"class-side lookup"
|
||||
(= (st-method-lookup "Account" "new" true) nil)
|
||||
false)
|
||||
(st-test
|
||||
"instance-side does not find class method"
|
||||
(st-method-lookup "Account" "new" false)
|
||||
nil)
|
||||
|
||||
;; ── 9. Re-bootstrap resets table ──
|
||||
(st-bootstrap-classes!)
|
||||
(st-test "after re-bootstrap Account gone" (st-class-exists? "Account") false)
|
||||
(st-test "after re-bootstrap Object stays" (st-class-exists? "Object") true)
|
||||
|
||||
;; ── 10. Method-lookup cache ──
|
||||
(st-bootstrap-classes!)
|
||||
(st-class-define! "Foo" "Object" (list))
|
||||
(st-class-define! "Bar" "Foo" (list))
|
||||
(st-class-add-method! "Foo" "greet" (st-parse-method "greet ^ 1"))
|
||||
|
||||
;; Bootstrap clears cache; record stats from now.
|
||||
(st-method-cache-reset-stats!)
|
||||
|
||||
;; First lookup is a miss; second is a hit.
|
||||
(st-method-lookup "Bar" "greet" false)
|
||||
(st-test
|
||||
"first lookup recorded as miss"
|
||||
(get (st-method-cache-stats) :misses)
|
||||
1)
|
||||
(st-test
|
||||
"first lookup recorded as hit count zero"
|
||||
(get (st-method-cache-stats) :hits)
|
||||
0)
|
||||
|
||||
(st-method-lookup "Bar" "greet" false)
|
||||
(st-test
|
||||
"second lookup hits cache"
|
||||
(get (st-method-cache-stats) :hits)
|
||||
1)
|
||||
|
||||
;; Misses are also cached as :not-found.
|
||||
(st-method-lookup "Bar" "frobnicate" false)
|
||||
(st-method-lookup "Bar" "frobnicate" false)
|
||||
(st-test
|
||||
"negative-result caches"
|
||||
(get (st-method-cache-stats) :hits)
|
||||
2)
|
||||
|
||||
;; Adding a new method invalidates the cache.
|
||||
(st-class-add-method! "Bar" "greet" (st-parse-method "greet ^ 2"))
|
||||
(st-test
|
||||
"cache cleared on method add"
|
||||
(get (st-method-cache-stats) :size)
|
||||
0)
|
||||
(st-test
|
||||
"after invalidation lookup picks up override"
|
||||
(get (st-method-lookup "Bar" "greet" false) :defining-class)
|
||||
"Bar")
|
||||
|
||||
;; Removing a method also invalidates and exposes the inherited one.
|
||||
(st-class-remove-method! "Bar" "greet")
|
||||
(st-test
|
||||
"after remove lookup falls through to Foo"
|
||||
(get (st-method-lookup "Bar" "greet" false) :defining-class)
|
||||
"Foo")
|
||||
|
||||
;; Cache survives across unrelated class-table mutations? No — define! clears.
|
||||
(st-method-lookup "Foo" "greet" false) ; warm cache
|
||||
(st-class-define! "Baz" "Object" (list))
|
||||
(st-test
|
||||
"class-define clears cache"
|
||||
(get (st-method-cache-stats) :size)
|
||||
0)
|
||||
|
||||
;; Class-side and instance-side cache entries are separate keys.
|
||||
(st-class-add-class-method! "Foo" "make" (st-parse-method "make ^ self new"))
|
||||
(st-method-lookup "Foo" "make" true)
|
||||
(st-method-lookup "Foo" "make" false)
|
||||
(st-test
|
||||
"class-side hit found, instance-side stored as not-found"
|
||||
(= (st-method-lookup "Foo" "make" true) nil)
|
||||
false)
|
||||
(st-test
|
||||
"instance-side same selector returns nil"
|
||||
(st-method-lookup "Foo" "make" false)
|
||||
nil)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,159 +0,0 @@
|
||||
;; Stream hierarchy tests — ReadStream / WriteStream / ReadWriteStream
|
||||
;; built on a `collection` + `position` pair. Reads use Smalltalk's
|
||||
;; 1-indexed `at:`; writes use the collection's `add:`.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Class hierarchy ──
|
||||
(st-test "ReadStream < PositionableStream"
|
||||
(st-class-inherits-from? "ReadStream" "PositionableStream") true)
|
||||
(st-test "WriteStream < PositionableStream"
|
||||
(st-class-inherits-from? "WriteStream" "PositionableStream") true)
|
||||
(st-test "ReadWriteStream < WriteStream"
|
||||
(st-class-inherits-from? "ReadWriteStream" "WriteStream") true)
|
||||
|
||||
;; ── 2. ReadStream basics ──
|
||||
(st-test "ReadStream next" (evp "^ (ReadStream on: #(1 2 3)) next") 1)
|
||||
|
||||
(st-test "ReadStream sequential reads"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(10 20 30).
|
||||
^ {s next. s next. s next}")
|
||||
(list 10 20 30))
|
||||
|
||||
(st-test "ReadStream atEnd"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(1 2).
|
||||
s next. s next.
|
||||
^ s atEnd")
|
||||
true)
|
||||
|
||||
(st-test "ReadStream next past end returns nil"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(1).
|
||||
s next.
|
||||
^ s next")
|
||||
nil)
|
||||
|
||||
(st-test "ReadStream peek doesn't advance"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(7 8 9).
|
||||
^ {s peek. s peek. s next}")
|
||||
(list 7 7 7))
|
||||
|
||||
(st-test "ReadStream position"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(1 2 3 4).
|
||||
s next. s next.
|
||||
^ s position")
|
||||
2)
|
||||
|
||||
(st-test "ReadStream reset goes back to start"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(1 2 3).
|
||||
s next. s next. s next.
|
||||
s reset.
|
||||
^ s next")
|
||||
1)
|
||||
|
||||
(st-test "ReadStream upToEnd"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(1 2 3 4 5).
|
||||
s next. s next.
|
||||
^ s upToEnd")
|
||||
(list 3 4 5))
|
||||
|
||||
(st-test "ReadStream next: takes up to n"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(10 20 30 40 50).
|
||||
^ s next: 3")
|
||||
(list 10 20 30))
|
||||
|
||||
(st-test "ReadStream skip:"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: #(1 2 3 4 5).
|
||||
s skip: 2.
|
||||
^ s next")
|
||||
3)
|
||||
|
||||
;; ── 3. WriteStream basics ──
|
||||
(st-test "WriteStream nextPut: + contents"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream on: (Array new: 0).
|
||||
s nextPut: 10.
|
||||
s nextPut: 20.
|
||||
s nextPut: 30.
|
||||
^ s contents")
|
||||
(list 10 20 30))
|
||||
|
||||
(st-test "WriteStream nextPutAll:"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream on: (Array new: 0).
|
||||
s nextPutAll: #(1 2 3).
|
||||
^ s contents")
|
||||
(list 1 2 3))
|
||||
|
||||
(st-test "WriteStream nextPut: returns the value"
|
||||
(evp "^ (WriteStream on: (Array new: 0)) nextPut: 42") 42)
|
||||
|
||||
(st-test "WriteStream position tracks writes"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream on: (Array new: 0).
|
||||
s nextPut: #a. s nextPut: #b.
|
||||
^ s position")
|
||||
2)
|
||||
|
||||
;; ── 4. WriteStream with: pre-fills ──
|
||||
(st-test "WriteStream with: starts at end"
|
||||
(evp
|
||||
"| s |
|
||||
s := WriteStream with: #(1 2 3).
|
||||
s nextPut: 99.
|
||||
^ s contents")
|
||||
(list 1 2 3 99))
|
||||
|
||||
;; ── 5. ReadStream on:collection works on String at: ──
|
||||
(st-test "ReadStream on String reads chars"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: 'abc'.
|
||||
^ {s next. s next. s next}")
|
||||
(list "a" "b" "c"))
|
||||
|
||||
(st-test "ReadStream atEnd on String"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadStream on: 'ab'.
|
||||
s next. s next.
|
||||
^ s atEnd")
|
||||
true)
|
||||
|
||||
;; ── 6. ReadWriteStream ──
|
||||
(st-test "ReadWriteStream read after writes"
|
||||
(evp
|
||||
"| s |
|
||||
s := ReadWriteStream on: (Array new: 0).
|
||||
s nextPut: 1. s nextPut: 2. s nextPut: 3.
|
||||
s reset.
|
||||
^ {s next. s next. s next}")
|
||||
(list 1 2 3))
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,198 +0,0 @@
|
||||
;; SUnit port tests. Loads `lib/smalltalk/sunit.sx` (which itself calls
|
||||
;; smalltalk-load to install TestCase/TestSuite/TestResult/TestFailure)
|
||||
;; and exercises the framework on small Smalltalk-defined cases.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
;; test.sh loads lib/smalltalk/sunit.sx for us BEFORE this file runs
|
||||
;; (nested SX loads do not propagate top-level forms reliably, so the
|
||||
;; bootstrap chain is concentrated in test.sh). The SUnit classes are
|
||||
;; already present in the class table at this point.
|
||||
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Classes installed ──
|
||||
(st-test "TestCase exists" (st-class-exists? "TestCase") true)
|
||||
(st-test "TestSuite exists" (st-class-exists? "TestSuite") true)
|
||||
(st-test "TestResult exists" (st-class-exists? "TestResult") true)
|
||||
(st-test "TestFailure < Error"
|
||||
(st-class-inherits-from? "TestFailure" "Error") true)
|
||||
|
||||
;; ── 2. A subclass with one passing test runs cleanly ──
|
||||
(smalltalk-load
|
||||
"TestCase subclass: #PassingCase
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!PassingCase methodsFor: 'tests'!
|
||||
testOnePlusOne self assert: 1 + 1 = 2! !")
|
||||
|
||||
(st-test "passing test runs and counts as pass"
|
||||
(evp
|
||||
"| suite r |
|
||||
suite := PassingCase suiteForAll: #(#testOnePlusOne).
|
||||
r := suite run.
|
||||
^ r passCount")
|
||||
1)
|
||||
|
||||
(st-test "passing test has no failures"
|
||||
(evp
|
||||
"| suite r |
|
||||
suite := PassingCase suiteForAll: #(#testOnePlusOne).
|
||||
r := suite run.
|
||||
^ r failureCount")
|
||||
0)
|
||||
|
||||
;; ── 3. A subclass with a failing assert: increments failures ──
|
||||
(smalltalk-load
|
||||
"TestCase subclass: #FailingCase
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!FailingCase methodsFor: 'tests'!
|
||||
testFalse self assert: false!
|
||||
testEquals self assert: 1 + 1 equals: 3! !")
|
||||
|
||||
(st-test "assert: false bumps failureCount"
|
||||
(evp
|
||||
"| suite r |
|
||||
suite := FailingCase suiteForAll: #(#testFalse).
|
||||
r := suite run.
|
||||
^ r failureCount")
|
||||
1)
|
||||
|
||||
(st-test "assert:equals: with mismatch fails"
|
||||
(evp
|
||||
"| suite r |
|
||||
suite := FailingCase suiteForAll: #(#testEquals).
|
||||
r := suite run.
|
||||
^ r failureCount")
|
||||
1)
|
||||
|
||||
(st-test "failure messageText captured"
|
||||
(evp
|
||||
"| suite r rec |
|
||||
suite := FailingCase suiteForAll: #(#testEquals).
|
||||
r := suite run.
|
||||
rec := r failures at: 1.
|
||||
^ rec at: 2")
|
||||
"expected 3 but got 2")
|
||||
|
||||
;; ── 4. Mixed pass/fail counts add up ──
|
||||
(smalltalk-load
|
||||
"TestCase subclass: #MixedCase
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!MixedCase methodsFor: 'tests'!
|
||||
testGood self assert: true!
|
||||
testBad self assert: false!
|
||||
testAlsoGood self assert: 2 > 1! !")
|
||||
|
||||
(st-test "mixed suite — totalCount"
|
||||
(evp
|
||||
"| s r |
|
||||
s := MixedCase suiteForAll: #(#testGood #testBad #testAlsoGood).
|
||||
r := s run.
|
||||
^ r totalCount")
|
||||
3)
|
||||
|
||||
(st-test "mixed suite — passCount"
|
||||
(evp
|
||||
"| s r |
|
||||
s := MixedCase suiteForAll: #(#testGood #testBad #testAlsoGood).
|
||||
r := s run.
|
||||
^ r passCount")
|
||||
2)
|
||||
|
||||
(st-test "mixed suite — failureCount"
|
||||
(evp
|
||||
"| s r |
|
||||
s := MixedCase suiteForAll: #(#testGood #testBad #testAlsoGood).
|
||||
r := s run.
|
||||
^ r failureCount")
|
||||
1)
|
||||
|
||||
(st-test "allPassed false on mix"
|
||||
(evp
|
||||
"| s r |
|
||||
s := MixedCase suiteForAll: #(#testGood #testBad #testAlsoGood).
|
||||
r := s run.
|
||||
^ r allPassed")
|
||||
false)
|
||||
|
||||
(st-test "allPassed true with only passes"
|
||||
(evp
|
||||
"| s r |
|
||||
s := MixedCase suiteForAll: #(#testGood #testAlsoGood).
|
||||
r := s run.
|
||||
^ r allPassed")
|
||||
true)
|
||||
|
||||
;; ── 5. setUp / tearDown ──
|
||||
(smalltalk-load
|
||||
"TestCase subclass: #FixtureCase
|
||||
instanceVariableNames: 'value'!
|
||||
|
||||
!FixtureCase methodsFor: 'fixture'!
|
||||
setUp value := 42. ^ self!
|
||||
tearDown ^ self! !
|
||||
|
||||
!FixtureCase methodsFor: 'tests'!
|
||||
testValueIs42 self assert: value = 42! !")
|
||||
|
||||
(st-test "setUp ran before test"
|
||||
(evp
|
||||
"| s r |
|
||||
s := FixtureCase suiteForAll: #(#testValueIs42).
|
||||
r := s run.
|
||||
^ r passCount")
|
||||
1)
|
||||
|
||||
;; ── 6. should:raise: and shouldnt:raise: ──
|
||||
(smalltalk-load
|
||||
"TestCase subclass: #RaiseCase
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!RaiseCase methodsFor: 'tests'!
|
||||
testShouldRaise
|
||||
self should: [Error signal: 'boom'] raise: Error!
|
||||
|
||||
testShouldRaiseFails
|
||||
self should: [42] raise: Error!
|
||||
|
||||
testShouldntRaise
|
||||
self shouldnt: [42] raise: Error! !")
|
||||
|
||||
(st-test "should:raise: catches matching"
|
||||
(evp
|
||||
"| r |
|
||||
r := (RaiseCase suiteForAll: #(#testShouldRaise)) run.
|
||||
^ r passCount") 1)
|
||||
|
||||
(st-test "should:raise: fails when no exception"
|
||||
(evp
|
||||
"| r |
|
||||
r := (RaiseCase suiteForAll: #(#testShouldRaiseFails)) run.
|
||||
^ r failureCount") 1)
|
||||
|
||||
(st-test "shouldnt:raise: passes when nothing thrown"
|
||||
(evp
|
||||
"| r |
|
||||
r := (RaiseCase suiteForAll: #(#testShouldntRaise)) run.
|
||||
^ r passCount") 1)
|
||||
|
||||
;; ── 7. summary string uses format: ──
|
||||
(st-test "summary contains pass count"
|
||||
(let
|
||||
((s (evp
|
||||
"| s r |
|
||||
s := MixedCase suiteForAll: #(#testGood #testBad).
|
||||
r := s run.
|
||||
^ r summary")))
|
||||
(cond
|
||||
((not (string? s)) false)
|
||||
(else (> (len s) 0))))
|
||||
true)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,149 +0,0 @@
|
||||
;; super-send tests.
|
||||
;;
|
||||
;; super looks up methods starting at the *defining class*'s superclass —
|
||||
;; not the receiver's class. This means an inherited method that uses
|
||||
;; `super` always reaches the same parent regardless of where in the
|
||||
;; subclass chain the receiver actually sits.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. Basic super: subclass override calls parent ──
|
||||
(st-class-define! "Animal" "Object" (list))
|
||||
(st-class-add-method! "Animal" "speak"
|
||||
(st-parse-method "speak ^ #generic"))
|
||||
|
||||
(st-class-define! "Dog" "Animal" (list))
|
||||
(st-class-add-method! "Dog" "speak"
|
||||
(st-parse-method "speak ^ super speak"))
|
||||
|
||||
(st-test
|
||||
"super reaches parent's speak"
|
||||
(str (evp "^ Dog new speak"))
|
||||
"generic")
|
||||
|
||||
(st-class-add-method! "Dog" "loud"
|
||||
(st-parse-method "loud ^ super speak , #'!' asString"))
|
||||
;; The above tries to use `, #'!' asString` which won't quite work with my
|
||||
;; primitives. Replace with a simpler test.
|
||||
(st-class-add-method! "Dog" "loud"
|
||||
(st-parse-method "loud | s | s := super speak. ^ s"))
|
||||
|
||||
(st-test
|
||||
"method calls super and returns same"
|
||||
(str (evp "^ Dog new loud"))
|
||||
"generic")
|
||||
|
||||
;; ── 2. Super with argument ──
|
||||
(st-class-add-method! "Animal" "greet:"
|
||||
(st-parse-method "greet: name ^ name , ' (animal)'"))
|
||||
(st-class-add-method! "Dog" "greet:"
|
||||
(st-parse-method "greet: name ^ super greet: name"))
|
||||
|
||||
(st-test
|
||||
"super with arg reaches parent and threads value"
|
||||
(evp "^ Dog new greet: 'Rex'")
|
||||
"Rex (animal)")
|
||||
|
||||
;; ── 3. Inherited method uses *defining* class for super ──
|
||||
;; A defines speak ^ 'A'
|
||||
;; A defines speakLog: which sends `super speak`. super starts at Object → no
|
||||
;; speak there → DNU. So invoke speakLog from A subclass to test that super
|
||||
;; resolves to A's parent (Object), not the subclass's parent.
|
||||
(st-class-define! "RootSpeaker" "Object" (list))
|
||||
(st-class-add-method! "RootSpeaker" "speak"
|
||||
(st-parse-method "speak ^ #root"))
|
||||
(st-class-add-method! "RootSpeaker" "speakDelegate"
|
||||
(st-parse-method "speakDelegate ^ super speak"))
|
||||
;; Object has no speak (and we add a temporary DNU for testing).
|
||||
(st-class-add-method! "Object" "doesNotUnderstand:"
|
||||
(st-parse-method "doesNotUnderstand: aMessage ^ #dnu"))
|
||||
|
||||
(st-class-define! "ChildSpeaker" "RootSpeaker" (list))
|
||||
(st-class-add-method! "ChildSpeaker" "speak"
|
||||
(st-parse-method "speak ^ #child"))
|
||||
|
||||
(st-test
|
||||
"inherited speakDelegate uses RootSpeaker's super, not ChildSpeaker's"
|
||||
(str (evp "^ ChildSpeaker new speakDelegate"))
|
||||
"dnu")
|
||||
|
||||
;; A non-inherited path: ChildSpeaker overrides speak, but speakDelegate is
|
||||
;; inherited from RootSpeaker. The super inside speakDelegate must resolve to
|
||||
;; *Object* (RootSpeaker's parent), not to RootSpeaker (ChildSpeaker's parent).
|
||||
(st-test
|
||||
"inherited method's super does not call subclass override"
|
||||
(str (evp "^ ChildSpeaker new speak"))
|
||||
"child")
|
||||
|
||||
;; Remove the Object DNU shim now that those tests are done.
|
||||
(st-class-remove-method! "Object" "doesNotUnderstand:")
|
||||
|
||||
;; ── 4. Multi-level: A → B → C ──
|
||||
(st-class-define! "GA" "Object" (list))
|
||||
(st-class-add-method! "GA" "level"
|
||||
(st-parse-method "level ^ #ga"))
|
||||
|
||||
(st-class-define! "GB" "GA" (list))
|
||||
(st-class-add-method! "GB" "level"
|
||||
(st-parse-method "level ^ super level"))
|
||||
|
||||
(st-class-define! "GC" "GB" (list))
|
||||
(st-class-add-method! "GC" "level"
|
||||
(st-parse-method "level ^ super level"))
|
||||
|
||||
(st-test
|
||||
"super chains to grandparent"
|
||||
(str (evp "^ GC new level"))
|
||||
"ga")
|
||||
|
||||
;; ── 5. Super inside a block ──
|
||||
(st-class-add-method! "Dog" "delayed"
|
||||
(st-parse-method "delayed ^ [super speak] value"))
|
||||
(st-test
|
||||
"super inside a block resolves correctly"
|
||||
(str (evp "^ Dog new delayed"))
|
||||
"generic")
|
||||
|
||||
;; ── 6. Super send keeps receiver as self ──
|
||||
(st-class-define! "Counter" "Object" (list "count"))
|
||||
(st-class-add-method! "Counter" "init"
|
||||
(st-parse-method "init count := 0. ^ self"))
|
||||
(st-class-add-method! "Counter" "incr"
|
||||
(st-parse-method "incr count := count + 1. ^ self"))
|
||||
(st-class-add-method! "Counter" "count"
|
||||
(st-parse-method "count ^ count"))
|
||||
|
||||
(st-class-define! "DoubleCounter" "Counter" (list))
|
||||
(st-class-add-method! "DoubleCounter" "incr"
|
||||
(st-parse-method "incr super incr. super incr. ^ self"))
|
||||
|
||||
(st-test
|
||||
"super uses same receiver — ivars on self update"
|
||||
(evp "| c | c := DoubleCounter new init. c incr. ^ c count")
|
||||
2)
|
||||
|
||||
;; ── 7. Super on a class without an immediate parent definition ──
|
||||
;; Mid-chain class with no override at this level: super resolves correctly
|
||||
;; through the missing rung.
|
||||
(st-class-define! "Mid" "Animal" (list))
|
||||
(st-class-define! "Pup" "Mid" (list))
|
||||
(st-class-add-method! "Pup" "speak"
|
||||
(st-parse-method "speak ^ super speak"))
|
||||
|
||||
(st-test
|
||||
"super walks past intermediate class with no override"
|
||||
(str (evp "^ Pup new speak"))
|
||||
"generic")
|
||||
|
||||
;; ── 8. Super outside any method errors ──
|
||||
;; (We don't have try/catch in SX from here; skip the negative test —
|
||||
;; documented behaviour is that st-super-send errors when method-class is nil.)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,362 +0,0 @@
|
||||
;; Smalltalk tokenizer tests.
|
||||
;;
|
||||
;; Lightweight runner: each test checks actual vs expected with structural
|
||||
;; equality and accumulates pass/fail counters. Final summary read by
|
||||
;; lib/smalltalk/test.sh.
|
||||
|
||||
(define
|
||||
st-deep=?
|
||||
(fn
|
||||
(a b)
|
||||
(cond
|
||||
((= a b) true)
|
||||
((and (dict? a) (dict? b))
|
||||
(let
|
||||
((ak (keys a)) (bk (keys b)))
|
||||
(if
|
||||
(not (= (len ak) (len bk)))
|
||||
false
|
||||
(every?
|
||||
(fn
|
||||
(k)
|
||||
(and (has-key? b k) (st-deep=? (get a k) (get b k))))
|
||||
ak))))
|
||||
((and (list? a) (list? b))
|
||||
(if
|
||||
(not (= (len a) (len b)))
|
||||
false
|
||||
(let
|
||||
((i 0) (ok true))
|
||||
(begin
|
||||
(define
|
||||
de-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and ok (< i (len a)))
|
||||
(begin
|
||||
(when
|
||||
(not (st-deep=? (nth a i) (nth b i)))
|
||||
(set! ok false))
|
||||
(set! i (+ i 1))
|
||||
(de-loop)))))
|
||||
(de-loop)
|
||||
ok))))
|
||||
(:else false))))
|
||||
|
||||
(define st-test-pass 0)
|
||||
(define st-test-fail 0)
|
||||
(define st-test-fails (list))
|
||||
|
||||
(define
|
||||
st-test
|
||||
(fn
|
||||
(name actual expected)
|
||||
(if
|
||||
(st-deep=? actual expected)
|
||||
(set! st-test-pass (+ st-test-pass 1))
|
||||
(begin
|
||||
(set! st-test-fail (+ st-test-fail 1))
|
||||
(append! st-test-fails {:actual actual :expected expected :name name})))))
|
||||
|
||||
;; Strip eof and project to just :type/:value.
|
||||
(define
|
||||
st-toks
|
||||
(fn
|
||||
(src)
|
||||
(map
|
||||
(fn (tok) {:type (get tok :type) :value (get tok :value)})
|
||||
(filter
|
||||
(fn (tok) (not (= (get tok :type) "eof")))
|
||||
(st-tokenize src)))))
|
||||
|
||||
;; ── 1. Whitespace / empty ──
|
||||
(st-test "empty input" (st-toks "") (list))
|
||||
(st-test "all whitespace" (st-toks " \t\n ") (list))
|
||||
|
||||
;; ── 2. Identifiers ──
|
||||
(st-test
|
||||
"lowercase ident"
|
||||
(st-toks "foo")
|
||||
(list {:type "ident" :value "foo"}))
|
||||
|
||||
(st-test
|
||||
"capitalised ident"
|
||||
(st-toks "Foo")
|
||||
(list {:type "ident" :value "Foo"}))
|
||||
|
||||
(st-test
|
||||
"underscore ident"
|
||||
(st-toks "_x")
|
||||
(list {:type "ident" :value "_x"}))
|
||||
|
||||
(st-test
|
||||
"digits in ident"
|
||||
(st-toks "foo123")
|
||||
(list {:type "ident" :value "foo123"}))
|
||||
|
||||
(st-test
|
||||
"two idents separated"
|
||||
(st-toks "foo bar")
|
||||
(list {:type "ident" :value "foo"} {:type "ident" :value "bar"}))
|
||||
|
||||
;; ── 3. Keyword selectors ──
|
||||
(st-test
|
||||
"keyword selector"
|
||||
(st-toks "foo:")
|
||||
(list {:type "keyword" :value "foo:"}))
|
||||
|
||||
(st-test
|
||||
"keyword call"
|
||||
(st-toks "x at: 1")
|
||||
(list
|
||||
{:type "ident" :value "x"}
|
||||
{:type "keyword" :value "at:"}
|
||||
{:type "number" :value 1}))
|
||||
|
||||
(st-test
|
||||
"two-keyword chain stays separate"
|
||||
(st-toks "at: 1 put: 2")
|
||||
(list
|
||||
{:type "keyword" :value "at:"}
|
||||
{:type "number" :value 1}
|
||||
{:type "keyword" :value "put:"}
|
||||
{:type "number" :value 2}))
|
||||
|
||||
(st-test
|
||||
"ident then assign — not a keyword"
|
||||
(st-toks "x := 1")
|
||||
(list
|
||||
{:type "ident" :value "x"}
|
||||
{:type "assign" :value ":="}
|
||||
{:type "number" :value 1}))
|
||||
|
||||
;; ── 4. Numbers ──
|
||||
(st-test
|
||||
"integer"
|
||||
(st-toks "42")
|
||||
(list {:type "number" :value 42}))
|
||||
|
||||
(st-test
|
||||
"float"
|
||||
(st-toks "3.14")
|
||||
(list {:type "number" :value 3.14}))
|
||||
|
||||
(st-test
|
||||
"hex radix"
|
||||
(st-toks "16rFF")
|
||||
(list
|
||||
{:type "number"
|
||||
:value
|
||||
{:radix 16 :digits "FF" :value 255 :kind "radix"}}))
|
||||
|
||||
(st-test
|
||||
"binary radix"
|
||||
(st-toks "2r1011")
|
||||
(list
|
||||
{:type "number"
|
||||
:value
|
||||
{:radix 2 :digits "1011" :value 11 :kind "radix"}}))
|
||||
|
||||
(st-test
|
||||
"exponent"
|
||||
(st-toks "1e3")
|
||||
(list {:type "number" :value 1000}))
|
||||
|
||||
(st-test
|
||||
"negative exponent (parser handles minus)"
|
||||
(st-toks "1.5e-2")
|
||||
(list {:type "number" :value 0.015}))
|
||||
|
||||
;; ── 5. Strings ──
|
||||
(st-test
|
||||
"simple string"
|
||||
(st-toks "'hi'")
|
||||
(list {:type "string" :value "hi"}))
|
||||
|
||||
(st-test
|
||||
"empty string"
|
||||
(st-toks "''")
|
||||
(list {:type "string" :value ""}))
|
||||
|
||||
(st-test
|
||||
"doubled-quote escape"
|
||||
(st-toks "'a''b'")
|
||||
(list {:type "string" :value "a'b"}))
|
||||
|
||||
;; ── 6. Characters ──
|
||||
(st-test
|
||||
"char literal letter"
|
||||
(st-toks "$a")
|
||||
(list {:type "char" :value "a"}))
|
||||
|
||||
(st-test
|
||||
"char literal punct"
|
||||
(st-toks "$$")
|
||||
(list {:type "char" :value "$"}))
|
||||
|
||||
(st-test
|
||||
"char literal space"
|
||||
(st-toks "$ ")
|
||||
(list {:type "char" :value " "}))
|
||||
|
||||
;; ── 7. Symbols ──
|
||||
(st-test
|
||||
"symbol ident"
|
||||
(st-toks "#foo")
|
||||
(list {:type "symbol" :value "foo"}))
|
||||
|
||||
(st-test
|
||||
"symbol binary"
|
||||
(st-toks "#+")
|
||||
(list {:type "symbol" :value "+"}))
|
||||
|
||||
(st-test
|
||||
"symbol arrow"
|
||||
(st-toks "#->")
|
||||
(list {:type "symbol" :value "->"}))
|
||||
|
||||
(st-test
|
||||
"symbol keyword chain"
|
||||
(st-toks "#at:put:")
|
||||
(list {:type "symbol" :value "at:put:"}))
|
||||
|
||||
(st-test
|
||||
"quoted symbol with spaces"
|
||||
(st-toks "#'foo bar'")
|
||||
(list {:type "symbol" :value "foo bar"}))
|
||||
|
||||
;; ── 8. Literal arrays / byte arrays ──
|
||||
(st-test
|
||||
"literal array open"
|
||||
(st-toks "#(1 2)")
|
||||
(list
|
||||
{:type "array-open" :value "#("}
|
||||
{:type "number" :value 1}
|
||||
{:type "number" :value 2}
|
||||
{:type "rparen" :value ")"}))
|
||||
|
||||
(st-test
|
||||
"byte array open"
|
||||
(st-toks "#[1 2 3]")
|
||||
(list
|
||||
{:type "byte-array-open" :value "#["}
|
||||
{:type "number" :value 1}
|
||||
{:type "number" :value 2}
|
||||
{:type "number" :value 3}
|
||||
{:type "rbracket" :value "]"}))
|
||||
|
||||
;; ── 9. Binary selectors ──
|
||||
(st-test "plus" (st-toks "+") (list {:type "binary" :value "+"}))
|
||||
(st-test "minus" (st-toks "-") (list {:type "binary" :value "-"}))
|
||||
(st-test "star" (st-toks "*") (list {:type "binary" :value "*"}))
|
||||
(st-test "double-equal" (st-toks "==") (list {:type "binary" :value "=="}))
|
||||
(st-test "leq" (st-toks "<=") (list {:type "binary" :value "<="}))
|
||||
(st-test "geq" (st-toks ">=") (list {:type "binary" :value ">="}))
|
||||
(st-test "neq" (st-toks "~=") (list {:type "binary" :value "~="}))
|
||||
(st-test "arrow" (st-toks "->") (list {:type "binary" :value "->"}))
|
||||
(st-test "comma" (st-toks ",") (list {:type "binary" :value ","}))
|
||||
|
||||
(st-test
|
||||
"binary in expression"
|
||||
(st-toks "a + b")
|
||||
(list
|
||||
{:type "ident" :value "a"}
|
||||
{:type "binary" :value "+"}
|
||||
{:type "ident" :value "b"}))
|
||||
|
||||
;; ── 10. Punctuation ──
|
||||
(st-test "lparen" (st-toks "(") (list {:type "lparen" :value "("}))
|
||||
(st-test "rparen" (st-toks ")") (list {:type "rparen" :value ")"}))
|
||||
(st-test "lbracket" (st-toks "[") (list {:type "lbracket" :value "["}))
|
||||
(st-test "rbracket" (st-toks "]") (list {:type "rbracket" :value "]"}))
|
||||
(st-test "lbrace" (st-toks "{") (list {:type "lbrace" :value "{"}))
|
||||
(st-test "rbrace" (st-toks "}") (list {:type "rbrace" :value "}"}))
|
||||
(st-test "period" (st-toks ".") (list {:type "period" :value "."}))
|
||||
(st-test "semi" (st-toks ";") (list {:type "semi" :value ";"}))
|
||||
(st-test "bar" (st-toks "|") (list {:type "bar" :value "|"}))
|
||||
(st-test "caret" (st-toks "^") (list {:type "caret" :value "^"}))
|
||||
(st-test "bang" (st-toks "!") (list {:type "bang" :value "!"}))
|
||||
(st-test "colon" (st-toks ":") (list {:type "colon" :value ":"}))
|
||||
(st-test "assign" (st-toks ":=") (list {:type "assign" :value ":="}))
|
||||
|
||||
;; ── 11. Comments ──
|
||||
(st-test "comment skipped" (st-toks "\"hello\"") (list))
|
||||
(st-test
|
||||
"comment between tokens"
|
||||
(st-toks "a \"comment\" b")
|
||||
(list {:type "ident" :value "a"} {:type "ident" :value "b"}))
|
||||
(st-test
|
||||
"multi-line comment"
|
||||
(st-toks "\"line1\nline2\"42")
|
||||
(list {:type "number" :value 42}))
|
||||
|
||||
;; ── 12. Compound expressions ──
|
||||
(st-test
|
||||
"block with params"
|
||||
(st-toks "[:a :b | a + b]")
|
||||
(list
|
||||
{:type "lbracket" :value "["}
|
||||
{:type "colon" :value ":"}
|
||||
{:type "ident" :value "a"}
|
||||
{:type "colon" :value ":"}
|
||||
{:type "ident" :value "b"}
|
||||
{:type "bar" :value "|"}
|
||||
{:type "ident" :value "a"}
|
||||
{:type "binary" :value "+"}
|
||||
{:type "ident" :value "b"}
|
||||
{:type "rbracket" :value "]"}))
|
||||
|
||||
(st-test
|
||||
"cascade"
|
||||
(st-toks "x m1; m2")
|
||||
(list
|
||||
{:type "ident" :value "x"}
|
||||
{:type "ident" :value "m1"}
|
||||
{:type "semi" :value ";"}
|
||||
{:type "ident" :value "m2"}))
|
||||
|
||||
(st-test
|
||||
"method body return"
|
||||
(st-toks "^ self foo")
|
||||
(list
|
||||
{:type "caret" :value "^"}
|
||||
{:type "ident" :value "self"}
|
||||
{:type "ident" :value "foo"}))
|
||||
|
||||
(st-test
|
||||
"class declaration head"
|
||||
(st-toks "Object subclass: #Foo")
|
||||
(list
|
||||
{:type "ident" :value "Object"}
|
||||
{:type "keyword" :value "subclass:"}
|
||||
{:type "symbol" :value "Foo"}))
|
||||
|
||||
(st-test
|
||||
"temp declaration"
|
||||
(st-toks "| t1 t2 |")
|
||||
(list
|
||||
{:type "bar" :value "|"}
|
||||
{:type "ident" :value "t1"}
|
||||
{:type "ident" :value "t2"}
|
||||
{:type "bar" :value "|"}))
|
||||
|
||||
(st-test
|
||||
"chunk separator"
|
||||
(st-toks "Foo bar !")
|
||||
(list
|
||||
{:type "ident" :value "Foo"}
|
||||
{:type "ident" :value "bar"}
|
||||
{:type "bang" :value "!"}))
|
||||
|
||||
(st-test
|
||||
"keyword call with binary precedence"
|
||||
(st-toks "x foo: 1 + 2")
|
||||
(list
|
||||
{:type "ident" :value "x"}
|
||||
{:type "keyword" :value "foo:"}
|
||||
{:type "number" :value 1}
|
||||
{:type "binary" :value "+"}
|
||||
{:type "number" :value 2}))
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,145 +0,0 @@
|
||||
;; whileTrue: / whileTrue / whileFalse: / whileFalse tests.
|
||||
;;
|
||||
;; In Smalltalk these are *ordinary* messages sent to the condition block.
|
||||
;; No special-form magic — just block sends. The runtime can intrinsify
|
||||
;; them later in the JIT (Tier 1 of bytecode expansion) but the spec-level
|
||||
;; semantics are what's pinned here.
|
||||
|
||||
(set! st-test-pass 0)
|
||||
(set! st-test-fail 0)
|
||||
(set! st-test-fails (list))
|
||||
|
||||
(st-bootstrap-classes!)
|
||||
(define ev (fn (src) (smalltalk-eval src)))
|
||||
(define evp (fn (src) (smalltalk-eval-program src)))
|
||||
|
||||
;; ── 1. whileTrue: with body — basic counter ──
|
||||
(st-test
|
||||
"whileTrue: counts down"
|
||||
(evp "| n | n := 5. [n > 0] whileTrue: [n := n - 1]. ^ n")
|
||||
0)
|
||||
|
||||
(st-test
|
||||
"whileTrue: returns nil"
|
||||
(evp "| n | n := 3. ^ [n > 0] whileTrue: [n := n - 1]")
|
||||
nil)
|
||||
|
||||
(st-test
|
||||
"whileTrue: zero iterations is fine"
|
||||
(evp "| n | n := 0. [n > 0] whileTrue: [n := n + 1]. ^ n")
|
||||
0)
|
||||
|
||||
;; ── 2. whileFalse: with body ──
|
||||
(st-test
|
||||
"whileFalse: counts down (cond becomes true)"
|
||||
(evp "| n | n := 5. [n <= 0] whileFalse: [n := n - 1]. ^ n")
|
||||
0)
|
||||
|
||||
(st-test
|
||||
"whileFalse: returns nil"
|
||||
(evp "| n | n := 3. ^ [n <= 0] whileFalse: [n := n - 1]")
|
||||
nil)
|
||||
|
||||
;; ── 3. whileTrue (no arg) — body-less side-effect loop ──
|
||||
(st-test
|
||||
"whileTrue without argument runs cond-only loop"
|
||||
(evp
|
||||
"| n decrement |
|
||||
n := 5.
|
||||
decrement := [n := n - 1. n > 0].
|
||||
decrement whileTrue.
|
||||
^ n")
|
||||
0)
|
||||
|
||||
;; ── 4. whileFalse (no arg) ──
|
||||
(st-test
|
||||
"whileFalse without argument"
|
||||
(evp
|
||||
"| n inc |
|
||||
n := 0.
|
||||
inc := [n := n + 1. n >= 3].
|
||||
inc whileFalse.
|
||||
^ n")
|
||||
3)
|
||||
|
||||
;; ── 5. Cond block evaluated each iteration (not cached) ──
|
||||
(st-test
|
||||
"whileTrue: re-evaluates cond on every iter"
|
||||
(evp
|
||||
"| n stop |
|
||||
n := 0. stop := false.
|
||||
[stop] whileFalse: [
|
||||
n := n + 1.
|
||||
n >= 4 ifTrue: [stop := true]].
|
||||
^ n")
|
||||
4)
|
||||
|
||||
;; ── 6. Body block sees outer locals ──
|
||||
(st-test
|
||||
"whileTrue: body reads + writes captured locals"
|
||||
(evp
|
||||
"| acc i |
|
||||
acc := 0. i := 1.
|
||||
[i <= 10] whileTrue: [acc := acc + i. i := i + 1].
|
||||
^ acc")
|
||||
55)
|
||||
|
||||
;; ── 7. Nested while loops ──
|
||||
(st-test
|
||||
"nested whileTrue: produces flat sum"
|
||||
(evp
|
||||
"| total i j |
|
||||
total := 0. i := 0.
|
||||
[i < 3] whileTrue: [
|
||||
j := 0.
|
||||
[j < 4] whileTrue: [total := total + 1. j := j + 1].
|
||||
i := i + 1].
|
||||
^ total")
|
||||
12)
|
||||
|
||||
;; ── 8. ^ inside whileTrue: short-circuits the surrounding method ──
|
||||
(st-class-define! "WhileEscape" "Object" (list))
|
||||
(st-class-add-method! "WhileEscape" "firstOver:in:"
|
||||
(st-parse-method
|
||||
"firstOver: limit in: arr
|
||||
| i |
|
||||
i := 1.
|
||||
[i <= arr size] whileTrue: [
|
||||
(arr at: i) > limit ifTrue: [^ arr at: i].
|
||||
i := i + 1].
|
||||
^ nil"))
|
||||
|
||||
(st-test
|
||||
"early ^ from whileTrue: body"
|
||||
(evp "^ WhileEscape new firstOver: 5 in: #(1 3 5 7 9)")
|
||||
7)
|
||||
|
||||
(st-test
|
||||
"whileTrue: completes when nothing matches"
|
||||
(evp "^ WhileEscape new firstOver: 100 in: #(1 2 3)")
|
||||
nil)
|
||||
|
||||
;; ── 9. whileTrue: invocations independent across calls ──
|
||||
(st-class-define! "Counter2" "Object" (list "n"))
|
||||
(st-class-add-method! "Counter2" "init"
|
||||
(st-parse-method "init n := 0. ^ self"))
|
||||
(st-class-add-method! "Counter2" "n"
|
||||
(st-parse-method "n ^ n"))
|
||||
(st-class-add-method! "Counter2" "tick:"
|
||||
(st-parse-method "tick: count [count > 0] whileTrue: [n := n + 1. count := count - 1]. ^ self"))
|
||||
|
||||
(st-test
|
||||
"instance state survives whileTrue: invocations"
|
||||
(evp
|
||||
"| c | c := Counter2 new init.
|
||||
c tick: 3. c tick: 4.
|
||||
^ c n")
|
||||
7)
|
||||
|
||||
;; ── 10. Timing: whileTrue: on a never-true cond runs zero times ──
|
||||
(st-test
|
||||
"whileTrue: with always-false cond"
|
||||
(evp "| ran | ran := false. [false] whileTrue: [ran := true]. ^ ran")
|
||||
false)
|
||||
|
||||
(list st-test-pass st-test-fail)
|
||||
@@ -1,366 +0,0 @@
|
||||
;; Smalltalk tokenizer.
|
||||
;;
|
||||
;; Token types:
|
||||
;; ident identifier (foo, Foo, _x)
|
||||
;; keyword selector keyword (foo:) — value is "foo:" with the colon
|
||||
;; binary binary selector chars run together (+, ==, ->, <=, ~=, ...)
|
||||
;; number integer or float; radix integers like 16rFF supported
|
||||
;; string 'hello''world' style
|
||||
;; char $c
|
||||
;; symbol #foo, #foo:bar:, #+, #'with spaces'
|
||||
;; array-open #(
|
||||
;; byte-array-open #[
|
||||
;; lparen rparen lbracket rbracket lbrace rbrace
|
||||
;; period semi bar caret colon assign bang
|
||||
;; eof
|
||||
;;
|
||||
;; Comments "…" are skipped.
|
||||
|
||||
(define st-make-token (fn (type value pos) {:type type :value value :pos pos}))
|
||||
|
||||
(define st-digit? (fn (c) (and (not (= c nil)) (>= c "0") (<= c "9"))))
|
||||
|
||||
(define
|
||||
st-letter?
|
||||
(fn
|
||||
(c)
|
||||
(and
|
||||
(not (= c nil))
|
||||
(or (and (>= c "a") (<= c "z")) (and (>= c "A") (<= c "Z"))))))
|
||||
|
||||
(define st-ident-start? (fn (c) (or (st-letter? c) (= c "_"))))
|
||||
|
||||
(define st-ident-char? (fn (c) (or (st-ident-start? c) (st-digit? c))))
|
||||
|
||||
(define st-ws? (fn (c) (or (= c " ") (= c "\t") (= c "\n") (= c "\r"))))
|
||||
|
||||
(define
|
||||
st-binary-chars
|
||||
(list "+" "-" "*" "/" "\\" "~" "<" ">" "=" "@" "%" "&" "?" ","))
|
||||
|
||||
(define
|
||||
st-binary-char?
|
||||
(fn (c) (and (not (= c nil)) (contains? st-binary-chars c))))
|
||||
|
||||
(define
|
||||
st-radix-digit?
|
||||
(fn
|
||||
(c)
|
||||
(and
|
||||
(not (= c nil))
|
||||
(or (st-digit? c) (and (>= c "A") (<= c "Z"))))))
|
||||
|
||||
(define
|
||||
st-tokenize
|
||||
(fn
|
||||
(src)
|
||||
(let
|
||||
((tokens (list)) (pos 0) (src-len (len src)))
|
||||
(define
|
||||
pk
|
||||
(fn
|
||||
(offset)
|
||||
(if (< (+ pos offset) src-len) (nth src (+ pos offset)) nil)))
|
||||
(define cur (fn () (pk 0)))
|
||||
(define advance! (fn (n) (set! pos (+ pos n))))
|
||||
(define
|
||||
push!
|
||||
(fn
|
||||
(type value start)
|
||||
(append! tokens (st-make-token type value start))))
|
||||
(define
|
||||
skip-comment!
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((>= pos src-len) nil)
|
||||
((= (cur) "\"") (advance! 1))
|
||||
(else (begin (advance! 1) (skip-comment!))))))
|
||||
(define
|
||||
skip-ws!
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((>= pos src-len) nil)
|
||||
((st-ws? (cur)) (begin (advance! 1) (skip-ws!)))
|
||||
((= (cur) "\"") (begin (advance! 1) (skip-comment!) (skip-ws!)))
|
||||
(else nil))))
|
||||
(define
|
||||
read-ident-chars!
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos src-len) (st-ident-char? (cur)))
|
||||
(begin (advance! 1) (read-ident-chars!)))))
|
||||
(define
|
||||
read-decimal-digits!
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos src-len) (st-digit? (cur)))
|
||||
(begin (advance! 1) (read-decimal-digits!)))))
|
||||
(define
|
||||
read-radix-digits!
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos src-len) (st-radix-digit? (cur)))
|
||||
(begin (advance! 1) (read-radix-digits!)))))
|
||||
(define
|
||||
read-exp-part!
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and
|
||||
(< pos src-len)
|
||||
(or (= (cur) "e") (= (cur) "E"))
|
||||
(let
|
||||
((p1 (pk 1)) (p2 (pk 2)))
|
||||
(or
|
||||
(st-digit? p1)
|
||||
(and (or (= p1 "+") (= p1 "-")) (st-digit? p2)))))
|
||||
(begin
|
||||
(advance! 1)
|
||||
(when
|
||||
(and (< pos src-len) (or (= (cur) "+") (= (cur) "-")))
|
||||
(advance! 1))
|
||||
(read-decimal-digits!)))))
|
||||
(define
|
||||
read-number
|
||||
(fn
|
||||
(start)
|
||||
(begin
|
||||
(read-decimal-digits!)
|
||||
(cond
|
||||
((and (< pos src-len) (= (cur) "r"))
|
||||
(let
|
||||
((base-str (slice src start pos)))
|
||||
(begin
|
||||
(advance! 1)
|
||||
(let
|
||||
((rstart pos))
|
||||
(begin
|
||||
(read-radix-digits!)
|
||||
(let
|
||||
((digits (slice src rstart pos)))
|
||||
{:radix (parse-number base-str)
|
||||
:digits digits
|
||||
:value (parse-radix base-str digits)
|
||||
:kind "radix"}))))))
|
||||
((and
|
||||
(< pos src-len)
|
||||
(= (cur) ".")
|
||||
(st-digit? (pk 1)))
|
||||
(begin
|
||||
(advance! 1)
|
||||
(read-decimal-digits!)
|
||||
(read-exp-part!)
|
||||
(parse-number (slice src start pos))))
|
||||
(else
|
||||
(begin
|
||||
(read-exp-part!)
|
||||
(parse-number (slice src start pos))))))))
|
||||
(define
|
||||
parse-radix
|
||||
(fn
|
||||
(base-str digits)
|
||||
(let
|
||||
((base (parse-number base-str))
|
||||
(chars digits)
|
||||
(n-len (len digits))
|
||||
(idx 0)
|
||||
(acc 0))
|
||||
(begin
|
||||
(define
|
||||
rd-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(< idx n-len)
|
||||
(let
|
||||
((c (nth chars idx)))
|
||||
(let
|
||||
((d (cond
|
||||
((and (>= c "0") (<= c "9")) (- (char-code c) 48))
|
||||
((and (>= c "A") (<= c "Z")) (- (char-code c) 55))
|
||||
(else 0))))
|
||||
(begin
|
||||
(set! acc (+ (* acc base) d))
|
||||
(set! idx (+ idx 1))
|
||||
(rd-loop)))))))
|
||||
(rd-loop)
|
||||
acc))))
|
||||
(define
|
||||
read-string
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((chars (list)))
|
||||
(begin
|
||||
(advance! 1)
|
||||
(define
|
||||
loop
|
||||
(fn
|
||||
()
|
||||
(cond
|
||||
((>= pos src-len) nil)
|
||||
((= (cur) "'")
|
||||
(cond
|
||||
((= (pk 1) "'")
|
||||
(begin
|
||||
(append! chars "'")
|
||||
(advance! 2)
|
||||
(loop)))
|
||||
(else (advance! 1))))
|
||||
(else
|
||||
(begin (append! chars (cur)) (advance! 1) (loop))))))
|
||||
(loop)
|
||||
(join "" chars)))))
|
||||
(define
|
||||
read-binary-run!
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((start pos))
|
||||
(begin
|
||||
(define
|
||||
bin-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos src-len) (st-binary-char? (cur)))
|
||||
(begin (advance! 1) (bin-loop)))))
|
||||
(bin-loop)
|
||||
(slice src start pos)))))
|
||||
(define
|
||||
read-symbol
|
||||
(fn
|
||||
(start)
|
||||
(cond
|
||||
;; Quoted symbol: #'whatever'
|
||||
((= (cur) "'")
|
||||
(let ((s (read-string))) (push! "symbol" s start)))
|
||||
;; Binary-char symbol: #+, #==, #->, #|
|
||||
((or (st-binary-char? (cur)) (= (cur) "|"))
|
||||
(let ((b (read-binary-run!)))
|
||||
(cond
|
||||
((= b "")
|
||||
;; lone | wasn't binary; consume it
|
||||
(begin (advance! 1) (push! "symbol" "|" start)))
|
||||
(else (push! "symbol" b start)))))
|
||||
;; Identifier or keyword chain: #foo, #foo:bar:
|
||||
((st-ident-start? (cur))
|
||||
(let ((id-start pos))
|
||||
(begin
|
||||
(read-ident-chars!)
|
||||
(define
|
||||
kw-loop
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos src-len) (= (cur) ":"))
|
||||
(begin
|
||||
(advance! 1)
|
||||
(when
|
||||
(and (< pos src-len) (st-ident-start? (cur)))
|
||||
(begin (read-ident-chars!) (kw-loop)))))))
|
||||
(kw-loop)
|
||||
(push! "symbol" (slice src id-start pos) start))))
|
||||
(else
|
||||
(error
|
||||
(str "st-tokenize: bad symbol at " pos))))))
|
||||
(define
|
||||
step
|
||||
(fn
|
||||
()
|
||||
(begin
|
||||
(skip-ws!)
|
||||
(when
|
||||
(< pos src-len)
|
||||
(let
|
||||
((start pos) (c (cur)))
|
||||
(cond
|
||||
;; Identifier or keyword
|
||||
((st-ident-start? c)
|
||||
(begin
|
||||
(read-ident-chars!)
|
||||
(let
|
||||
((word (slice src start pos)))
|
||||
(cond
|
||||
;; ident immediately followed by ':' (and not ':=') => keyword
|
||||
((and
|
||||
(< pos src-len)
|
||||
(= (cur) ":")
|
||||
(not (= (pk 1) "=")))
|
||||
(begin
|
||||
(advance! 1)
|
||||
(push!
|
||||
"keyword"
|
||||
(str word ":")
|
||||
start)))
|
||||
(else (push! "ident" word start))))
|
||||
(step)))
|
||||
;; Number
|
||||
((st-digit? c)
|
||||
(let
|
||||
((v (read-number start)))
|
||||
(begin (push! "number" v start) (step))))
|
||||
;; String
|
||||
((= c "'")
|
||||
(let
|
||||
((s (read-string)))
|
||||
(begin (push! "string" s start) (step))))
|
||||
;; Character literal
|
||||
((= c "$")
|
||||
(cond
|
||||
((>= (+ pos 1) src-len)
|
||||
(error (str "st-tokenize: $ at end of input")))
|
||||
(else
|
||||
(begin
|
||||
(advance! 1)
|
||||
(push! "char" (cur) start)
|
||||
(advance! 1)
|
||||
(step)))))
|
||||
;; Symbol or array literal
|
||||
((= c "#")
|
||||
(cond
|
||||
((= (pk 1) "(")
|
||||
(begin (advance! 2) (push! "array-open" "#(" start) (step)))
|
||||
((= (pk 1) "[")
|
||||
(begin (advance! 2) (push! "byte-array-open" "#[" start) (step)))
|
||||
(else
|
||||
(begin (advance! 1) (read-symbol start) (step)))))
|
||||
;; Assignment := or bare colon
|
||||
((= c ":")
|
||||
(cond
|
||||
((= (pk 1) "=")
|
||||
(begin (advance! 2) (push! "assign" ":=" start) (step)))
|
||||
(else
|
||||
(begin (advance! 1) (push! "colon" ":" start) (step)))))
|
||||
;; Single-char structural punctuation
|
||||
((= c "(") (begin (advance! 1) (push! "lparen" "(" start) (step)))
|
||||
((= c ")") (begin (advance! 1) (push! "rparen" ")" start) (step)))
|
||||
((= c "[") (begin (advance! 1) (push! "lbracket" "[" start) (step)))
|
||||
((= c "]") (begin (advance! 1) (push! "rbracket" "]" start) (step)))
|
||||
((= c "{") (begin (advance! 1) (push! "lbrace" "{" start) (step)))
|
||||
((= c "}") (begin (advance! 1) (push! "rbrace" "}" start) (step)))
|
||||
((= c ".") (begin (advance! 1) (push! "period" "." start) (step)))
|
||||
((= c ";") (begin (advance! 1) (push! "semi" ";" start) (step)))
|
||||
((= c "|") (begin (advance! 1) (push! "bar" "|" start) (step)))
|
||||
((= c "^") (begin (advance! 1) (push! "caret" "^" start) (step)))
|
||||
((= c "!") (begin (advance! 1) (push! "bang" "!" start) (step)))
|
||||
;; Binary selector run
|
||||
((st-binary-char? c)
|
||||
(let
|
||||
((b (read-binary-run!)))
|
||||
(begin (push! "binary" b start) (step))))
|
||||
(else
|
||||
(error
|
||||
(str
|
||||
"st-tokenize: unexpected char "
|
||||
c
|
||||
" at "
|
||||
pos)))))))))
|
||||
(step)
|
||||
(push! "eof" nil pos)
|
||||
tokens)))
|
||||
81
plans/agent-briefings/apl-loop.md
Normal file
81
plans/agent-briefings/apl-loop.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# apl-on-sx loop agent (single agent, queue-driven)
|
||||
|
||||
Role: iterates `plans/apl-on-sx.md` forever. Rank-polymorphic primitives + 6 operators on the JIT is the headline showcase — APL is the densest combinator algebra you can put on top of a primitive table. Every program is `array → array` pure pipelines, exactly what the JIT was built for.
|
||||
|
||||
```
|
||||
description: apl-on-sx queue loop
|
||||
subagent_type: general-purpose
|
||||
run_in_background: true
|
||||
isolation: worktree
|
||||
```
|
||||
|
||||
## Prompt
|
||||
|
||||
You are the sole background agent working `/root/rose-ash/plans/apl-on-sx.md`. Isolated worktree, forever, one commit per feature. Never push.
|
||||
|
||||
## Restart baseline — check before iterating
|
||||
|
||||
1. Read `plans/apl-on-sx.md` — roadmap + Progress log.
|
||||
2. `ls lib/apl/` — pick up from the most advanced file.
|
||||
3. If `lib/apl/tests/*.sx` exist, run them. Green before new work.
|
||||
4. If `lib/apl/scoreboard.md` exists, that's your baseline.
|
||||
|
||||
## The queue
|
||||
|
||||
Phase order per `plans/apl-on-sx.md`:
|
||||
|
||||
- **Phase 1** — tokenizer + parser. Unicode glyphs, `¯` for negative, strands (juxtaposition), right-to-left, valence resolution by syntactic position
|
||||
- **Phase 2** — array model + scalar primitives. `make-array {shape, ravel}`, scalar promotion, broadcast for `+ - × ÷ ⌈ ⌊ * ⍟ | ! ○`, comparison, logical, `⍳`, `⎕IO`
|
||||
- **Phase 3** — structural primitives + indexing. `⍴ , ⍉ ↑ ↓ ⌽ ⊖ ⌷ ⍋ ⍒ ⊂ ⊃ ∊`
|
||||
- **Phase 4** — **THE SHOWCASE**: operators. `f/` (reduce), `f¨` (each), `∘.f` (outer), `f.g` (inner), `f⍨` (commute), `f∘g` (compose), `f⍣n` (power), `f⍤k` (rank), `@` (at)
|
||||
- **Phase 5** — dfns + tradfns + control flow. `{⍺+⍵}`, `∇` recurse, `⍺←default`, tradfn header, `:If/:While/:For/:Select`
|
||||
- **Phase 6** — classic programs (life, mandelbrot, primes, n-queens, quicksort) + idiom corpus + drive to 100+
|
||||
|
||||
Within a phase, pick the checkbox that unlocks the most tests per effort.
|
||||
|
||||
Every iteration: implement → test → commit → tick `[ ]` → Progress log → next.
|
||||
|
||||
## Ground rules (hard)
|
||||
|
||||
- **Scope:** only `lib/apl/**` and `plans/apl-on-sx.md`. Do **not** edit `spec/`, `hosts/`, `shared/`, other `lib/<lang>/` dirs, `lib/stdlib.sx`, or `lib/` root. APL primitives go in `lib/apl/runtime.sx`.
|
||||
- **NEVER call `sx_build`.** 600s watchdog. If sx_server binary broken → Blockers entry, stop.
|
||||
- **Shared-file issues** → plan's Blockers with minimal repro.
|
||||
- **SX files:** `sx-tree` MCP tools ONLY. `sx_validate` after edits.
|
||||
- **Unicode in `.sx`:** raw UTF-8 only, never `\uXXXX` escapes. Glyphs land directly in source.
|
||||
- **Worktree:** commit locally. Never push. Never touch `main`.
|
||||
- **Commit granularity:** one feature per commit.
|
||||
- **Plan file:** update Progress log + tick boxes every commit.
|
||||
|
||||
## APL-specific gotchas
|
||||
|
||||
- **Right-to-left, no precedence among functions.** `2 × 3 + 4` is `2 × (3 + 4)` = 14, not 10. Operators bind tighter than functions: `+/ ⍳5` is `+/(⍳5)`, and `2 +.× 3 4` is `2 (+.×) 3 4`.
|
||||
- **Valence by position.** `-3` is monadic negate (`-` with no left arg). `5-3` is dyadic subtract. The parser must look left to decide. Same glyph; different fn.
|
||||
- **`¯` is part of a number literal**, not a prefix function. `¯3` is the literal negative three; `-3` is the function call. Tokenizer eats `¯` into the numeric token.
|
||||
- **Strands.** `1 2 3` is a 3-element vector, not three separate calls. Adjacent literals fuse into a strand at parse time. Adjacent names do *not* fuse — `a b c` is three separate references.
|
||||
- **Scalar promotion.** `1 + 2 3 4` ↦ `3 4 5`. Any scalar broadcasts against any-rank conformable shape.
|
||||
- **Conformability** = exactly matching shapes, OR one side scalar, OR (in some dialects) one side rank-1 cycling against rank-N. Keep strict in v1: matching shape or scalar only.
|
||||
- **`⍳` is overloaded.** Monadic `⍳N` = vector 1..N (or 0..N-1 if `⎕IO=0`). Dyadic `V ⍳ W` = first-index lookup, returns `≢V+1` for not-found.
|
||||
- **Reduce with `+/⍳0`** = `0` (identity for `+`). Each scalar primitive has a defined identity used by reduce-on-empty. Don't crash; return identity.
|
||||
- **Reduce direction.** `f/` reduces the *last* axis. `f⌿` reduces the *first*. Matters for matrices.
|
||||
- **Indexing is 1-based** by default (`⎕IO=1`). Do not silently translate to 0-based; respect `⎕IO`.
|
||||
- **Bracket indexing** `A[I]` is sugar for `I⌷A` (squad-quad). Multi-axis: `A[I;J]` is `I J⌷A` with semicolon-separated axes; `A[;J]` selects all of axis 0.
|
||||
- **Dfn `{...}`** — `⍺` = left arg (may be unbound for monadic call → check with `⍺←default`), `⍵` = right arg, `∇` = recurse. Default left arg syntax: `⍺←0`.
|
||||
- **Tradfn vs dfn** — tradfns use line-numbered `→linenum` for goto; dfns use guards `cond:expr`. Pick the right one for the user's syntax.
|
||||
- **Empty array** = rank-N array where some dim is 0. `0⍴⍳0` is empty rank-1. Scalar prototype matters for empty-array operations; ignore in v1, return 0/space.
|
||||
- **Test corpus:** custom + idioms. Place programs in `lib/apl/tests/programs/` with `.apl` extension.
|
||||
|
||||
## General gotchas (all loops)
|
||||
|
||||
- SX `do` = R7RS iteration. Use `begin` for multi-expr sequences.
|
||||
- `cond`/`when`/`let` clauses evaluate only the last expr.
|
||||
- `type-of` on user fn returns `"lambda"`.
|
||||
- Shell heredoc `||` gets eaten — escape or use `case`.
|
||||
|
||||
## Style
|
||||
|
||||
- No comments in `.sx` unless non-obvious.
|
||||
- No new planning docs — update `plans/apl-on-sx.md` inline.
|
||||
- Short, factual commit messages (`apl: outer product ∘. (+9)`).
|
||||
- One feature per iteration. Commit. Log. Next.
|
||||
|
||||
Go. Read the plan; find first `[ ]`; implement.
|
||||
80
plans/agent-briefings/common-lisp-loop.md
Normal file
80
plans/agent-briefings/common-lisp-loop.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# common-lisp-on-sx loop agent (single agent, queue-driven)
|
||||
|
||||
Role: iterates `plans/common-lisp-on-sx.md` forever. Conditions + restarts on delimited continuations is the headline showcase — every other Lisp reinvents resumable exceptions on the host stack. On SX `signal`/`invoke-restart` is just a captured continuation. Plus CLOS, the LOOP macro, packages.
|
||||
|
||||
```
|
||||
description: common-lisp-on-sx queue loop
|
||||
subagent_type: general-purpose
|
||||
run_in_background: true
|
||||
isolation: worktree
|
||||
```
|
||||
|
||||
## Prompt
|
||||
|
||||
You are the sole background agent working `/root/rose-ash/plans/common-lisp-on-sx.md`. Isolated worktree, forever, one commit per feature. Never push.
|
||||
|
||||
## Restart baseline — check before iterating
|
||||
|
||||
1. Read `plans/common-lisp-on-sx.md` — roadmap + Progress log.
|
||||
2. `ls lib/common-lisp/` — pick up from the most advanced file.
|
||||
3. If `lib/common-lisp/tests/*.sx` exist, run them. Green before new work.
|
||||
4. If `lib/common-lisp/scoreboard.md` exists, that's your baseline.
|
||||
|
||||
## The queue
|
||||
|
||||
Phase order per `plans/common-lisp-on-sx.md`:
|
||||
|
||||
- **Phase 1** — reader + parser (read macros `#'` `'` `` ` `` `,` `,@` `#( … )` `#:` `#\char` `#xFF` `#b1010`, ratios, dispatch chars, lambda lists with `&optional`/`&rest`/`&key`/`&aux`)
|
||||
- **Phase 2** — sequential eval + special forms (`let`/`let*`/`flet`/`labels`, `block`/`return-from`, `tagbody`/`go`, `unwind-protect`, multiple values, `setf` subset, dynamic variables)
|
||||
- **Phase 3** — **THE SHOWCASE**: condition system + restarts. `define-condition`, `signal`/`error`/`cerror`/`warn`, `handler-bind` (non-unwinding), `handler-case` (unwinding), `restart-case`, `restart-bind`, `find-restart`/`invoke-restart`/`compute-restarts`, `with-condition-restarts`. Classic programs (restart-demo, parse-recover, interactive-debugger) green.
|
||||
- **Phase 4** — CLOS: `defclass`, `defgeneric`, `defmethod` with `:before`/`:after`/`:around`, `call-next-method`, multiple dispatch
|
||||
- **Phase 5** — macros + LOOP macro + reader macros
|
||||
- **Phase 6** — packages + stdlib (sequence functions, FORMAT directives, drive corpus to 200+)
|
||||
|
||||
Within a phase, pick the checkbox that unlocks the most tests per effort.
|
||||
|
||||
Every iteration: implement → test → commit → tick `[ ]` → Progress log → next.
|
||||
|
||||
## Ground rules (hard)
|
||||
|
||||
- **Scope:** only `lib/common-lisp/**` and `plans/common-lisp-on-sx.md`. Do **not** edit `spec/`, `hosts/`, `shared/`, other `lib/<lang>/` dirs, `lib/stdlib.sx`, or `lib/` root. CL primitives go in `lib/common-lisp/runtime.sx`.
|
||||
- **NEVER call `sx_build`.** 600s watchdog. If sx_server binary broken → Blockers entry, stop.
|
||||
- **Shared-file issues** → plan's Blockers with minimal repro.
|
||||
- **Delimited continuations** are in `lib/callcc.sx` + `spec/evaluator.sx` Step 5. `sx_summarise` spec/evaluator.sx first — 2300+ lines.
|
||||
- **SX files:** `sx-tree` MCP tools ONLY. `sx_validate` after edits.
|
||||
- **Worktree:** commit locally. Never push. Never touch `main`.
|
||||
- **Commit granularity:** one feature per commit.
|
||||
- **Plan file:** update Progress log + tick boxes every commit.
|
||||
|
||||
## Common-Lisp-specific gotchas
|
||||
|
||||
- **`handler-bind` is non-unwinding** — handlers can decline by returning normally, in which case `signal` keeps walking the chain. **`handler-case` is unwinding** — picking a handler aborts the protected form via a captured continuation. Don't conflate them.
|
||||
- **Restarts are not handlers.** `restart-case` establishes named *resumption points*; `signal` runs handler code with restarts visible; the handler chooses a restart by calling `invoke-restart`, which abandons handler stack and resumes at the restart point. Two stacks: handlers walk down, restarts wait to be invoked.
|
||||
- **`block` / `return-from`** is lexical. `block name … (return-from name v) …` captures `^k` once at entry; `return-from` invokes it. `return-from` to a name not in scope is an error (don't fall back to outer block).
|
||||
- **`tagbody` / `go`** — each tag in tagbody is a continuation; `go tag` invokes it. Tags are lexical, can only target tagbodies in scope.
|
||||
- **`unwind-protect`** runs cleanup on *any* non-local exit (return-from, throw, condition unwind). Implement as a scope frame fired by the cleanup machinery.
|
||||
- **Multiple values**: primary-value-only contexts (function args, `if` test, etc.) drop extras silently. `values` produces multiple. `multiple-value-bind` / `multiple-value-call` consume them. Don't auto-list.
|
||||
- **CLOS dispatch:** sort applicable methods by argument-list specificity (`subclassp` per arg, left-to-right); standard method combination calls primary methods most-specific-first via `call-next-method` chain. `:before` runs all before primaries; `:after` runs all after, in reverse-specificity. `:around` wraps everything.
|
||||
- **`call-next-method`** is a *continuation* available only inside a method body. Implement as a thunk stored in a dynamic-extent variable.
|
||||
- **Generalised reference (`setf`)**: `(setf (foo x) v)` ↦ `(setf-foo v x)`. Look up the setf-expander, not just a writer fn. `define-setf-expander` is mandatory for non-trivial places. Start with the symbolic / list / aref / slot-value cases.
|
||||
- **Dynamic variables (specials):** `defvar`/`defparameter` mark a symbol as special. `let` over a special name *rebinds* in dynamic extent (use parameterize-style scope), not lexical.
|
||||
- **Symbols are package-qualified.** Reader resolves `cl:car`, `mypkg::internal`, bare `foo` (current package). Internal vs external matters for `:` (one colon) reads.
|
||||
- **`nil` is also `()` is also the empty list.** Same object. `nil` is also false. CL has no distinct unit value.
|
||||
- **LOOP macro is huge.** Build incrementally — start with `for/in`, `for/from`, `collect`, `sum`, `count`, `repeat`. Add conditional clauses (`when`, `if`, `else`) once iteration drivers stable. `named` blocks + `return-from named` last.
|
||||
- **Test corpus:** custom + curated `ansi-test` slice. Place programs in `lib/common-lisp/tests/programs/` with `.lisp` extension.
|
||||
|
||||
## General gotchas (all loops)
|
||||
|
||||
- SX `do` = R7RS iteration. Use `begin` for multi-expr sequences.
|
||||
- `cond`/`when`/`let` clauses evaluate only the last expr.
|
||||
- `type-of` on user fn returns `"lambda"`.
|
||||
- Shell heredoc `||` gets eaten — escape or use `case`.
|
||||
|
||||
## Style
|
||||
|
||||
- No comments in `.sx` unless non-obvious.
|
||||
- No new planning docs — update `plans/common-lisp-on-sx.md` inline.
|
||||
- Short, factual commit messages (`common-lisp: handler-bind + 12 tests`).
|
||||
- One feature per iteration. Commit. Log. Next.
|
||||
|
||||
Go. Read the plan; find first `[ ]`; implement.
|
||||
769
plans/agent-briefings/primitives-loop.md
Normal file
769
plans/agent-briefings/primitives-loop.md
Normal file
@@ -0,0 +1,769 @@
|
||||
# SX Primitives — Meta-Loop Briefing
|
||||
|
||||
Goal: add fundamental missing SX primitives in sequence, then sweep all language
|
||||
implementations to replace their workarounds. Full rationale: vectors fix O(n) array
|
||||
access across every language; numeric tower fixes float/int conflation; dynamic-wind
|
||||
fixes cleanup semantics; coroutine primitive unifies Ruby/Lua/Tcl; string buffer fixes
|
||||
O(n²) concat; algebraic data types eliminate the tagged-dict pattern everywhere.
|
||||
|
||||
**Each fire: find the first unchecked `[ ]`, do it, commit, tick it, stop.**
|
||||
Sub-items within a Phase may span multiple fires — just commit progress and tick what's done.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — Prep (gate)
|
||||
|
||||
- [x] Stop new-language loops: send `/exit` to sx-loops windows for the four blank-slate
|
||||
languages that haven't committed workarounds yet:
|
||||
```
|
||||
tmux send-keys -t sx-loops:common-lisp "/exit" Enter
|
||||
tmux send-keys -t sx-loops:apl "/exit" Enter
|
||||
tmux send-keys -t sx-loops:ruby "/exit" Enter
|
||||
tmux send-keys -t sx-loops:tcl "/exit" Enter
|
||||
```
|
||||
Verify all four windows are idle (claude prompt, no active task).
|
||||
|
||||
- [x] E38 + E39 landed: check both Bucket-E branches for implementation commits.
|
||||
```
|
||||
git log --oneline hs-e38-sourceinfo | head -5
|
||||
git log --oneline hs-e39-webworker | head -5
|
||||
```
|
||||
If either branch has only its base commit (no impl work yet): note "pending" and stop —
|
||||
next fire re-checks. Proceed only when both have at least one implementation commit.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Vectors
|
||||
|
||||
Native mutable integer-indexed arrays. Fix: Lua O(n) sort, APL rank polymorphism, Ruby
|
||||
Array, Tcl lists, Common Lisp vectors, all using string-keyed dicts today.
|
||||
|
||||
Primitives to add:
|
||||
- `make-vector` `n` `[fill]` → vector of length n
|
||||
- `vector?` `v` → bool
|
||||
- `vector-ref` `v` `i` → element at index i (0-based)
|
||||
- `vector-set!` `v` `i` `x` → mutate in place
|
||||
- `vector-length` `v` → integer
|
||||
- `vector->list` `v` → list
|
||||
- `list->vector` `lst` → vector
|
||||
- `vector-fill!` `v` `x` → fill all elements
|
||||
- `vector-copy` `v` `[start]` `[end]` → fresh copy of slice
|
||||
|
||||
Steps:
|
||||
- [x] OCaml: add `SxVector of value array` to `hosts/ocaml/sx_types.ml`; implement all
|
||||
primitives in `hosts/ocaml/sx_primitives.ml` (or equivalent); wire into evaluator.
|
||||
Note: Vector type + most prims were already present; added bounds-checked vector-ref/set!
|
||||
and optional start/end to vector-copy. 10/10 vector tests pass (r7rs suite).
|
||||
- [x] Spec: add vector entries to `spec/primitives.sx` with type signatures and descriptions.
|
||||
All 10 vector primitives now have :as type annotations, :returns, and :doc strings.
|
||||
make-vector: optional fill param; vector-copy: optional start/end (done prev step).
|
||||
- [x] JS bootstrapper: implement vectors in `hosts/javascript/platform.js` (or equivalent);
|
||||
ensure `sx-browser.js` rebuild picks them up.
|
||||
Fixed index-of for lists (was returning -1 not NIL, breaking bind-lambda-params),
|
||||
added _lastErrorKont_/hostError/try-catch/without-io-hook stubs. Vectors work.
|
||||
- [x] Tests: 40+ tests in `spec/tests/test-vectors.sx` covering construction, ref, set!,
|
||||
length, conversions, fill, copy, bounds behaviour.
|
||||
42 tests, all pass. 1847 standard / 2362 full passing (up from 5).
|
||||
- [x] Verify: full test suite still passes (`node hosts/javascript/run_tests.js --full`).
|
||||
2362/4924 pass (improvement from pre-existing lambda binding bug, no regressions).
|
||||
- [x] Commit: `spec: vector primitive (make-vector/vector-ref/vector-set!/etc)`
|
||||
Committed as: js: fix lambda binding (index-of on lists), add vectors + R7RS platform stubs
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Numeric tower
|
||||
|
||||
Float ≠ integer distinction. Fix: Erlang `=:=`, Lua `math.type()`, Haskell `Num`/`Integral`,
|
||||
Common Lisp `integerp`/`floatp`/`ratio`, JS `Number.isInteger`.
|
||||
|
||||
Changes:
|
||||
- `parse-number` preserves float identity: `"1.0"` → float 1.0, not integer 1
|
||||
- New predicates: `integer?`, `float?`, `exact?`, `inexact?`
|
||||
- New coercions: `exact->inexact`, `inexact->exact`
|
||||
- Fix `floor`/`ceiling`/`truncate`/`round` to return integers when applied to floats
|
||||
- `number->string` renders `1.0` as `"1.0"`, `1` as `"1"`
|
||||
- Arithmetic: `(+ 1 1.0)` → `2.0` (float contagion), `(+ 1 1)` → `2` (integer)
|
||||
|
||||
Steps:
|
||||
- [x] OCaml: distinguish `Integer of int` / `Number of float` in `sx_types.ml`; update all
|
||||
arithmetic primitives for float contagion; fix `parse-number`.
|
||||
92/92 numeric tower tests pass; 4874 total (394 pre-existing hs-upstream fails unchanged).
|
||||
- [x] Spec: update `spec/primitives.sx` with new predicates + coercions; document contagion rules.
|
||||
Added integer?/float? predicates; updated number? body; / returns "float"; floor/ceil/truncate
|
||||
return "integer"; +/-/* doc float contagion; fixed double-paren params; 4874/394 baseline.
|
||||
- [x] JS bootstrapper: update number representation and arithmetic.
|
||||
Added integer?/float?/exact?/inexact?/truncate/remainder/modulo/random-int/exact->inexact/
|
||||
inexact->exact/parse-number. Fixed sx_server.ml epoch protocol for Integer type.
|
||||
JS: 1940 passed (+60); OCaml: 4874/394 unchanged. 6 tests JS-only fail (float≡int limitation).
|
||||
- [x] Tests: 92 tests in `spec/tests/test-numeric-tower.sx` — int-arithmetic, float-contagion,
|
||||
division, predicates, coercions, rounding, parse-number, equality, modulo, min-max, stringify.
|
||||
- [x] Verify: full suite passes. OCaml 4874/394 (baseline unchanged). JS 1940/2500 (+60 vs pre-tower).
|
||||
No regressions on any test that relied on `1.0 = 1` — those tests were already using integer
|
||||
literals which remain identical in JS. 6 JS-only failures are platform-inherent (JS float≡int).
|
||||
- [x] Commit: all work landed across 4 commits (c70bbdeb, 45ec5535, b12a22e6, f5acb31c).
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Dynamic-wind
|
||||
|
||||
Fix: Common Lisp `unwind-protect`, Ruby `ensure`, JS `finally`, Tcl `catch`+cleanup,
|
||||
Erlang `try...after` (currently uses double-nested guard workaround).
|
||||
|
||||
- [x] Spec: implement `dynamic-wind` in `spec/evaluator.sx` such that the after-thunk fires
|
||||
on both normal return AND non-local exit (raise/call-cc escape). Must compose with
|
||||
`guard` — currently they don't interact.
|
||||
- [x] OCaml: wire `dynamic-wind` through the CEK machine with a `WindFrame` continuation.
|
||||
- [x] JS bootstrapper: update.
|
||||
- [x] Tests: 20+ tests covering normal return, raise, call/cc escape, nested dynamic-winds.
|
||||
- [x] Commit: `spec: dynamic-wind + guard integration`
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Coroutine primitive
|
||||
|
||||
Unify Ruby fibers, Lua coroutines, Tcl coroutines — all currently reimplemented separately
|
||||
using call/cc+perform/resume.
|
||||
|
||||
- [x] Spec: add `make-coroutine`, `coroutine-resume`, `coroutine-yield`, `coroutine?`,
|
||||
`coroutine-alive?` to `spec/primitives.sx`. Build on existing `perform`/`cek-resume`
|
||||
machinery — coroutines ARE perform/resume with a stable identity.
|
||||
Implemented as `spec/coroutines.sx` define-library; `make-coroutine` stub in evaluator.sx.
|
||||
17/17 coroutine tests pass (OCaml). Drives iteration via define+fn recursion (not named let —
|
||||
named let uses cek_call→cek_run which errors on IO suspension).
|
||||
- [x] OCaml: implement coroutine type; wire resume/yield through CEK suspension.
|
||||
No new native type needed — dict-based coroutine identity + existing cek-step-loop/
|
||||
cek-resume/perform primitives in run_tests.ml ARE the OCaml implementation. 17/17 pass.
|
||||
- [x] JS bootstrapper: update.
|
||||
All CEK primitives already in sx-browser.js. Fix: pre-load spec/coroutines.sx +
|
||||
spec/signals.sx in run_tests.js so (import (sx coroutines)) resolves without suspension.
|
||||
17/17 pass in JS. 1965/2500 (+25 vs 1940 baseline). Zero new failures.
|
||||
- [x] Tests: 25+ tests — multi-yield, final return, arg passthrough, alive? predicate,
|
||||
nested coroutines, "final return vs yield" distinction (the Lua gotcha).
|
||||
27 tests: added 10 new — state field inspection (ready/suspended/dead), yield from
|
||||
nested helper, initial resume arg ignored, mutable closure state, complex yield values,
|
||||
round-robin scheduling, factory-shared-no-state, non-coroutine error. 27/27 OCaml+JS.
|
||||
- [x] Commit: `spec: coroutine primitive (make-coroutine/resume/yield)`
|
||||
Phase 4 landed across 4 commits: 21cb9cf5 (spec library), 9eb12c66 (ocaml verified),
|
||||
b78e06a7 (js pre-load), 0ffe208e (27 tests). Phase 4 complete.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — String buffer
|
||||
|
||||
Fix O(n²) string concatenation in loops across Lua, Ruby, Common Lisp, Tcl.
|
||||
|
||||
- [x] Spec + OCaml: add `make-string-buffer`, `string-buffer-append!`, `string-buffer->string`,
|
||||
`string-buffer-length` to primitives. OCaml: `Buffer.t` wrapper. JS: array+join.
|
||||
Also: string-buffer? predicate; SxStringBuffer._string_buffer marker for typeOf/dict?
|
||||
exclusion; inspect case in sx_types.ml. 17/17 tests OCaml+JS.
|
||||
- [x] Tests: 15+ tests.
|
||||
17 tests written inline with Spec+OCaml step: construction, type-of, empty/length,
|
||||
single/multi-append, append-returns-nil, empty-string-append, reuse-after-to-string,
|
||||
independence, loop-building, CSV-row, unicode, repeated-to-string, join-pattern.
|
||||
17/17 OCaml+JS.
|
||||
- [x] Commit: `spec: string-buffer primitive`
|
||||
Committed as d98b5fa2 — all work in one commit (OCaml type + primitives + JS + spec + 17 tests).
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — Algebraic data types
|
||||
|
||||
The deepest structural gap. Every language uses `{:tag "..." :field ...}` tagged dicts to
|
||||
simulate sum types. A native `define-type` + `match` form eliminates this everywhere.
|
||||
|
||||
- [x] Design: write `plans/designs/sx-adt.md` covering syntax, CEK dispatch, interaction with
|
||||
existing `cond`/`case`, exhaustiveness checking, recursive types, pattern variables.
|
||||
Draft, then stop — next fire reviews design before implementing.
|
||||
Written: define-type/match syntax, AdtValue runtime rep, stepSfDefineType + MatchFrame
|
||||
CEK dispatch, exhaustiveness warnings via _adt_registry, recursive types, nested patterns,
|
||||
wildcard _, 3-phase impl plan (basic/nested/exhaustiveness), open questions on accessors/singletons/inspect.
|
||||
|
||||
- [x] Spec: implement `define-type` special form in `spec/evaluator.sx`:
|
||||
`(define-type Name (Ctor1 field...) (Ctor2 field...) ...)`
|
||||
Creates constructor functions `Ctor1`, `Ctor2` + predicate `Name?`.
|
||||
|
||||
- [x] Spec: implement `match` special form:
|
||||
`(match expr ((Ctor1 a b) body) ((Ctor2 x) body) (else body))`
|
||||
Exhaustiveness warning if not all constructors covered and no `else`.
|
||||
|
||||
- [x] OCaml: add `SxAdt of string * value array` to types; implement constructors + match.
|
||||
Dict-based ADT (no native type needed — matches spec). Hand-written sf_define_type
|
||||
in bootstrap.py FIXUPS; registered via register_special_form. 172 assertions pass.
|
||||
4280/1080 full suite (37 improvement over old baseline 4243/1117).
|
||||
- [x] JS bootstrapper: update.
|
||||
No changes needed — define-type/match are spec-level; sx-browser.js rebuilt at 0dc7e159.
|
||||
40/40 ADT tests pass JS. 2032/2500 total (+67 vs 1965 phase-4 baseline).
|
||||
- [x] Tests: 40+ tests in `spec/tests/test-adt.sx`.
|
||||
40 tests written across two spec commits (6c872107+0dc7e159). All pass OCaml+JS.
|
||||
- [x] Commit: `spec: algebraic data types (define-type + match)`
|
||||
Phase 6 landed across 5 commits: 6c872107 (define-type spec), 0dc7e159 (match spec),
|
||||
5d1913e7 (ocaml bootstrap), f63b2147 (plan tick). JS already current.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7 — Bitwise operations
|
||||
|
||||
Completely absent today. Needed by: Forth (core), APL (array masks), Erlang (bitmatch),
|
||||
JS (typed arrays, bitfields), Common Lisp (`logand`/`logior`/`logxor`/`lognot`/`ash`).
|
||||
|
||||
Primitives to add:
|
||||
- `bitwise-and` `a` `b` → integer
|
||||
- `bitwise-or` `a` `b` → integer
|
||||
- `bitwise-xor` `a` `b` → integer
|
||||
- `bitwise-not` `a` → integer
|
||||
- `arithmetic-shift` `a` `count` → integer (left if count > 0, right if count < 0)
|
||||
- `bit-count` `a` → number of set bits (popcount)
|
||||
- `integer-length` `a` → number of bits needed to represent a
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add entries to `spec/primitives.sx` with type signatures.
|
||||
stdlib.bitwise module with 7 entries appended to spec/primitives.sx.
|
||||
- [x] OCaml: implement in `hosts/ocaml/sx_primitives.ml` using OCaml `land`/`lor`/`lxor`/`lnot`/`lsl`/`asr`.
|
||||
land/lor/lxor/lnot/lsl/asr in sx_primitives.ml. bit-count: Kernighan loop. integer-length: lsr loop.
|
||||
- [x] JS bootstrapper: implement in `hosts/javascript/platform.js` using JS `&`/`|`/`^`/`~`/`<<`/`>>`.
|
||||
stdlib.bitwise module added to PRIMITIVES_JS_MODULES. bit-count: Hamming weight. integer-length: Math.clz32.
|
||||
- [x] Tests: 25+ tests in `spec/tests/test-bitwise.sx` — basic ops, shift left/right, negative numbers, popcount.
|
||||
26 tests, 158 assertions, all pass OCaml+JS.
|
||||
- [x] Commit: `spec: bitwise operations (bitwise-and/or/xor/not, arithmetic-shift, bit-count)`
|
||||
Committed a8a79dc9. Phase 7 complete in single commit.
|
||||
|
||||
---
|
||||
|
||||
## Phase 8 — Multiple values
|
||||
|
||||
R7RS standard. Common Lisp uses them heavily; Haskell tuples map naturally; Erlang
|
||||
multi-return. Without them, every function returning two things encodes it as a list or dict.
|
||||
|
||||
Primitives / forms to add:
|
||||
- `values` `v...` → multiple-value object
|
||||
- `call-with-values` `producer` `consumer` → applies consumer to values from producer
|
||||
- `let-values` `(((a b) expr) ...)` `body` — binding form (special form in evaluator)
|
||||
- `define-values` `(a b ...)` `expr` — top-level multi-value bind
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add `SxValues` type to evaluator; implement `values` + `call-with-values` in
|
||||
`spec/evaluator.sx`; add `let-values` / `define-values` special forms.
|
||||
- [x] OCaml: add `SxValues of value list` to `sx_types.ml`; wire through CEK.
|
||||
- [x] JS bootstrapper: implement values type + forms.
|
||||
- [x] Tests: 25+ tests in `spec/tests/test-values.sx` — basic producer/consumer, let-values
|
||||
destructuring, define-values, interaction with `begin`/`do`.
|
||||
- [x] Commit: `spec: multiple values (values/call-with-values/let-values)`
|
||||
|
||||
---
|
||||
|
||||
## Phase 9 — Promises (lazy evaluation)
|
||||
|
||||
Critical for Haskell — lazy evaluation is so central that without it the Haskell
|
||||
implementation can't be idiomatic. Also useful for lazy lists in Common Lisp and
|
||||
lazy streams in Scheme-style code generally.
|
||||
|
||||
Primitives / forms to add:
|
||||
- `delay` `expr` → promise (special form — expr not evaluated yet)
|
||||
- `force` `p` → evaluate promise, cache result, return it
|
||||
- `make-promise` `v` → already-forced promise wrapping v
|
||||
- `promise?` `v` → bool
|
||||
- `delay-force` `expr` → for iterative lazy sequences (avoids stack growth in lazy streams)
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add `delay` / `delay-force` special forms to `spec/evaluator.sx`; add promise
|
||||
type with mutable forced/value slots; `force` checks if already forced before eval.
|
||||
- [x] OCaml: add `SxPromise of { mutable forced: bool; mutable value: value; thunk: value }`;
|
||||
wire `delay`/`force`/`delay-force` through CEK.
|
||||
- [x] JS bootstrapper: implement promise type + forms.
|
||||
- [x] Tests: 25+ tests in `spec/tests/test-promises.sx` — basic delay/force, memoisation
|
||||
(forced only once), delay-force lazy stream, promise? predicate, make-promise.
|
||||
- [x] Commit: `spec: promises — delay/force/delay-force for lazy evaluation`
|
||||
|
||||
---
|
||||
|
||||
## Phase 10 — Mutable hash tables
|
||||
|
||||
Distinct from SX's immutable dicts. Dict primitives copy on every update — fine for
|
||||
functional code, wrong for table-heavy language implementations. Lua tables, Smalltalk
|
||||
dicts, Erlang process dictionaries, and JS Map all need O(1) mutable associative storage.
|
||||
|
||||
Primitives to add:
|
||||
- `make-hash-table` `[capacity]` → fresh mutable hash table
|
||||
- `hash-table?` `v` → bool
|
||||
- `hash-table-set!` `ht` `key` `val` → mutate in place
|
||||
- `hash-table-ref` `ht` `key` `[default]` → value or default/error
|
||||
- `hash-table-delete!` `ht` `key` → remove entry
|
||||
- `hash-table-size` `ht` → integer
|
||||
- `hash-table-keys` `ht` → list of keys
|
||||
- `hash-table-values` `ht` → list of values
|
||||
- `hash-table->alist` `ht` → list of (key . value) pairs
|
||||
- `hash-table-for-each` `ht` `fn` → iterate (fn key val) for side effects
|
||||
- `hash-table-merge!` `dst` `src` → merge src into dst in place
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add entries to `spec/primitives.sx`.
|
||||
stdlib.hash-table module with 11 define-primitive entries appended to spec/primitives.sx.
|
||||
- [x] OCaml: add `HashTable of (value, value) Hashtbl.t` to `sx_types.ml`; implement
|
||||
all primitives in `hosts/ocaml/sx_primitives.ml`.
|
||||
HashTable variant in sx_types.ml; type_of/inspect cases added; 11 primitives in sx_primitives.ml;
|
||||
fixed _cek_call_ref reference for hash-table-for-each. 4385/1080 (+28).
|
||||
- [x] JS bootstrapper: implement using JS `Map` in `hosts/javascript/platform.js`.
|
||||
SxHashTable class with Map; _hash_table marker; dict?/type-of exclusion; apply() for for-each.
|
||||
2137/2500 (+4 vs phase-9 baseline).
|
||||
- [x] Tests: 30+ tests in `spec/tests/test-hash-table.sx` — set/ref/delete, size, iteration,
|
||||
default on missing key, merge, keys/values lists.
|
||||
28 tests; all pass OCaml+JS. Used empty? not assert= for empty-list comparisons.
|
||||
- [x] Commit: `spec: mutable hash tables (make-hash-table/ref/set!/delete!/etc)`
|
||||
Committed 133bdf52. Phase 10 complete.
|
||||
|
||||
---
|
||||
|
||||
## Phase 11 — Sequence protocol
|
||||
|
||||
Unified iteration over lists and vectors without conversion. Currently `map`/`filter`/
|
||||
`for-each` only work on lists — you must `vector->list` first, which defeats the purpose
|
||||
of vectors. A sequence protocol makes all collection operations polymorphic.
|
||||
|
||||
Approach: extend existing `map`/`filter`/`reduce`/`for-each`/`some`/`every?` to dispatch
|
||||
on type (list → existing path, vector → index loop, string → char iteration). Add:
|
||||
- `in-range` `start` `[end]` `[step]` → lazy range sequence (works with `for-each`/`map`)
|
||||
- `sequence->list` `s` → coerce any sequence to list
|
||||
- `sequence->vector` `s` → coerce any sequence to vector
|
||||
- `sequence-length` `s` → length of any sequence
|
||||
- `sequence-ref` `s` `i` → element by index (lists and vectors)
|
||||
- `sequence-append` `s1` `s2` → concatenate two same-type sequences
|
||||
|
||||
Steps:
|
||||
- [x] Spec: extend `map`/`filter`/`reduce`/`for-each`/`some`/`every?` in `spec/evaluator.sx`
|
||||
to type-dispatch; add `in-range` lazy sequence type + helpers.
|
||||
- [x] OCaml: update HO form dispatch; add `SxRange` or use lazy list; implement `sequence-*`
|
||||
primitives.
|
||||
seq_to_list helper before let-rec block; ho_setup_dispatch wraps all 7 coll bindings;
|
||||
seq-to-list/sequence-to-list/vector/length/ref/append/in-range in sx_primitives.ml.
|
||||
4385/1080 (all failures pre-existing hs-*/regex; 0 regressions).
|
||||
- [x] JS bootstrapper: update.
|
||||
Already done in Spec step (da4b526a) — sx-browser.js rebuilt with seqToList/sequenceToList/
|
||||
sequenceToVector/sequenceLength/sequenceRef/sequenceAppend/inRange. 2137/2500 JS tests pass.
|
||||
- [x] Tests: 30+ tests in `spec/tests/test-sequences.sx` — map over vector, filter over
|
||||
range, for-each over string chars, sequence-append, sequence->list/vector coercions.
|
||||
45 tests all passing: JS 2185/2498 (+48), OCaml 4424/1087 (+39). Fixed: vector? rename
|
||||
(isVector), vectorLength/vectorRef/reverse aliases, in-range letrec→build-range,
|
||||
sequence-length nil=0, assert-equal for list comparisons. Committed 0fe00bf7.
|
||||
- [x] Commit: `spec: sequence protocol — polymorphic map/filter/for-each over list/vector/range`
|
||||
Work landed across da4b526a (Spec), 7286629c (OCaml), 06a3eee1 (JS bootstrap), 0fe00bf7 (Tests).
|
||||
|
||||
---
|
||||
|
||||
## Phase 12 — gensym + symbol interning
|
||||
|
||||
Unique symbol generation. Tiny to implement; broadly needed: Prolog uses it for fresh
|
||||
variable names, Common Lisp uses it constantly in macros, any hygienic macro system needs
|
||||
it, and Smalltalk uses it for anonymous class/method naming.
|
||||
|
||||
Primitives to add:
|
||||
- `gensym` `[prefix]` → unique symbol, e.g. `g42`, `var-17`. Counter-based, monotonically increasing.
|
||||
- `symbol-interned?` `s` → bool — whether the symbol is in the global intern table
|
||||
- `intern` `str` → symbol — intern a string as a symbol (string->symbol already exists; this is
|
||||
the explicit interning operation for languages that distinguish interned vs uninterned)
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add `gensym` counter to evaluator state; implement in `spec/evaluator.sx`.
|
||||
`string->symbol` already exists — `gensym` is just a counter-suffixed variant.
|
||||
Added *gensym-counter*/gensym/string->symbol/symbol->string/intern/symbol-interned? to
|
||||
evaluator.sx. Added string->symbol/symbol->string transpiler renames + platform.py aliases.
|
||||
JS 2186/+1. OCaml builds. Committed edf4e525.
|
||||
- [x] OCaml: add global gensym counter; implement primitives.
|
||||
gensym_counter ref + gensym/string->symbol/symbol->string/intern/symbol-interned? in sx_primitives.ml.
|
||||
Also fixed ListRef case in seq_to_list (both sx_ref.ml + sx_primitives.ml). 4431/1080 (was 4385/1080).
|
||||
- [x] JS bootstrapper: implement.
|
||||
Already done in Spec step. JS 2186/2497, all sequence tests pass.
|
||||
- [x] Tests: 15+ tests in `spec/tests/test-gensym.sx` — uniqueness, prefix, symbol?, string->symbol round-trip.
|
||||
19 tests. OCaml 4450/1080, JS 2205/2497, zero regressions.
|
||||
- [x] Commit: `spec: gensym + symbol interning` — 0862a614
|
||||
|
||||
---
|
||||
|
||||
## Phase 13 — Character type
|
||||
|
||||
Common Lisp and Haskell have a distinct `Char` type that is not a string. Without it both
|
||||
implementations are approximations — CL's `#\a` literal and Haskell's `'a'` both need a
|
||||
real char value, not a length-1 string.
|
||||
|
||||
Primitives to add:
|
||||
- `char?` `v` → bool
|
||||
- `char->integer` `c` → Unicode codepoint integer
|
||||
- `integer->char` `n` → char
|
||||
- `char=?` `char<?` `char>?` `char<=?` `char>=?` → comparators
|
||||
- `char-ci=?` `char-ci<?` etc. → case-insensitive comparators
|
||||
- `char-alphabetic?` `char-numeric?` `char-whitespace?` → predicates
|
||||
- `char-upper-case?` `char-lower-case?` → predicates
|
||||
- `char-upcase` `char-downcase` → char → char
|
||||
- `string->list` extended to return chars (not length-1 strings)
|
||||
- `list->string` accepting chars
|
||||
|
||||
Also: `#\a` reader syntax for char literals (parser addition).
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add `SxChar` type to evaluator; add char literal syntax `#\a`/`#\space`/`#\newline`
|
||||
to `spec/parser.sx`; implement all predicates + comparators.
|
||||
- [x] OCaml: add `SxChar of char` to `sx_types.ml`; implement primitives.
|
||||
- [x] JS bootstrapper: implement char type wrapping a codepoint integer.
|
||||
- [x] Tests: 30+ tests in `spec/tests/test-chars.sx` — literals, char->integer round-trip,
|
||||
comparators, predicates, upcase/downcase, string<->list with chars.
|
||||
- [x] Commit: `spec: character type (char? char->integer #\\a literals + predicates)`
|
||||
|
||||
---
|
||||
|
||||
## Phase 14 — String ports
|
||||
|
||||
Needed for any language with a reader protocol: Common Lisp's `read`, Prolog's term parser,
|
||||
Smalltalk's `printString`. Without string ports these all do their own character walking
|
||||
on raw strings rather than treating a string as an I/O stream.
|
||||
|
||||
Primitives to add:
|
||||
- `open-input-string` `str` → input port
|
||||
- `open-output-string` → output port
|
||||
- `get-output-string` `port` → string (flush output port to string)
|
||||
- `input-port?` `output-port?` `port?` → predicates
|
||||
- `read-char` `[port]` → char or eof-object
|
||||
- `peek-char` `[port]` → char or eof-object (non-consuming)
|
||||
- `read-line` `[port]` → string or eof-object
|
||||
- `write-char` `char` `[port]` → void
|
||||
- `write-string` `str` `[port]` → void
|
||||
- `eof-object` → the eof sentinel
|
||||
- `eof-object?` `v` → bool
|
||||
- `close-port` `port` → void
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add port type + eof-object to evaluator; implement all primitives.
|
||||
Ports are mutable objects with a position cursor (input) or accumulation buffer (output).
|
||||
- [x] OCaml: add `SxPort` variant covering string-input-port and string-output-port;
|
||||
Buffer.t for output, string+offset for input.
|
||||
- [x] JS bootstrapper: implement port type.
|
||||
- [x] Tests: 25+ tests in `spec/tests/test-ports.sx` — open/read/peek/eof, output accumulation,
|
||||
read-line, write-char, close.
|
||||
- [x] Commit: `spec: string ports (open-input-string/open-output-string/read-char/etc)` — 3d8937d7
|
||||
|
||||
---
|
||||
|
||||
## Phase 15 — Math completeness
|
||||
|
||||
Filling specific gaps that multiple language implementations need.
|
||||
|
||||
### 15a — modulo / remainder / quotient distinction
|
||||
They differ on negative numbers — critical for Erlang `rem`, Haskell `mod`/`rem`, CL `mod`/`rem`:
|
||||
- `quotient` `a` `b` → truncate toward zero (same sign as dividend)
|
||||
- `remainder` `a` `b` → sign follows dividend (truncation division)
|
||||
- `modulo` `a` `b` → sign follows divisor (floor division) — R7RS
|
||||
|
||||
### 15b — Trigonometry and transcendentals
|
||||
Lua, Haskell, Erlang, CL all need: `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `exp`,
|
||||
`log`, `sqrt`, `expt`. Check which are already present; add missing ones.
|
||||
|
||||
### 15c — GCD / LCM
|
||||
`gcd` `a` `b` → greatest common divisor; `lcm` `a` `b` → least common multiple.
|
||||
Needed by Haskell `Rational`, CL, and any language doing fraction arithmetic.
|
||||
|
||||
### 15d — Radix number parsing / formatting
|
||||
`(number->string n radix)` → e.g. `(number->string 255 16)` → `"ff"`.
|
||||
`(string->number s radix)` → e.g. `(string->number "ff" 16)` → `255`.
|
||||
Needed by: Common Lisp, Smalltalk, Erlang integer formatting.
|
||||
|
||||
Steps:
|
||||
- [x] Audit which trig / math functions are already in `spec/primitives.sx`; note gaps.
|
||||
- [x] Spec + OCaml + JS: implement missing trig (`sin`/`cos`/`tan`/`asin`/`acos`/`atan`/`exp`/`log`).
|
||||
- [x] Spec + OCaml + JS: `quotient`/`remainder`/`modulo` with correct negative semantics.
|
||||
- [x] Spec + OCaml + JS: `gcd`/`lcm`.
|
||||
- [x] Spec + OCaml + JS: radix variants of `number->string`/`string->number`.
|
||||
- [x] Tests: 40+ tests in `spec/tests/test-math.sx`.
|
||||
- [x] Commit: `spec: math completeness — trig, quotient/remainder/modulo, gcd/lcm, radix`
|
||||
|
||||
---
|
||||
|
||||
## Phase 16 — Rational numbers
|
||||
|
||||
Haskell's `Rational` type and Common Lisp ratios (`1/3`) both need this. Natural extension
|
||||
of the numeric tower (Phase 2) — rationals are the third numeric type alongside int and float.
|
||||
|
||||
Primitives to add:
|
||||
- `make-rational` `numerator` `denominator` → rational (auto-reduced by GCD)
|
||||
- `rational?` `v` → bool
|
||||
- `numerator` `r` → integer
|
||||
- `denominator` `r` → integer
|
||||
- Reader syntax: `1/3` parsed as rational literal
|
||||
- Arithmetic: `(+ 1/3 1/6)` → `1/2`; `(* 1/3 3)` → `1`; mixed int/rational → rational
|
||||
- `exact->inexact` on rational → float; `inexact->exact` on float → rational approximation
|
||||
- `(number->string 1/3)` → `"1/3"`
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add `SxRational` type; add `n/d` reader syntax to `spec/parser.sx`; extend
|
||||
all arithmetic primitives for rational contagion (int op rational → rational, rational
|
||||
op float → float).
|
||||
- [x] OCaml: add `SxRational of int * int` (stored in reduced form); implement all arithmetic.
|
||||
as_number + safe_eq extended for cross-type rational equality (= 2.5 5/2) → true.
|
||||
- [x] JS bootstrapper: implement rational type.
|
||||
JS keeps int/int → float for CSS backward compatibility; SxRational class with _rational marker.
|
||||
- [x] Tests: 30+ tests in `spec/tests/test-rationals.sx` — literals, arithmetic, reduction,
|
||||
mixed numeric tower, exact<->inexact conversion. 62 tests, all pass.
|
||||
- [x] Commit: `spec: rational numbers — 1/3 literals, arithmetic, numeric tower integration`
|
||||
Committed 036022cc. JS: 2232 passed. OCaml: 4532 passed (+11).
|
||||
|
||||
---
|
||||
|
||||
## Phase 17 — read / write / display
|
||||
|
||||
Completes the I/O model. Builds on string ports (Phase 14) and char type (Phase 13).
|
||||
`read` parses any SX value from a port; `write` serializes with quoting (round-trippable);
|
||||
`display` serializes without quoting (human-readable). Common Lisp's `read` macro,
|
||||
Prolog term I/O, and Smalltalk's `printString` all need this.
|
||||
|
||||
Primitives to add:
|
||||
- `read` `[port]` → SX value or eof-object — full SX parser reading from a port
|
||||
- `read-char` already in Phase 14; `read` uses it internally
|
||||
- `write` `val` `[port]` → void — serializes with quotes: `"hello"`, `#\a`, `(1 2 3)`
|
||||
- `display` `val` `[port]` → void — serializes without quotes: `hello`, `a`, `(1 2 3)`
|
||||
- `newline` `[port]` → void — writes `\n`
|
||||
- `write-to-string` `val` → string — convenience: `(write val (open-output-string))`
|
||||
- `display-to-string` `val` → string — convenience
|
||||
|
||||
Steps:
|
||||
- [x] Spec: implement `read` in `spec/evaluator.sx` — wraps the existing parser to read
|
||||
one datum from a port cursor; handles eof gracefully.
|
||||
- [x] Spec: implement `write`/`display`/`newline` — extend the existing serializer for
|
||||
port output; `write` quotes strings + uses `#\` for chars, `display` does not.
|
||||
- [x] OCaml: wire `read` through port type; implement `write`/`display` output path.
|
||||
- [x] JS bootstrapper: implement.
|
||||
- [x] Tests: 25+ tests in `spec/tests/test-read-write.sx` — read string literal, read list,
|
||||
read eof, write round-trip, display vs write quoting, newline, write-to-string.
|
||||
- [x] Commit: `spec: read/write/display — S-expression reader/writer on ports`
|
||||
|
||||
---
|
||||
|
||||
## Phase 18 — Sets
|
||||
|
||||
O(1) membership testing. Distinct from hash tables (unkeyed) and lists (O(n)).
|
||||
Erlang has sets as a stdlib staple, Haskell `Data.Set`, APL uses set operations
|
||||
constantly, Common Lisp has `union`/`intersection` on lists but a native set is O(1).
|
||||
|
||||
Primitives to add:
|
||||
- `make-set` `[list]` → fresh set, optionally seeded from list
|
||||
- `set?` `v` → bool
|
||||
- `set-add!` `s` `val` → void
|
||||
- `set-member?` `s` `val` → bool
|
||||
- `set-remove!` `s` `val` → void
|
||||
- `set-size` `s` → integer
|
||||
- `set->list` `s` → list (unspecified order)
|
||||
- `list->set` `lst` → set
|
||||
- `set-union` `s1` `s2` → new set
|
||||
- `set-intersection` `s1` `s2` → new set
|
||||
- `set-difference` `s1` `s2` → new set (elements in s1 not in s2)
|
||||
- `set-for-each` `s` `fn` → iterate for side effects
|
||||
- `set-map` `s` `fn` → new set of mapped values
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add entries to `spec/primitives.sx`.
|
||||
- [x] OCaml: implement using `Hashtbl.t` with unit values (or a proper `Set` functor
|
||||
with a comparison function); add `SxSet` to `sx_types.ml`.
|
||||
- [x] JS bootstrapper: implement using JS `Set`.
|
||||
- [x] Tests: 30+ tests in `spec/tests/test-sets.sx` — add/member/remove, union/intersection/
|
||||
difference, list conversion, for-each, size.
|
||||
- [x] Commit: `spec: sets (make-set/set-add!/set-member?/union/intersection/etc)`
|
||||
|
||||
---
|
||||
|
||||
## Phase 19 — Regular expressions as primitives
|
||||
|
||||
`lib/js/regex.sx` is a pure-SX regex engine already written. Promoting it to a primitive
|
||||
gives every language free regex without reinventing: Lua patterns, Tcl `regexp`, Ruby regex,
|
||||
JS regex, Erlang `re` module. Mostly a wiring job — the implementation exists.
|
||||
|
||||
Primitives to add:
|
||||
- `make-regexp` `pattern` `[flags]` → regexp object (`flags`: `"i"` case-insensitive, `"g"` global, `"m"` multiline)
|
||||
- `regexp?` `v` → bool
|
||||
- `regexp-match` `re` `str` → match dict `{:match "..." :start N :end N :groups (...)}` or nil
|
||||
- `regexp-match-all` `re` `str` → list of match dicts
|
||||
- `regexp-replace` `re` `str` `replacement` → string with first match replaced
|
||||
- `regexp-replace-all` `re` `str` `replacement` → string with all matches replaced
|
||||
- `regexp-split` `re` `str` → list of strings (split on matches)
|
||||
- Reader syntax: `#/pattern/flags` for regexp literals (parser addition)
|
||||
|
||||
Steps:
|
||||
- [x] Audit `lib/js/regex.sx` — understand the API it already exposes; map to the
|
||||
primitive API above.
|
||||
- [x] Spec: add `SxRegexp` type to evaluator; add `#/pattern/flags` literal syntax to
|
||||
`spec/parser.sx`; wire `lib/js/regex.sx` engine as the implementation.
|
||||
- [x] OCaml: implement using OCaml `Re` library (or `Str`); add `SxRegexp` to types.
|
||||
- [x] JS bootstrapper: use native JS `RegExp`; wrap in the primitive API.
|
||||
- [x] Tests: 30+ tests in `spec/tests/test-regexp.sx` — basic match, groups, replace,
|
||||
replace-all, split, flags (case-insensitive), no-match nil return.
|
||||
- [x] Commit: `spec: regular expressions (make-regexp/regexp-match/regexp-replace + #/pat/ literals)`
|
||||
|
||||
---
|
||||
|
||||
## Phase 20 — Bytevectors
|
||||
|
||||
R7RS standard. Needed for WebSocket binary frames (E36), binary protocol parsing, and
|
||||
efficient string encoding. Also the foundation for proper Unicode: `string->utf8` /
|
||||
`utf8->string` require a byte array type.
|
||||
|
||||
Primitives to add:
|
||||
- `make-bytevector` `n` `[fill]` → bytevector of n bytes (fill defaults to 0)
|
||||
- `bytevector?` `v` → bool
|
||||
- `bytevector-length` `bv` → integer
|
||||
- `bytevector-u8-ref` `bv` `i` → byte 0–255
|
||||
- `bytevector-u8-set!` `bv` `i` `byte` → void
|
||||
- `bytevector-copy` `bv` `[start]` `[end]` → fresh copy
|
||||
- `bytevector-copy!` `dst` `at` `src` `[start]` `[end]` → in-place copy
|
||||
- `bytevector-append` `bv...` → concatenated bytevector
|
||||
- `utf8->string` `bv` `[start]` `[end]` → string decoded as UTF-8
|
||||
- `string->utf8` `str` `[start]` `[end]` → bytevector UTF-8 encoded
|
||||
- `bytevector->list` / `list->bytevector` → conversion
|
||||
|
||||
Steps:
|
||||
- [x] Spec: add `SxBytevector` type; implement all primitives in `spec/evaluator.sx` / `spec/primitives.sx`.
|
||||
- [x] OCaml: add `SxBytevector of bytes` to `sx_types.ml`; implement primitives using
|
||||
OCaml `Bytes`.
|
||||
- [x] JS bootstrapper: implement using `Uint8Array`.
|
||||
- [x] Tests: 30+ tests in `spec/tests/test-bytevectors.sx` — construction, ref/set, copy,
|
||||
append, utf8 round-trip, slice.
|
||||
- [x] Commit: `spec: bytevectors (make-bytevector/u8-ref/u8-set!/utf8->string/etc)`
|
||||
|
||||
---
|
||||
|
||||
## Phase 21 — format
|
||||
|
||||
CL-style string formatting beyond `str`. `(format "Hello ~a, age ~d" name age)`.
|
||||
Haskell `printf`, Erlang `io:format`, CL `format`, and general string templating all use this idiom.
|
||||
|
||||
Directives:
|
||||
- `~a` — display (no quotes)
|
||||
- `~s` — write (with quotes)
|
||||
- `~d` — decimal integer
|
||||
- `~x` — hexadecimal integer
|
||||
- `~o` — octal integer
|
||||
- `~b` — binary integer
|
||||
- `~f` — fixed-point float
|
||||
- `~e` — scientific notation float
|
||||
- `~%` — newline
|
||||
- `~&` — fresh line (newline only if not already at start of line)
|
||||
- `~~` — literal tilde
|
||||
- `~t` — tab
|
||||
|
||||
Signature: `(format template arg...)` → string.
|
||||
Optional: `(format port template arg...)` — write to port directly.
|
||||
|
||||
Steps:
|
||||
- [ ] Spec: implement `format` as a pure SX function in `spec/primitives.sx` — parses
|
||||
`~X` directives, dispatches to `display`/`write`/`number->string` as appropriate.
|
||||
Pure SX: no host calls needed. Self-hosting — uses string-buffer (Phase 5) internally.
|
||||
- [ ] OCaml: expose as a primitive (or let it run as SX through the evaluator).
|
||||
- [ ] JS bootstrapper: same.
|
||||
- [ ] Tests: 25+ tests in `spec/tests/test-format.sx` — each directive, multiple args,
|
||||
nested format, port variant, `~~` escape.
|
||||
- [ ] Commit: `spec: format — CL-style string formatting (~a ~s ~d ~x ~% etc)`
|
||||
|
||||
---
|
||||
|
||||
## Phase 22 — Language sweep
|
||||
|
||||
Replace workarounds with primitives. One language per fire (or per sub-item for big ones).
|
||||
Start with blank slates (CL, APL, Ruby, Tcl) — they haven't committed to workarounds yet.
|
||||
|
||||
**Scope per language:** only `lib/<lang>/**`. Don't touch spec or other languages.
|
||||
Brief each language's loop agent (or do inline) after rebasing their branch onto architecture.
|
||||
|
||||
- [ ] Restart CL/APL/Ruby/Tcl loops with updated briefing pointing to new primitives.
|
||||
Add a note to each `plans/<lang>-on-sx.md` under a `## SX primitive baseline` section:
|
||||
"Use vectors for arrays; numeric tower + rationals for numbers; ADTs for tagged data;
|
||||
coroutines for fibers; string-buffer for mutable string building; bitwise ops for bit
|
||||
manipulation; multiple values for multi-return; promises for lazy evaluation; hash tables
|
||||
for mutable associative storage; sets for O(1) membership; sequence protocol for
|
||||
polymorphic iteration; gensym for unique symbols; char type for characters; string ports
|
||||
+ read/write for reader protocols; regexp for pattern matching; bytevectors for binary
|
||||
data; format for string templating."
|
||||
|
||||
- [ ] Common Lisp: char type (`#\a`); string ports + `read`/`write` for reader/printer;
|
||||
gensym for macros; rational numbers for CL ratios; multiple values; sets for CL set ops;
|
||||
`modulo`/`remainder`/`quotient`; radix formatting; `format` for `cl:format`.
|
||||
|
||||
- [ ] Lua: vectors for arrays; hash tables for Lua tables; `delay`/`force` for lazy iterators;
|
||||
regexp for Lua pattern matching; trig from math completeness; bytevectors for binary I/O.
|
||||
|
||||
- [ ] Erlang: numeric tower for float/int; bitwise ops for bitmatch; multiple values for
|
||||
multi-return; sets for Erlang sets; `remainder` for `rem`; regexp for `re` module.
|
||||
|
||||
- [ ] Haskell: numeric tower for `Num`/`Integral`/`Fractional`; promises for lazy evaluation
|
||||
(critical); multiple values for tuples; rational numbers for `Rational`; char type for
|
||||
`Char`; `gcd`/`lcm`; sets for `Data.Set`; `read`/`write` for `Show`/`Read` instances.
|
||||
|
||||
- [ ] JS: vectors for Array; hash tables for `Map`; sets for `Set`; bitwise ops for typed
|
||||
arrays; regexp for JS regex; bytevectors for `Uint8Array`; radix formatting.
|
||||
|
||||
- [ ] Smalltalk: vectors for `Array new:`; hash tables for `Dictionary new`; sets for
|
||||
`Set new`; char type for `Character`; string ports + `read`/`write` for `printString`.
|
||||
|
||||
- [ ] APL: vectors as core array type; bitwise ops for array masks; sets for APL set ops;
|
||||
sequence protocol for rank-polymorphic operations; format for APL output formatting.
|
||||
|
||||
- [ ] Ruby: coroutines for fibers; hash tables for `Hash`; sets for `Set`; regexp for
|
||||
Ruby regex; string ports for `StringIO`; bytevectors for `String` binary encoding.
|
||||
|
||||
- [ ] Tcl: string ports for Tcl channel abstraction; string-buffer for `append`; coroutines
|
||||
for Tcl coroutines; regexp for Tcl `regexp`; format for Tcl `format`.
|
||||
|
||||
- [ ] Forth: bitwise ops (core); string-buffer for word-definition accumulation; bytevectors
|
||||
for Forth's raw memory model.
|
||||
|
||||
---
|
||||
|
||||
## Ground rules
|
||||
|
||||
- Work on the `architecture` branch in `/root/rose-ash` (main worktree).
|
||||
- Use sx-tree MCP for all `.sx` file edits. Never use raw Edit/Write/Read on `.sx` files.
|
||||
- Commit after each concrete unit of work. Never leave the branch broken.
|
||||
- Never push to `main` — only push to `origin/architecture`.
|
||||
- Update this checklist every fire: tick `[x]` done, add inline notes on blockers.
|
||||
|
||||
---
|
||||
|
||||
## Progress log
|
||||
|
||||
_Newest first._
|
||||
|
||||
- 2026-04-26: Phase 7 complete — bitwise-and/or/xor/not + arithmetic-shift + bit-count + integer-length. OCaml: land/lor/lxor/lnot/lsl/asr + Kernighan popcount + lsr loop for integer-length. JS: bitwise ops + Hamming weight + Math.clz32. 26 tests, 158 assertions, all pass. a8a79dc9.
|
||||
- 2026-04-26: Phase 6 complete — JS+Tests+Commit all ticked. JS needed no changes (spec-level forms). 40/40 ADT tests pass JS. 2032/2500 JS total (+67 vs phase-4). Phase 6 fully landed: 6c872107+0dc7e159+5d1913e7. Phase 7 (bitwise) next.
|
||||
- 2026-04-26: Phase 6 OCaml done — Dict-based ADT (no native SxAdt type needed); hand-written sf_define_type in bootstrap.py FIXUPS (skipped from transpile — &rest params + empty-dict {} literals); registered via register_special_form; step_limit/step_count added to PREAMBLE. 172 assertions pass (test-adt). Full suite 4280/1080 (was 4243/1117, +37). Committed 5d1913e7.
|
||||
- 2026-04-26: Phase 6 Spec match done — ADT case added to match-pattern in spec/evaluator.sx: checks (list? pattern)+(symbol? first)+(dict? value)+(get value :_adt), then matches :_ctor+arity and recursively binds field patterns. No-clause error now uses make-cek-value+raise-eval-frame so guard can catch it. 20 new match tests pass; 40/40 total ADT tests green. Zero regressions.
|
||||
- 2026-04-26: Phase 6 Spec define-type done — sf-define-type registered via register-special-form! in spec/evaluator.sx; AdtValue as {:_adt true :_type "..." :_ctor "..." :_fields (list ...)}; ctor fns + arity checking + Name?/Ctor? predicates + Ctor-field accessors; *adt-registry* dict populated per define-type call. 20/20 JS tests pass in spec/tests/test-adt.sx. OCaml define-type is next task.
|
||||
- 2026-04-26: Phase 6 Design done — plans/designs/sx-adt.md written. Covers define-type/match syntax, AdtValue CEK runtime, stepSfDefineType+MatchFrame dispatch, exhaustiveness warnings, recursive types, nested patterns, wildcard _. 3-phase impl plan. Next fire: Spec implement define-type.
|
||||
- 2026-04-26: Phase 5 complete — string buffer fully landed (d98b5fa2). 17 tests, 17/17 OCaml+JS. Phase 6 (ADTs) next.
|
||||
- 2026-04-26: Phase 5 Spec+OCaml+JS step done — StringBuffer of Buffer.t in sx_types.ml; make-string-buffer/append!/->string/length/string-buffer? in sx_primitives.ml; SxStringBuffer with _string_buffer marker + typeOf/dict? fixes in platform.py; JS rebuilt. 17/17 tests OCaml+JS.
|
||||
- 2026-04-26: Phase 4 complete — coroutine primitive fully landed (4 commits: spec library + OCaml verified + JS pre-load + 27 tests). Phase 5 (string buffer) next.
|
||||
- 2026-04-26: Phase 4 Tests step done — 27 tests total (10 new: state field inspection, yield-from-helper, initial-arg-ignored, mutable-closure, complex-values, round-robin, factory-no-state, non-coroutine-error). 27/27 OCaml+JS.
|
||||
- 2026-04-26: Phase 4 JS step done — all CEK primitives already in sx-browser.js; fix was pre-loading spec/coroutines.sx+spec/signals.sx in run_tests.js so (import (sx coroutines)) resolves synchronously. 17/17 coroutine tests pass JS. 1965/2500 total (+25), zero new failures.
|
||||
- 2026-04-26: Phase 4 OCaml step done — no native SxCoroutine type needed; existing cek-step-loop/cek-resume/perform/make-cek-state primitives in run_tests.ml fully support the spec/coroutines.sx library. 284/284 pass (coroutines+vectors+numeric-tower+dynamic-wind), zero regressions.
|
||||
- 2026-04-26: Phase 4 Spec step done — spec/coroutines.sx define-library with make-coroutine/coroutine-resume/coroutine-yield/coroutine?/coroutine-alive?; make-coroutine stub in evaluator.sx; 17/17 coroutine tests pass (OCaml). Key insight: coroutine body must use (define loop (fn...)) + (loop 0) not named let — named let uses cek_call→cek_run which errors on IO suspension.
|
||||
- 2026-05-01: Phase 10 complete — mutable hash tables. HashTable variant in OCaml; JS Map-based SxHashTable. 11 primitives: make-hash-table/hash-table?/set!/ref/delete!/size/keys/values/->alist/for-each/merge!. 28 tests, all pass OCaml+JS. 133bdf52.
|
||||
- 2026-05-01: Phase 9 complete — delay/force/delay-force/make-promise/promise?. Dict-based promise {:_promise :forced :thunk :value}; :_iterative flag for delay-force chain following. 25/25 tests OCaml (4357) and JS (2109). Committed e44cb89a.
|
||||
- 2026-05-01: Phase 8 complete — values/call-with-values/let-values/define-values. Dict marker {:_values true :_list [...]} (no new type). step-sf-define desugars shorthand (define (f x) body) on both hosts. 25/25 tests OCaml+JS. Committed 43cc1d90.
|
||||
- 2026-04-26: Phase 3 complete — OCaml+JS done. CallccContinuation gains winders-depth int; make_callcc_continuation/callcc_continuation_winders_len wired; wind-after/wind-return CekFrame fields fixed (cf_f=after-thunk, cf_extra=winders-len, cf_name=body-result); get_val + transpiler.sx updated. 8/8 dynamic-wind tests pass on OCaml; 235/235 (callcc+guard+do+r7rs) zero regressions. Committed 6602ec8c.
|
||||
- 2026-04-26: Phase 3 Spec+Tests done — dynamic-wind CEK implementation: wind-after/wind-return frames, *winders* stack, kont-unwind-to-handler, wind-escape-to. callcc frame stores winders-len in continuation; callcc-continuation? calls wind-escape-to before escape. 8/8 dynamic-wind tests pass (normal return, raise, call/cc, nested LIFO, guard ordering). 1948/2500 JS (+8). Zero regressions. Committed a9d5a108.
|
||||
- 2026-04-26: Phase 2 complete — Verify+Commit done. OCaml 4874/394, JS 1940/2500 (+60). No regressions. 6 JS-only failures are float≡int platform-inherent. Phase 2 fully landed across 4 commits.
|
||||
- 2026-04-26: Phase 2 JS bootstrapper done — integer?/float?/exact?/inexact? added (Number.isInteger); truncate/remainder/modulo/random-int/exact->inexact/inexact->exact/parse-number added. Fixed sx_server.ml epoch+blob+io-response protocol for Integer type. JS: 1940/2500 (+60). OCaml: 4874/394 baseline. 6 JS tests fail (JS float≡int platform limit). Committed b12a22e6.
|
||||
- 2026-04-26: Phase 2 Spec done — integer?/float? predicates added to spec/primitives.sx; floor/ceil/truncate :returns updated to "integer"; / to "float"; exact->inexact/inexact->exact docs and returns updated; float contagion documented on +/-/*; 4874/394 baseline. Committed 45ec5535.
|
||||
- 2026-04-26: Phase 2 OCaml+Tests done — `Integer of int` / `Number of float` in sx_types.ml; float contagion across all arithmetic; floor/truncate/round → Integer; integer?/float?/exact?/inexact?/exact->inexact/inexact->exact; 92/92 numeric tower tests pass; 4874 total (394 pre-existing unchanged). Committed c70bbdeb.
|
||||
- 2026-04-26: Phase 1 complete — JS step done. Fixed fundamental lambda binding bug (index-of on arrays returned -1 not NIL, making bind-lambda-params mis-fire &rest branch). Added _lastErrorKont_/hostError/try-catch stubs. 42/42 vector tests pass. 1847 std / 2362 full passing (up from 5). Committed.
|
||||
- 2026-04-25: Phase 1 spec step done — all 10 vector primitives in spec/primitives.sx have full :as type annotations, :returns, :doc; make-vector optional fill param added.
|
||||
- 2026-04-25: Phase 1 OCaml step done — bounds-checked vector-ref/set!, vector-copy now accepts optional start/end, spec/primitives.sx doc updated. 10/10 r7rs vector tests pass, 4747 total (394 pre-existing hs-upstream fails unchanged).
|
||||
- 2026-04-25: Phase 0 complete — stopped CL/APL/Ruby/Tcl loops (all 4 idle at shell); confirmed E38 (tokenizer :end/:line) and E39 (WebWorker stub) both have implementation commits.
|
||||
- 2026-05-01: Phase 20 complete — bytevectors. SxBytevector of bytes in OCaml using Bytes; Uint8Array-backed SxBytevector in JS. 12 primitives: make-bytevector, bytevector?, bytevector-length, bytevector-u8-ref, bytevector-u8-set!, bytevector-copy, bytevector-copy!, bytevector-append, utf8->string, string->utf8, bytevector->list, list->bytevector. 32 tests, all pass. JS 2535, OCaml 4725. a3811545.
|
||||
- 2026-05-01: Phase 19 complete — regular expressions. SxRegexp(src,flags,Re.re) in OCaml via Re.Pcre; SxRegexp wrapper around JS RegExp. 9 primitives: make-regexp, regexp?, regexp-source, regexp-flags, regexp-match, regexp-match-all, regexp-replace, regexp-replace-all, regexp-split. Match dicts with :match/:start/:end/:groups. 32 tests, all pass. JS 2503, OCaml 4693. d8d5588e.
|
||||
- 2026-05-01: Phase 18 complete — sets. SxSet as (string,value) Hashtbl keyed by inspect(val) in OCaml; Map keyed by write-to-string in JS. 13 primitives: make-set, set?, set-add!, set-member?, set-remove!, set-size, set->list, list->set, set-union, set-intersection, set-difference, set-for-each, set-map. 33 tests, all pass. JS 2469, OCaml 4659. 3b0ac67a.
|
||||
- 2026-05-01: Phase 17 complete — read/write/display. OCaml: sx_write_val/sx_display_val helpers; read via Sx_parser.read_value with #t/#f and N/D rational support added to parser; postprocess ()→Nil. JS: sxReadNormalize (#t/#f→true/false), sxReadConvert (()→NIL), sxEq list equality, sxWriteVal symbol/keyword name fix (v.name not v._sym), readerMacroGet registry. 42 tests (test-read-write.sx), all pass both hosts. JS 2436, OCaml 4626. 7d329f02.
|
||||
- 2026-05-01: Phase 16 complete — rational numbers. SxRational type in OCaml (Rational of int*int, reduced, denom>0) and JS (SxRational class, _rational marker). n/d reader in spec/parser.sx. Arithmetic contagion: int op rational → rational, rational op float → float. JS keeps int/int → float for CSS compat. OCaml as_number+safe_eq extended for cross-type rational equality. 62 tests in test-rationals.sx, all pass. JS 2232, OCaml 4532 (+11). 036022cc.
|
||||
- 2026-05-01: Phase 15 complete — math completeness. stdlib.math module: sin/cos/tan/asin/acos/atan(1-2 args)/exp/log/expt/quotient/gcd/lcm/number->string(radix)/string->number(radix). OCaml atan updated for optional 2nd arg. Strict radix parsing in JS string->number. 44 tests in test-math.sx, all pass. JS 2311/4801, OCaml 4547/5629. be2b11ac.
|
||||
- 2026-05-01: Phase 14 OCaml done — Eof + Port{PortInput/PortOutput} in sx_types.ml; 15 port primitives in sx_primitives.ml; raw_serialize updated; 4532/4532 (+39, zero regressions). 8ba0a33f.
|
||||
- 2026-05-01: Phase 14 Spec+JS+Tests+Commit done — port type {_port,_kind,_source/_buffer,_pos,_closed}; eof singleton; 15 primitives in spec/primitives.sx (stdlib.ports) + platform.py; 39/39 tests in test-ports.sx. Committed 3d8937d7. OCaml step next.
|
||||
- 2026-05-01: Phase 13 OCaml done — Char of int in sx_types.ml; #\ reader in sx_parser.ml; all char primitives in sx_primitives.ml; fixed get_val for Integer n list indexing (was Number-only); fixed raw_serialize for Integer/Char. 4493/4493 (+43, zero regressions). b939becd.
|
||||
- 2026-05-01: Phase 13 Spec+JS+Tests+Commit done — SxChar tagged {_char,codepoint}; char? char->integer integer->char char-upcase/downcase; 10 comparators (ordered+ci); 5 predicates; string->list/list->string as platform primitives; #\a #\space #\newline reader syntax in spec/parser.sx; js-char-renames dict in transpiler.sx; 43/43 tests pass JS (2254/4745). Committed 4b600f17. OCaml step next.
|
||||
- 2026-05-01: Phase 12 complete — gensym + symbol interning. gensym_counter/gensym/string->symbol/symbol->string/intern/symbol-interned? in spec + OCaml + JS. Fixed ListRef case in seq_to_list (both hosts). 19 tests, all pass. OCaml 4450/1080, JS 2205/2497. Commits: edf4e525 Spec, 0862a614 OCaml+Tests.
|
||||
- 2026-05-01: Phase 11 complete — sequence protocol done. Commits: da4b526a Spec, 7286629c OCaml, 06a3eee1 JS, 0fe00bf7 Tests. JS 2185/+48, OCaml 4424/+39.
|
||||
- 2026-05-01: Phase 11 Tests done — 45 tests in test-sequences.sx all passing (JS 2185/+48, OCaml 4424/+39). Fixed vector? rename, vectorLength/vectorRef/reverse aliases, in-range letrec→build-range, sequence-length nil, assert-equal for lists. Committed 0fe00bf7.
|
||||
- 2026-05-01: Phase 11 JS bootstrapper step done — confirmed sx-browser.js current (built in Spec step da4b526a); 19 sequence primitive refs in output; 2137/2500 JS tests passing.
|
||||
- 2026-05-01: Phase 11 OCaml step done — seq_to_list helper added before let-rec; ho_setup_dispatch wraps all 7 coll bindings with seq_to_list; seq-to-list/sequence-to-list/to-vector/length/ref/append + in-range primitives in sx_primitives.ml. 4385/4385 baseline unchanged, 0 regressions. Committed 7286629c.
|
||||
- 2026-05-01: Phase 11 Spec step done — seq-to-list coercion helper; ho-setup-dispatch extended with seqToList on all collection args; sequence-to-list/vector/length/ref/append + in-range added to evaluator.sx. Restored 3 accidentally-deleted make-cek-state/value/suspended definitions. Fixed 8 shorthand define forms + added vector->list/list->vector transpiler renames. JS: 2137 passing (+28 vs HEAD baseline of 2109).
|
||||
83
plans/agent-briefings/ruby-loop.md
Normal file
83
plans/agent-briefings/ruby-loop.md
Normal file
@@ -0,0 +1,83 @@
|
||||
# ruby-on-sx loop agent (single agent, queue-driven)
|
||||
|
||||
Role: iterates `plans/ruby-on-sx.md` forever. Fibers via delcc is the headline showcase — `Fiber.new`/`Fiber.yield`/`Fiber.resume` are textbook delimited continuations with sugar, where MRI does it via C-stack swapping. Plus blocks/yield (lexical escape continuations, same shape as Smalltalk's non-local return), method_missing, and singleton classes.
|
||||
|
||||
```
|
||||
description: ruby-on-sx queue loop
|
||||
subagent_type: general-purpose
|
||||
run_in_background: true
|
||||
isolation: worktree
|
||||
```
|
||||
|
||||
## Prompt
|
||||
|
||||
You are the sole background agent working `/root/rose-ash/plans/ruby-on-sx.md`. Isolated worktree, forever, one commit per feature. Never push.
|
||||
|
||||
## Restart baseline — check before iterating
|
||||
|
||||
1. Read `plans/ruby-on-sx.md` — roadmap + Progress log.
|
||||
2. `ls lib/ruby/` — pick up from the most advanced file.
|
||||
3. If `lib/ruby/tests/*.sx` exist, run them. Green before new work.
|
||||
4. If `lib/ruby/scoreboard.md` exists, that's your baseline.
|
||||
|
||||
## The queue
|
||||
|
||||
Phase order per `plans/ruby-on-sx.md`:
|
||||
|
||||
- **Phase 1** — tokenizer + parser. Keywords, identifier sigils (`@` ivar, `@@` cvar, `$` global), strings with interpolation, `%w[]`/`%i[]`, symbols, blocks `{|x| …}` and `do |x| … end`, splats, default args, method def
|
||||
- **Phase 2** — object model + sequential eval. Class table, ancestor-chain dispatch, `super`, singleton classes, `method_missing` fallback, dynamic constant lookup
|
||||
- **Phase 3** — blocks + procs + lambdas. Method captures escape continuation `^k`; `yield` / `return` / `break` / `next` / `redo` semantics; lambda strict arity vs proc lax
|
||||
- **Phase 4** — **THE SHOWCASE**: fibers via delcc. `Fiber.new`/`Fiber.resume`/`Fiber.yield`/`Fiber.transfer`. Classic programs (generator, producer-consumer, tree-walk) green
|
||||
- **Phase 5** — modules + mixins + metaprogramming. `include`/`prepend`/`extend`, `define_method`, `class_eval`/`instance_eval`, `respond_to?`/`respond_to_missing?`, hooks
|
||||
- **Phase 6** — stdlib drive. `Enumerable` mixin, `Comparable`, Array/Hash/Range/String/Integer methods, drive corpus to 200+
|
||||
|
||||
Within a phase, pick the checkbox that unlocks the most tests per effort.
|
||||
|
||||
Every iteration: implement → test → commit → tick `[ ]` → Progress log → next.
|
||||
|
||||
## Ground rules (hard)
|
||||
|
||||
- **Scope:** only `lib/ruby/**` and `plans/ruby-on-sx.md`. Do **not** edit `spec/`, `hosts/`, `shared/`, other `lib/<lang>/` dirs, `lib/stdlib.sx`, or `lib/` root. Ruby primitives go in `lib/ruby/runtime.sx`.
|
||||
- **NEVER call `sx_build`.** 600s watchdog. If sx_server binary broken → Blockers entry, stop.
|
||||
- **Shared-file issues** → plan's Blockers with minimal repro.
|
||||
- **Delimited continuations** are in `lib/callcc.sx` + `spec/evaluator.sx` Step 5. `sx_summarise` spec/evaluator.sx first — 2300+ lines.
|
||||
- **SX files:** `sx-tree` MCP tools ONLY. `sx_validate` after edits.
|
||||
- **Worktree:** commit locally. Never push. Never touch `main`.
|
||||
- **Commit granularity:** one feature per commit.
|
||||
- **Plan file:** update Progress log + tick boxes every commit.
|
||||
|
||||
## Ruby-specific gotchas
|
||||
|
||||
- **Block `return` vs lambda `return`.** Inside a block `{ ... return v }`, `return` invokes the *enclosing method's* escape continuation (non-local return). Inside a lambda `->(){ ... return v }`, `return` returns from the *lambda*. Don't conflate. Implement: blocks bind their `^method-k`; lambdas bind their own `^lambda-k`.
|
||||
- **`break` from inside a block** invokes a different escape — the *iteration loop's* escape — and the loop returns the break-value. `next` is escape from current iteration, returns iteration value. `redo` re-enters current iteration without advancing.
|
||||
- **Proc arity is lax.** `proc { |a, b, c| … }.call(1, 2)` ↦ `c = nil`. Lambda is strict — same call raises ArgumentError. Check arity at call site for lambdas only.
|
||||
- **Block argument unpacking.** `[[1,2],[3,4]].each { |a, b| … }` — single Array arg auto-unpacks for blocks (not lambdas). One arg, one Array → unpack. Frequent footgun.
|
||||
- **Method dispatch chain order:** prepended modules → class methods → included modules → superclass → BasicObject → method_missing. `super` walks from the *defining* class's position, not the receiver class's.
|
||||
- **Singleton classes** are lazily allocated. Looking up the chain for an object passes through its singleton class first, then its actual class. `class << obj; …; end` opens the singleton.
|
||||
- **`method_missing`** — fallback when ancestor walk misses. Receives `(name_symbol, *args, &blk)`. Pair with `respond_to_missing?` for `respond_to?` to also report true. Do **not** swallow NoMethodError silently.
|
||||
- **Ivars are per-object dicts.** Reading an unset ivar yields `nil` and a warning (`-W`). Don't error.
|
||||
- **Constant lookup** is first lexical (Module.nesting), then inheritance (Module.ancestors of the innermost class). Different from method lookup.
|
||||
- **`Object#send`** invokes private and public methods alike; `Object#public_send` skips privates.
|
||||
- **Class reopening.** `class Foo; def bar; …; end; end` plus a later `class Foo; def baz; …; end; end` adds methods to the same class. Class table lookups must be by-name, mutable; methods dict is mutable.
|
||||
- **Fiber semantics.** `Fiber.new { |arg| … }` creates a fiber suspended at entry. First `Fiber.resume(v)` enters with `arg = v`. Inside, `Fiber.yield(w)` returns `w` to the resumer; the next `Fiber.resume(v')` returns `v'` to the yield site. End of block returns final value to last resumer; subsequent `Fiber.resume` raises FiberError.
|
||||
- **`Fiber.transfer`** is symmetric — either side can transfer to the other; no resume/yield asymmetry. Implement on top of the same continuation pair, just don't enforce direction.
|
||||
- **Symbols are interned.** `:foo == :foo` is identity. Use SX symbols.
|
||||
- **Strings are mutable.** `s = "abc"; s << "d"; s == "abcd"`. Hash keys can be strings; hash dups string keys at insertion to be safe (or freeze them).
|
||||
- **Truthiness:** only `false` and `nil` are falsy. `0`, `""`, `[]` are truthy.
|
||||
- **Test corpus:** custom + curated RubySpec slice. Place programs in `lib/ruby/tests/programs/` with `.rb` extension.
|
||||
|
||||
## General gotchas (all loops)
|
||||
|
||||
- SX `do` = R7RS iteration. Use `begin` for multi-expr sequences.
|
||||
- `cond`/`when`/`let` clauses evaluate only the last expr.
|
||||
- `type-of` on user fn returns `"lambda"`.
|
||||
- Shell heredoc `||` gets eaten — escape or use `case`.
|
||||
|
||||
## Style
|
||||
|
||||
- No comments in `.sx` unless non-obvious.
|
||||
- No new planning docs — update `plans/ruby-on-sx.md` inline.
|
||||
- Short, factual commit messages (`ruby: Fiber.yield + Fiber.resume (+8)`).
|
||||
- One feature per iteration. Commit. Log. Next.
|
||||
|
||||
Go. Read the plan; find first `[ ]`; implement.
|
||||
@@ -11,7 +11,7 @@ isolation: worktree
|
||||
|
||||
## Prompt
|
||||
|
||||
You are the sole background agent working `/root/rose-ash/plans/smalltalk-on-sx.md`. Isolated worktree, forever, one commit per feature. Push to `origin/loops/smalltalk` after every commit.
|
||||
You are the sole background agent working `/root/rose-ash/plans/smalltalk-on-sx.md`. Isolated worktree, forever, one commit per feature. Never push.
|
||||
|
||||
## Restart baseline — check before iterating
|
||||
|
||||
@@ -43,7 +43,7 @@ Every iteration: implement → test → commit → tick `[ ]` → Progress log
|
||||
- **Shared-file issues** → plan's Blockers with minimal repro.
|
||||
- **Delimited continuations** are in `lib/callcc.sx` + `spec/evaluator.sx` Step 5. `sx_summarise` spec/evaluator.sx first — 2300+ lines.
|
||||
- **SX files:** `sx-tree` MCP tools ONLY. `sx_validate` after edits.
|
||||
- **Worktree:** commit, then push to `origin/loops/smalltalk`. Never touch `main`.
|
||||
- **Worktree:** commit locally. Never push. Never touch `main`.
|
||||
- **Commit granularity:** one feature per commit.
|
||||
- **Plan file:** update Progress log + tick boxes every commit.
|
||||
|
||||
|
||||
83
plans/agent-briefings/tcl-loop.md
Normal file
83
plans/agent-briefings/tcl-loop.md
Normal file
@@ -0,0 +1,83 @@
|
||||
# tcl-on-sx loop agent (single agent, queue-driven)
|
||||
|
||||
Role: iterates `plans/tcl-on-sx.md` forever. `uplevel`/`upvar` is the headline showcase — Tcl's superpower for defining your own control structures, requiring deep VM cooperation in any normal host but falling out of SX's first-class env-chain. Plus the Dodekalogue (12 rules), command-substitution everywhere, and "everything is a string" homoiconicity.
|
||||
|
||||
```
|
||||
description: tcl-on-sx queue loop
|
||||
subagent_type: general-purpose
|
||||
run_in_background: true
|
||||
isolation: worktree
|
||||
```
|
||||
|
||||
## Prompt
|
||||
|
||||
You are the sole background agent working `/root/rose-ash/plans/tcl-on-sx.md`. Isolated worktree, forever, one commit per feature. Never push.
|
||||
|
||||
## Restart baseline — check before iterating
|
||||
|
||||
1. Read `plans/tcl-on-sx.md` — roadmap + Progress log.
|
||||
2. `ls lib/tcl/` — pick up from the most advanced file.
|
||||
3. If `lib/tcl/tests/*.sx` exist, run them. Green before new work.
|
||||
4. If `lib/tcl/scoreboard.md` exists, that's your baseline.
|
||||
|
||||
## The queue
|
||||
|
||||
Phase order per `plans/tcl-on-sx.md`:
|
||||
|
||||
- **Phase 1** — tokenizer + parser. The Dodekalogue (12 rules): word-splitting, command sub `[…]`, var sub `$name`/`${name}`/`$arr(idx)`, double-quote vs brace word, backslash, `;`, `#` comments only at command start, single-pass left-to-right substitution
|
||||
- **Phase 2** — sequential eval + core commands. `set`/`unset`/`incr`/`append`/`lappend`, `puts`/`gets`, `expr` (own mini-language), `if`/`while`/`for`/`foreach`/`switch`, string commands, list commands, dict commands
|
||||
- **Phase 3** — **THE SHOWCASE**: `proc` + `uplevel` + `upvar`. Frame stack with proc-call push/pop; `uplevel #N script` evaluates in caller's frame; `upvar` aliases names across frames. Classic programs (for-each-line, assert macro, with-temp-var) green
|
||||
- **Phase 4** — `return -code N`, `catch`, `try`/`trap`/`finally`, `throw`. Control flow as integer codes
|
||||
- **Phase 5** — namespaces + ensembles. `namespace eval`, qualified names `::ns::cmd`, ensembles, `namespace path`
|
||||
- **Phase 6** — coroutines (built on fibers, same delcc as Ruby fibers) + system commands + drive corpus to 150+
|
||||
|
||||
Within a phase, pick the checkbox that unlocks the most tests per effort.
|
||||
|
||||
Every iteration: implement → test → commit → tick `[ ]` → Progress log → next.
|
||||
|
||||
## Ground rules (hard)
|
||||
|
||||
- **Scope:** only `lib/tcl/**` and `plans/tcl-on-sx.md`. Do **not** edit `spec/`, `hosts/`, `shared/`, other `lib/<lang>/` dirs, `lib/stdlib.sx`, or `lib/` root. Tcl primitives go in `lib/tcl/runtime.sx`.
|
||||
- **NEVER call `sx_build`.** 600s watchdog. If sx_server binary broken → Blockers entry, stop.
|
||||
- **Shared-file issues** → plan's Blockers with minimal repro.
|
||||
- **Delimited continuations** are in `lib/callcc.sx` + `spec/evaluator.sx` Step 5. `sx_summarise` spec/evaluator.sx first — 2300+ lines.
|
||||
- **SX files:** `sx-tree` MCP tools ONLY. `sx_validate` after edits.
|
||||
- **Worktree:** commit locally. Never push. Never touch `main`.
|
||||
- **Commit granularity:** one feature per commit.
|
||||
- **Plan file:** update Progress log + tick boxes every commit.
|
||||
|
||||
## Tcl-specific gotchas
|
||||
|
||||
- **Everything is a string.** Internally cache shimmer reps (list, dict, int, double) for performance, but every value must be re-stringifiable. Mutating one rep dirties the cached string and vice versa.
|
||||
- **The Dodekalogue is strict.** Substitution is **one-pass**, **left-to-right**. The result of a substitution is a value, not a script — it does NOT get re-parsed for further substitutions. This is what makes Tcl safe-by-default. Don't accidentally re-parse.
|
||||
- **Brace word `{…}`** is the only way to defer evaluation. No substitution inside, just balanced braces. Used for `if {expr}` body, `proc body`, `expr` arguments.
|
||||
- **Double-quote word `"…"`** is identical to a bare word for substitution purposes — it just allows whitespace in a single word. `\` escapes still apply.
|
||||
- **Comments are only at command position.** `# this is a comment` after a `;` or newline; *not* inside a command. `set x 1 # not a comment` is a 4-arg `set`.
|
||||
- **`expr` has its own grammar** — operator precedence, function calls — and does its own substitution. Brace `expr {$x + 1}` to avoid double-substitution and to enable bytecode caching.
|
||||
- **`if` and `while` re-parse** the condition only if not braced. Always use `if {…}`/`while {…}` form. The unbraced form re-substitutes per iteration.
|
||||
- **`return` from a `proc`** uses control code 2. `break` is 3, `continue` is 4. `error` is 1. `catch` traps any non-zero code; user can return non-zero with `return -code error -errorcode FOO message`.
|
||||
- **`uplevel #0 script`** is global frame. `uplevel 1 script` (or just `uplevel script`) is caller's frame. `uplevel #N` is absolute level N (0=global, 1=top-level proc, 2=proc-called-from-top, …). Negative levels are errors.
|
||||
- **`upvar #N otherVar localVar`** binds `localVar` in the current frame as an *alias* — both names refer to the same storage. Reads and writes go through the alias.
|
||||
- **`info level`** with no arg returns current level number. `info level N` (positive) returns the command list that invoked level N. `info level -N` returns the command list of the level N relative-up.
|
||||
- **Variable names with `(…)`** are array elements: `set arr(foo) 1`. Arrays are not first-class values — you can't `set x $arr`. `array get arr` gives a flat list `{key1 val1 key2 val2 …}`.
|
||||
- **List vs string.** `set l "a b c"` and `set l [list a b c]` look the same when printed but the second has a cached list rep. `lindex` works on both via shimmering. Most user code can't tell the difference.
|
||||
- **`incr x`** errors if x doesn't exist; pre-set with `set x 0` or use `incr x 0` first if you mean "create-or-increment". Or use `dict incr` for dicts.
|
||||
- **Coroutines are fibers.** `coroutine name body` starts a coroutine; calling `name` resumes it; `yield value` from inside suspends and returns `value` to the resumer. Same primitive as Ruby fibers — share the implementation under the hood.
|
||||
- **`switch`** matches first clause whose pattern matches. Default is `default`. Variant matches: glob (default), `-exact`, `-glob`, `-regexp`. Body `-` means "fall through to next clause's body".
|
||||
- **Test corpus:** custom + slice of Tcl's own tests. Place programs in `lib/tcl/tests/programs/` with `.tcl` extension.
|
||||
|
||||
## General gotchas (all loops)
|
||||
|
||||
- SX `do` = R7RS iteration. Use `begin` for multi-expr sequences.
|
||||
- `cond`/`when`/`let` clauses evaluate only the last expr.
|
||||
- `type-of` on user fn returns `"lambda"`.
|
||||
- Shell heredoc `||` gets eaten — escape or use `case`.
|
||||
|
||||
## Style
|
||||
|
||||
- No comments in `.sx` unless non-obvious.
|
||||
- No new planning docs — update `plans/tcl-on-sx.md` inline.
|
||||
- Short, factual commit messages (`tcl: uplevel + upvar (+11)`).
|
||||
- One feature per iteration. Commit. Log. Next.
|
||||
|
||||
Go. Read the plan; find first `[ ]`; implement.
|
||||
115
plans/apl-on-sx.md
Normal file
115
plans/apl-on-sx.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# APL-on-SX: rank-polymorphic primitives + glyph parser
|
||||
|
||||
The headline showcase is **rank polymorphism** — a single primitive (`+`, `⌈`, `⊂`, `⍳`) works uniformly on scalars, vectors, matrices, and higher-rank arrays. ~80 glyph primitives + 6 operators bind together with right-to-left evaluation; the entire language is a high-density combinator algebra. The JIT compiler + primitive table pay off massively here because almost every program is `array → array` pure pipelines.
|
||||
|
||||
End-state goal: Dyalog-flavoured APL subset, dfns + tradfns, classic programs (game-of-life, mandelbrot, prime-sieve, n-queens, conway), 100+ green tests.
|
||||
|
||||
## Scope decisions (defaults — override by editing before we spawn)
|
||||
|
||||
- **Syntax:** Dyalog APL surface, Unicode glyphs. `⎕`-quad system functions for I/O. `∇` tradfn header.
|
||||
- **Conformance:** "Reads like APL, runs like APL." Not byte-compat with Dyalog; we care about right-to-left semantics and rank polymorphism.
|
||||
- **Test corpus:** custom — APL idioms (Roger Hui style), classic programs, plus ~50 pattern tests for primitives.
|
||||
- **Out of scope:** ⎕-namespaces beyond a handful, complex numbers, full TAO ordering, `⎕FX` runtime function definition (use static `∇` only), nested-array-of-functions higher orders, the editor.
|
||||
- **Glyphs:** input via plain Unicode in `.apl` source files. Backtick-prefix shortcuts handled by the user's editor — we don't ship one.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Scope:** only touch `lib/apl/**` and `plans/apl-on-sx.md`. Don't edit `spec/`, `hosts/`, `shared/`, or any other `lib/<lang>/**`. APL primitives go in `lib/apl/runtime.sx`.
|
||||
- **SX files:** use `sx-tree` MCP tools only.
|
||||
- **Commits:** one feature per commit. Keep `## Progress log` updated and tick roadmap boxes.
|
||||
|
||||
## Architecture sketch
|
||||
|
||||
```
|
||||
APL source (Unicode glyphs)
|
||||
│
|
||||
▼
|
||||
lib/apl/tokenizer.sx — glyphs, identifiers, numbers (¯ for negative), strings, strands
|
||||
│
|
||||
▼
|
||||
lib/apl/parser.sx — right-to-left with valence resolution (mon vs dyadic by position)
|
||||
│
|
||||
▼
|
||||
lib/apl/transpile.sx — AST → SX AST (entry: apl-eval-ast)
|
||||
│
|
||||
▼
|
||||
lib/apl/runtime.sx — array model, ~80 primitives, 6 operators, dfns/tradfns
|
||||
```
|
||||
|
||||
Core mapping:
|
||||
- **Array** = SX dict `{:shape (d1 d2 …) :ravel #(v1 v2 …)}`. Scalar is rank-0 (empty shape), vector is rank-1, matrix rank-2, etc. Type uniformity not required (heterogeneous nested arrays via "boxed" elements `⊂x`).
|
||||
- **Rank polymorphism** — every scalar primitive is broadcast: `1 2 3 + 4 5 6` ↦ `5 7 9`; `(2 3⍴⍳6) + 1` ↦ broadcast scalar to matrix.
|
||||
- **Conformability** = matching shapes, or one-side scalar, or rank-1 cycling (deferred — keep strict in v1).
|
||||
- **Valence** = each glyph has a monadic and a dyadic meaning; resolution is purely positional (left-arg present → dyadic).
|
||||
- **Operator** = takes one or two function operands, returns a derived function (`f¨` = `each f`, `f/` = `reduce f`, `f∘g` = `compose`, `f⍨` = `commute`).
|
||||
- **Tradfn** `∇R←L F R; locals` = named function with explicit header.
|
||||
- **Dfn** `{⍺+⍵}` = anonymous, `⍺` = left arg, `⍵` = right arg, `∇` = recurse.
|
||||
|
||||
## Roadmap
|
||||
|
||||
### Phase 1 — tokenizer + parser
|
||||
- [ ] Tokenizer: Unicode glyphs (the full APL set: `+ - × ÷ * ⍟ ⌈ ⌊ | ! ? ○ ~ < ≤ = ≥ > ≠ ∊ ∧ ∨ ⍱ ⍲ , ⍪ ⍴ ⌽ ⊖ ⍉ ↑ ↓ ⊂ ⊃ ⊆ ∪ ∩ ⍳ ⍸ ⌷ ⍋ ⍒ ⊥ ⊤ ⊣ ⊢ ⍎ ⍕ ⍝`), operators (`/ \ ¨ ⍨ ∘ . ⍣ ⍤ ⍥ @`), numbers (`¯` for negative, `1E2`, `1J2` complex deferred), characters (`'a'`, `''` escape), strands (juxtaposition of literals: `1 2 3`), names, comments `⍝ …`
|
||||
- [ ] Parser: right-to-left; classify each token as function, operator, value, or name; resolve valence positionally; dfn `{…}` body, tradfn `∇` header, guards `:`, control words `:If :While :For …` (Dyalog-style)
|
||||
- [ ] Unit tests in `lib/apl/tests/parse.sx`
|
||||
|
||||
### Phase 2 — array model + scalar primitives
|
||||
- [ ] Array constructor: `make-array shape ravel`, `scalar v`, `vector v…`, `enclose`/`disclose`
|
||||
- [ ] Shape arithmetic: `⍴` (shape), `,` (ravel), `≢` (tally / first-axis-length), `≡` (depth)
|
||||
- [ ] Scalar arithmetic primitives broadcast: `+ - × ÷ ⌈ ⌊ * ⍟ | ! ○`
|
||||
- [ ] Scalar comparison primitives: `< ≤ = ≥ > ≠`
|
||||
- [ ] Scalar logical: `~ ∧ ∨ ⍱ ⍲`
|
||||
- [ ] Index generator: `⍳n` (vector 1..n or 0..n-1 depending on `⎕IO`)
|
||||
- [ ] `⎕IO` = 1 default (Dyalog convention)
|
||||
- [ ] 40+ tests in `lib/apl/tests/scalar.sx`
|
||||
|
||||
### Phase 3 — structural primitives + indexing
|
||||
- [ ] Reshape `⍴`, ravel `,`, transpose `⍉` (full + dyadic axis spec)
|
||||
- [ ] Take `↑`, drop `↓`, rotate `⌽` (last axis), `⊖` (first axis)
|
||||
- [ ] Catenate `,` (last axis) and `⍪` (first axis)
|
||||
- [ ] Index `⌷` (squad), bracket-indexing `A[I]` (sugar for `⌷`)
|
||||
- [ ] Grade-up `⍋`, grade-down `⍒`
|
||||
- [ ] Enclose `⊂`, disclose `⊃`, partition (subset deferred)
|
||||
- [ ] Membership `∊`, find `⍳` (dyadic), without `~` (dyadic), unique `∪` (deferred to phase 6)
|
||||
- [ ] 40+ tests in `lib/apl/tests/structural.sx`
|
||||
|
||||
### Phase 4 — operators (THE SHOWCASE)
|
||||
- [ ] Reduce `f/` (last axis), `f⌿` (first axis) — including `∧/`, `∨/`, `+/`, `×/`, `⌈/`, `⌊/`
|
||||
- [ ] Scan `f\`, `f⍀`
|
||||
- [ ] Each `f¨` — applies `f` to each scalar/element
|
||||
- [ ] Outer product `∘.f` — `1 2 3 ∘.× 1 2 3` ↦ multiplication table
|
||||
- [ ] Inner product `f.g` — `+.×` is matrix multiply
|
||||
- [ ] Commute `f⍨` — `f⍨ x` ↔ `x f x`, `x f⍨ y` ↔ `y f x`
|
||||
- [ ] Compose `f∘g` — applies `g` first then `f`
|
||||
- [ ] Power `f⍣n` — apply f n times; `f⍣≡` until fixed point
|
||||
- [ ] Rank `f⍤k` — apply f at sub-rank k
|
||||
- [ ] At `@` — selective replace
|
||||
- [ ] 40+ tests in `lib/apl/tests/operators.sx`
|
||||
|
||||
### Phase 5 — dfns + tradfns + control flow
|
||||
- [ ] Dfn `{…}` with `⍺` (left arg, may be absent → niladic/monadic), `⍵` (right arg), `∇` (recurse), guards `cond:expr`, default left arg `⍺←default`
|
||||
- [ ] Local assignment via `←` (lexical inside dfn)
|
||||
- [ ] Tradfn `∇` header: `R←L F R;l1;l2`, statement-by-statement, branch via `→linenum`
|
||||
- [ ] Dyalog control words: `:If/:Else/:EndIf`, `:While/:EndWhile`, `:For X :In V :EndFor`, `:Select/:Case/:EndSelect`, `:Trap`/`:EndTrap`
|
||||
- [ ] Niladic / monadic / dyadic dispatch (function valence at definition time)
|
||||
- [ ] `lib/apl/conformance.sh` + runner, `scoreboard.json` + `scoreboard.md`
|
||||
|
||||
### Phase 6 — classic programs + drive corpus
|
||||
- [ ] Classic programs in `lib/apl/tests/programs/`:
|
||||
- [ ] `life.apl` — Conway's Game of Life as a one-liner using `⊂` `⊖` `⌽` `+/`
|
||||
- [ ] `mandelbrot.apl` — complex iteration with rank-polymorphic `+ × ⌊` (or real-axis subset)
|
||||
- [ ] `primes.apl` — `(2=+⌿0=A∘.|A)/A←⍳N` sieve
|
||||
- [ ] `n-queens.apl` — backtracking via reduce
|
||||
- [ ] `quicksort.apl` — the classic Roger Hui one-liner
|
||||
- [ ] System functions: `⎕FMT`, `⎕FR` (float repr), `⎕TS` (timestamp), `⎕IO`, `⎕ML` (migration level — fixed at 1), `⎕←` (print)
|
||||
- [ ] Drive corpus to 100+ green
|
||||
- [ ] Idiom corpus — `lib/apl/tests/idioms.sx` covering classic Roger Hui / Phil Last idioms
|
||||
|
||||
## Progress log
|
||||
|
||||
_Newest first._
|
||||
|
||||
- _(none yet)_
|
||||
|
||||
## Blockers
|
||||
|
||||
- _(none yet)_
|
||||
121
plans/common-lisp-on-sx.md
Normal file
121
plans/common-lisp-on-sx.md
Normal file
@@ -0,0 +1,121 @@
|
||||
# Common-Lisp-on-SX: conditions + restarts on delimited continuations
|
||||
|
||||
The headline showcase is the **condition system**. Restarts are *resumable* exceptions — every other Lisp implementation reinvents this on host-stack unwind tricks. On SX restarts are textbook delimited continuations: `signal` walks the handler chain; `invoke-restart` resumes the captured continuation at the restart point. Same delcc primitive that powers Erlang actors, expressed as a different surface.
|
||||
|
||||
End-state goal: ANSI Common Lisp subset with a working condition/restart system, CLOS multimethods (with `:before`/`:after`/`:around`), the LOOP macro, packages, and ~150 hand-written + classic programs.
|
||||
|
||||
## Scope decisions (defaults — override by editing before we spawn)
|
||||
|
||||
- **Syntax:** ANSI Common Lisp surface. Read tables, dispatch macros (`#'`, `#(`, `#\`, `#:`, `#x`, `#b`, `#o`, ratios `1/3`).
|
||||
- **Conformance:** ANSI X3.226 *as a target*, not bug-for-bug SBCL/CCL. "Reads like CL, runs like CL."
|
||||
- **Test corpus:** custom + a curated slice of `ansi-test`. Plus classic programs: condition-system demo, restart-driven debugger, multiple-dispatch geometry, LOOP corpus.
|
||||
- **Out of scope:** compilation to native, FFI, sockets, threads, MOP class redefinition, full pathname/logical-pathname machinery, structures with `:include` deep customization.
|
||||
- **Packages:** simple — `defpackage`/`in-package`/`export`/`use-package`/`:cl`/`:cl-user`. No nicknames, no shadowing-import edge cases.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Scope:** only touch `lib/common-lisp/**` and `plans/common-lisp-on-sx.md`. Don't edit `spec/`, `hosts/`, `shared/`, or any other `lib/<lang>/**`. CL primitives go in `lib/common-lisp/runtime.sx`.
|
||||
- **SX files:** use `sx-tree` MCP tools only.
|
||||
- **Commits:** one feature per commit. Keep `## Progress log` updated and tick roadmap boxes.
|
||||
|
||||
## Architecture sketch
|
||||
|
||||
```
|
||||
Common Lisp source
|
||||
│
|
||||
▼
|
||||
lib/common-lisp/reader.sx — tokenizer + reader (read macros, dispatch chars)
|
||||
│
|
||||
▼
|
||||
lib/common-lisp/parser.sx — AST: forms, declarations, lambda lists
|
||||
│
|
||||
▼
|
||||
lib/common-lisp/transpile.sx — AST → SX AST (entry: cl-eval-ast)
|
||||
│
|
||||
▼
|
||||
lib/common-lisp/runtime.sx — special forms, condition system, CLOS, packages, BIFs
|
||||
```
|
||||
|
||||
Core mapping:
|
||||
- **Symbol** = SX symbol with package prefix; package table is a flat dict.
|
||||
- **Cons cell** = SX pair via `cons`/`car`/`cdr`; lists native.
|
||||
- **Multiple values** = thread through `values`/`multiple-value-bind`; primary-value default for one-context callers.
|
||||
- **Block / return-from** = captured continuation; `return-from name v` invokes the block-named `^k`.
|
||||
- **Tagbody / go** = each tag is a continuation; `go tag` invokes it.
|
||||
- **Unwind-protect** = scope frame with a cleanup thunk fired on any non-local exit.
|
||||
- **Conditions / restarts** = layered handler chain on top of `handler-bind` + delcc. `signal` walks handlers; `invoke-restart` resumes a captured continuation.
|
||||
- **CLOS** = generic functions are dispatch tables on argument-class lists; method combination computed lazily; `call-next-method` is a continuation.
|
||||
- **Macros** = SX macros (sentinel-body) — defmacro lowers directly.
|
||||
|
||||
## Roadmap
|
||||
|
||||
### Phase 1 — reader + parser
|
||||
- [ ] Tokenizer: symbols (with package qualification `pkg:sym` / `pkg::sym`), numbers (int, float, ratio `1/3`, `#xFF`, `#b1010`, `#o17`), strings `"…"` with `\` escapes, characters `#\Space` `#\Newline` `#\a`, comments `;`, block comments `#| … |#`
|
||||
- [ ] Reader: list, dotted pair, quote `'`, function `#'`, quasiquote `` ` ``, unquote `,`, splice `,@`, vector `#(…)`, uninterned `#:foo`, nil/t literals
|
||||
- [ ] Parser: lambda lists with `&optional` `&rest` `&key` `&aux` `&allow-other-keys`, defaults, supplied-p variables
|
||||
- [ ] Unit tests in `lib/common-lisp/tests/read.sx`
|
||||
|
||||
### Phase 2 — sequential eval + special forms
|
||||
- [ ] `cl-eval-ast`: `quote`, `if`, `progn`, `let`, `let*`, `flet`, `labels`, `setq`, `setf` (subset), `function`, `lambda`, `the`, `locally`, `eval-when`
|
||||
- [ ] `block` + `return-from` via captured continuation
|
||||
- [ ] `tagbody` + `go` via per-tag continuations
|
||||
- [ ] `unwind-protect` cleanup frame
|
||||
- [ ] `multiple-value-bind`, `multiple-value-call`, `multiple-value-prog1`, `values`, `nth-value`
|
||||
- [ ] `defun`, `defparameter`, `defvar`, `defconstant`, `declaim`, `proclaim` (no-op)
|
||||
- [ ] Dynamic variables — `defvar`/`defparameter` produce specials; `let` rebinds via parameterize-style scope
|
||||
- [ ] 60+ tests in `lib/common-lisp/tests/eval.sx`
|
||||
|
||||
### Phase 3 — conditions + restarts (THE SHOWCASE)
|
||||
- [ ] `define-condition` — class hierarchy rooted at `condition`/`error`/`warning`/`simple-error`/`simple-warning`/`type-error`/`arithmetic-error`/`division-by-zero`
|
||||
- [ ] `signal`, `error`, `cerror`, `warn` — all walk the handler chain
|
||||
- [ ] `handler-bind` — non-unwinding handlers, may decline by returning normally
|
||||
- [ ] `handler-case` — unwinding handlers (delcc abort)
|
||||
- [ ] `restart-case`, `with-simple-restart`, `restart-bind`
|
||||
- [ ] `find-restart`, `invoke-restart`, `invoke-restart-interactively`, `compute-restarts`
|
||||
- [ ] `with-condition-restarts` — associate restarts with a specific condition
|
||||
- [ ] `*break-on-signals*`, `*debugger-hook*` (basic)
|
||||
- [ ] Classic programs in `lib/common-lisp/tests/programs/`:
|
||||
- [ ] `restart-demo.lisp` — division with `:use-zero` and `:retry` restarts
|
||||
- [ ] `parse-recover.lisp` — parser with skipped-token restart
|
||||
- [ ] `interactive-debugger.lisp` — ASCII REPL using `:debugger-hook`
|
||||
- [ ] `lib/common-lisp/conformance.sh` + runner, `scoreboard.json` + `scoreboard.md`
|
||||
|
||||
### Phase 4 — CLOS
|
||||
- [ ] `defclass` with `:initarg`/`:initform`/`:accessor`/`:reader`/`:writer`/`:allocation`
|
||||
- [ ] `make-instance`, `slot-value`, `(setf slot-value)`, `with-slots`, `with-accessors`
|
||||
- [ ] `defgeneric` with `:method-combination` (standard, plus `+`, `and`, `or`)
|
||||
- [ ] `defmethod` with `:before` / `:after` / `:around` qualifiers
|
||||
- [ ] `call-next-method` (continuation), `next-method-p`
|
||||
- [ ] `class-of`, `find-class`, `slot-boundp`, `change-class` (basic)
|
||||
- [ ] Multiple dispatch — method specificity by argument-class precedence list
|
||||
- [ ] Built-in classes registered for tagged values (`integer`, `float`, `string`, `symbol`, `cons`, `null`, `t`)
|
||||
- [ ] Classic programs:
|
||||
- [ ] `geometry.lisp` — `intersect` generic dispatching on (point line), (line line), (line plane)…
|
||||
- [ ] `mop-trace.lisp` — `:before` + `:after` printing call trace
|
||||
|
||||
### Phase 5 — macros + LOOP + reader macros
|
||||
- [ ] `defmacro`, `macrolet`, `symbol-macrolet`, `macroexpand-1`, `macroexpand`
|
||||
- [ ] `gensym`, `gentemp`
|
||||
- [ ] `set-macro-character`, `set-dispatch-macro-character`, `get-macro-character`
|
||||
- [ ] **The LOOP macro** — iteration drivers (`for … in/across/from/upto/downto/by`, `while`, `until`, `repeat`), accumulators (`collect`, `append`, `nconc`, `count`, `sum`, `maximize`, `minimize`), conditional clauses (`if`/`when`/`unless`/`else`), termination (`finally`/`thereis`/`always`/`never`), `named` blocks
|
||||
- [ ] LOOP test corpus: 30+ tests covering all clause types
|
||||
|
||||
### Phase 6 — packages + stdlib drive
|
||||
- [ ] `defpackage`, `in-package`, `export`, `use-package`, `import`, `find-package`
|
||||
- [ ] Package qualification at the reader level — `cl:car`, `mypkg::internal`
|
||||
- [ ] `:common-lisp` (`:cl`) and `:common-lisp-user` (`:cl-user`) packages
|
||||
- [ ] Sequence functions — `mapcar`, `mapc`, `mapcan`, `reduce`, `find`, `find-if`, `position`, `count`, `every`, `some`, `notany`, `notevery`, `remove`, `remove-if`, `subst`
|
||||
- [ ] List ops — `assoc`, `getf`, `nth`, `last`, `butlast`, `nthcdr`, `tailp`, `ldiff`
|
||||
- [ ] String ops — `string=`, `string-upcase`, `string-downcase`, `subseq`, `concatenate`
|
||||
- [ ] FORMAT — basic directives `~A`, `~S`, `~D`, `~F`, `~%`, `~&`, `~T`, `~{...~}` (iteration), `~[...~]` (conditional), `~^` (escape), `~P` (plural)
|
||||
- [ ] Drive corpus to 200+ green
|
||||
|
||||
## Progress log
|
||||
|
||||
_Newest first._
|
||||
|
||||
- _(none yet)_
|
||||
|
||||
## Blockers
|
||||
|
||||
- _(none yet)_
|
||||
257
plans/designs/sx-adt.md
Normal file
257
plans/designs/sx-adt.md
Normal file
@@ -0,0 +1,257 @@
|
||||
# SX Algebraic Data Types — Design
|
||||
|
||||
## Motivation
|
||||
|
||||
Every language implementation currently uses `{:tag "..." :field ...}` tagged dicts to
|
||||
simulate sum types. This is verbose, error-prone (typos in tag strings go undetected), and
|
||||
produces no exhaustiveness warnings. Native ADTs eliminate the pattern everywhere.
|
||||
|
||||
Examples of current workarounds:
|
||||
- Haskell `Maybe a` → `{:tag "Just" :value x}` / `{:tag "Nothing"}`
|
||||
- Prolog terms → `{:tag "functor" :name "foo" :args (list x y)}`
|
||||
- Lua result type → `{:tag "ok" :value v}` / `{:tag "err" :msg s}`
|
||||
- Common Lisp `cons` pairs → `{:tag "cons" :car a :cdr b}`
|
||||
|
||||
---
|
||||
|
||||
## Syntax
|
||||
|
||||
### `define-type`
|
||||
|
||||
```lisp
|
||||
(define-type Name
|
||||
(Ctor1 field1 field2 ...)
|
||||
(Ctor2 field1 ...)
|
||||
...)
|
||||
```
|
||||
|
||||
Creates:
|
||||
- Constructor functions: `Ctor1`, `Ctor2`, … (callable like normal functions)
|
||||
- Type predicate: `Name?` — returns true for any value of type `Name`
|
||||
- Constructor predicates: `Ctor1?`, `Ctor2?`, … (optional, auto-generated)
|
||||
- Field accessors: `Ctor1-field1`, `Ctor1-field2`, … (optional, auto-generated)
|
||||
|
||||
Examples:
|
||||
|
||||
```lisp
|
||||
(define-type Maybe
|
||||
(Just value)
|
||||
(Nothing))
|
||||
|
||||
(define-type Result
|
||||
(Ok value)
|
||||
(Err message))
|
||||
|
||||
(define-type Tree
|
||||
(Leaf)
|
||||
(Node left value right))
|
||||
|
||||
(define-type List-of
|
||||
(Nil-of)
|
||||
(Cons-of head tail))
|
||||
```
|
||||
|
||||
Constructors with no fields are zero-argument constructors (singletons by value):
|
||||
|
||||
```lisp
|
||||
(Nothing) ; => #<Nothing>
|
||||
(Leaf) ; => #<Leaf>
|
||||
```
|
||||
|
||||
### `match`
|
||||
|
||||
```lisp
|
||||
(match expr
|
||||
((Ctor1 a b) body)
|
||||
((Ctor2 x) body)
|
||||
((Ctor3) body)
|
||||
(else body))
|
||||
```
|
||||
|
||||
- Clauses are tried in order; first match wins.
|
||||
- `else` clause is optional but suppresses exhaustiveness warnings.
|
||||
- Pattern variables (`a`, `b`, `x`) are bound in the body scope.
|
||||
- Wildcard `_` discards the matched value.
|
||||
- Literal patterns: `42`, `"str"`, `true`, `nil` — match by value equality.
|
||||
- Nested patterns: `((Node left (Leaf) right) body)` — nested constructor patterns.
|
||||
|
||||
Examples:
|
||||
|
||||
```lisp
|
||||
(match result
|
||||
((Ok v) (str "got: " v))
|
||||
((Err m) (str "error: " m)))
|
||||
|
||||
(match tree
|
||||
((Leaf) 0)
|
||||
((Node l v r) (+ 1 (tree-depth l) (tree-depth r))))
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CEK Dispatch
|
||||
|
||||
### Runtime representation
|
||||
|
||||
ADT values are OCaml records (not dicts) — opaque, non-inspectable via `get`:
|
||||
|
||||
```ocaml
|
||||
type adt_value = {
|
||||
av_type : string; (* type name, e.g. "Maybe" *)
|
||||
av_ctor : string; (* constructor name, e.g. "Just" *)
|
||||
av_fields: value array; (* positional fields *)
|
||||
}
|
||||
```
|
||||
|
||||
In JS: `{ _adt: true, _type: "Maybe", _ctor: "Just", _fields: [v] }`.
|
||||
|
||||
`typeOf` returns the ADT type name (e.g. `"Maybe"`).
|
||||
|
||||
### `define-type` — special form
|
||||
|
||||
`stepSfDefineType(args, env, kont)`:
|
||||
|
||||
1. Parse `Name` and list of `(CtorN field...)` clauses.
|
||||
2. For each constructor `CtorK` with fields `[f1, f2, …]`:
|
||||
- Register `CtorK` as a `NativeFn` that takes `|fields|` args and returns an `AdtValue`.
|
||||
- Register `CtorK?` as a predicate (`AdtValue` with matching ctor name → `true`).
|
||||
- Register `CtorK-fN` as field accessor (returns `av_fields[N]`).
|
||||
3. Register `Name?` as a predicate (`AdtValue` with matching type name → `true`).
|
||||
4. All bindings go into the current environment via `env-bind!`.
|
||||
5. Returns `Nil`.
|
||||
|
||||
This is an environment mutation — no new frame needed. Evaluates in one step.
|
||||
|
||||
### `match` — special form
|
||||
|
||||
`stepSfMatch(args, env, kont)`:
|
||||
|
||||
1. Push `MatchFrame` with `clauses` and `env` onto kont.
|
||||
2. Return state evaluating the scrutinee `expr`.
|
||||
3. `MatchFrame` continue: receive scrutinee value, walk clauses:
|
||||
- For each `((CtorN vars...) body)`:
|
||||
- If scrutinee is an `AdtValue` with `av_ctor = "CtorN"` and `av_fields.length = |vars|`:
|
||||
- Bind `vars[i]` → `av_fields[i]` in fresh child env.
|
||||
- Return state evaluating `body` in that env.
|
||||
- `(else body)` — always matches, body evaluated in current env.
|
||||
- Literal `42`/`"str"` patterns: match by value equality.
|
||||
- Wildcard `_`: always matches, binds nothing.
|
||||
4. If no clause matched and no `else`: raise `"match: no clause matched <value>"`.
|
||||
|
||||
Frame type: `"match"` — stores `cf_remaining` (clauses), `cf_env` (enclosing env).
|
||||
|
||||
---
|
||||
|
||||
## Interaction with `cond` / `case`
|
||||
|
||||
`match` is the primary dispatch form for ADTs. `cond` / `case` remain unchanged:
|
||||
|
||||
- `cond` tests arbitrary boolean expressions — still useful for non-ADT dispatch.
|
||||
- `case` matches on equality to literal values — unchanged.
|
||||
- `match` is the new form: structural pattern matching on ADT constructors.
|
||||
|
||||
They are orthogonal. A `match` clause can contain a `cond`; a `cond` clause can contain a `match`.
|
||||
|
||||
---
|
||||
|
||||
## Exhaustiveness checking
|
||||
|
||||
Emit a **warning** (not an error) when:
|
||||
- A `match` has no `else` clause, AND
|
||||
- Not all constructors of the scrutinee's type are covered.
|
||||
|
||||
Detection: when `define-type` runs, it registers the constructor set in a global table
|
||||
`_adt_registry: type_name → [ctor_names]`. At `match` compile/evaluation time:
|
||||
- If the scrutinee's type is in `_adt_registry` and not all ctors appear as patterns:
|
||||
- `console.warn("[sx] match: non-exhaustive — missing: Ctor3, Ctor4 for type Maybe")`
|
||||
- Execution continues (warning, not error).
|
||||
|
||||
This is best-effort: the scrutinee type is only known at runtime. The warning fires on
|
||||
first non-exhaustive match evaluation, not at definition time.
|
||||
|
||||
---
|
||||
|
||||
## Recursive types
|
||||
|
||||
Recursive types work because constructors are registered as functions, and function bodies
|
||||
are evaluated lazily:
|
||||
|
||||
```lisp
|
||||
(define-type Tree
|
||||
(Leaf)
|
||||
(Node left value right))
|
||||
|
||||
; Recursive function over a recursive type:
|
||||
(define (depth tree)
|
||||
(match tree
|
||||
((Leaf) 0)
|
||||
((Node l v r) (+ 1 (max (depth l) (depth r))))))
|
||||
```
|
||||
|
||||
No special treatment needed — the type definition doesn't need to know about recursion.
|
||||
The constructor `Node` accepts any values, including other `Node` or `Leaf` values.
|
||||
|
||||
---
|
||||
|
||||
## Pattern variables
|
||||
|
||||
In `match` clauses, identifiers in constructor position that are NOT constructor names are
|
||||
treated as pattern variables (bound to matched field values):
|
||||
|
||||
```lisp
|
||||
(match x
|
||||
((Just v) v) ; v bound to the wrapped value
|
||||
((Nothing) nil))
|
||||
|
||||
(match pair
|
||||
((Cons-of h t) (list h t))) ; h, t bound to head and tail
|
||||
```
|
||||
|
||||
**Wildcard**: `_` is always a wildcard — matches anything, binds nothing.
|
||||
|
||||
```lisp
|
||||
(match x
|
||||
((Just _) "has value")
|
||||
((Nothing) "empty"))
|
||||
```
|
||||
|
||||
**Nested patterns**:
|
||||
|
||||
```lisp
|
||||
(match tree
|
||||
((Node (Leaf) v (Leaf)) (str "leaf node: " v))
|
||||
((Node l v r) (str "inner node: " v)))
|
||||
```
|
||||
|
||||
Nested patterns are matched recursively: the inner `(Leaf)` pattern checks that the
|
||||
`left` field is itself a `Leaf` ADT value.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 6a — `define-type` + basic `match` (no nested patterns, no exhaustiveness)
|
||||
|
||||
1. OCaml: add `AdtValue of adt_value` to `sx_types.ml`.
|
||||
2. Evaluator: add `step-sf-define-type` — parse clauses, register ctor fns + predicates + accessors.
|
||||
3. Evaluator: add `step-sf-match` + `MatchFrame` — linear scan of clauses, flat patterns only.
|
||||
4. JS: same (AdtValue as plain object with `_adt`/`_type`/`_ctor`/`_fields` props).
|
||||
|
||||
### Phase 6b — nested patterns (separate fire)
|
||||
|
||||
Recursive `matchPattern(pattern, value, env)` helper that:
|
||||
- Returns `{matched: bool, bindings: map}`
|
||||
- Recursively matches sub-patterns against ADT fields.
|
||||
|
||||
### Phase 6c — exhaustiveness warnings (separate fire)
|
||||
|
||||
`_adt_registry` global + warning emission on first non-exhaustive match.
|
||||
|
||||
---
|
||||
|
||||
## Open questions (deferred to review)
|
||||
|
||||
1. **Accessor auto-generation**: should `Ctor-field` accessors be generated always, or only on demand? Risk: name collisions if two types have constructors with same field names.
|
||||
2. **Singleton constructors**: `(Nothing)` — zero-arg ctor — should these be interned (same object every call) or fresh each time? Interning enables `eq?` checks but requires a global table.
|
||||
3. **Printing/inspect**: `inspect` on an AdtValue should show `(Just 42)` not `#<adt:Just>`. Implement in `inspect` function or via `display`/`write` (Phase 17 ports).
|
||||
4. **Pattern-matching on non-ADT values**: should `match` handle list patterns `(a . b)` and literal patterns in clause heads? Deferred — add only if needed by a language implementation.
|
||||
96
plans/hs-blockers-drain.md
Normal file
96
plans/hs-blockers-drain.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# HS conformance — blockers drain
|
||||
|
||||
Goal: take hyperscript conformance from **1277/1496 (85.4%)** to **1496/1496 (100%)** by clearing the blocked clusters and the design-done Bucket E subsystems.
|
||||
|
||||
This plan exists because the per-iteration `loops/hs` agent can't fit these into its 30-min budget — they need dedicated multi-commit sit-downs. Track progress here; refer to `plans/hs-conformance-to-100.md` for the canonical cluster ledger.
|
||||
|
||||
## Current state (2026-04-25)
|
||||
|
||||
- Loop running in `/root/rose-ash-loops/hs` (branch `loops/hs`)
|
||||
- sx-tree MCP **fixed** (was a session-stale binary issue — restart of claude in the tmux window picked it up). Loop hinted to retry **#32**, **#29** first.
|
||||
- Recent loop progress: ~1 commit/6h — easy wins drained, what's left needs focused attention.
|
||||
|
||||
## Remaining work
|
||||
|
||||
### Bucket-A/B/C blockers (small, in-place fixes)
|
||||
|
||||
| # | Cluster | Tests | Effort | Blocker | Fix sketch |
|
||||
|---|---------|------:|--------|---------|------------|
|
||||
| **17** | `tell` semantics | +3 | ~1h | Implicit-default-target ambiguity. `bare add .bar` inside `tell X` should target `X` but explicit `to me` must reach the original element. | Add `beingTold` symbol distinct from `me`; bare commands compile to `beingTold-or-me`; explicit `me` always the original. |
|
||||
| **22** | window global fn fallback | +2-4 | ~1h | `foo()` where `foo` isn't SX-defined needs to fall back to `(host-global "foo")`. Three attempts failed: guard (host-level error not catchable), `env-has?` (not in HS kernel), `hs-win-call` (NativeFn not callable from CALL). | Add `symbol-bound?` predicate to HS kernel **OR** a host-call-fn primitive with arity-agnostic dispatch. |
|
||||
| **29** | `hyperscript:before:init` / `:after:init` / `:parse-error` events | +4-6 | ~30m (post sx-tree fix) | Was sx-tree MCP outage. Now unblocked — loop should retry. 4 of 6 tests need stricter parser error-rejection (out of scope; mark partial). | Edit `integration.sx` to fire DOM events at activation boundaries. |
|
||||
|
||||
### Bucket D — medium features
|
||||
|
||||
| # | Cluster | Tests | Effort | Status |
|
||||
|---|---------|------:|--------|--------|
|
||||
| **31** | runtime null-safety error reporting | **+15-18** | **2-4h** | **THIS SESSION'S TARGET.** Plan node fully spec'd: 5 pieces of work. |
|
||||
| **32** | MutationObserver mock + `on mutation` | +10-15 | ~2h | Was sx-tree-blocked. Now unblocked — loop hinted to retry. Multi-file: parser, compiler, runtime, runner mock, generator skip-list. |
|
||||
| **33** | cookie API | +2 (remaining) | ~30m | Partial done (+3). Remaining 2 need `hs-method-call` runtime fallback for unknown methods + `hs-for-each` recognising host-array/proxy collections. |
|
||||
| 34 | event modifier DSL | +6-8 | ~1-2h | `elsewhere`, `every`, count filters (`once`/`twice`/`3 times`/ranges), `from elsewhere`. Pending. |
|
||||
| 35 | namespaced `def` | +3 | ~30m | Pending. |
|
||||
|
||||
### Bucket E — subsystems (design docs landed, multi-commit each)
|
||||
|
||||
Each has a design doc with a step-by-step checklist. These are 1-2 days of focused work each, not loop-fits.
|
||||
|
||||
| # | Subsystem | Tests | Design doc | Branch |
|
||||
|---|-----------|------:|------------|--------|
|
||||
| 36 | WebSocket + `socket` + RPC Proxy | +12-16 | `plans/designs/e36-websocket.md` | `worktree-agent-a9daf73703f520257` |
|
||||
| 37 | Tokenizer-as-API | +16-17 | `plans/designs/e37-tokenizer-api.md` | `worktree-agent-a6bb61d59cc0be8b4` |
|
||||
| 38 | SourceInfo API | +4 | `plans/designs/e38-sourceinfo.md` | `agent-e38-sourceinfo` |
|
||||
| 39 | WebWorker plugin (parser-only stub) | +1 | `plans/designs/e39-webworker.md` | `hs-design-e39-webworker` |
|
||||
| 40 | Real Fetch / non-2xx / before-fetch | +7 | `plans/designs/e40-real-fetch.md` | `worktree-agent-a94612a4283eaa5e0` |
|
||||
|
||||
### Bucket F — generator translation gaps
|
||||
|
||||
~25 tests SKIP'd because `tests/playwright/generate-sx-tests.py` bails with `return None`. Single dedicated generator-repair sit-down once Bucket D is drained. ~half-day.
|
||||
|
||||
## Order of attack
|
||||
|
||||
In approximate cost-per-test order:
|
||||
|
||||
1. **Loop self-heal** (no human work) — wait for #29, #32 to land via the running loop ⏱️ ~next 1-2 hours
|
||||
2. **#31 null-safety** — biggest scoped single win, dedicated worktree agent (this session)
|
||||
3. **#33 cookie API remainder** — quick partial completion
|
||||
4. **#17 / #22 / #34 / #35** — small fiddly fixes, one sit-down each
|
||||
5. **Bucket E** — pick one subsystem at a time. **#39 (WebWorker stub) first** — single commit, smallest. Then **#38 (SourceInfo)** — 4 commits. Then the bigger three (#36, #37, #40).
|
||||
6. **Bucket F** — generator repair sweep at the end.
|
||||
|
||||
Estimated total to 100%: ~10-15 days of focused work, parallelisable across branches.
|
||||
|
||||
## Cluster #31 spec (full detail)
|
||||
|
||||
The plan note from `hs-conformance-to-100.md`:
|
||||
|
||||
> 18 tests in `runtimeErrors`. When accessing `.foo` on nil, emit a structured error with position info. One coordinated fix in the compiler emit paths for property access, function calls, set/put.
|
||||
|
||||
**Required pieces:**
|
||||
|
||||
1. **Generator-side `eval-hs-error` helper + recognizer** for `expect(await error("HS")).toBe("MSG")` blocks. In `tests/playwright/generate-sx-tests.py`.
|
||||
2. **Runtime helpers** in `lib/hyperscript/runtime.sx`:
|
||||
- `hs-null-error!` raising `'<sel>' is null`
|
||||
- `hs-named-target` — wraps a query result with the original selector source
|
||||
- `hs-named-target-list` — same for list results
|
||||
3. **Compiler patches at every target-position `(query SEL)` emit** — wrap in named-target carrying the original selector source. ~17 command emit paths in `lib/hyperscript/compiler.sx`:
|
||||
add, remove, hide, show, measure, settle, trigger, send, set, default, increment, decrement, put, toggle, transition, append, take.
|
||||
4. **Function-call null-check** at bare `(name)`, `hs-method-call`, and `host-get` chains, deriving the leftmost-uncalled-name (`'x'` / `'x.y'`) from the parse tree.
|
||||
5. **Possessive-base null-check** (`set x's y to true` → `'x' is null`).
|
||||
|
||||
**Files in scope:**
|
||||
- `lib/hyperscript/runtime.sx` (new helpers)
|
||||
- `lib/hyperscript/compiler.sx` (~17 emit-path edits)
|
||||
- `tests/playwright/generate-sx-tests.py` (test recognizer)
|
||||
- `tests/hs-run-filtered.js` (if mock helpers needed)
|
||||
- `shared/static/wasm/sx/hs-runtime.sx` + `hs-compiler.sx` (WASM staging copies)
|
||||
|
||||
**Approach:** target-named pieces incrementally — runtime helpers first (no compiler change), then compiler emit paths in batches (group similar commands), then function-call/possessive at the end. Each batch is one commit if it lands +N tests; mark partial if it only unlocks part.
|
||||
|
||||
**Watch for:** smoke-range regressions (tests flipping pass→fail). Each commit: rerun smoke 0-195 and the `runtimeErrors` suite.
|
||||
|
||||
## Notes for future sessions
|
||||
|
||||
- `plans/hs-conformance-to-100.md` is the canonical cluster ledger — update it on every commit.
|
||||
- `plans/hs-conformance-scoreboard.md` is the live tally — bump `Merged:` and the bucket roll-up.
|
||||
- Loop has scope rule "never edit `spec/evaluator.sx` or broader SX kernel" — most fixes here stay in `lib/hyperscript/**`, `tests/`, generator. If a fix needs kernel work, surface to the user; don't merge silently.
|
||||
- Cluster #22's `symbol-bound?` predicate would be a kernel addition — that's a real cross-boundary scope expansion.
|
||||
@@ -125,7 +125,7 @@ Each item: implement → tests → update progress. Mark `[x]` when tests green.
|
||||
- [x] Rest params (`...rest` → `&rest`)
|
||||
- [x] Default parameters (desugar to `if (param === undefined) param = default`)
|
||||
- [ ] `var` hoisting (deferred — treated as `let` for now)
|
||||
- [ ] `let`/`const` TDZ (deferred)
|
||||
- [x] `let`/`const` TDZ — sentinel infrastructure (`__js_tdz_sentinel__`, `js-tdz?`, `js-tdz-check` in runtime.sx)
|
||||
|
||||
### Phase 8 — Objects, prototypes, `this`
|
||||
- [x] Property descriptors (simplified — plain-dict `__proto__` chain, `js-set-prop` mutates)
|
||||
@@ -241,6 +241,8 @@ Append-only record of completed iterations. Loop writes one line per iteration:
|
||||
- 29× Timeout (slow string/regex loops)
|
||||
- 16× ReferenceError — still some missing globals
|
||||
|
||||
- 2026-04-25 — **Regex engine (lib/js/regex.sx) + let/const TDZ infrastructure.** New file `lib/js/regex.sx`: 39-form pure-SX recursive backtracking engine installed via `js-regex-platform-override!`. Covers literals, `.`, `\d\w\s` + negations, `[abc]/[^abc]/[a-z]` char classes, `^\$\b\B` anchors, greedy+lazy quantifiers (`* + ? {n,m} *? +? ??`), capturing groups, non-capturing `(?:...)`, alternation `a|b`, flags `i`/`g`/`m`. Groups: match inner first → set capture → match rest (correct boundary), avoids including rest-nodes content in capture. Greedy: expand-first then backtrack (correct longest-match semantics). `js-regex-match-all` for String.matchAll. Fixed `String.prototype.match` to use platform engine (was calling stub). TDZ infrastructure added to `runtime.sx`: `__js_tdz_sentinel__` (unique sentinel dict), `js-tdz?`, `js-tdz-check`. `transpile.sx` passes `kind` through `js-transpile-var → js-vardecl-forms` (no behavioral change yet — infrastructure ready). `test262-runner.py` and `conformance.sh` updated to load `regex.sx` as epoch 6/50. Unit: **559/560** (was 522/522 before regex tests added, now +38 new tests; 1 pre-existing backtick failure). Conformance: **148/148** (unchanged). Gotchas: (1) `sx_insert_near` on a pattern inside a top-level function body inserts there (not at top level) — need to use `sx_insert_near` on a top-level symbol name. (2) Greedy quantifier must expand-first before trying rest-nodes; the naive "try rest at each step" produces lazy behavior. (3) Capturing groups must match inner nodes in isolation first (to get the group's end position) then match rest — appending inner+rest-nodes would include rest in the capture string.
|
||||
|
||||
## Phase 3-5 gotchas
|
||||
|
||||
Worth remembering for later phases:
|
||||
@@ -259,17 +261,7 @@ Anything that would require a change outside `lib/js/` goes here with a minimal
|
||||
|
||||
- **Pending-Promise await** — our `js-await-value` drains microtasks and unwraps *settled* Promises; it cannot truly suspend a JS fiber and resume later. Every Promise that settles eventually through the synchronous `resolve`/`reject` + microtask path works. A Promise that never settles without external input (e.g. a real `setTimeout` waiting on the event loop) would hit the `"await on pending Promise (no scheduler)"` error. Proper async suspension would need the JS eval path to run under `cek-step-loop` (not `eval-expr` → `cek-run`) and treat `await pending-Promise` as a `perform` that registers a resume thunk on the Promise's callback list. Non-trivial plumbing; out of scope for this phase. Consider it a Phase 9.5 item.
|
||||
|
||||
- **Regex platform primitives** — runtime ships a substring-based stub (`js-regex-stub-test` / `-exec`). Overridable via `js-regex-platform-override!` so a real engine can be dropped in. Required platform-primitive surface:
|
||||
- `regex-compile pattern flags` — build an opaque compiled handle
|
||||
- `regex-test compiled s` → bool
|
||||
- `regex-exec compiled s` → match dict `{match index input groups}` or nil
|
||||
- `regex-match-all compiled s` → list of match dicts (or empty list)
|
||||
- `regex-replace compiled s replacement` → string
|
||||
- `regex-replace-fn compiled s fn` → string (fn receives match+groups, returns string)
|
||||
- `regex-split compiled s` → list of strings
|
||||
- `regex-source compiled` → string
|
||||
- `regex-flags compiled` → string
|
||||
Ideally a single `(js-regex-platform-install-all! platform)` entry point the host calls once at boot. OCaml would wrap `Str` / `Re` or a dedicated regex lib; JS host can just delegate to the native `RegExp`.
|
||||
- ~~**Regex platform primitives**~~ **RESOLVED** — `lib/js/regex.sx` ships a pure-SX recursive backtracking engine. Installs via `js-regex-platform-override!` at load. Covers: literals, `.`, `\d\w\s` and negations, `[abc]` / `[^abc]` / ranges, `^` `$` `\b \B`, `* + ? {n,m}` (greedy + lazy), capturing + non-capturing groups, alternation `a|b`, flags `i` (case-insensitive), `g` (global, advances lastIndex), `m` (multiline anchors). `js-regex-match-all` for String.matchAll. String.prototype.match regex path updated to use platform engine (was calling stub). 34 new unit tests added (5000–5033). Conformance: 148/148 (unchanged — slice had no regex fixtures).
|
||||
|
||||
- **Math trig + transcendental primitives missing.** The scoreboard shows 34× "TypeError: not a function" across the Math category — every one a test calling `Math.sin/cos/tan/log/…` on our runtime. We shim `Math` via `js-global`; the SX runtime supplies `sqrt`, `pow`, `abs`, `floor`, `ceil`, `round` and a hand-rolled `trunc`/`sign`/`cbrt`/`hypot`. Nothing else. Missing platform primitives (each is a one-line OCaml/JS binding, but a primitive all the same — we can't land approximation polynomials from inside the JS shim, they'd blow `Math.sin(1e308)` precision):
|
||||
- Trig: `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`
|
||||
|
||||
124
plans/ruby-on-sx.md
Normal file
124
plans/ruby-on-sx.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# Ruby-on-SX: fibers + blocks + open classes on delimited continuations
|
||||
|
||||
The headline showcase is **fibers** — Ruby's `Fiber.new { … Fiber.yield v … }` / `Fiber.resume` are textbook delimited continuations with sugar. MRI implements them by swapping C stacks; on SX they fall out of the existing `perform`/`cek-resume` machinery for free. Plus blocks/yield (lexical escape continuations, same shape as Smalltalk's non-local return), method_missing, and singleton classes.
|
||||
|
||||
End-state goal: Ruby 2.7-flavoured subset, Enumerable mixin, fibers + threads-via-fibers (no real OS threads), method_missing-driven DSLs, ~150 hand-written + classic programs.
|
||||
|
||||
## Scope decisions (defaults — override by editing before we spawn)
|
||||
|
||||
- **Syntax:** Ruby 2.7. No 3.x pattern matching, no rightward assignment, no endless methods. We pick 2.7 because it's the biggest semantic surface that still parses cleanly.
|
||||
- **Conformance:** "Reads like Ruby, runs like Ruby." Slice of RubySpec (Core + Library subset), not full RubySpec.
|
||||
- **Test corpus:** custom + curated RubySpec slice. Plus classic programs: fiber-based generator, internal DSL with method_missing, mixin-based Enumerable on a custom class.
|
||||
- **Out of scope:** real threads, GIL, refinements, `binding_of_caller` from non-Ruby contexts, Encoding object beyond UTF-8/ASCII-8BIT, RubyVM::* introspection beyond bytecode-disassembly placeholder, IO subsystem beyond `puts`/`gets`/`File.read`.
|
||||
- **Symbols:** SX symbols. Strings are mutable copies; symbols are interned.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Scope:** only touch `lib/ruby/**` and `plans/ruby-on-sx.md`. Don't edit `spec/`, `hosts/`, `shared/`, or any other `lib/<lang>/**`. Ruby primitives go in `lib/ruby/runtime.sx`.
|
||||
- **SX files:** use `sx-tree` MCP tools only.
|
||||
- **Commits:** one feature per commit. Keep `## Progress log` updated and tick roadmap boxes.
|
||||
|
||||
## Architecture sketch
|
||||
|
||||
```
|
||||
Ruby source
|
||||
│
|
||||
▼
|
||||
lib/ruby/tokenizer.sx — keywords, ops, %w[], %i[], heredocs (deferred), regex (deferred)
|
||||
│
|
||||
▼
|
||||
lib/ruby/parser.sx — AST: classes, modules, methods, blocks, calls
|
||||
│
|
||||
▼
|
||||
lib/ruby/transpile.sx — AST → SX AST (entry: rb-eval-ast)
|
||||
│
|
||||
▼
|
||||
lib/ruby/runtime.sx — class table, MOP, dispatch, fibers, primitives
|
||||
```
|
||||
|
||||
Core mapping:
|
||||
- **Object** = SX dict `{:class :ivars :singleton-class?}`. Instance variables live in `ivars` keyed by symbol.
|
||||
- **Class** = SX dict `{:name :superclass :methods :class-methods :metaclass :includes :prepends}`. Class table is flat.
|
||||
- **Method dispatch** = lookup walks ancestor chain (prepended → class → included modules → superclass → …). Falls back to `method_missing` with a `Symbol`+args.
|
||||
- **Block** = lambda + escape continuation. `yield` invokes the block in current context. `return` from within a block invokes the enclosing-method's escape continuation.
|
||||
- **Proc** = lambda without strict arity. `Proc.new` + `proc {}`.
|
||||
- **Lambda** = lambda with strict arity + `return`-returns-from-lambda semantics.
|
||||
- **Fiber** = pair of continuations (resume-k, yield-k) wrapped in a record. `Fiber.new { … }` builds it; `Fiber.resume` invokes the resume-k; `Fiber.yield` invokes the yield-k. Built directly on `perform`/`cek-resume`.
|
||||
- **Module** = class without instance allocation. `include` puts it in the chain; `prepend` puts it earlier; `extend` puts it on the singleton.
|
||||
- **Singleton class** = lazily allocated per-object class for `def obj.foo` definitions.
|
||||
- **Symbol** = interned SX symbol. `:foo` reads as `(quote foo)` flavour.
|
||||
|
||||
## Roadmap
|
||||
|
||||
### Phase 1 — tokenizer + parser
|
||||
- [ ] Tokenizer: keywords (`def end class module if unless while until do return yield begin rescue ensure case when then else elsif`), identifiers (lowercase = local/method, `@` = ivar, `@@` = cvar, `$` = global, uppercase = constant), numbers (int, float, `0x` `0o` `0b`, `_` separators), strings (`"…"` interpolation, `'…'` literal, `%w[a b c]`, `%i[a b c]`), symbols `:foo` `:"…"`, operators (`+ - * / % ** == != < > <= >= <=> === =~ !~ << >> & | ^ ~ ! && || and or not`), `:: . , ; ( ) [ ] { } -> => |`, comments `#`
|
||||
- [ ] Parser: program is sequence of statements separated by newlines or `;`; method def `def name(args) … end`; class `class Foo < Bar … end`; module `module M … end`; block `do |a, b| … end` and `{ |a, b| … }`; call sugar (no parens), `obj.method`, `Mod::Const`; arg shapes (positional, default, splat `*args`, double-splat `**opts`, block `&blk`)
|
||||
- [ ] If/while/case expressions (return values), `unless`/`until`, postfix modifiers
|
||||
- [ ] Begin/rescue/ensure/retry, raise, raise with class+message
|
||||
- [ ] Unit tests in `lib/ruby/tests/parse.sx`
|
||||
|
||||
### Phase 2 — object model + sequential eval
|
||||
- [ ] Class table bootstrap: `BasicObject`, `Object`, `Kernel`, `Module`, `Class`, `Numeric`, `Integer`, `Float`, `String`, `Symbol`, `Array`, `Hash`, `Range`, `NilClass`, `TrueClass`, `FalseClass`, `Proc`, `Method`
|
||||
- [ ] `rb-eval-ast`: literals, variables (local, ivar, cvar, gvar, constant), assignment (single and parallel `a, b = 1, 2`, splat receive), method call, message dispatch
|
||||
- [ ] Method lookup walks ancestor chain; cache hit-class per `(class, selector)`
|
||||
- [ ] `method_missing` fallback constructing args list
|
||||
- [ ] `super` and `super(args)` — lookup in defining class's superclass
|
||||
- [ ] Singleton class allocation on first `def obj.foo` or `class << obj`
|
||||
- [ ] `nil`, `true`, `false` are singletons of their classes; tagged values aren't boxed
|
||||
- [ ] Constant lookup (lexical-then-inheritance) with `Module.nesting`
|
||||
- [ ] 60+ tests in `lib/ruby/tests/eval.sx`
|
||||
|
||||
### Phase 3 — blocks + procs + lambdas
|
||||
- [ ] Method invocation captures escape continuation `^k` for `return`; binds it as block's escape
|
||||
- [ ] `yield` invokes implicit block
|
||||
- [ ] `block_given?`, `&blk` parameter, `&proc` arg unpacking
|
||||
- [ ] `Proc.new`, `proc { }`, `lambda { }` (or `->(x) { x }`)
|
||||
- [ ] Lambda strict arity + lambda-local `return` semantics
|
||||
- [ ] Proc lax arity (`a, b, c` unpacks Array; missing args nil)
|
||||
- [ ] `break`, `next`, `redo` — `break` is escape-from-loop-or-block; `next` is escape-from-block-iteration; `redo` re-runs current iteration
|
||||
- [ ] 30+ tests in `lib/ruby/tests/blocks.sx`
|
||||
|
||||
### Phase 4 — fibers (THE SHOWCASE)
|
||||
- [ ] `Fiber.new { |arg| … Fiber.yield v … }` allocates a fiber record with paired continuations
|
||||
- [ ] `Fiber.resume(args…)` resumes the fiber, returning the value passed to `Fiber.yield`
|
||||
- [ ] `Fiber.yield(v)` from inside the fiber suspends and returns control to the resumer
|
||||
- [ ] `Fiber.current` from inside the fiber
|
||||
- [ ] `Fiber#alive?`, `Fiber#raise` (deferred)
|
||||
- [ ] `Fiber.transfer` — symmetric coroutines (resume from any side)
|
||||
- [ ] Classic programs in `lib/ruby/tests/programs/`:
|
||||
- [ ] `generator.rb` — pull-style infinite enumerator built on fibers
|
||||
- [ ] `producer-consumer.rb` — bounded buffer with `Fiber.transfer`
|
||||
- [ ] `tree-walk.rb` — recursive tree walker that yields each node, driven by `Fiber.resume`
|
||||
- [ ] `lib/ruby/conformance.sh` + runner, `scoreboard.json` + `scoreboard.md`
|
||||
|
||||
### Phase 5 — modules + mixins + metaprogramming
|
||||
- [ ] `include M` — appends M's methods after class methods in chain
|
||||
- [ ] `prepend M` — prepends M before class methods
|
||||
- [ ] `extend M` — adds M to singleton class
|
||||
- [ ] `Module#ancestors`, `Module#included_modules`
|
||||
- [ ] `define_method`, `class_eval`, `instance_eval`, `module_eval`
|
||||
- [ ] `respond_to?`, `respond_to_missing?`, `method_missing`
|
||||
- [ ] `Object#send`, `Object#public_send`, `Object#__send__`
|
||||
- [ ] `Module#method_added`, `singleton_method_added` hooks
|
||||
- [ ] Hooks: `included`, `extended`, `inherited`, `prepended`
|
||||
- [ ] Internal-DSL classic program: `lib/ruby/tests/programs/dsl.rb`
|
||||
|
||||
### Phase 6 — stdlib drive
|
||||
- [ ] `Enumerable` mixin: `each` (abstract), `map`, `select`/`filter`, `reject`, `reduce`/`inject`, `each_with_index`, `each_with_object`, `take`, `drop`, `take_while`, `drop_while`, `find`/`detect`, `find_index`, `any?`, `all?`, `none?`, `one?`, `count`, `min`, `max`, `min_by`, `max_by`, `sort`, `sort_by`, `group_by`, `partition`, `chunk`, `each_cons`, `each_slice`, `flat_map`, `lazy`
|
||||
- [ ] `Comparable` mixin: `<=>`, `<`, `<=`, `>`, `>=`, `==`, `between?`, `clamp`
|
||||
- [ ] `Array`: indexing, slicing, `push`/`pop`/`shift`/`unshift`, `concat`, `flatten`, `compact`, `uniq`, `sort`, `reverse`, `zip`, `dig`, `pack`/`unpack` (deferred)
|
||||
- [ ] `Hash`: `[]`, `[]=`, `delete`, `merge`, `each_pair`, `keys`, `values`, `to_a`, `dig`, `fetch`, default values, default proc
|
||||
- [ ] `Range`: `each`, `step`, `cover?`, `include?`, `size`, `min`, `max`
|
||||
- [ ] `String`: indexing, slicing, `split`, `gsub` (string-arg version, regex deferred), `sub`, `upcase`, `downcase`, `strip`, `chomp`, `chars`, `bytes`, `to_i`, `to_f`, `to_sym`, `*`, `+`, `<<`, format with `%`
|
||||
- [ ] `Integer`: `times`, `upto`, `downto`, `step`, `digits`, `gcd`, `lcm`
|
||||
- [ ] Drive corpus to 200+ green
|
||||
|
||||
## Progress log
|
||||
|
||||
_Newest first._
|
||||
|
||||
- _(none yet)_
|
||||
|
||||
## Blockers
|
||||
|
||||
- _(none yet)_
|
||||
@@ -50,100 +50,64 @@ Core mapping:
|
||||
## Roadmap
|
||||
|
||||
### Phase 1 — tokenizer + parser
|
||||
- [x] Tokenizer: identifiers, keywords (`foo:`), binary selectors (`+`, `==`, `,`, `->`, `~=` etc.), numbers (radix `16r1F`; **scaled `1.5s2` deferred**), strings `'…''…'`, characters `$c`, symbols `#foo` `#'foo bar'` `#+`, byte arrays `#[1 2 3]` (open token), literal arrays `#(1 #foo 'x')` (open token), comments `"…"`
|
||||
- [x] Parser (expression level): blocks `[:a :b | | t1 t2 | …]`, cascades, message precedence (unary > binary > keyword), assignment, return, statement sequences, literal arrays, byte arrays, paren grouping, method headers (`+ other`, `at:put:`, unary, with temps and body). Class-definition keyword messages parse as ordinary keyword sends — no special-case needed.
|
||||
- [x] Parser (chunk-stream level): `st-read-chunks` splits source on `!` (with `!!` doubling) and `st-parse-chunks` runs the Pharo file-in state machine — `methodsFor:` / `class methodsFor:` opens a method batch, an empty chunk closes it. Pragmas `<primitive: …>` (incl. multiple keyword pairs, before or after temps, multiple per method) parsed into the method AST.
|
||||
- [x] Unit tests in `lib/smalltalk/tests/parse.sx`
|
||||
- [ ] Tokenizer: identifiers, keywords (`foo:`), binary selectors (`+`, `==`, `,`, `->`, `~=` etc.), numbers (radix `16r1F`, scaled `1.5s2`), strings `'…''…'`, characters `$c`, symbols `#foo` `#'foo bar'` `#+`, byte arrays `#[1 2 3]`, literal arrays `#(1 #foo 'x')`, comments `"…"`
|
||||
- [ ] Parser: chunk format (`! !` separators), class definitions (`Object subclass: #X instanceVariableNames: '…' classVariableNames: '…' …`), method definitions (`extend: #Foo with: 'bar ^self'`), pragmas `<primitive: 1>`, blocks `[:a :b | | t1 t2 | …]`, cascades, message precedence (unary > binary > keyword)
|
||||
- [ ] Unit tests in `lib/smalltalk/tests/parse.sx`
|
||||
|
||||
### Phase 2 — object model + sequential eval
|
||||
- [x] Class table + bootstrap (`lib/smalltalk/runtime.sx`): canonical hierarchy installed (`Object`, `Behavior`, `ClassDescription`, `Class`, `Metaclass`, `UndefinedObject`, `Boolean`/`True`/`False`, `Magnitude`/`Number`/`Integer`/`SmallInteger`/`Float`/`Character`, `Collection`/`SequenceableCollection`/`ArrayedCollection`/`Array`/`String`/`Symbol`/`OrderedCollection`/`Dictionary`, `BlockClosure`). User class definition via `st-class-define!`, methods via `st-class-add-method!` (stamps `:defining-class` for super), method lookup walks chain, ivars accumulated through superclass chain, native SX value types map to Smalltalk classes via `st-class-of`.
|
||||
- [x] `smalltalk-eval-ast` (`lib/smalltalk/eval.sx`): all literal kinds, ident resolution (locals → ivars → class refs), self/super/thisContext, assignment (locals or ivars, mutating), message send, cascade, sequence, and ^return via a sentinel marker (proper continuation-based escape is the Phase 3 showcase). Frames carry a parent chain so blocks close over outer locals. Primitive method tables for SmallInteger/Float, String/Symbol, Boolean, UndefinedObject, Array, BlockClosure (value/value:/whileTrue:/etc.), and class-side `new`/`name`/etc. Also satisfies "30+ tests" — 60 eval tests.
|
||||
- [x] Method lookup: walk class → superclass already in `st-method-lookup-walk`; new cached wrapper `st-method-lookup` keys on `(class, selector, side)` and stores `:not-found` for negative results so DNU paths don't re-walk. Cache invalidates on `st-class-define!`, `st-class-add-method!`, `st-class-add-class-method!`, `st-class-remove-method!`, and full bootstrap. Stats helpers `st-method-cache-stats` / `st-method-cache-reset-stats!` for tests + later debugging.
|
||||
- [x] `doesNotUnderstand:` fallback. `Message` class added at bootstrap with `selector`/`arguments` ivars and accessor methods. Primitive senders (Number/String/Boolean/Nil/Array/BlockClosure/class-side) now return the `:unhandled` sentinel for unknown selectors; `st-send` builds a `Message` via `st-make-message` and routes through `st-dnu`, which looks up `doesNotUnderstand:` on the receiver's class chain (instance- or class-side as appropriate). User overrides intercept unknowns and see the symbol selector + arguments array in the Message.
|
||||
- [x] `super` send. Method invocation captures the defining class on the frame; `st-super-send` walks from `(st-class-superclass defining-class)` (instance- or class-side as appropriate). Falls through primitives → DNU when no method is found. Receiver is preserved as `self`, so ivar mutations stick. Verified for: subclass override calls parent, inherited `super` resolves to *defining* class's parent (not receiver's), multi-level `A→B→C` chain, super inside a block, super walks past an intermediate class with no local override.
|
||||
- [x] 30+ tests in `lib/smalltalk/tests/eval.sx` (60 tests, covering literals through user-class method dispatch with cascades and closures)
|
||||
- [ ] Class table + bootstrap: `Object`, `Behavior`, `Class`, `Metaclass`, `UndefinedObject`, `Boolean`/`True`/`False`, `Number`/`Integer`/`Float`, `String`, `Symbol`, `Array`, `Block`
|
||||
- [ ] `smalltalk-eval-ast`: literals, variable reference, assignment, message send, cascade, sequence, return
|
||||
- [ ] Method lookup: walk class → superclass; cache hit-class on `(class, selector)`
|
||||
- [ ] `doesNotUnderstand:` fallback constructing `Message` object
|
||||
- [ ] `super` send (lookup starts at superclass of *defining* class, not receiver class)
|
||||
- [ ] 30+ tests in `lib/smalltalk/tests/eval.sx`
|
||||
|
||||
### Phase 3 — blocks + non-local return (THE SHOWCASE)
|
||||
- [x] Method invocation captures a `^k` (the return continuation) and binds it as the block's escape. `st-invoke` wraps body in `(call/cc (fn (k) ...))`; the frame's `:return-k` is set to k. Block creation copies `(get frame :return-k)` onto the block. Block invocation sets the new frame's `:return-k` to the block's saved one — so non-local return reaches *back through* any number of intermediate block invocations.
|
||||
- [x] `^expr` from inside a block invokes that captured `^k`. The "return" AST type evaluates the expression then calls `(k v)` on the frame's :return-k. Verified: `detect:in:` style early-exit, multi-level nested blocks, ^ from inside `to:do:`/`whileTrue:`, ^ from a block passed to a *different* method (Caller→Helper) returns from Caller.
|
||||
- [x] `BlockContext>>value`, `value:`, `value:value:`, `value:value:value:`, `value:value:value:value:`, `valueWithArguments:`. Implemented in `st-block-dispatch` + `st-block-apply` (eval iteration); pinned by 19 dedicated tests in `lib/smalltalk/tests/blocks.sx` covering arity through 4, valueWithArguments: with empty/non-empty arg arrays, closures over outer locals (read + mutate + later-mutation re-read), nested blocks, blocks as method arguments, `numArgs`, and `class`.
|
||||
- [x] `whileTrue:` / `whileTrue` / `whileFalse:` / `whileFalse` as ordinary block sends. `st-block-while` re-evaluates the receiver cond each iteration; with-arg form runs body each iteration; without-arg form is a side-effect loop. Now returns `nil` per ANSI/Pharo. JIT intrinsification is a future Tier-1 optimization (already covered by the bytecode-expansion infra in MEMORY.md). 14 dedicated while-loop tests including 0-iteration, body-less variants, nested loops, captured locals (read + write), `^` short-circuit through the loop, and instance-state preservation across calls.
|
||||
- [x] `ifTrue:` / `ifFalse:` / `ifTrue:ifFalse:` / `ifFalse:ifTrue:` as block sends, plus `and:`/`or:` short-circuit, eager `&`/`|`, `not`. Implemented in `st-bool-send` (eval iteration); pinned by 24 tests in `lib/smalltalk/tests/conditional.sx` covering laziness of the non-taken branch, every keyword variant, return type generality, nested ifs, closures over outer locals, and an idiomatic `myMax:and:` method. Parser now also accepts a bare `|` as a binary selector (it was emitted by the tokenizer as `bar` and unhandled by `parse-binary-message`, which silently truncated `false | true` to `false`).
|
||||
- [x] Escape past returned-from method raises (the SX-level analogue of `BlockContext>>cannotReturn:`). Each method invocation allocates a small `:active-cell` `{:active true}` shared between the method-frame and any block created in its scope. `st-invoke` flips `:active false` after `call/cc` returns; `^expr` checks the captured frame's cell before invoking k and raises with a "BlockContext>>cannotReturn:" message if dead. Verified by `lib/smalltalk/tests/cannot_return.sx` (5 tests using SX `guard` to catch the raise). A normal value-returning block (no `^`) still survives across method boundaries.
|
||||
- [x] Classic programs in `lib/smalltalk/tests/programs/`:
|
||||
- [x] `eight-queens.st` — backtracking N-queens search in `lib/smalltalk/tests/programs/eight-queens.st`. The `.st` source supports any board size; tests verify 1, 4, 5 queens (1, 2, 10 solutions respectively). 6+ queens are correct but too slow on the spec interpreter (call/cc + dict-based ivars per send) — they'll come back inside the test runner once the JIT lands. The 8-queens canonical case will run in production.
|
||||
- [x] `quicksort.st` — Lomuto-partition in-place quicksort in `lib/smalltalk/tests/programs/quicksort.st`. Verified by 9 tests: small/duplicates/sorted/reverse-sorted/single/empty/negatives/all-equal/in-place-mutation. Exercises Array `at:`/`at:put:` mutation, recursion, `to:do:` over varying ranges.
|
||||
- [x] `mandelbrot.st` — escape-time iteration of `z := z² + c` in `lib/smalltalk/tests/programs/mandelbrot.st`. Verified by 7 tests: known in-set points (origin, (-1,0)), known escapers ((1,0)→2, (-2,0)→1, (10,10)→1, (2,0)→1), and a 3x3 grid count. Caught a real bug along the way: literal `#(...)` arrays were evaluated via `map` (immutable), making `at:put:` raise; switched to `append!` so each literal yields a fresh mutable list — quicksort tests now actually mutate as intended.
|
||||
- [x] `life.st` (Conway's Life). `lib/smalltalk/tests/programs/life.st` carries the canonical rules with edge handling. Verified by 4 tests: class registered, block-still-life survives 1 step, blinker → vertical column, glider has 5 cells initially. Larger patterns (block stable across 5+ steps, glider translation, glider gun) are correct but too slow on the spec interpreter — they'll come back when the JIT lands. Also added Pharo-style dynamic array literal `{e1. e2. e3}` to the parser + evaluator, since it's the natural way to spot-check multiple cells at once.
|
||||
- [x] `fibonacci.st` (recursive + Array-memoised) — `lib/smalltalk/tests/programs/fibonacci.st`. Loaded from chunk-format source by new `smalltalk-load` helper; verified by 13 tests in `lib/smalltalk/tests/programs.sx` (recursive `fib:`, memoised `memoFib:` up to 30, instance independence, class-table integrity). Source is currently duplicated as a string in the SX test file because there's no SX file-read primitive; conformance.sh will dedupe by piping the .st file directly.
|
||||
- [x] `lib/smalltalk/conformance.sh` + runner, `scoreboard.json` + `scoreboard.md`. The runner runs `bash lib/smalltalk/test.sh -v` once, parses per-file counts, and emits both files. JSON has date / program names / corpus-test count / all-test pass/total / exit code. Markdown has a totals table, the program list, the verbatim per-file test counts block, and notes about JIT-deferred work. Both are checked into the tree as the latest baseline; the runner overwrites them.
|
||||
- [ ] Method invocation captures a `^k` (the return continuation) and binds it as the block's escape
|
||||
- [ ] `^expr` from inside a block invokes that captured `^k`
|
||||
- [ ] `BlockContext>>value`, `value:`, `value:value:`, …, `valueWithArguments:`
|
||||
- [ ] `whileTrue:` / `whileTrue` / `whileFalse:` / `whileFalse` as ordinary block sends — runtime intrinsifies the loop in the bytecode JIT
|
||||
- [ ] `ifTrue:` / `ifFalse:` / `ifTrue:ifFalse:` as block sends, similarly intrinsified
|
||||
- [ ] Escape past returned-from method raises `BlockContext>>cannotReturn:`
|
||||
- [ ] Classic programs in `lib/smalltalk/tests/programs/`:
|
||||
- [ ] `eight-queens.st`
|
||||
- [ ] `quicksort.st`
|
||||
- [ ] `mandelbrot.st`
|
||||
- [ ] `life.st` (Conway's Life, glider gun)
|
||||
- [ ] `fibonacci.st` (recursive + memoised)
|
||||
- [ ] `lib/smalltalk/conformance.sh` + runner, `scoreboard.json` + `scoreboard.md`
|
||||
|
||||
### Phase 4 — reflection + MOP
|
||||
- [x] `Object>>class`, `class>>name`, `class>>superclass`, `class>>methodDict`, `class>>selectors`. `class` is universal in `st-primitive-send` (returns `Metaclass` for class-refs, the receiver's class otherwise). Class-side dispatch gains `methodDict`/`classMethodDict` (raw dict), `selectors`/`classSelectors` (Array of symbols), `instanceVariableNames` (own), `allInstVarNames` (inherited + own). 26 tests in `lib/smalltalk/tests/reflection.sx`.
|
||||
- [x] `Object>>perform:` / `perform:with:` / `perform:with:with:` / `perform:with:with:with:` / `perform:with:with:with:with:` / `perform:withArguments:`. Universal in `st-primitive-send`; routes back through `st-send` so user methods, primitives, super, and DNU all still apply. Selector arg can be a symbol or string (we `str` it). 10 new tests in `lib/smalltalk/tests/reflection.sx`.
|
||||
- [x] `Object>>respondsTo:`, `Object>>isKindOf:`, `Object>>isMemberOf:`. Universal in `st-primitive-send`. `respondsTo:` searches user method dicts (instance- or class-side based on receiver kind); native primitive selectors aren't enumerated, documented limitation. `isKindOf:` walks `st-class-inherits-from?`; `isMemberOf:` is exact class equality. 26 new tests in `reflection.sx`.
|
||||
- [x] `Behavior>>compile:` — runtime method addition. Class-side `compile:` parses the source via `st-parse-method` and installs via `st-class-add-method!`. Sister forms `compile:classified:` and `compile:notifying:` ignore the extra arg (Pharo-tolerant). Returns the selector as a symbol. Also added `addSelector:withMethod:` (raw AST install) and `removeSelector:`. 9 new tests in `reflection.sx`.
|
||||
- [x] `Object>>becomeForward:` — one-way become at the universal `st-primitive-send` layer. Mutates the receiver's `:class` and `:ivars` to match the target via `dict-set!`; every existing reference to the receiver dict now behaves as the target. Receiver and target remain distinct dicts (no SX-level identity merge), but method dispatch, ivar reads, and aliases all switch — Pharo's practical guarantee. 6 tests in `reflection.sx`, including the alias case (`a` and `alias := a` both see the new identity).
|
||||
- [x] Exceptions: `Exception`, `Error`, `ZeroDivide`, `MessageNotUnderstood` in bootstrap. `signal` raises the receiver via SX `raise`; `signal:` sets `messageText` first. `on:do:` / `ensure:` / `ifCurtailed:` on BlockClosure use SX `guard`. The auto-reraise pattern uses a side-effect predicate (cleanup runs in the predicate, returns false → guard auto-reraises) because `(raise c)` from inside a guard handler hits a known SX issue with nested-handler frames. 15 tests in `lib/smalltalk/tests/exceptions.sx`. Phase 4 complete.
|
||||
- [ ] `Object>>class`, `class>>name`, `class>>superclass`, `class>>methodDict`, `class>>selectors`
|
||||
- [ ] `Object>>perform:` / `perform:with:` / `perform:withArguments:`
|
||||
- [ ] `Object>>respondsTo:`, `Object>>isKindOf:`, `Object>>isMemberOf:`
|
||||
- [ ] `Behavior>>compile:` — runtime method addition
|
||||
- [ ] `Object>>becomeForward:` (one-way become; rewrites the class field of `aReceiver`)
|
||||
- [ ] Exceptions: `Exception`, `Error`, `signal`, `signal:`, `on:do:`, `ensure:`, `ifCurtailed:` — built on top of SX `handler-bind`/`raise`
|
||||
|
||||
### Phase 5 — collections + numeric tower
|
||||
- [x] `SequenceableCollection`/`OrderedCollection`/`Array`/`String`/`Symbol`. Bootstrap installs shared methods on `SequenceableCollection`: `inject:into:`, `detect:`/`detect:ifNone:`, `count:`, `allSatisfy:`/`anySatisfy:`, `includes:`, `do:separatedBy:`, `indexOf:`/`indexOf:ifAbsent:`, `reject:`, `isEmpty`/`notEmpty`, `asString`. They each call `self do:`, which dispatches to the receiver's primitive `do:` — so Array, String, and Symbol inherit them uniformly. String/Symbol primitives gained `at:` (1-indexed), `copyFrom:to:`, `first`/`last`, `do:`. OrderedCollection class is in the bootstrap hierarchy; its instance shape will fill out alongside Set/Dictionary in the next box. 28 tests in `lib/smalltalk/tests/collections.sx`.
|
||||
- [x] `HashedCollection`/`Set`/`Dictionary`/`IdentityDictionary`. Implemented as user classes in `runtime.sx`. `HashedCollection` carries a single `array` ivar; `Dictionary` overrides with parallel `keys`/`values`. Set: `add:` (dedup), `addAll:`, `remove:`, `includes:`, `do:`, `size`, `asArray`. Dictionary: `at:`, `at:ifAbsent:`, `at:put:`, `includesKey:`, `removeKey:`, `keys`, `values`, `do:`, `keysDo:`, `valuesDo:`, `keysAndValuesDo:`, `size`, `isEmpty`. `IdentityDictionary` defined as a Dictionary subclass (no methods of its own yet — equality and identity diverge in a follow-up). Class-side `new` calls `super new init`. Added Array primitive `add:` (append). 29 tests in `lib/smalltalk/tests/hashed.sx`.
|
||||
- [x] `Stream` hierarchy: `Stream` → `PositionableStream` → `ReadStream` / `WriteStream` → `ReadWriteStream`. User classes with `collection` + 0-based `position` ivars. ReadStream: `next`, `peek`, `atEnd`, `upToEnd`, `next:`, `skip:`, `reset`, `position`/`position:`. WriteStream: `nextPut:`, `nextPutAll:`, `contents`. Class-side `on:` constructor; `WriteStream class>>with:` pre-fills + `setToEnd`. Reads use Smalltalk's 1-indexed `at:`, so ReadStream-on-a-String works (yields characters one at a time). 21 tests in `lib/smalltalk/tests/streams.sx`. Bumped `test.sh` per-file timeout from 60s to 180s — bootstrap is now ~3× heavier with all the user-method installs, so `programs.sx` runs in ~64s.
|
||||
- [x] `Number` tower: `SmallInteger`/`LargePositiveInteger`/`Float`/`Fraction`. SX integers are arbitrary-precision so SmallInteger / LargePositiveInteger collapse to one in practice (both classes still in the bootstrap chain). Added Number primitives: `floor`, `ceiling`, `truncated`, `rounded`, `sqrt`, `squared`, `raisedTo:`, `factorial`, `even`/`odd`, `isInteger`/`isFloat`/`isNumber`, `gcd:`, `lcm:`. **Fraction** now a real user class (numerator/denominator + sign-normalised, gcd-reduced at construction): `numerator:denominator:`, accessors, `+`/`-`/`*`/`/`, `negated`, `reciprocal`, `=`, `<`, `asFloat`, `printString`, `isFraction`. 47 tests in `lib/smalltalk/tests/numbers.sx`.
|
||||
- [x] `String>>format:`, `printOn:` for everything. `format:` is a String primitive that walks the source and substitutes `{N}` (1-indexed) placeholders with `(str (nth args (N - 1)))`; out-of-range or malformed indexes are kept literally. `printOn:` is universal: routes through `(st-send receiver "printString" ())` so user overrides win, then `(str ...)` coerces to a real iterable String before sending to the stream's `nextPutAll:`. `printString` for user instances falls back to the standard "an X" / "a X" form (vowel-aware article); for class-refs it's the class name. 18 tests in `lib/smalltalk/tests/printing.sx`. Phase 5 complete.
|
||||
- [ ] `SequenceableCollection`/`OrderedCollection`/`Array`/`String`/`Symbol`
|
||||
- [ ] `HashedCollection`/`Set`/`Dictionary`/`IdentityDictionary`
|
||||
- [ ] `Stream` hierarchy: `ReadStream`/`WriteStream`/`ReadWriteStream`
|
||||
- [ ] `Number` tower: `SmallInteger`/`LargePositiveInteger`/`Float`/`Fraction`
|
||||
- [ ] `String>>format:`, `printOn:` for everything
|
||||
|
||||
### Phase 6 — SUnit + corpus to 200+
|
||||
- [x] Port SUnit (`lib/smalltalk/sunit.sx`). Written in Smalltalk source via `smalltalk-load`. Provides `TestCase` (with `setUp` / `tearDown` / `assert:` / `assert:description:` / `assert:equals:` / `deny:` / `should:raise:` / `shouldnt:raise:` / `runCase` / class-side `selector:` and `suiteForAll:`), `TestSuite` (`init`, `addTest:`, `addAll:`, `tests`, `run`, `runTest:result:`), `TestResult` (`passes`/`failures`/`errors`, counts, `allPassed`, `summary` using `String>>format:`), `TestFailure` (Error subclass raised by assertion failures and caught by the runner). 19 tests in `lib/smalltalk/tests/sunit.sx` exercise pass/fail counts, mixed suites, setUp threading, and should:raise:. test.sh now loads `lib/smalltalk/sunit.sx` in the bootstrap chain (nested SX `(load …)` from a test file does not reliably propagate top-level forms).
|
||||
- [x] Vendor a slice of Pharo `Kernel-Tests` and `Collections-Tests`. `lib/smalltalk/tests/pharo/kernel.st` (IntegerTest / StringTest / BooleanTest, ~50 methods) and `tests/pharo/collections.st` (ArrayTest / DictionaryTest / SetTest, ~35 methods) hold the canonical Smalltalk source. `lib/smalltalk/tests/pharo.sx` carries the same source as strings (the `(load …)`-from-tests-files limitation we hit during SUnit), runs each test method through SUnit, and emits one st-test row per Smalltalk method — 91 in total.
|
||||
- [x] Drive the scoreboard up: aim for 200+ green tests. **751 green** at this point — past the target by 3.7x.
|
||||
- [x] Stretch: ANSI Smalltalk validator subset (`lib/smalltalk/tests/ansi.sx`). 62 tests organised by ANSI X3J20 §6.10 Object, §6.11 Boolean, §6.12 Number, §6.13 Integer, §6.16 Symbol, §6.17 String, §6.18 Array, §6.19 BlockContext. Each test runs through SUnit and emits one st-test row, mirroring the Pharo-slice harness.
|
||||
- [ ] Port SUnit (TestCase, TestSuite, TestResult) — written in SX-Smalltalk, runs in itself
|
||||
- [ ] Vendor a slice of Pharo `Kernel-Tests` and `Collections-Tests`
|
||||
- [ ] Drive the scoreboard up: aim for 200+ green tests
|
||||
- [ ] Stretch: ANSI Smalltalk validator subset
|
||||
|
||||
### Phase 7 — speed (optional)
|
||||
- [x] Method-dictionary inline caching. Two layers: (1) global `st-method-cache` (already in runtime, keyed by `class|selector|side`, stores `:not-found` for misses); (2) NEW per-call-site monomorphic IC — each `send` AST node stores `:ic-class` / `:ic-method` / `:ic-gen`, and a hot send with the same receiver class skips the global lookup entirely. `st-ic-generation` (in runtime.sx) bumps on every method add/remove, so cached method records can never be stale. `st-ic-stats` / `st-ic-reset-stats!` for tests + later debugging. 10 dedicated IC tests in `lib/smalltalk/tests/inline_cache.sx`.
|
||||
- [x] Block intrinsification beyond `whileTrue:` / `ifTrue:`. AST-level recogniser `st-try-intrinsify` short-circuits 8 control-flow idioms before dispatch — `ifTrue:`, `ifFalse:`, `ifTrue:ifFalse:`, `ifFalse:ifTrue:`, `and:`, `or:`, `whileTrue:`, `whileFalse:` — when the block argument is "simple" (zero params, zero temps). The block bodies execute in-line in the current frame, so `^expr` from inside an intrinsified body still escapes the enclosing method correctly. `st-intrinsic-stats` / `st-intrinsic-reset!` for tests + later debugging. 24 tests in `lib/smalltalk/tests/intrinsics.sx`. Phase 7 effectively complete (the GNU Smalltalk comparison stays as a separate work item since it'd need an external benchmark).
|
||||
- [x] Compare against GNU Smalltalk on the corpus. `lib/smalltalk/compare.sh` runs a fibonacci(22) benchmark on both Smalltalk-on-SX (`sx_server.exe` + smalltalk-load + eval) and GNU Smalltalk (`gst -q`), emits a `compare-results.txt`. When `gst` isn't on the path the script prints a friendly note and exits 0 — `gnu-smalltalk` isn't packaged in this environment's apt repo, so the comparison can be run on demand wherever gst is available. **Phase 7 complete.**
|
||||
- [ ] Method-dictionary inline caching (already in CEK as a primitive; just wire selector cache)
|
||||
- [ ] Block intrinsification beyond `whileTrue:` / `ifTrue:`
|
||||
- [ ] Compare against GNU Smalltalk on the corpus
|
||||
|
||||
## Progress log
|
||||
|
||||
_Newest first. Agent appends on every commit._
|
||||
|
||||
- 2026-04-25: GNU Smalltalk compare harness (`lib/smalltalk/compare.sh`) — runs fib(22) on sx_server.exe + smalltalk-load and on `gst -q`, saves results. Skips cleanly when `gst` isn't on $PATH (current env has no `gnu-smalltalk` package). **Phase 7 complete. All briefing checkboxes done.**
|
||||
- 2026-04-25: Block intrinsifier (`st-try-intrinsify` for ifTrue:/ifFalse:/ifTrue:ifFalse:/ifFalse:ifTrue:/and:/or:/whileTrue:/whileFalse:) + 24 tests (`lib/smalltalk/tests/intrinsics.sx`). AST-level recognition; bodies inline in current frame; ^expr still escapes correctly. 847/847 total.
|
||||
- 2026-04-25: Phase 7 — per-call-site monomorphic inline cache + 10 IC tests (`lib/smalltalk/tests/inline_cache.sx`). `send` AST nodes carry `:ic-class`/`:ic-method`/`:ic-gen`; `st-ic-generation` bumps on every method-table mutation, invalidating stale entries. 823/823 total.
|
||||
- 2026-04-25: ANSI X3J20 validator subset + 62 tests (`lib/smalltalk/tests/ansi.sx`). One TestCase subclass per ANSI §6.x protocol; runs through SUnit. **Phase 6 complete.** 813/813 total.
|
||||
- 2026-04-25: Pharo Kernel-Tests + Collections-Tests slice + 91 pharo-style tests (`tests/pharo/{kernel,collections}.st` + `tests/pharo.sx`). Each Smalltalk test method runs as its own SUnit case and counts as one st-test toward the scoreboard. 751/751 total — past the Phase 6 "200+ green tests" target.
|
||||
- 2026-04-25: SUnit port (`lib/smalltalk/sunit.sx`, `lib/smalltalk/tests/sunit.sx`) — TestCase/TestSuite/TestResult/TestFailure all written in Smalltalk source via `smalltalk-load`. Full assert family + should:raise: + setUp/tearDown threading. 19 tests verify the framework. test.sh now bootstraps SUnit alongside runtime/eval. 660/660 total.
|
||||
- 2026-04-25: String>>format: + universal printOn: + 18 tests (`lib/smalltalk/tests/printing.sx`). `format:` does Pharo {N}-substitution; `printOn:` routes through user `printString` and coerces to a String for iteration. Phase 5 complete. 638/638 total.
|
||||
- 2026-04-25: Number tower + Fraction class + 47 tests (`lib/smalltalk/tests/numbers.sx`). 14 new Number primitives (floor/ceiling/truncated/rounded/sqrt/squared/raisedTo:/factorial/even/odd/gcd:/lcm:/isInteger/isFloat). Fraction with normalisation + arithmetic + comparisons + asFloat. 620/620 total.
|
||||
- 2026-04-25: Stream hierarchy + 21 tests (`lib/smalltalk/tests/streams.sx`). ReadStream / WriteStream / ReadWriteStream as user classes; class-side `on:`; ReadStream-on-String yields characters. Bumped `test.sh` per-file timeout 60s → 180s — heavier bootstrap pushed `programs.sx` past 60s. 573/573 total.
|
||||
- 2026-04-25: HashedCollection / Set / Dictionary / IdentityDictionary + 29 tests (`lib/smalltalk/tests/hashed.sx`). Set: dedup add:, remove:, includes:, do:, addAll:. Dictionary: parallel keys/values backing; at:put:, at:ifAbsent:, includesKey:, removeKey:, keysDo:, keysAndValuesDo:. Class-side `new` chains `super new init`. Array primitive `add:` added. 552/552 total.
|
||||
- 2026-04-25: Phase 5 sequenceable-collection methods + 28 tests (`lib/smalltalk/tests/collections.sx`). 13 shared methods on `SequenceableCollection` (inject:into:, detect:, count:, …), inherited by Array/String/Symbol via `self do:`. String primitives at:/copyFrom:to:/first/last/do:. 523/523 total.
|
||||
- 2026-04-25: Exception system + 15 tests (`lib/smalltalk/tests/exceptions.sx`). Exception/Error/ZeroDivide/MessageNotUnderstood in bootstrap; signal/signal: raise via SX `raise`; on:do:/ensure:/ifCurtailed: on BlockClosure via SX `guard`. Phase 4 complete. 495/495 total.
|
||||
- 2026-04-25: `Object>>becomeForward:` + 6 tests. In-place mutation of `:class` and `:ivars` via `dict-set!`; aliases see the new identity. 480/480 total.
|
||||
- 2026-04-25: `Behavior>>compile:` + sisters + 9 tests. Parses source via `st-parse-method`, installs via runtime helpers; also added `addSelector:withMethod:` and `removeSelector:`. 474/474 total.
|
||||
- 2026-04-25: `respondsTo:` / `isKindOf:` / `isMemberOf:` + 26 tests. Universal at `st-primitive-send`. 465/465 total.
|
||||
- 2026-04-25: `Object>>perform:` family + 10 tests. Universal dispatch via `st-send` after `(str (nth args 0))` for the selector. 439/439 total.
|
||||
- 2026-04-25: Phase 4 reflection accessors (`lib/smalltalk/tests/reflection.sx`, 26 tests). Universal `Object>>class`, plus `methodDict`/`selectors`/`instanceVariableNames`/`allInstVarNames`/`classMethodDict`/`classSelectors` on class-refs. 429/429 total.
|
||||
- 2026-04-25: conformance.sh + scoreboard.{json,md} (`lib/smalltalk/conformance.sh`, `lib/smalltalk/scoreboard.json`, `lib/smalltalk/scoreboard.md`). Single-pass runner over `test.sh -v`; baseline at 5 programs / 39 corpus tests / 403 total. **Phase 3 complete.**
|
||||
- 2026-04-25: classic-corpus #5 Life (`tests/programs/life.st`, 4 tests). Spec-interpreter Conway's Life with edge handling. Block + blinker + glider initial setup verified; larger step counts pending JIT (each spec-interpreter step is ~5-8s on a 5x5 grid). Added `{e1. e2. e3}` dynamic array literal to parser + evaluator. 403/403 total.
|
||||
- 2026-04-25: classic-corpus #4 mandelbrot (`tests/programs/mandelbrot.st`, 7 tests). Escape-time iterator + grid counter. Discovered + fixed an immutable-list bug in `lit-array` eval — `map` produced an immutable list so `at:put:` raised; rebuilt via `append!`. Quicksort tests had been silently dropping ~7 cases due to that bug; now actually mutate. 399/399 total.
|
||||
- 2026-04-25: classic-corpus #3 quicksort (`tests/programs/quicksort.st`, 9 tests). Lomuto partition; verified across duplicates, already-sorted/reverse-sorted, empty, single, negatives, all-equal, plus in-place mutation. 385/385 total.
|
||||
- 2026-04-25: classic-corpus #2 eight-queens (`tests/programs/eight-queens.st`, 5 tests). Backtracking search; verified for boards of size 1, 4, 5. Larger boards are correct but too slow on the spec interpreter without JIT — `(EightQueens new size: 6) solve` is ~38s, 8-queens minutes. 382/382 total.
|
||||
- 2026-04-25: classic-corpus #1 fibonacci (`tests/programs/fibonacci.st` + `tests/programs.sx`, 13 tests). Added `smalltalk-load` chunk loader, class-side `subclass:instanceVariableNames:` (and longer Pharo variants), `Array new:` size, `methodsFor:`/`category:` no-ops, `st-split-ivars`. 377/377 total.
|
||||
- 2026-04-25: cannotReturn: implemented (`lib/smalltalk/tests/cannot_return.sx`, 5 tests). Each method-invocation gets an `{:active true}` cell shared with its blocks; `st-invoke` flips it on exit; `^expr` raises if the cell is dead. Tests use SX `guard` to catch the raise. Non-`^` blocks unaffected. 364/364 total.
|
||||
- 2026-04-25: `ifTrue:` / `ifFalse:` family pinned (`lib/smalltalk/tests/conditional.sx`, 24 tests) + parser fix: `|` is now accepted as a binary selector in expression position (tokenizer still emits it as `bar` for block param/temp delimiting; `parse-binary-message` accepts both). Caught by `false | true` truncating silently to `false`. 359/359 total.
|
||||
- 2026-04-25: `whileTrue:` / `whileFalse:` / no-arg variants pinned (`lib/smalltalk/tests/while.sx`, 14 tests). `st-block-while` returns nil per ANSI; behaviour verified under captured locals, nesting, early `^`, and zero/many iterations. 334/334 total.
|
||||
- 2026-04-25: BlockContext value family pinned (`lib/smalltalk/tests/blocks.sx`, 19 tests). Each value/valueN/valueWithArguments: variant verified plus closure semantics (read, write, later-mutation re-read), nested blocks, and block-as-arg. 320/320 total.
|
||||
- 2026-04-25: **THE SHOWCASE** — non-local return via captured method-return continuations + 14 NLR tests (`lib/smalltalk/tests/nlr.sx`). `st-invoke` wraps body in `call/cc`; blocks copy creating method's `^k`; `^expr` invokes that k. Verified across nested blocks, `to:do:` / `whileTrue:`, blocks passed to different methods (Caller→Helper escapes back to Caller), inner-vs-outer method nesting. Sentinel-based return removed. 301/301 total.
|
||||
- 2026-04-25: `super` send + 9 tests (`lib/smalltalk/tests/super.sx`). `st-super-send` walks from defining-class's superclass; class-side aware; primitives → DNU fallback. Also fixed top-level `| temps |` parsing in `st-parse` (the absence of which was silently aborting earlier eval/dnu tests — counts go from 274 → 287, with previously-skipped tests now actually running).
|
||||
- 2026-04-25: `doesNotUnderstand:` + 12 DNU tests (`lib/smalltalk/tests/dnu.sx`). Bootstrap installs `Message` (with selector/arguments accessors). Primitives signal `:unhandled` instead of erroring; `st-dnu` builds a Message and walks `doesNotUnderstand:` lookup. User Object DNU intercepts unknown sends to native receivers (Number, String, Block) too. 267/267 total.
|
||||
- 2026-04-25: method-lookup cache (`st-method-cache` keyed by `class|selector|side`, stores `:not-found` for misses). Invalidation on define/add/remove + bootstrap. `st-class-remove-method!` added. Stats helpers + 10 cache tests; 255/255 total.
|
||||
- 2026-04-25: `smalltalk-eval-ast` + 60 eval tests (`lib/smalltalk/eval.sx`, `lib/smalltalk/tests/eval.sx`). Frame chain with mutable locals/ivars (via `dict-set!`), full literal eval, send dispatch (user methods + native primitive tables for Number/String/Boolean/Nil/Array/Block/Class), block closures, while/to:do:, cascades returning last, sentinel-based `^return`. User Point class round-trip works including `+` returning a fresh point. 245/245 total.
|
||||
- 2026-04-25: class table + bootstrap (`lib/smalltalk/runtime.sx`, `lib/smalltalk/tests/runtime.sx`). Canonical hierarchy, type→class mapping for native SX values, instance construction, ivar inheritance, method install with `:defining-class` stamp, instance- and class-side method lookup walking the superclass chain. 54 new tests, 185/185 total.
|
||||
- 2026-04-25: chunk-stream parser + pragmas + 21 chunk/pragma tests (`lib/smalltalk/tests/parse_chunks.sx`). `st-read-chunks` (with `!!` doubling), `st-parse-chunks` state machine for `methodsFor:` batches incl. class-side. Pragmas with multiple keyword pairs, signed numeric / string / symbol args, in either pragma-then-temps or temps-then-pragma order. 131/131 tests pass.
|
||||
- 2026-04-25: expression-level parser + 47 parse tests (`lib/smalltalk/parser.sx`, `lib/smalltalk/tests/parse.sx`). Full message precedence (unary > binary > keyword), cascades, blocks with params/temps, literal/byte arrays, assignment chain, method headers (unary/binary/keyword). Chunk-format `! !` driver deferred to a follow-up box. 110/110 tests pass.
|
||||
- 2026-04-25: tokenizer + 63 tests (`lib/smalltalk/tokenizer.sx`, `lib/smalltalk/tests/tokenize.sx`, `lib/smalltalk/test.sh`). All token types covered except scaled decimals `1.5s2` (deferred). `#(` and `#[` emit open tokens; literal-array contents lexed as ordinary tokens for the parser to interpret.
|
||||
- _(none yet)_
|
||||
|
||||
## Blockers
|
||||
|
||||
|
||||
127
plans/tcl-on-sx.md
Normal file
127
plans/tcl-on-sx.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# Tcl-on-SX: uplevel/upvar = stack-walking delcc, everything-is-a-string
|
||||
|
||||
The headline showcase is **uplevel/upvar** — Tcl's superpower for defining your own control structures. `uplevel` evaluates a script in the *caller's* stack frame; `upvar` aliases a variable in the caller. On a normal language host this requires deep VM cooperation; on SX it falls out of the env-chain made first-class via captured continuations. Plus the *Dodekalogue* (12 rules), command-substitution everywhere, and "everything is a string" homoiconicity.
|
||||
|
||||
End-state goal: Tcl 8.6-flavoured subset, the Dodekalogue parser, namespaces, `try`/`catch`/`return -code`, `coroutine` (built on fibers), classic programs that show off uplevel-driven DSLs, ~150 hand-written tests.
|
||||
|
||||
## Scope decisions (defaults — override by editing before we spawn)
|
||||
|
||||
- **Syntax:** Tcl 8.6 surface. The 12-rule Dodekalogue. Brace-quoted scripts deferred-evaluate; double-quoted ones substitute.
|
||||
- **Conformance:** "Reads like Tcl, runs like Tcl." Slice of Tcl's own test suite, not full TCT.
|
||||
- **Test corpus:** custom + curated `tcl-tests/` slice. Plus classic programs: define-your-own `for-each-line`, expression-language compiler-in-Tcl, fiber-based event loop.
|
||||
- **Out of scope:** Tk, sockets beyond a stub, threads (mapped to `coroutine` only), `package require` of binary loadables, `dde`/`registry` Windows shims, full `clock format` locale support.
|
||||
- **Channels:** `puts` and `gets` on `stdout`/`stdin`/`stderr`; `open` on regular files; no async I/O beyond what `coroutine` gives.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- **Scope:** only touch `lib/tcl/**` and `plans/tcl-on-sx.md`. Don't edit `spec/`, `hosts/`, `shared/`, or any other `lib/<lang>/**`. Tcl primitives go in `lib/tcl/runtime.sx`.
|
||||
- **SX files:** use `sx-tree` MCP tools only.
|
||||
- **Commits:** one feature per commit. Keep `## Progress log` updated and tick roadmap boxes.
|
||||
|
||||
## Architecture sketch
|
||||
|
||||
```
|
||||
Tcl source
|
||||
│
|
||||
▼
|
||||
lib/tcl/tokenizer.sx — the Dodekalogue: words, [..], ${..}, "..", {..}, ;, \n, \, #
|
||||
│
|
||||
▼
|
||||
lib/tcl/parser.sx — list-of-words AST (script = list of commands; command = list of words)
|
||||
│
|
||||
▼
|
||||
lib/tcl/transpile.sx — AST → SX AST (entry: tcl-eval-script)
|
||||
│
|
||||
▼
|
||||
lib/tcl/runtime.sx — env stack, command table, uplevel/upvar, coroutines, BIFs
|
||||
```
|
||||
|
||||
Core mapping:
|
||||
- **Value** = string. Internally we cache a "shimmer" representation (list, dict, integer, double) for performance, but every value can be re-stringified.
|
||||
- **Variable** = entry in current frame's env. Frames form a stack; level-0 is the global frame.
|
||||
- **Command** = entry in command table; first word of any list dispatches into it. User-defined via `proc`. Built-ins are SX functions registered in the table.
|
||||
- **Frame** = `{:locals (dict) :level n :parent frame}`. Each `proc` call pushes a frame; commands run in current frame.
|
||||
- **`uplevel #N script`** = walk frame chain to absolute level N (or relative if no `#`); evaluate script in that frame's env.
|
||||
- **`upvar [#N] varname localname`** = bind `localname` in the current frame as an alias to `varname` in the level-N frame (env-chain delegate).
|
||||
- **`return -code N`** = control flow as integers: 0=ok, 1=error, 2=return, 3=break, 4=continue. `catch` traps any non-zero; `try` adds named handlers.
|
||||
- **`coroutine`** = fiber on top of `perform`/`cek-resume`. `yield`/`yieldto` suspend; calling the coroutine command resumes.
|
||||
- **List / dict** = list-shaped string ("element1 element2 …") with a cached parsed form. Modifications dirty the string cache.
|
||||
|
||||
## Roadmap
|
||||
|
||||
### Phase 1 — tokenizer + parser (the Dodekalogue)
|
||||
- [ ] Tokenizer applying the 12 rules:
|
||||
1. Commands separated by `;` or newlines
|
||||
2. Words separated by whitespace within a command
|
||||
3. Double-quoted words: `\` escapes + `[…]` + `${…}` + `$var` substitution
|
||||
4. Brace-quoted words: literal, no substitution; brace count must balance
|
||||
5. Argument expansion: `{*}list`
|
||||
6. Command substitution: `[script]` evaluates script, takes its return value
|
||||
7. Variable substitution: `$name`, `${name}`, `$arr(idx)`, `$arr($i)`
|
||||
8. Backslash substitution: `\n`, `\t`, `\\`, `\xNN`, `\uNNNN`, `\<newline>` continues
|
||||
9. Comments: `#` only at the start of a command
|
||||
10. Order of substitution is left-to-right, single-pass
|
||||
11. Substitutions don't recurse — substituted text is not re-parsed
|
||||
12. The result of any substitution is the value, not a new script
|
||||
- [ ] Parser: script = list of commands; command = list of words; word = literal string + list of substitutions
|
||||
- [ ] Unit tests in `lib/tcl/tests/parse.sx`
|
||||
|
||||
### Phase 2 — sequential eval + core commands
|
||||
- [ ] `tcl-eval-script`: walk command list, dispatch each first-word into command table
|
||||
- [ ] Core commands: `set`, `unset`, `incr`, `append`, `lappend`, `puts`, `gets`, `expr`, `if`, `while`, `for`, `foreach`, `switch`, `break`, `continue`, `return`, `error`, `eval`, `subst`, `format`, `scan`
|
||||
- [ ] `expr` is its own mini-language — operator precedence, function calls (`sin`, `sqrt`, `pow`, `abs`, `int`, `double`), variable substitution, command substitution
|
||||
- [ ] String commands: `string length`, `string index`, `string range`, `string compare`, `string match`, `string toupper`, `string tolower`, `string trim`, `string map`, `string repeat`, `string first`, `string last`, `string is`, `string cat`
|
||||
- [ ] List commands: `list`, `lindex`, `lrange`, `llength`, `lreverse`, `lsearch`, `lsort`, `lsort -integer/-real/-dictionary`, `lreplace`, `linsert`, `concat`, `split`, `join`
|
||||
- [ ] Dict commands: `dict create`, `dict get`, `dict set`, `dict unset`, `dict exists`, `dict keys`, `dict values`, `dict size`, `dict for`, `dict update`, `dict merge`
|
||||
- [ ] 60+ tests in `lib/tcl/tests/eval.sx`
|
||||
|
||||
### Phase 3 — proc + uplevel + upvar (THE SHOWCASE)
|
||||
- [ ] `proc name args body` — register user-defined command; args supports defaults `{name default}` and rest `args`
|
||||
- [ ] Frame stack: each proc call pushes a frame with locals dict; pop on return
|
||||
- [ ] `uplevel ?level? script` — evaluate `script` in level-N frame's env; default level is 1 (caller). `#0` is global, `#1` is relative-1
|
||||
- [ ] `upvar ?level? otherVar localVar ?…?` — alias localVar to a variable in level-N frame; reads/writes go through the alias
|
||||
- [ ] `info level`, `info level N`, `info frame`, `info vars`, `info locals`, `info globals`, `info commands`, `info procs`, `info args`, `info body`
|
||||
- [ ] `global var ?…?` — alias to global frame (sugar for `upvar #0 var var`)
|
||||
- [ ] `variable name ?value?` — namespace-scoped global
|
||||
- [ ] Classic programs in `lib/tcl/tests/programs/`:
|
||||
- [ ] `for-each-line.tcl` — define your own loop construct using `uplevel`
|
||||
- [ ] `assert.tcl` — assertion macro that reports caller's line
|
||||
- [ ] `with-temp-var.tcl` — scoped variable rebind via `upvar`
|
||||
- [ ] `lib/tcl/conformance.sh` + runner, `scoreboard.json` + `scoreboard.md`
|
||||
|
||||
### Phase 4 — control flow + error handling
|
||||
- [ ] `return -code (ok|error|return|break|continue|N) -errorinfo … -errorcode … -level N value`
|
||||
- [ ] `catch script ?resultVar? ?optionsVar?` — runs script, returns code; sets resultVar to return value/message; optionsVar to the dict
|
||||
- [ ] `try script ?on code var body ...? ?trap pattern var body...? ?finally body?`
|
||||
- [ ] `throw type message`
|
||||
- [ ] `error message ?info? ?code?`
|
||||
- [ ] Stack-trace with `errorInfo` / `errorCode`
|
||||
- [ ] 30+ tests in `lib/tcl/tests/error.sx`
|
||||
|
||||
### Phase 5 — namespaces + ensembles
|
||||
- [ ] `namespace eval ns body`, `namespace current`, `namespace which`, `namespace import`, `namespace export`, `namespace forget`, `namespace delete`
|
||||
- [ ] Qualified names: `::ns::cmd`, `::ns::var`
|
||||
- [ ] Ensembles: `namespace ensemble create -map { sub1 cmd1 sub2 cmd2 }`
|
||||
- [ ] `namespace path` for resolution chain
|
||||
- [ ] `proc` and `variable` work inside namespaces
|
||||
|
||||
### Phase 6 — coroutines + drive corpus
|
||||
- [ ] `coroutine name cmd ?args…?` — start a coroutine; future calls to `name` resume it
|
||||
- [ ] `yield ?value?` — suspend, return value to resumer
|
||||
- [ ] `yieldto cmd ?args…?` — symmetric transfer
|
||||
- [ ] `coroutine` semantics built on fibers (same delcc primitive as Ruby fibers)
|
||||
- [ ] Classic programs: `event-loop.tcl` — cooperative scheduler with multiple coroutines
|
||||
- [ ] System: `clock seconds`, `clock format`, `clock scan` (subset)
|
||||
- [ ] File I/O: `open`, `close`, `read`, `gets`, `puts -nonewline`, `flush`, `eof`, `seek`, `tell`
|
||||
- [ ] Drive corpus to 150+ green
|
||||
- [ ] Idiom corpus — `lib/tcl/tests/idioms.sx` covering classic Welch/Jones idioms
|
||||
|
||||
## Progress log
|
||||
|
||||
_Newest first._
|
||||
|
||||
- _(none yet)_
|
||||
|
||||
## Blockers
|
||||
|
||||
- _(none yet)_
|
||||
@@ -30,7 +30,7 @@ fi
|
||||
|
||||
if [ "$CLEAN" = "1" ]; then
|
||||
cd "$(dirname "$0")/.."
|
||||
for lang in lua prolog forth erlang haskell js hs smalltalk; do
|
||||
for lang in lua prolog forth erlang haskell js hs smalltalk common-lisp apl ruby tcl; do
|
||||
wt="$WORKTREE_BASE/$lang"
|
||||
if [ -d "$wt" ]; then
|
||||
git worktree remove --force "$wt" 2>/dev/null || rm -rf "$wt"
|
||||
@@ -39,5 +39,5 @@ if [ "$CLEAN" = "1" ]; then
|
||||
done
|
||||
git worktree prune
|
||||
echo "Worktree branches (loops/<lang>) are preserved. Delete manually if desired:"
|
||||
echo " git branch -D loops/lua loops/prolog loops/forth loops/erlang loops/haskell loops/js loops/hs loops/smalltalk"
|
||||
echo " git branch -D loops/lua loops/prolog loops/forth loops/erlang loops/haskell loops/js loops/hs loops/smalltalk loops/common-lisp loops/apl loops/ruby loops/tcl"
|
||||
fi
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Spawn 8 claude sessions in tmux, one per language loop.
|
||||
# Spawn 12 claude sessions in tmux, one per language loop.
|
||||
# Each runs in its own git worktree rooted at /root/rose-ash-loops/<lang>,
|
||||
# on branch loops/<lang>. No two loops share a working tree, so there's
|
||||
# zero risk of file collisions between languages.
|
||||
@@ -9,7 +9,7 @@
|
||||
#
|
||||
# After the script prints done:
|
||||
# tmux a -t sx-loops
|
||||
# Ctrl-B + <window-number> to switch (0=lua ... 7=smalltalk)
|
||||
# Ctrl-B + <window-number> to switch (0=lua ... 11=tcl)
|
||||
# Ctrl-B + d to detach (loops keep running, SSH-safe)
|
||||
#
|
||||
# Stop: ./scripts/sx-loops-down.sh
|
||||
@@ -39,8 +39,12 @@ declare -A BRIEFING=(
|
||||
[js]=loop.md
|
||||
[hs]=hs-loop.md
|
||||
[smalltalk]=smalltalk-loop.md
|
||||
[common-lisp]=common-lisp-loop.md
|
||||
[apl]=apl-loop.md
|
||||
[ruby]=ruby-loop.md
|
||||
[tcl]=tcl-loop.md
|
||||
)
|
||||
ORDER=(lua prolog forth erlang haskell js hs smalltalk)
|
||||
ORDER=(lua prolog forth erlang haskell js hs smalltalk common-lisp apl ruby tcl)
|
||||
|
||||
mkdir -p "$WORKTREE_BASE"
|
||||
|
||||
@@ -61,13 +65,13 @@ for lang in "${ORDER[@]}"; do
|
||||
fi
|
||||
done
|
||||
|
||||
# Create tmux session with 7 windows, each cwd in its worktree
|
||||
# Create tmux session with one window per language, each cwd in its worktree
|
||||
tmux new-session -d -s "$SESSION" -n "${ORDER[0]}" -c "$WORKTREE_BASE/${ORDER[0]}"
|
||||
for lang in "${ORDER[@]:1}"; do
|
||||
tmux new-window -t "$SESSION" -n "$lang" -c "$WORKTREE_BASE/$lang"
|
||||
done
|
||||
|
||||
echo "Starting 8 claude sessions..."
|
||||
echo "Starting ${#ORDER[@]} claude sessions..."
|
||||
for lang in "${ORDER[@]}"; do
|
||||
tmux send-keys -t "$SESSION:$lang" "claude" C-m
|
||||
done
|
||||
@@ -90,10 +94,10 @@ for lang in "${ORDER[@]}"; do
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Done. 8 loops started in tmux session '$SESSION', each in its own worktree."
|
||||
echo "Done. ${#ORDER[@]} loops started in tmux session '$SESSION', each in its own worktree."
|
||||
echo ""
|
||||
echo " Attach: tmux a -t $SESSION"
|
||||
echo " Switch: Ctrl-B <0..7> (0=lua 1=prolog 2=forth 3=erlang 4=haskell 5=js 6=hs 7=smalltalk)"
|
||||
echo " Switch: Ctrl-B <0..11> (0=lua 1=prolog 2=forth 3=erlang 4=haskell 5=js 6=hs 7=smalltalk 8=common-lisp 9=apl 10=ruby 11=tcl)"
|
||||
echo " List: Ctrl-B w"
|
||||
echo " Detach: Ctrl-B d"
|
||||
echo " Stop: ./scripts/sx-loops-down.sh"
|
||||
|
||||
121
scripts/sx-primitives-up.sh
Executable file
121
scripts/sx-primitives-up.sh
Executable file
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env bash
|
||||
# Spawn a single claude session to implement SX primitives in sequence.
|
||||
# Runs in its own git worktree on branch sx-primitives from architecture.
|
||||
#
|
||||
# Usage: ./scripts/sx-primitives-up.sh [interval]
|
||||
# interval defaults to self-paced (omit to let model decide)
|
||||
#
|
||||
# After the script prints done:
|
||||
# tmux a -t sx-primitives
|
||||
# Ctrl-B + d to detach
|
||||
#
|
||||
# Stop: ./scripts/sx-primitives-down.sh
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
SESSION="sx-primitives"
|
||||
WORKTREE="$ROOT" # runs in the main worktree — architecture branch
|
||||
BRANCH="architecture"
|
||||
INTERVAL="${1:-}"
|
||||
BOOT_WAIT=20
|
||||
|
||||
if tmux has-session -t "$SESSION" 2>/dev/null; then
|
||||
echo "Session '$SESSION' already exists."
|
||||
echo " Attach: tmux a -t $SESSION"
|
||||
echo " Kill: ./scripts/sx-primitives-down.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Write settings into the main worktree .claude dir
|
||||
SETTINGS_DIR="$ROOT/.claude"
|
||||
mkdir -p "$SETTINGS_DIR"
|
||||
cat > "$SETTINGS_DIR/settings.local.json" <<'SETTINGS'
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__sx-tree__sx_summarise",
|
||||
"mcp__sx-tree__sx_read_tree",
|
||||
"mcp__sx-tree__sx_read_subtree",
|
||||
"mcp__sx-tree__sx_get_context",
|
||||
"mcp__sx-tree__sx_find_all",
|
||||
"mcp__sx-tree__sx_find_across",
|
||||
"mcp__sx-tree__sx_get_siblings",
|
||||
"mcp__sx-tree__sx_validate",
|
||||
"mcp__sx-tree__sx_replace_node",
|
||||
"mcp__sx-tree__sx_insert_child",
|
||||
"mcp__sx-tree__sx_insert_near",
|
||||
"mcp__sx-tree__sx_delete_node",
|
||||
"mcp__sx-tree__sx_wrap_node",
|
||||
"mcp__sx-tree__sx_rename_symbol",
|
||||
"mcp__sx-tree__sx_replace_by_pattern",
|
||||
"mcp__sx-tree__sx_rename_across",
|
||||
"mcp__sx-tree__sx_write_file",
|
||||
"mcp__sx-tree__sx_pretty_print",
|
||||
"mcp__sx-tree__sx_eval",
|
||||
"mcp__sx-tree__sx_harness_eval",
|
||||
"mcp__sx-tree__sx_macroexpand",
|
||||
"mcp__sx-tree__sx_trace",
|
||||
"mcp__sx-tree__sx_deps",
|
||||
"mcp__sx-tree__sx_diff",
|
||||
"mcp__sx-tree__sx_diff_branch",
|
||||
"mcp__sx-tree__sx_changed",
|
||||
"mcp__sx-tree__sx_blame",
|
||||
"mcp__sx-tree__sx_build",
|
||||
"mcp__sx-tree__sx_build_manifest",
|
||||
"mcp__sx-tree__sx_build_bytecode",
|
||||
"mcp__sx-tree__sx_test",
|
||||
"mcp__sx-tree__sx_format_check",
|
||||
"mcp__sx-tree__sx_comp_list",
|
||||
"mcp__sx-tree__sx_comp_usage",
|
||||
"mcp__sx-tree__sx_nav",
|
||||
"mcp__sx-tree__sx_env",
|
||||
"mcp__sx-tree__sx_playwright",
|
||||
"mcp__hs-test__hs_test_run",
|
||||
"mcp__hs-test__hs_test_regen",
|
||||
"mcp__hs-test__hs_test_kill",
|
||||
"mcp__hs-test__hs_test_status",
|
||||
"Bash(node *)",
|
||||
"Bash(python3 *)",
|
||||
"Bash(bash *)",
|
||||
"Bash(cp *)",
|
||||
"Bash(git *)",
|
||||
"Bash(tmux *)"
|
||||
]
|
||||
},
|
||||
"enabledMcpjsonServers": [
|
||||
"sx-tree",
|
||||
"rose-ash-services",
|
||||
"hs-test"
|
||||
]
|
||||
}
|
||||
SETTINGS
|
||||
|
||||
echo "Creating tmux session '$SESSION' in $ROOT ..."
|
||||
tmux new-session -d -s "$SESSION" -n "primitives" -c "$ROOT"
|
||||
|
||||
echo "Starting claude..."
|
||||
tmux send-keys -t "$SESSION:primitives" "claude" C-m
|
||||
|
||||
echo "Waiting ${BOOT_WAIT}s for claude to boot..."
|
||||
sleep "$BOOT_WAIT"
|
||||
|
||||
if [ -n "$INTERVAL" ]; then
|
||||
preamble="/loop $INTERVAL "
|
||||
else
|
||||
preamble="/loop "
|
||||
fi
|
||||
|
||||
cmd="${preamble}Read plans/agent-briefings/primitives-loop.md and do ONE step per fire: find the first unchecked [ ] task, implement it fully, run the relevant tests to verify, commit with a short factual message, push to origin/architecture, tick the box [x] in the plan, append one dated line to the Progress log (newest first), then stop. You are on branch architecture in /root/rose-ash. Use sx-tree MCP for all .sx edits. Never push to main."
|
||||
|
||||
tmux send-keys -t "$SESSION:primitives" "$cmd"
|
||||
sleep 0.5
|
||||
tmux send-keys -t "$SESSION:primitives" Enter
|
||||
|
||||
echo ""
|
||||
echo "Done. SX primitives loop started in tmux session '$SESSION'."
|
||||
echo ""
|
||||
echo " Attach: tmux a -t $SESSION"
|
||||
echo " Detach: Ctrl-B d"
|
||||
echo " Stop: ./scripts/sx-primitives-down.sh"
|
||||
echo ""
|
||||
File diff suppressed because it is too large
Load Diff
56
spec/coroutines.sx
Normal file
56
spec/coroutines.sx
Normal file
@@ -0,0 +1,56 @@
|
||||
(define-library
|
||||
(sx coroutines)
|
||||
(export
|
||||
make-coroutine
|
||||
coroutine?
|
||||
coroutine-alive?
|
||||
coroutine-yield
|
||||
coroutine-handle-result
|
||||
coroutine-resume)
|
||||
(begin
|
||||
(define make-coroutine (fn (thunk) {:suspension nil :thunk thunk :type "coroutine" :state "ready"}))
|
||||
(define
|
||||
coroutine?
|
||||
(fn (v) (and (dict? v) (= (get v "type") "coroutine"))))
|
||||
(define
|
||||
coroutine-alive?
|
||||
(fn (c) (and (coroutine? c) (not (= (get c "state") "dead")))))
|
||||
(define coroutine-yield (fn (val) (perform {:value val :op "coroutine-yield"})))
|
||||
(define
|
||||
coroutine-handle-result
|
||||
(fn
|
||||
(c result)
|
||||
(if
|
||||
(cek-terminal? result)
|
||||
(do (dict-set! c "state" "dead") {:done true :value (cek-value result)})
|
||||
(let
|
||||
((request (cek-io-request result)))
|
||||
(if
|
||||
(and (dict? request) (= (get request "op") "coroutine-yield"))
|
||||
(do
|
||||
(dict-set! c "state" "suspended")
|
||||
(dict-set! c "suspension" result)
|
||||
{:done false :value (get request "value")})
|
||||
(perform request))))))
|
||||
(define
|
||||
coroutine-resume
|
||||
(fn
|
||||
(c val)
|
||||
(cond
|
||||
(not (coroutine? c))
|
||||
(error "coroutine-resume: not a coroutine")
|
||||
(= (get c "state") "dead")
|
||||
(error "coroutine-resume: coroutine is dead")
|
||||
(= (get c "state") "ready")
|
||||
(do
|
||||
(dict-set! c "state" "running")
|
||||
(coroutine-handle-result
|
||||
c
|
||||
(cek-step-loop
|
||||
(make-cek-state (list (get c "thunk")) (make-env) (list)))))
|
||||
(= (get c "state") "suspended")
|
||||
(do
|
||||
(dict-set! c "state" "running")
|
||||
(coroutine-handle-result c (cek-resume (get c "suspension") val)))
|
||||
:else (error
|
||||
(str "coroutine-resume: unexpected state: " (get c "state"))))))))
|
||||
File diff suppressed because it is too large
Load Diff
743
spec/parser.sx
743
spec/parser.sx
@@ -14,13 +14,15 @@
|
||||
;; list → '(' expr* ')'
|
||||
;; vector → '[' expr* ']' (sugar for list)
|
||||
;; map → '{' (key expr)* '}'
|
||||
;; atom → string | number | keyword | symbol | boolean | nil
|
||||
;; atom → string | number | rational | keyword | symbol | boolean | nil | char
|
||||
;; string → '"' (char | escape)* '"'
|
||||
;; number → '-'? digit+ ('.' digit+)? ([eE] [+-]? digit+)?
|
||||
;; rational → integer '/' digit+
|
||||
;; keyword → ':' ident
|
||||
;; symbol → ident
|
||||
;; boolean → 'true' | 'false'
|
||||
;; nil → 'nil'
|
||||
;; char → '#\' (ident | single-char)
|
||||
;; ident → ident-start ident-char*
|
||||
;; comment → ';' to end of line (discarded)
|
||||
;;
|
||||
@@ -34,6 +36,8 @@
|
||||
;; #;expr → datum comment (read and discard expr)
|
||||
;; #|raw chars| → raw string literal (no escape processing)
|
||||
;; #'expr → (quote expr)
|
||||
;; #\a → character literal (char value)
|
||||
;; #\space → named character (space = 32)
|
||||
;; #name expr → extensible dispatch (calls registered handler)
|
||||
;;
|
||||
;; Platform interface (each target implements natively):
|
||||
@@ -42,6 +46,11 @@
|
||||
;; (make-symbol name) → Symbol value
|
||||
;; (make-keyword name) → Keyword value
|
||||
;; (escape-string s) → string with " and \ escaped for serialization
|
||||
;; (make-char n) → Char value from Unicode codepoint
|
||||
;; (make-rational n d) → Rational value (auto-reduced by GCD)
|
||||
;; (char->integer c) → Unicode codepoint of char c
|
||||
;; (char-from-code n) → single-char string from codepoint
|
||||
;; (char-code s) → codepoint of first char in string s
|
||||
;; ==========================================================================
|
||||
|
||||
|
||||
@@ -51,308 +60,436 @@
|
||||
;; Returns a list of top-level AST expressions.
|
||||
|
||||
;; Parse SX source string into AST
|
||||
(define sx-parse :effects []
|
||||
(fn ((source :as string))
|
||||
(let ((pos 0)
|
||||
(len-src (len source)))
|
||||
|
||||
;; -- Cursor helpers (closure over pos, source, len-src) --
|
||||
|
||||
(define skip-comment :effects []
|
||||
(fn ()
|
||||
(when (and (< pos len-src) (not (= (nth source pos) "\n")))
|
||||
(define
|
||||
sx-parse
|
||||
:effects ()
|
||||
(fn
|
||||
((source :as string))
|
||||
(let
|
||||
((pos 0) (len-src (len source)))
|
||||
(define
|
||||
skip-comment
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos len-src) (not (= (nth source pos) "\n")))
|
||||
(set! pos (inc pos))
|
||||
(skip-comment))))
|
||||
|
||||
(define skip-ws :effects []
|
||||
(fn ()
|
||||
(when (< pos len-src)
|
||||
(let ((ch (nth source pos)))
|
||||
(define
|
||||
skip-ws
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(< pos len-src)
|
||||
(let
|
||||
((ch (nth source pos)))
|
||||
(cond
|
||||
;; Whitespace
|
||||
(or (= ch " ") (= ch "\t") (= ch "\n") (= ch "\r"))
|
||||
(do (set! pos (inc pos)) (skip-ws))
|
||||
;; Comment — skip to end of line
|
||||
(do (set! pos (inc pos)) (skip-ws))
|
||||
(= ch ";")
|
||||
(do (set! pos (inc pos))
|
||||
(skip-comment)
|
||||
(skip-ws))
|
||||
;; Not whitespace or comment — stop
|
||||
(do (set! pos (inc pos)) (skip-comment) (skip-ws))
|
||||
:else nil)))))
|
||||
|
||||
;; -- Atom readers --
|
||||
|
||||
(define hex-digit-value :effects []
|
||||
(define
|
||||
hex-digit-value
|
||||
:effects ()
|
||||
(fn (ch) (index-of "0123456789abcdef" (lower ch))))
|
||||
|
||||
(define read-string :effects []
|
||||
(fn ()
|
||||
(set! pos (inc pos)) ;; skip opening "
|
||||
(let ((buf ""))
|
||||
(define read-str-loop :effects []
|
||||
(fn ()
|
||||
(if (>= pos len-src)
|
||||
(define
|
||||
read-string
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(set! pos (inc pos))
|
||||
(let
|
||||
((buf ""))
|
||||
(define
|
||||
read-str-loop
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(if
|
||||
(>= pos len-src)
|
||||
(error "Unterminated string")
|
||||
(let ((ch (nth source pos)))
|
||||
(let
|
||||
((ch (nth source pos)))
|
||||
(cond
|
||||
(= ch "\"")
|
||||
(do (set! pos (inc pos)) nil) ;; done
|
||||
(do (set! pos (inc pos)) nil)
|
||||
(= ch "\\")
|
||||
(do (set! pos (inc pos))
|
||||
(let ((esc (nth source pos)))
|
||||
(if (= esc "u")
|
||||
;; Unicode escape: \uXXXX → char
|
||||
(do (set! pos (inc pos))
|
||||
(let ((d0 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos)))
|
||||
(d1 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos)))
|
||||
(d2 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos)))
|
||||
(d3 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos))))
|
||||
(set! buf (str buf (char-from-code
|
||||
(+ (* d0 4096) (* d1 256) (* d2 16) d3))))
|
||||
(read-str-loop)))
|
||||
;; Standard escapes: \n \t \r or literal
|
||||
(do (set! buf (str buf
|
||||
(cond
|
||||
(= esc "n") "\n"
|
||||
(= esc "t") "\t"
|
||||
(= esc "r") "\r"
|
||||
:else esc)))
|
||||
(set! pos (inc pos))
|
||||
(read-str-loop)))))
|
||||
:else
|
||||
(do (set! buf (str buf ch))
|
||||
(set! pos (inc pos))
|
||||
(read-str-loop)))))))
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(let
|
||||
((esc (nth source pos)))
|
||||
(if
|
||||
(= esc "u")
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(let
|
||||
((d0 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos)))
|
||||
(d1 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos)))
|
||||
(d2 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos)))
|
||||
(d3 (hex-digit-value (nth source pos)))
|
||||
(_ (set! pos (inc pos))))
|
||||
(set!
|
||||
buf
|
||||
(str
|
||||
buf
|
||||
(char-from-code
|
||||
(+
|
||||
(* d0 4096)
|
||||
(* d1 256)
|
||||
(* d2 16)
|
||||
d3))))
|
||||
(read-str-loop)))
|
||||
(do
|
||||
(set!
|
||||
buf
|
||||
(str
|
||||
buf
|
||||
(cond
|
||||
(= esc "n")
|
||||
"\n"
|
||||
(= esc "t")
|
||||
"\t"
|
||||
(= esc "r")
|
||||
"\r"
|
||||
:else esc)))
|
||||
(set! pos (inc pos))
|
||||
(read-str-loop)))))
|
||||
:else (do
|
||||
(set! buf (str buf ch))
|
||||
(set! pos (inc pos))
|
||||
(read-str-loop)))))))
|
||||
(read-str-loop)
|
||||
buf)))
|
||||
|
||||
(define read-ident :effects []
|
||||
(fn ()
|
||||
(let ((start pos))
|
||||
(define read-ident-loop :effects []
|
||||
(fn ()
|
||||
(when (and (< pos len-src)
|
||||
(ident-char? (nth source pos)))
|
||||
(define
|
||||
read-ident
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((start pos))
|
||||
(define
|
||||
read-ident-loop
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos len-src) (ident-char? (nth source pos)))
|
||||
(set! pos (inc pos))
|
||||
(read-ident-loop))))
|
||||
(read-ident-loop)
|
||||
(slice source start pos))))
|
||||
|
||||
(define read-keyword :effects []
|
||||
(fn ()
|
||||
(set! pos (inc pos)) ;; skip :
|
||||
(make-keyword (read-ident))))
|
||||
|
||||
(define read-number :effects []
|
||||
(fn ()
|
||||
(let ((start pos))
|
||||
;; Optional leading minus
|
||||
(when (and (< pos len-src) (= (nth source pos) "-"))
|
||||
(define
|
||||
read-keyword
|
||||
:effects ()
|
||||
(fn () (set! pos (inc pos)) (make-keyword (read-ident))))
|
||||
(define
|
||||
read-number
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((start pos))
|
||||
(when
|
||||
(and (< pos len-src) (= (nth source pos) "-"))
|
||||
(set! pos (inc pos)))
|
||||
;; Integer digits
|
||||
(define read-digits :effects []
|
||||
(fn ()
|
||||
(when (and (< pos len-src)
|
||||
(let ((c (nth source pos)))
|
||||
(and (>= c "0") (<= c "9"))))
|
||||
(define
|
||||
read-digits
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and
|
||||
(< pos len-src)
|
||||
(let
|
||||
((c (nth source pos)))
|
||||
(and (>= c "0") (<= c "9"))))
|
||||
(set! pos (inc pos))
|
||||
(read-digits))))
|
||||
(read-digits)
|
||||
;; Decimal part
|
||||
(when (and (< pos len-src) (= (nth source pos) "."))
|
||||
(set! pos (inc pos))
|
||||
(read-digits))
|
||||
;; Exponent
|
||||
(when (and (< pos len-src)
|
||||
(or (= (nth source pos) "e")
|
||||
(= (nth source pos) "E")))
|
||||
(set! pos (inc pos))
|
||||
(when (and (< pos len-src)
|
||||
(or (= (nth source pos) "+")
|
||||
(= (nth source pos) "-")))
|
||||
(set! pos (inc pos)))
|
||||
(read-digits))
|
||||
(parse-number (slice source start pos)))))
|
||||
|
||||
(define read-symbol :effects []
|
||||
(fn ()
|
||||
(let ((name (read-ident)))
|
||||
(if
|
||||
(and
|
||||
(< pos len-src)
|
||||
(= (nth source pos) "/")
|
||||
(< (inc pos) len-src)
|
||||
(let
|
||||
((nc (nth source (inc pos))))
|
||||
(and (>= nc "0") (<= nc "9"))))
|
||||
(let
|
||||
((numer (parse-number (slice source start pos))))
|
||||
(set! pos (inc pos))
|
||||
(let
|
||||
((denom-start pos))
|
||||
(read-digits)
|
||||
(make-rational
|
||||
numer
|
||||
(parse-number (slice source denom-start pos)))))
|
||||
(do
|
||||
(when
|
||||
(and (< pos len-src) (= (nth source pos) "."))
|
||||
(set! pos (inc pos))
|
||||
(read-digits))
|
||||
(when
|
||||
(and
|
||||
(< pos len-src)
|
||||
(or (= (nth source pos) "e") (= (nth source pos) "E")))
|
||||
(set! pos (inc pos))
|
||||
(when
|
||||
(and
|
||||
(< pos len-src)
|
||||
(or
|
||||
(= (nth source pos) "+")
|
||||
(= (nth source pos) "-")))
|
||||
(set! pos (inc pos)))
|
||||
(read-digits))
|
||||
(parse-number (slice source start pos)))))))
|
||||
(define
|
||||
read-symbol
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((name (read-ident)))
|
||||
(cond
|
||||
(= name "true") true
|
||||
(= name "false") false
|
||||
(= name "nil") nil
|
||||
:else (make-symbol name)))))
|
||||
|
||||
;; -- Composite readers --
|
||||
|
||||
(define read-list :effects []
|
||||
(fn ((close-ch :as string))
|
||||
(let ((items (list)))
|
||||
(define read-list-loop :effects []
|
||||
(fn ()
|
||||
(= name "true")
|
||||
true
|
||||
(= name "false")
|
||||
false
|
||||
(= name "nil")
|
||||
nil
|
||||
:else (make-symbol name)))))
|
||||
(define
|
||||
read-list
|
||||
:effects ()
|
||||
(fn
|
||||
((close-ch :as string))
|
||||
(let
|
||||
((items (list)))
|
||||
(define
|
||||
read-list-loop
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(skip-ws)
|
||||
(if (>= pos len-src)
|
||||
(if
|
||||
(>= pos len-src)
|
||||
(error "Unterminated list")
|
||||
(if (= (nth source pos) close-ch)
|
||||
(do (set! pos (inc pos)) nil) ;; done
|
||||
(do (append! items (read-expr))
|
||||
(read-list-loop))))))
|
||||
(if
|
||||
(= (nth source pos) close-ch)
|
||||
(do (set! pos (inc pos)) nil)
|
||||
(do (append! items (read-expr)) (read-list-loop))))))
|
||||
(read-list-loop)
|
||||
items)))
|
||||
|
||||
(define read-map :effects []
|
||||
(fn ()
|
||||
(let ((result (dict)))
|
||||
(define read-map-loop :effects []
|
||||
(fn ()
|
||||
(define
|
||||
read-map
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((result (dict)))
|
||||
(define
|
||||
read-map-loop
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(skip-ws)
|
||||
(if (>= pos len-src)
|
||||
(if
|
||||
(>= pos len-src)
|
||||
(error "Unterminated map")
|
||||
(if (= (nth source pos) "}")
|
||||
(do (set! pos (inc pos)) nil) ;; done
|
||||
(let ((key-expr (read-expr))
|
||||
(key-str (if (= (type-of key-expr) "keyword")
|
||||
(keyword-name key-expr)
|
||||
(str key-expr)))
|
||||
(val-expr (read-expr)))
|
||||
(if
|
||||
(= (nth source pos) "}")
|
||||
(do (set! pos (inc pos)) nil)
|
||||
(let
|
||||
((key-expr (read-expr))
|
||||
(key-str
|
||||
(if
|
||||
(= (type-of key-expr) "keyword")
|
||||
(keyword-name key-expr)
|
||||
(str key-expr)))
|
||||
(val-expr (read-expr)))
|
||||
(dict-set! result key-str val-expr)
|
||||
(read-map-loop))))))
|
||||
(read-map-loop)
|
||||
result)))
|
||||
|
||||
;; -- Raw string reader (for #|...|) --
|
||||
|
||||
(define read-raw-string :effects []
|
||||
(fn ()
|
||||
(let ((buf ""))
|
||||
(define raw-loop :effects []
|
||||
(fn ()
|
||||
(if (>= pos len-src)
|
||||
(define
|
||||
read-raw-string
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((buf ""))
|
||||
(define
|
||||
raw-loop
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(if
|
||||
(>= pos len-src)
|
||||
(error "Unterminated raw string")
|
||||
(let ((ch (nth source pos)))
|
||||
(if (= ch "|")
|
||||
(do (set! pos (inc pos)) nil) ;; done
|
||||
(do (set! buf (str buf ch))
|
||||
(set! pos (inc pos))
|
||||
(raw-loop)))))))
|
||||
(let
|
||||
((ch (nth source pos)))
|
||||
(if
|
||||
(= ch "|")
|
||||
(do (set! pos (inc pos)) nil)
|
||||
(do
|
||||
(set! buf (str buf ch))
|
||||
(set! pos (inc pos))
|
||||
(raw-loop)))))))
|
||||
(raw-loop)
|
||||
buf)))
|
||||
|
||||
;; -- Main expression reader --
|
||||
|
||||
(define read-expr :effects []
|
||||
(fn ()
|
||||
(define
|
||||
read-char-literal
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(if
|
||||
(>= pos len-src)
|
||||
(error "Unexpected end of input after #\\")
|
||||
(let
|
||||
((first-ch (nth source pos)))
|
||||
(if
|
||||
(ident-start? first-ch)
|
||||
(let
|
||||
((char-start pos))
|
||||
(define
|
||||
read-char-name-loop
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(when
|
||||
(and (< pos len-src) (ident-char? (nth source pos)))
|
||||
(set! pos (inc pos))
|
||||
(read-char-name-loop))))
|
||||
(read-char-name-loop)
|
||||
(let
|
||||
((char-name (slice source char-start pos)))
|
||||
(make-char
|
||||
(cond
|
||||
(= char-name "space")
|
||||
32
|
||||
(= char-name "newline")
|
||||
10
|
||||
(= char-name "tab")
|
||||
9
|
||||
(= char-name "nul")
|
||||
0
|
||||
(= char-name "null")
|
||||
0
|
||||
(= char-name "return")
|
||||
13
|
||||
(= char-name "escape")
|
||||
27
|
||||
(= char-name "delete")
|
||||
127
|
||||
(= char-name "backspace")
|
||||
8
|
||||
(= char-name "altmode")
|
||||
27
|
||||
(= char-name "rubout")
|
||||
127
|
||||
:else (char-code first-ch)))))
|
||||
(do (set! pos (inc pos)) (make-char (char-code first-ch))))))))
|
||||
(define
|
||||
read-expr
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(skip-ws)
|
||||
(if (>= pos len-src)
|
||||
(if
|
||||
(>= pos len-src)
|
||||
(error "Unexpected end of input")
|
||||
(let ((ch (nth source pos)))
|
||||
(let
|
||||
((ch (nth source pos)))
|
||||
(cond
|
||||
;; Lists
|
||||
(= ch "(")
|
||||
(do (set! pos (inc pos)) (read-list ")"))
|
||||
(do (set! pos (inc pos)) (read-list ")"))
|
||||
(= ch "[")
|
||||
(do (set! pos (inc pos)) (read-list "]"))
|
||||
|
||||
;; Map
|
||||
(do (set! pos (inc pos)) (read-list "]"))
|
||||
(= ch "{")
|
||||
(do (set! pos (inc pos)) (read-map))
|
||||
|
||||
;; String
|
||||
(do (set! pos (inc pos)) (read-map))
|
||||
(= ch "\"")
|
||||
(read-string)
|
||||
|
||||
;; Keyword
|
||||
(read-string)
|
||||
(= ch ":")
|
||||
(read-keyword)
|
||||
|
||||
;; Quote sugar
|
||||
(read-keyword)
|
||||
(= ch "'")
|
||||
(do (set! pos (inc pos))
|
||||
(list (make-symbol "quote") (read-expr)))
|
||||
|
||||
;; Quasiquote sugar
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(list (make-symbol "quote") (read-expr)))
|
||||
(= ch "`")
|
||||
(do (set! pos (inc pos))
|
||||
(list (make-symbol "quasiquote") (read-expr)))
|
||||
|
||||
;; Unquote / splice-unquote
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(list (make-symbol "quasiquote") (read-expr)))
|
||||
(= ch ",")
|
||||
(do (set! pos (inc pos))
|
||||
(if (and (< pos len-src) (= (nth source pos) "@"))
|
||||
(do (set! pos (inc pos))
|
||||
(list (make-symbol "splice-unquote") (read-expr)))
|
||||
(list (make-symbol "unquote") (read-expr))))
|
||||
|
||||
;; Reader macros: #
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(if
|
||||
(and (< pos len-src) (= (nth source pos) "@"))
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(list (make-symbol "splice-unquote") (read-expr)))
|
||||
(list (make-symbol "unquote") (read-expr))))
|
||||
(= ch "#")
|
||||
(do (set! pos (inc pos))
|
||||
(if (>= pos len-src)
|
||||
(error "Unexpected end of input after #")
|
||||
(let ((dispatch-ch (nth source pos)))
|
||||
(cond
|
||||
;; #; — datum comment: read and discard next expr
|
||||
(= dispatch-ch ";")
|
||||
(do (set! pos (inc pos))
|
||||
(read-expr) ;; read and discard
|
||||
(read-expr)) ;; return the NEXT expr
|
||||
|
||||
;; #| — raw string
|
||||
(= dispatch-ch "|")
|
||||
(do (set! pos (inc pos))
|
||||
(read-raw-string))
|
||||
|
||||
;; #' — quote shorthand
|
||||
(= dispatch-ch "'")
|
||||
(do (set! pos (inc pos))
|
||||
(list (make-symbol "quote") (read-expr)))
|
||||
|
||||
;; #name — extensible dispatch
|
||||
(ident-start? dispatch-ch)
|
||||
(let ((macro-name (read-ident)))
|
||||
(let ((handler (reader-macro-get macro-name)))
|
||||
(if handler
|
||||
(handler (read-expr))
|
||||
(error (str "Unknown reader macro: #" macro-name)))))
|
||||
|
||||
:else
|
||||
(error (str "Unknown reader macro: #" dispatch-ch))))))
|
||||
|
||||
;; Number (or negative number)
|
||||
(or (and (>= ch "0") (<= ch "9"))
|
||||
(and (= ch "-")
|
||||
(< (inc pos) len-src)
|
||||
(let ((next-ch (nth source (inc pos))))
|
||||
(and (>= next-ch "0") (<= next-ch "9")))))
|
||||
(read-number)
|
||||
|
||||
;; Ellipsis (... as a symbol)
|
||||
(and (= ch ".")
|
||||
(< (+ pos 2) len-src)
|
||||
(= (nth source (+ pos 1)) ".")
|
||||
(= (nth source (+ pos 2)) "."))
|
||||
(do (set! pos (+ pos 3))
|
||||
(make-symbol "..."))
|
||||
|
||||
;; Symbol (must be ident-start char)
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(if
|
||||
(>= pos len-src)
|
||||
(error "Unexpected end of input after #")
|
||||
(let
|
||||
((dispatch-ch (nth source pos)))
|
||||
(cond
|
||||
(= dispatch-ch ";")
|
||||
(do (set! pos (inc pos)) (read-expr) (read-expr))
|
||||
(= dispatch-ch "|")
|
||||
(do (set! pos (inc pos)) (read-raw-string))
|
||||
(= dispatch-ch "'")
|
||||
(do
|
||||
(set! pos (inc pos))
|
||||
(list (make-symbol "quote") (read-expr)))
|
||||
(= dispatch-ch "\\")
|
||||
(do (set! pos (inc pos)) (read-char-literal))
|
||||
(ident-start? dispatch-ch)
|
||||
(let
|
||||
((macro-name (read-ident)))
|
||||
(let
|
||||
((handler (reader-macro-get macro-name)))
|
||||
(if
|
||||
handler
|
||||
(handler (read-expr))
|
||||
(error
|
||||
(str "Unknown reader macro: #" macro-name)))))
|
||||
:else (error (str "Unknown reader macro: #" dispatch-ch))))))
|
||||
(or
|
||||
(and (>= ch "0") (<= ch "9"))
|
||||
(and
|
||||
(= ch "-")
|
||||
(< (inc pos) len-src)
|
||||
(let
|
||||
((next-ch (nth source (inc pos))))
|
||||
(and (>= next-ch "0") (<= next-ch "9")))))
|
||||
(read-number)
|
||||
(and
|
||||
(= ch ".")
|
||||
(< (+ pos 2) len-src)
|
||||
(= (nth source (+ pos 1)) ".")
|
||||
(= (nth source (+ pos 2)) "."))
|
||||
(do (set! pos (+ pos 3)) (make-symbol "..."))
|
||||
(ident-start? ch)
|
||||
(read-symbol)
|
||||
|
||||
;; Unexpected
|
||||
:else
|
||||
(error (str "Unexpected character: " ch)))))))
|
||||
|
||||
;; -- Entry point: parse all top-level expressions --
|
||||
(let ((exprs (list)))
|
||||
(define parse-loop :effects []
|
||||
(fn ()
|
||||
(read-symbol)
|
||||
:else (error (str "Unexpected character: " ch)))))))
|
||||
(let
|
||||
((exprs (list)))
|
||||
(define
|
||||
parse-loop
|
||||
:effects ()
|
||||
(fn
|
||||
()
|
||||
(skip-ws)
|
||||
(when (< pos len-src)
|
||||
(append! exprs (read-expr))
|
||||
(parse-loop))))
|
||||
(when (< pos len-src) (append! exprs (read-expr)) (parse-loop))))
|
||||
(parse-loop)
|
||||
exprs))))
|
||||
|
||||
@@ -362,30 +499,77 @@
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
;; Serialize AST value back to SX source
|
||||
(define sx-serialize :effects []
|
||||
(fn (val)
|
||||
(case (type-of val)
|
||||
"nil" "nil"
|
||||
"boolean" (if val "true" "false")
|
||||
"number" (str val)
|
||||
"string" (str "\"" (escape-string val) "\"")
|
||||
"symbol" (symbol-name val)
|
||||
"keyword" (str ":" (keyword-name val))
|
||||
"list" (str "(" (join " " (map sx-serialize val)) ")")
|
||||
"dict" (sx-serialize-dict val)
|
||||
"sx-expr" (sx-expr-source val)
|
||||
"spread" (str "(make-spread " (sx-serialize-dict (spread-attrs val)) ")")
|
||||
:else (str val))))
|
||||
(define
|
||||
sx-serialize
|
||||
:effects ()
|
||||
(fn
|
||||
(val)
|
||||
(case
|
||||
(type-of val)
|
||||
"nil"
|
||||
"nil"
|
||||
"boolean"
|
||||
(if val "true" "false")
|
||||
"number"
|
||||
(str val)
|
||||
"rational"
|
||||
(str (numerator val) "/" (denominator val))
|
||||
"string"
|
||||
(str "\"" (escape-string val) "\"")
|
||||
"symbol"
|
||||
(symbol-name val)
|
||||
"keyword"
|
||||
(str ":" (keyword-name val))
|
||||
"list"
|
||||
(str "(" (join " " (map sx-serialize val)) ")")
|
||||
"dict"
|
||||
(sx-serialize-dict val)
|
||||
"sx-expr"
|
||||
(sx-expr-source val)
|
||||
"spread"
|
||||
(str "(make-spread " (sx-serialize-dict (spread-attrs val)) ")")
|
||||
"char"
|
||||
(let
|
||||
((n (char->integer val)))
|
||||
(str
|
||||
"#\\"
|
||||
(cond
|
||||
(= n 32)
|
||||
"space"
|
||||
(= n 10)
|
||||
"newline"
|
||||
(= n 9)
|
||||
"tab"
|
||||
(= n 13)
|
||||
"return"
|
||||
(= n 0)
|
||||
"nul"
|
||||
(= n 27)
|
||||
"escape"
|
||||
(= n 127)
|
||||
"delete"
|
||||
(= n 8)
|
||||
"backspace"
|
||||
:else (char-from-code n))))
|
||||
:else (str val))))
|
||||
|
||||
|
||||
;; Serialize a dict to SX {:key val} format
|
||||
(define sx-serialize-dict :effects []
|
||||
(fn ((d :as dict))
|
||||
(str "{"
|
||||
(join " "
|
||||
(define
|
||||
sx-serialize-dict
|
||||
:effects ()
|
||||
(fn
|
||||
((d :as dict))
|
||||
(str
|
||||
"{"
|
||||
(join
|
||||
" "
|
||||
(reduce
|
||||
(fn ((acc :as list) (key :as string))
|
||||
(concat acc (list (str ":" key) (sx-serialize (dict-get d key)))))
|
||||
(fn
|
||||
((acc :as list) (key :as string))
|
||||
(concat
|
||||
acc
|
||||
(list (str ":" key) (sx-serialize (dict-get d key)))))
|
||||
(list)
|
||||
(keys d)))
|
||||
"}")))
|
||||
@@ -407,13 +591,18 @@
|
||||
;; True for: ident-start chars plus: 0-9 . : / # ,
|
||||
;;
|
||||
;; Constructors (provided by the SX runtime):
|
||||
;; (make-symbol name) → Symbol value
|
||||
;; (make-keyword name) → Keyword value
|
||||
;; (parse-number s) → number (int or float from string)
|
||||
;; (make-symbol name) → Symbol value
|
||||
;; (make-keyword name) → Keyword value
|
||||
;; (parse-number s) → number (int or float from string)
|
||||
;; (make-char n) → Char value from Unicode codepoint n
|
||||
;; (make-rational n d) → Rational value (auto-reduced by GCD; d=0 is an error)
|
||||
;; (char->integer c) → Unicode codepoint of char c
|
||||
;;
|
||||
;; String utilities:
|
||||
;; (escape-string s) → string with " and \ escaped
|
||||
;; (sx-expr-source e) → unwrap SxExpr to its source string
|
||||
;; (char-from-code n) → single-char string from codepoint n
|
||||
;; (char-code s) → codepoint of first char in string s
|
||||
;;
|
||||
;; Reader macro registry:
|
||||
;; (reader-macro-get name) → handler fn or nil
|
||||
|
||||
@@ -43,35 +43,35 @@
|
||||
"+"
|
||||
:params (&rest (args :as number))
|
||||
:returns "number"
|
||||
:doc "Sum all arguments."
|
||||
:doc "Sum all arguments. Returns integer iff all args are exact integers (float contagion)."
|
||||
:body (reduce (fn (a b) (native-add a b)) 0 args))
|
||||
|
||||
(define-primitive
|
||||
"-"
|
||||
:params ((a :as number) &rest (b :as number))
|
||||
:returns "number"
|
||||
:doc "Subtract. Unary: negate. Binary: a - b."
|
||||
:doc "Subtract. Unary: negate. Binary: a - b. Float contagion: returns integer iff all args are integers."
|
||||
:body (if (empty? b) (native-neg a) (native-sub a (first b))))
|
||||
|
||||
(define-primitive
|
||||
"*"
|
||||
:params (&rest (args :as number))
|
||||
:returns "number"
|
||||
:doc "Multiply all arguments."
|
||||
:doc "Multiply all arguments. Float contagion: integer result iff all args are exact integers."
|
||||
:body (reduce (fn (a b) (native-mul a b)) 1 args))
|
||||
|
||||
(define-primitive
|
||||
"/"
|
||||
:params ((a :as number) (b :as number))
|
||||
:returns "number"
|
||||
:doc "Divide a by b."
|
||||
:returns "float"
|
||||
:doc "Divide a by b. Always returns inexact float."
|
||||
:body (native-div a b))
|
||||
|
||||
(define-primitive
|
||||
"mod"
|
||||
:params ((a :as number) (b :as number))
|
||||
:returns "number"
|
||||
:doc "Modulo a % b."
|
||||
:doc "Modulo a % b. Returns integer iff both args are integers."
|
||||
:body (native-mod a b))
|
||||
|
||||
(define-primitive
|
||||
@@ -108,26 +108,26 @@
|
||||
(define-primitive
|
||||
"floor"
|
||||
:params ((x :as number))
|
||||
:returns "number"
|
||||
:doc "Floor to integer.")
|
||||
:returns "integer"
|
||||
:doc "Floor toward negative infinity — returns exact integer.")
|
||||
|
||||
(define-primitive
|
||||
"ceil"
|
||||
:params ((x :as number))
|
||||
:returns "number"
|
||||
:doc "Ceiling to integer.")
|
||||
:returns "integer"
|
||||
:doc "Ceiling toward positive infinity — returns exact integer.")
|
||||
|
||||
(define-primitive
|
||||
"round"
|
||||
:params ((x :as number) &rest (ndigits :as number))
|
||||
:returns "number"
|
||||
:doc "Round to ndigits decimal places (default 0).")
|
||||
:doc "Round to ndigits decimal places (default 0). Returns integer when ndigits is 0.")
|
||||
|
||||
(define-primitive
|
||||
"truncate"
|
||||
:params (((x :as number)))
|
||||
:returns "number"
|
||||
:doc "Truncate toward zero.")
|
||||
:params ((x :as number))
|
||||
:returns "integer"
|
||||
:doc "Truncate toward zero — returns exact integer.")
|
||||
|
||||
(define-primitive
|
||||
"remainder"
|
||||
@@ -143,42 +143,42 @@
|
||||
|
||||
(define-primitive
|
||||
"exact?"
|
||||
:params (((x :as number)))
|
||||
:params ((x :as number))
|
||||
:returns "boolean"
|
||||
:doc "True if x is exact (integer-valued).")
|
||||
:doc "True if x is an exact integer (not an inexact float).")
|
||||
|
||||
(define-primitive
|
||||
"inexact?"
|
||||
:params (((x :as number)))
|
||||
:params ((x :as number))
|
||||
:returns "boolean"
|
||||
:doc "True if x is inexact (non-integer).")
|
||||
:doc "True if x is an inexact float (not an exact integer).")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Core — Comparison
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"exact->inexact"
|
||||
:params (((x :as number)))
|
||||
:returns "number"
|
||||
:doc "Convert exact to inexact (identity for float tower).")
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "Convert exact integer to inexact float. Floats pass through unchanged.")
|
||||
|
||||
(define-primitive
|
||||
"inexact->exact"
|
||||
:params (((x :as number)))
|
||||
:returns "number"
|
||||
:doc "Convert inexact to nearest exact integer.")
|
||||
:params ((x :as number))
|
||||
:returns "integer"
|
||||
:doc "Convert inexact float to nearest exact integer (truncates). Integers pass through unchanged.")
|
||||
|
||||
(define-primitive
|
||||
"make-vector"
|
||||
:params ((n :as number))
|
||||
:params ((n :as number) (fill :as any :optional true))
|
||||
:returns "vector"
|
||||
:doc "Create vector of size n, optionally filled.")
|
||||
:doc "Create vector of length n, each element initialised to fill (default nil).")
|
||||
|
||||
(define-primitive
|
||||
"vector"
|
||||
:params ()
|
||||
:params (:rest (elts :as any))
|
||||
:returns "vector"
|
||||
:doc "Create vector from arguments.")
|
||||
:doc "Construct a vector from its arguments.")
|
||||
|
||||
(define-primitive
|
||||
"vector?"
|
||||
@@ -190,31 +190,31 @@
|
||||
"vector-length"
|
||||
:params ((v :as vector))
|
||||
:returns "number"
|
||||
:doc "Number of elements.")
|
||||
:doc "Number of elements in vector v.")
|
||||
|
||||
(define-primitive
|
||||
"vector-ref"
|
||||
:params ((v :as vector) (i :as number))
|
||||
:returns "any"
|
||||
:doc "Element at index.")
|
||||
:doc "Element at 0-based index i. Error if out of bounds.")
|
||||
|
||||
(define-primitive
|
||||
"vector-set!"
|
||||
:params ((v :as vector) (i :as number) (val :as any))
|
||||
:returns "nil"
|
||||
:doc "Set element at index.")
|
||||
:doc "Mutate element at index i to val. Error if out of bounds.")
|
||||
|
||||
(define-primitive
|
||||
"vector->list"
|
||||
:params ((v :as vector))
|
||||
:returns "list"
|
||||
:doc "Convert vector to list.")
|
||||
:doc "Convert vector to a fresh list.")
|
||||
|
||||
(define-primitive
|
||||
"list->vector"
|
||||
:params ((l :as list))
|
||||
:returns "vector"
|
||||
:doc "Convert list to vector.")
|
||||
:doc "Convert list to a fresh vector.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Core — Predicates
|
||||
@@ -223,13 +223,15 @@
|
||||
"vector-fill!"
|
||||
:params ((v :as vector) (val :as any))
|
||||
:returns "nil"
|
||||
:doc "Fill all elements.")
|
||||
:doc "Set every element of v to val in place.")
|
||||
|
||||
(define-primitive
|
||||
"vector-copy"
|
||||
:params ((v :as vector))
|
||||
:params ((v :as vector)
|
||||
(start :as number :optional true)
|
||||
(end :as number :optional true))
|
||||
:returns "vector"
|
||||
:doc "Independent shallow copy.")
|
||||
:doc "Shallow copy of vector, optionally sliced from start (inclusive) to end (exclusive).")
|
||||
|
||||
(define-primitive
|
||||
"min"
|
||||
@@ -372,8 +374,20 @@
|
||||
"number?"
|
||||
:params (x)
|
||||
:returns "boolean"
|
||||
:doc "True if x is a number (int or float)."
|
||||
:body (= (type-of x) "number"))
|
||||
:doc "True if x is any number — exact integer or inexact float."
|
||||
:body (or (= (type-of x) "number") (integer? x)))
|
||||
|
||||
(define-primitive
|
||||
"integer?"
|
||||
:params (x)
|
||||
:returns "boolean"
|
||||
:doc "True if x is an exact integer, or a float with no fractional part (e.g. 1.0).")
|
||||
|
||||
(define-primitive
|
||||
"float?"
|
||||
:params (x)
|
||||
:returns "boolean"
|
||||
:doc "True if x is an inexact float (Number type). Does not match exact integers.")
|
||||
|
||||
(define-primitive
|
||||
"string?"
|
||||
@@ -478,6 +492,12 @@
|
||||
:returns "string"
|
||||
:doc "Convert Unicode code point to single-character string.")
|
||||
|
||||
(define-primitive
|
||||
"char-code"
|
||||
:params ((s :as string))
|
||||
:returns "number"
|
||||
:doc "Unicode codepoint of the first character of string s.")
|
||||
|
||||
(define-primitive
|
||||
"substring"
|
||||
:params ((s :as string) (start :as number) (end :as number))
|
||||
@@ -532,15 +552,15 @@
|
||||
:returns "boolean"
|
||||
:doc "True if string s starts with prefix.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Core — Dict operations
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"ends-with?"
|
||||
:params ((s :as string) (suffix :as string))
|
||||
:returns "boolean"
|
||||
:doc "True if string s ends with suffix.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Core — Dict operations
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-module :core.collections)
|
||||
|
||||
(define-primitive
|
||||
@@ -585,15 +605,15 @@
|
||||
:returns "any"
|
||||
:doc "Last element, or nil if empty.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Stdlib — Format
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"rest"
|
||||
:params ((coll :as list))
|
||||
:returns "list"
|
||||
:doc "All elements except the first.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Stdlib — Format
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"nth"
|
||||
:params ((coll :as list) (n :as number))
|
||||
@@ -618,15 +638,15 @@
|
||||
:returns "list"
|
||||
:doc "Mutate coll by appending x in-place. Returns coll.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Stdlib — Text
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"reverse"
|
||||
:params ((coll :as list))
|
||||
:returns "list"
|
||||
:doc "Return coll in reverse order.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Stdlib — Text
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"flatten"
|
||||
:params ((coll :as list))
|
||||
@@ -645,29 +665,29 @@
|
||||
:returns "list"
|
||||
:doc "Consecutive pairs: (1 2 3 4) → ((1 2) (2 3) (3 4)).")
|
||||
|
||||
(define-module :core.dict)
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Stdlib — Style
|
||||
;; --------------------------------------------------------------------------
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Stdlib — Debug
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-module :core.dict)
|
||||
|
||||
(define-primitive
|
||||
"keys"
|
||||
:params ((d :as dict))
|
||||
:returns "list"
|
||||
:doc "List of dict keys.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Type introspection — platform primitives
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"vals"
|
||||
:params ((d :as dict))
|
||||
:returns "list"
|
||||
:doc "List of dict values.")
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Type introspection — platform primitives
|
||||
;; --------------------------------------------------------------------------
|
||||
(define-primitive
|
||||
"merge"
|
||||
:params (&rest (dicts :as dict))
|
||||
@@ -783,3 +803,526 @@
|
||||
:params ((source :as string))
|
||||
:returns "list"
|
||||
:doc "Parse SX source string into a list of AST expressions.")
|
||||
|
||||
(define-primitive
|
||||
"make-string-buffer"
|
||||
:params ()
|
||||
:returns "string-buffer"
|
||||
:doc "Create a new empty mutable string buffer for O(1) amortised append.")
|
||||
|
||||
(define-module :stdlib.coroutines)
|
||||
|
||||
(define-module :stdlib.bitwise)
|
||||
|
||||
(define-primitive
|
||||
"bitwise-and"
|
||||
:params (((a :as number) (b :as number)))
|
||||
:returns "number"
|
||||
:doc "Bitwise AND of two integers.")
|
||||
|
||||
(define-primitive
|
||||
"bitwise-or"
|
||||
:params (((a :as number) (b :as number)))
|
||||
:returns "number"
|
||||
:doc "Bitwise OR of two integers.")
|
||||
|
||||
(define-primitive
|
||||
"bitwise-xor"
|
||||
:params (((a :as number) (b :as number)))
|
||||
:returns "number"
|
||||
:doc "Bitwise XOR of two integers.")
|
||||
|
||||
(define-primitive
|
||||
"bitwise-not"
|
||||
:params ((a :as number))
|
||||
:returns "number"
|
||||
:doc "Bitwise NOT (one's complement) of an integer.")
|
||||
|
||||
(define-primitive
|
||||
"arithmetic-shift"
|
||||
:params (((a :as number) (count :as number)))
|
||||
:returns "number"
|
||||
:doc "Arithmetic shift: left if count > 0, right if count < 0.")
|
||||
|
||||
(define-primitive
|
||||
"bit-count"
|
||||
:params ((a :as number))
|
||||
:returns "number"
|
||||
:doc "Count set bits (popcount) in a non-negative integer.")
|
||||
|
||||
(define-primitive
|
||||
"integer-length"
|
||||
:params ((a :as number))
|
||||
:returns "number"
|
||||
:doc "Number of bits needed to represent integer a (excluding sign).")
|
||||
|
||||
(define-module :stdlib.ports)
|
||||
|
||||
(define-primitive
|
||||
"eof-object"
|
||||
:params ()
|
||||
:returns "eof-object"
|
||||
:doc "The EOF sentinel value.")
|
||||
|
||||
(define-primitive
|
||||
"eof-object?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is the EOF sentinel.")
|
||||
|
||||
(define-primitive
|
||||
"open-input-string"
|
||||
:params ((s :as string))
|
||||
:returns "input-port"
|
||||
:doc "Open a string as an input port.")
|
||||
|
||||
(define-primitive
|
||||
"open-output-string"
|
||||
:params ()
|
||||
:returns "output-port"
|
||||
:doc "Open a fresh output string port.")
|
||||
|
||||
(define-primitive
|
||||
"get-output-string"
|
||||
:params ((p :as output-port))
|
||||
:returns "string"
|
||||
:doc "Flush output port contents to a string.")
|
||||
|
||||
(define-primitive
|
||||
"port?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is any port.")
|
||||
|
||||
(define-primitive
|
||||
"input-port?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is an input port.")
|
||||
|
||||
(define-primitive
|
||||
"output-port?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is an output port.")
|
||||
|
||||
(define-primitive
|
||||
"close-port"
|
||||
:params ((p :as port))
|
||||
:returns "nil"
|
||||
:doc "Close a port.")
|
||||
|
||||
(define-primitive
|
||||
"read-char"
|
||||
:params (&rest (p :as input-port))
|
||||
:returns "any"
|
||||
:doc "Read next char from port; returns eof-object at end.")
|
||||
|
||||
(define-primitive
|
||||
"peek-char"
|
||||
:params (&rest (p :as input-port))
|
||||
:returns "any"
|
||||
:doc "Peek next char without consuming; returns eof-object at end.")
|
||||
|
||||
(define-primitive
|
||||
"read-line"
|
||||
:params (&rest (p :as input-port))
|
||||
:returns "any"
|
||||
:doc "Read a line from port; returns eof-object at end.")
|
||||
|
||||
(define-primitive
|
||||
"write-char"
|
||||
:params ((c :as char) &rest (p :as output-port))
|
||||
:returns "nil"
|
||||
:doc "Write a char to output port.")
|
||||
|
||||
(define-primitive
|
||||
"write-string"
|
||||
:params ((s :as string) &rest (p :as output-port))
|
||||
:returns "nil"
|
||||
:doc "Write a string to output port.")
|
||||
|
||||
(define-primitive
|
||||
"char-ready?"
|
||||
:params (&rest (p :as input-port))
|
||||
:returns "boolean"
|
||||
:doc "True if a char is immediately available on the port.")
|
||||
|
||||
|
||||
(define-primitive
|
||||
"read"
|
||||
:params (&rest (p :as input-port))
|
||||
:returns "any"
|
||||
:doc "Read one datum from port; returns eof-object at end.")
|
||||
|
||||
(define-primitive
|
||||
"write"
|
||||
:params (v &rest (p :as output-port))
|
||||
:returns "nil"
|
||||
:doc "Serialize v to port with quoting — strings quoted, chars as #\\a notation.")
|
||||
|
||||
(define-primitive
|
||||
"display"
|
||||
:params (v &rest (p :as output-port))
|
||||
:returns "nil"
|
||||
:doc "Serialize v to port without quoting — strings unquoted, chars as characters.")
|
||||
|
||||
(define-primitive
|
||||
"newline"
|
||||
:params (&rest (p :as output-port))
|
||||
:returns "nil"
|
||||
:doc "Write a newline to port.")
|
||||
|
||||
(define-primitive
|
||||
"write-to-string"
|
||||
:params (v)
|
||||
:returns "string"
|
||||
:doc "Serialize v with write quoting, return as string.")
|
||||
|
||||
(define-primitive
|
||||
"display-to-string"
|
||||
:params (v)
|
||||
:returns "string"
|
||||
:doc "Serialize v with display format, return as string.")
|
||||
|
||||
(define-primitive
|
||||
"current-input-port"
|
||||
:params ()
|
||||
:returns "any"
|
||||
:doc "Return current default input port.")
|
||||
|
||||
(define-primitive
|
||||
"current-output-port"
|
||||
:params ()
|
||||
:returns "any"
|
||||
:doc "Return current default output port.")
|
||||
|
||||
(define-primitive
|
||||
"current-error-port"
|
||||
:params ()
|
||||
:returns "any"
|
||||
:doc "Return current error port.")
|
||||
|
||||
(define-module :stdlib.math)
|
||||
|
||||
(define-primitive
|
||||
"sin"
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "Sine of x (radians).")
|
||||
|
||||
(define-primitive
|
||||
"cos"
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "Cosine of x (radians).")
|
||||
|
||||
(define-primitive
|
||||
"tan"
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "Tangent of x (radians).")
|
||||
|
||||
(define-primitive
|
||||
"asin"
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "Arc sine of x; result in radians.")
|
||||
|
||||
(define-primitive
|
||||
"acos"
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "Arc cosine of x; result in radians.")
|
||||
|
||||
(define-primitive
|
||||
"atan"
|
||||
:params ((x :as number) &rest (y :as number))
|
||||
:returns "float"
|
||||
:doc "Arc tangent. (atan x) → radians in (-π/2, π/2). (atan y x) → atan2(y, x).")
|
||||
|
||||
(define-primitive
|
||||
"exp"
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "e raised to the power x.")
|
||||
|
||||
(define-primitive
|
||||
"log"
|
||||
:params ((x :as number))
|
||||
:returns "float"
|
||||
:doc "Natural logarithm of x.")
|
||||
|
||||
(define-primitive
|
||||
"expt"
|
||||
:params ((base :as number) (exp :as number))
|
||||
:returns "number"
|
||||
:doc "base raised to the power exp. Alias: pow.")
|
||||
|
||||
(define-primitive
|
||||
"quotient"
|
||||
:params ((a :as number) (b :as number))
|
||||
:returns "integer"
|
||||
:doc "Integer quotient: truncate(a / b) toward zero. Sign follows dividend.")
|
||||
|
||||
(define-primitive
|
||||
"gcd"
|
||||
:params ((a :as number) (b :as number))
|
||||
:returns "integer"
|
||||
:doc "Greatest common divisor of a and b.")
|
||||
|
||||
(define-primitive
|
||||
"lcm"
|
||||
:params ((a :as number) (b :as number))
|
||||
:returns "integer"
|
||||
:doc "Least common multiple of a and b.")
|
||||
|
||||
(define-primitive
|
||||
"number->string"
|
||||
:params ((n :as number) &rest (radix :as number))
|
||||
:returns "string"
|
||||
:doc "Convert number n to string. Optional radix (default 10). E.g. (number->string 255 16) → \"ff\".")
|
||||
|
||||
(define-primitive
|
||||
"string->number"
|
||||
:params ((s :as string) &rest (radix :as number))
|
||||
:returns "any"
|
||||
:doc "Parse string s as a number. Optional radix (default 10). Returns nil on failure.")
|
||||
|
||||
(define-module :stdlib.rational)
|
||||
|
||||
(define-primitive
|
||||
"make-rational"
|
||||
:params (n d)
|
||||
:returns "rational"
|
||||
:doc "Rational n/d, auto-reduced by GCD. Error if d=0.")
|
||||
|
||||
(define-primitive
|
||||
"rational?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is a rational number.")
|
||||
|
||||
(define-primitive
|
||||
"numerator"
|
||||
:params ((r :as rational))
|
||||
:returns "integer"
|
||||
:doc "Numerator of rational r (after reduction).")
|
||||
|
||||
(define-primitive
|
||||
"denominator"
|
||||
:params ((r :as rational))
|
||||
:returns "integer"
|
||||
:doc "Denominator of rational r (after reduction, always positive).")
|
||||
|
||||
(define-module :stdlib.hash-table)
|
||||
|
||||
(define-module :stdlib.sets)
|
||||
|
||||
(define-primitive
|
||||
"make-set"
|
||||
:params (&rest (lst :as list))
|
||||
:returns "set"
|
||||
:doc "Create a fresh empty set. Optional list argument seeds the set: (make-set '(1 2 3)).")
|
||||
|
||||
(define-primitive
|
||||
"set?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is a set.")
|
||||
|
||||
(define-primitive
|
||||
"set-add!"
|
||||
:params (s val)
|
||||
:returns "nil"
|
||||
:doc "Add val to set s in place. No-op if already present.")
|
||||
|
||||
(define-primitive
|
||||
"set-member?"
|
||||
:params (s val)
|
||||
:returns "boolean"
|
||||
:doc "True if val is in set s.")
|
||||
|
||||
(define-primitive
|
||||
"set-remove!"
|
||||
:params (s val)
|
||||
:returns "nil"
|
||||
:doc "Remove val from set s in place. No-op if absent.")
|
||||
|
||||
(define-primitive
|
||||
"set-size"
|
||||
:params (s)
|
||||
:returns "integer"
|
||||
:doc "Number of elements in set s.")
|
||||
|
||||
(define-primitive
|
||||
"set->list"
|
||||
:params (s)
|
||||
:returns "list"
|
||||
:doc "All elements of set s as a list (unspecified order).")
|
||||
|
||||
(define-primitive
|
||||
"list->set"
|
||||
:params (lst)
|
||||
:returns "set"
|
||||
:doc "Create a new set containing all elements of lst.")
|
||||
|
||||
(define-primitive
|
||||
"set-union"
|
||||
:params (s1 s2)
|
||||
:returns "set"
|
||||
:doc "New set with all elements from s1 and s2.")
|
||||
|
||||
(define-primitive
|
||||
"set-intersection"
|
||||
:params (s1 s2)
|
||||
:returns "set"
|
||||
:doc "New set with elements present in both s1 and s2.")
|
||||
|
||||
(define-primitive
|
||||
"set-difference"
|
||||
:params (s1 s2)
|
||||
:returns "set"
|
||||
:doc "New set with elements in s1 that are not in s2.")
|
||||
|
||||
(define-primitive
|
||||
"set-for-each"
|
||||
:params (s fn)
|
||||
:returns "nil"
|
||||
:doc "Call (fn val) for each element in set s. Order unspecified.")
|
||||
|
||||
(define-primitive
|
||||
"set-map"
|
||||
:params (s fn)
|
||||
:returns "set"
|
||||
:doc "New set of results of (fn val) for each element in s.")
|
||||
|
||||
(define-module :stdlib.regexp)
|
||||
|
||||
(define-primitive
|
||||
"make-regexp"
|
||||
:params ((pattern :as string) &rest (flags :as string))
|
||||
:returns "regexp"
|
||||
:doc "Compile regexp from pattern string and optional flags string (\"i\" case-insensitive, \"m\" multiline, \"s\" dotall).")
|
||||
|
||||
(define-primitive
|
||||
"regexp?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is a compiled regexp.")
|
||||
|
||||
(define-primitive
|
||||
"regexp-source"
|
||||
:params ((re :as regexp))
|
||||
:returns "string"
|
||||
:doc "Pattern string of a regexp.")
|
||||
|
||||
(define-primitive
|
||||
"regexp-flags"
|
||||
:params ((re :as regexp))
|
||||
:returns "string"
|
||||
:doc "Flags string of a regexp.")
|
||||
|
||||
(define-primitive
|
||||
"regexp-match"
|
||||
:params ((re :as regexp) (str :as string))
|
||||
:returns "any"
|
||||
:doc "First match of re in str. Returns {:match \"...\" :start N :end N :groups (...)} or nil.")
|
||||
|
||||
(define-primitive
|
||||
"regexp-match-all"
|
||||
:params ((re :as regexp) (str :as string))
|
||||
:returns "list"
|
||||
:doc "All non-overlapping matches of re in str as a list of match dicts.")
|
||||
|
||||
(define-primitive
|
||||
"regexp-replace"
|
||||
:params ((re :as regexp) (str :as string) (replacement :as string))
|
||||
:returns "string"
|
||||
:doc "Replace first match of re in str with replacement. $& = whole match, $1..$9 = groups.")
|
||||
|
||||
(define-primitive
|
||||
"regexp-replace-all"
|
||||
:params ((re :as regexp) (str :as string) (replacement :as string))
|
||||
:returns "string"
|
||||
:doc "Replace all matches of re in str with replacement.")
|
||||
|
||||
(define-primitive
|
||||
"regexp-split"
|
||||
:params ((re :as regexp) (str :as string))
|
||||
:returns "list"
|
||||
:doc "Split str on every match of re; returns list of strings.")
|
||||
|
||||
(define-module :stdlib.bytevectors)
|
||||
|
||||
(define-primitive
|
||||
"make-bytevector"
|
||||
:params (n &rest fill)
|
||||
:returns "bytevector"
|
||||
:doc "Create a bytevector of n bytes, all initialised to fill (default 0).")
|
||||
|
||||
(define-primitive
|
||||
"bytevector?"
|
||||
:params (v)
|
||||
:returns "boolean"
|
||||
:doc "True if v is a bytevector.")
|
||||
|
||||
(define-primitive
|
||||
"bytevector-length"
|
||||
:params ((bv :as bytevector))
|
||||
:returns "number"
|
||||
:doc "Number of bytes in bv.")
|
||||
|
||||
(define-primitive
|
||||
"bytevector-u8-ref"
|
||||
:params ((bv :as bytevector) (i :as number))
|
||||
:returns "number"
|
||||
:doc "Byte value 0-255 at index i.")
|
||||
|
||||
(define-primitive
|
||||
"bytevector-u8-set!"
|
||||
:params ((bv :as bytevector) (i :as number) (byte :as number))
|
||||
:returns "nil"
|
||||
:doc "Set byte at index i to byte 0-255. Mutates bv.")
|
||||
|
||||
(define-primitive
|
||||
"bytevector-copy"
|
||||
:params ((bv :as bytevector) &rest bounds)
|
||||
:returns "bytevector"
|
||||
:doc "Fresh copy of bv, optionally sliced to [start, end).")
|
||||
|
||||
(define-primitive
|
||||
"bytevector-copy!"
|
||||
:params ((dst :as bytevector) (at :as number) (src :as bytevector) &rest bounds)
|
||||
:returns "nil"
|
||||
:doc "Copy bytes from src[start..end) into dst starting at at. Mutates dst.")
|
||||
|
||||
(define-primitive
|
||||
"bytevector-append"
|
||||
:params (&rest bvs)
|
||||
:returns "bytevector"
|
||||
:doc "Concatenate bytevectors into a new bytevector.")
|
||||
|
||||
(define-primitive
|
||||
"utf8->string"
|
||||
:params ((bv :as bytevector) &rest bounds)
|
||||
:returns "string"
|
||||
:doc "Decode bv[start..end) as UTF-8 and return the string.")
|
||||
|
||||
(define-primitive
|
||||
"string->utf8"
|
||||
:params ((s :as string) &rest bounds)
|
||||
:returns "bytevector"
|
||||
:doc "Encode s[start..end) as UTF-8 and return a bytevector.")
|
||||
|
||||
(define-primitive
|
||||
"bytevector->list"
|
||||
:params ((bv :as bytevector))
|
||||
:returns "list"
|
||||
:doc "Convert bytevector to a list of byte integers.")
|
||||
|
||||
(define-primitive
|
||||
"list->bytevector"
|
||||
:params ((lst :as list))
|
||||
:returns "bytevector"
|
||||
:doc "Build a bytevector from a list of byte integers 0-255.")
|
||||
|
||||
278
spec/tests/test-adt.sx
Normal file
278
spec/tests/test-adt.sx
Normal file
@@ -0,0 +1,278 @@
|
||||
(defsuite
|
||||
"algebraic-data-types"
|
||||
(deftest
|
||||
"constructor creates dict with adt marker"
|
||||
(do
|
||||
(define-type Maybe (Just value) (Nothing))
|
||||
(assert= true (get (Just 42) :_adt))))
|
||||
(deftest
|
||||
"constructor stores type name"
|
||||
(do
|
||||
(define-type Shape (Circle radius) (Square side))
|
||||
(assert= "Shape" (get (Circle 5) :_type))
|
||||
(assert= "Shape" (get (Square 3) :_type))))
|
||||
(deftest
|
||||
"constructor stores constructor name"
|
||||
(do
|
||||
(define-type Opt (Some val) (None))
|
||||
(assert= "Some" (get (Some 1) :_ctor))
|
||||
(assert= "None" (get (None) :_ctor))))
|
||||
(deftest
|
||||
"constructor stores fields as list"
|
||||
(do
|
||||
(define-type Pair (Pair-of fst snd))
|
||||
(assert-equal
|
||||
(list 1 2)
|
||||
(get (Pair-of 1 2) :_fields))))
|
||||
(deftest
|
||||
"zero-arg constructor has empty fields"
|
||||
(do
|
||||
(define-type Flag (Set) (Unset))
|
||||
(assert-equal (list) (get (Set) :_fields))
|
||||
(assert-equal (list) (get (Unset) :_fields))))
|
||||
(deftest
|
||||
"type predicate true for all constructors"
|
||||
(do
|
||||
(define-type Expr (Num n) (Add left right) (Neg e))
|
||||
(assert= true (Expr? (Num 5)))
|
||||
(assert= true (Expr? (Add (Num 1) (Num 2))))
|
||||
(assert= true (Expr? (Neg (Num 3))))))
|
||||
(deftest
|
||||
"type predicate false for non-adt values"
|
||||
(do
|
||||
(define-type Box (Box-of x))
|
||||
(assert= false (Box? 42))
|
||||
(assert= false (Box? "hello"))
|
||||
(assert= false (Box? nil))
|
||||
(assert= false (Box? (list 1 2)))
|
||||
(assert= false (Box? {}))))
|
||||
(deftest
|
||||
"type predicate false for wrong adt type"
|
||||
(do
|
||||
(define-type AT (AV x))
|
||||
(define-type BT (BV x))
|
||||
(assert= false (AT? (BV 1)))
|
||||
(assert= false (BT? (AV 1)))))
|
||||
(deftest
|
||||
"constructor predicate true for matching constructor"
|
||||
(do
|
||||
(define-type Result (Ok value) (Err msg))
|
||||
(assert= true (Ok? (Ok 42)))
|
||||
(assert= true (Err? (Err "bad")))))
|
||||
(deftest
|
||||
"constructor predicate false for wrong constructor"
|
||||
(do
|
||||
(define-type Coin (Heads) (Tails))
|
||||
(assert= false (Heads? (Tails)))
|
||||
(assert= false (Tails? (Heads)))))
|
||||
(deftest
|
||||
"constructor predicate false for non-adt"
|
||||
(do
|
||||
(define-type Wrap (Wrapped x))
|
||||
(assert= false (Wrapped? 42))
|
||||
(assert= false (Wrapped? nil))
|
||||
(assert= false (Wrapped? "str"))))
|
||||
(deftest
|
||||
"single-field accessor returns field value"
|
||||
(do
|
||||
(define-type Holder (Held content))
|
||||
(assert= 99 (Held-content (Held 99)))
|
||||
(assert= "hello" (Held-content (Held "hello")))))
|
||||
(deftest
|
||||
"multi-field accessors return correct fields"
|
||||
(do
|
||||
(define-type Triple (Triple-of a b c))
|
||||
(let
|
||||
((t (Triple-of 10 20 30)))
|
||||
(assert= 10 (Triple-of-a t))
|
||||
(assert= 20 (Triple-of-b t))
|
||||
(assert= 30 (Triple-of-c t)))))
|
||||
(deftest
|
||||
"tree constructors and accessors"
|
||||
(do
|
||||
(define-type Tree (Leaf) (Node left val right))
|
||||
(let
|
||||
((t (Node (Leaf) 5 (Node (Leaf) 3 (Leaf)))))
|
||||
(assert= true (Node? t))
|
||||
(assert= 5 (Node-val t))
|
||||
(assert= true (Leaf? (Node-left t)))
|
||||
(assert= true (Node? (Node-right t)))
|
||||
(assert= 3 (Node-val (Node-right t))))))
|
||||
(deftest
|
||||
"arity error on too few args"
|
||||
(do
|
||||
(define-type Pair2 (Pair2-of a b))
|
||||
(let
|
||||
((ok false))
|
||||
(guard (exn (else (set! ok true))) (Pair2-of 1))
|
||||
(assert ok))))
|
||||
(deftest
|
||||
"arity error on too many args"
|
||||
(do
|
||||
(define-type Single (Single-of x))
|
||||
(let
|
||||
((ok false))
|
||||
(guard
|
||||
(exn (else (set! ok true)))
|
||||
(Single-of 1 2))
|
||||
(assert ok))))
|
||||
(deftest
|
||||
"multiple types are independent"
|
||||
(do
|
||||
(define-type Color2 (Red2) (Green2) (Blue2))
|
||||
(define-type Suit (Hearts) (Diamonds) (Clubs) (Spades))
|
||||
(assert= false (Color2? (Hearts)))
|
||||
(assert= false (Suit? (Red2)))
|
||||
(assert= true (Color2? (Blue2)))
|
||||
(assert= true (Suit? (Spades)))))
|
||||
(deftest
|
||||
"adt fields can hold any value"
|
||||
(do
|
||||
(define-type Container (Hold x))
|
||||
(assert-equal
|
||||
(list 1 2 3)
|
||||
(Hold-x (Hold (list 1 2 3))))
|
||||
(assert-equal {:a 1} (Hold-x (Hold {:a 1})))))
|
||||
(deftest
|
||||
"adt-registry tracks type constructor names"
|
||||
(do
|
||||
(define-type Days (Mon) (Tue) (Wed) (Thu) (Fri))
|
||||
(assert-equal
|
||||
(list "Mon" "Tue" "Wed" "Thu" "Fri")
|
||||
(get *adt-registry* "Days"))))
|
||||
(deftest
|
||||
"constructors with same field name in different types are independent"
|
||||
(do
|
||||
(define-type P1 (P1-ctor value))
|
||||
(define-type P2 (P2-ctor value))
|
||||
(assert= 10 (P1-ctor-value (P1-ctor 10)))
|
||||
(assert= 20 (P2-ctor-value (P2-ctor 20)))))
|
||||
(deftest
|
||||
"match dispatches on first matching constructor"
|
||||
(do
|
||||
(define-type Color (Red) (Green) (Blue))
|
||||
(assert= "red" (match (Red) ((Red) "red") ((Green) "green") ((Blue) "blue")))
|
||||
(assert= "green" (match (Green) ((Red) "red") ((Green) "green") ((Blue) "blue")))
|
||||
(assert= "blue" (match (Blue) ((Red) "red") ((Green) "green") ((Blue) "blue")))))
|
||||
(deftest
|
||||
"match binds field to variable"
|
||||
(do
|
||||
(define-type Wrapper (Wrap val))
|
||||
(assert= 42 (match (Wrap 42) ((Wrap v) v)))
|
||||
(assert= "hi" (match (Wrap "hi") ((Wrap v) v)))))
|
||||
(deftest
|
||||
"match zero-arg constructor"
|
||||
(do
|
||||
(define-type Signal (On) (Off))
|
||||
(assert= "on" (match (On) ((On) "on") ((Off) "off")))
|
||||
(assert= "off" (match (Off) ((On) "on") ((Off) "off")))))
|
||||
(deftest
|
||||
"match multi-field constructor binds all fields"
|
||||
(do
|
||||
(define-type Vec2 (V2 x y))
|
||||
(let ((v (V2 3 4)))
|
||||
(assert= 7 (match v ((V2 a b) (+ a b)))))))
|
||||
(deftest
|
||||
"match with else clause"
|
||||
(do
|
||||
(define-type Opt2 (Some2 val) (None2))
|
||||
(assert= 10 (match (Some2 10) ((Some2 v) v) (else 0)))
|
||||
(assert= 0 (match (None2) ((Some2 v) v) (else 0)))))
|
||||
(deftest
|
||||
"match else catches non-adt values"
|
||||
(do
|
||||
(assert= "other" (match 42 ((else) "other") (else "other")))
|
||||
(assert= "other" (match "str" (else "other")))))
|
||||
(deftest
|
||||
"match returns body expression value"
|
||||
(do
|
||||
(define-type Num (Num-of n))
|
||||
(assert= 100 (match (Num-of 10) ((Num-of n) (* n n))))))
|
||||
(deftest
|
||||
"match second arm fires when first does not match"
|
||||
(do
|
||||
(define-type Either (Left val) (Right val))
|
||||
(assert= "left-1" (match (Left 1) ((Left v) (str "left-" v)) ((Right v) (str "right-" v))))
|
||||
(assert= "right-2" (match (Right 2) ((Left v) (str "left-" v)) ((Right v) (str "right-" v))))))
|
||||
(deftest
|
||||
"match wildcard _ in constructor pattern"
|
||||
(do
|
||||
(define-type Pair3 (Pair3-of a b))
|
||||
(assert= 5 (match (Pair3-of 5 99) ((Pair3-of x _) x)))
|
||||
(assert= 99 (match (Pair3-of 5 99) ((Pair3-of _ y) y)))))
|
||||
(deftest
|
||||
"match nested adt constructor pattern"
|
||||
(do
|
||||
(define-type Tree2 (Leaf2) (Node2 left val right))
|
||||
(let ((t (Node2 (Leaf2) 7 (Leaf2))))
|
||||
(assert= 7 (match t ((Node2 _ v _) v)))
|
||||
(assert= true (match t ((Node2 (Leaf2) _ _) true) (else false))))))
|
||||
(deftest
|
||||
"match literal pattern"
|
||||
(do
|
||||
(assert= "zero" (match 0 (0 "zero") (else "nonzero")))
|
||||
(assert= "hello" (match "hello" ("hello" "hello") (else "other")))))
|
||||
(deftest
|
||||
"match symbol binding pattern"
|
||||
(do
|
||||
(assert= 42 (match 42 (x x)))))
|
||||
(deftest
|
||||
"match no matching clause raises error"
|
||||
(do
|
||||
(define-type AB (A-val) (B-val))
|
||||
(let ((ok false))
|
||||
(guard (exn (else (set! ok true)))
|
||||
(match (A-val) ((B-val) "b")))
|
||||
(assert ok))))
|
||||
(deftest
|
||||
"match result used in further computation"
|
||||
(do
|
||||
(define-type Num2 (N v))
|
||||
(assert= 30
|
||||
(+
|
||||
(match (N 10) ((N v) v))
|
||||
(match (N 20) ((N v) v))))))
|
||||
(deftest
|
||||
"match with define"
|
||||
(do
|
||||
(define-type Tag (Tagged label value))
|
||||
(define get-label (fn (t) (match t ((Tagged lbl _) lbl))))
|
||||
(define get-value (fn (t) (match t ((Tagged _ val) val))))
|
||||
(let ((t (Tagged "name" 99)))
|
||||
(assert= "name" (get-label t))
|
||||
(assert= 99 (get-value t)))))
|
||||
(deftest
|
||||
"match three-field constructor"
|
||||
(do
|
||||
(define-type Triple2 (T3 a b c))
|
||||
(assert= 6 (match (T3 1 2 3) ((T3 a b c) (+ a b c))))))
|
||||
(deftest
|
||||
"match clauses tried in order"
|
||||
(do
|
||||
(define-type Expr2 (Lit n) (Add l r) (Mul l r))
|
||||
(define eval-expr2 (fn (e)
|
||||
(match e
|
||||
((Lit n) n)
|
||||
((Add l r) (+ (eval-expr2 l) (eval-expr2 r)))
|
||||
((Mul l r) (* (eval-expr2 l) (eval-expr2 r))))))
|
||||
(assert= 7 (eval-expr2 (Add (Lit 3) (Lit 4))))
|
||||
(assert= 12 (eval-expr2 (Mul (Lit 3) (Lit 4))))
|
||||
(assert= 11 (eval-expr2 (Add (Lit 2) (Mul (Lit 3) (Lit 3)))))))
|
||||
(deftest
|
||||
"match else binding captures value"
|
||||
(do
|
||||
(define-type Coin2 (Heads2) (Tails2))
|
||||
(assert= "Tails2" (match (Tails2) ((Heads2) "Heads2") (x (get x :_ctor))))))
|
||||
(deftest
|
||||
"match on adt with string field"
|
||||
(do
|
||||
(define-type Msg (Hello name) (Bye name))
|
||||
(assert= "Hello, Alice" (match (Hello "Alice") ((Hello n) (str "Hello, " n)) ((Bye n) (str "Bye, " n))))
|
||||
(assert= "Bye, Bob" (match (Bye "Bob") ((Hello n) (str "Hello, " n)) ((Bye n) (str "Bye, " n))))))
|
||||
(deftest
|
||||
"match nested pattern with variable binding"
|
||||
(do
|
||||
(define-type Box2 (Box2-of v))
|
||||
(define-type Inner (Inner-of n))
|
||||
(assert= 5 (match (Box2-of (Inner-of 5)) ((Box2-of (Inner-of n)) n)))))
|
||||
)
|
||||
157
spec/tests/test-bitwise.sx
Normal file
157
spec/tests/test-bitwise.sx
Normal file
@@ -0,0 +1,157 @@
|
||||
(defsuite
|
||||
"bitwise-operations"
|
||||
(deftest
|
||||
"bitwise-and basic"
|
||||
(do
|
||||
(assert= 0 (bitwise-and 0 0))
|
||||
(assert= 1 (bitwise-and 3 1))
|
||||
(assert= 0 (bitwise-and 5 2))
|
||||
(assert= 4 (bitwise-and 12 6))))
|
||||
(deftest
|
||||
"bitwise-and identity and zero"
|
||||
(do
|
||||
(assert= 255 (bitwise-and 255 255))
|
||||
(assert= 0 (bitwise-and 255 0))))
|
||||
(deftest
|
||||
"bitwise-or basic"
|
||||
(do
|
||||
(assert= 0 (bitwise-or 0 0))
|
||||
(assert= 3 (bitwise-or 1 2))
|
||||
(assert= 7 (bitwise-or 5 3))
|
||||
(assert= 15 (bitwise-or 9 6))))
|
||||
(deftest
|
||||
"bitwise-or identity"
|
||||
(do
|
||||
(assert= 255 (bitwise-or 255 0))
|
||||
(assert= 255 (bitwise-or 0 255))))
|
||||
(deftest
|
||||
"bitwise-xor basic"
|
||||
(do
|
||||
(assert= 0 (bitwise-xor 0 0))
|
||||
(assert= 3 (bitwise-xor 1 2))
|
||||
(assert= 6 (bitwise-xor 3 5))
|
||||
(assert= 0 (bitwise-xor 255 255))))
|
||||
(deftest
|
||||
"bitwise-xor toggle bits"
|
||||
(do
|
||||
(assert= 14 (bitwise-xor 10 4))
|
||||
(assert= 10 (bitwise-xor 14 4))))
|
||||
(deftest
|
||||
"bitwise-not zero"
|
||||
(do (assert= -1 (bitwise-not 0))))
|
||||
(deftest
|
||||
"bitwise-not positive"
|
||||
(do
|
||||
(assert= -2 (bitwise-not 1))
|
||||
(assert= -5 (bitwise-not 4))
|
||||
(assert= -256 (bitwise-not 255))))
|
||||
(deftest
|
||||
"bitwise-not negative"
|
||||
(do
|
||||
(assert= 0 (bitwise-not -1))
|
||||
(assert= 1 (bitwise-not -2))
|
||||
(assert= 4 (bitwise-not -5))))
|
||||
(deftest
|
||||
"bitwise-not double negation"
|
||||
(do
|
||||
(assert= 42 (bitwise-not (bitwise-not 42)))
|
||||
(assert= 0 (bitwise-not (bitwise-not 0)))))
|
||||
(deftest
|
||||
"arithmetic-shift left"
|
||||
(do
|
||||
(assert= 2 (arithmetic-shift 1 1))
|
||||
(assert= 4 (arithmetic-shift 1 2))
|
||||
(assert= 16 (arithmetic-shift 1 4))
|
||||
(assert= 8 (arithmetic-shift 2 2))))
|
||||
(deftest
|
||||
"arithmetic-shift right"
|
||||
(do
|
||||
(assert= 1 (arithmetic-shift 2 -1))
|
||||
(assert= 1 (arithmetic-shift 4 -2))
|
||||
(assert= 5 (arithmetic-shift 10 -1))
|
||||
(assert= 2 (arithmetic-shift 16 -3))))
|
||||
(deftest
|
||||
"arithmetic-shift by zero"
|
||||
(do
|
||||
(assert= 42 (arithmetic-shift 42 0))
|
||||
(assert= 0 (arithmetic-shift 0 5))))
|
||||
(deftest
|
||||
"arithmetic-shift negative value right preserves sign"
|
||||
(do
|
||||
(assert= -1 (arithmetic-shift -1 -1))
|
||||
(assert= -2 (arithmetic-shift -4 -1))))
|
||||
(deftest
|
||||
"bit-count zero"
|
||||
(do (assert= 0 (bit-count 0))))
|
||||
(deftest
|
||||
"bit-count powers of two"
|
||||
(do
|
||||
(assert= 1 (bit-count 1))
|
||||
(assert= 1 (bit-count 2))
|
||||
(assert= 1 (bit-count 4))
|
||||
(assert= 1 (bit-count 128))))
|
||||
(deftest
|
||||
"bit-count all-ones values"
|
||||
(do
|
||||
(assert= 8 (bit-count 255))
|
||||
(assert= 4 (bit-count 15))
|
||||
(assert= 2 (bit-count 3))))
|
||||
(deftest
|
||||
"bit-count mixed"
|
||||
(do
|
||||
(assert= 3 (bit-count 7))
|
||||
(assert= 2 (bit-count 5))
|
||||
(assert= 3 (bit-count 11))
|
||||
(assert= 4 (bit-count 30))))
|
||||
(deftest
|
||||
"integer-length zero"
|
||||
(do (assert= 0 (integer-length 0))))
|
||||
(deftest
|
||||
"integer-length powers of two"
|
||||
(do
|
||||
(assert= 1 (integer-length 1))
|
||||
(assert= 2 (integer-length 2))
|
||||
(assert= 3 (integer-length 4))
|
||||
(assert= 4 (integer-length 8))
|
||||
(assert= 8 (integer-length 128))))
|
||||
(deftest
|
||||
"integer-length non-powers"
|
||||
(do
|
||||
(assert= 2 (integer-length 3))
|
||||
(assert= 3 (integer-length 5))
|
||||
(assert= 3 (integer-length 7))
|
||||
(assert= 8 (integer-length 255))
|
||||
(assert= 9 (integer-length 256))))
|
||||
(deftest
|
||||
"bitwise ops compose"
|
||||
(do
|
||||
(assert=
|
||||
5
|
||||
(bitwise-and
|
||||
(bitwise-or 5 3)
|
||||
(bitwise-xor 7 2)))
|
||||
(assert= 0 (bitwise-and 170 85))))
|
||||
(deftest
|
||||
"arithmetic-shift round-trip"
|
||||
(do
|
||||
(assert=
|
||||
10
|
||||
(arithmetic-shift (arithmetic-shift 10 3) -3))))
|
||||
(deftest
|
||||
"extract bits with mask"
|
||||
(do
|
||||
(let
|
||||
((x 52))
|
||||
(assert=
|
||||
5
|
||||
(bitwise-and (arithmetic-shift x -2) 7)))))
|
||||
(deftest
|
||||
"clear low bits with bitwise-not mask"
|
||||
(do
|
||||
(assert= 252 (bitwise-and 255 (bitwise-not 3)))))
|
||||
(deftest
|
||||
"integer-length after shift"
|
||||
(do
|
||||
(assert=
|
||||
4
|
||||
(integer-length (arithmetic-shift 1 3))))))
|
||||
236
spec/tests/test-bytevectors.sx
Normal file
236
spec/tests/test-bytevectors.sx
Normal file
@@ -0,0 +1,236 @@
|
||||
;; ==========================================================================
|
||||
;; test-bytevectors.sx — Tests for bytevector primitives
|
||||
;; ==========================================================================
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; make-bytevector / bytevector?
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"bv:create"
|
||||
(deftest
|
||||
"make-bytevector returns bytevector"
|
||||
(assert (bytevector? (make-bytevector 4))))
|
||||
(deftest
|
||||
"make-bytevector zeroes by default"
|
||||
(let
|
||||
((bv (make-bytevector 3)))
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-u8-ref bv 0) 0)
|
||||
(= (bytevector-u8-ref bv 1) 0)
|
||||
(= (bytevector-u8-ref bv 2) 0)))))
|
||||
(deftest
|
||||
"make-bytevector with fill"
|
||||
(let
|
||||
((bv (make-bytevector 3 42)))
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-u8-ref bv 0) 42)
|
||||
(= (bytevector-u8-ref bv 1) 42)
|
||||
(= (bytevector-u8-ref bv 2) 42)))))
|
||||
(deftest
|
||||
"make-bytevector length 0"
|
||||
(assert= (bytevector-length (make-bytevector 0)) 0))
|
||||
(deftest
|
||||
"bytevector? true for bytevector"
|
||||
(assert (bytevector? (make-bytevector 2))))
|
||||
(deftest
|
||||
"bytevector? false for string"
|
||||
(assert (not (bytevector? "hello"))))
|
||||
(deftest "bytevector? false for nil" (assert (not (bytevector? nil))))
|
||||
(deftest
|
||||
"bytevector? false for list"
|
||||
(assert (not (bytevector? (list 1 2 3))))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; bytevector-length / u8-ref / u8-set!
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"bv:access"
|
||||
(deftest
|
||||
"bytevector-length"
|
||||
(assert= (bytevector-length (make-bytevector 5)) 5))
|
||||
(deftest
|
||||
"u8-ref reads fill byte"
|
||||
(assert=
|
||||
(bytevector-u8-ref (make-bytevector 4 99) 2)
|
||||
99))
|
||||
(deftest
|
||||
"u8-set! mutates"
|
||||
(let
|
||||
((bv (make-bytevector 3 0)))
|
||||
(bytevector-u8-set! bv 1 200)
|
||||
(assert= (bytevector-u8-ref bv 1) 200)))
|
||||
(deftest
|
||||
"u8-set! boundary byte 255"
|
||||
(let
|
||||
((bv (make-bytevector 1 0)))
|
||||
(bytevector-u8-set! bv 0 255)
|
||||
(assert= (bytevector-u8-ref bv 0) 255)))
|
||||
(deftest
|
||||
"u8-set! byte 0"
|
||||
(let
|
||||
((bv (make-bytevector 1 255)))
|
||||
(bytevector-u8-set! bv 0 0)
|
||||
(assert= (bytevector-u8-ref bv 0) 0))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; bytevector-copy
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"bv:copy"
|
||||
(deftest
|
||||
"copy produces equal content"
|
||||
(let
|
||||
((bv (make-bytevector 3 7)))
|
||||
(let
|
||||
((bv2 (bytevector-copy bv)))
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-u8-ref bv2 0) 7)
|
||||
(= (bytevector-u8-ref bv2 1) 7)
|
||||
(= (bytevector-u8-ref bv2 2) 7))))))
|
||||
(deftest
|
||||
"copy is independent"
|
||||
(let
|
||||
((bv (make-bytevector 2 0)))
|
||||
(let
|
||||
((bv2 (bytevector-copy bv)))
|
||||
(bytevector-u8-set! bv2 0 99)
|
||||
(assert= (bytevector-u8-ref bv 0) 0))))
|
||||
(deftest
|
||||
"copy with start"
|
||||
(let
|
||||
((bv (list->bytevector (list 10 20 30 40))))
|
||||
(let
|
||||
((bv2 (bytevector-copy bv 2)))
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-length bv2) 2)
|
||||
(= (bytevector-u8-ref bv2 0) 30))))))
|
||||
(deftest
|
||||
"copy with start and end"
|
||||
(let
|
||||
((bv (list->bytevector (list 10 20 30 40))))
|
||||
(let
|
||||
((bv2 (bytevector-copy bv 1 3)))
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-length bv2) 2)
|
||||
(= (bytevector-u8-ref bv2 0) 20)
|
||||
(= (bytevector-u8-ref bv2 1) 30)))))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; bytevector-copy!
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"bv:copy-bang"
|
||||
(deftest
|
||||
"copy! overwrites dst region"
|
||||
(let
|
||||
((dst (make-bytevector 4 0)))
|
||||
(let
|
||||
((src (list->bytevector (list 1 2 3))))
|
||||
(bytevector-copy! dst 1 src)
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-u8-ref dst 0) 0)
|
||||
(= (bytevector-u8-ref dst 1) 1)
|
||||
(= (bytevector-u8-ref dst 2) 2)
|
||||
(= (bytevector-u8-ref dst 3) 3))))))
|
||||
(deftest
|
||||
"copy! with src bounds"
|
||||
(let
|
||||
((dst (make-bytevector 2 0)))
|
||||
(let
|
||||
((src (list->bytevector (list 10 20 30 40))))
|
||||
(bytevector-copy! dst 0 src 1 3)
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-u8-ref dst 0) 20)
|
||||
(= (bytevector-u8-ref dst 1) 30)))))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; bytevector-append
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"bv:append"
|
||||
(deftest
|
||||
"append two bytevectors"
|
||||
(let
|
||||
((bv (bytevector-append (list->bytevector (list 1 2)) (list->bytevector (list 3 4)))))
|
||||
(assert
|
||||
(and
|
||||
(= (bytevector-length bv) 4)
|
||||
(= (bytevector-u8-ref bv 0) 1)
|
||||
(= (bytevector-u8-ref bv 3) 4)))))
|
||||
(deftest
|
||||
"append three bytevectors"
|
||||
(let
|
||||
((bv (bytevector-append (list->bytevector (list 1)) (list->bytevector (list 2)) (list->bytevector (list 3)))))
|
||||
(assert= (bytevector-length bv) 3)))
|
||||
(deftest
|
||||
"append empty"
|
||||
(assert=
|
||||
(bytevector-length
|
||||
(bytevector-append
|
||||
(make-bytevector 0)
|
||||
(make-bytevector 0)))
|
||||
0)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; list->bytevector / bytevector->list
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"bv:conversion"
|
||||
(deftest
|
||||
"list->bytevector roundtrip"
|
||||
(let
|
||||
((lst (list 10 20 30)))
|
||||
(assert= (bytevector->list (list->bytevector lst)) lst)))
|
||||
(deftest
|
||||
"list->bytevector empty"
|
||||
(assert= (bytevector-length (list->bytevector nil)) 0))
|
||||
(deftest
|
||||
"bytevector->list from make-bytevector"
|
||||
(let
|
||||
((lst (bytevector->list (make-bytevector 3 5))))
|
||||
(assert= lst (list 5 5 5)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; utf8 roundtrip
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"bv:utf8"
|
||||
(deftest
|
||||
"string->utf8 returns bytevector"
|
||||
(assert (bytevector? (string->utf8 "hello"))))
|
||||
(deftest
|
||||
"string->utf8 length"
|
||||
(assert= (bytevector-length (string->utf8 "abc")) 3))
|
||||
(deftest
|
||||
"utf8->string roundtrip"
|
||||
(assert= (utf8->string (string->utf8 "hello")) "hello"))
|
||||
(deftest
|
||||
"utf8->string with slice"
|
||||
(let
|
||||
((bv (string->utf8 "hello")))
|
||||
(assert= (utf8->string bv 1 4) "ell")))
|
||||
(deftest
|
||||
"string->utf8 with start"
|
||||
(assert= (utf8->string (string->utf8 "hello" 2)) "llo"))
|
||||
(deftest
|
||||
"string->utf8 with start and end"
|
||||
(assert=
|
||||
(utf8->string (string->utf8 "hello" 1 4))
|
||||
"ell"))
|
||||
(deftest
|
||||
"empty string round-trips"
|
||||
(assert= (utf8->string (string->utf8 "")) "")))
|
||||
185
spec/tests/test-chars.sx
Normal file
185
spec/tests/test-chars.sx
Normal file
@@ -0,0 +1,185 @@
|
||||
;; Tests for character type (Phase 13)
|
||||
;; Uses (make-char n) and (char-code "x") instead of #\x literals
|
||||
;; (char literal parser syntax tested via sx-parse call)
|
||||
|
||||
(deftest
|
||||
"make-char produces a char"
|
||||
(assert= true (char? (make-char 97))))
|
||||
|
||||
(deftest "char? false for string" (assert= false (char? "a")))
|
||||
|
||||
(deftest "char? false for number" (assert= false (char? 65)))
|
||||
|
||||
(deftest "char? false for nil" (assert= false (char? nil)))
|
||||
|
||||
(deftest
|
||||
"char->integer extracts codepoint"
|
||||
(assert= 97 (char->integer (make-char 97))))
|
||||
|
||||
(deftest
|
||||
"integer->char alias for make-char"
|
||||
(assert= 65 (char->integer (integer->char 65))))
|
||||
|
||||
(deftest
|
||||
"char->integer round-trip"
|
||||
(assert= 122 (char->integer (make-char 122))))
|
||||
|
||||
(deftest
|
||||
"char=? equal"
|
||||
(assert= true (char=? (make-char 97) (make-char 97))))
|
||||
|
||||
(deftest
|
||||
"char=? unequal"
|
||||
(assert= false (char=? (make-char 97) (make-char 98))))
|
||||
|
||||
(deftest
|
||||
"char<? ordering"
|
||||
(assert= true (char<? (make-char 97) (make-char 98))))
|
||||
|
||||
(deftest
|
||||
"char>? ordering"
|
||||
(assert= true (char>? (make-char 98) (make-char 97))))
|
||||
|
||||
(deftest
|
||||
"char<=? equal"
|
||||
(assert= true (char<=? (make-char 65) (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char>=? greater"
|
||||
(assert= true (char>=? (make-char 90) (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char-ci=? ignores case (a vs A)"
|
||||
(assert= true (char-ci=? (make-char 97) (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char-ci<? a < b case-insensitive"
|
||||
(assert= true (char-ci<? (make-char 97) (make-char 98))))
|
||||
|
||||
(deftest
|
||||
"char-ci>? b > a case-insensitive"
|
||||
(assert= true (char-ci>? (make-char 66) (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char-alphabetic? true for a"
|
||||
(assert= true (char-alphabetic? (make-char 97))))
|
||||
|
||||
(deftest
|
||||
"char-alphabetic? true for Z"
|
||||
(assert= true (char-alphabetic? (make-char 90))))
|
||||
|
||||
(deftest
|
||||
"char-alphabetic? false for digit"
|
||||
(assert= false (char-alphabetic? (make-char 48))))
|
||||
|
||||
(deftest
|
||||
"char-numeric? true for 0"
|
||||
(assert= true (char-numeric? (make-char 48))))
|
||||
|
||||
(deftest
|
||||
"char-numeric? true for 9"
|
||||
(assert= true (char-numeric? (make-char 57))))
|
||||
|
||||
(deftest
|
||||
"char-numeric? false for letter"
|
||||
(assert= false (char-numeric? (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char-whitespace? true for space"
|
||||
(assert= true (char-whitespace? (make-char 32))))
|
||||
|
||||
(deftest
|
||||
"char-whitespace? true for newline"
|
||||
(assert= true (char-whitespace? (make-char 10))))
|
||||
|
||||
(deftest
|
||||
"char-whitespace? false for letter"
|
||||
(assert= false (char-whitespace? (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char-upper-case? true for A"
|
||||
(assert= true (char-upper-case? (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char-upper-case? false for a"
|
||||
(assert= false (char-upper-case? (make-char 97))))
|
||||
|
||||
(deftest
|
||||
"char-lower-case? true for a"
|
||||
(assert= true (char-lower-case? (make-char 97))))
|
||||
|
||||
(deftest
|
||||
"char-lower-case? false for A"
|
||||
(assert= false (char-lower-case? (make-char 65))))
|
||||
|
||||
(deftest
|
||||
"char-upcase converts a to A"
|
||||
(assert= 65 (char->integer (char-upcase (make-char 97)))))
|
||||
|
||||
(deftest
|
||||
"char-downcase converts A to a"
|
||||
(assert=
|
||||
97
|
||||
(char->integer (char-downcase (make-char 65)))))
|
||||
|
||||
(deftest
|
||||
"char-upcase idempotent on uppercase"
|
||||
(assert= 65 (char->integer (char-upcase (make-char 65)))))
|
||||
|
||||
(deftest
|
||||
"string->list returns list of chars"
|
||||
(assert= 3 (len (string->list "abc"))))
|
||||
|
||||
(deftest
|
||||
"string->list element 0 is char"
|
||||
(assert= true (char? (get (string->list "abc") 0))))
|
||||
|
||||
(deftest
|
||||
"string->list codepoints correct"
|
||||
(assert= 97 (char->integer (get (string->list "abc") 0))))
|
||||
|
||||
(deftest
|
||||
"list->string from chars produces string"
|
||||
(assert=
|
||||
"abc"
|
||||
(list->string
|
||||
(list
|
||||
(make-char 97)
|
||||
(make-char 98)
|
||||
(make-char 99)))))
|
||||
|
||||
(deftest
|
||||
"string->list list->string round-trip"
|
||||
(let ((s "hello")) (assert= s (list->string (string->list s)))))
|
||||
|
||||
(deftest
|
||||
"char literal parsed via sx-parse"
|
||||
(let
|
||||
((ast (sx-parse "#\\a")))
|
||||
(assert= true (char? (get ast 0)))))
|
||||
|
||||
(deftest
|
||||
"char literal codepoint via sx-parse"
|
||||
(let
|
||||
((ast (sx-parse "#\\a")))
|
||||
(assert= 97 (char->integer (get ast 0)))))
|
||||
|
||||
(deftest
|
||||
"named char space via sx-parse"
|
||||
(let
|
||||
((ast (sx-parse "#\\space")))
|
||||
(assert= 32 (char->integer (get ast 0)))))
|
||||
|
||||
(deftest
|
||||
"named char newline via sx-parse"
|
||||
(let
|
||||
((ast (sx-parse "#\\newline")))
|
||||
(assert= 10 (char->integer (get ast 0)))))
|
||||
|
||||
(deftest
|
||||
"char-ci<=? equal case-insensitive"
|
||||
(assert= true (char-ci<=? (make-char 65) (make-char 97))))
|
||||
|
||||
(deftest
|
||||
"char-ci>=? equal case-insensitive"
|
||||
(assert= true (char-ci>=? (make-char 97) (make-char 65))))
|
||||
305
spec/tests/test-coroutines.sx
Normal file
305
spec/tests/test-coroutines.sx
Normal file
@@ -0,0 +1,305 @@
|
||||
(import (sx coroutines))
|
||||
|
||||
(defsuite
|
||||
"coroutine"
|
||||
(deftest
|
||||
"coroutine? recognizes coroutine objects"
|
||||
(let
|
||||
((co (make-coroutine (fn () nil))))
|
||||
(assert (coroutine? co))
|
||||
(assert= false (coroutine? 42))
|
||||
(assert= false (coroutine? "hello"))
|
||||
(assert= false (coroutine? nil))
|
||||
(assert= false (coroutine? (list)))))
|
||||
(deftest
|
||||
"coroutine-alive? true for ready coroutine"
|
||||
(let
|
||||
((co (make-coroutine (fn () nil))))
|
||||
(assert (coroutine-alive? co))))
|
||||
(deftest
|
||||
"coroutine-alive? false for non-coroutine"
|
||||
(assert= false (coroutine-alive? 42)))
|
||||
(deftest
|
||||
"immediate return — done true, value is body result"
|
||||
(let
|
||||
((co (make-coroutine (fn () 42))))
|
||||
(let
|
||||
((r (coroutine-resume co nil)))
|
||||
(assert= true (get r "done"))
|
||||
(assert= 42 (get r "value")))))
|
||||
(deftest
|
||||
"immediate nil return"
|
||||
(let
|
||||
((co (make-coroutine (fn () nil))))
|
||||
(let
|
||||
((r (coroutine-resume co nil)))
|
||||
(assert= true (get r "done"))
|
||||
(assert= nil (get r "value")))))
|
||||
(deftest
|
||||
"coroutine-alive? false after completion"
|
||||
(let
|
||||
((co (make-coroutine (fn () nil))))
|
||||
(coroutine-resume co nil)
|
||||
(assert= false (coroutine-alive? co))))
|
||||
(deftest
|
||||
"single yield — done false on yield, done true on finish"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield 10) 20))))
|
||||
(let
|
||||
((r1 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r2 (coroutine-resume co nil)))
|
||||
(assert= false (get r1 "done"))
|
||||
(assert= 10 (get r1 "value"))
|
||||
(assert= true (get r2 "done"))
|
||||
(assert= 20 (get r2 "value"))))))
|
||||
(deftest
|
||||
"coroutine-alive? true between yield and next resume"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield nil) nil))))
|
||||
(assert (coroutine-alive? co))
|
||||
(coroutine-resume co nil)
|
||||
(assert (coroutine-alive? co))
|
||||
(coroutine-resume co nil)
|
||||
(assert= false (coroutine-alive? co))))
|
||||
(deftest
|
||||
"three yields then return"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield "a") (coroutine-yield "b") (coroutine-yield "c") "z"))))
|
||||
(let
|
||||
((r1 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r2 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r3 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r4 (coroutine-resume co nil)))
|
||||
(assert= "a" (get r1 "value"))
|
||||
(assert= false (get r1 "done"))
|
||||
(assert= "b" (get r2 "value"))
|
||||
(assert= false (get r2 "done"))
|
||||
(assert= "c" (get r3 "value"))
|
||||
(assert= false (get r3 "done"))
|
||||
(assert= "z" (get r4 "value"))
|
||||
(assert= true (get r4 "done"))))))))
|
||||
(deftest
|
||||
"final return vs yield — done flag distinguishes them"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield "yielded") "returned"))))
|
||||
(let
|
||||
((y (coroutine-resume co nil)))
|
||||
(let
|
||||
((r (coroutine-resume co nil)))
|
||||
(assert= false (get y "done"))
|
||||
(assert= "yielded" (get y "value"))
|
||||
(assert= true (get r "done"))
|
||||
(assert= "returned" (get r "value"))))))
|
||||
(deftest
|
||||
"resume val becomes yield return value"
|
||||
(let
|
||||
((co (make-coroutine (fn () (let ((received (coroutine-yield "first"))) received)))))
|
||||
(let
|
||||
((r1 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r2 (coroutine-resume co 99)))
|
||||
(assert= "first" (get r1 "value"))
|
||||
(assert= false (get r1 "done"))
|
||||
(assert= 99 (get r2 "value"))
|
||||
(assert= true (get r2 "done"))))))
|
||||
(deftest
|
||||
"multiple resume values passed through yields"
|
||||
(let
|
||||
((co (make-coroutine (fn () (let ((a (coroutine-yield 1))) (let ((b (coroutine-yield 2))) (+ a b)))))))
|
||||
(let
|
||||
((r1 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r2 (coroutine-resume co 10)))
|
||||
(let
|
||||
((r3 (coroutine-resume co 20)))
|
||||
(assert= 1 (get r1 "value"))
|
||||
(assert= 2 (get r2 "value"))
|
||||
(assert= true (get r3 "done"))
|
||||
(assert= 30 (get r3 "value")))))))
|
||||
(deftest
|
||||
"coroutine captures lexical environment"
|
||||
(let
|
||||
((x 10)
|
||||
(co
|
||||
(make-coroutine
|
||||
(fn () (coroutine-yield (* x 2)) (* x 3)))))
|
||||
(let
|
||||
((r1 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r2 (coroutine-resume co nil)))
|
||||
(assert= 20 (get r1 "value"))
|
||||
(assert= 30 (get r2 "value"))))))
|
||||
(deftest
|
||||
"resuming dead coroutine raises error"
|
||||
(let
|
||||
((co (make-coroutine (fn () nil))))
|
||||
(coroutine-resume co nil)
|
||||
(assert-throws (fn () (coroutine-resume co nil)))))
|
||||
(deftest
|
||||
"coroutine drives iteration via recursive body"
|
||||
(let
|
||||
((co (make-coroutine (fn () (define loop (fn (i) (when (< i 4) (coroutine-yield i) (loop (+ i 1))))) (loop 0))))
|
||||
(results (list)))
|
||||
(let
|
||||
drive
|
||||
()
|
||||
(let
|
||||
((r (coroutine-resume co nil)))
|
||||
(when
|
||||
(not (get r "done"))
|
||||
(append! results (get r "value"))
|
||||
(drive))))
|
||||
(assert= 4 (len results))
|
||||
(assert= 0 (nth results 0))
|
||||
(assert= 1 (nth results 1))
|
||||
(assert= 2 (nth results 2))
|
||||
(assert= 3 (nth results 3))))
|
||||
(deftest
|
||||
"nested coroutine — inner resumed from outer body"
|
||||
(let
|
||||
((inner (make-coroutine (fn () (coroutine-yield "inner-a") "inner-done")))
|
||||
(outer
|
||||
(make-coroutine
|
||||
(fn
|
||||
()
|
||||
(let
|
||||
((i1 (coroutine-resume inner nil)))
|
||||
(coroutine-yield (get i1 "value")))
|
||||
(let ((i2 (coroutine-resume inner nil))) (get i2 "value"))))))
|
||||
(let
|
||||
((o1 (coroutine-resume outer nil)))
|
||||
(let
|
||||
((o2 (coroutine-resume outer nil)))
|
||||
(assert= false (get o1 "done"))
|
||||
(assert= "inner-a" (get o1 "value"))
|
||||
(assert= true (get o2 "done"))
|
||||
(assert= "inner-done" (get o2 "value"))))))
|
||||
(deftest
|
||||
"two independent coroutines interleave correctly"
|
||||
(let
|
||||
((co1 (make-coroutine (fn () (coroutine-yield 1) 5)))
|
||||
(co2
|
||||
(make-coroutine (fn () (coroutine-yield 2) 6))))
|
||||
(let
|
||||
((a (coroutine-resume co1 nil)))
|
||||
(let
|
||||
((b (coroutine-resume co2 nil)))
|
||||
(let
|
||||
((c (coroutine-resume co1 nil)))
|
||||
(let
|
||||
((d (coroutine-resume co2 nil)))
|
||||
(assert= false (get a "done"))
|
||||
(assert= 1 (get a "value"))
|
||||
(assert= false (get b "done"))
|
||||
(assert= 2 (get b "value"))
|
||||
(assert= true (get c "done"))
|
||||
(assert= 5 (get c "value"))
|
||||
(assert= true (get d "done"))
|
||||
(assert= 6 (get d "value"))))))))
|
||||
(deftest
|
||||
"coroutine state field is ready before first resume"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield 1)))))
|
||||
(assert= "ready" (get co "state"))))
|
||||
(deftest
|
||||
"coroutine state field is suspended between yields"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield 1) 2))))
|
||||
(coroutine-resume co nil)
|
||||
(assert= "suspended" (get co "state"))))
|
||||
(deftest
|
||||
"coroutine state field is dead after completion"
|
||||
(let
|
||||
((co (make-coroutine (fn () nil))))
|
||||
(coroutine-resume co nil)
|
||||
(assert= "dead" (get co "state"))))
|
||||
(deftest
|
||||
"yield works when called from nested helper function"
|
||||
(let
|
||||
((co (make-coroutine (fn () (define helper (fn (x) (coroutine-yield x))) (helper 10) (helper 20)))))
|
||||
(let
|
||||
((r1 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r2 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r3 (coroutine-resume co nil)))
|
||||
(assert= false (get r1 "done"))
|
||||
(assert= 10 (get r1 "value"))
|
||||
(assert= false (get r2 "done"))
|
||||
(assert= 20 (get r2 "value"))
|
||||
(assert= true (get r3 "done")))))))
|
||||
(deftest
|
||||
"initial resume argument is ignored by ready coroutine"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield 42)))))
|
||||
(let
|
||||
((r (coroutine-resume co "ignored")))
|
||||
(assert= false (get r "done"))
|
||||
(assert= 42 (get r "value")))))
|
||||
(deftest
|
||||
"coroutine with mutable closure state"
|
||||
(let
|
||||
((counter {:value 0}))
|
||||
(let
|
||||
((co (make-coroutine (fn () (dict-set! counter "value" 1) (coroutine-yield "a") (dict-set! counter "value" 2) (coroutine-yield "b")))))
|
||||
(assert= 0 (get counter "value"))
|
||||
(coroutine-resume co nil)
|
||||
(assert= 1 (get counter "value"))
|
||||
(coroutine-resume co nil)
|
||||
(assert= 2 (get counter "value")))))
|
||||
(deftest
|
||||
"coroutine can yield complex values"
|
||||
(let
|
||||
((co (make-coroutine (fn () (coroutine-yield (list 1 2 3)) (coroutine-yield {:key "val"})))))
|
||||
(let
|
||||
((r1 (coroutine-resume co nil)))
|
||||
(let
|
||||
((r2 (coroutine-resume co nil)))
|
||||
(assert= false (get r1 "done"))
|
||||
(assert= 3 (len (get r1 "value")))
|
||||
(assert= false (get r2 "done"))
|
||||
(assert= "val" (get (get r2 "value") "key"))))))
|
||||
(deftest
|
||||
"round-robin scheduling of multiple coroutines"
|
||||
(let
|
||||
((results (list))
|
||||
(co1
|
||||
(make-coroutine
|
||||
(fn () (coroutine-yield "a") (coroutine-yield "b"))))
|
||||
(co2
|
||||
(make-coroutine
|
||||
(fn () (coroutine-yield "c") (coroutine-yield "d")))))
|
||||
(append! results (get (coroutine-resume co1 nil) "value"))
|
||||
(append! results (get (coroutine-resume co2 nil) "value"))
|
||||
(append! results (get (coroutine-resume co1 nil) "value"))
|
||||
(append! results (get (coroutine-resume co2 nil) "value"))
|
||||
(assert= 4 (len results))
|
||||
(assert= "a" (nth results 0))
|
||||
(assert= "c" (nth results 1))
|
||||
(assert= "b" (nth results 2))
|
||||
(assert= "d" (nth results 3))))
|
||||
(deftest
|
||||
"coroutines created from same factory share no state"
|
||||
(let
|
||||
((make-counter (fn (start) (make-coroutine (fn () (define loop (fn (n) (coroutine-yield n) (loop (+ n 1)))) (loop start))))))
|
||||
(let
|
||||
((c1 (make-counter 0)) (c2 (make-counter 100)))
|
||||
(let
|
||||
((a (get (coroutine-resume c1 nil) "value")))
|
||||
(let
|
||||
((b (get (coroutine-resume c2 nil) "value")))
|
||||
(let
|
||||
((c (get (coroutine-resume c1 nil) "value")))
|
||||
(let
|
||||
((d (get (coroutine-resume c2 nil) "value")))
|
||||
(assert= 0 a)
|
||||
(assert= 100 b)
|
||||
(assert= 1 c)
|
||||
(assert= 101 d))))))))
|
||||
(deftest
|
||||
"resuming non-coroutine raises error"
|
||||
(assert-throws (fn () (coroutine-resume "not-a-coroutine" nil)))))
|
||||
113
spec/tests/test-dynamic-wind.sx
Normal file
113
spec/tests/test-dynamic-wind.sx
Normal file
@@ -0,0 +1,113 @@
|
||||
;; Tests for dynamic-wind: after-thunk fires on normal return,
|
||||
;; non-local exit via raise/guard, and call/cc escape.
|
||||
|
||||
(defsuite
|
||||
"dynamic-wind-basic"
|
||||
(deftest
|
||||
"after fires on normal return"
|
||||
(let
|
||||
((log (list)))
|
||||
(dynamic-wind
|
||||
(fn () (append! log "before"))
|
||||
(fn () (append! log "body"))
|
||||
(fn () (append! log "after")))
|
||||
(assert= 3 (len log))
|
||||
(assert= "before" (nth log 0))
|
||||
(assert= "body" (nth log 1))
|
||||
(assert= "after" (nth log 2))))
|
||||
(deftest
|
||||
"after fires on raise escape"
|
||||
(let
|
||||
((log (list)))
|
||||
(guard
|
||||
(e (true nil))
|
||||
(dynamic-wind
|
||||
(fn () (append! log "before"))
|
||||
(fn () (append! log "body") (error "boom"))
|
||||
(fn () (append! log "after"))))
|
||||
(assert= 3 (len log))
|
||||
(assert= "before" (nth log 0))
|
||||
(assert= "body" (nth log 1))
|
||||
(assert= "after" (nth log 2))))
|
||||
(deftest
|
||||
"after fires on call/cc escape"
|
||||
(let
|
||||
((log (list)))
|
||||
(call/cc
|
||||
(fn
|
||||
(k)
|
||||
(dynamic-wind
|
||||
(fn () (append! log "before"))
|
||||
(fn () (append! log "body") (k nil))
|
||||
(fn () (append! log "after")))))
|
||||
(assert= 3 (len log))
|
||||
(assert= "before" (nth log 0))
|
||||
(assert= "body" (nth log 1))
|
||||
(assert= "after" (nth log 2))))
|
||||
(deftest
|
||||
"nested dynamic-wind after-thunks fire LIFO on normal return"
|
||||
(let
|
||||
((log (list)))
|
||||
(dynamic-wind
|
||||
(fn () (append! log "outer-before"))
|
||||
(fn
|
||||
()
|
||||
(dynamic-wind
|
||||
(fn () (append! log "inner-before"))
|
||||
(fn () (append! log "inner-body"))
|
||||
(fn () (append! log "inner-after"))))
|
||||
(fn () (append! log "outer-after")))
|
||||
(assert= 5 (len log))
|
||||
(assert= "outer-before" (nth log 0))
|
||||
(assert= "inner-before" (nth log 1))
|
||||
(assert= "inner-body" (nth log 2))
|
||||
(assert= "inner-after" (nth log 3))
|
||||
(assert= "outer-after" (nth log 4))))
|
||||
(deftest
|
||||
"nested dynamic-wind after-thunks fire LIFO on raise"
|
||||
(let
|
||||
((log (list)))
|
||||
(guard
|
||||
(e (true nil))
|
||||
(dynamic-wind
|
||||
(fn () (append! log "outer-before"))
|
||||
(fn
|
||||
()
|
||||
(dynamic-wind
|
||||
(fn () (append! log "inner-before"))
|
||||
(fn () (append! log "inner-body") (error "boom"))
|
||||
(fn () (append! log "inner-after"))))
|
||||
(fn () (append! log "outer-after"))))
|
||||
(assert= 5 (len log))
|
||||
(assert= "outer-before" (nth log 0))
|
||||
(assert= "inner-before" (nth log 1))
|
||||
(assert= "inner-body" (nth log 2))
|
||||
(assert= "inner-after" (nth log 3))
|
||||
(assert= "outer-after" (nth log 4))))
|
||||
(deftest
|
||||
"before and after are called"
|
||||
(let
|
||||
((count 0))
|
||||
(dynamic-wind
|
||||
(fn () (set! count (+ count 1)))
|
||||
(fn () nil)
|
||||
(fn () (set! count (+ count 10))))
|
||||
(assert= 11 count)))
|
||||
(deftest
|
||||
"dynamic-wind return value is body result"
|
||||
(let
|
||||
((result (dynamic-wind (fn () nil) (fn () 42) (fn () nil))))
|
||||
(assert= 42 result)))
|
||||
(deftest
|
||||
"after fires before guard handler"
|
||||
(let
|
||||
((log (list)))
|
||||
(guard
|
||||
(e (true (append! log "guard-handler")))
|
||||
(dynamic-wind
|
||||
(fn () nil)
|
||||
(fn () (error "boom"))
|
||||
(fn () (append! log "after"))))
|
||||
(assert= 2 (len log))
|
||||
(assert= "after" (nth log 0))
|
||||
(assert= "guard-handler" (nth log 1)))))
|
||||
@@ -10,57 +10,56 @@
|
||||
;; Literals and types
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "literals"
|
||||
(deftest "numbers are numbers"
|
||||
(defsuite
|
||||
"literals"
|
||||
(deftest
|
||||
"numbers are numbers"
|
||||
(assert-type "number" 42)
|
||||
(assert-type "number" 3.14)
|
||||
(assert-type "number" -1))
|
||||
|
||||
(deftest "strings are strings"
|
||||
(deftest
|
||||
"strings are strings"
|
||||
(assert-type "string" "hello")
|
||||
(assert-type "string" ""))
|
||||
|
||||
(deftest "booleans are booleans"
|
||||
(deftest
|
||||
"booleans are booleans"
|
||||
(assert-type "boolean" true)
|
||||
(assert-type "boolean" false))
|
||||
|
||||
(deftest "nil is nil"
|
||||
(assert-type "nil" nil)
|
||||
(assert-nil nil))
|
||||
|
||||
(deftest "lists are lists"
|
||||
(deftest "nil is nil" (assert-type "nil" nil) (assert-nil nil))
|
||||
(deftest
|
||||
"lists are lists"
|
||||
(assert-type "list" (list 1 2 3))
|
||||
(assert-type "list" (list)))
|
||||
|
||||
(deftest "dicts are dicts"
|
||||
(assert-type "dict" {:a 1 :b 2})))
|
||||
(deftest "dicts are dicts" (assert-type "dict" {:b 2 :a 1})))
|
||||
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Arithmetic
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "arithmetic"
|
||||
(deftest "addition"
|
||||
(defsuite
|
||||
"arithmetic"
|
||||
(deftest
|
||||
"addition"
|
||||
(assert-equal 3 (+ 1 2))
|
||||
(assert-equal 0 (+ 0 0))
|
||||
(assert-equal -1 (+ 1 -2))
|
||||
(assert-equal 10 (+ 1 2 3 4)))
|
||||
|
||||
(deftest "subtraction"
|
||||
(deftest
|
||||
"subtraction"
|
||||
(assert-equal 1 (- 3 2))
|
||||
(assert-equal -1 (- 2 3)))
|
||||
|
||||
(deftest "multiplication"
|
||||
(deftest
|
||||
"multiplication"
|
||||
(assert-equal 6 (* 2 3))
|
||||
(assert-equal 0 (* 0 100))
|
||||
(assert-equal 24 (* 1 2 3 4)))
|
||||
|
||||
(deftest "division"
|
||||
(deftest
|
||||
"division"
|
||||
(assert-equal 2 (/ 6 3))
|
||||
(assert-equal 2.5 (/ 5 2)))
|
||||
|
||||
(deftest "modulo"
|
||||
(deftest
|
||||
"modulo"
|
||||
(assert-equal 1 (mod 7 3))
|
||||
(assert-equal 0 (mod 6 3))))
|
||||
|
||||
@@ -69,20 +68,26 @@
|
||||
;; Comparison
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "comparison"
|
||||
(deftest "equality"
|
||||
(defsuite
|
||||
"comparison"
|
||||
(deftest
|
||||
"equality"
|
||||
(assert-true (= 1 1))
|
||||
(assert-false (= 1 2))
|
||||
(assert-true (= "a" "a"))
|
||||
(assert-false (= "a" "b")))
|
||||
|
||||
(deftest "deep equality"
|
||||
(assert-true (equal? (list 1 2 3) (list 1 2 3)))
|
||||
(assert-false (equal? (list 1 2) (list 1 3)))
|
||||
(deftest
|
||||
"deep equality"
|
||||
(assert-true
|
||||
(equal?
|
||||
(list 1 2 3)
|
||||
(list 1 2 3)))
|
||||
(assert-false
|
||||
(equal? (list 1 2) (list 1 3)))
|
||||
(assert-true (equal? {:a 1} {:a 1}))
|
||||
(assert-false (equal? {:a 1} {:a 2})))
|
||||
|
||||
(deftest "ordering"
|
||||
(deftest
|
||||
"ordering"
|
||||
(assert-true (< 1 2))
|
||||
(assert-false (< 2 1))
|
||||
(assert-true (> 2 1))
|
||||
@@ -96,34 +101,36 @@
|
||||
;; String operations
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "strings"
|
||||
(deftest "str concatenation"
|
||||
(defsuite
|
||||
"strings"
|
||||
(deftest
|
||||
"str concatenation"
|
||||
(assert-equal "abc" (str "a" "b" "c"))
|
||||
(assert-equal "hello world" (str "hello" " " "world"))
|
||||
(assert-equal "42" (str 42))
|
||||
(assert-equal "" (str)))
|
||||
|
||||
(deftest "string-length"
|
||||
(deftest
|
||||
"string-length"
|
||||
(assert-equal 5 (string-length "hello"))
|
||||
(assert-equal 0 (string-length "")))
|
||||
|
||||
(deftest "substring"
|
||||
(deftest
|
||||
"substring"
|
||||
(assert-equal "ell" (substring "hello" 1 4))
|
||||
(assert-equal "hello" (substring "hello" 0 5)))
|
||||
|
||||
(deftest "string-contains?"
|
||||
(deftest
|
||||
"string-contains?"
|
||||
(assert-true (string-contains? "hello world" "world"))
|
||||
(assert-false (string-contains? "hello" "xyz")))
|
||||
|
||||
(deftest "upcase and downcase"
|
||||
(deftest
|
||||
"upcase and downcase"
|
||||
(assert-equal "HELLO" (upcase "hello"))
|
||||
(assert-equal "hello" (downcase "HELLO")))
|
||||
|
||||
(deftest "trim"
|
||||
(deftest
|
||||
"trim"
|
||||
(assert-equal "hello" (trim " hello "))
|
||||
(assert-equal "hello" (trim "hello")))
|
||||
|
||||
(deftest "split and join"
|
||||
(deftest
|
||||
"split and join"
|
||||
(assert-equal (list "a" "b" "c") (split "a,b,c" ","))
|
||||
(assert-equal "a-b-c" (join "-" (list "a" "b" "c")))))
|
||||
|
||||
@@ -132,121 +139,145 @@
|
||||
;; List operations
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "lists"
|
||||
(deftest "constructors"
|
||||
(assert-equal (list 1 2 3) (list 1 2 3))
|
||||
(defsuite
|
||||
"lists"
|
||||
(deftest
|
||||
"constructors"
|
||||
(assert-equal
|
||||
(list 1 2 3)
|
||||
(list 1 2 3))
|
||||
(assert-equal (list) (list))
|
||||
(assert-length 3 (list 1 2 3)))
|
||||
|
||||
(deftest "first and rest"
|
||||
(deftest
|
||||
"first and rest"
|
||||
(assert-equal 1 (first (list 1 2 3)))
|
||||
(assert-equal (list 2 3) (rest (list 1 2 3)))
|
||||
(assert-equal
|
||||
(list 2 3)
|
||||
(rest (list 1 2 3)))
|
||||
(assert-nil (first (list)))
|
||||
(assert-equal (list) (rest (list))))
|
||||
|
||||
(deftest "nth"
|
||||
(assert-equal 1 (nth (list 1 2 3) 0))
|
||||
(assert-equal 2 (nth (list 1 2 3) 1))
|
||||
(assert-equal 3 (nth (list 1 2 3) 2)))
|
||||
|
||||
(deftest "last"
|
||||
(deftest
|
||||
"nth"
|
||||
(assert-equal
|
||||
1
|
||||
(nth (list 1 2 3) 0))
|
||||
(assert-equal
|
||||
2
|
||||
(nth (list 1 2 3) 1))
|
||||
(assert-equal
|
||||
3
|
||||
(nth (list 1 2 3) 2)))
|
||||
(deftest
|
||||
"last"
|
||||
(assert-equal 3 (last (list 1 2 3)))
|
||||
(assert-nil (last (list))))
|
||||
|
||||
(deftest "cons and append"
|
||||
(assert-equal (list 0 1 2) (cons 0 (list 1 2)))
|
||||
(assert-equal (list 1 2 3 4) (append (list 1 2) (list 3 4))))
|
||||
|
||||
(deftest "reverse"
|
||||
(assert-equal (list 3 2 1) (reverse (list 1 2 3)))
|
||||
(deftest
|
||||
"cons and append"
|
||||
(assert-equal
|
||||
(list 0 1 2)
|
||||
(cons 0 (list 1 2)))
|
||||
(assert-equal
|
||||
(list 1 2 3 4)
|
||||
(append (list 1 2) (list 3 4))))
|
||||
(deftest
|
||||
"reverse"
|
||||
(assert-equal
|
||||
(list 3 2 1)
|
||||
(reverse (list 1 2 3)))
|
||||
(assert-equal (list) (reverse (list))))
|
||||
|
||||
(deftest "empty?"
|
||||
(deftest
|
||||
"empty?"
|
||||
(assert-true (empty? (list)))
|
||||
(assert-false (empty? (list 1))))
|
||||
|
||||
(deftest "len"
|
||||
(deftest
|
||||
"len"
|
||||
(assert-equal 0 (len (list)))
|
||||
(assert-equal 3 (len (list 1 2 3))))
|
||||
|
||||
(deftest "contains?"
|
||||
(assert-true (contains? (list 1 2 3) 2))
|
||||
(assert-false (contains? (list 1 2 3) 4)))
|
||||
|
||||
(deftest "flatten"
|
||||
(assert-equal (list 1 2 3 4) (flatten (list (list 1 2) (list 3 4))))))
|
||||
(deftest
|
||||
"contains?"
|
||||
(assert-true
|
||||
(contains? (list 1 2 3) 2))
|
||||
(assert-false
|
||||
(contains? (list 1 2 3) 4)))
|
||||
(deftest
|
||||
"flatten"
|
||||
(assert-equal
|
||||
(list 1 2 3 4)
|
||||
(flatten
|
||||
(list (list 1 2) (list 3 4))))))
|
||||
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Dict operations
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "dicts"
|
||||
(deftest "dict literal"
|
||||
(assert-type "dict" {:a 1 :b 2})
|
||||
(defsuite
|
||||
"dicts"
|
||||
(deftest
|
||||
"dict literal"
|
||||
(assert-type "dict" {:b 2 :a 1})
|
||||
(assert-equal 1 (get {:a 1} "a"))
|
||||
(assert-equal 2 (get {:a 1 :b 2} "b")))
|
||||
|
||||
(deftest "assoc"
|
||||
(assert-equal {:a 1 :b 2} (assoc {:a 1} "b" 2))
|
||||
(assert-equal 2 (get {:b 2 :a 1} "b")))
|
||||
(deftest
|
||||
"assoc"
|
||||
(assert-equal {:b 2 :a 1} (assoc {:a 1} "b" 2))
|
||||
(assert-equal {:a 99} (assoc {:a 1} "a" 99)))
|
||||
|
||||
(deftest "dissoc"
|
||||
(assert-equal {:b 2} (dissoc {:a 1 :b 2} "a")))
|
||||
|
||||
(deftest "keys and vals"
|
||||
(let ((d {:a 1 :b 2}))
|
||||
(deftest "dissoc" (assert-equal {:b 2} (dissoc {:b 2 :a 1} "a")))
|
||||
(deftest
|
||||
"keys and vals"
|
||||
(let
|
||||
((d {:b 2 :a 1}))
|
||||
(assert-length 2 (keys d))
|
||||
(assert-length 2 (vals d))
|
||||
(assert-contains "a" (keys d))
|
||||
(assert-contains "b" (keys d))))
|
||||
|
||||
(deftest "has-key?"
|
||||
(deftest
|
||||
"has-key?"
|
||||
(assert-true (has-key? {:a 1} "a"))
|
||||
(assert-false (has-key? {:a 1} "b")))
|
||||
|
||||
(deftest "merge"
|
||||
(assert-equal {:a 1 :b 2 :c 3}
|
||||
(merge {:a 1 :b 2} {:c 3}))
|
||||
(assert-equal {:a 99 :b 2}
|
||||
(merge {:a 1 :b 2} {:a 99}))))
|
||||
(deftest
|
||||
"merge"
|
||||
(assert-equal {:c 3 :b 2 :a 1} (merge {:b 2 :a 1} {:c 3}))
|
||||
(assert-equal {:b 2 :a 99} (merge {:b 2 :a 1} {:a 99}))))
|
||||
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Predicates
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "predicates"
|
||||
(deftest "nil?"
|
||||
(defsuite
|
||||
"predicates"
|
||||
(deftest
|
||||
"nil?"
|
||||
(assert-true (nil? nil))
|
||||
(assert-false (nil? 0))
|
||||
(assert-false (nil? false))
|
||||
(assert-false (nil? "")))
|
||||
|
||||
(deftest "number?"
|
||||
(deftest
|
||||
"number?"
|
||||
(assert-true (number? 42))
|
||||
(assert-true (number? 3.14))
|
||||
(assert-false (number? "42")))
|
||||
|
||||
(deftest "string?"
|
||||
(deftest
|
||||
"string?"
|
||||
(assert-true (string? "hello"))
|
||||
(assert-false (string? 42)))
|
||||
|
||||
(deftest "list?"
|
||||
(deftest
|
||||
"list?"
|
||||
(assert-true (list? (list 1 2)))
|
||||
(assert-false (list? "not a list")))
|
||||
|
||||
(deftest "dict?"
|
||||
(deftest
|
||||
"dict?"
|
||||
(assert-true (dict? {:a 1}))
|
||||
(assert-false (dict? (list 1))))
|
||||
|
||||
(deftest "boolean?"
|
||||
(deftest
|
||||
"boolean?"
|
||||
(assert-true (boolean? true))
|
||||
(assert-true (boolean? false))
|
||||
(assert-false (boolean? nil))
|
||||
(assert-false (boolean? 0)))
|
||||
|
||||
(deftest "not"
|
||||
(deftest
|
||||
"not"
|
||||
(assert-true (not false))
|
||||
(assert-true (not nil))
|
||||
(assert-false (not true))
|
||||
@@ -258,77 +289,67 @@
|
||||
;; Special forms
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "special-forms"
|
||||
(deftest "if"
|
||||
(defsuite
|
||||
"special-forms"
|
||||
(deftest
|
||||
"if"
|
||||
(assert-equal "yes" (if true "yes" "no"))
|
||||
(assert-equal "no" (if false "yes" "no"))
|
||||
(assert-equal "no" (if nil "yes" "no"))
|
||||
(assert-nil (if false "yes")))
|
||||
|
||||
(deftest "when"
|
||||
(deftest
|
||||
"when"
|
||||
(assert-equal "yes" (when true "yes"))
|
||||
(assert-nil (when false "yes")))
|
||||
|
||||
(deftest "cond"
|
||||
(deftest
|
||||
"cond"
|
||||
(assert-equal "a" (cond true "a" :else "b"))
|
||||
(assert-equal "b" (cond false "a" :else "b"))
|
||||
(assert-equal "c" (cond
|
||||
false "a"
|
||||
false "b"
|
||||
:else "c")))
|
||||
|
||||
(deftest "cond with 2-element predicate as first test"
|
||||
;; Regression: cond misclassifies Clojure-style as scheme-style when
|
||||
;; the first test is a 2-element list like (nil? x) or (empty? x).
|
||||
;; The evaluator checks: is first arg a 2-element list? If yes, treats
|
||||
;; as scheme-style ((test body) ...) — returning the arg instead of
|
||||
;; evaluating the predicate call.
|
||||
(assert-equal "c" (cond false "a" false "b" :else "c")))
|
||||
(deftest
|
||||
"cond with 2-element predicate as first test"
|
||||
(assert-equal 0 (cond (nil? nil) 0 :else 1))
|
||||
(assert-equal 1 (cond (nil? "x") 0 :else 1))
|
||||
(assert-equal "empty" (cond (empty? (list)) "empty" :else "not-empty"))
|
||||
(assert-equal "not-empty" (cond (empty? (list 1)) "empty" :else "not-empty"))
|
||||
(assert-equal
|
||||
"not-empty"
|
||||
(cond (empty? (list 1)) "empty" :else "not-empty"))
|
||||
(assert-equal "yes" (cond (not false) "yes" :else "no"))
|
||||
(assert-equal "no" (cond (not true) "yes" :else "no")))
|
||||
|
||||
(deftest "cond with 2-element predicate and no :else"
|
||||
;; Same bug, but without :else — this is the worst case because the
|
||||
;; bootstrapper heuristic also breaks (all clauses are 2-element lists).
|
||||
(assert-equal "found"
|
||||
(cond (nil? nil) "found"
|
||||
(nil? "x") "other"))
|
||||
(assert-equal "b"
|
||||
(cond (nil? "x") "a"
|
||||
(not false) "b")))
|
||||
|
||||
(deftest "and"
|
||||
(deftest
|
||||
"cond with 2-element predicate and no :else"
|
||||
(assert-equal "found" (cond (nil? nil) "found" (nil? "x") "other"))
|
||||
(assert-equal "b" (cond (nil? "x") "a" (not false) "b")))
|
||||
(deftest
|
||||
"and"
|
||||
(assert-true (and true true))
|
||||
(assert-false (and true false))
|
||||
(assert-false (and false true))
|
||||
(assert-equal 3 (and 1 2 3)))
|
||||
|
||||
(deftest "or"
|
||||
(deftest
|
||||
"or"
|
||||
(assert-equal 1 (or 1 2))
|
||||
(assert-equal 2 (or false 2))
|
||||
(assert-equal "fallback" (or nil false "fallback"))
|
||||
(assert-false (or false false)))
|
||||
|
||||
(deftest "let"
|
||||
(assert-equal 3 (let ((x 1) (y 2)) (+ x y)))
|
||||
(assert-equal "hello world"
|
||||
(deftest
|
||||
"let"
|
||||
(assert-equal
|
||||
3
|
||||
(let ((x 1) (y 2)) (+ x y)))
|
||||
(assert-equal
|
||||
"hello world"
|
||||
(let ((a "hello") (b " world")) (str a b))))
|
||||
|
||||
(deftest "let clojure-style"
|
||||
(deftest
|
||||
"let clojure-style"
|
||||
(assert-equal 3 (let (x 1 y 2) (+ x y))))
|
||||
|
||||
(deftest "do / begin"
|
||||
(deftest
|
||||
"do / begin"
|
||||
(assert-equal 3 (do 1 2 3))
|
||||
(assert-equal "last" (begin "first" "middle" "last")))
|
||||
|
||||
(deftest "define"
|
||||
(define x 42)
|
||||
(assert-equal 42 x))
|
||||
|
||||
(deftest "set!"
|
||||
(deftest "define" (define x 42) (assert-equal 42 x))
|
||||
(deftest
|
||||
"set!"
|
||||
(define x 1)
|
||||
(set! x 2)
|
||||
(assert-equal 2 x)))
|
||||
@@ -338,86 +359,126 @@
|
||||
;; Lambda and closures
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "lambdas"
|
||||
(deftest "basic lambda"
|
||||
(let ((add (fn (a b) (+ a b))))
|
||||
(defsuite
|
||||
"lambdas"
|
||||
(deftest
|
||||
"basic lambda"
|
||||
(let
|
||||
((add (fn (a b) (+ a b))))
|
||||
(assert-equal 3 (add 1 2))))
|
||||
|
||||
(deftest "closure captures env"
|
||||
(let ((x 10))
|
||||
(let ((add-x (fn (y) (+ x y))))
|
||||
(deftest
|
||||
"closure captures env"
|
||||
(let
|
||||
((x 10))
|
||||
(let
|
||||
((add-x (fn (y) (+ x y))))
|
||||
(assert-equal 15 (add-x 5)))))
|
||||
|
||||
(deftest "lambda as argument"
|
||||
(assert-equal (list 2 4 6)
|
||||
(map (fn (x) (* x 2)) (list 1 2 3))))
|
||||
|
||||
(deftest "recursive lambda via define"
|
||||
(define factorial
|
||||
(fn (n) (if (<= n 1) 1 (* n (factorial (- n 1))))))
|
||||
(deftest
|
||||
"lambda as argument"
|
||||
(assert-equal
|
||||
(list 2 4 6)
|
||||
(map
|
||||
(fn (x) (* x 2))
|
||||
(list 1 2 3))))
|
||||
(deftest
|
||||
"recursive lambda via define"
|
||||
(define
|
||||
factorial
|
||||
(fn
|
||||
(n)
|
||||
(if
|
||||
(<= n 1)
|
||||
1
|
||||
(* n (factorial (- n 1))))))
|
||||
(assert-equal 120 (factorial 5)))
|
||||
|
||||
(deftest "higher-order returns lambda"
|
||||
(let ((make-adder (fn (n) (fn (x) (+ n x)))))
|
||||
(let ((add5 (make-adder 5)))
|
||||
(deftest
|
||||
"higher-order returns lambda"
|
||||
(let
|
||||
((make-adder (fn (n) (fn (x) (+ n x)))))
|
||||
(let
|
||||
((add5 (make-adder 5)))
|
||||
(assert-equal 8 (add5 3)))))
|
||||
|
||||
(deftest "multi-body lambda returns last value"
|
||||
;; All body expressions must execute. Return value is the last.
|
||||
;; Catches: sf-lambda using nth(args,1) instead of rest(args).
|
||||
(let ((f (fn (x) (+ x 1) (+ x 2) (+ x 3))))
|
||||
(deftest
|
||||
"multi-body lambda returns last value"
|
||||
(let
|
||||
((f (fn (x) (+ x 1) (+ x 2) (+ x 3))))
|
||||
(assert-equal 13 (f 10))))
|
||||
|
||||
(deftest "multi-body lambda side effects via dict mutation"
|
||||
;; Verify all body expressions run by mutating a shared dict.
|
||||
(let ((state (dict "a" 0 "b" 0)))
|
||||
(let ((f (fn ()
|
||||
(dict-set! state "a" 1)
|
||||
(dict-set! state "b" 2)
|
||||
"done")))
|
||||
(deftest
|
||||
"multi-body lambda side effects via dict mutation"
|
||||
(let
|
||||
((state (dict "a" 0 "b" 0)))
|
||||
(let
|
||||
((f (fn () (dict-set! state "a" 1) (dict-set! state "b" 2) "done")))
|
||||
(assert-equal "done" (f))
|
||||
(assert-equal 1 (get state "a"))
|
||||
(assert-equal 2 (get state "b")))))
|
||||
|
||||
(deftest "multi-body lambda two expressions"
|
||||
;; Simplest case: two body expressions, return value is second.
|
||||
(assert-equal 20
|
||||
(deftest
|
||||
"multi-body lambda two expressions"
|
||||
(assert-equal
|
||||
20
|
||||
((fn (x) (+ x 1) (* x 2)) 10))
|
||||
;; And with zero-arg lambda
|
||||
(assert-equal 42
|
||||
((fn () (+ 1 2) 42)))))
|
||||
(assert-equal 42 ((fn () (+ 1 2) 42)))))
|
||||
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Higher-order forms
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "higher-order"
|
||||
(deftest "map"
|
||||
(assert-equal (list 2 4 6)
|
||||
(map (fn (x) (* x 2)) (list 1 2 3)))
|
||||
(defsuite
|
||||
"higher-order"
|
||||
(deftest
|
||||
"map"
|
||||
(assert-equal
|
||||
(list 2 4 6)
|
||||
(map
|
||||
(fn (x) (* x 2))
|
||||
(list 1 2 3)))
|
||||
(assert-equal (list) (map (fn (x) x) (list))))
|
||||
|
||||
(deftest "filter"
|
||||
(assert-equal (list 2 4)
|
||||
(filter (fn (x) (= (mod x 2) 0)) (list 1 2 3 4)))
|
||||
(assert-equal (list)
|
||||
(deftest
|
||||
"filter"
|
||||
(assert-equal
|
||||
(list 2 4)
|
||||
(filter
|
||||
(fn (x) (= (mod x 2) 0))
|
||||
(list 1 2 3 4)))
|
||||
(assert-equal
|
||||
(list)
|
||||
(filter (fn (x) false) (list 1 2 3))))
|
||||
|
||||
(deftest "reduce"
|
||||
(assert-equal 10 (reduce (fn (acc x) (+ acc x)) 0 (list 1 2 3 4)))
|
||||
(assert-equal 0 (reduce (fn (acc x) (+ acc x)) 0 (list))))
|
||||
|
||||
(deftest "some"
|
||||
(assert-true (some (fn (x) (> x 3)) (list 1 2 3 4 5)))
|
||||
(assert-false (some (fn (x) (> x 10)) (list 1 2 3))))
|
||||
|
||||
(deftest "every?"
|
||||
(assert-true (every? (fn (x) (> x 0)) (list 1 2 3)))
|
||||
(assert-false (every? (fn (x) (> x 2)) (list 1 2 3))))
|
||||
|
||||
(deftest "map-indexed"
|
||||
(assert-equal (list "0:a" "1:b" "2:c")
|
||||
(deftest
|
||||
"reduce"
|
||||
(assert-equal
|
||||
10
|
||||
(reduce
|
||||
(fn (acc x) (+ acc x))
|
||||
0
|
||||
(list 1 2 3 4)))
|
||||
(assert-equal
|
||||
0
|
||||
(reduce (fn (acc x) (+ acc x)) 0 (list))))
|
||||
(deftest
|
||||
"some"
|
||||
(assert-true
|
||||
(some
|
||||
(fn (x) (> x 3))
|
||||
(list 1 2 3 4 5)))
|
||||
(assert-false
|
||||
(some
|
||||
(fn (x) (> x 10))
|
||||
(list 1 2 3))))
|
||||
(deftest
|
||||
"every?"
|
||||
(assert-true
|
||||
(every?
|
||||
(fn (x) (> x 0))
|
||||
(list 1 2 3)))
|
||||
(assert-false
|
||||
(every?
|
||||
(fn (x) (> x 2))
|
||||
(list 1 2 3))))
|
||||
(deftest
|
||||
"map-indexed"
|
||||
(assert-equal
|
||||
(list "0:a" "1:b" "2:c")
|
||||
(map-indexed (fn (i x) (str i ":" x)) (list "a" "b" "c")))))
|
||||
|
||||
|
||||
@@ -425,49 +486,39 @@
|
||||
;; Components
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "components"
|
||||
(deftest "defcomp creates component"
|
||||
(defcomp ~test-comp (&key title)
|
||||
(div title))
|
||||
(defsuite
|
||||
"components"
|
||||
(deftest
|
||||
"defcomp creates component"
|
||||
(defcomp ~test-comp (&key title) (div title))
|
||||
(assert-true (not (nil? ~test-comp))))
|
||||
|
||||
(deftest "component renders with keyword args"
|
||||
(defcomp ~greeting (&key name)
|
||||
(span (str "Hello, " name "!")))
|
||||
(deftest
|
||||
"component renders with keyword args"
|
||||
(defcomp ~greeting (&key name) (span (str "Hello, " name "!")))
|
||||
(assert-true (not (nil? ~greeting))))
|
||||
|
||||
(deftest "component with children"
|
||||
(defcomp ~box (&key &rest children)
|
||||
(div :class "box" children))
|
||||
(deftest
|
||||
"component with children"
|
||||
(defcomp ~box (&key &rest children) (div :class "box" children))
|
||||
(assert-true (not (nil? ~box))))
|
||||
|
||||
(deftest "component with default via or"
|
||||
(defcomp ~label (&key text)
|
||||
(span (or text "default")))
|
||||
(deftest
|
||||
"component with default via or"
|
||||
(defcomp ~label (&key text) (span (or text "default")))
|
||||
(assert-true (not (nil? ~label))))
|
||||
|
||||
(deftest "defcomp default affinity is auto"
|
||||
(defcomp ~aff-default (&key x)
|
||||
(div x))
|
||||
(deftest
|
||||
"defcomp default affinity is auto"
|
||||
(defcomp ~aff-default (&key x) (div x))
|
||||
(assert-equal "auto" (component-affinity ~aff-default)))
|
||||
|
||||
(deftest "defcomp affinity client"
|
||||
(defcomp ~aff-client (&key x)
|
||||
:affinity :client
|
||||
(div x))
|
||||
(deftest
|
||||
"defcomp affinity client"
|
||||
(defcomp ~aff-client (&key x) :affinity :client (div x))
|
||||
(assert-equal "client" (component-affinity ~aff-client)))
|
||||
|
||||
(deftest "defcomp affinity server"
|
||||
(defcomp ~aff-server (&key x)
|
||||
:affinity :server
|
||||
(div x))
|
||||
(deftest
|
||||
"defcomp affinity server"
|
||||
(defcomp ~aff-server (&key x) :affinity :server (div x))
|
||||
(assert-equal "server" (component-affinity ~aff-server)))
|
||||
|
||||
(deftest "defcomp affinity preserves body"
|
||||
(defcomp ~aff-body (&key val)
|
||||
:affinity :client
|
||||
(span val))
|
||||
;; Component should still render correctly
|
||||
(deftest
|
||||
"defcomp affinity preserves body"
|
||||
(defcomp ~aff-body (&key val) :affinity :client (span val))
|
||||
(assert-equal "client" (component-affinity ~aff-body))
|
||||
(assert-true (not (nil? ~aff-body)))))
|
||||
|
||||
@@ -476,93 +527,98 @@
|
||||
;; Macros
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "macros"
|
||||
(deftest "defmacro creates macro"
|
||||
(defmacro unless (cond &rest body)
|
||||
`(if (not ,cond) (do ,@body)))
|
||||
(defsuite
|
||||
"macros"
|
||||
(deftest
|
||||
"defmacro creates macro"
|
||||
(defmacro
|
||||
unless
|
||||
(cond &rest body)
|
||||
(quasiquote (if (not (unquote cond)) (do (splice-unquote body)))))
|
||||
(assert-equal "yes" (unless false "yes"))
|
||||
(assert-nil (unless true "no")))
|
||||
|
||||
(deftest "quasiquote and unquote"
|
||||
(let ((x 42))
|
||||
(assert-equal (list 1 42 3) `(1 ,x 3))))
|
||||
|
||||
(deftest "splice-unquote"
|
||||
(let ((xs (list 2 3 4)))
|
||||
(assert-equal (list 1 2 3 4 5) `(1 ,@xs 5)))))
|
||||
(deftest
|
||||
"quasiquote and unquote"
|
||||
(let
|
||||
((x 42))
|
||||
(assert-equal
|
||||
(list 1 42 3)
|
||||
(quasiquote (1 (unquote x) 3)))))
|
||||
(deftest
|
||||
"splice-unquote"
|
||||
(let
|
||||
((xs (list 2 3 4)))
|
||||
(assert-equal
|
||||
(list 1 2 3 4 5)
|
||||
(quasiquote (1 (splice-unquote xs) 5))))))
|
||||
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Threading macro
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "threading"
|
||||
(deftest "thread-first"
|
||||
(defsuite
|
||||
"threading"
|
||||
(deftest
|
||||
"thread-first"
|
||||
(assert-equal 8 (-> 5 (+ 1) (+ 2)))
|
||||
(assert-equal "HELLO" (-> "hello" upcase))
|
||||
(assert-equal "HELLO WORLD"
|
||||
(-> "hello"
|
||||
(str " world")
|
||||
upcase))))
|
||||
(assert-equal "HELLO WORLD" (-> "hello" (str " world") upcase))))
|
||||
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Truthiness
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "truthiness"
|
||||
(deftest "truthy values"
|
||||
(defsuite
|
||||
"truthiness"
|
||||
(deftest
|
||||
"truthy values"
|
||||
(assert-true (if 1 true false))
|
||||
(assert-true (if "x" true false))
|
||||
(assert-true (if (list 1) true false))
|
||||
(assert-true (if true true false)))
|
||||
|
||||
(deftest "falsy values"
|
||||
(deftest
|
||||
"falsy values"
|
||||
(assert-false (if false true false))
|
||||
(assert-false (if nil true false)))
|
||||
|
||||
;; NOTE: empty list, zero, and empty string truthiness is
|
||||
;; platform-dependent. Python treats all three as falsy.
|
||||
;; JavaScript treats [] as truthy but 0 and "" as falsy.
|
||||
;; These tests are omitted — each bootstrapper should emit
|
||||
;; platform-specific truthiness tests instead.
|
||||
)
|
||||
(assert-false (if nil true false))))
|
||||
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Edge cases and regression tests
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "edge-cases"
|
||||
(deftest "nested let scoping"
|
||||
(let ((x 1))
|
||||
(let ((x 2))
|
||||
(assert-equal 2 x))
|
||||
;; outer x should be unchanged by inner let
|
||||
;; (this tests that let creates a new scope)
|
||||
))
|
||||
|
||||
(deftest "recursive map"
|
||||
(assert-equal (list (list 2 4) (list 6 8))
|
||||
(map (fn (sub) (map (fn (x) (* x 2)) sub))
|
||||
(list (list 1 2) (list 3 4)))))
|
||||
|
||||
(deftest "keyword as value"
|
||||
(defsuite
|
||||
"edge-cases"
|
||||
(deftest
|
||||
"nested let scoping"
|
||||
(let
|
||||
((x 1))
|
||||
(let ((x 2)) (assert-equal 2 x))))
|
||||
(deftest
|
||||
"recursive map"
|
||||
(assert-equal
|
||||
(list (list 2 4) (list 6 8))
|
||||
(map
|
||||
(fn (sub) (map (fn (x) (* x 2)) sub))
|
||||
(list (list 1 2) (list 3 4)))))
|
||||
(deftest
|
||||
"keyword as value"
|
||||
(assert-equal "class" :class)
|
||||
(assert-equal "id" :id))
|
||||
|
||||
(deftest "dict with evaluated values"
|
||||
(let ((x 42))
|
||||
(assert-equal 42 (get {:val x} "val"))))
|
||||
|
||||
(deftest "nil propagation"
|
||||
(deftest
|
||||
"dict with evaluated values"
|
||||
(let ((x 42)) (assert-equal 42 (get {:val x} "val"))))
|
||||
(deftest
|
||||
"nil propagation"
|
||||
(assert-nil (get {:a 1} "missing"))
|
||||
(assert-equal "default" (or (get {:a 1} "missing") "default")))
|
||||
|
||||
(deftest "empty operations"
|
||||
(deftest
|
||||
"empty operations"
|
||||
(assert-equal (list) (map (fn (x) x) (list)))
|
||||
(assert-equal (list) (filter (fn (x) true) (list)))
|
||||
(assert-equal 0 (reduce (fn (acc x) (+ acc x)) 0 (list)))
|
||||
(assert-equal
|
||||
0
|
||||
(reduce (fn (acc x) (+ acc x)) 0 (list)))
|
||||
(assert-equal 0 (len (list)))
|
||||
(assert-equal "" (str))))
|
||||
|
||||
|
||||
78
spec/tests/test-gensym.sx
Normal file
78
spec/tests/test-gensym.sx
Normal file
@@ -0,0 +1,78 @@
|
||||
(defsuite
|
||||
"gensym"
|
||||
(deftest "gensym returns a symbol" (assert= true (symbol? (gensym))))
|
||||
(deftest
|
||||
"gensym default prefix is g"
|
||||
(let
|
||||
((s (symbol-name (gensym))))
|
||||
(assert= true (string-contains? s "g"))))
|
||||
(deftest
|
||||
"gensym with prefix uses that prefix"
|
||||
(let
|
||||
((s (symbol-name (gensym "var"))))
|
||||
(assert= "var" (substring s 0 3))))
|
||||
(deftest
|
||||
"gensym produces unique symbols"
|
||||
(let
|
||||
((a (gensym)) (b (gensym)))
|
||||
(assert= false (= (symbol-name a) (symbol-name b)))))
|
||||
(deftest
|
||||
"gensym same prefix produces unique symbols"
|
||||
(let
|
||||
((a (gensym "x")) (b (gensym "x")) (c (gensym "x")))
|
||||
(assert= false (= (symbol-name a) (symbol-name b)))
|
||||
(assert= false (= (symbol-name b) (symbol-name c)))))
|
||||
(deftest
|
||||
"gensym counter increases: names differ"
|
||||
(let
|
||||
((a (gensym "k")) (b (gensym "k")))
|
||||
(assert= false (= (symbol-name a) (symbol-name b)))))
|
||||
(deftest
|
||||
"gensym no-arg and prefix-arg both unique"
|
||||
(let
|
||||
((a (gensym)) (b (gensym "g")))
|
||||
(assert= false (= (symbol-name a) (symbol-name b)))))
|
||||
(deftest
|
||||
"string->symbol returns a symbol"
|
||||
(assert= true (symbol? (string->symbol "hello"))))
|
||||
(deftest
|
||||
"string->symbol symbol has correct name"
|
||||
(assert= "hello" (symbol-name (string->symbol "hello"))))
|
||||
(deftest
|
||||
"string->symbol empty string"
|
||||
(assert= true (symbol? (string->symbol ""))))
|
||||
(deftest
|
||||
"symbol->string returns a string"
|
||||
(assert= true (string? (symbol->string (quote foo)))))
|
||||
(deftest
|
||||
"symbol->string round-trips with string->symbol"
|
||||
(assert= "hello" (symbol->string (string->symbol "hello"))))
|
||||
(deftest
|
||||
"string->symbol/symbol->string round-trip"
|
||||
(let
|
||||
((sym (string->symbol "my-var")))
|
||||
(assert= "my-var" (symbol->string sym))))
|
||||
(deftest
|
||||
"intern returns a symbol"
|
||||
(assert= true (symbol? (intern "foo"))))
|
||||
(deftest
|
||||
"intern same as string->symbol"
|
||||
(assert= "bar" (symbol-name (intern "bar"))))
|
||||
(deftest
|
||||
"symbol-interned? true for literal symbols"
|
||||
(assert= true (symbol-interned? (quote hello))))
|
||||
(deftest
|
||||
"symbol-interned? true for gensym'd symbol"
|
||||
(assert= true (symbol-interned? (gensym "g"))))
|
||||
(deftest
|
||||
"symbol-interned? true for string->symbol"
|
||||
(assert= true (symbol-interned? (string->symbol "test"))))
|
||||
(deftest
|
||||
"multiple gensym calls all unique"
|
||||
(let
|
||||
((syms (map (fn (i) (gensym "t")) (in-range 5))))
|
||||
(let
|
||||
((names (map symbol-name syms)))
|
||||
(let
|
||||
((unique-names (reduce (fn (acc n) (if (some (fn (x) (= x n)) acc) acc (cons n acc))) (list) names)))
|
||||
(assert-equal 5 (len unique-names)))))))
|
||||
166
spec/tests/test-hash-table.sx
Normal file
166
spec/tests/test-hash-table.sx
Normal file
@@ -0,0 +1,166 @@
|
||||
;; Tests for mutable hash tables (Phase 10)
|
||||
|
||||
(defsuite
|
||||
"hash-table"
|
||||
(deftest
|
||||
"make-hash-table returns a hash table"
|
||||
(assert (hash-table? (make-hash-table))))
|
||||
(deftest
|
||||
"hash-table? false for dict"
|
||||
(assert= false (hash-table? {:a 1})))
|
||||
(deftest "hash-table? false for nil" (assert= false (hash-table? nil)))
|
||||
(deftest
|
||||
"hash-table? false for list"
|
||||
(assert= false (hash-table? (list 1 2))))
|
||||
(deftest
|
||||
"empty table has size 0"
|
||||
(assert= 0 (hash-table-size (make-hash-table))))
|
||||
(deftest
|
||||
"size after one set"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "a" 1)
|
||||
(assert= 1 (hash-table-size ht))))
|
||||
(deftest
|
||||
"size after multiple sets"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "a" 1)
|
||||
(hash-table-set! ht "b" 2)
|
||||
(hash-table-set! ht "c" 3)
|
||||
(assert= 3 (hash-table-size ht))))
|
||||
(deftest
|
||||
"set same key does not grow size"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "a" 1)
|
||||
(hash-table-set! ht "a" 2)
|
||||
(assert= 1 (hash-table-size ht))))
|
||||
(deftest
|
||||
"ref returns set value"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "k" 42)
|
||||
(assert= 42 (hash-table-ref ht "k"))))
|
||||
(deftest
|
||||
"ref returns updated value after overwrite"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "k" 1)
|
||||
(hash-table-set! ht "k" 99)
|
||||
(assert= 99 (hash-table-ref ht "k"))))
|
||||
(deftest
|
||||
"ref with default returns default for missing key"
|
||||
(assert=
|
||||
"fallback"
|
||||
(hash-table-ref (make-hash-table) "missing" "fallback")))
|
||||
(deftest
|
||||
"ref with default returns value when key exists"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "x" 7)
|
||||
(assert= 7 (hash-table-ref ht "x" 0))))
|
||||
(deftest
|
||||
"keyword keys work"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht :foo "bar")
|
||||
(assert= "bar" (hash-table-ref ht :foo))))
|
||||
(deftest
|
||||
"number keys work"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht 0 "zero")
|
||||
(assert= "zero" (hash-table-ref ht 0))))
|
||||
(deftest
|
||||
"delete removes key"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "x" 1)
|
||||
(hash-table-delete! ht "x")
|
||||
(assert= "gone" (hash-table-ref ht "x" "gone"))))
|
||||
(deftest
|
||||
"delete reduces size"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "a" 1)
|
||||
(hash-table-set! ht "b" 2)
|
||||
(hash-table-delete! ht "a")
|
||||
(assert= 1 (hash-table-size ht))))
|
||||
(deftest
|
||||
"delete missing key is no-op"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-delete! ht "absent")
|
||||
(assert= 0 (hash-table-size ht))))
|
||||
(deftest
|
||||
"keys of empty table is empty"
|
||||
(assert (empty? (hash-table-keys (make-hash-table)))))
|
||||
(deftest
|
||||
"keys has correct count"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "a" 1)
|
||||
(hash-table-set! ht "b" 2)
|
||||
(assert= 2 (len (hash-table-keys ht)))))
|
||||
(deftest
|
||||
"values has correct count"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "a" 10)
|
||||
(hash-table-set! ht "b" 20)
|
||||
(assert= 2 (len (hash-table-values ht)))))
|
||||
(deftest
|
||||
"alist of empty table is empty"
|
||||
(assert (empty? (hash-table->alist (make-hash-table)))))
|
||||
(deftest
|
||||
"alist has correct length"
|
||||
(let
|
||||
((ht (make-hash-table)))
|
||||
(hash-table-set! ht "x" 1)
|
||||
(hash-table-set! ht "y" 2)
|
||||
(assert= 2 (len (hash-table->alist ht)))))
|
||||
(deftest
|
||||
"for-each visits all entries"
|
||||
(let
|
||||
((ht (make-hash-table)) (count 0))
|
||||
(hash-table-set! ht "a" 1)
|
||||
(hash-table-set! ht "b" 2)
|
||||
(hash-table-set! ht "c" 3)
|
||||
(hash-table-for-each ht (fn (k v) (set! count (+ count 1))))
|
||||
(assert= 3 count)))
|
||||
(deftest
|
||||
"for-each sums values"
|
||||
(let
|
||||
((ht (make-hash-table)) (total 0))
|
||||
(hash-table-set! ht "a" 10)
|
||||
(hash-table-set! ht "b" 20)
|
||||
(hash-table-set! ht "c" 30)
|
||||
(hash-table-for-each ht (fn (k v) (set! total (+ total v))))
|
||||
(assert= 60 total)))
|
||||
(deftest
|
||||
"merge copies entries from src to dst"
|
||||
(let
|
||||
((dst (make-hash-table)) (src (make-hash-table)))
|
||||
(hash-table-set! src "x" 1)
|
||||
(hash-table-set! src "y" 2)
|
||||
(hash-table-merge! dst src)
|
||||
(assert= 2 (hash-table-size dst))))
|
||||
(deftest
|
||||
"merge overwrites existing keys in dst"
|
||||
(let
|
||||
((dst (make-hash-table)) (src (make-hash-table)))
|
||||
(hash-table-set! dst "k" "old")
|
||||
(hash-table-set! src "k" "new")
|
||||
(hash-table-merge! dst src)
|
||||
(assert= "new" (hash-table-ref dst "k"))))
|
||||
(deftest
|
||||
"merge does not modify src"
|
||||
(let
|
||||
((dst (make-hash-table)) (src (make-hash-table)))
|
||||
(hash-table-set! src "a" 1)
|
||||
(hash-table-merge! dst src)
|
||||
(assert= 1 (hash-table-size src))))
|
||||
(deftest
|
||||
"type-of returns hash-table"
|
||||
(assert= "hash-table" (type-of (make-hash-table)))))
|
||||
@@ -88,6 +88,27 @@
|
||||
(raise _e))))
|
||||
(handler me-val))))))
|
||||
|
||||
;; Evaluate a hyperscript expression, catch the first error raised, and
|
||||
;; return its message string. Used by runtimeErrors tests.
|
||||
;; Returns nil if no error is raised (test would then fail equality).
|
||||
(define eval-hs-error
|
||||
(fn (src)
|
||||
(let ((sx (hs-to-sx (hs-compile src))))
|
||||
(let ((handler (eval-expr-cek
|
||||
(list (quote fn) (list (quote me))
|
||||
(list (quote let) (list (list (quote it) nil) (list (quote event) nil)) sx)))))
|
||||
(guard
|
||||
(_e
|
||||
(true
|
||||
(if
|
||||
(string? _e)
|
||||
_e
|
||||
(if
|
||||
(and (list? _e) (= (first _e) "hs-return"))
|
||||
nil
|
||||
(str _e)))))
|
||||
(begin (handler nil) nil))))))
|
||||
|
||||
;; ── add (19 tests) ──
|
||||
(defsuite "hs-upstream-add"
|
||||
(deftest "can add a value to a set"
|
||||
@@ -2153,41 +2174,75 @@
|
||||
;; ── core/runtimeErrors (18 tests) ──
|
||||
(defsuite "hs-upstream-core/runtimeErrors"
|
||||
(deftest "reports basic function invocation null errors properly"
|
||||
(error "SKIP (untranslated): reports basic function invocation null errors properly"))
|
||||
(assert= (eval-hs-error "x()") "'x' is null")
|
||||
(assert= (eval-hs-error "x.y()") "'x' is null")
|
||||
(assert= (eval-hs-error "x.y.z()") "'x.y' is null")
|
||||
)
|
||||
(deftest "reports basic function invocation null errors properly w/ of"
|
||||
(error "SKIP (untranslated): reports basic function invocation null errors properly w/ of"))
|
||||
(assert= (eval-hs-error "z() of y of x") "'z' is null")
|
||||
)
|
||||
(deftest "reports basic function invocation null errors properly w/ possessives"
|
||||
(error "SKIP (untranslated): reports basic function invocation null errors properly w/ possessives"))
|
||||
(assert= (eval-hs-error "x's y()") "'x' is null")
|
||||
(assert= (eval-hs-error "x's y's z()") "'x's y' is null")
|
||||
)
|
||||
(deftest "reports null errors on add command properly"
|
||||
(error "SKIP (untranslated): reports null errors on add command properly"))
|
||||
(assert= (eval-hs-error "add .foo to #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "add @foo to #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "add {display:none} to #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on decrement command properly"
|
||||
(error "SKIP (untranslated): reports null errors on decrement command properly"))
|
||||
(assert= (eval-hs-error "decrement #doesntExist's innerHTML") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on default command properly"
|
||||
(error "SKIP (untranslated): reports null errors on default command properly"))
|
||||
(assert= (eval-hs-error "default #doesntExist's innerHTML to 'foo'") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on hide command properly"
|
||||
(error "SKIP (untranslated): reports null errors on hide command properly"))
|
||||
(assert= (eval-hs-error "hide #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on increment command properly"
|
||||
(error "SKIP (untranslated): reports null errors on increment command properly"))
|
||||
(assert= (eval-hs-error "increment #doesntExist's innerHTML") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on measure command properly"
|
||||
(error "SKIP (untranslated): reports null errors on measure command properly"))
|
||||
(assert= (eval-hs-error "measure #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on put command properly"
|
||||
(error "SKIP (untranslated): reports null errors on put command properly"))
|
||||
(assert= (eval-hs-error "put 'foo' into #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "put 'foo' into #doesntExist's innerHTML") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "put 'foo' into #doesntExist.innerHTML") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "put 'foo' before #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "put 'foo' after #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "put 'foo' at the start of #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "put 'foo' at the end of #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on remove command properly"
|
||||
(error "SKIP (untranslated): reports null errors on remove command properly"))
|
||||
(assert= (eval-hs-error "remove .foo from #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "remove @foo from #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "remove #doesntExist from #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on send command properly"
|
||||
(error "SKIP (untranslated): reports null errors on send command properly"))
|
||||
(assert= (eval-hs-error "send 'foo' to #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on sets properly"
|
||||
(error "SKIP (untranslated): reports null errors on sets properly"))
|
||||
(assert= (eval-hs-error "set x's y to true") "'x' is null")
|
||||
(assert= (eval-hs-error "set x's @y to true") "'x' is null")
|
||||
)
|
||||
(deftest "reports null errors on settle command properly"
|
||||
(error "SKIP (untranslated): reports null errors on settle command properly"))
|
||||
(assert= (eval-hs-error "settle #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on show command properly"
|
||||
(error "SKIP (untranslated): reports null errors on show command properly"))
|
||||
(assert= (eval-hs-error "show #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on toggle command properly"
|
||||
(error "SKIP (untranslated): reports null errors on toggle command properly"))
|
||||
(assert= (eval-hs-error "toggle .foo on #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "toggle between .foo and .bar on #doesntExist") "'#doesntExist' is null")
|
||||
(assert= (eval-hs-error "toggle @foo on #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on transition command properly"
|
||||
(error "SKIP (untranslated): reports null errors on transition command properly"))
|
||||
(assert= (eval-hs-error "transition #doesntExist's *visibility to 0") "'#doesntExist' is null")
|
||||
)
|
||||
(deftest "reports null errors on trigger command properly"
|
||||
(error "SKIP (untranslated): reports null errors on trigger command properly"))
|
||||
(assert= (eval-hs-error "trigger 'foo' on #doesntExist") "'#doesntExist' is null")
|
||||
)
|
||||
)
|
||||
|
||||
;; ── core/scoping (20 tests) ──
|
||||
|
||||
131
spec/tests/test-math.sx
Normal file
131
spec/tests/test-math.sx
Normal file
@@ -0,0 +1,131 @@
|
||||
|
||||
(deftest
|
||||
"math completeness"
|
||||
(deftest
|
||||
"trigonometry"
|
||||
(deftest
|
||||
"sin"
|
||||
(assert= 0 (round (sin 0)) "sin 0 = 0")
|
||||
(assert=
|
||||
1
|
||||
(round (sin (/ 3.14159 2)))
|
||||
"sin pi/2 = 1")
|
||||
(assert= 0 (round (sin 3.14159)) "sin pi = 0"))
|
||||
(deftest
|
||||
"cos"
|
||||
(assert= 1 (round (cos 0)) "cos 0 = 1")
|
||||
(assert=
|
||||
0
|
||||
(round (cos (/ 3.14159 2)))
|
||||
"cos pi/2 = 0")
|
||||
(assert= -1 (round (cos 3.14159)) "cos pi = -1"))
|
||||
(deftest
|
||||
"tan"
|
||||
(assert= 0 (round (tan 0)) "tan 0 = 0")
|
||||
(assert= 1 (round (tan 0.785398)) "tan pi/4 = 1"))
|
||||
(deftest
|
||||
"asin"
|
||||
(assert= 0 (round (asin 0)) "asin 0 = 0")
|
||||
(let
|
||||
(r (asin 1))
|
||||
(assert= true (and (> r 1.5) (< r 1.6)) "asin 1 ≈ pi/2")))
|
||||
(deftest
|
||||
"acos"
|
||||
(assert= 0 (round (acos 1)) "acos 1 = 0")
|
||||
(let
|
||||
(r (acos 0))
|
||||
(assert= true (and (> r 1.5) (< r 1.6)) "acos 0 ≈ pi/2")))
|
||||
(deftest
|
||||
"atan"
|
||||
(assert= 0 (round (atan 0)) "atan 0 = 0")
|
||||
(let
|
||||
(r (atan 1))
|
||||
(assert= true (and (> r 0.78) (< r 0.8)) "atan 1 ≈ pi/4"))
|
||||
(let
|
||||
(r (atan 1 1))
|
||||
(assert=
|
||||
true
|
||||
(and (> r 0.78) (< r 0.8))
|
||||
"atan 1 1 = atan2(1,1) ≈ pi/4"))
|
||||
(let
|
||||
(r (atan 1 0))
|
||||
(assert= true (and (> r 1.5) (< r 1.6)) "atan 1 0 ≈ pi/2")))
|
||||
(deftest
|
||||
"exp"
|
||||
(assert= 1 (round (exp 0)) "exp 0 = 1")
|
||||
(let
|
||||
(r (exp 1))
|
||||
(assert= true (and (> r 2.71) (< r 2.72)) "exp 1 ≈ e")))
|
||||
(deftest
|
||||
"log"
|
||||
(assert= 0 (round (log 1)) "log 1 = 0")
|
||||
(let
|
||||
(r (log 2.71828))
|
||||
(assert= true (and (> r 0.99) (< r 1.01)) "log e ≈ 1"))))
|
||||
(deftest
|
||||
"expt"
|
||||
(assert= 8 (expt 2 3) "2^3 = 8")
|
||||
(assert= 1 (expt 5 0) "5^0 = 1")
|
||||
(assert= 1000 (expt 10 3) "10^3 = 1000")
|
||||
(let
|
||||
(r (expt 2 0.5))
|
||||
(assert= true (and (> r 1.41) (< r 1.43)) "2^0.5 ≈ sqrt(2)")))
|
||||
(deftest
|
||||
"quotient"
|
||||
(assert= 3 (quotient 13 4) "13/4 = 3")
|
||||
(assert=
|
||||
-3
|
||||
(quotient -13 4)
|
||||
"-13/4 = -3 (truncate toward zero)")
|
||||
(assert=
|
||||
-3
|
||||
(quotient 13 -4)
|
||||
"13/-4 = -3 (truncate toward zero)")
|
||||
(assert= 3 (quotient -13 -4) "-13/-4 = 3")
|
||||
(assert= 0 (quotient 0 5) "0/5 = 0"))
|
||||
(deftest
|
||||
"gcd"
|
||||
(assert= 6 (gcd 12 18) "gcd 12 18 = 6")
|
||||
(assert= 1 (gcd 7 13) "gcd 7 13 = 1 (coprime)")
|
||||
(assert= 4 (gcd 8 12) "gcd 8 12 = 4")
|
||||
(assert= 5 (gcd 0 5) "gcd 0 5 = 5")
|
||||
(assert= 6 (gcd -12 18) "gcd handles negatives"))
|
||||
(deftest
|
||||
"lcm"
|
||||
(assert= 12 (lcm 4 6) "lcm 4 6 = 12")
|
||||
(assert= 36 (lcm 12 18) "lcm 12 18 = 36")
|
||||
(assert= 0 (lcm 0 5) "lcm 0 5 = 0")
|
||||
(assert= 15 (lcm 3 5) "lcm 3 5 = 15"))
|
||||
(deftest
|
||||
"number->string"
|
||||
(assert= "42" (number->string 42) "integer to string")
|
||||
(assert= "0" (number->string 0) "zero to string")
|
||||
(assert= "-7" (number->string -7) "negative to string")
|
||||
(assert= "ff" (number->string 255 16) "255 in hex")
|
||||
(assert= "1111" (number->string 15 2) "15 in binary")
|
||||
(assert= "377" (number->string 255 8) "255 in octal")
|
||||
(assert= "z" (number->string 35 36) "35 in base 36"))
|
||||
(deftest
|
||||
"string->number"
|
||||
(assert= 42 (string->number "42") "string to integer")
|
||||
(assert= -7 (string->number "-7") "negative string to integer")
|
||||
(assert= 255 (string->number "ff" 16) "hex string")
|
||||
(assert= 15 (string->number "1111" 2) "binary string")
|
||||
(assert= 255 (string->number "377" 8) "octal string")
|
||||
(assert= nil (string->number "not-a-number") "invalid returns nil")
|
||||
(assert= nil (string->number "fg" 16) "invalid hex returns nil"))
|
||||
(deftest
|
||||
"numeric tower integration"
|
||||
(assert=
|
||||
true
|
||||
(< (abs (- (sin (asin 0.5)) 0.5)) 0.0001)
|
||||
"sin(asin(x)) = x")
|
||||
(assert=
|
||||
true
|
||||
(< (abs (- (cos (acos 0.5)) 0.5)) 0.0001)
|
||||
"cos(acos(x)) = x")
|
||||
(assert= true (< (abs (- (exp (log 2)) 2)) 0.0001) "exp(log(x)) = x")
|
||||
(assert=
|
||||
(* 12 18)
|
||||
(* (gcd 12 18) (lcm 12 18))
|
||||
"gcd * lcm = a * b")))
|
||||
230
spec/tests/test-numeric-tower.sx
Normal file
230
spec/tests/test-numeric-tower.sx
Normal file
@@ -0,0 +1,230 @@
|
||||
;; ==========================================================================
|
||||
;; test-numeric-tower.sx — Numeric tower: Integer vs Float distinction
|
||||
;;
|
||||
;; Tests for float contagion, integer arithmetic, predicates,
|
||||
;; coercions, parsing, and rendering.
|
||||
;;
|
||||
;; Note: Use fractional floats (1.5, 3.14) or exact->inexact for round floats,
|
||||
;; since the SX serializer renders Number 1.0 as "1" (int form).
|
||||
;; ==========================================================================
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Integer arithmetic — result stays Integer when all args are Integer
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:int-arithmetic"
|
||||
(deftest "int + int = int" (assert (integer? (+ 1 2))))
|
||||
(deftest "int + int value" (assert= (+ 1 2) 3))
|
||||
(deftest "int - int = int" (assert (integer? (- 10 3))))
|
||||
(deftest "int - int value" (assert= (- 10 3) 7))
|
||||
(deftest "int * int = int" (assert (integer? (* 4 5))))
|
||||
(deftest "int * int value" (assert= (* 4 5) 20))
|
||||
(deftest "zero identity" (assert= (+ 0 0) 0))
|
||||
(deftest "negative int" (assert= (- 0 5) -5))
|
||||
(deftest
|
||||
"int negation is int"
|
||||
(assert (integer? (- 0 7))))
|
||||
(deftest
|
||||
"large int product"
|
||||
(assert= (* 100 100) 10000)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Float contagion — any float arg promotes result to float
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:float-contagion"
|
||||
(deftest "int + float = float" (assert (float? (+ 1 1.5))))
|
||||
(deftest "int + float value" (assert= (+ 1 1.5) 2.5))
|
||||
(deftest "float + int = float" (assert (float? (+ 1.5 2))))
|
||||
(deftest "float + float = float" (assert (float? (+ 1.5 2.5))))
|
||||
(deftest "int * float = float" (assert (float? (* 2 1.5))))
|
||||
(deftest "int * float value" (assert= (* 2 1.5) 3))
|
||||
(deftest "int - float = float" (assert (float? (- 5 2.5))))
|
||||
(deftest "float - int = float" (assert (float? (- 5.5 2))))
|
||||
(deftest
|
||||
"three args with float"
|
||||
(assert (float? (+ 1 2 3.5))))
|
||||
(deftest
|
||||
"exact->inexact promotes to float"
|
||||
(assert (float? (exact->inexact 5)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Division
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:division"
|
||||
(deftest
|
||||
"exact division value"
|
||||
(assert= (/ 6 2) 3))
|
||||
(deftest "inexact division value" (assert= (/ 1 4) 0.25))
|
||||
(deftest "float / float = float" (assert (float? (/ 3.5 2.5))))
|
||||
(deftest
|
||||
"rational / int = rational"
|
||||
(assert (rational? (/ 1/2 2))))
|
||||
(deftest "rational division value" (assert= (/ 1/2 2) 1/4)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Type predicates
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:predicates"
|
||||
(deftest "integer? on int" (assert (integer? 42)))
|
||||
(deftest "integer? on negative" (assert (integer? -7)))
|
||||
(deftest "integer? on zero" (assert (integer? 0)))
|
||||
(deftest
|
||||
"integer? on float-int"
|
||||
(assert (integer? (exact->inexact 2))))
|
||||
(deftest "integer? on fractional float" (assert (not (integer? 1.5))))
|
||||
(deftest "float? on 1.5" (assert (float? 1.5)))
|
||||
(deftest
|
||||
"float? on exact->inexact"
|
||||
(assert (float? (exact->inexact 2))))
|
||||
(deftest "float? on int" (assert (not (float? 42))))
|
||||
(deftest "number? on int" (assert (number? 42)))
|
||||
(deftest "number? on float" (assert (number? 3.14)))
|
||||
(deftest "number? on rational" (assert (number? 1/3)))
|
||||
(deftest "number? on string" (assert (not (number? "42"))))
|
||||
(deftest "exact? on int" (assert (exact? 1)))
|
||||
(deftest "exact? on rational" (assert (exact? 1/3)))
|
||||
(deftest
|
||||
"exact? on exact->inexact"
|
||||
(assert (not (exact? (exact->inexact 1)))))
|
||||
(deftest "inexact? on 1.5" (assert (inexact? 1.5)))
|
||||
(deftest "inexact? on int" (assert (not (inexact? 3)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Coercions
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:coercions"
|
||||
(deftest
|
||||
"exact->inexact int"
|
||||
(assert= (exact->inexact 3) 3))
|
||||
(deftest
|
||||
"exact->inexact produces float"
|
||||
(assert (float? (exact->inexact 5))))
|
||||
(deftest
|
||||
"exact->inexact float passthrough"
|
||||
(assert= (exact->inexact 1.5) 1.5))
|
||||
(deftest "exact->inexact rational" (assert= (exact->inexact 1/4) 0.25))
|
||||
(deftest "inexact->exact 1.5" (assert= (inexact->exact 1.5) 2))
|
||||
(deftest
|
||||
"inexact->exact produces int"
|
||||
(assert (integer? (inexact->exact (exact->inexact 4)))))
|
||||
(deftest "inexact->exact 2.7" (assert= (inexact->exact 2.7) 3))
|
||||
(deftest
|
||||
"inexact->exact int passthrough"
|
||||
(assert= (inexact->exact 5) 5)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; floor / ceiling / truncate / round — return Integer for floats
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:rounding"
|
||||
(deftest "floor 3.7" (assert= (floor 3.7) 3))
|
||||
(deftest "floor produces int" (assert (integer? (floor 3.7))))
|
||||
(deftest "floor negative" (assert= (floor -2.3) -3))
|
||||
(deftest "truncate 3.9" (assert= (truncate 3.9) 3))
|
||||
(deftest "truncate negative" (assert= (truncate -3.9) -3))
|
||||
(deftest "truncate produces int" (assert (integer? (truncate 3.9))))
|
||||
(deftest "round 2.3 down" (assert= (round 2.3) 2))
|
||||
(deftest "round produces int" (assert (integer? (round 2.3))))
|
||||
(deftest
|
||||
"floor of int passthrough"
|
||||
(assert= (floor 5) 5))
|
||||
(deftest "floor of int stays int" (assert (integer? (floor 5)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; parse-number distinguishes int vs float strings
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:parse-number"
|
||||
(deftest
|
||||
"parse-number int string"
|
||||
(assert= (parse-number "42") 42))
|
||||
(deftest
|
||||
"parse-number int is integer?"
|
||||
(assert (integer? (parse-number "42"))))
|
||||
(deftest "parse-number 3.14" (assert= (parse-number "3.14") 3.14))
|
||||
(deftest
|
||||
"parse-number float is float?"
|
||||
(assert (float? (parse-number "3.14"))))
|
||||
(deftest
|
||||
"parse-number 1.5 is float?"
|
||||
(assert (float? (parse-number "1.5"))))
|
||||
(deftest
|
||||
"parse-number negative int"
|
||||
(assert= (parse-number "-5") -5))
|
||||
(deftest
|
||||
"parse-number negative int is integer?"
|
||||
(assert (integer? (parse-number "-5"))))
|
||||
(deftest "parse-int returns integer" (assert (integer? (parse-int "7"))))
|
||||
(deftest "parse-int value" (assert= (parse-int "7") 7)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Equality across numeric types
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:equality"
|
||||
(deftest "int = same int" (assert= 5 5))
|
||||
(deftest
|
||||
"int = float eq"
|
||||
(assert (= 1 (exact->inexact 1))))
|
||||
(deftest
|
||||
"float = int eq"
|
||||
(assert (= (exact->inexact 1) 1)))
|
||||
(deftest "int != different int" (assert (!= 1 2)))
|
||||
(deftest "int < float" (assert (< 1 1.5)))
|
||||
(deftest "float > int" (assert (> 2.5 2)))
|
||||
(deftest "int <= float" (assert (<= 2 2.5)))
|
||||
(deftest "int >= int" (assert (>= 3 3))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; mod / remainder / modulo with integers
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:modulo"
|
||||
(deftest
|
||||
"mod int int = int"
|
||||
(assert (integer? (mod 10 3))))
|
||||
(deftest "mod value" (assert= (mod 10 3) 1))
|
||||
(deftest
|
||||
"remainder int int = int"
|
||||
(assert (integer? (remainder 10 3))))
|
||||
(deftest
|
||||
"remainder value"
|
||||
(assert= (remainder 10 3) 1)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; min / max with mixed types
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:min-max"
|
||||
(deftest "min two ints" (assert= (min 3 7) 3))
|
||||
(deftest
|
||||
"min int result type"
|
||||
(assert (integer? (min 3 7))))
|
||||
(deftest "max two ints" (assert= (max 3 7) 7))
|
||||
(deftest "min with float" (assert= (min 3 2.5) 2.5))
|
||||
(deftest "max with float" (assert= (max 3 3.5) 3.5)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; str rendering of int vs float
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"numeric-tower:stringify"
|
||||
(deftest "str of int" (assert= (str 42) "42"))
|
||||
(deftest "str of negative int" (assert= (str -5) "-5"))
|
||||
(deftest "str of 3.14" (assert= (str 3.14) "3.14"))
|
||||
(deftest "str of 1.5" (assert= (str 1.5) "1.5")))
|
||||
232
spec/tests/test-ports.sx
Normal file
232
spec/tests/test-ports.sx
Normal file
@@ -0,0 +1,232 @@
|
||||
;; Phase 14 — String ports + eof-object
|
||||
|
||||
(deftest
|
||||
"eof-object"
|
||||
(deftest
|
||||
"eof-object is eof"
|
||||
(assert=
|
||||
true
|
||||
(eof-object? (eof-object))
|
||||
"eof-object? returns true for eof-object"))
|
||||
(deftest
|
||||
"non-eof values are not eof"
|
||||
(assert= false (eof-object? nil) "nil is not eof")
|
||||
(assert= false (eof-object? "") "string is not eof")
|
||||
(assert= false (eof-object? 0) "zero is not eof")
|
||||
(assert= false (eof-object? false) "false is not eof"))
|
||||
(deftest
|
||||
"type-of eof-object"
|
||||
(assert=
|
||||
"eof-object"
|
||||
(type-of (eof-object))
|
||||
"type-of eof-object is eof-object")))
|
||||
|
||||
(deftest
|
||||
"open-input-string"
|
||||
(deftest
|
||||
"creates input port"
|
||||
(let
|
||||
(p (open-input-string "hello"))
|
||||
(assert= true (port? p) "is a port")
|
||||
(assert= true (input-port? p) "is an input port")
|
||||
(assert= false (output-port? p) "is not an output port")))
|
||||
(deftest
|
||||
"type-of input port"
|
||||
(let
|
||||
(p (open-input-string "x"))
|
||||
(assert= "input-port" (type-of p) "type-of is input-port"))))
|
||||
|
||||
(deftest
|
||||
"open-output-string"
|
||||
(deftest
|
||||
"creates output port"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(assert= true (port? p) "is a port")
|
||||
(assert= true (output-port? p) "is an output port")
|
||||
(assert= false (input-port? p) "is not an input port")))
|
||||
(deftest
|
||||
"type-of output port"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(assert= "output-port" (type-of p) "type-of is output-port"))))
|
||||
|
||||
(deftest
|
||||
"read-char"
|
||||
(deftest
|
||||
"reads chars sequentially"
|
||||
(let
|
||||
(p (open-input-string "ab"))
|
||||
(let
|
||||
(c1 (read-char p))
|
||||
(assert= true (char? c1) "first result is char")
|
||||
(assert= 97 (char->integer c1) "first char is a"))))
|
||||
(deftest
|
||||
"reads second char"
|
||||
(let
|
||||
(p (open-input-string "ab"))
|
||||
(read-char p)
|
||||
(let
|
||||
(c2 (read-char p))
|
||||
(assert= true (char? c2) "second result is char")
|
||||
(assert= 98 (char->integer c2) "second char is b"))))
|
||||
(deftest
|
||||
"returns eof at end"
|
||||
(let
|
||||
(p (open-input-string "x"))
|
||||
(read-char p)
|
||||
(assert= true (eof-object? (read-char p)) "eof after last char")))
|
||||
(deftest
|
||||
"empty string yields eof immediately"
|
||||
(let
|
||||
(p (open-input-string ""))
|
||||
(assert= true (eof-object? (read-char p)) "eof from empty string"))))
|
||||
|
||||
(deftest
|
||||
"peek-char"
|
||||
(deftest
|
||||
"peeks without consuming"
|
||||
(let
|
||||
(p (open-input-string "x"))
|
||||
(let
|
||||
(c1 (peek-char p))
|
||||
(let
|
||||
(c2 (peek-char p))
|
||||
(assert=
|
||||
(char->integer c1)
|
||||
(char->integer c2)
|
||||
"peek twice gives same char")))))
|
||||
(deftest
|
||||
"peek then read"
|
||||
(let
|
||||
(p (open-input-string "z"))
|
||||
(let
|
||||
(peeked (peek-char p))
|
||||
(let
|
||||
(read (read-char p))
|
||||
(assert=
|
||||
(char->integer peeked)
|
||||
(char->integer read)
|
||||
"peek and read agree")))))
|
||||
(deftest
|
||||
"peek at end returns eof"
|
||||
(let
|
||||
(p (open-input-string ""))
|
||||
(assert= true (eof-object? (peek-char p)) "eof on empty peek"))))
|
||||
|
||||
(deftest
|
||||
"read-line"
|
||||
(deftest
|
||||
"reads a single line"
|
||||
(let
|
||||
(p (open-input-string "hello"))
|
||||
(assert= "hello" (read-line p) "reads whole string as line")))
|
||||
(deftest
|
||||
"reads line up to newline"
|
||||
(let
|
||||
(p (open-input-string "foo\nbar"))
|
||||
(assert= "foo" (read-line p) "first line is foo")))
|
||||
(deftest
|
||||
"reads second line"
|
||||
(let
|
||||
(p (open-input-string "foo\nbar"))
|
||||
(read-line p)
|
||||
(assert= "bar" (read-line p) "second line is bar")))
|
||||
(deftest
|
||||
"returns eof on empty port"
|
||||
(let
|
||||
(p (open-input-string ""))
|
||||
(assert= true (eof-object? (read-line p)) "eof on empty")))
|
||||
(deftest
|
||||
"returns eof after last line"
|
||||
(let
|
||||
(p (open-input-string "hi"))
|
||||
(read-line p)
|
||||
(assert= true (eof-object? (read-line p)) "eof after reading"))))
|
||||
|
||||
(deftest
|
||||
"write-char and get-output-string"
|
||||
(deftest
|
||||
"write single char"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(write-char (make-char 65) p)
|
||||
(assert= "A" (get-output-string p) "write char A")))
|
||||
(deftest
|
||||
"write multiple chars"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(write-char (make-char 72) p)
|
||||
(write-char (make-char 105) p)
|
||||
(assert= "Hi" (get-output-string p) "write Hi"))))
|
||||
|
||||
(deftest
|
||||
"write-string"
|
||||
(deftest
|
||||
"write a string to port"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(write-string "hello" p)
|
||||
(assert= "hello" (get-output-string p) "write-string result")))
|
||||
(deftest
|
||||
"multiple writes concatenate"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(write-string "foo" p)
|
||||
(write-string "bar" p)
|
||||
(assert= "foobar" (get-output-string p) "concatenated writes"))))
|
||||
|
||||
(deftest
|
||||
"get-output-string idempotent"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(write-string "test" p)
|
||||
(assert= "test" (get-output-string p) "first call")
|
||||
(assert= "test" (get-output-string p) "second call same result")))
|
||||
|
||||
(deftest
|
||||
"char-ready?"
|
||||
(deftest
|
||||
"ready when chars available"
|
||||
(let
|
||||
(p (open-input-string "x"))
|
||||
(assert= true (char-ready? p) "ready with content")))
|
||||
(deftest
|
||||
"not ready when empty"
|
||||
(let
|
||||
(p (open-input-string ""))
|
||||
(assert= false (char-ready? p) "not ready when empty"))))
|
||||
|
||||
(deftest
|
||||
"close-port"
|
||||
(deftest
|
||||
"close input port"
|
||||
(let
|
||||
(p (open-input-string "hello"))
|
||||
(close-port p)
|
||||
(assert= true (eof-object? (read-char p)) "read after close gives eof")))
|
||||
(deftest
|
||||
"close output port"
|
||||
(let
|
||||
(p (open-output-string))
|
||||
(write-string "ok" p)
|
||||
(close-port p)
|
||||
(assert= "ok" (get-output-string p) "output preserved after close"))))
|
||||
|
||||
(deftest
|
||||
"roundtrip string via ports"
|
||||
(let
|
||||
(in (open-input-string "abc"))
|
||||
(let
|
||||
(out (open-output-string))
|
||||
(do
|
||||
(let
|
||||
(c1 (read-char in))
|
||||
(when (not (eof-object? c1)) (write-char c1 out)))
|
||||
(let
|
||||
(c2 (read-char in))
|
||||
(when (not (eof-object? c2)) (write-char c2 out)))
|
||||
(let
|
||||
(c3 (read-char in))
|
||||
(when (not (eof-object? c3)) (write-char c3 out)))
|
||||
(assert= "abc" (get-output-string out) "roundtrip via ports")))))
|
||||
@@ -6,20 +6,36 @@
|
||||
;; Arithmetic
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "arithmetic"
|
||||
(defsuite
|
||||
"arithmetic"
|
||||
(deftest "add" (assert-equal 3 (+ 1 2)))
|
||||
(deftest "add multiple" (assert-equal 10 (+ 1 2 3 4)))
|
||||
(deftest
|
||||
"add multiple"
|
||||
(assert-equal 10 (+ 1 2 3 4)))
|
||||
(deftest "add zero" (assert-equal 5 (+ 5 0)))
|
||||
(deftest "add negative" (assert-equal -1 (+ 1 -2)))
|
||||
(deftest
|
||||
"add negative"
|
||||
(assert-equal -1 (+ 1 -2)))
|
||||
(deftest "subtract" (assert-equal 3 (- 5 2)))
|
||||
(deftest "subtract negative" (assert-equal 7 (- 5 -2)))
|
||||
(deftest
|
||||
"subtract negative"
|
||||
(assert-equal 7 (- 5 -2)))
|
||||
(deftest "multiply" (assert-equal 12 (* 3 4)))
|
||||
(deftest "multiply zero" (assert-equal 0 (* 5 0)))
|
||||
(deftest "multiply negative" (assert-equal -6 (* 2 -3)))
|
||||
(deftest
|
||||
"multiply zero"
|
||||
(assert-equal 0 (* 5 0)))
|
||||
(deftest
|
||||
"multiply negative"
|
||||
(assert-equal -6 (* 2 -3)))
|
||||
(deftest "divide" (assert-equal 3 (/ 9 3)))
|
||||
(deftest "divide float" (assert-equal 2.5 (/ 5 2)))
|
||||
(deftest "mod" (assert-equal 1 (mod 7 3)))
|
||||
(deftest "mod negative" (assert-true (or (= (mod -1 3) 2) (= (mod -1 3) -1))))
|
||||
(deftest
|
||||
"mod negative"
|
||||
(assert-true
|
||||
(or
|
||||
(= (mod -1 3) 2)
|
||||
(= (mod -1 3) -1))))
|
||||
(deftest "inc" (assert-equal 6 (inc 5)))
|
||||
(deftest "dec" (assert-equal 4 (dec 5)))
|
||||
(deftest "abs positive" (assert-equal 5 (abs 5)))
|
||||
@@ -32,7 +48,8 @@
|
||||
;; Comparison
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "comparison"
|
||||
(defsuite
|
||||
"comparison"
|
||||
(deftest "equal numbers" (assert-true (= 1 1)))
|
||||
(deftest "not equal numbers" (assert-false (= 1 2)))
|
||||
(deftest "equal strings" (assert-true (= "a" "a")))
|
||||
@@ -52,7 +69,8 @@
|
||||
;; Predicates
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "predicates"
|
||||
(defsuite
|
||||
"predicates"
|
||||
(deftest "nil? nil" (assert-true (nil? nil)))
|
||||
(deftest "nil? number" (assert-false (nil? 0)))
|
||||
(deftest "nil? string" (assert-false (nil? "")))
|
||||
@@ -76,15 +94,22 @@
|
||||
;; String operations
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "strings"
|
||||
(deftest "str concat" (assert-equal "hello world" (str "hello" " " "world")))
|
||||
(defsuite
|
||||
"strings"
|
||||
(deftest
|
||||
"str concat"
|
||||
(assert-equal "hello world" (str "hello" " " "world")))
|
||||
(deftest "str number" (assert-equal "42" (str 42)))
|
||||
(deftest "str empty" (assert-equal "" (str)))
|
||||
(deftest "len string" (assert-equal 5 (len "hello")))
|
||||
(deftest "len empty" (assert-equal 0 (len "")))
|
||||
(deftest "slice" (assert-equal "ell" (slice "hello" 1 4)))
|
||||
(deftest
|
||||
"slice"
|
||||
(assert-equal "ell" (slice "hello" 1 4)))
|
||||
(deftest "slice from" (assert-equal "llo" (slice "hello" 2)))
|
||||
(deftest "slice empty" (assert-equal "" (slice "hello" 2 2)))
|
||||
(deftest
|
||||
"slice empty"
|
||||
(assert-equal "" (slice "hello" 2 2)))
|
||||
(deftest "join" (assert-equal "a,b,c" (join "," (list "a" "b" "c"))))
|
||||
(deftest "join empty" (assert-equal "" (join "," (list))))
|
||||
(deftest "join single" (assert-equal "a" (join "," (list "a"))))
|
||||
@@ -101,88 +126,238 @@
|
||||
(deftest "replace" (assert-equal "hXllo" (replace "hello" "e" "X")))
|
||||
(deftest "string-length" (assert-equal 5 (string-length "hello")))
|
||||
(deftest "index-of found" (assert-equal 2 (index-of "hello" "l")))
|
||||
(deftest "index-of not found" (assert-equal -1 (index-of "hello" "z"))))
|
||||
(deftest
|
||||
"index-of not found"
|
||||
(assert-equal -1 (index-of "hello" "z"))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; List operations
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "lists"
|
||||
(deftest "list create" (assert-equal (list 1 2 3) (list 1 2 3)))
|
||||
(deftest "first" (assert-equal 1 (first (list 1 2 3))))
|
||||
(defsuite
|
||||
"lists"
|
||||
(deftest
|
||||
"list create"
|
||||
(assert-equal
|
||||
(list 1 2 3)
|
||||
(list 1 2 3)))
|
||||
(deftest
|
||||
"first"
|
||||
(assert-equal 1 (first (list 1 2 3))))
|
||||
(deftest "first empty" (assert-nil (first (list))))
|
||||
(deftest "rest" (assert-equal (list 2 3) (rest (list 1 2 3))))
|
||||
(deftest
|
||||
"rest"
|
||||
(assert-equal
|
||||
(list 2 3)
|
||||
(rest (list 1 2 3))))
|
||||
(deftest "rest single" (assert-equal (list) (rest (list 1))))
|
||||
(deftest "rest empty" (assert-equal (list) (rest (list))))
|
||||
(deftest "nth" (assert-equal 2 (nth (list 1 2 3) 1)))
|
||||
(deftest "nth out of bounds" (assert-nil (nth (list 1 2) 5)))
|
||||
(deftest "last" (assert-equal 3 (last (list 1 2 3))))
|
||||
(deftest
|
||||
"nth"
|
||||
(assert-equal
|
||||
2
|
||||
(nth (list 1 2 3) 1)))
|
||||
(deftest
|
||||
"nth out of bounds"
|
||||
(assert-nil (nth (list 1 2) 5)))
|
||||
(deftest
|
||||
"last"
|
||||
(assert-equal 3 (last (list 1 2 3))))
|
||||
(deftest "last single" (assert-equal 1 (last (list 1))))
|
||||
(deftest "len list" (assert-equal 3 (len (list 1 2 3))))
|
||||
(deftest
|
||||
"len list"
|
||||
(assert-equal 3 (len (list 1 2 3))))
|
||||
(deftest "len empty" (assert-equal 0 (len (list))))
|
||||
(deftest "cons" (assert-equal (list 0 1 2) (cons 0 (list 1 2))))
|
||||
(deftest "append" (assert-equal (list 1 2 3 4) (append (list 1 2) (list 3 4))))
|
||||
(deftest "append element" (assert-equal (list 1 2 3) (append (list 1 2) (list 3))))
|
||||
(deftest "slice list" (assert-equal (list 2 3) (slice (list 1 2 3 4) 1 3)))
|
||||
(deftest "concat" (assert-equal (list 1 2 3 4) (concat (list 1 2) (list 3 4))))
|
||||
(deftest "reverse" (assert-equal (list 3 2 1) (reverse (list 1 2 3))))
|
||||
(deftest
|
||||
"cons"
|
||||
(assert-equal
|
||||
(list 0 1 2)
|
||||
(cons 0 (list 1 2))))
|
||||
(deftest
|
||||
"append"
|
||||
(assert-equal
|
||||
(list 1 2 3 4)
|
||||
(append (list 1 2) (list 3 4))))
|
||||
(deftest
|
||||
"append element"
|
||||
(assert-equal
|
||||
(list 1 2 3)
|
||||
(append (list 1 2) (list 3))))
|
||||
(deftest
|
||||
"slice list"
|
||||
(assert-equal
|
||||
(list 2 3)
|
||||
(slice
|
||||
(list 1 2 3 4)
|
||||
1
|
||||
3)))
|
||||
(deftest
|
||||
"concat"
|
||||
(assert-equal
|
||||
(list 1 2 3 4)
|
||||
(concat (list 1 2) (list 3 4))))
|
||||
(deftest
|
||||
"reverse"
|
||||
(assert-equal
|
||||
(list 3 2 1)
|
||||
(reverse (list 1 2 3))))
|
||||
(deftest "reverse empty" (assert-equal (list) (reverse (list))))
|
||||
(deftest "contains? list" (assert-true (contains? (list 1 2 3) 2)))
|
||||
(deftest "contains? list false" (assert-false (contains? (list 1 2 3) 5)))
|
||||
(deftest "range" (assert-equal (list 0 1 2) (range 0 3)))
|
||||
(deftest "range step" (assert-equal (list 0 2 4) (range 0 6 2)))
|
||||
(deftest "flatten" (assert-equal (list 1 2 3 4) (flatten (list (list 1 2) (list 3 4))))))
|
||||
(deftest
|
||||
"contains? list"
|
||||
(assert-true
|
||||
(contains? (list 1 2 3) 2)))
|
||||
(deftest
|
||||
"contains? list false"
|
||||
(assert-false
|
||||
(contains? (list 1 2 3) 5)))
|
||||
(deftest
|
||||
"range"
|
||||
(assert-equal
|
||||
(list 0 1 2)
|
||||
(range 0 3)))
|
||||
(deftest
|
||||
"range step"
|
||||
(assert-equal
|
||||
(list 0 2 4)
|
||||
(range 0 6 2)))
|
||||
(deftest
|
||||
"flatten"
|
||||
(assert-equal
|
||||
(list 1 2 3 4)
|
||||
(flatten
|
||||
(list (list 1 2) (list 3 4))))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Dict operations
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "dicts"
|
||||
(deftest "dict create" (assert-equal 1 (get (dict "a" 1 "b" 2) "a")))
|
||||
(defsuite
|
||||
"dicts"
|
||||
(deftest
|
||||
"dict create"
|
||||
(assert-equal 1 (get (dict "a" 1 "b" 2) "a")))
|
||||
(deftest "get missing" (assert-nil (get (dict "a" 1) "z")))
|
||||
(deftest "get default" (assert-equal 99 (get (dict "a" 1) "z" 99)))
|
||||
(deftest "keys" (assert-true (contains? (keys (dict "a" 1 "b" 2)) "a")))
|
||||
(deftest
|
||||
"get default"
|
||||
(assert-equal 99 (get (dict "a" 1) "z" 99)))
|
||||
(deftest
|
||||
"keys"
|
||||
(assert-true
|
||||
(contains? (keys (dict "a" 1 "b" 2)) "a")))
|
||||
(deftest "has-key?" (assert-true (has-key? (dict "a" 1) "a")))
|
||||
(deftest "has-key? false" (assert-false (has-key? (dict "a" 1) "z")))
|
||||
(deftest "assoc" (assert-equal 2 (get (assoc (dict "a" 1) "b" 2) "b")))
|
||||
(deftest "dissoc" (assert-false (has-key? (dissoc (dict "a" 1 "b" 2) "a") "a")))
|
||||
(deftest "len dict" (assert-equal 2 (len (dict "a" 1 "b" 2))))
|
||||
(deftest
|
||||
"has-key? false"
|
||||
(assert-false (has-key? (dict "a" 1) "z")))
|
||||
(deftest
|
||||
"assoc"
|
||||
(assert-equal
|
||||
2
|
||||
(get (assoc (dict "a" 1) "b" 2) "b")))
|
||||
(deftest
|
||||
"dissoc"
|
||||
(assert-false
|
||||
(has-key? (dissoc (dict "a" 1 "b" 2) "a") "a")))
|
||||
(deftest
|
||||
"len dict"
|
||||
(assert-equal 2 (len (dict "a" 1 "b" 2))))
|
||||
(deftest "len empty dict" (assert-equal 0 (len (dict))))
|
||||
(deftest "empty? dict" (assert-true (empty? (dict))))
|
||||
(deftest "empty? nonempty dict" (assert-false (empty? (dict "a" 1)))))
|
||||
(deftest
|
||||
"empty? nonempty dict"
|
||||
(assert-false (empty? (dict "a" 1)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Higher-order functions
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "higher-order"
|
||||
(deftest "map" (assert-equal (list 2 4 6) (map (fn (x) (* x 2)) (list 1 2 3))))
|
||||
(defsuite
|
||||
"higher-order"
|
||||
(deftest
|
||||
"map"
|
||||
(assert-equal
|
||||
(list 2 4 6)
|
||||
(map
|
||||
(fn (x) (* x 2))
|
||||
(list 1 2 3))))
|
||||
(deftest "map empty" (assert-equal (list) (map (fn (x) x) (list))))
|
||||
(deftest "filter" (assert-equal (list 2 4) (filter (fn (x) (= (mod x 2) 0)) (list 1 2 3 4 5))))
|
||||
(deftest "filter none" (assert-equal (list) (filter (fn (x) false) (list 1 2 3))))
|
||||
(deftest "reduce" (assert-equal 10 (reduce (fn (acc x) (+ acc x)) 0 (list 1 2 3 4))))
|
||||
(deftest "reduce empty" (assert-equal 0 (reduce (fn (acc x) (+ acc x)) 0 (list))))
|
||||
(deftest "some true" (assert-true (some (fn (x) (> x 3)) (list 1 2 3 4 5))))
|
||||
(deftest "some false" (assert-false (some (fn (x) (> x 10)) (list 1 2 3))))
|
||||
(deftest
|
||||
"filter"
|
||||
(assert-equal
|
||||
(list 2 4)
|
||||
(filter
|
||||
(fn (x) (= (mod x 2) 0))
|
||||
(list 1 2 3 4 5))))
|
||||
(deftest
|
||||
"filter none"
|
||||
(assert-equal
|
||||
(list)
|
||||
(filter (fn (x) false) (list 1 2 3))))
|
||||
(deftest
|
||||
"reduce"
|
||||
(assert-equal
|
||||
10
|
||||
(reduce
|
||||
(fn (acc x) (+ acc x))
|
||||
0
|
||||
(list 1 2 3 4))))
|
||||
(deftest
|
||||
"reduce empty"
|
||||
(assert-equal
|
||||
0
|
||||
(reduce (fn (acc x) (+ acc x)) 0 (list))))
|
||||
(deftest
|
||||
"some true"
|
||||
(assert-true
|
||||
(some
|
||||
(fn (x) (> x 3))
|
||||
(list 1 2 3 4 5))))
|
||||
(deftest
|
||||
"some false"
|
||||
(assert-false
|
||||
(some
|
||||
(fn (x) (> x 10))
|
||||
(list 1 2 3))))
|
||||
(deftest "some empty" (assert-false (some (fn (x) true) (list))))
|
||||
(deftest "every? true" (assert-true (every? (fn (x) (> x 0)) (list 1 2 3))))
|
||||
(deftest "every? false" (assert-false (every? (fn (x) (> x 2)) (list 1 2 3))))
|
||||
(deftest
|
||||
"every? true"
|
||||
(assert-true
|
||||
(every?
|
||||
(fn (x) (> x 0))
|
||||
(list 1 2 3))))
|
||||
(deftest
|
||||
"every? false"
|
||||
(assert-false
|
||||
(every?
|
||||
(fn (x) (> x 2))
|
||||
(list 1 2 3))))
|
||||
(deftest "every? empty" (assert-true (every? (fn (x) false) (list))))
|
||||
(deftest "for-each returns nil"
|
||||
(let ((log (list)))
|
||||
(for-each (fn (x) (append! log x)) (list 1 2 3))
|
||||
(deftest
|
||||
"for-each returns nil"
|
||||
(let
|
||||
((log (list)))
|
||||
(for-each
|
||||
(fn (x) (append! log x))
|
||||
(list 1 2 3))
|
||||
(assert-equal (list 1 2 3) log)))
|
||||
(deftest "map-indexed"
|
||||
(assert-equal (list (list 0 "a") (list 1 "b"))
|
||||
(deftest
|
||||
"map-indexed"
|
||||
(assert-equal
|
||||
(list (list 0 "a") (list 1 "b"))
|
||||
(map-indexed (fn (i x) (list i x)) (list "a" "b")))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Type coercion
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite "type-coercion"
|
||||
(deftest "str bool" (assert-true (or (= (str true) "true") (= (str true) "True"))))
|
||||
(defsuite
|
||||
"type-coercion"
|
||||
(deftest
|
||||
"str bool"
|
||||
(assert-true (or (= (str true) "true") (= (str true) "True"))))
|
||||
(deftest "str nil" (assert-equal "" (str nil)))
|
||||
(deftest "str list" (assert-true (not (empty? (str (list 1 2 3))))))
|
||||
(deftest
|
||||
"str list"
|
||||
(assert-true
|
||||
(not (empty? (str (list 1 2 3))))))
|
||||
(deftest "parse-int" (assert-equal 42 (parse-int "42")))
|
||||
(deftest "parse-float skipped" (assert-true true)))
|
||||
|
||||
150
spec/tests/test-promises.sx
Normal file
150
spec/tests/test-promises.sx
Normal file
@@ -0,0 +1,150 @@
|
||||
(defsuite
|
||||
"promises"
|
||||
(deftest
|
||||
"delay creates a promise"
|
||||
(do (assert (promise? (delay 42)))))
|
||||
(deftest
|
||||
"delay does not evaluate immediately"
|
||||
(do
|
||||
(let
|
||||
((count 0))
|
||||
(let
|
||||
((p (delay (do (set! count (+ count 1)) count))))
|
||||
(assert= 0 count)))))
|
||||
(deftest
|
||||
"force evaluates the expression"
|
||||
(do (assert= 42 (force (delay 42)))))
|
||||
(deftest
|
||||
"force with arithmetic"
|
||||
(do (assert= 10 (force (delay (+ 3 7))))))
|
||||
(deftest
|
||||
"force memoises result"
|
||||
(do
|
||||
(let
|
||||
((count 0))
|
||||
(let
|
||||
((p (delay (do (set! count (+ count 1)) count))))
|
||||
(force p)
|
||||
(force p)
|
||||
(assert= 1 count)))))
|
||||
(deftest
|
||||
"force returns same value on repeated calls"
|
||||
(do
|
||||
(let
|
||||
((p (delay (+ 1 2))))
|
||||
(assert= 3 (force p))
|
||||
(assert= 3 (force p)))))
|
||||
(deftest
|
||||
"make-promise creates an already-forced promise"
|
||||
(do
|
||||
(let
|
||||
((p (make-promise 99)))
|
||||
(assert (promise? p))
|
||||
(assert= 99 (force p)))))
|
||||
(deftest
|
||||
"make-promise memoises without evaluating"
|
||||
(do
|
||||
(let
|
||||
((count 0))
|
||||
(let
|
||||
((p (make-promise 42)))
|
||||
(force p)
|
||||
(force p)
|
||||
(assert= 0 count)))))
|
||||
(deftest
|
||||
"promise? returns true for delay"
|
||||
(do (assert (promise? (delay 1)))))
|
||||
(deftest
|
||||
"promise? returns true for make-promise"
|
||||
(do (assert (promise? (make-promise 1)))))
|
||||
(deftest
|
||||
"promise? returns false for non-promise"
|
||||
(do
|
||||
(assert= false (promise? 42))
|
||||
(assert= false (promise? "hello"))
|
||||
(assert= false (promise? nil))
|
||||
(assert= false (promise? (list 1 2)))))
|
||||
(deftest
|
||||
"force non-promise returns value unchanged"
|
||||
(do
|
||||
(assert= 42 (force 42))
|
||||
(assert= "hi" (force "hi"))
|
||||
(assert= nil (force nil))))
|
||||
(deftest
|
||||
"delay captures environment"
|
||||
(do
|
||||
(let
|
||||
((x 10))
|
||||
(let
|
||||
((p (delay (+ x 5))))
|
||||
(assert= 15 (force p))))))
|
||||
(deftest
|
||||
"delay-force basic"
|
||||
(do (assert= 42 (force (delay-force (delay 42))))))
|
||||
(deftest
|
||||
"delay-force chains"
|
||||
(do
|
||||
(assert=
|
||||
5
|
||||
(force (delay-force (delay-force (delay 5)))))))
|
||||
(deftest
|
||||
"delay with string"
|
||||
(do (assert= "hello" (force (delay "hello")))))
|
||||
(deftest
|
||||
"delay with list"
|
||||
(do
|
||||
(assert-equal
|
||||
(list 1 2 3)
|
||||
(force (delay (list 1 2 3))))))
|
||||
(deftest
|
||||
"delay with function call"
|
||||
(do (assert= 6 (force (delay (* 2 3))))))
|
||||
(deftest
|
||||
"nested delay"
|
||||
(do
|
||||
(let
|
||||
((p (delay (delay 99))))
|
||||
(assert (promise? (force p))))))
|
||||
(deftest
|
||||
"force already forced promise"
|
||||
(do
|
||||
(let
|
||||
((p (make-promise 7)))
|
||||
(assert= 7 (force p))
|
||||
(assert= 7 (force p)))))
|
||||
(deftest
|
||||
"lazy stream first element"
|
||||
(do
|
||||
(define (stream-cons x s) (delay (list x s)))
|
||||
(define (stream-car s) (first (force s)))
|
||||
(define (stream-cdr s) (nth (force s) 1))
|
||||
(let
|
||||
((s (stream-cons 1 (stream-cons 2 (stream-cons 3 nil)))))
|
||||
(assert= 1 (stream-car s))
|
||||
(assert= 2 (stream-car (stream-cdr s))))))
|
||||
(deftest
|
||||
"delay-force is a promise"
|
||||
(do (assert (promise? (delay-force (delay 1))))))
|
||||
(deftest
|
||||
"force with side effects runs once"
|
||||
(do
|
||||
(let
|
||||
((log (list)))
|
||||
(let
|
||||
((p (delay (do (set! log (cons 42 log)) 42))))
|
||||
(force p)
|
||||
(force p)
|
||||
(assert= 1 (len log))))))
|
||||
(deftest
|
||||
"make-promise with nil"
|
||||
(do
|
||||
(let
|
||||
((p (make-promise nil)))
|
||||
(assert (promise? p))
|
||||
(assert= nil (force p)))))
|
||||
(deftest
|
||||
"delay in let binding"
|
||||
(do
|
||||
(let
|
||||
((p (delay (+ 10 20))))
|
||||
(assert= 30 (force p))))))
|
||||
135
spec/tests/test-rationals.sx
Normal file
135
spec/tests/test-rationals.sx
Normal file
@@ -0,0 +1,135 @@
|
||||
;; ==========================================================================
|
||||
;; test-rationals.sx — Rational number type: literals, arithmetic, tower
|
||||
;;
|
||||
;; Note: in the JS host, (/ int int) returns float (backward-compatible).
|
||||
;; Use rational literals (1/3, 3/4) or make-rational for exact rationals.
|
||||
;; ==========================================================================
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Literals and type
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"rationals:literals"
|
||||
(deftest "1/3 is rational" (assert (rational? 1/3)))
|
||||
(deftest "1/2 is rational" (assert (rational? 1/2)))
|
||||
(deftest "2/3 is rational" (assert (rational? 2/3)))
|
||||
(deftest "literal numerator 1/3" (assert= (numerator 1/3) 1))
|
||||
(deftest "literal denominator 1/3" (assert= (denominator 1/3) 3))
|
||||
(deftest "literal numerator 2/3" (assert= (numerator 2/3) 2))
|
||||
(deftest "auto-reduce 2/4 = 1/2" (assert= 2/4 1/2))
|
||||
(deftest "auto-reduce 6/9 = 2/3" (assert= 6/9 2/3))
|
||||
(deftest "negative literal" (assert= (numerator -1/3) -1)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Constructor and predicates
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"rationals:constructor"
|
||||
(deftest
|
||||
"make-rational basic"
|
||||
(assert (rational? (make-rational 1 3))))
|
||||
(deftest
|
||||
"make-rational reduces"
|
||||
(assert= (make-rational 2 4) 1/2))
|
||||
(deftest
|
||||
"make-rational exact int"
|
||||
(assert (integer? (make-rational 6 3))))
|
||||
(deftest
|
||||
"make-rational 6/3 = 2"
|
||||
(assert= (make-rational 6 3) 2))
|
||||
(deftest
|
||||
"make-rational negative"
|
||||
(assert= (numerator (make-rational -1 3)) -1))
|
||||
(deftest
|
||||
"make-rational neg denom"
|
||||
(assert= (numerator (make-rational 1 -3)) -1))
|
||||
(deftest "rational? on int" (assert (not (rational? 5))))
|
||||
(deftest "rational? on float" (assert (not (rational? 1.5))))
|
||||
(deftest "rational? on string" (assert (not (rational? "1/2"))))
|
||||
(deftest "number? on rational" (assert (number? 1/3)))
|
||||
(deftest "exact? on rational" (assert (exact? 1/3)))
|
||||
(deftest "inexact? on rational" (assert (not (inexact? 1/3))))
|
||||
(deftest "integer? on rational" (assert (not (integer? 1/3))))
|
||||
(deftest "dict? on rational" (assert (not (dict? 1/3)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Accessors
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"rationals:accessors"
|
||||
(deftest "numerator 1/3" (assert= (numerator 1/3) 1))
|
||||
(deftest "denominator 1/3" (assert= (denominator 1/3) 3))
|
||||
(deftest "numerator 3/4" (assert= (numerator 3/4) 3))
|
||||
(deftest "denominator 3/4" (assert= (denominator 3/4) 4))
|
||||
(deftest "numerator of int" (assert= (numerator 5) 5))
|
||||
(deftest
|
||||
"denominator of int"
|
||||
(assert= (denominator 5) 1)))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Arithmetic
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"rationals:arithmetic"
|
||||
(deftest "add two rationals" (assert= (+ 1/3 1/3) 2/3))
|
||||
(deftest "add to integer" (assert= (+ 1 1/2) 3/2))
|
||||
(deftest "add integer to rational" (assert= (+ 1/2 1) 3/2))
|
||||
(deftest "add reduces" (assert= (+ 1/6 1/6) 1/3))
|
||||
(deftest "add to whole number" (assert (integer? (+ 1/2 1/2))))
|
||||
(deftest "add whole = 1" (assert= (+ 1/2 1/2) 1))
|
||||
(deftest "subtract rationals" (assert= (- 3/4 1/4) 1/2))
|
||||
(deftest "subtract int from rational" (assert= (- 3/2 1) 1/2))
|
||||
(deftest "negate rational" (assert= (- 1/3) -1/3))
|
||||
(deftest "multiply rationals" (assert= (* 2/3 3/4) 1/2))
|
||||
(deftest "multiply int and rational" (assert= (* 2 1/3) 2/3))
|
||||
(deftest "multiply reduces to int" (assert (integer? (* 3 1/3))))
|
||||
(deftest "divide rational by int" (assert= (/ 2/3 2) 1/3))
|
||||
(deftest "divide rational by rational" (assert= (/ 1/2 1/4) 2))
|
||||
(deftest
|
||||
"divide rational gives int when exact"
|
||||
(assert (integer? (/ 1/2 1/2)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Float contagion
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"rationals:float-contagion"
|
||||
(deftest "rational + float = float" (assert (float? (+ 1/3 0.5))))
|
||||
(deftest "float + rational = float" (assert (float? (+ 0.5 1/3))))
|
||||
(deftest "rational * float = float" (assert (float? (* 1/2 2))))
|
||||
(deftest "rational - float = float" (assert (float? (- 1/2 0.1)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Comparison
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"rationals:comparison"
|
||||
(deftest "equal rationals" (assert (= 1/2 1/2)))
|
||||
(deftest "equal reduced" (assert (= 2/4 1/2)))
|
||||
(deftest "not equal" (assert (not (= 1/3 1/2))))
|
||||
(deftest "less than" (assert (< 1/3 1/2)))
|
||||
(deftest "less than int" (assert (< 1/3 1)))
|
||||
(deftest "greater than" (assert (> 2/3 1/2)))
|
||||
(deftest "less equal" (assert (<= 1/3 1/3)))
|
||||
(deftest "greater equal" (assert (>= 2/3 2/3)))
|
||||
(deftest "rational less than float" (assert (< 1/3 0.5))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; Coercion
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"rationals:coercion"
|
||||
(deftest "exact->inexact 1/2" (assert= (exact->inexact 1/2) 0.5))
|
||||
(deftest "exact->inexact 1/4" (assert= (exact->inexact 1/4) 0.25))
|
||||
(deftest
|
||||
"exact->inexact 1/3 is float"
|
||||
(assert (float? (exact->inexact 1/3))))
|
||||
(deftest "number->string 1/2" (assert= (number->string 1/2) "1/2"))
|
||||
(deftest "number->string 3/4" (assert= (number->string 3/4) "3/4")))
|
||||
212
spec/tests/test-read-write.sx
Normal file
212
spec/tests/test-read-write.sx
Normal file
@@ -0,0 +1,212 @@
|
||||
;; ==========================================================================
|
||||
;; test-read-write.sx — Tests for read / write / display / newline
|
||||
;; ==========================================================================
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; read — parse one datum from an input port
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"read:basics"
|
||||
(deftest
|
||||
"read integer"
|
||||
(let ((p (open-input-string "42"))) (assert= (read p) 42)))
|
||||
(deftest
|
||||
"read float"
|
||||
(let ((p (open-input-string "3.14"))) (assert= (read p) 3.14)))
|
||||
(deftest
|
||||
"read string"
|
||||
(let ((p (open-input-string "\"hello\""))) (assert= (read p) "hello")))
|
||||
(deftest
|
||||
"read boolean true"
|
||||
(let ((p (open-input-string "#t"))) (assert (read p))))
|
||||
(deftest
|
||||
"read boolean false"
|
||||
(let ((p (open-input-string "#f"))) (assert (not (read p)))))
|
||||
(deftest
|
||||
"read nil"
|
||||
(let ((p (open-input-string "()"))) (assert-nil (read p))))
|
||||
(deftest
|
||||
"read list"
|
||||
(let
|
||||
((p (open-input-string "(1 2 3)")))
|
||||
(assert= (read p) (list 1 2 3))))
|
||||
(deftest
|
||||
"read nested list"
|
||||
(let
|
||||
((p (open-input-string "(+ 1 (* 2 3))")))
|
||||
(assert=
|
||||
(read p)
|
||||
(list (quote +) 1 (list (quote *) 2 3))))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; read — eof and multi-read
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"read:eof"
|
||||
(deftest
|
||||
"read eof returns eof-object"
|
||||
(let ((p (open-input-string ""))) (assert (eof-object? (read p)))))
|
||||
(deftest
|
||||
"read whitespace-only returns eof"
|
||||
(let ((p (open-input-string " "))) (assert (eof-object? (read p)))))
|
||||
(deftest
|
||||
"read two forms"
|
||||
(let
|
||||
((p (open-input-string "1 2")))
|
||||
(let
|
||||
((a (read p)) (b (read p)))
|
||||
(assert (and (= a 1) (= b 2))))))
|
||||
(deftest
|
||||
"read returns eof after last form"
|
||||
(let
|
||||
((p (open-input-string "42")))
|
||||
(read p)
|
||||
(assert (eof-object? (read p))))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; write — serialize with quoting
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"write:basics"
|
||||
(deftest "write integer" (assert= (write-to-string 42) "42"))
|
||||
(deftest
|
||||
"write negative integer"
|
||||
(assert= (write-to-string -5) "-5"))
|
||||
(deftest "write float" (assert= (write-to-string 3.14) "3.14"))
|
||||
(deftest "write true" (assert= (write-to-string true) "#t"))
|
||||
(deftest "write false" (assert= (write-to-string false) "#f"))
|
||||
(deftest "write nil" (assert= (write-to-string nil) "()"))
|
||||
(deftest
|
||||
"write string quotes"
|
||||
(assert= (write-to-string "hello") "\"hello\""))
|
||||
(deftest
|
||||
"write string with escapes"
|
||||
(assert= (write-to-string "a\"b") "\"a\\\"b\""))
|
||||
(deftest
|
||||
"write list"
|
||||
(assert=
|
||||
(write-to-string (list 1 2 3))
|
||||
"(1 2 3)"))
|
||||
(deftest
|
||||
"write nested list"
|
||||
(assert=
|
||||
(write-to-string (list 1 (list 2 3)))
|
||||
"(1 (2 3))"))
|
||||
(deftest "write symbol" (assert= (write-to-string (quote foo)) "foo"))
|
||||
(deftest "write rational" (assert= (write-to-string 1/3) "1/3")))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; display — serialize without quoting
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"display:basics"
|
||||
(deftest "display integer" (assert= (display-to-string 42) "42"))
|
||||
(deftest
|
||||
"display string no quotes"
|
||||
(assert= (display-to-string "hello") "hello"))
|
||||
(deftest "display true" (assert= (display-to-string true) "#t"))
|
||||
(deftest "display nil" (assert= (display-to-string nil) "()"))
|
||||
(deftest
|
||||
"display list"
|
||||
(assert=
|
||||
(display-to-string (list 1 2 3))
|
||||
"(1 2 3)")))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; write vs display distinction
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"write-vs-display"
|
||||
(deftest
|
||||
"write quotes string, display does not"
|
||||
(let
|
||||
((s "hello"))
|
||||
(assert
|
||||
(and
|
||||
(= (write-to-string s) "\"hello\"")
|
||||
(= (display-to-string s) "hello")))))
|
||||
(deftest
|
||||
"write and display same for numbers"
|
||||
(assert= (write-to-string 42) (display-to-string 42)))
|
||||
(deftest
|
||||
"write and display same for lists"
|
||||
(assert=
|
||||
(write-to-string (list 1 2))
|
||||
(display-to-string (list 1 2)))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; write/display/newline to port
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"write-to-port"
|
||||
(deftest
|
||||
"write to output port"
|
||||
(let
|
||||
((p (open-output-string)))
|
||||
(write 42 p)
|
||||
(assert= (get-output-string p) "42")))
|
||||
(deftest
|
||||
"display to output port"
|
||||
(let
|
||||
((p (open-output-string)))
|
||||
(display "hi" p)
|
||||
(assert= (get-output-string p) "hi")))
|
||||
(deftest
|
||||
"newline to output port"
|
||||
(let
|
||||
((p (open-output-string)))
|
||||
(newline p)
|
||||
(assert= (get-output-string p) "\n")))
|
||||
(deftest
|
||||
"write then newline"
|
||||
(let
|
||||
((p (open-output-string)))
|
||||
(write "hello" p)
|
||||
(newline p)
|
||||
(assert= (get-output-string p) "\"hello\"\n")))
|
||||
(deftest
|
||||
"display multiple values"
|
||||
(let
|
||||
((p (open-output-string)))
|
||||
(display 1 p)
|
||||
(display " " p)
|
||||
(display 2 p)
|
||||
(assert= (get-output-string p) "1 2"))))
|
||||
|
||||
;; --------------------------------------------------------------------------
|
||||
;; write round-trip
|
||||
;; --------------------------------------------------------------------------
|
||||
|
||||
(defsuite
|
||||
"write:round-trip"
|
||||
(deftest
|
||||
"integer round-trips"
|
||||
(let
|
||||
((p (open-input-string (write-to-string 42))))
|
||||
(assert= (read p) 42)))
|
||||
(deftest
|
||||
"string round-trips"
|
||||
(let
|
||||
((p (open-input-string (write-to-string "hello world"))))
|
||||
(assert= (read p) "hello world")))
|
||||
(deftest
|
||||
"list round-trips"
|
||||
(let
|
||||
((p (open-input-string (write-to-string (list 1 2 3)))))
|
||||
(assert= (read p) (list 1 2 3))))
|
||||
(deftest
|
||||
"boolean true round-trips"
|
||||
(let
|
||||
((p (open-input-string (write-to-string true))))
|
||||
(assert (read p))))
|
||||
(deftest
|
||||
"boolean false round-trips"
|
||||
(let
|
||||
((p (open-input-string (write-to-string false))))
|
||||
(assert (not (read p))))))
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user