Compare commits
37 Commits
loops/js
...
83dbb5958a
| Author | SHA1 | Date | |
|---|---|---|---|
| 83dbb5958a | |||
| d21cde336a | |||
| f0f339709e | |||
| 0596376199 | |||
| 35511db15b | |||
| 40ce4df6b1 | |||
| 0cc36450c4 | |||
| 21e8e51174 | |||
| bc45b7abf5 | |||
| 2c61be39de | |||
| ea064346e1 | |||
| 23c44cf6cf | |||
| 5e0fcb9316 | |||
| d295ab8463 | |||
| afddc92c70 | |||
| 95f96efb78 | |||
| 95b22a648d | |||
| cffd3bec83 | |||
| eb5babaf99 | |||
| a49b1a9f79 | |||
| 263d9aae68 | |||
| 0dbf9b9f73 | |||
| 7b11f3d44a | |||
| a26be0bfd0 | |||
| 9ed3e4faaf | |||
| ac013c9381 | |||
| 72ccaf4565 | |||
| c8d7fdd59a | |||
| 82da16e4bb | |||
| 35aa998fcc | |||
| 6ee052593c | |||
| 1a17d8d232 | |||
| 666e29d5f0 | |||
| 3316d402fd | |||
| fb72c4ab9c | |||
| e52c209c3d | |||
| 6a00df2609 |
@@ -688,6 +688,11 @@ let setup_evaluator_bridge env =
|
||||
| [expr; e] -> Sx_ref.eval_expr expr (Env (Sx_runtime.unwrap_env e))
|
||||
| [expr] -> Sx_ref.eval_expr expr (Env env)
|
||||
| _ -> raise (Eval_error "eval-expr: expected (expr env?)"));
|
||||
(* eval-in-env: (env expr) → result. Evaluates expr in the given env. *)
|
||||
Sx_primitives.register "eval-in-env" (fun args ->
|
||||
match args with
|
||||
| [e; expr] -> Sx_ref.eval_expr expr e
|
||||
| _ -> raise (Eval_error "eval-in-env: (env expr)"));
|
||||
bind "trampoline" (fun args ->
|
||||
match args with
|
||||
| [v] ->
|
||||
@@ -749,7 +754,13 @@ let setup_evaluator_bridge env =
|
||||
| _ -> raise (Eval_error "register-special-form!: expected (name handler)"));
|
||||
ignore (env_bind env "*custom-special-forms*" Sx_ref.custom_special_forms);
|
||||
ignore (Sx_ref.register_special_form (String "<>") (NativeFn ("<>", fun args ->
|
||||
List (List.map (fun a -> Sx_ref.eval_expr a (Env env)) args))))
|
||||
List (List.map (fun a -> Sx_ref.eval_expr a (Env env)) args))));
|
||||
(* current-env: special form — returns current lexical env as a first-class value *)
|
||||
ignore (Sx_ref.register_special_form (String "current-env")
|
||||
(NativeFn ("current-env", fun args ->
|
||||
match args with
|
||||
| [_arg_list; env_val] -> env_val
|
||||
| _ -> Nil)))
|
||||
|
||||
(* ---- Type predicates and introspection ---- *)
|
||||
let setup_introspection env =
|
||||
@@ -935,7 +946,24 @@ let setup_env_operations env =
|
||||
bind "env-has?" (fun args -> match args with [e; String k] -> Bool (Sx_types.env_has (uw e) k) | [e; Keyword k] -> Bool (Sx_types.env_has (uw e) k) | _ -> raise (Eval_error "env-has?: expected env and string"));
|
||||
bind "env-bind!" (fun args -> match args with [e; String k; v] -> Sx_types.env_bind (uw e) k v | [e; Keyword k; v] -> Sx_types.env_bind (uw e) k v | _ -> raise (Eval_error "env-bind!: expected env, key, value"));
|
||||
bind "env-set!" (fun args -> match args with [e; String k; v] -> Sx_types.env_set (uw e) k v | [e; Keyword k; v] -> Sx_types.env_set (uw e) k v | _ -> raise (Eval_error "env-set!: expected env, key, value"));
|
||||
bind "env-extend" (fun args -> match args with [e] -> Env (Sx_types.env_extend (uw e)) | _ -> raise (Eval_error "env-extend: expected env"));
|
||||
bind "env-extend" (fun args ->
|
||||
match args with
|
||||
| e :: pairs ->
|
||||
let child = Sx_types.env_extend (uw e) in
|
||||
let rec go = function
|
||||
| [] -> ()
|
||||
| k :: v :: rest ->
|
||||
ignore (Sx_types.env_bind child (Sx_runtime.value_to_str k) v); go rest
|
||||
| [_] -> raise (Eval_error "env-extend: odd number of key-val pairs") in
|
||||
go pairs; Env child
|
||||
| _ -> raise (Eval_error "env-extend: expected env"));
|
||||
bind "env-lookup" (fun args ->
|
||||
match args with
|
||||
| [e; key] ->
|
||||
let k = Sx_runtime.value_to_str key in
|
||||
let raw = uw e in
|
||||
if Sx_types.env_has raw k then Sx_types.env_get raw k else Nil
|
||||
| _ -> raise (Eval_error "env-lookup: (env key)"));
|
||||
bind "env-merge" (fun args -> match args with [a; b] -> Sx_runtime.env_merge a b | _ -> raise (Eval_error "env-merge: expected 2 envs"))
|
||||
|
||||
(* ---- Strict mode (gradual type system support) ---- *)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
(library
|
||||
(name sx)
|
||||
(wrapped false)
|
||||
(libraries re re.pcre))
|
||||
(libraries re re.pcre unix))
|
||||
|
||||
@@ -1871,4 +1871,175 @@ let () =
|
||||
| [rx] ->
|
||||
let (_, _, flags) = regex_of_value rx in
|
||||
String flags
|
||||
| _ -> raise (Eval_error "regex-flags: (regex)"))
|
||||
| _ -> raise (Eval_error "regex-flags: (regex)"));
|
||||
|
||||
(* === File I/O === *)
|
||||
register "file-read" (fun args ->
|
||||
match args with
|
||||
| [String path] ->
|
||||
(try
|
||||
let ic = open_in path in
|
||||
let n = in_channel_length ic in
|
||||
let s = Bytes.create n in
|
||||
really_input ic s 0 n;
|
||||
close_in ic;
|
||||
String (Bytes.to_string s)
|
||||
with Sys_error msg -> raise (Eval_error ("file-read: " ^ msg)))
|
||||
| _ -> raise (Eval_error "file-read: (path)"));
|
||||
|
||||
register "file-write" (fun args ->
|
||||
match args with
|
||||
| [String path; String content] ->
|
||||
(try
|
||||
let oc = open_out path in
|
||||
output_string oc content;
|
||||
close_out oc;
|
||||
Nil
|
||||
with Sys_error msg -> raise (Eval_error ("file-write: " ^ msg)))
|
||||
| _ -> raise (Eval_error "file-write: (path content)"));
|
||||
|
||||
register "file-append" (fun args ->
|
||||
match args with
|
||||
| [String path; String content] ->
|
||||
(try
|
||||
let oc = open_out_gen [Open_append; Open_creat; Open_wronly; Open_text] 0o644 path in
|
||||
output_string oc content;
|
||||
close_out oc;
|
||||
Nil
|
||||
with Sys_error msg -> raise (Eval_error ("file-append: " ^ msg)))
|
||||
| _ -> raise (Eval_error "file-append: (path content)"));
|
||||
|
||||
register "file-exists?" (fun args ->
|
||||
match args with
|
||||
| [String path] -> Bool (Sys.file_exists path)
|
||||
| _ -> raise (Eval_error "file-exists?: (path)"));
|
||||
|
||||
register "file-glob" (fun args ->
|
||||
let glob_match pat str =
|
||||
let pn = String.length pat and sn = String.length str in
|
||||
let rec go pi si =
|
||||
if pi = pn then si = sn
|
||||
else match pat.[pi] with
|
||||
| '*' ->
|
||||
let rec try_from i = i <= sn && (go (pi+1) i || try_from (i+1)) in
|
||||
try_from si
|
||||
| '?' -> si < sn && go (pi+1) (si+1)
|
||||
| '[' ->
|
||||
let pi' = ref (pi+1) in
|
||||
let negate = !pi' < pn && pat.[!pi'] = '^' in
|
||||
if negate then incr pi';
|
||||
let matched = ref false in
|
||||
while !pi' < pn && pat.[!pi'] <> ']' do
|
||||
let c1 = pat.[!pi'] in
|
||||
incr pi';
|
||||
if !pi' + 1 < pn && pat.[!pi'] = '-' then begin
|
||||
let c2 = pat.[!pi' + 1] in
|
||||
pi' := !pi' + 2;
|
||||
if si < sn && str.[si] >= c1 && str.[si] <= c2 then matched := true
|
||||
end else if si < sn && str.[si] = c1 then matched := true
|
||||
done;
|
||||
if !pi' < pn then incr pi';
|
||||
((!matched && not negate) || (not !matched && negate)) && go !pi' (si+1)
|
||||
| c -> si < sn && str.[si] = c && go (pi+1) (si+1)
|
||||
in go 0 0
|
||||
in
|
||||
let glob_paths pat =
|
||||
let dir = Filename.dirname pat in
|
||||
let base_pat = Filename.basename pat in
|
||||
let dir' = if dir = "." && not (String.length pat > 1 && pat.[0] = '.') then "." else dir in
|
||||
(try
|
||||
let entries = Sys.readdir dir' in
|
||||
Array.fold_left (fun acc entry ->
|
||||
if glob_match base_pat entry then
|
||||
let full = if dir' = "." then entry else Filename.concat dir' entry in
|
||||
full :: acc
|
||||
else acc
|
||||
) [] entries
|
||||
|> List.sort String.compare
|
||||
with Sys_error _ -> [])
|
||||
in
|
||||
match args with
|
||||
| [String pat] -> List (List.map (fun s -> String s) (glob_paths pat))
|
||||
| _ -> raise (Eval_error "file-glob: (pattern)"));
|
||||
|
||||
(* === Clock === *)
|
||||
register "clock-seconds" (fun args ->
|
||||
match args with
|
||||
| [] -> Number (Float.round (Unix.gettimeofday ()))
|
||||
| _ -> raise (Eval_error "clock-seconds: no args"));
|
||||
|
||||
register "clock-milliseconds" (fun args ->
|
||||
match args with
|
||||
| [] -> Number (Float.round (Unix.gettimeofday () *. 1000.0))
|
||||
| _ -> raise (Eval_error "clock-milliseconds: no args"));
|
||||
|
||||
register "clock-format" (fun args ->
|
||||
match args with
|
||||
| [Number t_f] | [Number t_f; String _] ->
|
||||
let t = int_of_float t_f in
|
||||
let fmt = (match args with [_; String f] -> f | _ -> "%a %b %e %H:%M:%S %Z %Y") in
|
||||
let tm = Unix.gmtime (float_of_int t) in
|
||||
let buf = Buffer.create 32 in
|
||||
let n = String.length fmt in
|
||||
let i = ref 0 in
|
||||
while !i < n do
|
||||
if fmt.[!i] = '%' && !i + 1 < n then begin
|
||||
(match fmt.[!i + 1] with
|
||||
| 'Y' -> Buffer.add_string buf (Printf.sprintf "%04d" (1900 + tm.Unix.tm_year))
|
||||
| 'm' -> Buffer.add_string buf (Printf.sprintf "%02d" (tm.Unix.tm_mon + 1))
|
||||
| 'd' -> Buffer.add_string buf (Printf.sprintf "%02d" tm.Unix.tm_mday)
|
||||
| 'e' -> Buffer.add_string buf (Printf.sprintf "%2d" tm.Unix.tm_mday)
|
||||
| 'H' -> Buffer.add_string buf (Printf.sprintf "%02d" tm.Unix.tm_hour)
|
||||
| 'M' -> Buffer.add_string buf (Printf.sprintf "%02d" tm.Unix.tm_min)
|
||||
| 'S' -> Buffer.add_string buf (Printf.sprintf "%02d" tm.Unix.tm_sec)
|
||||
| 'j' -> Buffer.add_string buf (Printf.sprintf "%03d" (tm.Unix.tm_yday + 1))
|
||||
| 'Z' -> Buffer.add_string buf "UTC"
|
||||
| 'a' -> let days = [|"Sun";"Mon";"Tue";"Wed";"Thu";"Fri";"Sat"|] in
|
||||
Buffer.add_string buf days.(tm.Unix.tm_wday)
|
||||
| 'A' -> let days = [|"Sunday";"Monday";"Tuesday";"Wednesday";"Thursday";"Friday";"Saturday"|] in
|
||||
Buffer.add_string buf days.(tm.Unix.tm_wday)
|
||||
| 'b' | 'h' -> let mons = [|"Jan";"Feb";"Mar";"Apr";"May";"Jun";"Jul";"Aug";"Sep";"Oct";"Nov";"Dec"|] in
|
||||
Buffer.add_string buf mons.(tm.Unix.tm_mon)
|
||||
| 'B' -> let mons = [|"January";"February";"March";"April";"May";"June";"July";"August";"September";"October";"November";"December"|] in
|
||||
Buffer.add_string buf mons.(tm.Unix.tm_mon)
|
||||
| c -> Buffer.add_char buf '%'; Buffer.add_char buf c);
|
||||
i := !i + 2
|
||||
end else begin
|
||||
Buffer.add_char buf fmt.[!i];
|
||||
incr i
|
||||
end
|
||||
done;
|
||||
String (Buffer.contents buf)
|
||||
| _ -> raise (Eval_error "clock-format: (seconds [format])"));
|
||||
|
||||
(* === Env-as-value (Phase 4) === *)
|
||||
|
||||
(* env-lookup: (env key) → value or nil. Works on Env, Dict, or Nil. *)
|
||||
register "env-lookup" (fun args ->
|
||||
let unwrap = function
|
||||
| Env e -> e
|
||||
| Nil -> make_env ()
|
||||
| _ -> raise (Eval_error "env-lookup: first arg must be an environment") in
|
||||
match args with
|
||||
| [env_val; key] ->
|
||||
let e = unwrap env_val in
|
||||
let k = value_to_string key in
|
||||
if env_has e k then env_get e k else Nil
|
||||
| _ -> raise (Eval_error "env-lookup: (env key)"));
|
||||
|
||||
(* env-extend: (env [key val ...]) → new child env with optional bindings. *)
|
||||
register "env-extend" (fun args ->
|
||||
match args with
|
||||
| [] -> raise (Eval_error "env-extend: requires at least one arg")
|
||||
| env_val :: pairs ->
|
||||
let parent_env = match env_val with
|
||||
| Env e -> e
|
||||
| Nil -> make_env ()
|
||||
| _ -> raise (Eval_error "env-extend: first arg must be an environment") in
|
||||
let child = env_extend parent_env in
|
||||
let rec add_bindings = function
|
||||
| [] -> ()
|
||||
| k :: v :: rest -> ignore (env_bind child (value_to_string k) v); add_bindings rest
|
||||
| [_] -> raise (Eval_error "env-extend: odd number of key-val pairs") in
|
||||
add_bindings pairs;
|
||||
Env child)
|
||||
|
||||
@@ -529,3 +529,4 @@ let jit_try_call f args =
|
||||
(match hook f arg_list with Some result -> incr _jit_hit; result | None -> incr _jit_miss; _jit_skip_sentinel)
|
||||
| _ -> incr _jit_skip; _jit_skip_sentinel
|
||||
|
||||
|
||||
|
||||
44
lib/fiber.sx
Normal file
44
lib/fiber.sx
Normal file
@@ -0,0 +1,44 @@
|
||||
; lib/fiber.sx — pure SX fiber library using call/cc
|
||||
;
|
||||
; A fiber is a cooperative coroutine with true suspension (no eager
|
||||
; pre-execution). Each fiber is a dict {:resume fn :done? fn}.
|
||||
;
|
||||
; make-fiber body → fiber dict
|
||||
; body = (fn (yield init-val) ...) — body receives yield + first resume val
|
||||
; yield = (fn (val) ...) — suspends fiber, returns val to resumer
|
||||
;
|
||||
; fiber-resume f v → next yielded value, or nil when body returns
|
||||
; fiber-done? f → true after body has returned
|
||||
|
||||
(define make-fiber
|
||||
(fn (body)
|
||||
(let
|
||||
((resume-k nil)
|
||||
(caller-k nil)
|
||||
(done false))
|
||||
(let
|
||||
((yield
|
||||
(fn (val)
|
||||
(call/cc
|
||||
(fn (k)
|
||||
(set! resume-k k)
|
||||
(caller-k val))))))
|
||||
{:resume
|
||||
(fn (val)
|
||||
(if
|
||||
done
|
||||
nil
|
||||
(call/cc
|
||||
(fn (k)
|
||||
(set! caller-k k)
|
||||
(if
|
||||
(nil? resume-k)
|
||||
(begin
|
||||
(body yield val)
|
||||
(set! done true)
|
||||
(k nil))
|
||||
(resume-k val))))))
|
||||
:done? (fn () done)}))))
|
||||
|
||||
(define fiber-resume (fn (f v) ((get f :resume) v)))
|
||||
(define fiber-done? (fn (f) ((get f :done?))))
|
||||
251
lib/js/lexer.sx
251
lib/js/lexer.sx
@@ -29,16 +29,6 @@
|
||||
(and (>= c "a") (<= c "f"))
|
||||
(and (>= c "A") (<= c "F")))))
|
||||
|
||||
(define
|
||||
js-hex-value
|
||||
(fn
|
||||
(c)
|
||||
(cond
|
||||
((and (>= c "0") (<= c "9")) (- (char-code c) 48))
|
||||
((and (>= c "a") (<= c "f")) (- (char-code c) 87))
|
||||
((and (>= c "A") (<= c "F")) (- (char-code c) 55))
|
||||
(else 0))))
|
||||
|
||||
(define
|
||||
js-letter?
|
||||
(fn (c) (or (and (>= c "a") (<= c "z")) (and (>= c "A") (<= c "Z")))))
|
||||
@@ -47,9 +37,9 @@
|
||||
|
||||
(define js-ident-char? (fn (c) (or (js-ident-start? c) (js-digit? c))))
|
||||
|
||||
;; ── Reserved words ────────────────────────────────────────────────
|
||||
(define js-ws? (fn (c) (or (= c " ") (= c "\t") (= c "\n") (= c "\r"))))
|
||||
|
||||
;; ── Reserved words ────────────────────────────────────────────────
|
||||
(define
|
||||
js-keywords
|
||||
(list
|
||||
@@ -96,18 +86,15 @@
|
||||
"await"
|
||||
"of"))
|
||||
|
||||
;; ── Main tokenizer ────────────────────────────────────────────────
|
||||
(define js-keyword? (fn (word) (contains? js-keywords word)))
|
||||
|
||||
;; ── Main tokenizer ────────────────────────────────────────────────
|
||||
(define
|
||||
js-tokenize
|
||||
(fn
|
||||
(src)
|
||||
(let
|
||||
((tokens (list))
|
||||
(pos 0)
|
||||
(src-len (len src))
|
||||
(nl-before false))
|
||||
((tokens (list)) (pos 0) (src-len (len src)))
|
||||
(define
|
||||
js-peek
|
||||
(fn
|
||||
@@ -122,7 +109,11 @@
|
||||
(let
|
||||
((sl (len s)))
|
||||
(and (<= (+ pos sl) src-len) (= (slice src pos (+ pos sl)) s)))))
|
||||
(define js-emit! (fn (type value start) (append! tokens {:nl nl-before :type type :value value :pos start})))
|
||||
(define
|
||||
js-emit!
|
||||
(fn
|
||||
(type value start)
|
||||
(append! tokens (js-make-token type value start))))
|
||||
(define
|
||||
skip-line-comment!
|
||||
(fn
|
||||
@@ -145,13 +136,7 @@
|
||||
()
|
||||
(cond
|
||||
((>= pos src-len) nil)
|
||||
((js-ws? (cur))
|
||||
(do
|
||||
(when
|
||||
(or (= (cur) "\n") (= (cur) "\r"))
|
||||
(set! nl-before true))
|
||||
(advance! 1)
|
||||
(skip-ws!)))
|
||||
((js-ws? (cur)) (do (advance! 1) (skip-ws!)))
|
||||
((and (= (cur) "/") (< (+ pos 1) src-len) (= (js-peek 1) "/"))
|
||||
(do (advance! 2) (skip-line-comment!) (skip-ws!)))
|
||||
((and (= (cur) "/") (< (+ pos 1) src-len) (= (js-peek 1) "*"))
|
||||
@@ -269,55 +254,11 @@
|
||||
((= ch "b") (append! chars "\\b"))
|
||||
((= ch "f") (append! chars "\\f"))
|
||||
((= ch "v") (append! chars "\\v"))
|
||||
((= ch "u")
|
||||
(if
|
||||
(and
|
||||
(< (+ pos 4) src-len)
|
||||
(js-hex-digit? (js-peek 1))
|
||||
(js-hex-digit? (js-peek 2))
|
||||
(js-hex-digit? (js-peek 3))
|
||||
(js-hex-digit? (js-peek 4)))
|
||||
(do
|
||||
(append!
|
||||
chars
|
||||
(char-from-code
|
||||
(+
|
||||
(*
|
||||
4096
|
||||
(js-hex-value
|
||||
(js-peek 1)))
|
||||
(*
|
||||
256
|
||||
(js-hex-value
|
||||
(js-peek 2)))
|
||||
(*
|
||||
16
|
||||
(js-hex-value
|
||||
(js-peek 3)))
|
||||
(js-hex-value (js-peek 4)))))
|
||||
(advance! 4))
|
||||
(append! chars ch)))
|
||||
((= ch "x")
|
||||
(if
|
||||
(and
|
||||
(< (+ pos 2) src-len)
|
||||
(js-hex-digit? (js-peek 1))
|
||||
(js-hex-digit? (js-peek 2)))
|
||||
(do
|
||||
(append!
|
||||
chars
|
||||
(char-from-code
|
||||
(+
|
||||
(* 16 (js-hex-value (js-peek 1)))
|
||||
(js-hex-value (js-peek 2)))))
|
||||
(advance! 2))
|
||||
(append! chars ch)))
|
||||
(else (append! chars ch)))
|
||||
(advance! 1))))
|
||||
(loop)))
|
||||
((= (cur) quote-char) (advance! 1))
|
||||
(else
|
||||
(do (append! chars (cur)) (advance! 1) (loop))))))
|
||||
(else (do (append! chars (cur)) (advance! 1) (loop))))))
|
||||
(loop)
|
||||
(join "" chars))))
|
||||
(define
|
||||
@@ -348,8 +289,7 @@
|
||||
()
|
||||
(cond
|
||||
((>= pos src-len) nil)
|
||||
((and (= (cur) "}") (= depth 1))
|
||||
(advance! 1))
|
||||
((and (= (cur) "}") (= depth 1)) (advance! 1))
|
||||
((= (cur) "}")
|
||||
(do
|
||||
(append! buf (cur))
|
||||
@@ -385,9 +325,7 @@
|
||||
(advance! 1)))
|
||||
(sloop)))
|
||||
((= (cur) q)
|
||||
(do
|
||||
(append! buf (cur))
|
||||
(advance! 1)))
|
||||
(do (append! buf (cur)) (advance! 1)))
|
||||
(else
|
||||
(do
|
||||
(append! buf (cur))
|
||||
@@ -396,10 +334,7 @@
|
||||
(sloop)
|
||||
(expr-loop))))
|
||||
(else
|
||||
(do
|
||||
(append! buf (cur))
|
||||
(advance! 1)
|
||||
(expr-loop))))))
|
||||
(do (append! buf (cur)) (advance! 1) (expr-loop))))))
|
||||
(expr-loop)
|
||||
(join "" buf))))
|
||||
(define
|
||||
@@ -441,17 +376,14 @@
|
||||
(else (append! chars ch)))
|
||||
(advance! 1))))
|
||||
(loop)))
|
||||
(else
|
||||
(do (append! chars (cur)) (advance! 1) (loop))))))
|
||||
(else (do (append! chars (cur)) (advance! 1) (loop))))))
|
||||
(loop)
|
||||
(flush-chars!)
|
||||
(if
|
||||
(= (len parts) 0)
|
||||
""
|
||||
(if
|
||||
(and
|
||||
(= (len parts) 1)
|
||||
(= (nth (nth parts 0) 0) "str"))
|
||||
(and (= (len parts) 1) (= (nth (nth parts 0) 0) "str"))
|
||||
(nth (nth parts 0) 1)
|
||||
parts)))))
|
||||
(define
|
||||
@@ -467,7 +399,7 @@
|
||||
((ty (dict-get tk "type")) (vv (dict-get tk "value")))
|
||||
(cond
|
||||
((= ty "punct")
|
||||
(and (not (= vv ")")) (not (= vv "]")) (not (= vv "}"))))
|
||||
(and (not (= vv ")")) (not (= vv "]"))))
|
||||
((= ty "op") true)
|
||||
((= ty "keyword")
|
||||
(contains?
|
||||
@@ -521,13 +453,9 @@
|
||||
(append! buf (cur))
|
||||
(advance! 1)
|
||||
(body-loop)))
|
||||
((and (= (cur) "/") (not in-class))
|
||||
(advance! 1))
|
||||
((and (= (cur) "/") (not in-class)) (advance! 1))
|
||||
(else
|
||||
(begin
|
||||
(append! buf (cur))
|
||||
(advance! 1)
|
||||
(body-loop))))))
|
||||
(begin (append! buf (cur)) (advance! 1) (body-loop))))))
|
||||
(body-loop)
|
||||
(let
|
||||
((flags-buf (list)))
|
||||
@@ -542,7 +470,7 @@
|
||||
(advance! 1)
|
||||
(flags-loop)))))
|
||||
(flags-loop)
|
||||
{:flags (join "" flags-buf) :pattern (join "" buf)}))))
|
||||
{:pattern (join "" buf) :flags (join "" flags-buf)}))))
|
||||
(define
|
||||
try-op-4!
|
||||
(fn
|
||||
@@ -582,113 +510,64 @@
|
||||
(fn
|
||||
(start)
|
||||
(cond
|
||||
((at? "==")
|
||||
(do (js-emit! "op" "==" start) (advance! 2) true))
|
||||
((at? "!=")
|
||||
(do (js-emit! "op" "!=" start) (advance! 2) true))
|
||||
((at? "<=")
|
||||
(do (js-emit! "op" "<=" start) (advance! 2) true))
|
||||
((at? ">=")
|
||||
(do (js-emit! "op" ">=" start) (advance! 2) true))
|
||||
((at? "&&")
|
||||
(do (js-emit! "op" "&&" start) (advance! 2) true))
|
||||
((at? "||")
|
||||
(do (js-emit! "op" "||" start) (advance! 2) true))
|
||||
((at? "??")
|
||||
(do (js-emit! "op" "??" start) (advance! 2) true))
|
||||
((at? "=>")
|
||||
(do (js-emit! "op" "=>" start) (advance! 2) true))
|
||||
((at? "**")
|
||||
(do (js-emit! "op" "**" start) (advance! 2) true))
|
||||
((at? "<<")
|
||||
(do (js-emit! "op" "<<" start) (advance! 2) true))
|
||||
((at? ">>")
|
||||
(do (js-emit! "op" ">>" start) (advance! 2) true))
|
||||
((at? "++")
|
||||
(do (js-emit! "op" "++" start) (advance! 2) true))
|
||||
((at? "--")
|
||||
(do (js-emit! "op" "--" start) (advance! 2) true))
|
||||
((at? "+=")
|
||||
(do (js-emit! "op" "+=" start) (advance! 2) true))
|
||||
((at? "-=")
|
||||
(do (js-emit! "op" "-=" start) (advance! 2) true))
|
||||
((at? "*=")
|
||||
(do (js-emit! "op" "*=" start) (advance! 2) true))
|
||||
((at? "/=")
|
||||
(do (js-emit! "op" "/=" start) (advance! 2) true))
|
||||
((at? "%=")
|
||||
(do (js-emit! "op" "%=" start) (advance! 2) true))
|
||||
((at? "&=")
|
||||
(do (js-emit! "op" "&=" start) (advance! 2) true))
|
||||
((at? "|=")
|
||||
(do (js-emit! "op" "|=" start) (advance! 2) true))
|
||||
((at? "^=")
|
||||
(do (js-emit! "op" "^=" start) (advance! 2) true))
|
||||
((at? "?.")
|
||||
(do (js-emit! "op" "?." start) (advance! 2) true))
|
||||
((at? "==") (do (js-emit! "op" "==" start) (advance! 2) true))
|
||||
((at? "!=") (do (js-emit! "op" "!=" start) (advance! 2) true))
|
||||
((at? "<=") (do (js-emit! "op" "<=" start) (advance! 2) true))
|
||||
((at? ">=") (do (js-emit! "op" ">=" start) (advance! 2) true))
|
||||
((at? "&&") (do (js-emit! "op" "&&" start) (advance! 2) true))
|
||||
((at? "||") (do (js-emit! "op" "||" start) (advance! 2) true))
|
||||
((at? "??") (do (js-emit! "op" "??" start) (advance! 2) true))
|
||||
((at? "=>") (do (js-emit! "op" "=>" start) (advance! 2) true))
|
||||
((at? "**") (do (js-emit! "op" "**" start) (advance! 2) true))
|
||||
((at? "<<") (do (js-emit! "op" "<<" start) (advance! 2) true))
|
||||
((at? ">>") (do (js-emit! "op" ">>" start) (advance! 2) true))
|
||||
((at? "++") (do (js-emit! "op" "++" start) (advance! 2) true))
|
||||
((at? "--") (do (js-emit! "op" "--" start) (advance! 2) true))
|
||||
((at? "+=") (do (js-emit! "op" "+=" start) (advance! 2) true))
|
||||
((at? "-=") (do (js-emit! "op" "-=" start) (advance! 2) true))
|
||||
((at? "*=") (do (js-emit! "op" "*=" start) (advance! 2) true))
|
||||
((at? "/=") (do (js-emit! "op" "/=" start) (advance! 2) true))
|
||||
((at? "%=") (do (js-emit! "op" "%=" start) (advance! 2) true))
|
||||
((at? "&=") (do (js-emit! "op" "&=" start) (advance! 2) true))
|
||||
((at? "|=") (do (js-emit! "op" "|=" start) (advance! 2) true))
|
||||
((at? "^=") (do (js-emit! "op" "^=" start) (advance! 2) true))
|
||||
((at? "?.") (do (js-emit! "op" "?." start) (advance! 2) true))
|
||||
(else false))))
|
||||
(define
|
||||
emit-one-op!
|
||||
(fn
|
||||
(ch start)
|
||||
(cond
|
||||
((= ch "(")
|
||||
(do (js-emit! "punct" "(" start) (advance! 1)))
|
||||
((= ch ")")
|
||||
(do (js-emit! "punct" ")" start) (advance! 1)))
|
||||
((= ch "[")
|
||||
(do (js-emit! "punct" "[" start) (advance! 1)))
|
||||
((= ch "]")
|
||||
(do (js-emit! "punct" "]" start) (advance! 1)))
|
||||
((= ch "{")
|
||||
(do (js-emit! "punct" "{" start) (advance! 1)))
|
||||
((= ch "}")
|
||||
(do (js-emit! "punct" "}" start) (advance! 1)))
|
||||
((= ch ",")
|
||||
(do (js-emit! "punct" "," start) (advance! 1)))
|
||||
((= ch ";")
|
||||
(do (js-emit! "punct" ";" start) (advance! 1)))
|
||||
((= ch ":")
|
||||
(do (js-emit! "punct" ":" start) (advance! 1)))
|
||||
((= ch ".")
|
||||
(do (js-emit! "punct" "." start) (advance! 1)))
|
||||
((= ch "?")
|
||||
(do (js-emit! "op" "?" start) (advance! 1)))
|
||||
((= ch "+")
|
||||
(do (js-emit! "op" "+" start) (advance! 1)))
|
||||
((= ch "-")
|
||||
(do (js-emit! "op" "-" start) (advance! 1)))
|
||||
((= ch "*")
|
||||
(do (js-emit! "op" "*" start) (advance! 1)))
|
||||
((= ch "/")
|
||||
(do (js-emit! "op" "/" start) (advance! 1)))
|
||||
((= ch "%")
|
||||
(do (js-emit! "op" "%" start) (advance! 1)))
|
||||
((= ch "=")
|
||||
(do (js-emit! "op" "=" start) (advance! 1)))
|
||||
((= ch "<")
|
||||
(do (js-emit! "op" "<" start) (advance! 1)))
|
||||
((= ch ">")
|
||||
(do (js-emit! "op" ">" start) (advance! 1)))
|
||||
((= ch "!")
|
||||
(do (js-emit! "op" "!" start) (advance! 1)))
|
||||
((= ch "&")
|
||||
(do (js-emit! "op" "&" start) (advance! 1)))
|
||||
((= ch "|")
|
||||
(do (js-emit! "op" "|" start) (advance! 1)))
|
||||
((= ch "^")
|
||||
(do (js-emit! "op" "^" start) (advance! 1)))
|
||||
((= ch "~")
|
||||
(do (js-emit! "op" "~" start) (advance! 1)))
|
||||
((= ch "\\")
|
||||
(error "Unexpected char '\\' in source"))
|
||||
((= ch "(") (do (js-emit! "punct" "(" start) (advance! 1)))
|
||||
((= ch ")") (do (js-emit! "punct" ")" start) (advance! 1)))
|
||||
((= ch "[") (do (js-emit! "punct" "[" start) (advance! 1)))
|
||||
((= ch "]") (do (js-emit! "punct" "]" start) (advance! 1)))
|
||||
((= ch "{") (do (js-emit! "punct" "{" start) (advance! 1)))
|
||||
((= ch "}") (do (js-emit! "punct" "}" start) (advance! 1)))
|
||||
((= ch ",") (do (js-emit! "punct" "," start) (advance! 1)))
|
||||
((= ch ";") (do (js-emit! "punct" ";" start) (advance! 1)))
|
||||
((= ch ":") (do (js-emit! "punct" ":" start) (advance! 1)))
|
||||
((= ch ".") (do (js-emit! "punct" "." start) (advance! 1)))
|
||||
((= ch "?") (do (js-emit! "op" "?" start) (advance! 1)))
|
||||
((= ch "+") (do (js-emit! "op" "+" start) (advance! 1)))
|
||||
((= ch "-") (do (js-emit! "op" "-" start) (advance! 1)))
|
||||
((= ch "*") (do (js-emit! "op" "*" start) (advance! 1)))
|
||||
((= ch "/") (do (js-emit! "op" "/" start) (advance! 1)))
|
||||
((= ch "%") (do (js-emit! "op" "%" start) (advance! 1)))
|
||||
((= ch "=") (do (js-emit! "op" "=" start) (advance! 1)))
|
||||
((= ch "<") (do (js-emit! "op" "<" start) (advance! 1)))
|
||||
((= ch ">") (do (js-emit! "op" ">" start) (advance! 1)))
|
||||
((= ch "!") (do (js-emit! "op" "!" start) (advance! 1)))
|
||||
((= ch "&") (do (js-emit! "op" "&" start) (advance! 1)))
|
||||
((= ch "|") (do (js-emit! "op" "|" start) (advance! 1)))
|
||||
((= ch "^") (do (js-emit! "op" "^" start) (advance! 1)))
|
||||
((= ch "~") (do (js-emit! "op" "~" start) (advance! 1)))
|
||||
(else (advance! 1)))))
|
||||
(define
|
||||
scan!
|
||||
(fn
|
||||
()
|
||||
(do
|
||||
(set! nl-before false)
|
||||
(skip-ws!)
|
||||
(when
|
||||
(< pos src-len)
|
||||
|
||||
249
lib/js/parser.sx
249
lib/js/parser.sx
@@ -153,32 +153,6 @@
|
||||
(do (jp-advance! st) (list (quote js-ident) "this")))
|
||||
((and (= (get t :type) "keyword") (= (get t :value) "new"))
|
||||
(do (jp-advance! st) (jp-parse-new-expr st)))
|
||||
((and (= (get t :type) "keyword") (= (get t :value) "function"))
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(let
|
||||
((nm
|
||||
(if
|
||||
(= (get (jp-peek st) :type) "ident")
|
||||
(let ((n (get (jp-peek st) :value))) (do (jp-advance! st) n))
|
||||
nil)))
|
||||
(let
|
||||
((params (jp-parse-param-list st)))
|
||||
(let
|
||||
((body (jp-parse-fn-body st)))
|
||||
(list (quote js-funcexpr) nm params body))))))
|
||||
((and (= (get t :type) "keyword") (= (get t :value) "true"))
|
||||
(do (jp-advance! st) (list (quote js-bool) true)))
|
||||
((and (= (get t :type) "keyword") (= (get t :value) "false"))
|
||||
(do (jp-advance! st) (list (quote js-bool) false)))
|
||||
((and (= (get t :type) "keyword") (= (get t :value) "null"))
|
||||
(do (jp-advance! st) (list (quote js-null))))
|
||||
((and (= (get t :type) "keyword") (= (get t :value) "undefined"))
|
||||
(do (jp-advance! st) (list (quote js-undef))))
|
||||
((= (get t :type) "number")
|
||||
(do (jp-advance! st) (list (quote js-num) (get t :value))))
|
||||
((= (get t :type) "string")
|
||||
(do (jp-advance! st) (list (quote js-str) (get t :value))))
|
||||
((and (= (get t :type) "punct") (= (get t :value) "("))
|
||||
(jp-parse-paren-or-arrow st))
|
||||
(else
|
||||
@@ -237,7 +211,7 @@
|
||||
(let
|
||||
((params (jp-parse-param-list st)))
|
||||
(let
|
||||
((body (jp-parse-fn-body st)))
|
||||
((body (jp-parse-block st)))
|
||||
(list (quote js-funcexpr-async) nm params body))))))
|
||||
((= (get t :type) "ident")
|
||||
(do
|
||||
@@ -389,7 +363,7 @@
|
||||
(let
|
||||
((params (jp-parse-param-list st)))
|
||||
(let
|
||||
((body (jp-parse-fn-body st)))
|
||||
((body (jp-parse-block st)))
|
||||
(list (quote js-funcexpr) nm params body))))))
|
||||
((= (get t :type) "ident")
|
||||
(do
|
||||
@@ -444,51 +418,16 @@
|
||||
(dict-set! st :idx saved)
|
||||
(jp-advance! st)
|
||||
(let
|
||||
((e (jp-parse-comma-seq st)))
|
||||
((e (jp-parse-assignment st)))
|
||||
(jp-expect! st "punct" ")")
|
||||
(jp-paren-wrap e))))
|
||||
e)))
|
||||
(do
|
||||
(dict-set! st :idx saved)
|
||||
(jp-advance! st)
|
||||
(let
|
||||
((e (jp-parse-comma-seq st)))
|
||||
((e (jp-parse-assignment st)))
|
||||
(jp-expect! st "punct" ")")
|
||||
(jp-paren-wrap e))))))))
|
||||
|
||||
(define
|
||||
jp-paren-wrap
|
||||
(fn
|
||||
(e)
|
||||
(cond
|
||||
((and (list? e) (= (first e) (quote js-unop)))
|
||||
(list (quote js-paren) e))
|
||||
(else e))))
|
||||
|
||||
(define
|
||||
jp-parse-comma-seq
|
||||
(fn
|
||||
(st)
|
||||
(let
|
||||
((first-expr (jp-parse-assignment st)))
|
||||
(if
|
||||
(jp-at? st "punct" ",")
|
||||
(jp-parse-comma-seq-rest st (list first-expr))
|
||||
first-expr))))
|
||||
|
||||
(define
|
||||
jp-parse-comma-seq-rest
|
||||
(fn
|
||||
(st acc)
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(let
|
||||
((next-expr (jp-parse-assignment st)))
|
||||
(let
|
||||
((acc2 (append acc (list next-expr))))
|
||||
(if
|
||||
(jp-at? st "punct" ",")
|
||||
(jp-parse-comma-seq-rest st acc2)
|
||||
(cons (quote js-comma) (list acc2))))))))
|
||||
e)))))))
|
||||
|
||||
(define
|
||||
jp-collect-params
|
||||
@@ -546,11 +485,6 @@
|
||||
(st elems)
|
||||
(cond
|
||||
((jp-at? st "punct" "]") nil)
|
||||
((jp-at? st "punct" ",")
|
||||
(begin
|
||||
(append! elems (list (quote js-undef)))
|
||||
(jp-advance! st)
|
||||
(jp-array-loop st elems)))
|
||||
(else
|
||||
(begin
|
||||
(cond
|
||||
@@ -624,20 +558,6 @@
|
||||
(jp-advance! st)
|
||||
(jp-expect! st "punct" ":")
|
||||
(append! kvs {:value (jp-parse-assignment st) :key (get t :value)})))
|
||||
((and (= (get t :type) "punct") (= (get t :value) "["))
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(let
|
||||
((key-expr (jp-parse-assignment st)))
|
||||
(jp-expect! st "punct" "]")
|
||||
(jp-expect! st "punct" ":")
|
||||
(append!
|
||||
kvs
|
||||
{:value (jp-parse-assignment st) :computed-key key-expr :key ""}))))
|
||||
((and (= (get t :type) "punct") (= (get t :value) "..."))
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(append! kvs {:spread (jp-parse-assignment st)})))
|
||||
(else (error (str "Unexpected in object: " (get t :type))))))))
|
||||
|
||||
(define
|
||||
@@ -709,7 +629,7 @@
|
||||
st
|
||||
(list (quote js-optchain-member) left (get t :value))))
|
||||
(error "expected ident, [ or ( after ?.")))))))
|
||||
((and (or (jp-at? st "op" "++") (jp-at? st "op" "--")) (not (jp-token-nl? st)))
|
||||
((or (jp-at? st "op" "++") (jp-at? st "op" "--"))
|
||||
(let
|
||||
((op (get (jp-peek st) :value)))
|
||||
(jp-advance! st)
|
||||
@@ -762,12 +682,6 @@
|
||||
(cond
|
||||
((< prec 0) left)
|
||||
((< prec min-prec) left)
|
||||
((and (= op "**") (list? left) (= (first left) (quote js-unop)))
|
||||
(error
|
||||
(str
|
||||
"SyntaxError: Unary operator '"
|
||||
(nth left 1)
|
||||
"' used immediately before exponentiation expression")))
|
||||
(else
|
||||
(do
|
||||
(jp-advance! st)
|
||||
@@ -921,12 +835,6 @@
|
||||
jp-eat-semi
|
||||
(fn (st) (if (jp-at? st "punct" ";") (do (jp-advance! st) nil) nil)))
|
||||
|
||||
(define
|
||||
jp-token-nl?
|
||||
(fn
|
||||
(st)
|
||||
(let ((tok (jp-peek st))) (if tok (= (get tok :nl) true) false))))
|
||||
|
||||
(define
|
||||
jp-parse-vardecl
|
||||
(fn
|
||||
@@ -1144,63 +1052,15 @@
|
||||
((c (jp-parse-assignment st)))
|
||||
(do
|
||||
(jp-expect! st "punct" ")")
|
||||
(jp-disallow-decl-stmt! st "if")
|
||||
(let
|
||||
((t (jp-parse-stmt st)))
|
||||
(if
|
||||
(jp-at? st "keyword" "else")
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(jp-disallow-decl-stmt! st "else")
|
||||
(list (quote js-if) c t (jp-parse-stmt st)))
|
||||
(list (quote js-if) c t nil))))))))
|
||||
|
||||
(define
|
||||
jp-disallow-decl-stmt!
|
||||
(fn
|
||||
(st context)
|
||||
(let
|
||||
((t (jp-peek st)))
|
||||
(cond
|
||||
((and (= (get t :type) "keyword")
|
||||
(or (= (get t :value) "let")
|
||||
(= (get t :value) "const")
|
||||
(= (get t :value) "function")
|
||||
(= (get t :value) "class")))
|
||||
(cond
|
||||
((and (= (get t :value) "let")
|
||||
(or (= (get (jp-peek-at st 1) :type) "ident")
|
||||
(and (= (get (jp-peek-at st 1) :type) "punct")
|
||||
(or (= (get (jp-peek-at st 1) :value) "[")
|
||||
(= (get (jp-peek-at st 1) :value) "{")))))
|
||||
(error
|
||||
(str
|
||||
"SyntaxError: Lexical declaration cannot appear in single-statement context: "
|
||||
context)))
|
||||
((or (= (get t :value) "const")
|
||||
(= (get t :value) "function")
|
||||
(= (get t :value) "class"))
|
||||
(error
|
||||
(str
|
||||
"SyntaxError: "
|
||||
(get t :value)
|
||||
" declaration cannot appear in single-statement context: "
|
||||
context)))
|
||||
(else nil)))
|
||||
(else nil)))))
|
||||
|
||||
(define
|
||||
jp-bump!
|
||||
(fn
|
||||
(st key)
|
||||
(dict-set! st key (+ (get st key) 1))))
|
||||
|
||||
(define
|
||||
jp-decr!
|
||||
(fn
|
||||
(st key)
|
||||
(dict-set! st key (- (get st key) 1))))
|
||||
|
||||
(define
|
||||
jp-parse-while-stmt
|
||||
(fn
|
||||
@@ -1212,11 +1072,7 @@
|
||||
((c (jp-parse-assignment st)))
|
||||
(do
|
||||
(jp-expect! st "punct" ")")
|
||||
(jp-disallow-decl-stmt! st "while")
|
||||
(jp-bump! st :loop-depth)
|
||||
(let ((body (jp-parse-stmt st)))
|
||||
(jp-decr! st :loop-depth)
|
||||
(list (quote js-while) c body)))))))
|
||||
(let ((body (jp-parse-stmt st))) (list (quote js-while) c body)))))))
|
||||
|
||||
(define
|
||||
jp-parse-do-while-stmt
|
||||
@@ -1224,11 +1080,8 @@
|
||||
(st)
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(jp-disallow-decl-stmt! st "do")
|
||||
(jp-bump! st :loop-depth)
|
||||
(let
|
||||
((body (jp-parse-stmt st)))
|
||||
(jp-decr! st :loop-depth)
|
||||
(do
|
||||
(if
|
||||
(jp-at? st "keyword" "while")
|
||||
@@ -1273,11 +1126,8 @@
|
||||
(let
|
||||
((iter (jp-parse-assignment st)))
|
||||
(jp-expect! st "punct" ")")
|
||||
(jp-disallow-decl-stmt! st "for-of/in")
|
||||
(jp-bump! st :loop-depth)
|
||||
(let
|
||||
((body (jp-parse-stmt st)))
|
||||
(jp-decr! st :loop-depth)
|
||||
(list (quote js-for-of-in) iter-kind ident iter body)))))))
|
||||
(else
|
||||
(let
|
||||
@@ -1288,11 +1138,8 @@
|
||||
(let
|
||||
((step (if (jp-at? st "punct" ")") nil (jp-parse-assignment st))))
|
||||
(jp-expect! st "punct" ")")
|
||||
(jp-disallow-decl-stmt! st "for")
|
||||
(jp-bump! st :loop-depth)
|
||||
(let
|
||||
((body (jp-parse-stmt st)))
|
||||
(jp-decr! st :loop-depth)
|
||||
(list (quote js-for) init cond-ast step body)))))))))))
|
||||
|
||||
(define
|
||||
@@ -1315,14 +1162,10 @@
|
||||
(st)
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(when
|
||||
(= (get st :fn-depth) 0)
|
||||
(error "SyntaxError: Illegal return statement"))
|
||||
(if
|
||||
(or
|
||||
(jp-at? st "punct" ";")
|
||||
(jp-at? st "punct" "}")
|
||||
(jp-token-nl? st)
|
||||
(jp-at? st "eof" nil))
|
||||
(do (jp-eat-semi st) (list (quote js-return) nil))
|
||||
(let
|
||||
@@ -1345,7 +1188,7 @@
|
||||
(let
|
||||
((params (jp-parse-param-list st)))
|
||||
(let
|
||||
((body (jp-parse-fn-body st)))
|
||||
((body (jp-parse-block st)))
|
||||
(list (quote js-funcdecl) nm params body))))))))
|
||||
|
||||
(define
|
||||
@@ -1364,7 +1207,7 @@
|
||||
(let
|
||||
((params (jp-parse-param-list st)))
|
||||
(let
|
||||
((body (jp-parse-fn-body st)))
|
||||
((body (jp-parse-block st)))
|
||||
(list (quote js-funcdecl-async) nm params body))))))))
|
||||
|
||||
(define
|
||||
@@ -1413,7 +1256,7 @@
|
||||
(let
|
||||
((params (jp-parse-param-list st)))
|
||||
(let
|
||||
((body (jp-parse-fn-body st)))
|
||||
((body (jp-parse-block st)))
|
||||
(list
|
||||
(quote js-method)
|
||||
(if static? "static" "instance")
|
||||
@@ -1441,11 +1284,9 @@
|
||||
((disc (jp-parse-assignment st)))
|
||||
(jp-expect! st "punct" ")")
|
||||
(jp-expect! st "punct" "{")
|
||||
(jp-bump! st :switch-depth)
|
||||
(let
|
||||
((cases (list)))
|
||||
(jp-parse-switch-cases st cases)
|
||||
(jp-decr! st :switch-depth)
|
||||
(jp-expect! st "punct" "}")
|
||||
(list (quote js-switch) disc cases)))))
|
||||
|
||||
@@ -1521,40 +1362,9 @@
|
||||
((jp-at? st "keyword" "for") (jp-parse-for-stmt st))
|
||||
((jp-at? st "keyword" "return") (jp-parse-return-stmt st))
|
||||
((jp-at? st "keyword" "break")
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(cond
|
||||
((= (get (jp-peek st) :type) "ident")
|
||||
(do (jp-advance! st) (jp-eat-semi st) (list (quote js-break))))
|
||||
(else
|
||||
(do
|
||||
(when
|
||||
(and (= (get st :loop-depth) 0) (= (get st :switch-depth) 0))
|
||||
(error "SyntaxError: Illegal break statement"))
|
||||
(jp-eat-semi st)
|
||||
(list (quote js-break)))))))
|
||||
((jp-at? st "keyword" "continue")
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(cond
|
||||
((= (get (jp-peek st) :type) "ident")
|
||||
(do (jp-advance! st) (jp-eat-semi st) (list (quote js-continue))))
|
||||
(else
|
||||
(do
|
||||
(when
|
||||
(= (get st :loop-depth) 0)
|
||||
(error "SyntaxError: Illegal continue statement"))
|
||||
(jp-eat-semi st)
|
||||
(list (quote js-continue)))))))
|
||||
((and
|
||||
(= (get (jp-peek st) :type) "ident")
|
||||
(= (get (jp-peek-at st 1) :type) "punct")
|
||||
(= (get (jp-peek-at st 1) :value) ":"))
|
||||
(do
|
||||
(jp-advance! st)
|
||||
(jp-advance! st)
|
||||
(jp-disallow-decl-stmt! st "label")
|
||||
(jp-parse-stmt st)))
|
||||
((jp-at? st "keyword" "class") (jp-parse-class-decl st))
|
||||
((jp-at? st "keyword" "throw") (jp-parse-throw-stmt st))
|
||||
((jp-at? st "keyword" "try") (jp-parse-try-stmt st))
|
||||
@@ -1564,7 +1374,7 @@
|
||||
((jp-at? st "keyword" "switch") (jp-parse-switch-stmt st))
|
||||
(else
|
||||
(let
|
||||
((e (jp-parse-comma-seq st)))
|
||||
((e (jp-parse-assignment st)))
|
||||
(do (jp-eat-semi st) (list (quote js-exprstmt) e)))))))
|
||||
|
||||
(define
|
||||
@@ -1590,33 +1400,10 @@
|
||||
jp-parse-arrow-body
|
||||
(fn
|
||||
(st)
|
||||
(jp-bump! st :fn-depth)
|
||||
(let
|
||||
((saved-loop (get st :loop-depth)) (saved-switch (get st :switch-depth)))
|
||||
(dict-set! st :loop-depth 0)
|
||||
(dict-set! st :switch-depth 0)
|
||||
(let
|
||||
((body (if (jp-at? st "punct" "{") (jp-parse-block st) (jp-parse-assignment st))))
|
||||
(jp-decr! st :fn-depth)
|
||||
(dict-set! st :loop-depth saved-loop)
|
||||
(dict-set! st :switch-depth saved-switch)
|
||||
body))))
|
||||
|
||||
(define
|
||||
jp-parse-fn-body
|
||||
(fn
|
||||
(st)
|
||||
(jp-bump! st :fn-depth)
|
||||
(let
|
||||
((saved-loop (get st :loop-depth)) (saved-switch (get st :switch-depth)))
|
||||
(dict-set! st :loop-depth 0)
|
||||
(dict-set! st :switch-depth 0)
|
||||
(let
|
||||
((body (jp-parse-block st)))
|
||||
(jp-decr! st :fn-depth)
|
||||
(dict-set! st :loop-depth saved-loop)
|
||||
(dict-set! st :switch-depth saved-switch)
|
||||
body))))
|
||||
(if
|
||||
(jp-at? st "punct" "{")
|
||||
(jp-parse-block st)
|
||||
(jp-parse-assignment st))))
|
||||
|
||||
(define
|
||||
js-parse
|
||||
@@ -1627,7 +1414,7 @@
|
||||
(= (len tokens) 0)
|
||||
(and (= (len tokens) 1) (= (get (nth tokens 0) :type) "eof")))
|
||||
(list (quote js-program) (list))
|
||||
(let ((st {:idx 0 :tokens tokens :arrow-candidate true :loop-depth 0 :switch-depth 0 :fn-depth 0})) (jp-parse-program st)))))
|
||||
(let ((st {:idx 0 :tokens tokens :arrow-candidate true})) (jp-parse-program st)))))
|
||||
|
||||
(define
|
||||
js-parse-expr
|
||||
@@ -1640,4 +1427,4 @@
|
||||
(= (len tokens) 0)
|
||||
(and (= (len tokens) 1) (= (get (nth tokens 0) :type) "eof")))
|
||||
(list)
|
||||
(let ((st {:idx 0 :tokens tokens :arrow-candidate true :loop-depth 0 :switch-depth 0 :fn-depth 0})) (jp-parse-assignment st))))))
|
||||
(let ((st {:idx 0 :tokens tokens :arrow-candidate true})) (jp-parse-assignment st))))))
|
||||
|
||||
3833
lib/js/runtime.sx
3833
lib/js/runtime.sx
File diff suppressed because it is too large
Load Diff
@@ -1323,25 +1323,6 @@ 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 1.ASI: automatic semicolon insertion ─────────────────
|
||||
(epoch 4200)
|
||||
(eval "(js-eval \"function f() { return\n42\n} f()\")")
|
||||
(epoch 4201)
|
||||
(eval "(js-eval \"function g() { return 42 } g()\")")
|
||||
(epoch 4202)
|
||||
(eval "(let ((toks (js-tokenize \"a\nb\"))) (get (nth toks 1) :nl))")
|
||||
(epoch 4203)
|
||||
(eval "(let ((toks (js-tokenize \"a b\"))) (get (nth toks 1) :nl))")
|
||||
|
||||
(epoch 4300)
|
||||
(eval "(js-eval \"var x = 5; x\")")
|
||||
(epoch 4301)
|
||||
(eval "(js-eval \"function f() { return x; var x = 42; } f()\")")
|
||||
(epoch 4302)
|
||||
(eval "(js-eval \"function f() { var y = 7; return y; } f()\")")
|
||||
(epoch 4303)
|
||||
(eval "(js-eval \"function f() { var z; z = 3; return z; } f()\")")
|
||||
|
||||
EPOCHS
|
||||
|
||||
|
||||
@@ -2061,17 +2042,6 @@ check 3503 "indexOf.call arrLike" '1'
|
||||
check 3504 "filter.call arrLike" '"2,3"'
|
||||
check 3505 "forEach.call arrLike sum" '60'
|
||||
|
||||
# ── Phase 1.ASI: automatic semicolon insertion ────────────────────
|
||||
check 4200 "return+newline → undefined" '"js-undefined"'
|
||||
check 4201 "return+space+val → val" '42'
|
||||
check 4202 "nl-before flag set after newline" 'true'
|
||||
check 4203 "nl-before flag false on same line" 'false'
|
||||
|
||||
check 4300 "var decl program-level" '5'
|
||||
check 4301 "var hoisted before use → undef" '"js-undefined"'
|
||||
check 4302 "var in function body" '7'
|
||||
check 4303 "var then set in function" '3'
|
||||
|
||||
TOTAL=$((PASS + FAIL))
|
||||
if [ $FAIL -eq 0 ]; then
|
||||
echo "✓ $PASS/$TOTAL JS-on-SX tests passed"
|
||||
|
||||
@@ -52,7 +52,7 @@ UPSTREAM = REPO / "lib" / "js" / "test262-upstream"
|
||||
TEST_ROOT = UPSTREAM / "test"
|
||||
HARNESS_DIR = UPSTREAM / "harness"
|
||||
|
||||
DEFAULT_PER_TEST_TIMEOUT_S = 15.0
|
||||
DEFAULT_PER_TEST_TIMEOUT_S = 5.0
|
||||
DEFAULT_BATCH_TIMEOUT_S = 120
|
||||
|
||||
# Cache dir for precomputed SX source of harness JS (one file per Python run).
|
||||
@@ -134,9 +134,6 @@ var verifyProperty = function (obj, name, desc, opts) {
|
||||
}
|
||||
};
|
||||
var verifyPrimordialProperty = verifyProperty;
|
||||
var verifyEqualTo = function (obj, name, value) {
|
||||
assert.sameValue(obj[name], value, name + " equals");
|
||||
};
|
||||
var verifyNotEnumerable = function (o, n, v, w, x) { };
|
||||
var verifyNotWritable = function (o, n, v, w, x) { };
|
||||
var verifyNotConfigurable = function (o, n, v, w, x) { };
|
||||
@@ -149,50 +146,6 @@ var isConstructor = function (f) {
|
||||
// Best-effort: built-in functions and arrows aren't; declared `function` decls are.
|
||||
return false;
|
||||
};
|
||||
// $DONE / asyncTest — async-flag tests call $DONE(err) to signal completion.
|
||||
// Since we drain microtasks synchronously, $DONE is just a final-assertion sink.
|
||||
var $DONE = function (err) {
|
||||
if (err) { throw new Test262Error((err && err.message) || err); }
|
||||
};
|
||||
var asyncTest = function (testFunc) {
|
||||
Promise.resolve(testFunc()).then(function () { $DONE(); }, function (e) { $DONE(e); });
|
||||
};
|
||||
// promiseHelper.js include — used by Promise.all/race tests for ordering checks.
|
||||
var checkSequence = function (arr, message) {
|
||||
for (var i = 0; i < arr.length; i = i + 1) {
|
||||
if (arr[i] !== (i + 1)) {
|
||||
throw new Test262Error((message || "Sequence") + " expected " + (i+1) + " at index " + i + " but got " + arr[i]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
var checkSettledPromises = function (settleds, expected, message) {
|
||||
var msg = message ? message + " " : "";
|
||||
if (settleds.length !== expected.length) {
|
||||
throw new Test262Error(msg + "lengths differ: " + settleds.length + " vs " + expected.length);
|
||||
}
|
||||
for (var i = 0; i < settleds.length; i = i + 1) {
|
||||
if (settleds[i].status !== expected[i].status) {
|
||||
throw new Test262Error(msg + "status[" + i + "]: " + settleds[i].status + " vs " + expected[i].status);
|
||||
}
|
||||
if (expected[i].status === "fulfilled" && settleds[i].value !== expected[i].value) {
|
||||
throw new Test262Error(msg + "value[" + i + "]: " + settleds[i].value + " vs " + expected[i].value);
|
||||
}
|
||||
if (expected[i].status === "rejected" && settleds[i].reason !== expected[i].reason) {
|
||||
throw new Test262Error(msg + "reason[" + i + "]: " + settleds[i].reason + " vs " + expected[i].reason);
|
||||
}
|
||||
}
|
||||
};
|
||||
// decimalToHexString.js include — used by URI/escape tests.
|
||||
var decimalToHexString = function (n) {
|
||||
var hex = "0123456789ABCDEF";
|
||||
if (n < 0) { n = n + 65536; }
|
||||
return hex[(n >> 12) & 15] + hex[(n >> 8) & 15] + hex[(n >> 4) & 15] + hex[n & 15];
|
||||
};
|
||||
var decimalToPercentHexString = function (n) {
|
||||
var hex = "0123456789ABCDEF";
|
||||
return "%" + hex[(n >> 4) & 15] + hex[n & 15];
|
||||
};
|
||||
// Trivial helper for tests that use Array.isArray-like functionality
|
||||
// (many tests reach for it via compareArray)
|
||||
"""
|
||||
@@ -405,8 +358,6 @@ def classify_negative_result(fm: Frontmatter, kind: str, payload: str):
|
||||
or ("expected" in low and "got" in low)
|
||||
or "js-transpile-unop" in low
|
||||
or "js-transpile-binop" in low
|
||||
or "js-transpile-assign" in low
|
||||
or "js-transpile" in low
|
||||
or "js-compound-update" in low
|
||||
or "parse" in low
|
||||
):
|
||||
@@ -1060,45 +1011,11 @@ def _worker_run(args):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_HARNESS_INCLUDE_CACHE: dict = {}
|
||||
|
||||
# Only inline these small harness files per-test. Large ones like propertyHelper.js
|
||||
# multiply js-eval/JIT cost by ~5-10x and push tests over the per-test timeout.
|
||||
_INLINE_INCLUDES = {"nans.js", "sta.js", "byteConversionValues.js", "compareArray.js"}
|
||||
|
||||
|
||||
def _load_harness_include(name: str) -> str:
|
||||
"""Read an upstream harness include file (e.g. nans.js).
|
||||
Returns empty string if the file isn't present.
|
||||
"""
|
||||
if name in _HARNESS_INCLUDE_CACHE:
|
||||
return _HARNESS_INCLUDE_CACHE[name]
|
||||
path = HARNESS_DIR / name
|
||||
try:
|
||||
src = path.read_text()
|
||||
except OSError:
|
||||
src = ""
|
||||
_HARNESS_INCLUDE_CACHE[name] = src
|
||||
return src
|
||||
|
||||
|
||||
def assemble_source(t):
|
||||
"""Return JS source to feed to js-eval. Harness is preloaded, so we only
|
||||
append the test source (plus a small allowlist of per-test includes).
|
||||
append the test source (plus negative-test prep if needed).
|
||||
"""
|
||||
if not getattr(t.fm, "includes", None):
|
||||
return t.src
|
||||
parts = []
|
||||
for inc in t.fm.includes:
|
||||
if inc not in _INLINE_INCLUDES:
|
||||
continue
|
||||
chunk = _load_harness_include(inc)
|
||||
if chunk:
|
||||
parts.append(chunk)
|
||||
if not parts:
|
||||
return t.src
|
||||
parts.append(t.src)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def aggregate(results):
|
||||
@@ -1276,7 +1193,7 @@ def main(argv):
|
||||
shards = [[] for _ in range(n_workers)]
|
||||
for i, t in enumerate(tests):
|
||||
shards[i % n_workers].append(
|
||||
(t.rel, t.category, assemble_source(t), t.fm.negative_phase, t.fm.negative_type)
|
||||
(t.rel, t.category, t.src, t.fm.negative_phase, t.fm.negative_type)
|
||||
)
|
||||
|
||||
t_run_start = time.monotonic()
|
||||
|
||||
@@ -1,53 +1,137 @@
|
||||
{
|
||||
"totals": {
|
||||
"pass": 4,
|
||||
"fail": 10,
|
||||
"skip": 16,
|
||||
"timeout": 0,
|
||||
"total": 30,
|
||||
"runnable": 14,
|
||||
"pass_rate": 28.6
|
||||
"pass": 162,
|
||||
"fail": 128,
|
||||
"skip": 1597,
|
||||
"timeout": 10,
|
||||
"total": 1897,
|
||||
"runnable": 300,
|
||||
"pass_rate": 54.0
|
||||
},
|
||||
"categories": [
|
||||
{
|
||||
"category": "built-ins/Function",
|
||||
"total": 30,
|
||||
"pass": 4,
|
||||
"fail": 10,
|
||||
"skip": 16,
|
||||
"timeout": 0,
|
||||
"pass_rate": 28.6,
|
||||
"category": "built-ins/Math",
|
||||
"total": 327,
|
||||
"pass": 43,
|
||||
"fail": 56,
|
||||
"skip": 227,
|
||||
"timeout": 1,
|
||||
"pass_rate": 43.0,
|
||||
"top_failures": [
|
||||
[
|
||||
"SyntaxError (parse/unsupported syntax)",
|
||||
"TypeError: not a function",
|
||||
36
|
||||
],
|
||||
[
|
||||
"Test262Error (assertion failed)",
|
||||
20
|
||||
],
|
||||
[
|
||||
"Timeout",
|
||||
1
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"category": "built-ins/Number",
|
||||
"total": 340,
|
||||
"pass": 77,
|
||||
"fail": 19,
|
||||
"skip": 240,
|
||||
"timeout": 4,
|
||||
"pass_rate": 77.0,
|
||||
"top_failures": [
|
||||
[
|
||||
"Test262Error (assertion failed)",
|
||||
19
|
||||
],
|
||||
[
|
||||
"Timeout",
|
||||
4
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"category": "built-ins/String",
|
||||
"total": 1223,
|
||||
"pass": 42,
|
||||
"fail": 53,
|
||||
"skip": 1123,
|
||||
"timeout": 5,
|
||||
"pass_rate": 42.0,
|
||||
"top_failures": [
|
||||
[
|
||||
"Test262Error (assertion failed)",
|
||||
44
|
||||
],
|
||||
[
|
||||
"Timeout",
|
||||
5
|
||||
],
|
||||
[
|
||||
"ReferenceError (undefined symbol)",
|
||||
3
|
||||
2
|
||||
],
|
||||
[
|
||||
"TypeError (other)",
|
||||
3
|
||||
"Unhandled: Not callable: {:__proto__ {:toLowerCase <lambda(&rest, args)",
|
||||
2
|
||||
],
|
||||
[
|
||||
"Unhandled: Not callable: \\\\\\",
|
||||
2
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"category": "built-ins/StringIteratorPrototype",
|
||||
"total": 7,
|
||||
"pass": 0,
|
||||
"fail": 0,
|
||||
"skip": 7,
|
||||
"timeout": 0,
|
||||
"pass_rate": 0.0,
|
||||
"top_failures": []
|
||||
}
|
||||
],
|
||||
"top_failure_modes": [
|
||||
[
|
||||
"SyntaxError (parse/unsupported syntax)",
|
||||
4
|
||||
"Test262Error (assertion failed)",
|
||||
83
|
||||
],
|
||||
[
|
||||
"TypeError: not a function",
|
||||
36
|
||||
],
|
||||
[
|
||||
"Timeout",
|
||||
10
|
||||
],
|
||||
[
|
||||
"ReferenceError (undefined symbol)",
|
||||
3
|
||||
2
|
||||
],
|
||||
[
|
||||
"TypeError (other)",
|
||||
3
|
||||
"Unhandled: Not callable: {:__proto__ {:toLowerCase <lambda(&rest, args)",
|
||||
2
|
||||
],
|
||||
[
|
||||
"Unhandled: Not callable: \\\\\\",
|
||||
2
|
||||
],
|
||||
[
|
||||
"SyntaxError (parse/unsupported syntax)",
|
||||
1
|
||||
],
|
||||
[
|
||||
"Unhandled: Not callable: {:__proto__ {:valueOf <lambda()> :propertyIsEn",
|
||||
1
|
||||
],
|
||||
[
|
||||
"Unhandled: js-transpile-binop: unsupported op: >>>\\",
|
||||
1
|
||||
]
|
||||
],
|
||||
"pinned_commit": "d5e73fc8d2c663554fb72e2380a8c2bc1a318a33",
|
||||
"elapsed_seconds": 11.2,
|
||||
"elapsed_seconds": 274.5,
|
||||
"workers": 1
|
||||
}
|
||||
@@ -1,26 +1,47 @@
|
||||
# test262 scoreboard
|
||||
|
||||
Pinned commit: `d5e73fc8d2c663554fb72e2380a8c2bc1a318a33`
|
||||
Wall time: 11.2s
|
||||
Wall time: 274.5s
|
||||
|
||||
**Total:** 4/14 runnable passed (28.6%). Raw: pass=4 fail=10 skip=16 timeout=0 total=30.
|
||||
**Total:** 162/300 runnable passed (54.0%). Raw: pass=162 fail=128 skip=1597 timeout=10 total=1897.
|
||||
|
||||
## Top failure modes
|
||||
|
||||
- **4x** SyntaxError (parse/unsupported syntax)
|
||||
- **3x** ReferenceError (undefined symbol)
|
||||
- **3x** TypeError (other)
|
||||
- **83x** Test262Error (assertion failed)
|
||||
- **36x** TypeError: not a function
|
||||
- **10x** Timeout
|
||||
- **2x** ReferenceError (undefined symbol)
|
||||
- **2x** Unhandled: Not callable: {:__proto__ {:toLowerCase <lambda(&rest, args)
|
||||
- **2x** Unhandled: Not callable: \\\
|
||||
- **1x** SyntaxError (parse/unsupported syntax)
|
||||
- **1x** Unhandled: Not callable: {:__proto__ {:valueOf <lambda()> :propertyIsEn
|
||||
- **1x** Unhandled: js-transpile-binop: unsupported op: >>>\
|
||||
|
||||
## Categories (worst pass-rate first, min 10 runnable)
|
||||
|
||||
| Category | Pass | Fail | Skip | Timeout | Total | Pass % |
|
||||
|---|---:|---:|---:|---:|---:|---:|
|
||||
| built-ins/Function | 4 | 10 | 16 | 0 | 30 | 28.6% |
|
||||
| built-ins/String | 42 | 53 | 1123 | 5 | 1223 | 42.0% |
|
||||
| built-ins/Math | 43 | 56 | 227 | 1 | 327 | 43.0% |
|
||||
| built-ins/Number | 77 | 19 | 240 | 4 | 340 | 77.0% |
|
||||
|
||||
## Per-category top failures (min 10 runnable, worst first)
|
||||
|
||||
### built-ins/Function (4/14 — 28.6%)
|
||||
### built-ins/String (42/100 — 42.0%)
|
||||
|
||||
- **4x** SyntaxError (parse/unsupported syntax)
|
||||
- **3x** ReferenceError (undefined symbol)
|
||||
- **3x** TypeError (other)
|
||||
- **44x** Test262Error (assertion failed)
|
||||
- **5x** Timeout
|
||||
- **2x** ReferenceError (undefined symbol)
|
||||
- **2x** Unhandled: Not callable: {:__proto__ {:toLowerCase <lambda(&rest, args)
|
||||
- **2x** Unhandled: Not callable: \\\
|
||||
|
||||
### built-ins/Math (43/100 — 43.0%)
|
||||
|
||||
- **36x** TypeError: not a function
|
||||
- **20x** Test262Error (assertion failed)
|
||||
- **1x** Timeout
|
||||
|
||||
### built-ins/Number (77/100 — 77.0%)
|
||||
|
||||
- **19x** Test262Error (assertion failed)
|
||||
- **4x** Timeout
|
||||
|
||||
@@ -98,7 +98,6 @@
|
||||
(list (js-sym "js-regex-new") (nth ast 1) (nth ast 2)))
|
||||
((js-tag? ast "js-null") nil)
|
||||
((js-tag? ast "js-undef") (list (js-sym "quote") :js-undefined))
|
||||
((js-tag? ast "js-paren") (js-transpile (nth ast 1)))
|
||||
((js-tag? ast "js-ident") (js-transpile-ident (nth ast 1)))
|
||||
((js-tag? ast "js-unop")
|
||||
(js-transpile-unop (nth ast 1) (nth ast 2)))
|
||||
@@ -117,8 +116,7 @@
|
||||
((js-tag? ast "js-arrow")
|
||||
(js-transpile-arrow (nth ast 1) (nth ast 2)))
|
||||
((js-tag? ast "js-program") (js-transpile-stmts (nth ast 1)))
|
||||
((js-tag? ast "js-block")
|
||||
(cons (js-sym "begin") (js-transpile-stmt-list (nth ast 1))))
|
||||
((js-tag? ast "js-block") (js-transpile-stmts (nth ast 1)))
|
||||
((js-tag? ast "js-exprstmt") (js-transpile (nth ast 1)))
|
||||
((js-tag? ast "js-empty") nil)
|
||||
((js-tag? ast "js-var")
|
||||
@@ -166,8 +164,6 @@
|
||||
(js-transpile-new (nth ast 1) (nth ast 2)))
|
||||
((js-tag? ast "js-class")
|
||||
(js-transpile-class (nth ast 1) (nth ast 2) (nth ast 3)))
|
||||
((js-tag? ast "js-comma")
|
||||
(cons (js-sym "begin") (map js-transpile (nth ast 1))))
|
||||
((js-tag? ast "js-throw") (js-transpile-throw (nth ast 1)))
|
||||
((js-tag? ast "js-try")
|
||||
(js-transpile-try (nth ast 1) (nth ast 2) (nth ast 3)))
|
||||
@@ -225,23 +221,7 @@
|
||||
(js-sym "js-delete-prop")
|
||||
(js-transpile (nth arg 1))
|
||||
(js-transpile (nth arg 2))))
|
||||
((js-tag? arg "js-ident") false)
|
||||
((js-tag? arg "js-paren") (js-transpile-unop op (nth arg 1)))
|
||||
(else true)))
|
||||
((and (= op "typeof") (js-tag? arg "js-ident"))
|
||||
(let
|
||||
((name (nth arg 1)))
|
||||
(list
|
||||
(js-sym "if")
|
||||
(list
|
||||
(js-sym "or")
|
||||
(list
|
||||
(js-sym "env-has?")
|
||||
(list (js-sym "current-env"))
|
||||
name)
|
||||
(list (js-sym "dict-has?") (js-sym "js-global") name))
|
||||
(list (js-sym "js-typeof") (js-transpile arg))
|
||||
"undefined")))
|
||||
(else
|
||||
(let
|
||||
((a (js-transpile arg)))
|
||||
@@ -251,8 +231,7 @@
|
||||
((= op "!") (list (js-sym "js-not") a))
|
||||
((= op "~") (list (js-sym "js-bitnot") a))
|
||||
((= op "typeof") (list (js-sym "js-typeof") a))
|
||||
((= op "void")
|
||||
(list (js-sym "begin") a (list (js-sym "quote") :js-undefined)))
|
||||
((= op "void") (list (js-sym "quote") :js-undefined))
|
||||
(else (error (str "js-transpile-unop: unsupported op: " op)))))))))
|
||||
|
||||
;; ── Array literal ─────────────────────────────────────────────────
|
||||
@@ -316,21 +295,6 @@
|
||||
(list (js-sym "js-undefined?") (js-sym "_a")))
|
||||
(js-transpile r)
|
||||
(js-sym "_a"))))
|
||||
((= op ">>>")
|
||||
(list
|
||||
(js-sym "js-unsigned-rshift")
|
||||
(js-transpile l)
|
||||
(js-transpile r)))
|
||||
((= op "<<")
|
||||
(list (js-sym "js-shl") (js-transpile l) (js-transpile r)))
|
||||
((= op ">>")
|
||||
(list (js-sym "js-shr") (js-transpile l) (js-transpile r)))
|
||||
((= op "&")
|
||||
(list (js-sym "js-bitand") (js-transpile l) (js-transpile r)))
|
||||
((= op "|")
|
||||
(list (js-sym "js-bitor") (js-transpile l) (js-transpile r)))
|
||||
((= op "^")
|
||||
(list (js-sym "js-bitxor") (js-transpile l) (js-transpile r)))
|
||||
(else (error (str "js-transpile-binop: unsupported op: " op))))))
|
||||
|
||||
;; ── Object literal ────────────────────────────────────────────────
|
||||
@@ -409,19 +373,7 @@
|
||||
(list
|
||||
(js-sym "js-new-call")
|
||||
(js-transpile callee)
|
||||
(cond
|
||||
((js-has-spread? args)
|
||||
(cons
|
||||
(js-sym "js-array-spread-build")
|
||||
(map
|
||||
(fn
|
||||
(e)
|
||||
(if
|
||||
(js-tag? e "js-spread")
|
||||
(list (js-sym "list") "js-spread" (js-transpile (nth e 1)))
|
||||
(list (js-sym "list") "js-value" (js-transpile e))))
|
||||
args)))
|
||||
(else (cons (js-sym "js-args") (map js-transpile args)))))))
|
||||
(cons (js-sym "list") (map js-transpile args)))))
|
||||
|
||||
(define
|
||||
js-transpile-array
|
||||
@@ -439,7 +391,7 @@
|
||||
(list (js-sym "list") "js-spread" (js-transpile (nth e 1)))
|
||||
(list (js-sym "list") "js-value" (js-transpile e))))
|
||||
elts))
|
||||
(cons (js-sym "js-make-list") (map js-transpile elts)))))
|
||||
(cons (js-sym "list") (map js-transpile elts)))))
|
||||
|
||||
(define
|
||||
js-has-spread?
|
||||
@@ -469,7 +421,7 @@
|
||||
(list (js-sym "list") "js-spread" (js-transpile (nth e 1)))
|
||||
(list (js-sym "list") "js-value" (js-transpile e))))
|
||||
args))
|
||||
(cons (js-sym "js-args") (map js-transpile args)))))
|
||||
(cons (js-sym "list") (map js-transpile args)))))
|
||||
|
||||
;; Transpile a JS expression string to SX source text (for inspection
|
||||
;; in tests). Useful for asserting the exact emitted tree.
|
||||
@@ -479,28 +431,18 @@
|
||||
(entries)
|
||||
(list
|
||||
(js-sym "let")
|
||||
(list (list (js-sym "_obj") (list (js-sym "js-make-obj"))))
|
||||
(list (list (js-sym "_obj") (list (js-sym "dict"))))
|
||||
(cons
|
||||
(js-sym "begin")
|
||||
(append
|
||||
(map
|
||||
(fn
|
||||
(entry)
|
||||
(cond
|
||||
((contains? (keys entry) :spread)
|
||||
(list
|
||||
(js-sym "js-obj-spread!")
|
||||
(js-sym "dict-set!")
|
||||
(js-sym "_obj")
|
||||
(js-transpile (get entry :spread))))
|
||||
(else
|
||||
(list
|
||||
(js-sym "js-obj-set!")
|
||||
(js-sym "_obj")
|
||||
(if
|
||||
(contains? (keys entry) :computed-key)
|
||||
(list (js-sym "js-to-string") (js-transpile (get entry :computed-key)))
|
||||
(get entry :key))
|
||||
(js-transpile (get entry :value))))))
|
||||
(get entry :key)
|
||||
(js-transpile (get entry :value))))
|
||||
entries)
|
||||
(list (js-sym "_obj")))))))
|
||||
|
||||
@@ -544,95 +486,6 @@
|
||||
(append inits (list (js-transpile body))))))))
|
||||
(list (js-sym "fn") param-syms body-tr))))
|
||||
|
||||
(define
|
||||
js-collect-var-decl-names
|
||||
(fn
|
||||
(decls)
|
||||
(cond
|
||||
((empty? decls) (list))
|
||||
((js-tag? (first decls) "js-vardecl")
|
||||
(cons
|
||||
(nth (first decls) 1)
|
||||
(js-collect-var-decl-names (rest decls))))
|
||||
(else (js-collect-var-decl-names (rest decls))))))
|
||||
|
||||
(define
|
||||
js-collect-var-names
|
||||
(fn
|
||||
(stmts)
|
||||
(cond
|
||||
((empty? stmts) (list))
|
||||
(else
|
||||
(append
|
||||
(js-collect-var-names-stmt (first stmts))
|
||||
(js-collect-var-names (rest stmts)))))))
|
||||
|
||||
(define
|
||||
js-collect-var-names-stmt
|
||||
(fn
|
||||
(stmt)
|
||||
(cond
|
||||
((not (list? stmt)) (list))
|
||||
((and (js-tag? stmt "js-var") (= (nth stmt 1) "var"))
|
||||
(js-collect-var-decl-names (nth stmt 2)))
|
||||
((js-tag? stmt "js-block") (js-collect-var-names (nth stmt 1)))
|
||||
((js-tag? stmt "js-for")
|
||||
(append
|
||||
(js-collect-var-names-stmt (nth stmt 1))
|
||||
(js-collect-var-names-stmt (nth stmt 4))))
|
||||
((js-tag? stmt "js-for-of-in")
|
||||
(js-collect-var-names-stmt (nth stmt 4)))
|
||||
((js-tag? stmt "js-while")
|
||||
(js-collect-var-names-stmt (nth stmt 2)))
|
||||
((js-tag? stmt "js-do-while")
|
||||
(js-collect-var-names-stmt (nth stmt 1)))
|
||||
((js-tag? stmt "js-if")
|
||||
(append
|
||||
(js-collect-var-names-stmt (nth stmt 2))
|
||||
(if (>= (len stmt) 4) (js-collect-var-names-stmt (nth stmt 3)) (list))))
|
||||
((js-tag? stmt "js-try")
|
||||
(append
|
||||
(js-collect-var-names-stmt (nth stmt 1))
|
||||
(if (and (>= (len stmt) 3) (list? (nth stmt 2)))
|
||||
(js-collect-var-names-stmt (nth (nth stmt 2) 2))
|
||||
(list))
|
||||
(if (>= (len stmt) 4) (js-collect-var-names-stmt (nth stmt 3)) (list))))
|
||||
((js-tag? stmt "js-switch")
|
||||
(js-collect-var-names-cases (nth stmt 2)))
|
||||
(else (list)))))
|
||||
|
||||
(define
|
||||
js-collect-var-names-cases
|
||||
(fn
|
||||
(cases)
|
||||
(cond
|
||||
((empty? cases) (list))
|
||||
(else
|
||||
(append
|
||||
(js-collect-var-names (nth (first cases) 2))
|
||||
(js-collect-var-names-cases (rest cases)))))))
|
||||
|
||||
(define
|
||||
js-dedup-names
|
||||
(fn
|
||||
(names seen)
|
||||
(cond
|
||||
((empty? names) (list))
|
||||
((some (fn (s) (= s (first names))) seen)
|
||||
(js-dedup-names (rest names) seen))
|
||||
(else
|
||||
(cons
|
||||
(first names)
|
||||
(js-dedup-names (rest names) (cons (first names) seen)))))))
|
||||
|
||||
(define
|
||||
js-var-hoist-forms
|
||||
(fn
|
||||
(names)
|
||||
(map
|
||||
(fn (name) (list (js-sym "define") (js-sym name) :js-undefined))
|
||||
names)))
|
||||
|
||||
(define
|
||||
js-transpile-tpl
|
||||
(fn
|
||||
@@ -724,12 +577,6 @@
|
||||
(list (js-sym "js-undefined?") lhs-expr))
|
||||
rhs-expr
|
||||
lhs-expr))
|
||||
((= op "<<=") (list (js-sym "js-shl") lhs-expr rhs-expr))
|
||||
((= op ">>=") (list (js-sym "js-shr") lhs-expr rhs-expr))
|
||||
((= op ">>>=") (list (js-sym "js-unsigned-rshift") lhs-expr rhs-expr))
|
||||
((= op "&=") (list (js-sym "js-bitand") lhs-expr rhs-expr))
|
||||
((= op "|=") (list (js-sym "js-bitor") lhs-expr rhs-expr))
|
||||
((= op "^=") (list (js-sym "js-bitxor") lhs-expr rhs-expr))
|
||||
(else (error (str "js-compound-update: unsupported op: " op))))))
|
||||
|
||||
(define
|
||||
@@ -959,7 +806,7 @@
|
||||
(if
|
||||
(= iter-kind "of")
|
||||
(list (js-sym "js-iterable-to-list") iter-sx)
|
||||
(list (js-sym "js-for-in-keys") iter-sx))))
|
||||
(list (js-sym "js-object-keys") iter-sx))))
|
||||
(list
|
||||
(js-sym "for-each")
|
||||
(list
|
||||
@@ -988,7 +835,7 @@
|
||||
(fn
|
||||
(params)
|
||||
(cond
|
||||
((empty? params) (list (js-sym "&rest") (js-sym "__extra_args__")))
|
||||
((empty? params) (list))
|
||||
((and (list? (first params)) (js-tag? (first params) "js-rest"))
|
||||
(list (js-sym "&rest") (js-sym (nth (first params) 1))))
|
||||
(else
|
||||
@@ -996,27 +843,6 @@
|
||||
(js-param-sym (first params))
|
||||
(js-build-param-list (rest params)))))))
|
||||
|
||||
(define
|
||||
js-arguments-build-form
|
||||
(fn
|
||||
(params)
|
||||
(list (js-sym "js-list-copy") (js-arguments-build-form-raw params))))
|
||||
|
||||
(define
|
||||
js-arguments-build-form-raw
|
||||
(fn
|
||||
(params)
|
||||
(cond
|
||||
((empty? params)
|
||||
(js-sym "__extra_args__"))
|
||||
((and (list? (first params)) (js-tag? (first params) "js-rest"))
|
||||
(js-sym (nth (first params) 1)))
|
||||
(else
|
||||
(list
|
||||
(js-sym "cons")
|
||||
(js-param-sym (first params))
|
||||
(js-arguments-build-form-raw (rest params)))))))
|
||||
|
||||
(define
|
||||
js-param-init-forms
|
||||
(fn
|
||||
@@ -1050,7 +876,7 @@
|
||||
(fn
|
||||
(stmts)
|
||||
(let
|
||||
((hoisted (append (js-var-hoist-forms (js-dedup-names (js-collect-var-names stmts) (list))) (js-collect-funcdecls stmts))))
|
||||
((hoisted (js-collect-funcdecls stmts)))
|
||||
(let
|
||||
((rest-stmts (js-transpile-stmt-list stmts)))
|
||||
(cons (js-sym "begin") (append hoisted rest-stmts))))))
|
||||
@@ -1109,12 +935,12 @@
|
||||
|
||||
(define
|
||||
js-transpile-var
|
||||
(fn (kind decls) (cons (js-sym "begin") (js-vardecl-forms decls (= kind "var")))))
|
||||
(fn (kind decls) (cons (js-sym "begin") (js-vardecl-forms decls))))
|
||||
|
||||
(define
|
||||
js-vardecl-forms
|
||||
(fn
|
||||
(decls is-var)
|
||||
(decls)
|
||||
(cond
|
||||
((empty? decls) (list))
|
||||
(else
|
||||
@@ -1124,10 +950,10 @@
|
||||
((js-tag? d "js-vardecl")
|
||||
(cons
|
||||
(list
|
||||
(js-sym (if is-var "set!" "define"))
|
||||
(js-sym "define")
|
||||
(js-sym (nth d 1))
|
||||
(js-transpile (nth d 2)))
|
||||
(js-vardecl-forms (rest decls) is-var)))
|
||||
(js-vardecl-forms (rest decls))))
|
||||
((js-tag? d "js-vardecl-obj")
|
||||
(let
|
||||
((names (nth d 1))
|
||||
@@ -1138,7 +964,7 @@
|
||||
(js-vardecl-obj-forms
|
||||
names
|
||||
tmp-sym
|
||||
(js-vardecl-forms (rest decls) is-var)))))
|
||||
(js-vardecl-forms (rest decls))))))
|
||||
((js-tag? d "js-vardecl-arr")
|
||||
(let
|
||||
((names (nth d 1))
|
||||
@@ -1150,7 +976,7 @@
|
||||
names
|
||||
tmp-sym
|
||||
0
|
||||
(js-vardecl-forms (rest decls) is-var)))))
|
||||
(js-vardecl-forms (rest decls))))))
|
||||
(else (error "js-vardecl-forms: unexpected decl"))))))))
|
||||
|
||||
(define
|
||||
@@ -1450,28 +1276,7 @@
|
||||
(let
|
||||
((body-tr (js-transpile body)))
|
||||
(let
|
||||
((with-catch
|
||||
(cond
|
||||
((= catch-part nil) body-tr)
|
||||
(else
|
||||
(let
|
||||
((pname (nth catch-part 0))
|
||||
(cbody (nth catch-part 1))
|
||||
(raw-sym (js-sym "__raw_exc__")))
|
||||
(list
|
||||
(js-sym "guard")
|
||||
(list
|
||||
raw-sym
|
||||
(list
|
||||
(js-sym "else")
|
||||
(cond
|
||||
((= pname nil) (js-transpile cbody))
|
||||
(else
|
||||
(list
|
||||
(js-sym "let")
|
||||
(list (list (js-sym pname) (list (js-sym "js-wrap-exn") raw-sym)))
|
||||
(js-transpile cbody))))))
|
||||
body-tr))))))
|
||||
((with-catch (cond ((= catch-part nil) body-tr) (else (let ((pname (nth catch-part 0)) (cbody (nth catch-part 1))) (list (js-sym "guard") (list (if (= pname nil) (js-sym "__exc__") (js-sym pname)) (list (js-sym "else") (js-transpile cbody))) body-tr))))))
|
||||
(cond
|
||||
((= finally-part nil) with-catch)
|
||||
(else
|
||||
@@ -1492,7 +1297,7 @@
|
||||
(if
|
||||
(and (list? body) (js-tag? body "js-block"))
|
||||
(let
|
||||
((hoisted (append (js-var-hoist-forms (js-dedup-names (js-collect-var-names (nth body 1)) (list))) (js-collect-funcdecls (nth body 1)))))
|
||||
((hoisted (js-collect-funcdecls (nth body 1))))
|
||||
(append hoisted (js-transpile-stmt-list (nth body 1))))
|
||||
(list (js-transpile body)))))
|
||||
(list
|
||||
@@ -1500,9 +1305,7 @@
|
||||
param-syms
|
||||
(list
|
||||
(js-sym "let")
|
||||
(list
|
||||
(list (js-sym "this") (list (js-sym "js-this")))
|
||||
(list (js-sym "arguments") (js-arguments-build-form params)))
|
||||
(list (list (js-sym "this") (list (js-sym "js-this"))))
|
||||
(list
|
||||
(js-sym "let")
|
||||
(list
|
||||
@@ -1513,7 +1316,7 @@
|
||||
(list
|
||||
(js-sym "fn")
|
||||
(list (js-sym "__return__"))
|
||||
(cons (js-sym "begin") (append (append inits body-forms) (list nil)))))))
|
||||
(cons (js-sym "begin") (append inits body-forms))))))
|
||||
(list
|
||||
(js-sym "if")
|
||||
(list (js-sym "=") (js-sym "__r__") nil)
|
||||
@@ -1530,7 +1333,7 @@
|
||||
(if
|
||||
(and (list? body) (js-tag? body "js-block"))
|
||||
(let
|
||||
((hoisted (append (js-var-hoist-forms (js-dedup-names (js-collect-var-names (nth body 1)) (list))) (js-collect-funcdecls (nth body 1)))))
|
||||
((hoisted (js-collect-funcdecls (nth body 1))))
|
||||
(append hoisted (js-transpile-stmt-list (nth body 1))))
|
||||
(list (js-transpile body)))))
|
||||
(list
|
||||
@@ -1598,7 +1401,7 @@
|
||||
(fn
|
||||
(src)
|
||||
(let
|
||||
((result (eval-expr (list (quote let) (list (list (js-sym "this") (list (js-sym "js-this")))) (js-transpile (js-parse (js-tokenize src)))))))
|
||||
((result (eval-expr (js-transpile (js-parse (js-tokenize src))))))
|
||||
(js-drain-microtasks!)
|
||||
result)))
|
||||
|
||||
|
||||
145
lib/tcl/conformance.sh
Executable file
145
lib/tcl/conformance.sh
Executable file
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tcl-on-SX conformance runner — epoch protocol to sx_server.exe
|
||||
# Usage: lib/tcl/conformance.sh [file.tcl ...]
|
||||
# Defaults to lib/tcl/tests/programs/*.tcl
|
||||
set -uo pipefail
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
SX_SERVER="${SX_SERVER:-hosts/ocaml/_build/default/bin/sx_server.exe}"
|
||||
if [ ! -x "$SX_SERVER" ]; then
|
||||
SX_SERVER="/root/rose-ash/hosts/ocaml/_build/default/bin/sx_server.exe"
|
||||
fi
|
||||
if [ ! -x "$SX_SERVER" ]; then echo "ERROR: sx_server.exe not found"; exit 1; fi
|
||||
|
||||
SCOREBOARD_JSON="${SCOREBOARD_JSON:-lib/tcl/scoreboard.json}"
|
||||
SCOREBOARD_MD="${SCOREBOARD_MD:-lib/tcl/scoreboard.md}"
|
||||
|
||||
# Collect tcl files
|
||||
if [ "$#" -gt 0 ]; then
|
||||
TCL_FILES=("$@")
|
||||
else
|
||||
TCL_FILES=(lib/tcl/tests/programs/*.tcl)
|
||||
fi
|
||||
|
||||
# Generate a helper .sx file that defines the Tcl source as an SX string variable.
|
||||
# We escape the source for SX string literals: backslashes → \\, quotes → \", newlines → \n.
|
||||
# This is safe in a (define ...) context — no double-parsing like (eval "...") would cause.
|
||||
write_sx_helper() {
|
||||
local tcl_file="$1"
|
||||
local helper_file="$2"
|
||||
python3 << PYEOF
|
||||
src = open('${tcl_file}').read()
|
||||
escaped = src.replace('\\\\', '\\\\\\\\').replace('"', '\\\\"').replace('\\n', '\\\\n')
|
||||
with open('${helper_file}', 'w') as f:
|
||||
f.write(f'(define __tcl-src "{escaped}")\\n')
|
||||
f.write('(define __tcl-result (get (tcl-eval-string (make-default-tcl-interp) __tcl-src) :result))\\n')
|
||||
PYEOF
|
||||
}
|
||||
|
||||
total=0
|
||||
passed=0
|
||||
failed=0
|
||||
programs_json=""
|
||||
md_rows=""
|
||||
|
||||
for tcl_file in "${TCL_FILES[@]}"; do
|
||||
basename_noext=$(basename "$tcl_file" .tcl)
|
||||
total=$((total + 1))
|
||||
|
||||
# Read expected value from first-line comment "# expected: VALUE"
|
||||
expected=$(head -1 "$tcl_file" | sed -n 's/^# expected: *//p')
|
||||
if [ -z "$expected" ]; then
|
||||
echo "WARN: no '# expected:' annotation in $tcl_file — skipping"
|
||||
continue
|
||||
fi
|
||||
|
||||
tmpfile=$(mktemp)
|
||||
helper=$(mktemp --suffix=.sx)
|
||||
trap "rm -f $tmpfile $helper" EXIT
|
||||
|
||||
# Write helper .sx with Tcl source embedded as SX string
|
||||
write_sx_helper "$tcl_file" "$helper"
|
||||
|
||||
# Build epoch input using quoted heredoc for static parts; helper path via variable
|
||||
cat > "$tmpfile" << EPOCHS
|
||||
(epoch 1)
|
||||
(load "lib/tcl/tokenizer.sx")
|
||||
(epoch 2)
|
||||
(load "lib/tcl/parser.sx")
|
||||
(epoch 3)
|
||||
(load "lib/tcl/runtime.sx")
|
||||
(epoch 4)
|
||||
(load "$helper")
|
||||
(epoch 5)
|
||||
(eval "__tcl-result")
|
||||
(epoch 6)
|
||||
EPOCHS
|
||||
|
||||
output=$(timeout 30 "$SX_SERVER" < "$tmpfile" 2>&1)
|
||||
got=$(echo "$output" | grep -A1 "^(ok-len 5 " | tail -1 | tr -d '"')
|
||||
|
||||
if [ "$got" = "$expected" ]; then
|
||||
status="PASS"
|
||||
passed=$((passed + 1))
|
||||
echo "PASS $basename_noext (expected: $expected, got: $got)"
|
||||
else
|
||||
status="FAIL"
|
||||
failed=$((failed + 1))
|
||||
echo "FAIL $basename_noext (expected: $expected, got: ${got:-<empty>})"
|
||||
if [ -n "${VERBOSE:-}" ]; then
|
||||
echo "--- server output ---"
|
||||
echo "$output"
|
||||
echo "--- helper.sx ---"
|
||||
cat "$helper"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Accumulate JSON fragment (escape for JSON)
|
||||
got_json=$(printf '%s' "$got" | python3 -c "import sys,json; sys.stdout.write(json.dumps(sys.stdin.read()))" | tr -d '"')
|
||||
exp_json=$(printf '%s' "$expected" | python3 -c "import sys,json; sys.stdout.write(json.dumps(sys.stdin.read()))" | tr -d '"')
|
||||
|
||||
if [ -n "$programs_json" ]; then
|
||||
programs_json="${programs_json},"
|
||||
fi
|
||||
programs_json="${programs_json}
|
||||
\"${basename_noext}\": {\"status\": \"${status}\", \"expected\": \"${exp_json}\", \"got\": \"${got_json}\"}"
|
||||
|
||||
# Accumulate Markdown row
|
||||
if [ "$status" = "PASS" ]; then
|
||||
icon="✓ PASS"
|
||||
else
|
||||
icon="✗ FAIL"
|
||||
fi
|
||||
md_rows="${md_rows}| ${basename_noext} | ${icon} | ${expected} | ${got} |
|
||||
"
|
||||
done
|
||||
|
||||
# Write scoreboard.json
|
||||
cat > "$SCOREBOARD_JSON" << JSON
|
||||
{
|
||||
"total": ${total},
|
||||
"passed": ${passed},
|
||||
"failed": ${failed},
|
||||
"programs": {${programs_json}
|
||||
}
|
||||
}
|
||||
JSON
|
||||
|
||||
# Write scoreboard.md
|
||||
cat > "$SCOREBOARD_MD" << MD
|
||||
# Tcl-on-SX Conformance Scoreboard
|
||||
|
||||
| Program | Status | Expected | Got |
|
||||
|---|---|---|---|
|
||||
${md_rows}
|
||||
**${passed}/${total} passing**
|
||||
MD
|
||||
|
||||
echo ""
|
||||
echo "Scoreboard: ${passed}/${total} passing"
|
||||
echo "Written: $SCOREBOARD_JSON, $SCOREBOARD_MD"
|
||||
|
||||
if [ "$failed" -gt 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
41
lib/tcl/parser.sx
Normal file
41
lib/tcl/parser.sx
Normal file
@@ -0,0 +1,41 @@
|
||||
; Tcl parser — thin layer over tcl-tokenize
|
||||
; Adds tcl-parse entry point and word utility fns
|
||||
|
||||
; Entry point: parse Tcl source to a list of commands.
|
||||
; Returns same structure as tcl-tokenize.
|
||||
(define tcl-parse (fn (src) (tcl-tokenize src)))
|
||||
|
||||
; True if word has no substitutions — value can be read statically.
|
||||
; braced words are always simple. compound words are simple when all
|
||||
; parts are plain text with no var/cmd parts.
|
||||
(define tcl-word-simple?
|
||||
(fn (word)
|
||||
(cond
|
||||
((= (get word :type) "braced") true)
|
||||
((= (get word :type) "compound")
|
||||
(let ((parts (get word :parts)))
|
||||
(every? (fn (p) (= (get p :type) "text")) parts)))
|
||||
(else false))))
|
||||
|
||||
; Concatenate text parts of a simple word into a single string.
|
||||
; For braced words returns :value directly.
|
||||
; For compound words with only text parts, joins them.
|
||||
; Returns nil for words with substitutions.
|
||||
(define tcl-word-literal
|
||||
(fn (word)
|
||||
(cond
|
||||
((= (get word :type) "braced") (get word :value))
|
||||
((= (get word :type) "compound")
|
||||
(if (tcl-word-simple? word)
|
||||
(join "" (map (fn (p) (get p :value)) (get word :parts)))
|
||||
nil))
|
||||
(else nil))))
|
||||
|
||||
; Number of words in a parsed command.
|
||||
(define tcl-cmd-len
|
||||
(fn (cmd) (len (get cmd :words))))
|
||||
|
||||
; Nth word literal from a command (index 0 = command name).
|
||||
; Returns nil if word has substitutions.
|
||||
(define tcl-nth-literal
|
||||
(fn (cmd n) (tcl-word-literal (nth (get cmd :words) n))))
|
||||
3336
lib/tcl/runtime.sx
Normal file
3336
lib/tcl/runtime.sx
Normal file
File diff suppressed because it is too large
Load Diff
10
lib/tcl/scoreboard.json
Normal file
10
lib/tcl/scoreboard.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"total": 3,
|
||||
"passed": 3,
|
||||
"failed": 0,
|
||||
"programs": {
|
||||
"assert": {"status": "PASS", "expected": "10", "got": "10"},
|
||||
"for-each-line": {"status": "PASS", "expected": "13", "got": "13"},
|
||||
"with-temp-var": {"status": "PASS", "expected": "100 999", "got": "100 999"}
|
||||
}
|
||||
}
|
||||
9
lib/tcl/scoreboard.md
Normal file
9
lib/tcl/scoreboard.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Tcl-on-SX Conformance Scoreboard
|
||||
|
||||
| Program | Status | Expected | Got |
|
||||
|---|---|---|---|
|
||||
| assert | ✓ PASS | 10 | 10 |
|
||||
| for-each-line | ✓ PASS | 13 | 13 |
|
||||
| with-temp-var | ✓ PASS | 100 999 | 100 999 |
|
||||
|
||||
**3/3 passing**
|
||||
114
lib/tcl/test.sh
Executable file
114
lib/tcl/test.sh
Executable file
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tcl-on-SX test runner — epoch protocol to sx_server.exe
|
||||
set -uo pipefail
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
SX_SERVER="${SX_SERVER:-hosts/ocaml/_build/default/bin/sx_server.exe}"
|
||||
if [ ! -x "$SX_SERVER" ]; then
|
||||
SX_SERVER="/root/rose-ash/hosts/ocaml/_build/default/bin/sx_server.exe"
|
||||
fi
|
||||
if [ ! -x "$SX_SERVER" ]; then echo "ERROR: sx_server.exe not found"; exit 1; fi
|
||||
|
||||
VERBOSE="${1:-}"
|
||||
TMPFILE=$(mktemp)
|
||||
HELPER=$(mktemp --suffix=.sx)
|
||||
trap "rm -f $TMPFILE $HELPER" EXIT
|
||||
|
||||
# Helper file: run all test suites and format a parseable summary string
|
||||
cat > "$HELPER" << 'HELPER_EOF'
|
||||
(define __pr (tcl-run-parse-tests))
|
||||
(define __er (tcl-run-eval-tests))
|
||||
(define __xr (tcl-run-error-tests))
|
||||
(define __nr (tcl-run-namespace-tests))
|
||||
(define __cr (tcl-run-coro-tests))
|
||||
(define __ir (tcl-run-idiom-tests))
|
||||
(define tcl-test-summary
|
||||
(str "PARSE:" (get __pr "passed") ":" (get __pr "failed")
|
||||
" EVAL:" (get __er "passed") ":" (get __er "failed")
|
||||
" ERROR:" (get __xr "passed") ":" (get __xr "failed")
|
||||
" NAMESPACE:" (get __nr "passed") ":" (get __nr "failed")
|
||||
" CORO:" (get __cr "passed") ":" (get __cr "failed")
|
||||
" IDIOM:" (get __ir "passed") ":" (get __ir "failed")))
|
||||
HELPER_EOF
|
||||
|
||||
cat > "$TMPFILE" << EPOCHS
|
||||
(epoch 1)
|
||||
(load "lib/tcl/tokenizer.sx")
|
||||
(epoch 2)
|
||||
(load "lib/tcl/parser.sx")
|
||||
(epoch 3)
|
||||
(load "lib/tcl/tests/parse.sx")
|
||||
(epoch 4)
|
||||
(load "lib/fiber.sx")
|
||||
(load "lib/tcl/runtime.sx")
|
||||
(epoch 5)
|
||||
(load "lib/tcl/tests/eval.sx")
|
||||
(epoch 6)
|
||||
(load "lib/tcl/tests/error.sx")
|
||||
(epoch 7)
|
||||
(load "lib/tcl/tests/namespace.sx")
|
||||
(epoch 8)
|
||||
(load "lib/tcl/tests/coro.sx")
|
||||
(epoch 9)
|
||||
(load "lib/tcl/tests/idioms.sx")
|
||||
(epoch 10)
|
||||
(load "$HELPER")
|
||||
(epoch 11)
|
||||
(eval "tcl-test-summary")
|
||||
EPOCHS
|
||||
|
||||
OUTPUT=$(timeout 180 "$SX_SERVER" < "$TMPFILE" 2>&1)
|
||||
[ "$VERBOSE" = "-v" ] && echo "$OUTPUT"
|
||||
|
||||
# Extract summary line from epoch 11 output
|
||||
SUMMARY=$(echo "$OUTPUT" | grep -A1 "^(ok-len 11 " | tail -1 | tr -d '"')
|
||||
|
||||
if [ -z "$SUMMARY" ]; then
|
||||
echo "ERROR: no summary from test run"
|
||||
echo "$OUTPUT" | tail -20
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Parse PARSE:N:M EVAL:N:M ERROR:N:M NAMESPACE:N:M CORO:N:M IDIOM:N:M
|
||||
PARSE_PART=$(echo "$SUMMARY" | grep -o 'PARSE:[0-9]*:[0-9]*')
|
||||
EVAL_PART=$(echo "$SUMMARY" | grep -o 'EVAL:[0-9]*:[0-9]*')
|
||||
ERROR_PART=$(echo "$SUMMARY" | grep -o 'ERROR:[0-9]*:[0-9]*')
|
||||
NAMESPACE_PART=$(echo "$SUMMARY" | grep -o 'NAMESPACE:[0-9]*:[0-9]*')
|
||||
CORO_PART=$(echo "$SUMMARY" | grep -o 'CORO:[0-9]*:[0-9]*')
|
||||
IDIOM_PART=$(echo "$SUMMARY" | grep -o 'IDIOM:[0-9]*:[0-9]*')
|
||||
|
||||
PARSE_PASSED=$(echo "$PARSE_PART" | cut -d: -f2)
|
||||
PARSE_FAILED=$(echo "$PARSE_PART" | cut -d: -f3)
|
||||
EVAL_PASSED=$(echo "$EVAL_PART" | cut -d: -f2)
|
||||
EVAL_FAILED=$(echo "$EVAL_PART" | cut -d: -f3)
|
||||
ERROR_PASSED=$(echo "$ERROR_PART" | cut -d: -f2)
|
||||
ERROR_FAILED=$(echo "$ERROR_PART" | cut -d: -f3)
|
||||
NAMESPACE_PASSED=$(echo "$NAMESPACE_PART" | cut -d: -f2)
|
||||
NAMESPACE_FAILED=$(echo "$NAMESPACE_PART" | cut -d: -f3)
|
||||
CORO_PASSED=$(echo "$CORO_PART" | cut -d: -f2)
|
||||
CORO_FAILED=$(echo "$CORO_PART" | cut -d: -f3)
|
||||
IDIOM_PASSED=$(echo "$IDIOM_PART" | cut -d: -f2)
|
||||
IDIOM_FAILED=$(echo "$IDIOM_PART" | cut -d: -f3)
|
||||
|
||||
PARSE_PASSED=${PARSE_PASSED:-0}; PARSE_FAILED=${PARSE_FAILED:-1}
|
||||
EVAL_PASSED=${EVAL_PASSED:-0}; EVAL_FAILED=${EVAL_FAILED:-1}
|
||||
ERROR_PASSED=${ERROR_PASSED:-0}; ERROR_FAILED=${ERROR_FAILED:-1}
|
||||
NAMESPACE_PASSED=${NAMESPACE_PASSED:-0}; NAMESPACE_FAILED=${NAMESPACE_FAILED:-1}
|
||||
CORO_PASSED=${CORO_PASSED:-0}; CORO_FAILED=${CORO_FAILED:-1}
|
||||
IDIOM_PASSED=${IDIOM_PASSED:-0}; IDIOM_FAILED=${IDIOM_FAILED:-1}
|
||||
|
||||
TOTAL_PASSED=$((PARSE_PASSED + EVAL_PASSED + ERROR_PASSED + NAMESPACE_PASSED + CORO_PASSED + IDIOM_PASSED))
|
||||
TOTAL_FAILED=$((PARSE_FAILED + EVAL_FAILED + ERROR_FAILED + NAMESPACE_FAILED + CORO_FAILED + IDIOM_FAILED))
|
||||
TOTAL=$((TOTAL_PASSED + TOTAL_FAILED))
|
||||
|
||||
if [ "$TOTAL_FAILED" = "0" ]; then
|
||||
echo "ok $TOTAL_PASSED/$TOTAL tcl tests passed (parse: $PARSE_PASSED, eval: $EVAL_PASSED, error: $ERROR_PASSED, namespace: $NAMESPACE_PASSED, coro: $CORO_PASSED, idiom: $IDIOM_PASSED)"
|
||||
exit 0
|
||||
else
|
||||
echo "FAIL $TOTAL_PASSED/$TOTAL passed, $TOTAL_FAILED failed (parse: $PARSE_PASSED/$((PARSE_PASSED+PARSE_FAILED)), eval: $EVAL_PASSED/$((EVAL_PASSED+EVAL_FAILED)), error: $ERROR_PASSED/$((ERROR_PASSED+ERROR_FAILED)), namespace: $NAMESPACE_PASSED/$((NAMESPACE_PASSED+NAMESPACE_FAILED)), coro: $CORO_PASSED/$((CORO_PASSED+CORO_FAILED)), idiom: $IDIOM_PASSED/$((IDIOM_PASSED+IDIOM_FAILED)))"
|
||||
if [ -z "$VERBOSE" ]; then
|
||||
echo "--- output ---"
|
||||
echo "$OUTPUT" | tail -30
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
136
lib/tcl/tests/coro.sx
Normal file
136
lib/tcl/tests/coro.sx
Normal file
@@ -0,0 +1,136 @@
|
||||
; Tcl-on-SX coroutine tests (Phase 6)
|
||||
(define tcl-coro-pass 0)
|
||||
(define tcl-coro-fail 0)
|
||||
(define tcl-coro-failures (list))
|
||||
|
||||
(define
|
||||
tcl-coro-assert
|
||||
(fn
|
||||
(label expected actual)
|
||||
(if
|
||||
(equal? expected actual)
|
||||
(set! tcl-coro-pass (+ tcl-coro-pass 1))
|
||||
(begin
|
||||
(set! tcl-coro-fail (+ tcl-coro-fail 1))
|
||||
(append!
|
||||
tcl-coro-failures
|
||||
(str label ": expected=" (str expected) " got=" (str actual)))))))
|
||||
|
||||
(define
|
||||
tcl-run-coro-tests
|
||||
(fn
|
||||
()
|
||||
(set! tcl-coro-pass 0)
|
||||
(set! tcl-coro-fail 0)
|
||||
(set! tcl-coro-failures (list))
|
||||
(define interp (fn () (make-default-tcl-interp)))
|
||||
(define run (fn (src) (tcl-eval-string (interp) src)))
|
||||
(define
|
||||
ok
|
||||
(fn (label actual expected) (tcl-coro-assert label expected actual)))
|
||||
|
||||
; --- basic coroutine: yields one value ---
|
||||
(ok "coro-single-yield"
|
||||
(get (run "proc gen {} { yield hello }\ncoroutine g gen\ng") :result)
|
||||
"hello")
|
||||
|
||||
; --- coroutine yields multiple values in order ---
|
||||
(ok "coro-multi-yield-1"
|
||||
(get (run "proc cnt {} { yield a; yield b; yield c }\ncoroutine c1 cnt\nc1") :result)
|
||||
"a")
|
||||
|
||||
(ok "coro-multi-yield-2"
|
||||
(get (run "proc cnt {} { yield a; yield b; yield c }\ncoroutine c1 cnt\nc1\nc1") :result)
|
||||
"b")
|
||||
|
||||
(ok "coro-multi-yield-3"
|
||||
(get (run "proc cnt {} { yield a; yield b; yield c }\ncoroutine c1 cnt\nc1\nc1\nc1") :result)
|
||||
"c")
|
||||
|
||||
; --- coroutine with arguments to proc ---
|
||||
(ok "coro-args"
|
||||
(get (run "proc gen2 {n} { yield $n; yield [expr {$n + 1}] }\ncoroutine g2 gen2 10\ng2") :result)
|
||||
"10")
|
||||
|
||||
(ok "coro-args-2"
|
||||
(get (run "proc gen2 {n} { yield $n; yield [expr {$n + 1}] }\ncoroutine g2 gen2 10\ng2\ng2") :result)
|
||||
"11")
|
||||
|
||||
; --- coroutine exhausted returns empty string ---
|
||||
(ok "coro-exhausted"
|
||||
(get (run "proc g3 {} { yield only }\ncoroutine c3 g3\nc3\nc3") :result)
|
||||
"")
|
||||
|
||||
; --- yield in while loop ---
|
||||
(ok "coro-while-loop-1"
|
||||
(get (run "proc counter {max} { set i 0; while {$i < $max} { yield $i; incr i } }\ncoroutine cw counter 3\ncw") :result)
|
||||
"0")
|
||||
|
||||
(ok "coro-while-loop-2"
|
||||
(get (run "proc counter {max} { set i 0; while {$i < $max} { yield $i; incr i } }\ncoroutine cw counter 3\ncw\ncw") :result)
|
||||
"1")
|
||||
|
||||
(ok "coro-while-loop-3"
|
||||
(get (run "proc counter {max} { set i 0; while {$i < $max} { yield $i; incr i } }\ncoroutine cw counter 3\ncw\ncw\ncw") :result)
|
||||
"2")
|
||||
|
||||
; --- collect all yields from coroutine ---
|
||||
(ok "coro-collect-all"
|
||||
(get
|
||||
(run
|
||||
"proc counter {n max} { while {$n < $max} { yield $n; incr n }; yield done }\ncoroutine gen1 counter 0 3\nset out {}\nfor {set i 0} {$i < 4} {incr i} { lappend out [gen1] }\nlindex $out 3")
|
||||
:result)
|
||||
"done")
|
||||
|
||||
; --- two independent coroutines ---
|
||||
(ok "coro-two-independent"
|
||||
(get
|
||||
(run
|
||||
"proc seq {start} { yield $start; yield [expr {$start+1}] }\ncoroutine ca seq 0\ncoroutine cb seq 10\nset r [ca]\nappend r \":\" [cb]")
|
||||
:result)
|
||||
"0:10")
|
||||
|
||||
; --- yield with no value returns empty string ---
|
||||
(ok "coro-yield-no-val"
|
||||
(get (run "proc g {} { yield }\ncoroutine cg g\ncg") :result)
|
||||
"")
|
||||
|
||||
; --- clock seconds ---
|
||||
(ok "clock-seconds"
|
||||
(> (parse-int (get (run "clock seconds") :result)) 0)
|
||||
true)
|
||||
|
||||
; --- clock milliseconds ---
|
||||
(ok "clock-milliseconds"
|
||||
(> (parse-int (get (run "clock milliseconds") :result)) 0)
|
||||
true)
|
||||
|
||||
; --- clock format stub ---
|
||||
(ok "clock-format"
|
||||
(get (run "clock format 0") :result)
|
||||
"Thu Jan 1 00:00:00 UTC 1970")
|
||||
|
||||
; --- file stubs ---
|
||||
(ok "file-exists-stub"
|
||||
(get (run "file exists /no/such/file") :result)
|
||||
"0")
|
||||
|
||||
(ok "file-join"
|
||||
(get (run "file join foo bar baz") :result)
|
||||
"foo/bar/baz")
|
||||
|
||||
(ok "open-returns-channel"
|
||||
(get (run "open /dev/null r") :result)
|
||||
"file0")
|
||||
|
||||
(ok "eof-returns-1"
|
||||
(get (run "set ch [open /dev/null r]\neof $ch") :result)
|
||||
"1")
|
||||
|
||||
(dict
|
||||
"passed"
|
||||
tcl-coro-pass
|
||||
"failed"
|
||||
tcl-coro-fail
|
||||
"failures"
|
||||
tcl-coro-failures)))
|
||||
192
lib/tcl/tests/error.sx
Normal file
192
lib/tcl/tests/error.sx
Normal file
@@ -0,0 +1,192 @@
|
||||
; Tcl-on-SX error handling tests (Phase 4)
|
||||
(define tcl-err-pass 0)
|
||||
(define tcl-err-fail 0)
|
||||
(define tcl-err-failures (list))
|
||||
|
||||
(define
|
||||
tcl-err-assert
|
||||
(fn
|
||||
(label expected actual)
|
||||
(if
|
||||
(equal? expected actual)
|
||||
(set! tcl-err-pass (+ tcl-err-pass 1))
|
||||
(begin
|
||||
(set! tcl-err-fail (+ tcl-err-fail 1))
|
||||
(append!
|
||||
tcl-err-failures
|
||||
(str label ": expected=" (str expected) " got=" (str actual)))))))
|
||||
|
||||
(define
|
||||
tcl-run-error-tests
|
||||
(fn
|
||||
()
|
||||
(set! tcl-err-pass 0)
|
||||
(set! tcl-err-fail 0)
|
||||
(set! tcl-err-failures (list))
|
||||
(define interp (fn () (make-default-tcl-interp)))
|
||||
(define run (fn (src) (tcl-eval-string (interp) src)))
|
||||
(define
|
||||
ok
|
||||
(fn (label actual expected) (tcl-err-assert label expected actual)))
|
||||
(define
|
||||
ok?
|
||||
(fn (label condition) (tcl-err-assert label true condition)))
|
||||
|
||||
; --- catch basic ---
|
||||
(ok "catch-ok-code" (get (run "catch {set x 1}") :result) "0")
|
||||
(ok "catch-ok-result-var" (tcl-var-get (run "catch {set x hello} r") "r") "hello")
|
||||
(ok "catch-ok-returns-0" (get (run "catch {set x hello} r") :result) "0")
|
||||
|
||||
; --- catch error ---
|
||||
(ok "catch-error-code" (get (run "catch {error oops} r") :result) "1")
|
||||
(ok "catch-error-result-var" (tcl-var-get (run "catch {error oops} r") "r") "oops")
|
||||
|
||||
; --- catch outer code stays 0 ---
|
||||
(ok? "catch-outer-code-ok" (= (get (run "catch {error boom} r") :code) 0))
|
||||
|
||||
; --- catch code 2 (return) ---
|
||||
(ok "catch-return-code" (get (run "proc p {} {return hello}\ncatch {p} r") :result) "0")
|
||||
(ok "catch-return-val" (tcl-var-get (run "proc p {} {return hello}\ncatch {p} r") "r") "hello")
|
||||
|
||||
; --- catch code 3 (break) ---
|
||||
(ok "catch-break-code" (get (run "catch {break} r") :result) "3")
|
||||
|
||||
; --- catch code 4 (continue) ---
|
||||
(ok "catch-continue-code" (get (run "catch {continue} r") :result) "4")
|
||||
|
||||
; --- catch no resultVar ---
|
||||
(ok "catch-no-var-ok" (get (run "catch {set x 1}") :result) "0")
|
||||
(ok "catch-no-var-err" (get (run "catch {error boom}") :result) "1")
|
||||
|
||||
; --- catch with optsVar ---
|
||||
(ok? "catch-opts-var-set"
|
||||
(let
|
||||
((i (run "catch {error boom} r opts")))
|
||||
(not (equal? (tcl-var-get i "opts") ""))))
|
||||
(ok? "catch-opts-contains-code"
|
||||
(let
|
||||
((i (run "catch {error boom} r opts")))
|
||||
(let
|
||||
((opts-str (tcl-var-get i "opts")))
|
||||
(not (equal? (tcl-string-first "-code" opts-str 0) "-1")))))
|
||||
|
||||
; --- catch nested ---
|
||||
(ok "catch-nested"
|
||||
(tcl-var-get (run "catch {catch {error inner} r2} outer") "r2")
|
||||
"inner")
|
||||
|
||||
; --- return -code error ---
|
||||
(ok "return-code-error-code"
|
||||
(get (run "catch {return -code error oops} r") :result)
|
||||
"1")
|
||||
(ok "return-code-error-val"
|
||||
(tcl-var-get (run "catch {return -code error oops} r") "r")
|
||||
"oops")
|
||||
|
||||
; --- return -code ok ---
|
||||
(ok "return-code-ok"
|
||||
(get (run "catch {return -code ok hello} r") :result)
|
||||
"0")
|
||||
(ok "return-code-ok-val"
|
||||
(tcl-var-get (run "catch {return -code ok hello} r") "r")
|
||||
"hello")
|
||||
|
||||
; --- return -code break ---
|
||||
(ok "return-code-break"
|
||||
(get (run "catch {return -code break} r") :result)
|
||||
"3")
|
||||
|
||||
; --- return -code continue ---
|
||||
(ok "return-code-continue"
|
||||
(get (run "catch {return -code continue} r") :result)
|
||||
"4")
|
||||
|
||||
; --- return -code numeric ---
|
||||
(ok "return-code-numeric-5"
|
||||
(get (run "catch {return -code 5 msg} r") :result)
|
||||
"5")
|
||||
|
||||
; --- return plain still code 2 (catch sees raw return code) ---
|
||||
(ok "return-plain-code"
|
||||
(get (run "catch {return hello} r") :result)
|
||||
"2")
|
||||
(ok "return-plain-val"
|
||||
(tcl-var-get (run "catch {return hello} r") "r")
|
||||
"hello")
|
||||
|
||||
; --- proc return -code error ---
|
||||
(ok "proc-return-code-error"
|
||||
(get (run "proc p {} {return -code error bad}\ncatch {p} r") :result)
|
||||
"1")
|
||||
(ok "proc-return-code-error-val"
|
||||
(tcl-var-get (run "proc p {} {return -code error bad}\ncatch {p} r") "r")
|
||||
"bad")
|
||||
|
||||
; --- error with info/code args ---
|
||||
(ok? "error-errorinfo-stored"
|
||||
(let
|
||||
((i (run "catch {error msg myinfo mycode} r")))
|
||||
(= (get i :code) 0)))
|
||||
|
||||
; --- throw ---
|
||||
(ok "throw-code" (get (run "catch {throw MYERR something} r") :result) "1")
|
||||
(ok "throw-msg" (tcl-var-get (run "catch {throw MYERR something} r") "r") "something")
|
||||
|
||||
; --- try basic ok ---
|
||||
(ok "try-ok-result"
|
||||
(get (run "try {set x hello} on ok {r} {set r2 $r}") :result)
|
||||
"hello")
|
||||
|
||||
; --- try on error ---
|
||||
(ok "try-on-error-handled"
|
||||
(get (run "try {error boom} on error {e} {set caught $e}") :result)
|
||||
"boom")
|
||||
(ok "try-on-error-var"
|
||||
(tcl-var-get (run "try {error boom} on error {e} {set caught $e}") "caught")
|
||||
"boom")
|
||||
|
||||
; --- try finally always runs ---
|
||||
(ok "try-finally-ok"
|
||||
(tcl-var-get (run "try {set x 1} finally {set done yes}") "done")
|
||||
"yes")
|
||||
(ok "try-finally-error"
|
||||
(tcl-var-get (run "catch {try {error boom} finally {set done yes}} r") "done")
|
||||
"yes")
|
||||
|
||||
; --- try on error + finally ---
|
||||
(ok "try-error-finally"
|
||||
(tcl-var-get
|
||||
(run "try {error oops} on error {e} {set caught $e} finally {set cleaned yes}")
|
||||
"cleaned")
|
||||
"yes")
|
||||
(ok "try-error-finally-caught"
|
||||
(tcl-var-get
|
||||
(run "try {error oops} on error {e} {set caught $e} finally {set cleaned yes}")
|
||||
"caught")
|
||||
"oops")
|
||||
|
||||
; --- try on ok and on error ---
|
||||
(ok "try-multi-clause-ok"
|
||||
(tcl-var-get
|
||||
(run "try {set x 1} on ok {r} {set which ok} on error {e} {set which err}")
|
||||
"which")
|
||||
"ok")
|
||||
(ok "try-multi-clause-err"
|
||||
(tcl-var-get
|
||||
(run "try {error boom} on ok {r} {set which ok} on error {e} {set which err}")
|
||||
"which")
|
||||
"err")
|
||||
|
||||
; --- catch preserves output ---
|
||||
(ok "catch-output-preserved"
|
||||
(get (run "puts -nonewline before\ncatch {puts -nonewline inside\nerror oops}\nputs -nonewline after")
|
||||
:output)
|
||||
"beforeinsideafter")
|
||||
|
||||
(dict
|
||||
"passed"
|
||||
tcl-err-pass
|
||||
"failed"
|
||||
tcl-err-fail
|
||||
"failures"
|
||||
tcl-err-failures)))
|
||||
386
lib/tcl/tests/eval.sx
Normal file
386
lib/tcl/tests/eval.sx
Normal file
@@ -0,0 +1,386 @@
|
||||
; Tcl-on-SX eval tests
|
||||
(define tcl-eval-pass 0)
|
||||
(define tcl-eval-fail 0)
|
||||
(define tcl-eval-failures (list))
|
||||
|
||||
(define
|
||||
tcl-eval-assert
|
||||
(fn
|
||||
(label expected actual)
|
||||
(if
|
||||
(equal? expected actual)
|
||||
(set! tcl-eval-pass (+ tcl-eval-pass 1))
|
||||
(begin
|
||||
(set! tcl-eval-fail (+ tcl-eval-fail 1))
|
||||
(append!
|
||||
tcl-eval-failures
|
||||
(str label ": expected=" (str expected) " got=" (str actual)))))))
|
||||
|
||||
(define
|
||||
tcl-run-eval-tests
|
||||
(fn
|
||||
()
|
||||
(set! tcl-eval-pass 0)
|
||||
(set! tcl-eval-fail 0)
|
||||
(set! tcl-eval-failures (list))
|
||||
(define interp (fn () (make-default-tcl-interp)))
|
||||
(define run (fn (src) (tcl-eval-string (interp) src)))
|
||||
(define
|
||||
ok
|
||||
(fn (label actual expected) (tcl-eval-assert label expected actual)))
|
||||
(define
|
||||
ok?
|
||||
(fn (label condition) (tcl-eval-assert label true condition)))
|
||||
(tcl-eval-assert "set-result" "hello" (get (run "set x hello") :result))
|
||||
(tcl-eval-assert
|
||||
"set-stored"
|
||||
"hello"
|
||||
(tcl-var-get (run "set x hello") "x"))
|
||||
(tcl-eval-assert
|
||||
"var-sub"
|
||||
"hello"
|
||||
(tcl-var-get (run "set x hello\nset y $x") "y"))
|
||||
(tcl-eval-assert
|
||||
"puts"
|
||||
"world\n"
|
||||
(get (run "set x world\nputs $x") :output))
|
||||
(tcl-eval-assert
|
||||
"puts-nonewline"
|
||||
"hi"
|
||||
(get (run "puts -nonewline hi") :output))
|
||||
(tcl-eval-assert "incr" "6" (tcl-var-get (run "set x 5\nincr x") "x"))
|
||||
(tcl-eval-assert
|
||||
"incr-delta"
|
||||
"8"
|
||||
(tcl-var-get (run "set x 5\nincr x 3") "x"))
|
||||
(tcl-eval-assert
|
||||
"incr-neg"
|
||||
"7"
|
||||
(tcl-var-get (run "set x 10\nincr x -3") "x"))
|
||||
(tcl-eval-assert
|
||||
"append"
|
||||
"foobar"
|
||||
(tcl-var-get (run "set x foo\nappend x bar") "x"))
|
||||
(tcl-eval-assert
|
||||
"append-new"
|
||||
"hello"
|
||||
(tcl-var-get (run "append x hello") "x"))
|
||||
(tcl-eval-assert
|
||||
"cmdsub-result"
|
||||
"6"
|
||||
(get (run "set x 5\nset y [incr x]") :result))
|
||||
(tcl-eval-assert
|
||||
"cmdsub-y"
|
||||
"6"
|
||||
(tcl-var-get (run "set x 5\nset y [incr x]") "y"))
|
||||
(tcl-eval-assert
|
||||
"cmdsub-x"
|
||||
"6"
|
||||
(tcl-var-get (run "set x 5\nset y [incr x]") "x"))
|
||||
(tcl-eval-assert
|
||||
"multi-cmd"
|
||||
"second"
|
||||
(get (run "set x first\nset x second") :result))
|
||||
(tcl-eval-assert "semi-x" "1" (tcl-var-get (run "set x 1; set y 2") "x"))
|
||||
(tcl-eval-assert "semi-y" "2" (tcl-var-get (run "set x 1; set y 2") "y"))
|
||||
(tcl-eval-assert
|
||||
"braced-nosub"
|
||||
"$x"
|
||||
(tcl-var-get (run "set x 42\nset y {$x}") "y"))
|
||||
(tcl-eval-assert
|
||||
"concat-word"
|
||||
"foobar"
|
||||
(tcl-var-get (run "set x foo\nset y ${x}bar") "y"))
|
||||
(tcl-eval-assert
|
||||
"set-get"
|
||||
"world"
|
||||
(get (run "set x world\nset x") :result))
|
||||
(tcl-eval-assert
|
||||
"puts-channel"
|
||||
"hello\n"
|
||||
(get (run "puts stdout hello") :output))
|
||||
(ok "if-true" (get (run "set x 0\nif {1} {set x 1}") :result) "1")
|
||||
(ok "if-false" (get (run "set x 0\nif {0} {set x 1}") :result) "0")
|
||||
(ok
|
||||
"if-else-t"
|
||||
(tcl-var-get (run "if {1} {set x yes} else {set x no}") "x")
|
||||
"yes")
|
||||
(ok
|
||||
"if-else-f"
|
||||
(tcl-var-get (run "if {0} {set x yes} else {set x no}") "x")
|
||||
"no")
|
||||
(ok
|
||||
"if-cmp"
|
||||
(tcl-var-get
|
||||
(run "set x 5\nif {$x > 3} {set r big} else {set r small}")
|
||||
"r")
|
||||
"big")
|
||||
(ok
|
||||
"while"
|
||||
(tcl-var-get
|
||||
(run "set i 0\nset s 0\nwhile {$i < 5} {incr i\nincr s $i}")
|
||||
"s")
|
||||
"15")
|
||||
(ok
|
||||
"while-break"
|
||||
(tcl-var-get
|
||||
(run "set i 0\nwhile {1} {incr i\nif {$i == 3} {break}}")
|
||||
"i")
|
||||
"3")
|
||||
(ok
|
||||
"for"
|
||||
(tcl-var-get
|
||||
(run "set s 0\nfor {set i 1} {$i <= 5} {incr i} {incr s $i}")
|
||||
"s")
|
||||
"15")
|
||||
(ok
|
||||
"foreach"
|
||||
(tcl-var-get (run "set s 0\nforeach x {1 2 3 4 5} {incr s $x}") "s")
|
||||
"15")
|
||||
(ok
|
||||
"foreach-list"
|
||||
(get (run "set acc \"\"\nforeach w {hello world} {append acc $w}") :result)
|
||||
"helloworld")
|
||||
(ok
|
||||
"lappend"
|
||||
(tcl-var-get (run "lappend lst a\nlappend lst b\nlappend lst c") "lst")
|
||||
"a b c")
|
||||
(ok?
|
||||
"unset-gone"
|
||||
(let
|
||||
((i (run "set x 42\nunset x")))
|
||||
(let
|
||||
((frame (get i :frame)))
|
||||
(nil? (get (get frame :locals) "x")))))
|
||||
(ok "eval" (tcl-var-get (run "eval {set x hello}") "x") "hello")
|
||||
(ok "expr-precedence" (get (run "expr {3 + 4 * 2}") :result) "11")
|
||||
(ok "expr-parens" (get (run "expr {(3 + 4) * 2}") :result) "14")
|
||||
(ok "expr-unary-minus" (get (run "expr {-5}") :result) "-5")
|
||||
(ok "expr-unary-not-0" (get (run "expr {!0}") :result) "1")
|
||||
(ok "expr-unary-not-1" (get (run "expr {!1}") :result) "0")
|
||||
(ok "expr-power" (get (run "expr {2 ** 10}") :result) "1024")
|
||||
(ok "expr-le" (get (run "expr {3 <= 3}") :result) "1")
|
||||
(ok "expr-ge" (get (run "expr {4 >= 5}") :result) "0")
|
||||
(ok "expr-and" (get (run "expr {1 && 1}") :result) "1")
|
||||
(ok "expr-or" (get (run "expr {0 || 1}") :result) "1")
|
||||
(ok "expr-var-sub" (get (run "set x 7\nexpr {$x * 3}") :result) "21")
|
||||
(ok "expr-abs-neg" (get (run "expr {abs(-3)}") :result) "3")
|
||||
(ok "expr-abs-pos" (get (run "expr {abs(5)}") :result) "5")
|
||||
(ok "expr-pow-fn" (get (run "expr {pow(2, 8)}") :result) "256")
|
||||
(ok "expr-max" (get (run "expr {max(3, 7)}") :result) "7")
|
||||
(ok "expr-min" (get (run "expr {min(3, 7)}") :result) "3")
|
||||
(ok "expr-sqrt-9" (get (run "expr {sqrt(9)}") :result) "3")
|
||||
(ok "expr-sqrt-16" (get (run "expr {sqrt(16)}") :result) "4")
|
||||
(ok "expr-mod" (get (run "expr {17 % 5}") :result) "2")
|
||||
(ok "expr-nospace" (get (run "expr {3+4*2}") :result) "11")
|
||||
(ok "expr-add" (get (run "expr {3 + 4}") :result) "7")
|
||||
(ok "expr-cmp" (get (run "expr {5 > 3}") :result) "1")
|
||||
(ok
|
||||
"break-stops"
|
||||
(tcl-var-get (run "set x 0\nwhile {1} {set x 1\nbreak\nset x 99}") "x")
|
||||
"1")
|
||||
(ok
|
||||
"continue"
|
||||
(tcl-var-get
|
||||
(run
|
||||
"set s 0\nfor {set i 1} {$i <= 5} {incr i} {if {$i == 3} {continue}\nincr s $i}")
|
||||
"s")
|
||||
"12")
|
||||
(ok
|
||||
"switch"
|
||||
(tcl-var-get
|
||||
(run "set x foo\nswitch $x {{foo} {set r yes} {bar} {set r no}}")
|
||||
"r")
|
||||
"yes")
|
||||
(ok
|
||||
"switch-default"
|
||||
(tcl-var-get
|
||||
(run "set x baz\nswitch $x {{foo} {set r yes} default {set r other}}")
|
||||
"r")
|
||||
"other")
|
||||
(ok
|
||||
"nested-if"
|
||||
(tcl-var-get
|
||||
(run
|
||||
"set x 5\nif {$x > 10} {set r big} elseif {$x > 3} {set r mid} else {set r small}")
|
||||
"r")
|
||||
"mid")
|
||||
(ok "str-length" (get (run "string length hello") :result) "5")
|
||||
(ok "str-length-empty" (get (run "string length {}") :result) "0")
|
||||
(ok "str-index" (get (run "string index hello 1") :result) "e")
|
||||
(ok "str-index-oob" (get (run "string index hello 99") :result) "")
|
||||
(ok "str-range" (get (run "string range hello 1 3") :result) "ell")
|
||||
(ok "str-range-clamp" (get (run "string range hello 3 99") :result) "lo")
|
||||
(ok "str-compare-eq" (get (run "string compare abc abc") :result) "0")
|
||||
(ok "str-compare-lt" (get (run "string compare abc abd") :result) "-1")
|
||||
(ok "str-compare-gt" (get (run "string compare b a") :result) "1")
|
||||
(ok "str-match-star" (get (run "string match h*o hello") :result) "1")
|
||||
(ok "str-match-q" (get (run "string match h?llo hello") :result) "1")
|
||||
(ok "str-match-no" (get (run "string match h*x hello") :result) "0")
|
||||
(ok "str-toupper" (get (run "string toupper hello") :result) "HELLO")
|
||||
(ok "str-tolower" (get (run "string tolower WORLD") :result) "world")
|
||||
(ok "str-trim" (get (run "string trim { hi }") :result) "hi")
|
||||
(ok "str-trimleft" (get (run "string trimleft { hi }") :result) "hi ")
|
||||
(ok "str-trimright" (get (run "string trimright { hi }") :result) " hi")
|
||||
(ok "str-trim-chars" (get (run "string trim {xxhelloxx} x") :result) "hello")
|
||||
(ok "str-map" (get (run "string map {a X b Y} {abc}") :result) "XYc")
|
||||
(ok "str-repeat" (get (run "string repeat ab 3") :result) "ababab")
|
||||
(ok "str-first" (get (run "string first ll hello") :result) "2")
|
||||
(ok "str-first-miss" (get (run "string first z hello") :result) "-1")
|
||||
(ok "str-last" (get (run "string last l hello") :result) "3")
|
||||
(ok "str-is-int" (get (run "string is integer 42") :result) "1")
|
||||
(ok "str-is-not-int" (get (run "string is integer foo") :result) "0")
|
||||
(ok "str-is-alpha" (get (run "string is alpha hello") :result) "1")
|
||||
(ok "str-is-alpha-no" (get (run "string is alpha hello1") :result) "0")
|
||||
(ok "str-is-boolean" (get (run "string is boolean true") :result) "1")
|
||||
(ok "str-cat" (get (run "string cat foo bar baz") :result) "foobarbaz")
|
||||
; --- list command tests ---
|
||||
(ok "list-simple" (get (run "list a b c") :result) "a b c")
|
||||
(ok "list-brace-elem" (get (run "list {a b} c") :result) "{a b} c")
|
||||
(ok "list-empty" (get (run "list") :result) "")
|
||||
(ok "lindex-1" (get (run "lindex {a b c} 1") :result) "b")
|
||||
(ok "lindex-0" (get (run "lindex {a b c} 0") :result) "a")
|
||||
(ok "lindex-oob" (get (run "lindex {a b c} 5") :result) "")
|
||||
(ok "lrange" (get (run "lrange {a b c d} 1 2") :result) "b c")
|
||||
(ok "lrange-full" (get (run "lrange {a b c} 0 end") :result) "a b c")
|
||||
(ok "llength" (get (run "llength {a b c}") :result) "3")
|
||||
(ok "llength-empty" (get (run "llength {}") :result) "0")
|
||||
(ok "lreverse" (get (run "lreverse {1 2 3}") :result) "3 2 1")
|
||||
(ok "lsearch-found" (get (run "lsearch {a b c} b") :result) "1")
|
||||
(ok "lsearch-missing" (get (run "lsearch {a b c} z") :result) "-1")
|
||||
(ok "lsearch-exact" (get (run "lsearch -exact {foo bar} foo") :result) "0")
|
||||
(ok "lsort-asc" (get (run "lsort {banana apple cherry}") :result) "apple banana cherry")
|
||||
(ok "lsort-int" (get (run "lsort -integer {10 2 30 5}") :result) "2 5 10 30")
|
||||
(ok "lsort-dec" (get (run "lsort -decreasing {c a b}") :result) "c b a")
|
||||
(ok "lreplace" (get (run "lreplace {a b c d} 1 2 X Y") :result) "a X Y d")
|
||||
(ok "linsert" (get (run "linsert {a b c} 1 X Y") :result) "a X Y b c")
|
||||
(ok "linsert-end" (get (run "linsert {a b} end Z") :result) "a b Z")
|
||||
(ok "concat" (get (run "concat {a b} {c d}") :result) "a b c d")
|
||||
(ok "split-sep" (get (run "split {a:b:c} :") :result) "a b c")
|
||||
(ok "split-ws" (get (run "split {a b c}") :result) "a b c")
|
||||
(ok "join-sep" (get (run "join {a b c} -") :result) "a-b-c")
|
||||
(ok "join-default" (get (run "join {a b c}") :result) "a b c")
|
||||
(ok "list-var" (get (run "set L {x y z}\nllength $L") :result) "3")
|
||||
; --- dict command tests ---
|
||||
(ok "dict-create" (get (run "dict create a 1 b 2") :result) "a 1 b 2")
|
||||
(ok "dict-create-empty" (get (run "dict create") :result) "")
|
||||
(ok "dict-get" (get (run "dict get {a 1 b 2} a") :result) "1")
|
||||
(ok "dict-get-b" (get (run "dict get {a 1 b 2} b") :result) "2")
|
||||
(ok "dict-exists-yes" (get (run "dict exists {a 1 b 2} a") :result) "1")
|
||||
(ok "dict-exists-no" (get (run "dict exists {a 1 b 2} z") :result) "0")
|
||||
(ok "dict-set-new" (get (run "set d {}\ndict set d x 42") :result) "x 42")
|
||||
(ok "dict-set-update" (get (run "set d {a 1 b 2}\ndict set d a 99") :result) "a 99 b 2")
|
||||
(ok "dict-set-stored" (tcl-var-get (run "set d {a 1}\ndict set d b 2") "d") "a 1 b 2")
|
||||
(ok "dict-unset" (get (run "set d {a 1 b 2}\ndict unset d a") :result) "b 2")
|
||||
(ok "dict-unset-stored" (tcl-var-get (run "set d {a 1 b 2}\ndict unset d a") "d") "b 2")
|
||||
(ok "dict-keys" (get (run "dict keys {a 1 b 2}") :result) "a b")
|
||||
(ok "dict-keys-pattern" (get (run "dict keys {abc 1 abd 2 xyz 3} ab*") :result) "abc abd")
|
||||
(ok "dict-values" (get (run "dict values {a 1 b 2}") :result) "1 2")
|
||||
(ok "dict-size" (get (run "dict size {a 1 b 2 c 3}") :result) "3")
|
||||
(ok "dict-size-empty" (get (run "dict size {}") :result) "0")
|
||||
(ok "dict-for" (tcl-var-get (run "set acc {}\ndict for {k v} {a 1 b 2} {append acc $k$v}") "acc") "a1b2")
|
||||
(ok "dict-merge-disjoint" (get (run "dict merge {a 1} {b 2}") :result) "a 1 b 2")
|
||||
(ok "dict-merge-overlap" (get (run "dict merge {a 1 b 2} {b 99}") :result) "a 1 b 99")
|
||||
(ok "dict-incr-existing" (get (run "set d {x 5}\ndict incr d x") :result) "x 6")
|
||||
(ok "dict-incr-delta" (get (run "set d {x 5}\ndict incr d x 3") :result) "x 8")
|
||||
(ok "dict-incr-missing" (get (run "set d {}\ndict incr d n") :result) "n 1")
|
||||
(ok "dict-append" (get (run "set d {x hello}\ndict append d x _hi") :result) "x hello_hi")
|
||||
(ok "dict-append-new" (get (run "set d {}\ndict append d k val") :result) "k val")
|
||||
; --- proc tests ---
|
||||
(ok "proc-basic" (get (run "proc add {a b} {expr {$a + $b}}\nadd 3 4") :result) "7")
|
||||
(ok "proc-return" (get (run "proc greet {name} {set msg \"hi $name\"\nreturn $msg}\ngreet World") :result) "hi World")
|
||||
(ok "proc-factorial" (get (run "proc factorial {n} {if {$n <= 1} {return 1}\nexpr {$n * [factorial [expr {$n - 1}]]}}\nfactorial 5") :result) "120")
|
||||
(ok "proc-args" (get (run "proc sum args {set t 0\nforeach x $args {incr t $x}\nreturn $t}\nsum 1 2 3 4") :result) "10")
|
||||
(ok "proc-isolated" (get (run "set x outer\nproc p {} {set x inner\nreturn $x}\np") :result) "inner")
|
||||
(ok "proc-caller-unchanged" (tcl-var-get (run "set x outer\nproc p {} {set x inner\nreturn $x}\np\nset dummy 1") "x") "outer")
|
||||
(ok "proc-output" (get (run "proc hello {} {puts -nonewline hi}\nhello") :output) "hi")
|
||||
; --- upvar tests ---
|
||||
(ok "upvar-incr" (tcl-var-get (run "proc incr2 {varname} {upvar 1 $varname v\nincr v}\nset counter 10\nincr2 counter\nset counter") "counter") "11")
|
||||
(ok "upvar-double" (tcl-var-get (run "proc double-it {varname} {upvar 1 $varname x\nset x [expr {$x * 2}]}\nset val 5\ndouble-it val\nset val") "val") "10")
|
||||
(ok "upvar-result" (get (run "proc double-it {varname} {upvar 1 $varname x\nset x [expr {$x * 2}]}\nset val 5\ndouble-it val\nset val") :result) "10")
|
||||
; --- uplevel tests ---
|
||||
(ok "uplevel-set" (tcl-var-get (run "proc setvar {name val} {uplevel 1 \"set $name $val\"}\nsetvar x 99\nset x") "x") "99")
|
||||
(ok "uplevel-get" (get (run "proc getvar {name} {uplevel 1 \"set $name\"}\nset y 77\ngetvar y") :result) "77")
|
||||
; --- global tests ---
|
||||
(ok "global-read" (get (run "set g 100\nproc getg {} {global g\nreturn $g}\ngetg") :result) "100")
|
||||
(ok "global-write" (tcl-var-get (run "set g 0\nproc bumping {} {global g\nincr g}\nbumping\nbumping\nset g") "g") "2")
|
||||
; --- info tests ---
|
||||
(ok "info-level-0" (get (run "info level") :result) "0")
|
||||
(ok "info-level-proc" (get (run "proc p {} {info level}\np") :result) "1")
|
||||
(ok "info-procs" (let ((r (get (run "proc myfn {} {}\ninfo procs") :result))) (contains? (tcl-list-split r) "myfn")) true)
|
||||
(ok "info-args" (get (run "proc add {a b} {expr {$a+$b}}\ninfo args add") :result) "a b")
|
||||
(ok "info-commands-has-set" (let ((r (get (run "info commands") :result))) (contains? (tcl-list-split r) "set")) true)
|
||||
; --- classic programs ---
|
||||
(ok
|
||||
"classic-for-each-line"
|
||||
(get
|
||||
(run "proc for-each-line {var lines body} {\n foreach item $lines {\n uplevel 1 [list set $var $item]\n uplevel 1 $body\n }\n}\nset total 0\nfor-each-line line {hello world foo} {\n incr total [string length $line]\n}\nset total")
|
||||
:result)
|
||||
"13")
|
||||
(ok
|
||||
"classic-assert"
|
||||
(get
|
||||
(run "proc assert {expr_str} {\n set result [uplevel 1 [list expr $expr_str]]\n if {!$result} {\n error \"Assertion failed: $expr_str\"\n }\n}\nset x 42\nassert {$x == 42}\nassert {$x > 0}\nset x 10\nassert {$x < 100}\nset x")
|
||||
:result)
|
||||
"10")
|
||||
(ok
|
||||
"classic-with-temp-var"
|
||||
(get
|
||||
(run "proc with-temp-var {varname tempval body} {\n upvar 1 $varname v\n set saved $v\n set v $tempval\n uplevel 1 $body\n set v $saved\n}\nset x 100\nwith-temp-var x 999 {\n set captured $x\n}\nlist $x $captured")
|
||||
:result)
|
||||
"100 999")
|
||||
(ok
|
||||
"array-set-get"
|
||||
(get
|
||||
(run "array set a {x 1 y 2 z 3}; array get a x")
|
||||
:result)
|
||||
"x 1")
|
||||
(ok
|
||||
"array-names"
|
||||
(get
|
||||
(run "array set a {p 10 q 20}; lsort [array names a]")
|
||||
:result)
|
||||
"p q")
|
||||
(ok
|
||||
"array-size"
|
||||
(get
|
||||
(run "array set a {x 1 y 2 z 3}; array size a")
|
||||
:result)
|
||||
"3")
|
||||
(ok
|
||||
"array-exists-true"
|
||||
(get
|
||||
(run "array set a {x 1}; array exists a")
|
||||
:result)
|
||||
"1")
|
||||
(ok
|
||||
"array-exists-false"
|
||||
(get
|
||||
(run "array exists nosucharray")
|
||||
:result)
|
||||
"0")
|
||||
(ok
|
||||
"array-unset-key"
|
||||
(get
|
||||
(run "array set a {x 1 y 2 z 3}; array unset a y; lsort [array names a]")
|
||||
:result)
|
||||
"x z")
|
||||
(ok
|
||||
"array-scalar-access"
|
||||
(get
|
||||
(run "set a(foo) hello; set a(bar) world; set a(foo)")
|
||||
:result)
|
||||
"hello")
|
||||
(ok
|
||||
"array-get-all"
|
||||
(get
|
||||
(run "set a(k) v; set pairs [array get a]; llength $pairs")
|
||||
:result)
|
||||
"2")
|
||||
(dict
|
||||
"passed"
|
||||
tcl-eval-pass
|
||||
"failed"
|
||||
tcl-eval-fail
|
||||
"failures"
|
||||
tcl-eval-failures)))
|
||||
196
lib/tcl/tests/idioms.sx
Normal file
196
lib/tcl/tests/idioms.sx
Normal file
@@ -0,0 +1,196 @@
|
||||
; Tcl-on-SX idiom corpus (Phase 6)
|
||||
; Classic Tcl idioms covering lists, dicts, procs, patterns
|
||||
(define tcl-idiom-pass 0)
|
||||
(define tcl-idiom-fail 0)
|
||||
(define tcl-idiom-failures (list))
|
||||
|
||||
(define
|
||||
tcl-idiom-assert
|
||||
(fn
|
||||
(label expected actual)
|
||||
(if
|
||||
(equal? expected actual)
|
||||
(set! tcl-idiom-pass (+ tcl-idiom-pass 1))
|
||||
(begin
|
||||
(set! tcl-idiom-fail (+ tcl-idiom-fail 1))
|
||||
(append!
|
||||
tcl-idiom-failures
|
||||
(str label ": expected=" (str expected) " got=" (str actual)))))))
|
||||
|
||||
(define
|
||||
tcl-run-idiom-tests
|
||||
(fn
|
||||
()
|
||||
(set! tcl-idiom-pass 0)
|
||||
(set! tcl-idiom-fail 0)
|
||||
(set! tcl-idiom-failures (list))
|
||||
(define interp (fn () (make-default-tcl-interp)))
|
||||
(define run (fn (src) (tcl-eval-string (interp) src)))
|
||||
(define
|
||||
ok
|
||||
(fn (label actual expected) (tcl-idiom-assert label expected actual)))
|
||||
(ok
|
||||
"idiom-lmap"
|
||||
(get
|
||||
(run
|
||||
"set result {}\nforeach x {1 2 3} { lappend result [expr {$x * $x}] }\nset result")
|
||||
:result)
|
||||
"1 4 9")
|
||||
(ok
|
||||
"idiom-flatten"
|
||||
(get
|
||||
(run
|
||||
"proc flatten {lst} { set out {}\n foreach item $lst {\n if {[llength $item] > 1} {\n foreach sub [flatten $item] { lappend out $sub }\n } else {\n lappend out $item\n }\n }\n return $out\n}\nflatten {1 {2 3} {4 {5 6}}}")
|
||||
:result)
|
||||
"1 2 3 4 5 6")
|
||||
(ok
|
||||
"idiom-string-builder"
|
||||
(get
|
||||
(run
|
||||
"set buf \"\"\nforeach w {Hello World Tcl} { append buf $w \" \" }\nstring trimright $buf")
|
||||
:result)
|
||||
"Hello World Tcl")
|
||||
(ok
|
||||
"idiom-default-param"
|
||||
(get (run "if {![info exists x]} { set x 42 }\nset x") :result)
|
||||
"42")
|
||||
(ok
|
||||
"idiom-alist-lookup"
|
||||
(get
|
||||
(run
|
||||
"set keys {a b c}\nset vals {10 20 30}\nset idx [lsearch $keys b]\nlindex $vals $idx")
|
||||
:result)
|
||||
"20")
|
||||
(ok
|
||||
"idiom-optional-args"
|
||||
(get
|
||||
(run
|
||||
"proc greet {name args} {\n set greeting \"Hello\"\n if {[llength $args] > 0} { set greeting [lindex $args 0] }\n return \"$greeting $name\"\n}\ngreet World Hi")
|
||||
:result)
|
||||
"Hi World")
|
||||
(ok
|
||||
"idiom-dict-builder"
|
||||
(get
|
||||
(run
|
||||
"proc build-dict {args} { dict create {*}$args }\ndict get [build-dict name Alice age 30] name")
|
||||
:result)
|
||||
"Alice")
|
||||
(ok
|
||||
"idiom-loop-with-index"
|
||||
(get
|
||||
(run "set i 0\nforeach x {a b c} { set arr($i) $x; incr i }\nset arr(1)")
|
||||
:result)
|
||||
"b")
|
||||
(ok
|
||||
"idiom-string-reverse"
|
||||
(get
|
||||
(run
|
||||
"set s hello\nset chars [split $s \"\"]\nset rev [lreverse $chars]\njoin $rev \"\"")
|
||||
:result)
|
||||
"olleh")
|
||||
(ok "idiom-number-format" (get (run "format \"%05d\" 42") :result) "00042")
|
||||
(ok
|
||||
"idiom-dict-comprehension"
|
||||
(get
|
||||
(run
|
||||
"set squares {}\nforeach n {1 2 3 4} { dict set squares $n [expr {$n * $n}] }\ndict get $squares 3")
|
||||
:result)
|
||||
"9")
|
||||
(ok
|
||||
"idiom-stack"
|
||||
(get
|
||||
(run
|
||||
"proc stack-push {stackvar val} { upvar $stackvar s; lappend s $val }\nproc stack-pop {stackvar} { upvar $stackvar s; set val [lindex $s end]; set s [lrange $s 0 end-1]; return $val }\nset stk {}\nstack-push stk 10\nstack-push stk 20\nstack-push stk 30\nstack-pop stk")
|
||||
:result)
|
||||
"30")
|
||||
(ok
|
||||
"idiom-queue"
|
||||
(get
|
||||
(run
|
||||
"proc q-enq {qvar val} { upvar $qvar q; lappend q $val }\nproc q-deq {qvar} { upvar $qvar q; set val [lindex $q 0]; set q [lrange $q 1 end]; return $val }\nset q {}\nq-enq q alpha\nq-enq q beta\nq-enq q gamma\nq-deq q")
|
||||
:result)
|
||||
"alpha")
|
||||
(ok
|
||||
"idiom-pipeline"
|
||||
(get
|
||||
(run
|
||||
"proc double {x} { expr {$x * 2} }\nproc add1 {x} { expr {$x + 1} }\nproc pipeline {val procs} { foreach p $procs { set val [$p $val] }; return $val }\npipeline 5 {double add1 double}")
|
||||
:result)
|
||||
"22")
|
||||
(ok
|
||||
"idiom-memoize"
|
||||
(get
|
||||
(run
|
||||
"set cache {}\nproc cached-square {n} { global cache\n if {[dict exists $cache $n]} { return [dict get $cache $n] }\n set r [expr {$n * $n}]\n dict set cache $n $r\n return $r\n}\nset a [cached-square 7]\nset b [cached-square 7]\nset c [cached-square 8]\nexpr {$a == $b && $c == 64}")
|
||||
:result)
|
||||
"1")
|
||||
(ok
|
||||
"idiom-recursive-eval"
|
||||
(get
|
||||
(run
|
||||
"proc calc {expr} { return [::tcl::mathop::+ 0 [expr $expr]] }\nexpr {3 + 4 * 2}")
|
||||
:result)
|
||||
"11")
|
||||
(ok
|
||||
"idiom-dict-for"
|
||||
(get
|
||||
(run
|
||||
"set d [dict create a 1 b 2 c 3]\nset total 0\ndict for {k v} $d { incr total $v }\nset total")
|
||||
:result)
|
||||
"6")
|
||||
(ok
|
||||
"idiom-find-max"
|
||||
(get
|
||||
(run
|
||||
"proc list-max {lst} {\n set m [lindex $lst 0]\n foreach x $lst { if {$x > $m} { set m $x } }\n return $m\n}\nlist-max {3 1 4 1 5 9 2 6}")
|
||||
:result)
|
||||
"9")
|
||||
(ok
|
||||
"idiom-filter-list"
|
||||
(get
|
||||
(run
|
||||
"proc list-filter {lst pred} {\n set out {}\n foreach x $lst { if {[$pred $x]} { lappend out $x } }\n return $out\n}\nproc is-even {n} { expr {$n % 2 == 0} }\nlist-filter {1 2 3 4 5 6} is-even")
|
||||
:result)
|
||||
"2 4 6")
|
||||
(ok
|
||||
"idiom-zip"
|
||||
(get
|
||||
(run
|
||||
"proc zip {a b} {\n set out {}\n set n [llength $a]\n for {set i 0} {$i < $n} {incr i} {\n lappend out [lindex $a $i]\n lappend out [lindex $b $i]\n }\n return $out\n}\nzip {1 2 3} {a b c}")
|
||||
:result)
|
||||
"1 a 2 b 3 c")
|
||||
(ok
|
||||
"env-lookup-basic"
|
||||
(env-lookup (let ((x 42)) (current-env)) "x")
|
||||
42)
|
||||
(ok
|
||||
"env-lookup-missing"
|
||||
(env-lookup (let ((x 42)) (current-env)) "z")
|
||||
nil)
|
||||
(ok
|
||||
"env-extend-lookup"
|
||||
(let
|
||||
((e (let ((x 5)) (current-env))))
|
||||
(env-lookup (env-extend e "y" 10) "y"))
|
||||
10)
|
||||
(ok
|
||||
"eval-in-env-parent"
|
||||
(let
|
||||
((x 5))
|
||||
(eval-in-env (env-extend (current-env) "y" 10) (quote (+ x y))))
|
||||
15)
|
||||
(ok
|
||||
"eval-in-env-multi"
|
||||
(let
|
||||
((base (current-env)))
|
||||
(eval-in-env
|
||||
(env-extend (env-extend base "a" 3) "b" 7)
|
||||
(quote (* a b))))
|
||||
21)
|
||||
(dict
|
||||
"passed"
|
||||
tcl-idiom-pass
|
||||
"failed"
|
||||
tcl-idiom-fail
|
||||
"failures"
|
||||
tcl-idiom-failures)))
|
||||
147
lib/tcl/tests/namespace.sx
Normal file
147
lib/tcl/tests/namespace.sx
Normal file
@@ -0,0 +1,147 @@
|
||||
; Tcl-on-SX namespace tests (Phase 5)
|
||||
(define tcl-ns-pass 0)
|
||||
(define tcl-ns-fail 0)
|
||||
(define tcl-ns-failures (list))
|
||||
|
||||
(define
|
||||
tcl-ns-assert
|
||||
(fn
|
||||
(label expected actual)
|
||||
(if
|
||||
(equal? expected actual)
|
||||
(set! tcl-ns-pass (+ tcl-ns-pass 1))
|
||||
(begin
|
||||
(set! tcl-ns-fail (+ tcl-ns-fail 1))
|
||||
(append!
|
||||
tcl-ns-failures
|
||||
(str label ": expected=" (str expected) " got=" (str actual)))))))
|
||||
|
||||
(define
|
||||
tcl-run-namespace-tests
|
||||
(fn
|
||||
()
|
||||
(set! tcl-ns-pass 0)
|
||||
(set! tcl-ns-fail 0)
|
||||
(set! tcl-ns-failures (list))
|
||||
(define interp (fn () (make-default-tcl-interp)))
|
||||
(define run (fn (src) (tcl-eval-string (interp) src)))
|
||||
(define
|
||||
ok
|
||||
(fn (label actual expected) (tcl-ns-assert label expected actual)))
|
||||
(define
|
||||
ok?
|
||||
(fn (label condition) (tcl-ns-assert label true condition)))
|
||||
|
||||
; --- namespace current ---
|
||||
(ok "ns-current-global"
|
||||
(get (run "namespace current") :result)
|
||||
"::")
|
||||
|
||||
; --- namespace eval defines proc ---
|
||||
(ok "ns-eval-proc-result"
|
||||
(get (run "namespace eval myns { proc foo {} { return bar } }\nmyns::foo") :result)
|
||||
"bar")
|
||||
|
||||
; --- fully qualified call ---
|
||||
(ok "ns-qualified-call"
|
||||
(get (run "namespace eval myns { proc greet {name} { return \"hello $name\" } }\n::myns::greet World") :result)
|
||||
"hello World")
|
||||
|
||||
; --- namespace current inside eval ---
|
||||
(ok "ns-current-inside"
|
||||
(get (run "namespace eval myns { namespace current }") :result)
|
||||
"::myns")
|
||||
|
||||
; --- namespace current restored after eval ---
|
||||
(ok "ns-current-restored"
|
||||
(get (run "namespace eval myns { set x 1 }\nnamespace current") :result)
|
||||
"::")
|
||||
|
||||
; --- relative call from within namespace ---
|
||||
(ok "ns-relative-call"
|
||||
(get (run "namespace eval math {\n proc double {x} { expr {$x * 2} }\n proc quad {x} { double [double $x] }\n}\nmath::quad 3") :result)
|
||||
"12")
|
||||
|
||||
; --- proc defined as qualified name inside namespace eval ---
|
||||
(ok "ns-qualified-proc-name"
|
||||
(get (run "namespace eval utils { proc ::utils::helper {x} { return $x } }\n::utils::helper done") :result)
|
||||
"done")
|
||||
|
||||
; --- namespace exists ---
|
||||
(ok "ns-exists-yes"
|
||||
(get (run "namespace eval testns { proc p {} {} }\nnamespace exists testns") :result)
|
||||
"1")
|
||||
|
||||
(ok "ns-exists-no"
|
||||
(get (run "namespace exists nosuchns") :result)
|
||||
"0")
|
||||
|
||||
(ok "ns-exists-global"
|
||||
(get (run "proc top {} {}\nnamespace exists ::") :result)
|
||||
"1")
|
||||
|
||||
; --- namespace delete ---
|
||||
(ok "ns-delete-removes"
|
||||
(get (run "namespace eval todel { proc pp {} { return yes } }\nnamespace delete todel\nnamespace exists todel") :result)
|
||||
"0")
|
||||
|
||||
; --- namespace which ---
|
||||
(ok "ns-which-found"
|
||||
(get (run "namespace eval wns { proc wfn {} {} }\nnamespace which -command wns::wfn") :result)
|
||||
"::wns::wfn")
|
||||
|
||||
(ok "ns-which-not-found"
|
||||
(get (run "namespace which -command nosuchfn") :result)
|
||||
"")
|
||||
|
||||
; --- namespace ensemble create auto-map ---
|
||||
(ok "ns-ensemble-add"
|
||||
(get (run "namespace eval mymath {\n proc add {a b} { expr {$a + $b} }\n proc mul {a b} { expr {$a * $b} }\n namespace ensemble create\n}\nmymath add 3 4") :result)
|
||||
"7")
|
||||
|
||||
(ok "ns-ensemble-mul"
|
||||
(get (run "namespace eval mymath {\n proc add {a b} { expr {$a + $b} }\n proc mul {a b} { expr {$a * $b} }\n namespace ensemble create\n}\nmymath mul 3 4") :result)
|
||||
"12")
|
||||
|
||||
; --- namespace ensemble with -map ---
|
||||
(ok "ns-ensemble-map"
|
||||
(get (run "namespace eval ops {\n proc do-add {a b} { expr {$a + $b} }\n namespace ensemble create -map {plus ::ops::do-add}\n}\nops plus 5 6") :result)
|
||||
"11")
|
||||
|
||||
; --- proc inside namespace eval with args ---
|
||||
(ok "ns-proc-args"
|
||||
(get (run "namespace eval calc {\n proc sum {a b c} { expr {$a + $b + $c} }\n}\ncalc::sum 1 2 3") :result)
|
||||
"6")
|
||||
|
||||
; --- info procs inside namespace ---
|
||||
(ok? "ns-info-procs-in-ns"
|
||||
(let
|
||||
((r (get (run "namespace eval foo { proc bar {} {} }\nnamespace eval foo { info procs }") :result)))
|
||||
(contains? (tcl-list-split r) "bar")))
|
||||
|
||||
; --- variable inside namespace eval ---
|
||||
(ok "ns-variable-inside"
|
||||
(get (run "namespace eval storage {\n variable count 0\n proc bump {} { global count\n incr count\n return $count }\n}\n::storage::bump\n::storage::bump") :result)
|
||||
"2")
|
||||
|
||||
; --- nested namespaces ---
|
||||
(ok "ns-nested"
|
||||
(get (run "namespace eval outer {\n namespace eval inner {\n proc greet {} { return nested }\n }\n}\n::outer::inner::greet") :result)
|
||||
"nested")
|
||||
|
||||
; --- namespace eval accumulates procs ---
|
||||
(ok "ns-eval-accumulate"
|
||||
(get (run "namespace eval acc { proc f1 {} { return one } }\nnamespace eval acc { proc f2 {} { return two } }\nacc::f1") :result)
|
||||
"one")
|
||||
|
||||
(ok "ns-eval-accumulate-2"
|
||||
(get (run "namespace eval acc { proc f1 {} { return one } }\nnamespace eval acc { proc f2 {} { return two } }\nacc::f2") :result)
|
||||
"two")
|
||||
|
||||
(dict
|
||||
"passed"
|
||||
tcl-ns-pass
|
||||
"failed"
|
||||
tcl-ns-fail
|
||||
"failures"
|
||||
tcl-ns-failures)))
|
||||
186
lib/tcl/tests/parse.sx
Normal file
186
lib/tcl/tests/parse.sx
Normal file
@@ -0,0 +1,186 @@
|
||||
(define tcl-parse-pass 0)
|
||||
(define tcl-parse-fail 0)
|
||||
(define tcl-parse-failures (list))
|
||||
|
||||
(define tcl-assert
|
||||
(fn (label expected actual)
|
||||
(if (= expected actual)
|
||||
(set! tcl-parse-pass (+ tcl-parse-pass 1))
|
||||
(begin
|
||||
(set! tcl-parse-fail (+ tcl-parse-fail 1))
|
||||
(append! tcl-parse-failures
|
||||
(str label ": expected=" (str expected) " got=" (str actual)))))))
|
||||
|
||||
(define tcl-first-cmd
|
||||
(fn (src) (nth (tcl-tokenize src) 0)))
|
||||
|
||||
(define tcl-cmd-words
|
||||
(fn (src) (get (tcl-first-cmd src) :words)))
|
||||
|
||||
(define tcl-word
|
||||
(fn (src wi) (nth (tcl-cmd-words src) wi)))
|
||||
|
||||
(define tcl-parts
|
||||
(fn (src wi) (get (tcl-word src wi) :parts)))
|
||||
|
||||
(define tcl-part
|
||||
(fn (src wi pi) (nth (tcl-parts src wi) pi)))
|
||||
|
||||
(define tcl-run-parse-tests
|
||||
(fn ()
|
||||
(set! tcl-parse-pass 0)
|
||||
(set! tcl-parse-fail 0)
|
||||
(set! tcl-parse-failures (list))
|
||||
|
||||
; empty / whitespace-only
|
||||
(tcl-assert "empty" 0 (len (tcl-tokenize "")))
|
||||
(tcl-assert "ws-only" 0 (len (tcl-tokenize " ")))
|
||||
(tcl-assert "nl-only" 0 (len (tcl-tokenize "\n\n")))
|
||||
|
||||
; single command word count
|
||||
(tcl-assert "1word" 1 (len (tcl-cmd-words "set")))
|
||||
(tcl-assert "3words" 3 (len (tcl-cmd-words "set x 1")))
|
||||
(tcl-assert "4words" 4 (len (tcl-cmd-words "set a b c")))
|
||||
|
||||
; word type — bare word is compound
|
||||
(tcl-assert "bare-type" "compound" (get (tcl-word "set x 1" 0) :type))
|
||||
(tcl-assert "bare-quoted" false (get (tcl-word "set x 1" 0) :quoted))
|
||||
(tcl-assert "bare-part-type" "text" (get (tcl-part "set x 1" 0 0) :type))
|
||||
(tcl-assert "bare-part-val" "set" (get (tcl-part "set x 1" 0 0) :value))
|
||||
(tcl-assert "bare-part2-val" "x" (get (tcl-part "set x 1" 1 0) :value))
|
||||
(tcl-assert "bare-part3-val" "1" (get (tcl-part "set x 1" 2 0) :value))
|
||||
|
||||
; multiple commands
|
||||
(tcl-assert "semi-sep" 2 (len (tcl-tokenize "set x 1; set y 2")))
|
||||
(tcl-assert "nl-sep" 2 (len (tcl-tokenize "set x 1\nset y 2")))
|
||||
(tcl-assert "multi-nl" 3 (len (tcl-tokenize "a\nb\nc")))
|
||||
|
||||
; comments
|
||||
(tcl-assert "comment-only" 0 (len (tcl-tokenize "# comment")))
|
||||
(tcl-assert "comment-nl" 0 (len (tcl-tokenize "# comment\n")))
|
||||
(tcl-assert "comment-then-cmd" 1 (len (tcl-tokenize "# comment\nset x 1")))
|
||||
(tcl-assert "semi-then-comment" 1 (len (tcl-tokenize "set x 1; # comment")))
|
||||
|
||||
; brace-quoted words
|
||||
(tcl-assert "brace-type" "braced" (get (tcl-word "{hello}" 0) :type))
|
||||
(tcl-assert "brace-value" "hello" (get (tcl-word "{hello}" 0) :value))
|
||||
(tcl-assert "brace-spaces" "hello world" (get (tcl-word "{hello world}" 0) :value))
|
||||
(tcl-assert "brace-nested" "a {b} c" (get (tcl-word "{a {b} c}" 0) :value))
|
||||
(tcl-assert "brace-no-var-sub" "hello $x" (get (tcl-word "{hello $x}" 0) :value))
|
||||
(tcl-assert "brace-no-cmd-sub" "[expr 1]" (get (tcl-word "{[expr 1]}" 0) :value))
|
||||
|
||||
; double-quoted words
|
||||
(tcl-assert "dq-type" "compound" (get (tcl-word "\"hello\"" 0) :type))
|
||||
(tcl-assert "dq-quoted" true (get (tcl-word "\"hello\"" 0) :quoted))
|
||||
(tcl-assert "dq-literal" "hello" (get (tcl-part "\"hello\"" 0 0) :value))
|
||||
|
||||
; variable substitution in bare word
|
||||
(tcl-assert "var-type" "var" (get (tcl-part "$x" 0 0) :type))
|
||||
(tcl-assert "var-name" "x" (get (tcl-part "$x" 0 0) :name))
|
||||
(tcl-assert "var-long" "long_name" (get (tcl-part "$long_name" 0 0) :name))
|
||||
|
||||
; ${name} form
|
||||
(tcl-assert "var-brace-type" "var" (get (tcl-part "${x}" 0 0) :type))
|
||||
(tcl-assert "var-brace-name" "x" (get (tcl-part "${x}" 0 0) :name))
|
||||
|
||||
; array variable substitution
|
||||
(tcl-assert "arr-type" "var-arr" (get (tcl-part "$arr(key)" 0 0) :type))
|
||||
(tcl-assert "arr-name" "arr" (get (tcl-part "$arr(key)" 0 0) :name))
|
||||
(tcl-assert "arr-key-len" 1 (len (get (tcl-part "$arr(key)" 0 0) :key)))
|
||||
(tcl-assert "arr-key-text" "key"
|
||||
(get (nth (get (tcl-part "$arr(key)" 0 0) :key) 0) :value))
|
||||
|
||||
; command substitution
|
||||
(tcl-assert "cmd-type" "cmd" (get (tcl-part "[expr 1+1]" 0 0) :type))
|
||||
(tcl-assert "cmd-src" "expr 1+1" (get (tcl-part "[expr 1+1]" 0 0) :src))
|
||||
|
||||
; nested command substitution
|
||||
(tcl-assert "cmd-nested-src" "expr [string length x]"
|
||||
(get (tcl-part "[expr [string length x]]" 0 0) :src))
|
||||
|
||||
; backslash substitution in double-quoted word
|
||||
(let ((ps (tcl-parts "\"a\\nb\"" 0)))
|
||||
(begin
|
||||
(tcl-assert "bs-n-part0" "a" (get (nth ps 0) :value))
|
||||
(tcl-assert "bs-n-part1" "\n" (get (nth ps 1) :value))
|
||||
(tcl-assert "bs-n-part2" "b" (get (nth ps 2) :value))))
|
||||
|
||||
(let ((ps (tcl-parts "\"a\\tb\"" 0)))
|
||||
(tcl-assert "bs-t-part1" "\t" (get (nth ps 1) :value)))
|
||||
|
||||
(let ((ps (tcl-parts "\"a\\\\b\"" 0)))
|
||||
(tcl-assert "bs-bs-part1" "\\" (get (nth ps 1) :value)))
|
||||
|
||||
; mixed word: text + var + text in double-quoted
|
||||
(let ((ps (tcl-parts "\"hello $name!\"" 0)))
|
||||
(begin
|
||||
(tcl-assert "mixed-text0" "hello " (get (nth ps 0) :value))
|
||||
(tcl-assert "mixed-var1-type" "var" (get (nth ps 1) :type))
|
||||
(tcl-assert "mixed-var1-name" "name" (get (nth ps 1) :name))
|
||||
(tcl-assert "mixed-text2" "!" (get (nth ps 2) :value))))
|
||||
|
||||
; {*} expansion
|
||||
(tcl-assert "expand-type" "expand" (get (tcl-word "{*}$list" 0) :type))
|
||||
|
||||
; line continuation between words
|
||||
(tcl-assert "cont-words" 3 (len (tcl-cmd-words "set x \\\n 1")))
|
||||
|
||||
; continuation — third command word is correct
|
||||
(tcl-assert "cont-word2-val" "1"
|
||||
(get (tcl-part "set x \\\n 1" 2 0) :value))
|
||||
|
||||
|
||||
; --- parser helpers ---
|
||||
; tcl-parse is an alias for tcl-tokenize
|
||||
(tcl-assert "parse-cmd-count" 1 (len (tcl-parse "set x 1")))
|
||||
(tcl-assert "parse-2cmds" 2 (len (tcl-parse "set x 1; set y 2")))
|
||||
|
||||
; tcl-cmd-len
|
||||
(tcl-assert "cmd-len-3" 3 (tcl-cmd-len (nth (tcl-parse "set x 1") 0)))
|
||||
(tcl-assert "cmd-len-1" 1 (tcl-cmd-len (nth (tcl-parse "puts") 0)))
|
||||
|
||||
; tcl-word-simple? on braced word
|
||||
(tcl-assert "simple-braced" true
|
||||
(tcl-word-simple? (nth (get (nth (tcl-parse "{hello}") 0) :words) 0)))
|
||||
|
||||
; tcl-word-simple? on bare word with no subs
|
||||
(tcl-assert "simple-bare" true
|
||||
(tcl-word-simple? (nth (get (nth (tcl-parse "hello") 0) :words) 0)))
|
||||
|
||||
; tcl-word-simple? on word containing a var sub — false
|
||||
(tcl-assert "simple-var-false" false
|
||||
(tcl-word-simple? (nth (get (nth (tcl-parse "$x") 0) :words) 0)))
|
||||
|
||||
; tcl-word-simple? on word containing a cmd sub — false
|
||||
(tcl-assert "simple-cmd-false" false
|
||||
(tcl-word-simple? (nth (get (nth (tcl-parse "[expr 1]") 0) :words) 0)))
|
||||
|
||||
; tcl-word-literal on braced word
|
||||
(tcl-assert "lit-braced" "hello world"
|
||||
(tcl-word-literal (nth (get (nth (tcl-parse "{hello world}") 0) :words) 0)))
|
||||
|
||||
; tcl-word-literal on bare word
|
||||
(tcl-assert "lit-bare" "hello"
|
||||
(tcl-word-literal (nth (get (nth (tcl-parse "hello") 0) :words) 0)))
|
||||
|
||||
; tcl-word-literal on word with var sub returns nil
|
||||
(tcl-assert "lit-var-nil" nil
|
||||
(tcl-word-literal (nth (get (nth (tcl-parse "$x") 0) :words) 0)))
|
||||
|
||||
; tcl-nth-literal
|
||||
(tcl-assert "nth-lit-0" "set"
|
||||
(tcl-nth-literal (nth (tcl-parse "set x 1") 0) 0))
|
||||
(tcl-assert "nth-lit-1" "x"
|
||||
(tcl-nth-literal (nth (tcl-parse "set x 1") 0) 1))
|
||||
(tcl-assert "nth-lit-2" "1"
|
||||
(tcl-nth-literal (nth (tcl-parse "set x 1") 0) 2))
|
||||
|
||||
; tcl-nth-literal returns nil when word has subs
|
||||
(tcl-assert "nth-lit-nil" nil
|
||||
(tcl-nth-literal (nth (tcl-parse "set x $y") 0) 2))
|
||||
|
||||
|
||||
(dict
|
||||
"passed" tcl-parse-pass
|
||||
"failed" tcl-parse-fail
|
||||
"failures" tcl-parse-failures)))
|
||||
14
lib/tcl/tests/programs/assert.tcl
Normal file
14
lib/tcl/tests/programs/assert.tcl
Normal file
@@ -0,0 +1,14 @@
|
||||
# expected: 10
|
||||
proc assert {expr_str} {
|
||||
set result [uplevel 1 [list expr $expr_str]]
|
||||
if {!$result} {
|
||||
error "Assertion failed: $expr_str"
|
||||
}
|
||||
}
|
||||
|
||||
set x 42
|
||||
assert {$x == 42}
|
||||
assert {$x > 0}
|
||||
set x 10
|
||||
assert {$x < 100}
|
||||
set x
|
||||
22
lib/tcl/tests/programs/event-loop.tcl
Normal file
22
lib/tcl/tests/programs/event-loop.tcl
Normal file
@@ -0,0 +1,22 @@
|
||||
# expected: done
|
||||
# Cooperative scheduler demo using coroutines (generator style)
|
||||
# coroutine eagerly collects all yields; invoking the coroutine name pops values
|
||||
|
||||
proc counter {n max} {
|
||||
while {$n < $max} {
|
||||
yield $n
|
||||
incr n
|
||||
}
|
||||
yield done
|
||||
}
|
||||
|
||||
coroutine gen1 counter 0 3
|
||||
|
||||
# gen1 yields: 0 1 2 done
|
||||
set out {}
|
||||
for {set i 0} {$i < 4} {incr i} {
|
||||
lappend out [gen1]
|
||||
}
|
||||
|
||||
# last val is "done"
|
||||
lindex $out 3
|
||||
14
lib/tcl/tests/programs/for-each-line.tcl
Normal file
14
lib/tcl/tests/programs/for-each-line.tcl
Normal file
@@ -0,0 +1,14 @@
|
||||
# expected: 13
|
||||
proc for-each-line {var lines body} {
|
||||
foreach item $lines {
|
||||
uplevel 1 [list set $var $item]
|
||||
uplevel 1 $body
|
||||
}
|
||||
}
|
||||
|
||||
# Usage: accumulate lengths of each "line"
|
||||
set total 0
|
||||
for-each-line line {hello world foo} {
|
||||
incr total [string length $line]
|
||||
}
|
||||
set total
|
||||
14
lib/tcl/tests/programs/with-temp-var.tcl
Normal file
14
lib/tcl/tests/programs/with-temp-var.tcl
Normal file
@@ -0,0 +1,14 @@
|
||||
# expected: 100 999
|
||||
proc with-temp-var {varname tempval body} {
|
||||
upvar 1 $varname v
|
||||
set saved $v
|
||||
set v $tempval
|
||||
uplevel 1 $body
|
||||
set v $saved
|
||||
}
|
||||
|
||||
set x 100
|
||||
with-temp-var x 999 {
|
||||
set captured $x
|
||||
}
|
||||
list $x $captured
|
||||
308
lib/tcl/tokenizer.sx
Normal file
308
lib/tcl/tokenizer.sx
Normal file
@@ -0,0 +1,308 @@
|
||||
(define tcl-ws? (fn (c) (or (= c " ") (= c "\t") (= c "\r"))))
|
||||
|
||||
(define tcl-alpha?
|
||||
(fn (c)
|
||||
(and
|
||||
(not (= c nil))
|
||||
(or (and (>= c "a") (<= c "z")) (and (>= c "A") (<= c "Z"))))))
|
||||
|
||||
(define tcl-digit?
|
||||
(fn (c) (and (not (= c nil)) (>= c "0") (<= c "9"))))
|
||||
|
||||
(define tcl-ident-start?
|
||||
(fn (c) (or (tcl-alpha? c) (= c "_"))))
|
||||
|
||||
(define tcl-ident-char?
|
||||
(fn (c) (or (tcl-ident-start? c) (tcl-digit? c))))
|
||||
|
||||
(define tcl-tokenize
|
||||
(fn (src)
|
||||
(let ((pos 0) (src-len (len src)) (commands (list)))
|
||||
|
||||
(define char-at
|
||||
(fn (off)
|
||||
(if (< (+ pos off) src-len) (nth src (+ pos off)) nil)))
|
||||
|
||||
(define cur (fn () (char-at 0)))
|
||||
|
||||
(define advance! (fn (n) (set! pos (+ pos n))))
|
||||
|
||||
(define skip-ws!
|
||||
(fn ()
|
||||
(when (tcl-ws? (cur))
|
||||
(begin (advance! 1) (skip-ws!)))))
|
||||
|
||||
(define skip-to-eol!
|
||||
(fn ()
|
||||
(when (and (< pos src-len) (not (= (cur) "\n")))
|
||||
(begin (advance! 1) (skip-to-eol!)))))
|
||||
|
||||
(define skip-brace-content!
|
||||
(fn (d)
|
||||
(when (and (< pos src-len) (> d 0))
|
||||
(cond
|
||||
((= (cur) "{") (begin (advance! 1) (skip-brace-content! (+ d 1))))
|
||||
((= (cur) "}") (begin (advance! 1) (skip-brace-content! (- d 1))))
|
||||
(else (begin (advance! 1) (skip-brace-content! d)))))))
|
||||
|
||||
(define skip-dquote-content!
|
||||
(fn ()
|
||||
(when (and (< pos src-len) (not (= (cur) "\"")))
|
||||
(begin
|
||||
(when (= (cur) "\\") (advance! 1))
|
||||
(when (< pos src-len) (advance! 1))
|
||||
(skip-dquote-content!)))))
|
||||
|
||||
(define parse-bs
|
||||
(fn ()
|
||||
(advance! 1)
|
||||
(let ((c (cur)))
|
||||
(cond
|
||||
((= c nil) "\\")
|
||||
((= c "n") (begin (advance! 1) "\n"))
|
||||
((= c "t") (begin (advance! 1) "\t"))
|
||||
((= c "r") (begin (advance! 1) "\r"))
|
||||
((= c "\\") (begin (advance! 1) "\\"))
|
||||
((= c "[") (begin (advance! 1) "["))
|
||||
((= c "]") (begin (advance! 1) "]"))
|
||||
((= c "{") (begin (advance! 1) "{"))
|
||||
((= c "}") (begin (advance! 1) "}"))
|
||||
((= c "$") (begin (advance! 1) "$"))
|
||||
((= c ";") (begin (advance! 1) ";"))
|
||||
((= c "\"") (begin (advance! 1) "\""))
|
||||
((= c "'") (begin (advance! 1) "'"))
|
||||
((= c " ") (begin (advance! 1) " "))
|
||||
((= c "\n")
|
||||
(begin
|
||||
(advance! 1)
|
||||
(skip-ws!)
|
||||
" "))
|
||||
(else (begin (advance! 1) (str "\\" c)))))))
|
||||
|
||||
(define parse-cmd-sub
|
||||
(fn ()
|
||||
(advance! 1)
|
||||
(let ((start pos) (depth 1))
|
||||
(define scan!
|
||||
(fn ()
|
||||
(when (and (< pos src-len) (> depth 0))
|
||||
(cond
|
||||
((= (cur) "[")
|
||||
(begin (set! depth (+ depth 1)) (advance! 1) (scan!)))
|
||||
((= (cur) "]")
|
||||
(begin
|
||||
(set! depth (- depth 1))
|
||||
(when (> depth 0) (advance! 1))
|
||||
(scan!)))
|
||||
((= (cur) "{")
|
||||
(begin (advance! 1) (skip-brace-content! 1) (scan!)))
|
||||
((= (cur) "\"")
|
||||
(begin
|
||||
(advance! 1)
|
||||
(skip-dquote-content!)
|
||||
(when (= (cur) "\"") (advance! 1))
|
||||
(scan!)))
|
||||
((= (cur) "\\")
|
||||
(begin (advance! 1) (when (< pos src-len) (advance! 1)) (scan!)))
|
||||
(else (begin (advance! 1) (scan!)))))))
|
||||
(scan!)
|
||||
(let ((src-text (slice src start pos)))
|
||||
(begin
|
||||
(when (= (cur) "]") (advance! 1))
|
||||
{:type "cmd" :src src-text})))))
|
||||
|
||||
(define scan-name!
|
||||
(fn ()
|
||||
(when (and (< pos src-len) (not (= (cur) "}")))
|
||||
(begin (advance! 1) (scan-name!)))))
|
||||
|
||||
(define scan-ns-name!
|
||||
(fn ()
|
||||
(cond
|
||||
((tcl-ident-char? (cur))
|
||||
(begin (advance! 1) (scan-ns-name!)))
|
||||
((and (= (cur) ":") (= (char-at 1) ":"))
|
||||
(begin (advance! 2) (scan-ns-name!)))
|
||||
(else nil))))
|
||||
|
||||
(define scan-klit!
|
||||
(fn ()
|
||||
(when (and (< pos src-len)
|
||||
(not (= (cur) ")"))
|
||||
(not (= (cur) "$"))
|
||||
(not (= (cur) "["))
|
||||
(not (= (cur) "\\")))
|
||||
(begin (advance! 1) (scan-klit!)))))
|
||||
|
||||
(define scan-key!
|
||||
(fn (kp)
|
||||
(when (and (< pos src-len) (not (= (cur) ")")))
|
||||
(cond
|
||||
((= (cur) "$")
|
||||
(begin (append! kp (parse-var-sub)) (scan-key! kp)))
|
||||
((= (cur) "[")
|
||||
(begin (append! kp (parse-cmd-sub)) (scan-key! kp)))
|
||||
((= (cur) "\\")
|
||||
(begin
|
||||
(append! kp {:type "text" :value (parse-bs)})
|
||||
(scan-key! kp)))
|
||||
(else
|
||||
(let ((kstart pos))
|
||||
(begin
|
||||
(scan-klit!)
|
||||
(append! kp {:type "text" :value (slice src kstart pos)})
|
||||
(scan-key! kp))))))))
|
||||
|
||||
(define parse-var-sub
|
||||
(fn ()
|
||||
(advance! 1)
|
||||
(cond
|
||||
((= (cur) "{")
|
||||
(begin
|
||||
(advance! 1)
|
||||
(let ((start pos))
|
||||
(begin
|
||||
(scan-name!)
|
||||
(let ((name (slice src start pos)))
|
||||
(begin
|
||||
(when (= (cur) "}") (advance! 1))
|
||||
{:type "var" :name name}))))))
|
||||
((tcl-ident-start? (cur))
|
||||
(let ((start pos))
|
||||
(begin
|
||||
(scan-ns-name!)
|
||||
(let ((name (slice src start pos)))
|
||||
(if (= (cur) "(")
|
||||
(begin
|
||||
(advance! 1)
|
||||
(let ((key-parts (list)))
|
||||
(begin
|
||||
(scan-key! key-parts)
|
||||
(when (= (cur) ")") (advance! 1))
|
||||
{:type "var-arr" :name name :key key-parts})))
|
||||
{:type "var" :name name})))))
|
||||
(else {:type "text" :value "$"}))))
|
||||
|
||||
(define scan-lit!
|
||||
(fn (stop?)
|
||||
(when (and (< pos src-len)
|
||||
(not (stop? (cur)))
|
||||
(not (= (cur) "$"))
|
||||
(not (= (cur) "["))
|
||||
(not (= (cur) "\\")))
|
||||
(begin (advance! 1) (scan-lit! stop?)))))
|
||||
|
||||
(define parse-word-parts!
|
||||
(fn (parts stop?)
|
||||
(when (and (< pos src-len) (not (stop? (cur))))
|
||||
(cond
|
||||
((= (cur) "$")
|
||||
(begin (append! parts (parse-var-sub)) (parse-word-parts! parts stop?)))
|
||||
((= (cur) "[")
|
||||
(begin (append! parts (parse-cmd-sub)) (parse-word-parts! parts stop?)))
|
||||
((= (cur) "\\")
|
||||
(begin
|
||||
(append! parts {:type "text" :value (parse-bs)})
|
||||
(parse-word-parts! parts stop?)))
|
||||
(else
|
||||
(let ((start pos))
|
||||
(begin
|
||||
(scan-lit! stop?)
|
||||
(when (> pos start)
|
||||
(append! parts {:type "text" :value (slice src start pos)}))
|
||||
(parse-word-parts! parts stop?))))))))
|
||||
|
||||
(define parse-brace-word
|
||||
(fn ()
|
||||
(advance! 1)
|
||||
(let ((depth 1) (start pos))
|
||||
(define scan!
|
||||
(fn ()
|
||||
(when (and (< pos src-len) (> depth 0))
|
||||
(cond
|
||||
((= (cur) "{")
|
||||
(begin (set! depth (+ depth 1)) (advance! 1) (scan!)))
|
||||
((= (cur) "}")
|
||||
(begin (set! depth (- depth 1)) (when (> depth 0) (advance! 1)) (scan!)))
|
||||
(else (begin (advance! 1) (scan!)))))))
|
||||
(scan!)
|
||||
(let ((value (slice src start pos)))
|
||||
(begin
|
||||
(when (= (cur) "}") (advance! 1))
|
||||
{:type "braced" :value value})))))
|
||||
|
||||
(define parse-dquote-word
|
||||
(fn ()
|
||||
(advance! 1)
|
||||
(let ((parts (list)))
|
||||
(begin
|
||||
(parse-word-parts! parts (fn (c) (or (= c "\"") (= c nil))))
|
||||
(when (= (cur) "\"") (advance! 1))
|
||||
{:type "compound" :parts parts :quoted true}))))
|
||||
|
||||
(define parse-bare-word
|
||||
(fn ()
|
||||
(let ((parts (list)))
|
||||
(begin
|
||||
(parse-word-parts!
|
||||
parts
|
||||
(fn (c) (or (tcl-ws? c) (= c "\n") (= c ";") (= c nil))))
|
||||
{:type "compound" :parts parts :quoted false}))))
|
||||
|
||||
(define parse-word-no-expand
|
||||
(fn ()
|
||||
(cond
|
||||
((= (cur) "{") (parse-brace-word))
|
||||
((= (cur) "\"") (parse-dquote-word))
|
||||
(else (parse-bare-word)))))
|
||||
|
||||
(define parse-word
|
||||
(fn ()
|
||||
(cond
|
||||
((and (= (cur) "{") (= (char-at 1) "*") (= (char-at 2) "}"))
|
||||
(begin
|
||||
(advance! 3)
|
||||
{:type "expand" :word (parse-word-no-expand)}))
|
||||
((= (cur) "{") (parse-brace-word))
|
||||
((= (cur) "\"") (parse-dquote-word))
|
||||
(else (parse-bare-word)))))
|
||||
|
||||
(define parse-words!
|
||||
(fn (words)
|
||||
(skip-ws!)
|
||||
(cond
|
||||
((or (= (cur) nil) (= (cur) "\n") (= (cur) ";")) nil)
|
||||
((and (= (cur) "\\") (= (char-at 1) "\n"))
|
||||
(begin (advance! 2) (skip-ws!) (parse-words! words)))
|
||||
(else
|
||||
(begin
|
||||
(append! words (parse-word))
|
||||
(parse-words! words))))))
|
||||
|
||||
(define skip-seps!
|
||||
(fn ()
|
||||
(when (< pos src-len)
|
||||
(cond
|
||||
((or (tcl-ws? (cur)) (= (cur) "\n") (= (cur) ";"))
|
||||
(begin (advance! 1) (skip-seps!)))
|
||||
((and (= (cur) "\\") (= (char-at 1) "\n"))
|
||||
(begin (advance! 2) (skip-seps!)))
|
||||
(else nil)))))
|
||||
|
||||
(define parse-all!
|
||||
(fn ()
|
||||
(skip-seps!)
|
||||
(when (< pos src-len)
|
||||
(cond
|
||||
((= (cur) "#")
|
||||
(begin (skip-to-eol!) (parse-all!)))
|
||||
(else
|
||||
(let ((words (list)))
|
||||
(begin
|
||||
(parse-words! words)
|
||||
(when (> (len words) 0)
|
||||
(append! commands {:type "command" :words words}))
|
||||
(parse-all!))))))))
|
||||
|
||||
(parse-all!)
|
||||
commands)))
|
||||
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.
|
||||
@@ -14,7 +14,7 @@ You are the sole background agent working `/root/rose-ash/plans/js-on-sx.md`. A
|
||||
|
||||
## Current state (restart baseline — verify before iterating)
|
||||
|
||||
- Branch: `loops/js`.
|
||||
- Branch: `architecture`. HEAD: `14b6586e` (HS-related, not js-on-sx).
|
||||
- `lib/js/` is **untracked** — nothing is committed yet. First commit should stage everything current on disk.
|
||||
- `lib/js/test262-upstream/` is a clone of tc39/test262 pinned at `d5e73fc8d2c663554fb72e2380a8c2bc1a318a33`. **Gitignore it** (`lib/js/.gitignore` → `test262-upstream/`). Do not commit the 50k test files.
|
||||
- `lib/js/test262-runner.py` exists but is buggy — current scoreboard is `0/8 (7 timeouts, 1 fail)`. The runner needs real work: harness script loading, batching, per-test timeout tuning, strict-mode skipping.
|
||||
@@ -61,7 +61,7 @@ Tagged dict: `{:__js_string__ true :utf16 <list-of-uint16> :str <lazy-utf8-cache
|
||||
- **Scope:** only `lib/js/**` and `plans/js-on-sx.md`. Do NOT touch `spec/`, `shared/`, `lib/hyperscript/`. Shared-file issues go under the plan's "Blockers" section.
|
||||
- **SX files:** `sx-tree` MCP tools ONLY. `sx_summarise` / `sx_read_subtree` / `sx_find_all` / `sx_get_context` before edits. `sx_replace_node` / `sx_insert_child` / `sx_insert_near` / `sx_replace_by_pattern` / `sx_rename_symbol` for edits. `sx_validate` after. `sx_write_file` for new files. Never `Edit`/`Read`/`Write` on `.sx`.
|
||||
- **Shell, Python, Markdown, JSON:** edit normally.
|
||||
- **Branch:** `loops/js`. Commit, then push to `origin/loops/js`. Never touch `main`.
|
||||
- **Branch:** `architecture`. Commit locally. Never push. Never touch `main`.
|
||||
- **Commit granularity:** one feature per commit. Short, factual commit messages. Commit even if a partial fix — don't hoard changes.
|
||||
- **Tests:** `bash lib/js/test.sh` (254/254 baseline) and `bash lib/js/conformance.sh` (148/148 baseline). Never regress. If a feature requires larger refactor, split into multiple commits each green.
|
||||
- **Plan file:** append one paragraph per iteration to "Progress log". Tick `[x]` boxes. Don't rewrite history.
|
||||
|
||||
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.
|
||||
77
plans/agent-briefings/smalltalk-loop.md
Normal file
77
plans/agent-briefings/smalltalk-loop.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# smalltalk-on-sx loop agent (single agent, queue-driven)
|
||||
|
||||
Role: iterates `plans/smalltalk-on-sx.md` forever. Message-passing OO + **blocks with non-local return** on delimited continuations. Non-local return is the headline showcase — every other Smalltalk reinvents it on the host stack; on SX it falls out of the captured method-return continuation.
|
||||
|
||||
```
|
||||
description: smalltalk-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/smalltalk-on-sx.md`. Isolated worktree, forever, one commit per feature. Never push.
|
||||
|
||||
## Restart baseline — check before iterating
|
||||
|
||||
1. Read `plans/smalltalk-on-sx.md` — roadmap + Progress log.
|
||||
2. `ls lib/smalltalk/` — pick up from the most advanced file.
|
||||
3. If `lib/smalltalk/tests/*.sx` exist, run them. Green before new work.
|
||||
4. If `lib/smalltalk/scoreboard.md` exists, that's your baseline.
|
||||
|
||||
## The queue
|
||||
|
||||
Phase order per `plans/smalltalk-on-sx.md`:
|
||||
|
||||
- **Phase 1** — tokenizer + parser (chunk format, identifiers, keywords `foo:`, binary selectors, `#sym`, `#(…)`, `$c`, blocks `[:a | …]`, cascades, message precedence)
|
||||
- **Phase 2** — object model + sequential eval (class table bootstrap, message dispatch, `super`, `doesNotUnderstand:`, instance variables)
|
||||
- **Phase 3** — **THE SHOWCASE**: blocks with non-local return via captured method-return continuation. `whileTrue:` / `ifTrue:ifFalse:` as block sends. 5 classic programs (eight-queens, quicksort, mandelbrot, life, fibonacci) green.
|
||||
- **Phase 4** — reflection + MOP: `perform:`, `respondsTo:`, runtime method addition, `becomeForward:`, `Exception` / `on:do:` / `ensure:` on top of `handler-bind`/`raise`
|
||||
- **Phase 5** — collections + numeric tower + streams
|
||||
- **Phase 6** — port SUnit, vendor Pharo Kernel-Tests slice, drive corpus to 200+
|
||||
- **Phase 7** — speed (optional): inline caching, block intrinsification
|
||||
|
||||
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/smalltalk/**` and `plans/smalltalk-on-sx.md`. Do **not** edit `spec/`, `hosts/`, `shared/`, other `lib/<lang>/` dirs, `lib/stdlib.sx`, or `lib/` root. Smalltalk primitives go in `lib/smalltalk/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.
|
||||
|
||||
## Smalltalk-specific gotchas
|
||||
|
||||
- **Method invocation captures `^k`** — the return continuation. Bind it as the block's escape token. `^expr` from inside any nested block invokes that captured `^k`. Escape past method return raises `BlockContext>>cannotReturn:`.
|
||||
- **Blocks are lambdas + escape token**, not bare lambdas. `value`/`value:`/… invoke the lambda; `^` invokes the escape.
|
||||
- **`ifTrue:` / `ifFalse:` / `whileTrue:` are ordinary block sends** — no special form. The runtime intrinsifies them in the JIT path (Tier 1 of bytecode expansion already covers this pattern).
|
||||
- **Cascade** `r m1; m2; m3` desugars to `(let ((tmp r)) (st-send tmp 'm1 ()) (st-send tmp 'm2 ()) (st-send tmp 'm3 ()))`. Result is the cascade's last send (or first, depending on parser variant — pick one and document).
|
||||
- **`super` send** looks up starting from the *defining* class's superclass, not the receiver class. Stash the defining class on the method record.
|
||||
- **Selectors are interned symbols.** Use SX symbols.
|
||||
- **Receiver dispatch:** tagged ints / floats / strings / symbols / `nil` / `true` / `false` aren't boxed. Their classes (`SmallInteger`, `Float`, `String`, `Symbol`, `UndefinedObject`, `True`, `False`) are looked up by SX type-of, not by an `:class` field.
|
||||
- **Method precedence:** unary > binary > keyword. `3 + 4 factorial` is `3 + (4 factorial)`. `a foo: b bar` is `a foo: (b bar)` (keyword absorbs trailing unary).
|
||||
- **Image / fileIn / become: between sessions** = out of scope. One-way `becomeForward:` only.
|
||||
- **Test corpus:** ~200 hand-written + a slice of Pharo Kernel-Tests. Place programs in `lib/smalltalk/tests/programs/`.
|
||||
|
||||
## 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/smalltalk-on-sx.md` inline.
|
||||
- Short, factual commit messages (`smalltalk: tokenizer + 56 tests`).
|
||||
- One feature per iteration. Commit. Log. Next.
|
||||
|
||||
Go. Read the plan; find first `[ ]`; implement.
|
||||
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. Push to `origin/loops/tcl` after every commit.
|
||||
|
||||
## 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, then push to `origin/loops/tcl`. 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)_
|
||||
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.
|
||||
@@ -65,7 +65,7 @@ Each item: implement → tests → update progress. Mark `[x]` when tests green.
|
||||
- [x] Punctuation: `( ) { } [ ] , ; : . ...`
|
||||
- [x] Operators: `+ - * / % ** = == === != !== < > <= >= && || ! ?? ?: & | ^ ~ << >> >>> += -= ...`
|
||||
- [x] Comments (`//`, `/* */`)
|
||||
- [x] Automatic Semicolon Insertion (defer — initially require semicolons)
|
||||
- [ ] Automatic Semicolon Insertion (defer — initially require semicolons)
|
||||
|
||||
### Phase 2 — Expression parser (Pratt-style)
|
||||
- [x] Literals → AST nodes
|
||||
@@ -124,7 +124,7 @@ Each item: implement → tests → update progress. Mark `[x]` when tests green.
|
||||
- [x] Closures — work via SX `fn` env capture
|
||||
- [x] Rest params (`...rest` → `&rest`)
|
||||
- [x] Default parameters (desugar to `if (param === undefined) param = default`)
|
||||
- [x] `var` hoisting (shallow — collects direct `var` decls, emits `(define name :js-undefined)` before funcdecls)
|
||||
- [ ] `var` hoisting (deferred — treated as `let` for now)
|
||||
- [ ] `let`/`const` TDZ (deferred)
|
||||
|
||||
### Phase 8 — Objects, prototypes, `this`
|
||||
@@ -158,272 +158,6 @@ Each item: implement → tests → update progress. Mark `[x]` when tests green.
|
||||
|
||||
Append-only record of completed iterations. Loop writes one line per iteration: date, what was done, test count delta.
|
||||
|
||||
- 2026-05-10 — **`String.prototype.repeat` no longer arity-collides with itself; raises RangeError on negative or +Infinity counts.** Earlier JSON.stringify iteration introduced a 2-arg `js-string-repeat` that shadowed the existing 3-arg `(s n acc)` accumulator implementation, breaking every `s.repeat(n)` call with "expects 2 args, got 3". Renamed the accumulator helper to `js-string-repeat-loop` and made `js-string-repeat` a 2-arg facade that delegates. Hooked the repeat method to raise RangeError when `count < 0` or `count = Infinity` per spec. Result: built-ins/String/prototype/repeat 7/13 → 11/13 (+4). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **test262-runner inlines small upstream harness includes (`nans.js`, `sta.js`, `byteConversionValues.js`, `compareArray.js`) per-test.** The runner parsed `includes:` frontmatter but never used it, so tests like `built-ins/isNaN/return-true-nan.js` (which depends on `var NaNs = [...]`) failed with "ReferenceError: undefined symbol". Added `_load_harness_include` (cached) and `assemble_source` now prepends each allowlisted include's source to the test. Allowlist excludes large helpers like `propertyHelper.js` because per-test js-eval+JIT cost on a 371-line harness pushes tests over the 15s per-test timeout (regressed Math/abs 7/7 → 4/7 in a first-pass attempt before allowlisting). Result: built-ins/isNaN 2/7 → 3/7. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **Real `Date.prototype.setFullYear/setMonth/setDate/setHours/setMinutes/setSeconds/setMilliseconds` (+ UTC variants) and a corrected `setTime`.** All Date setters were missing — only `setTime` existed and didn't validate. Added a unified `js-date-setter(d, field, args)` that decomposes the current ms into `(y mo da hh mm ss msv)` via `js-date-decompose`, splices in the `args` per the field's optional-arg contract (e.g. `setHours(h, m?, s?, ms?)`), recomposes via `js-date-civil-to-days`, and TimeClips at ±8.64e15. NaN args anywhere → ms set to NaN. Wired all 14 setters to the helper. Hit a parser gotcha: SX `cond` clause body is single-form only — multi-expression bodies like `(else (dict-set! ...) new-ms)` silently treat the second form as `(<first-result> new-ms)` ("Not callable: false"). Wrapped these in `(begin ...)`. Result: setFullYear 5/18 → 13/18 (+8). setHours 5/21 → 15/21 (+10). setMonth 3/15 → 9/15 (+6). setMinutes 4/16 → 10/16 (+6). setSeconds 3/15 → 9/15 (+6). setDate 2/12 → 6/12 (+4). setMilliseconds 2/12 → 6/12 (+4). setTime 4/9 → 6/9 (+2). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`Object.assign` keys now visible to `Object.keys` / `JSON.stringify`.** `Object.assign({}, {a:1})` was mutating the target via `dict-set!` which bypasses our `__js_order__` insertion-order side table; `Object.keys(t)` (which iterates `__js_order__` when present) returned `[]`, and `JSON.stringify` saw nothing. Switched `js-object-assign` to use `js-set-prop` (which calls `js-obj-order-add!` on new keys) for both dict and string sources. Result: built-ins/Object/assign 13/25 → 14/25. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **User functions' `prototype` chain through Object.prototype + auto-set `constructor`.** Per ES spec, every function's `prototype` slot defaults to `{ constructor: F, __proto__: Object.prototype }`. Our `js-get-ctor-proto` lazily created a fresh empty `(dict)` for user functions on first access — so `(new F) instanceof Object` was `false`, `F.prototype.constructor` was undefined, and `x.constructor === F` failed. Now the lazy-init seeds the proto with `__proto__ → Object.prototype` and `constructor → F` before caching in `__js_proto_table__`. Result: language/expressions/instanceof 25/30 → 26/30. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **Postfix `++`/`--` reject a preceding LineTerminator (ASI).** Per ES spec, `x\n++;` is a syntax error: no LineTerminator allowed between LHS and postfix `++`/`--`. Our `jp-parse-postfix` was matching `++`/`--` regardless of whether the preceding token had `:nl true`. Added `(not (jp-token-nl? st))` guard so newline-before-`++` makes the postfix arm fall through, the `++` then becomes a prefix-expr starting a new statement, which fails to parse and the runner classifies as SyntaxError. Result: language/expressions/postfix-increment 16/30 → 18/30 (+2). postfix-decrement 16/30 → 18/30 (+2). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **Parse-time SyntaxError when `let`/`const`/`function`/`class` appear as a single-statement body of `if`/`while`/`do`/`for`/labeled.** Per ES grammar, those positions accept a Statement, not a Declaration — only block bodies (`{ ... }`) may contain Declarations. Added `jp-disallow-decl-stmt!` helper that, when the next token is a Declaration keyword in single-statement context, raises SyntaxError. The `let` arm checks for `let <ident>`, `let [`, or `let {` to avoid mis-rejecting `let;` (where `let` is just an identifier expression). Hook calls in `jp-parse-if-stmt` (then + else branches), `jp-parse-while-stmt`, `jp-parse-do-while-stmt`, both for-of/in and C-for body sites, and the labeled-statement entry. Result: language/statements/while 16/30 → 20/30. statements/labeled 4/15 → 7/15. statements/if 20/30 → 21/30. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **Parse-time SyntaxError for `break`/`continue` outside loops/switches and `return` outside functions; `void <expr>` evaluates `<expr>` for side effects.** Parser tracks `:loop-depth`, `:switch-depth`, and `:fn-depth` on the state dict (initialized to 0). `jp-parse-while-stmt`, `jp-parse-do-while-stmt`, `jp-parse-for-stmt` (both for-of/in and C-for) bump `:loop-depth` around body parsing; `jp-parse-switch-stmt` bumps `:switch-depth`; new `jp-parse-fn-body` and `jp-parse-arrow-body` save+reset loop/switch depth and bump `:fn-depth` (so `break` inside an outer loop's nested function is rejected). Bare `break` requires `loop-depth > 0 OR switch-depth > 0`; bare `continue` requires `loop-depth > 0`; `return` requires `fn-depth > 0`. Separately, `void <expr>` was compiling to just `:js-undefined` (dropping the expression entirely); now `(begin <expr> :js-undefined)` so side effects fire. Result: language/statements/return 4/15 → 14/15 (+10). statements/break 9/20 → 12/20. statements/continue 12/24 → 15/24. expressions/void 7/9 → 8/9. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`Math.hypot` and `Math.cbrt` honour spec edges for NaN, ±Infinity, and ±0.** `Math.hypot(NaN, Infinity)` was returning NaN instead of +Infinity (spec: any ±Infinity arg dominates NaN). Rewrote `js-math-hypot` to scan args once tracking inf/nan flags, return +Infinity if any arg is ±Infinity, else NaN if any was NaN, else `sqrt(sum of squares)`. `Math.cbrt(NaN)` was 0 (because `pow(NaN, 1/3)` produced 0 in our path); also `Math.cbrt(-0)` returned +0 instead of -0. Added explicit short-circuits: NaN→NaN, ±Infinity→arg, ±0→arg, plus changed `(/ 1 3)` (rational) to `(/ 1.0 3.0)` (inexact) to avoid rational fractional-power oddities. Result: built-ins/Math/hypot 9/11 → 10/11. Math/cbrt 3/4 → 4/4. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`globalThis.globalThis === globalThis`; `Number.prototype.toFixed` honours digit-range and ≥1e21 fallback.** (1) `globalThis` was bound to `nil` in the global object literal (originally to dodge an inspect-cycle hang) — added `(dict-set! js-global "globalThis" js-global)` after the literal so `globalThis.globalThis === globalThis` per spec. (2) `Number.prototype.toFixed` rewrites: RangeError when fractionDigits is NaN or outside `[0,100]` (was silently producing garbage), and for `|x| >= 1e21` returns `js-number-to-string` (the value's own ToString) per spec step 9. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`delete <ident>` returns `false` instead of `true` per non-strict spec.** ES non-strict semantics: `delete x` where `x` is a declared binding (variable / function / parameter) returns `false` and does not unbind. Our transpiler was emitting `true` for any `delete <expr>` whose argument wasn't a member or index access. Now `delete <js-ident>` → `false`, and `delete <js-paren expr>` recurses on the inner expression so `delete (1+2)` still works. Result: language/expressions/delete 14/30 → 18/30 (+4). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **Parser rejects unary-op directly before `**` (e.g. `-1 ** 2`, `delete o.p ** 2`, `!x ** 2`, `~x ** 2`) per ES spec.** ES disallows `UnaryExpression ** ExponentiationExpression`; only `UpdateExpression ** ExponentiationExpression` and `(<UnaryExpr>) ** ...` are legal. Added a guard in `jp-binary-loop`: when op is `**` and the LHS is a `(js-unop ...)` node, raise SyntaxError. Parens are made transparent for everything except this check via a new `jp-paren-wrap` helper that emits `(js-paren <unop>)` only when wrapping an explicit unary op (so `(-1) ** 2` parses fine), and a new `js-paren` AST tag in `js-transpile` that just unwraps. Result: language/expressions/exponentiation 25/30 → 28/30 (+3). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`Math.round` / `Math.max` / `Math.min` honour spec edge cases for NaN, ±Infinity, and ±0.** `Math.round(NaN)` was returning 0 because `floor(NaN+0.5)` doesn't propagate NaN; ditto `±Infinity` paths. `Math.max({})` silently returned `-Infinity` (initial accumulator) because the first arg wasn't ToNumber'd. `Math.max(0, -0)` returned `-0` because `>` doesn't distinguish them. Rewrites: round NaN/±Infinity/±0 short-circuits; max/min ToNumber the first arg, propagate NaN immediately, and use a `js-is-positive-zero?` (rational-safe) tiebreaker so `Math.max(0, -0) === 0` per spec. Result: built-ins/Math/round 5/10 → 8/10 (+3). Math/max 6/9 → 8/9 (+2). Math/min 6/9 → 8/9 (+2). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`Map.prototype.*` and `Set.prototype.*` raise TypeError when called on non-Map / non-Set `this`.** All five `js-map-do-*` and four `js-set-do-*` helpers were assuming `this` had `__map_keys__` / `__set_items__`, so `Map.prototype.clear.call({})` silently returned undefined (after creating dangling state) instead of throwing. Added `js-map-check!` / `js-set-check!` guards run as the first step of each method; raise spec-correct `TypeError` instances. Result: built-ins/Map 18/30 → 22/30 (+4). built-ins/Set 15/30 → 28/30 (+13). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`Date.UTC` / `new Date(...)` propagate NaN/±Infinity arguments and return NaN.** `Date.UTC()` (no args) returned 0 instead of NaN; `Date.UTC(NaN, ...)` did the math and produced bogus ms; `new Date(year, NaN)` constructed a normal Date instead of an invalid one. Added `js-date-args-have-nan?` (also detects ±Infinity and propagates from rationals) used by both `Date.UTC` and the multi-arg constructor branch; UTC now returns NaN on no-arg / any-NaN-arg / out-of-range result, and `new Date(args)` stores NaN in `__date_value__` when any arg is NaN. Also fixed `js-date-from-one(undefined)` to return NaN. Result: built-ins/Date/UTC 6/16 → 10/16 (+4). Date 17/30 → 26/30 (timeouts dropped from 12 → 4 because invalid Dates now short-circuit). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **Real `Date` construction + getters via Howard-Hinnant civil-day arithmetic.** `js-date-from-parts` now computes a true ms-since-epoch from `(year, month, day, hour, min, sec, ms)` via `js-date-civil-to-days` (the inverse of last iteration's `days-to-ymd`), with the legacy 2-digit-year coercion (0..99 → 1900+y). `getFullYear/Month/Date/Day/Hours/Minutes/Seconds/Milliseconds` (UTC + non-UTC) all share a new `js-date-getter`: TypeErrors on non-Date this, returns NaN on invalid time, otherwise decomposes ms into y/m/d/h/m/s/ms/dow. Plus added `Date.prototype.constructor = Date` (was missing). Result: each of the 8 Date getter categories went 2/6 → 5/6 (+3 each, +24 total). Date toISOString 11/16 → 13/16. Some Date construction-loop tests now exceed the 15s per-test timeout — the new civil math is heavier than the old (year-1970)*ms-per-year approximation, but correctness wins. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`Date.prototype.toISOString` produces real `YYYY-MM-DDTHH:mm:ss.sssZ` and validates input.** Old `js-date-iso` only computed the year and hardcoded the rest as `01-01T00:00:00.000Z`. Added: (1) TypeError when this isn't a Date (no `__js_is_date__` slot); (2) RangeError when ms is NaN, undefined, or |ms| > 8.64e15; (3) full date breakdown via Howard-Hinnant `days_to_civil` algorithm (`js-date-days-to-ymd`) → year/month/day, plus modular hours/min/sec/ms; (4) extended-year format `±YYYYYY` for years outside 0..9999. Result: built-ins/Date/prototype/toISOString 7/16 → 11/16 (+4). Date 21/30. conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`JSON.stringify` honours `replacer` (function + array forms), `space`, and `toJSON`.** Previous impl ignored the second/third arguments entirely and never called `toJSON`. Rewrote around a `js-json-serialize-property(key, holder, rep-fn, rep-keys, gap, indent)` core: walks `toJSON` first, then replacer-fn (with `holder` as `this`); arrays-as-replacer become a property-name allowlist; numeric `space` clamped to 0..10 spaces, string `space` truncated to 10 chars, non-empty gap activates indented output with `:` → `: ` separator. Number wrapper / String wrapper / Boolean wrapper unwrap before serialization; non-finite numbers serialize as `"null"`; functions serialize as `undefined`. Result: built-ins/JSON/stringify 6/30 → 14/30 (+8). conformance.sh: 148/148.
|
||||
|
||||
- 2026-05-10 — **`JSON.parse` raises spec-correct `SyntaxError` instances and rejects malformed input.** Previously `JSON.parse("12 34")` silently returned `12` (no trailing-content check), `JSON.parse('" | ||||