diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 148f5c3d..4a49675c 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -23,6 +23,12 @@ kept so existing scripts fail loudly (Refs #56) ==== Added +* WASM: `slice` on a String and `show` on Int or Bool now compile on the +core-WASM backend. The typechecker records the argument type and the wasm +elaboration picks `string_slice`, `int_to_string`, or an if over +"true"/"false". `show` on other types is a named error, since the +interpreter and Deno render Strings, Chars and Floats differently; a +user-defined `show` or `slice` is still called (Closes #560) * json: `hpm_json_object_len` / `hpm_json_object_key` enumerate object members, so `to_json` materialises objects instead of returning `None`. Lowered on Bun-ESM; the matching hpm-json-rsr Zig exports are not merged diff --git a/lib/codegen.ml b/lib/codegen.ml index 6cd9bc3a..c3acf7e4 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -419,7 +419,7 @@ let rec is_string_concat_operand (e : expr) : bool = (* String-returning builtins (Int/Char-returning ones are excluded). *) List.mem id.name [ "int_to_string"; "float_to_string"; "to_lowercase"; "to_uppercase"; - "trim"; "string_sub"; "string_from_char_code"; "show" ] + "trim"; "string_sub"; "string_slice"; "string_from_char_code"; "show" ] | ExprBinary (a, OpConcat, b) -> is_string_concat_operand a || is_string_concat_operand b | _ -> false @@ -1509,6 +1509,79 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_v, code) + | ExprVar id when id.name = "string_slice" + && List.length args = 3 -> + (* #560: `slice(s, lo, hi)` on a String, after + Typecheck.elaborate_string_concat picked the String case of the + polymorphic builtin. Half-open [lo, hi); a negative index counts + from the end; both are clamped. This matches the interpreter + oracle (lib/interp.ml `slice`) and JS `.slice` on the Deno backend: + norm i = i < 0 ? max 0 (n + i) : min i n + len = max 0 (norm hi - norm lo) + followed by the same allocate-then-copy as `string_sub`. *) + let* (ctx1, s_code) = gen_expr ctx (List.nth args 0) in + let* (ctx2, lo_code) = gen_expr ctx1 (List.nth args 1) in + let* (ctx3, hi_code) = gen_expr ctx2 (List.nth args 2) in + let (ctx4, heap_idx) = ensure_heap_ptr ctx3 in + let (c5, src) = alloc_local ctx4 "__sslc_src" in + let (c6, n) = alloc_local c5 "__sslc_n" in + let (c7, lo) = alloc_local c6 "__sslc_lo" in + let (c8, hi) = alloc_local c7 "__sslc_hi" in + let (c9, dst) = alloc_local c8 "__sslc_dst" in + let (c10, k) = alloc_local c9 "__sslc_k" in + (* local := (local < 0) ? max(0, n + local) : min(local, n) *) + let norm v = + [ LocalGet v; I32Const 0l; I32LtS; + If (BtEmpty, + (* n + v, floored at 0 *) + [ LocalGet n; LocalGet v; I32Add; I32Const 0l; + LocalGet n; LocalGet v; I32Add; I32Const 0l; I32GtS; + Select; LocalSet v ], + (* min(v, n) *) + [ LocalGet v; LocalGet n; LocalGet v; LocalGet n; I32LtS; + Select; LocalSet v ]) ] in + let code = + s_code @ [LocalSet src] @ + lo_code @ [LocalSet lo] @ + hi_code @ [LocalSet hi] @ + [ LocalGet src; I32Load (2, 0); LocalSet n ] @ + norm lo @ norm hi @ + (* hi := max(0, hi - lo), now the byte count *) + [ LocalGet hi; LocalGet lo; I32Sub; I32Const 0l; + LocalGet hi; LocalGet lo; I32Sub; I32Const 0l; I32GtS; + Select; LocalSet hi ] @ + (* dst = heap; heap += 4 + count; dst[0] = count *) + [ GlobalGet heap_idx; LocalSet dst; + GlobalGet heap_idx; I32Const 4l; LocalGet hi; I32Add; I32Add; + GlobalSet heap_idx; + LocalGet dst; LocalGet hi; I32Store (2, 0) ] @ + (* for k in 0..count: dst[4+k] = src[4 + lo + k] *) + [ I32Const 0l; LocalSet k; + Block (BtEmpty, [ Loop (BtEmpty, [ + LocalGet k; LocalGet hi; I32GeS; BrIf 1; + LocalGet dst; LocalGet k; I32Add; + LocalGet src; LocalGet lo; I32Add; LocalGet k; I32Add; + I32Load8U (0, 4); + I32Store8 (0, 4); + LocalGet k; I32Const 1l; I32Add; LocalSet k; + Br 0 ]) ]) ] @ + [ LocalGet dst ] + in + Ok (c10, code) + + | ExprVar id when String.length id.name > 19 + && String.sub id.name 0 19 = "__show_unsupported:" -> + (* #560: `show` on a type whose rendering the backends do not agree + on (the interpreter quotes Strings and Chars and prints Float 3.0 + as "3."; the Deno backend does not), so core WASM refuses it by + name rather than pick one. Int and Bool are lowered. *) + let tname = String.sub id.name 19 (String.length id.name - 19) in + Error (UnsupportedFeature (Printf.sprintf + "show on %s is not lowered on the core-WASM backend (its output \ + differs between backends; only Int and Bool are lowered). Use \ + the type's own to-string function, e.g. float_to_string. (#560)" + tname)) + | ExprVar id when id.name = "string_sub" && List.length args = 3 -> (* PHASE-F string-wall slice 3: the runtime-length copy op. diff --git a/lib/typecheck.ml b/lib/typecheck.ml index 98aaaff1..96af4cfa 100644 --- a/lib/typecheck.ml +++ b/lib/typecheck.ml @@ -843,6 +843,18 @@ let float_heap_sites : expr list ref = ref [] (** Discard any recorded Float-heap sites (e.g. before re-checking). *) let reset_float_heap_sites () : unit = float_heap_sites := [] +(** String-wall #560. Physical-identity map from each call of a polymorphic + builtin the core-WASM backend cannot lower untyped (`slice`, `show`) to + the instantiated function type at that call. After checking, the first + parameter of that type is the argument's type, so + {!elaborate_string_concat} can pick a monomorphic lowering: + `slice` on a String becomes `string_slice`; `show` on Int becomes + `int_to_string`, on Bool an if over two literals. Same physical-identity + discipline as {!string_concat_sites}. *) +let poly_builtin_sites : (expr * ty) list ref = ref [] + +let reset_poly_builtin_sites () : unit = poly_builtin_sites := [] + (** Float heap wall — heterogeneous tuples. A tuple with at least one scalar `Float` field is laid out with uniform 8-byte cells (see {!Ast.ExprCellTuple}). These two physical-identity *maps* carry the per-cell kinds (a set is not @@ -1042,8 +1054,14 @@ let rec synth (ctx : context) (expr : expr) : ty result = Ok ty (* Function application *) - | ExprApp (fn_expr, args) -> + | ExprApp (fn_expr, args) as app_node -> let* fn_ty = synth ctx fn_expr in + (* #560: remember the instantiated type at `slice`/`show` calls; the + argument type is read off it after [apply_args] has unified it. *) + (match fn_expr, args with + | ExprVar { name = ("slice" | "show"); _ }, _ :: _ -> + poly_builtin_sites := (app_node, fn_ty) :: !poly_builtin_sites + | _ -> ()); begin match args with | [] -> (* A zero-argument call [f()]. Zero-parameter function @@ -1739,6 +1757,27 @@ and synth_and_unify (ctx : context) (expr : expr) (expected : ty) : unit result expression grammar — any constructor it failed to descend into would leave a String `++` un-elaborated, where the slice-8a guard would (loudly) catch the obvious cases and a var-var case could still miscompile. *) +let poly_builtin_shadowed : string list ref = ref [] + +(** #560: monomorphic lowering for a recorded `slice`/`show` call, from the + argument type (first parameter of the instantiated [fty]). Cases the + backends do not agree on are renamed to `__show_unsupported:`, so + core-WASM codegen reports them by name instead of "unbound `show`". *) +let elab_poly_builtin (id : ident) (fty : ty) (args : expr list) : expr = + let arg_ty = match repr fty with TArrow (a, _, _, _) -> Some (repr a) | _ -> None in + let call name = ExprApp (ExprVar { id with name }, args) in + match id.name, arg_ty, args with + | "slice", Some (TCon "String"), _ -> call "string_slice" + | "show", Some (TCon "Int"), _ -> call "int_to_string" + | "show", Some (TCon "Bool"), [b] -> + ExprIf { ei_cond = b; + ei_then = ExprLit (LitString ("true", id.span)); + ei_else = Some (ExprLit (LitString ("false", id.span))) } + | "show", Some t, _ -> + let tname = match t with TCon c -> c | TApp (TCon c, _) -> c | _ -> "this type" in + call ("__show_unsupported:" ^ tname) + | _ -> ExprApp (ExprVar id, args) + let rec elab_expr (e : expr) : expr = match e with | ExprBinary (l, op, r) -> @@ -1776,7 +1815,13 @@ let rec elab_expr (e : expr) : expr = ExprMatch { em_scrutinee = elab_expr r.em_scrutinee; em_arms = List.map elab_arm r.em_arms } | ExprLambda r -> ExprLambda { r with elam_body = elab_expr r.elam_body } - | ExprApp (f, args) -> ExprApp (elab_expr f, List.map elab_expr args) + | ExprApp (f, args) -> + let args' = List.map elab_expr args in + (match List.assq_opt e !poly_builtin_sites, f with + | Some fty, ExprVar ({ name; _ } as id) + when not (List.mem name !poly_builtin_shadowed) -> + elab_poly_builtin id fty args' + | _ -> ExprApp (elab_expr f, args')) | ExprTupleIndex (e1, i) -> (* Float heap wall: rewrite a float-bearing tuple's `t.i` into the cell load. *) (match List.assq_opt e !cell_tuple_index_sites with @@ -1890,7 +1935,16 @@ let elaborate_string_concat (program : program) : program = || !float_binop_sites <> [] || !float_heap_sites <> [] || !cell_tuple_sites <> [] || !cell_tuple_index_sites <> [] || !cell_record_sites <> [] || !cell_field_sites <> [] + || !poly_builtin_sites <> [] in + (* #560: a program that defines its own `slice`/`show` keeps calling it. *) + poly_builtin_shadowed := + List.filter_map (function + | TopFn fd when fd.fd_name.name = "slice" || fd.fd_name.name = "show" -> + Some fd.fd_name.name + | TopExternFn { ef_name; _ } + when ef_name.name = "slice" || ef_name.name = "show" -> Some ef_name.name + | _ -> None) program.prog_decls; let result = if any_sites then { program with prog_decls = List.map elab_top program.prog_decls } @@ -1905,6 +1959,7 @@ let elaborate_string_concat (program : program) : program = reset_cell_tuple_index_sites (); reset_cell_record_sites (); reset_cell_field_sites (); + reset_poly_builtin_sites (); result (** {1 Declaration checking} *) diff --git a/proposals/MIGRATION-PLAN.adoc b/proposals/MIGRATION-PLAN.adoc index 1c52a2b7..e753b3b3 100644 --- a/proposals/MIGRATION-PLAN.adoc +++ b/proposals/MIGRATION-PLAN.adoc @@ -44,9 +44,12 @@ toc::[] slice 3), *ASCII case-folding* (`to_lowercase` / `to_uppercase`, slice 4), *whitespace trimming* (`trim`, slice 5), *substring search* (`string_find`, slice 6), and *decimal rendering* (`int_to_string`, slice 7) now lower to - wasm (Phase F, see Ledger) — *the clean lane is closed*; only concat / `++` - and polymorphic `slice` remain, gated on a type-access design decision (see - Ledger F+). Gates every STRING-GATED kernel (e.g. `Kernel_IO`, `DeviceType`, + wasm (Phase F, see Ledger) — *the clean lane is closed*. String `++` + (slice 8b) and polymorphic `slice` on a String plus `show` on Int / Bool + (#560) are lowered by type-directed elaboration: the typechecker records + the argument type and `Typecheck.elaborate_string_concat` picks the + monomorphic op. `show` on other types is a named codegen error, because the + interpreter and Deno render Strings, Chars and Floats differently. Gates every STRING-GATED kernel (e.g. `Kernel_IO`, `DeviceType`, i18n) whose work is building/transforming strings rather than scanning them. Lives in *this* repo's compiler, so it is @@ -218,7 +221,7 @@ Heuristic: | F (string slice 7) | DONE | String-wall slice 7 — *decimal rendering landed in the wasm backend* (2026-06-13, Opus). `int_to_string(n)` (already wired in resolve/typecheck/interp) gained a wasm lowering over the slice-3 allocation idiom: `neg = n<0`; `m = neg ? n : -n` (non-positive magnitude via `Select`); a do-while digit-count loop (so `n=0` yields one '0' with no special case); allocate `4 + dc + neg`; a do-while backward-write loop emitting `48 - (m%10)` per digit; leading `'-'` when negative. *INT_MIN-safe* — the un-representable positive magnitude is never formed; `div_s`/`rem_s` by 10 never trap. *Gates:* G1 builds; G2 parity over 0/single/multi-digit/negative/powers-of-ten/INT_MAX/INT_MIN (wasm string read back from memory vs `string_of_int`). Tests: `test/test_e2e.ml` new `eval_string_fn` + group "E2E String-wall slice 7 (int_to_string)" (5 full-string cases incl. INT_MIN, `dune runtest`) + `tests/codegen/string_int_to_string.{affine,…mjs}` (executable wasm parity; full `run_codegen_wasm_tests.sh` green, no regressions). Evidence: `proposals/EVIDENCE-stringwall-slice7.adoc`. *Clean lane CLOSED — every name-dispatched string builtin with a trap-free wasm analogue is lowered.* NEXT: the gated concat/`slice` decision, or the effect wall. | F (string slice 8a) | DONE | String-wall slice 8a — *string-`++` footgun GUARD landed in the wasm backend* (2026-06-13, Opus). *Finding:* string `++` silently miscompiles to wasm — it typechecks (`++` is type-dispatched at `typecheck.ml:1062`), the interp is correct, but codegen lowers `++` only as *list*-concat (4-byte element stride), so a string's `[len][utf8]` is copied as i32 elements (`"ab" ++ "cd"` -> byte 2 = 2, the length word of "cd", instead of 'c'). A #555-class silent mis-lowering. *Decision (owner, "guard first, then full fix"):* the "add a `string_concat` builtin / ban `++`" route is ruled out — `++` is the canonical, stdlib-pervasive surface and `string_concat` was deliberately removed (#330). *This slice:* the wasm `OpConcat` handler now rejects the syntactically-obvious string `++` (string literal / String-returning builtin call / nested string `++`, via `is_string_concat_operand`) with a loud `UnsupportedFeature` error instead of emitting garbage — a *sound-rejection* heuristic (never misfires on list `++`; deliberately incomplete on pure var-var string `++`, which slice 8b closes). *Gates:* G1 builds; guard verified (string `++` -> loud error; list `++` + slices 1-7 fixtures still compile; full `run_codegen_wasm_tests.sh` green incl. `list_concat`). Tests: `test/test_e2e.ml` group "E2E String-wall slice 8 guard". Design: `proposals/DESIGN-string-concat.adoc` (merged #574). NEXT: slice 8b — type-directed string-`++` lowering (`ExprStringConcat` elaboration + byte-concat), making `++` correct + complete. | F (string slice 8b) | DONE | String-wall slice 8b — *type-directed string-`++` lowering landed in the wasm backend* (2026-06-13, Opus). The full fix the 8a guard stood in for. *Channel:* `synth` records each `++` it types as String concat (physical identity, `string_concat_sites`); `Typecheck.elaborate_string_concat` rewrites exactly those nodes to a new `ExprStringConcat` (`ast.ml`); the wasm path (`bin/main.ml`) runs it after typecheck, before `Opt.fold` — the interp + non-wasm backends keep the original `ExprBinary _ OpConcat _`, so the oracle is unchanged. Physical-identity keying is sound because typecheck and codegen share one `prog` object (`parse_with_face`'s lowered prog). *Lowering* (`codegen.ml`): byte concat — alloc `4 + la + lb`, length word, copy a's then b's bytes (the list-concat handler with 1-byte elements + one length word). *Effect parity:* `effect_sites.ml` recurses `ExprStringConcat` like `ExprBinary`, NOT as an `ExprApp` call site, so effect-ordinals stay identical interp-vs-wasm (no #555-class desync). `opt.ml` folds sub-exprs; `interp.ml` handles it defensively. *Gates:* G1 builds; the canonical miscompile is fixed (`"ab" ++ "cd"` byte 2 = 99 'c', was 2); var-var + chained + empty all parity-green; list `++` + slices 1-7 + effect tests still green (full `run_codegen_wasm_tests.sh`). Tests: `tests/codegen/string_concat.{affine,mjs}` (executable parity) + `test/test_e2e.ml` "E2E String-wall slice 8 guard" (incl. lowers-after-elaboration). The 8a guard is retained as a backstop. Design: `proposals/DESIGN-string-concat.adoc`. *String wall: every name-dispatched op (slices 1-7) + concat (8) now lower to wasm.* -| F+ | TODO | *String-wall residuals (minor/deferred), then the effect wall.* String residuals: *`slice`*-on-string negative-index (mostly covered by the shipped `string_sub`); *`float_to_string`* stays host-side permanently (float-wall — floats are Int-native-re-decomposed per the C6/C7 milli-unit convention); *`string_get`/`int_to_char`* deferred (raise on out-of-range; no trap-free wasm analogue). These do not gate "CLEAR" materially. *The big remaining compiler half is the effect-codegen wall* (111 EFFECT-GATED corpus files per Phase B): module-state, `Date.now`, `Console.log` → wasm. Essentially unstarted. After both walls + the migratable corpus: *Phase Ω* cutover/extinction (retire shadows, flip FeaturePacks). *String slices 1-8 landed (clean lane + concat).* +| F+ | TODO | *String-wall residuals (minor/deferred), then the effect wall.* String residuals: *`slice`* on a String (incl. negative indices) DONE in #560 (`string_slice`, wasm parity in `tests/codegen/string_slice.{affine,…mjs}`); `slice` on an *array* still unlowered; `show` lowered for Int / Bool only (#560); *`float_to_string`* stays host-side permanently (float-wall — floats are Int-native-re-decomposed per the C6/C7 milli-unit convention); *`string_get`/`int_to_char`* deferred (raise on out-of-range; no trap-free wasm analogue). These do not gate "CLEAR" materially. *The big remaining compiler half is the effect-codegen wall* (111 EFFECT-GATED corpus files per Phase B): module-state, `Date.now`, `Console.log` → wasm. Essentially unstarted. After both walls + the migratable corpus: *Phase Ω* cutover/extinction (retire shadows, flip FeaturePacks). *String slices 1-8 landed (clean lane + concat).* | Ω | TODO (access-gated) | Cutover + extinction. |=== diff --git a/test/test_e2e.ml b/test/test_e2e.ml index 1d49f236..33ec32b7 100644 --- a/test/test_e2e.ml +++ b/test/test_e2e.ml @@ -4442,6 +4442,70 @@ let string_contains s sub = let rec go i = i + m <= n && (String.sub s i m = sub || go (i + 1)) in go 0 + +(* ---- #560 (codegen wall 1): `slice` on String, `show` on Int / Bool ---- + + Both builtins are polymorphic, so core WASM cannot lower them untyped. + The typechecker records each call (poly_builtin_sites) and + Typecheck.elaborate_string_concat rewrites it to a monomorphic op. The + interpreter cases pin the oracle; tests/codegen/string_slice.affine is the + wasm-side parity fixture for the same values. *) + +let test_slice560_interp_plain () = + Alcotest.(check int) "slice(\"hello world\",1,4) == \"ell\"" 1 + (eval_int_fn "fn f() -> Int { if slice(\"hello world\", 1, 4) == \"ell\" { 1 } else { 0 } }") + +let test_slice560_interp_negative () = + Alcotest.(check int) "slice(s,-5,99) == \"world\"" 1 + (eval_int_fn "fn f() -> Int { if slice(\"hello world\", -5, 99) == \"world\" { 1 } else { 0 } }") + +let test_slice560_interp_empty () = + Alcotest.(check int) "slice(s,7,2) is empty" 0 + (eval_int_fn "fn f() -> Int { string_length(slice(\"hello world\", 7, 2)) }") + +let test_slice560_interp_both_negative () = + Alcotest.(check int) "slice(s,-99,-6) == \"hello\"" 1 + (eval_int_fn "fn f() -> Int { if slice(\"hello world\", -99, -6) == \"hello\" { 1 } else { 0 } }") + +(* frontend -> elaborate -> core-WASM codegen, from source text *) +let wasm_of_source src = + let prog = Parse_driver.parse_string ~file:"<560>" src in + match resolve_program prog with + | Error e -> Error e + | Ok (resolve_ctx, _) -> + match typecheck_program resolve_ctx.symbols prog with + | Error e -> Error e + | Ok _ -> wasm_codegen (Typecheck.elaborate_string_concat prog) + +let test_slice560_wasm_lowers () = + match wasm_of_source + "fn f(s: String) -> Int { string_length(slice(s, 1, 3)) + \ + string_length(show(7)) + string_length(show(true)) }" with + | Ok _ -> () + | Error msg -> Alcotest.failf "slice/show should lower to wasm: %s" msg + +let test_show560_float_named_error () = + match wasm_of_source "fn f() -> Int { string_length(show(1.5)) }" with + | Ok _ -> Alcotest.fail "show on Float must not compile silently to wasm" + | Error msg when string_contains msg "show on Float" -> () + | Error msg -> Alcotest.failf "expected the named show-on-Float error, got: %s" msg + +let test_show560_user_defined_wins () = + match wasm_of_source + "fn show(x: Float) -> String { \"n\" }\n\ + fn f() -> Int { string_length(show(1.5)) }" with + | Ok _ -> () + | Error msg -> Alcotest.failf "a user-defined `show` must still be called: %s" msg + +let slice560_tests = [ + Alcotest.test_case "interp: plain slice" `Quick test_slice560_interp_plain; + Alcotest.test_case "interp: negative lo, hi clamped" `Quick test_slice560_interp_negative; + Alcotest.test_case "interp: hi < lo -> empty" `Quick test_slice560_interp_empty; + Alcotest.test_case "interp: both negative" `Quick test_slice560_interp_both_negative; + Alcotest.test_case "wasm: slice/show lower after elaboration" `Quick test_slice560_wasm_lowers; + Alcotest.test_case "wasm: show on Float is a named error" `Quick test_show560_float_named_error; + Alcotest.test_case "wasm: user-defined show is not rewritten" `Quick test_show560_user_defined_wins; +] let test_stringwall_concat_guard_rejects_string () = let prog = Parse_driver.parse_string ~file:"" "fn f() -> Int { string_char_code_at(\"ab\" ++ \"cd\", 0) }" in @@ -5909,6 +5973,7 @@ let tests = ("E2E String-wall slice 1 (indexing)", stringwall_index_tests); ("E2E String-wall slice 2 (string_from_char_code)", stringwall_alloc_tests); ("E2E String-wall slice 3 (string_sub)", stringwall_sub_tests); + ("E2E String-wall #560 (slice, show)", slice560_tests); ("E2E String-wall slice 4 (case-fold)", stringwall_case_tests); ("E2E String-wall slice 5 (trim)", stringwall_trim_tests); ("E2E String-wall slice 6 (string_find)", stringwall_find_tests); diff --git a/tests/codegen/string_slice.affine b/tests/codegen/string_slice.affine new file mode 100644 index 00000000..e683dd23 --- /dev/null +++ b/tests/codegen/string_slice.affine @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2025-2026 hyperpolymath +// +// #560 (codegen wall 1): `slice` on a String and `show` on Int / Bool lower +// to core WASM. The typechecker records each call's argument type and +// Typecheck.elaborate_string_concat rewrites it to a monomorphic op +// (`string_slice`, `int_to_string`, an if over "true"/"false"). +// +// slice is half-open [lo, hi); a negative index counts from the end; both +// are clamped (lib/interp.ml `slice`, JS `.slice`). The companion harness +// test_string_slice.mjs asserts main() == 31; the same cases are pinned +// interpreter-side in test/test_e2e.ml (E2E String-wall #560). + +fn cut(s: String, lo: Int, hi: Int) -> String { slice(s, lo, hi) } + +fn main() -> Int { + let s = "hello world"; + let a = if cut(s, 1, 4) == "ell" { 1 } else { 0 }; // plain + let b = if cut(s, -5, 99) == "world" { 2 } else { 0 }; // negative lo, hi clamped + let c = if cut(s, 7, 2) == "" { 4 } else { 0 }; // hi < lo -> empty + let d = if cut(s, -99, -6) == "hello" { 8 } else { 0 }; // both negative, lo floored at 0 + let e = if show(-42) ++ show(true) ++ show(1 < 0) == "-42truefalse" { 16 } else { 0 }; + a + b + c + d + e // 31 when every case holds +} diff --git a/tests/codegen/test_string_slice.mjs b/tests/codegen/test_string_slice.mjs new file mode 100644 index 00000000..9a6524ea --- /dev/null +++ b/tests/codegen/test_string_slice.mjs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MPL-2.0 +// +// #560 — wasm parity check for `slice` on String and `show` on Int / Bool. +// string_slice.affine sets one bit per case that matches the interpreter +// oracle (lib/interp.ml `slice` / `show`); all five bits set is 31. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +const buf = await readFile('./tests/codegen/string_slice.wasm'); +const imports = { wasi_snapshot_preview1: { fd_write: () => 0 } }; +const inst = (await WebAssembly.instantiate(buf, imports)).instance; +const result = inst.exports.main(); + +assert.equal(result, 31, `string_slice parity: wasm main()=${result}, want 31 (bits: plain=1 neg=2 empty=4 bothneg=8 show=16)`); +console.log('test_string_slice.mjs OK');