From 6d390c619a7809e5726446c738559eb59138c2a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 20:32:57 +0000 Subject: [PATCH 1/3] feat(diagnostics): locate E0104 and name a continued if/match; add char_to_string Found while building hyperpolymath/consent-aware-inspector on the Bun backend. 1. E0104 carried no location. `check --json` reported line 0 in file "", so one bad call gave no clue where it was. - New `Typecheck.Located (err, span)`: the first step of the "Phase B" span threading that json_output.ml already names. - Calls now attach the callee's start (`expr_start_span`). - Face (every face) and Json_output render the location. - Json_output also now uses QuantityError's own span, which it used to drop. 2. The commonest cause of that E0104 is the documented #644 rule: a statement `if`/`match` followed by `(` continues the expression, so `if c { .. }` followed by `(a, b)` is a call on Unit. It is now reported as `StatementContinued { kind; ty }`, still E0104. The message names the rule (ON-RAMP "Statements and `;`") and the remedy, a `;` after the `}`. The grammar rule itself is unchanged. 3. `char_to_string : Char -> String`. There was no total route from a code point to a String: `string_from_char_code` keeps 8 bits. It is wired like int_to_char (resolver, type checker, interpreter, Bun-ESM) and allowlisted in the builtins consistency test. Ledger: main is red on property 3 at 4a55253, because the #833 row was lost in #843's merge. This ports the ledger part of #856 (restores the #833 row and drops the stale test_intrinsic_shadow digest). It is a no-op once #856 merges. The stamp is advanced to 4a55253. Tests: - test/test_call_diagnostics.ml: 7 cases (located if/match/plain call; the `;` remedy type-checks; text and JSON both carry file:line; char_to_string types). - tests/codegen-bun/char_to_string: ASCII, Latin-1, BMP and astral. - dune runtest: 856 tests pass. Bun codegen harnesses pass. check-soundness-ledger.sh: all 5 properties hold. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK --- docs/ON-RAMP.adoc | 3 + docs/SOUNDNESS.adoc | 22 +++- lib/codegen_deno.ml | 2 + lib/face.ml | 7 +- lib/interp.ml | 5 + lib/json_output.ml | 22 +++- lib/resolve.ml | 2 +- lib/typecheck.ml | 69 ++++++++++- stdlib/string.affine | 1 + test/test_call_diagnostics.ml | 113 +++++++++++++++++++ test/test_deno_builtins_consistency.ml | 2 +- test/test_main.ml | 1 + tests/codegen-bun/char_to_string.affine | 10 ++ tests/codegen-bun/char_to_string.harness.mjs | 12 ++ tools/soundness-anchors.sha256 | 1 - 15 files changed, 260 insertions(+), 12 deletions(-) create mode 100644 test/test_call_diagnostics.ml create mode 100644 tests/codegen-bun/char_to_string.affine create mode 100644 tests/codegen-bun/char_to_string.harness.mjs diff --git a/docs/ON-RAMP.adoc b/docs/ON-RAMP.adoc index a7733fca..3078c289 100644 --- a/docs/ON-RAMP.adoc +++ b/docs/ON-RAMP.adoc @@ -285,6 +285,9 @@ pub fn f(o: Opt) -> Int { that can continue an expression (`*`, `-`, `(`, `[`, `&`, `|`) is read as that longer expression, so `match o { .. } -1;` subtracts. Put a `;` after the `}` when the next statement starts with one of those tokens. + When the continued expression is a call on the statement's value, the + type checker says so: E0104 names the `if` or `match`, gives its line, and + suggests the `;`. Empty arm bodies (`Pat => {}`) are fine, in any position. Both rules are pinned in `test/test_e2e.ml` (`test_match_statement_self_terminates`). diff --git a/docs/SOUNDNESS.adoc b/docs/SOUNDNESS.adoc index 21bccb16..77449ac2 100644 --- a/docs/SOUNDNESS.adoc +++ b/docs/SOUNDNESS.adoc @@ -4,7 +4,7 @@ // Freshness stamp — a real main-ancestor commit (survives squash-merge); advance // it (and --reseal) in any change that touches a soundness path. See "Keeping // this honest" and tools/check-soundness-ledger.sh (property 4). -:ground-truth-sha: 84eca60 +:ground-truth-sha: 4a55253 :ground-truth-date: 2026-12-01 :stamp-verified-by: tools/check-soundness-ledger.sh :toc: macro @@ -311,6 +311,26 @@ write into the literal region. Layout invariant: `test_wasm_heap_literals_intact_after_alloc` — run under Bun's WASI; `test_wasm_heap_exhaustion_traps`); `lib/codegen.ml` `memory_layout_of_datas` / `check_memory_layout` + +| #833 +| The tree-walking interpreter — the oracle the compiled backends are compared +against — runs the programs the checker accepts and agrees with Bun-ESM on +them. It used to refuse a function that calls itself, one that calls a later +declaration, any `let mut` / `const mut` assignment, and any use of an +imported `Some` / `None` / `Ok` / `Err` (all loud). One shape was *silent*: an +early `return` evaluated its operand and carried on, so +`if c { return 1; } 2` yielded `2`. (The assignment arm also ignored a +compound operator — `a += 5` would have stored `5` — which a +`let mut` program could not reach, because the assignment failed first.) `affinescript eval` also type-checked +with its own fold of `Typecheck.check_decl`, without the signature +pre-registration of `Typecheck.check_program`, so it rejected forward and +mutual references that `check` and `compile` accept; it now calls +`check_program`. Not changed: `eval` still does not run the borrow checker +(`check` and `compile` do), so it accepts programs they reject. +| `fixed` +| `test/test_interp_eval.ml` (18 cases: each program passes the full frontend, +then its interpreter output is compared with the expected lines and with the +Bun-ESM output of the same program; all 18 fail on `4248912`). |=== == Still open — read before claiming "sound" diff --git a/lib/codegen_deno.ml b/lib/codegen_deno.ml index b51dc1e9..b0bd2187 100644 --- a/lib/codegen_deno.ml +++ b/lib/codegen_deno.ml @@ -1313,6 +1313,8 @@ let () = b "parse_float" (fun a -> Printf.sprintf "__as_parseFloat(%s)" (arg 0 a)); b "char_to_int" (fun a -> Printf.sprintf "__as_charToInt(%s)" (arg 0 a)); b "int_to_char" (fun a -> Printf.sprintf "__as_intToChar(%s)" (arg 0 a)); + (* A Char is a JS string of one code point, so this is the identity. *) + b "char_to_string" (fun a -> Printf.sprintf "String(%s)" (arg 0 a)); b "string_char_code_at" (fun a -> Printf.sprintf "__as_strCharCodeAt(%s, %s)" (arg 0 a) (arg 1 a)); b "string_from_char_code" diff --git a/lib/face.ml b/lib/face.ml index 68ce3db4..6e63ec39 100644 --- a/lib/face.ml +++ b/lib/face.ml @@ -316,7 +316,12 @@ let format_unify_error (face : face) (ue : Unify.unify_error) : string = (* ─── Type errors ────────────────────────────────────────────────────── *) (** Format a type-checker error for the given face. *) -let format_type_error (face : face) (err : Typecheck.type_error) : string = +let rec format_type_error (face : face) (err : Typecheck.type_error) : string = + match err with + | Typecheck.Located (inner, span) -> + Format.asprintf "%a: %s" Span.pp_short span (format_type_error face inner) + | Typecheck.StatementContinued _ -> Typecheck.format_type_error err + | _ -> match face with | Canonical -> Typecheck.format_type_error err | Js -> diff --git a/lib/interp.ml b/lib/interp.ml index 9198fb2e..95e67b2a 100644 --- a/lib/interp.ml +++ b/lib/interp.ml @@ -900,6 +900,11 @@ let create_initial_env () : env = else Error (RuntimeError "int_to_char: code point out of ASCII range") | _ -> Error (TypeMismatch "int_to_char expects Int") )); + ("char_to_string", VBuiltin ("char_to_string", fun args -> + match args with + | [VChar c] -> Ok (VString (String.make 1 c)) + | _ -> Error (TypeMismatch "char_to_string expects Char") + )); (* Byte-oriented String <-> Int accessors (see typecheck.ml bindings). string_char_code_at returns the 0..255 byte at [i]; out-of-bounds reads return -1 (mirroring string_find's "absent" sentinel rather diff --git a/lib/json_output.ml b/lib/json_output.ml index 9dde6b4f..5fc67ea9 100644 --- a/lib/json_output.ml +++ b/lib/json_output.ml @@ -190,11 +190,25 @@ let of_resolve_error (e : Resolve.resolve_error) (span : Span.t) : diagnostic = (** Convert a type error to a diagnostic. - Type errors currently lack span information in the compiler, so we - use [Span.dummy] as a placeholder. Phase B will thread spans through - the type checker. *) -let of_type_error (e : Typecheck.type_error) : diagnostic = + Phase B: an error wrapped in [Typecheck.Located] carries its span, and + [QuantityError] carries one of its own; every other type error still + reports [Span.dummy] until its site learns a span. *) +let rec of_type_error (e : Typecheck.type_error) : diagnostic = + match e with + | Typecheck.Located (inner, span) -> { (of_type_error inner) with span } + | Typecheck.QuantityError (_, span) when span <> Span.dummy -> + { (of_type_error_body e) with span } + | _ -> of_type_error_body e + +and of_type_error_body (e : Typecheck.type_error) : diagnostic = let code, message, help = match e with + | Typecheck.Located (inner, _) -> + let d = of_type_error inner in d.code, d.message, d.help + | Typecheck.StatementContinued { kind; ty } -> + "E0104", + Printf.sprintf "Expected a function, got %s: the `%s` statement before `(` was read as a call on its value" + (Types.show_ty ty) kind, + Some "A statement `if` or `match` followed by `(`, `[`, `*`, `-`, `&` or `|` continues the expression (docs/ON-RAMP.adoc, \"Statements and `;`\"). Put `;` after its closing `}`." | Typecheck.UnboundVariable v -> "E0100", Printf.sprintf "Unbound variable: %s" v, Some "Check spelling or add an import" diff --git a/lib/resolve.ml b/lib/resolve.ml index 009e96cd..09463634 100644 --- a/lib/resolve.ml +++ b/lib/resolve.ml @@ -69,7 +69,7 @@ let seed_builtins (symbols : Symbol.t) : unit = def "net_recv"; def "net_send"; def "net_accept"; (* String / char builtins *) def "len"; def "slice"; def "string_get"; def "string_sub"; def "string_find"; - def "char_to_int"; def "int_to_char"; def "show"; + def "char_to_int"; def "int_to_char"; def "char_to_string"; def "show"; def "string_char_code_at"; def "string_from_char_code"; def "to_lowercase"; def "to_uppercase"; def "trim"; def "int_to_string"; def "float_to_string"; def "string_length"; diff --git a/lib/typecheck.ml b/lib/typecheck.ml index 873d4e67..d13de2b0 100644 --- a/lib/typecheck.ml +++ b/lib/typecheck.ml @@ -127,6 +127,19 @@ type type_error = (** Two impls of the same trait have overlapping (unifiable) self types, so method resolution would be ambiguous (#559). The string is the human-readable overlap description. *) + | StatementContinued of { kind : string; ty : ty } + (** An `if` or `match` statement whose closing `}` is followed by `(` + was read as a call on the statement's value (#644: a statement + `if`/`match` followed by `(`, `[`, `*`, `-`, `&` or `|` continues + the expression). [kind] is "if" or "match"; [ty] is the value + that was called. Reported in place of [NotAFunction] so the + message names the rule and its remedy. *) + | Located of type_error * Span.t + (** An error with the source location it was found at. Phase B of + the span threading (json_output.ml): renderers print the + location, then the inner error. Raised first at calls + ([NotAFunction], [StatementContinued]); other errors gain it as + their sites learn a span. *) (* Known exports of stdlib/prelude.affine. Mirrors the same list in lib/face.ml — when an UnboundVariable fires at type-check time with @@ -149,7 +162,17 @@ let prelude_hint (name : string) : string = else "" (** Format a type error for human consumption. *) -let show_type_error = function +let rec show_type_error = function + | Located (e, span) -> + Format.asprintf "%a: %s" Span.pp_short span (show_type_error e) + | StatementContinued { kind; ty } -> + Printf.sprintf + "Expected a function type, got %s: the `%s` statement before `(` was \ + read as a call on its value. A statement `if` or `match` followed by \ + `(`, `[`, `*`, `-`, `&` or `|` continues the expression \ + (docs/ON-RAMP.adoc, \"Statements and `;`\"). Put `;` after its \ + closing `}`." + (ty_to_string ty) kind | UnboundVariable v -> "Unbound variable: " ^ v ^ prelude_hint v | TypeMismatch { expected; got } -> Printf.sprintf "Type mismatch: expected %s, got %s" @@ -211,6 +234,38 @@ let show_type_error = function let format_type_error = show_type_error +(** Where an expression starts, when the AST knows: identifiers and + literals carry spans; compound expressions take the span of their + first spanned part. [None] when nothing in it is spanned. *) +let rec expr_start_span (e : expr) : Span.t option = + let known s = if s = Span.dummy then None else Some s in + match e with + | ExprSpan (_, s) -> known s + | ExprVar id -> known id.span + | ExprLit (LitInt (_, s) | LitFloat (_, s) | LitBool (_, s) + | LitChar (_, s) | LitString (_, s) | LitUnit s) -> known s + | ExprIf { ei_cond; _ } -> expr_start_span ei_cond + | ExprMatch { em_scrutinee; _ } -> expr_start_span em_scrutinee + | ExprApp (f, _) | ExprField (f, _) | ExprTupleIndex (f, _) + | ExprIndex (f, _) | ExprBinary (f, _, _) | ExprUnary (_, f) -> expr_start_span f + | ExprTuple (f :: _) | ExprArray (f :: _) -> expr_start_span f + | _ -> None + +(** The error for calling [callee] whose type [ty] is not a function: + [StatementContinued] when the callee is a statement `if`/`match` + continued by `(` (#644), else [NotAFunction]; located when the + callee's start is known. *) +let not_a_function_error (callee : expr) (ty : ty) : type_error = + let rec strip = function ExprSpan (e, _) -> strip e | e -> e in + let err = match strip callee with + | ExprIf _ -> StatementContinued { kind = "if"; ty } + | ExprMatch _ -> StatementContinued { kind = "match"; ty } + | _ -> NotAFunction ty + in + match expr_start_span callee with + | Some s -> Located (err, s) + | None -> err + (** Raised by [lower_effect_expr] for an unknown effect name; caught at the [check_program] boundary and converted to [UnknownEffect] (lowering is not in the result monad). *) @@ -1058,6 +1113,10 @@ let rec synth (ctx : context) (expr : expr) : ty result = (* Function application *) | ExprApp (fn_expr, args) as app_node -> let* fn_ty = synth ctx fn_expr in + let locate_call r = match r with + | Error (NotAFunction t) -> Error (not_a_function_error fn_expr t) + | r -> r + 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 @@ -1078,9 +1137,9 @@ let rec synth (ctx : context) (expr : expr) : ty result = begin match repr fn_ty with | TArrow (param_ty, _q, ret_ty, _eff) when repr param_ty = ty_unit -> Ok ret_ty - | _ -> apply_args ctx fn_ty args + | _ -> locate_call (apply_args ctx fn_ty args) end - | _ -> apply_args ctx fn_ty args + | _ -> locate_call (apply_args ctx fn_ty args) end (* Tuple *) @@ -2152,6 +2211,10 @@ let register_builtins (ctx : context) : unit = bind_var ctx "parse_float" (TArrow (ty_string, QOmega, opt ty_float, EPure)); bind_var ctx "char_to_int" (TArrow (ty_char, QOmega, ty_int, EPure)); bind_var ctx "int_to_char" (TArrow (ty_int, QOmega, ty_char, EPure)); + (* One Char as a one-character String. Without it, code that builds a + String from code points had no total route: string_from_char_code + keeps only the low 8 bits. *) + bind_var ctx "char_to_string" (TArrow (ty_char, QOmega, ty_string, EPure)); (* Byte-oriented String accessors underpinning stdlib/encoding.affine's base64. Unlike string_get/int_to_char (which traffic in [Char] and, on the interpreter, clamp to ASCII), these go String<->Int directly so a diff --git a/stdlib/string.affine b/stdlib/string.affine index ed42e9fb..9a996e50 100644 --- a/stdlib/string.affine +++ b/stdlib/string.affine @@ -16,6 +16,7 @@ // parse_float(s) -> Option (string to float) // char_to_int(c) -> Int (character to ASCII code point) // int_to_char(n) -> Char (ASCII code point to character) +// char_to_string(c) -> String (one Char as a one-character String) // show(v) -> String (any value to debug string) // Cross-module import (ADR-011: explicit `use module::{...}`) diff --git a/test/test_call_diagnostics.ml b/test/test_call_diagnostics.ml new file mode 100644 index 00000000..c2d8b67b --- /dev/null +++ b/test/test_call_diagnostics.ml @@ -0,0 +1,113 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* Copyright (c) 2026 Jonathan D.A. Jewell *) +(** Calling a value that is not a function: where, and why. + + E0104 used to carry no location, even with [check --json] (start line + 0, file ""), so a program with one bad call gave no clue which + line it was on. Its commonest cause is the documented #644 rule: a + statement [if] or [match] followed on the next line by [(] continues + the expression, so [if c { .. }] then [(a, b)] is a call on Unit. + + These tests pin three things: the error now carries the callee's + location ([Typecheck.Located]); a continued [if]/[match] is reported + as [StatementContinued], naming the rule and the remedy; and the + remedy, a [;] after the [}], type-checks. They also pin the + [char_to_string] builtin. *) + +open Affinescript + +let typecheck (src : string) : (unit, Typecheck.type_error) result = + let prog = Parse_driver.parse_string ~file:"t.affine" src in + let dir = Sys.getcwd () in + let config = + { (Module_loader.default_config ()) with current_dir = dir; search_paths = [ dir ] } + in + let loader = Module_loader.create config in + match Resolve.resolve_program_with_loader prog loader with + | Error (e, _) -> Alcotest.failf "resolution error: %s" (Resolve.show_resolve_error e) + | Ok (rc, tc) -> + (match Typecheck.check_program ~import_types:tc.Typecheck.name_types rc.symbols prog with + | Ok _ -> Ok () + | Error e -> Error e) + +let expect_error src = + match typecheck src with + | Ok () -> Alcotest.fail "expected a type error, got Ok" + | Error e -> e + +let line_of (e : Typecheck.type_error) = + match e with + | Typecheck.Located (_, s) -> s.Span.start_pos.line + | _ -> Alcotest.failf "error has no location: %s" (Typecheck.format_type_error e) + +let continued_if_is_named_and_located () = + let e = expect_error + "pub fn f(t: Int) -> (Int, Int) {\n\ + \ let mut u = t;\n\ + \ if u > 0 { u = 1; }\n\ + \ (u, 2)\n\ + }\n" in + Alcotest.(check int) "line of the if" 3 (line_of e); + match e with + | Typecheck.Located (Typecheck.StatementContinued { kind = "if"; _ }, _) -> () + | _ -> Alcotest.failf "expected StatementContinued if, got %s" (Typecheck.format_type_error e) + +let continued_match_is_named_and_located () = + let e = expect_error + "pub fn f(t: Int) -> (Int, Int) {\n\ + \ let mut u = t;\n\ + \ match u { 0 => { u = 1; }, _ => {} }\n\ + \ (u, 2)\n\ + }\n" in + Alcotest.(check int) "line of the match" 3 (line_of e); + match e with + | Typecheck.Located (Typecheck.StatementContinued { kind = "match"; _ }, _) -> () + | _ -> Alcotest.failf "expected StatementContinued match, got %s" (Typecheck.format_type_error e) + +let the_documented_remedy_typechecks () = + match typecheck + "pub fn f(t: Int) -> (Int, Int) {\n\ + \ let mut u = t;\n\ + \ if u > 0 { u = 1; };\n\ + \ (u, 2)\n\ + }\n" with + | Ok () -> () + | Error e -> Alcotest.failf "the ; remedy should type-check: %s" (Typecheck.format_type_error e) + +let plain_bad_call_is_located () = + let e = expect_error "pub fn h(n: Int) -> Int {\n n(1)\n}\n" in + Alcotest.(check int) "line of the call" 2 (line_of e); + match e with + | Typecheck.Located (Typecheck.NotAFunction _, _) -> () + | _ -> Alcotest.failf "expected NotAFunction, got %s" (Typecheck.format_type_error e) + +let text_and_json_carry_the_location () = + let e = expect_error "pub fn h(n: Int) -> Int {\n n(1)\n}\n" in + let text = Typecheck.format_type_error e in + Alcotest.(check bool) "text starts with t.affine:2:" true + (String.length text > 11 && String.sub text 0 11 = "t.affine:2:"); + let d = Json_output.of_type_error e in + Alcotest.(check string) "json code" "E0104" d.Json_output.code; + Alcotest.(check int) "json start line" 2 d.Json_output.span.Span.start_pos.line; + Alcotest.(check string) "json file" "t.affine" d.Json_output.span.Span.file + +let char_to_string_types () = + match typecheck + "pub fn g(c: Int) -> String {\n\ + \ char_to_string(int_to_char(c)) ++ \"!\"\n\ + }\n" with + | Ok () -> () + | Error e -> Alcotest.failf "char_to_string should type: %s" (Typecheck.format_type_error e) + +let char_to_string_rejects_a_string () = + ignore (expect_error "pub fn g(s: String) -> String {\n char_to_string(s)\n}\n") + +let tests = [ + Alcotest.test_case "continued if: named and located" `Quick continued_if_is_named_and_located; + Alcotest.test_case "continued match: named and located" `Quick continued_match_is_named_and_located; + Alcotest.test_case "the ; remedy type-checks" `Quick the_documented_remedy_typechecks; + Alcotest.test_case "plain call on a non-function is located" `Quick plain_bad_call_is_located; + Alcotest.test_case "text and JSON carry the location" `Quick text_and_json_carry_the_location; + Alcotest.test_case "char_to_string : Char -> String" `Quick char_to_string_types; + Alcotest.test_case "char_to_string rejects a String" `Quick char_to_string_rejects_a_string; +] diff --git a/test/test_deno_builtins_consistency.ml b/test/test_deno_builtins_consistency.ml index b945484b..37f11399 100644 --- a/test/test_deno_builtins_consistency.ml +++ b/test/test_deno_builtins_consistency.ml @@ -82,7 +82,7 @@ let list_stdlib_affine () = let codegen_only_names = [ "len"; "panic"; "get"; "set"; "slice"; "show"; "error"; "make_ref"; "int_to_string"; "float_to_string"; "string_to_int"; "parse_int"; - "parse_float"; "int_to_char"; "char_to_int"; + "parse_float"; "int_to_char"; "char_to_int"; "char_to_string"; (* stdlib/math.affine header builtins (resolver-level, no extern decl); the rest of that family is registered in a loop the regex skips. *) "float"; "atan2"; "pow_float"; diff --git a/test/test_main.ml b/test/test_main.ml index 80e76955..8330696b 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -29,6 +29,7 @@ let () = ("Qualified paths (#228, ADR-014)", Test_qualified_paths.tests); ("Generic enum kinds", Test_generic_enum_kinds.tests); ("Block-scoped let in the type checker", Test_block_scope.tests); + ("Call diagnostics: location, continued statements, char_to_string", Test_call_diagnostics.tests); ("Module search path ($AFFINESCRIPT_PATH)", Test_module_search_path.tests); ("Module root, decl match, flattening, interp binops, Bun-ESM return-in-arm", Test_module_root_flatten.tests); ("Record update + imported types", Test_records_and_imports.tests); diff --git a/tests/codegen-bun/char_to_string.affine b/tests/codegen-bun/char_to_string.affine new file mode 100644 index 00000000..bd44435a --- /dev/null +++ b/tests/codegen-bun/char_to_string.affine @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MPL-2.0 +// char_to_string: one Char as a one-character String, for any code point +// (string_from_char_code keeps only the low 8 bits). +pub fn one(c: Int) -> String { + char_to_string(int_to_char(c)) +} + +pub fn spell(a: Int, b: Int, c: Int) -> String { + char_to_string(int_to_char(a)) ++ char_to_string(int_to_char(b)) ++ char_to_string(int_to_char(c)) +} diff --git a/tests/codegen-bun/char_to_string.harness.mjs b/tests/codegen-bun/char_to_string.harness.mjs new file mode 100644 index 00000000..95e435d5 --- /dev/null +++ b/tests/codegen-bun/char_to_string.harness.mjs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +import * as subject from "./char_to_string.bun.js"; + +const expect = (label, got, want) => { + if (got !== want) throw new Error(`${label}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`); +}; +expect("ASCII", subject.one(65), "A"); +expect("Latin-1 above 127", subject.one(233), "é"); +expect("above 255 (string_from_char_code would truncate)", subject.one(0x4e2d), "中"); +expect("astral code point", subject.one(0x1f600), "😀"); +expect("concatenation", subject.spell(104, 105, 33), "hi!"); +console.log("char_to_string: ok"); diff --git a/tools/soundness-anchors.sha256 b/tools/soundness-anchors.sha256 index 2d788c56..8d9a6543 100644 --- a/tools/soundness-anchors.sha256 +++ b/tools/soundness-anchors.sha256 @@ -9,7 +9,6 @@ 20e73d88738c8fd075f81a36803554f92fa4ee53f71e33fa6759eae07c6e70f4 suite:test/test_intrinsic_shadow.ml 2bbd1b989fd0097530eede3e5230258e0e1092271a23ff7dff20cca65c0e612e suite:test/test_wasm_call_resolution.ml 2dfe36a21983a7dfb7ffa1157f7ddec9865a531a92682976b8fd677e4825e78d test:test_801_impl_methods_refused -3b74c20f201d0d53c2fbab5582a681d3dfc3cf978a0aea676ecc6400087452d9 suite:test/test_intrinsic_shadow.ml 45eb0f3aa5f643afbd003248998dd5a046688418647b491e0f2d4bb55fcbd0f2 test:test_wasm_heap_exhaustion_traps 546939eaa3c64c82edd23da0a3ba7f74bcf7378cfe1e426132dd1a9f8fd46050 test:test_801_transitive_public_and_const 5b84a4f71aa65f9aa9383e31c0cb624291c4f9d0de7cca4a0ea6a76fe85aea35 fixture:test/e2e/fixtures/handle_resume_nontail.affine From 583dc7adee91f4e6e8d7a0e38fc6363cf3d9cdfc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 20:41:11 +0000 Subject: [PATCH 2/3] fix(diagnostics): name a continued if/match only when its value is Unit CodeRabbit review on #862: `(if c { 1 } else { 2 })(3)` in value position was reported as a continued statement and told to add a `;` it does not need. A statement `if`/`match` has the value Unit, so that type is now the evidence. Any other callee type keeps located NotAFunction. Test: value_position_if_keeps_not_a_function. dune runtest: 857 pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK --- lib/typecheck.ml | 12 +++++++++--- test/test_call_diagnostics.ml | 13 +++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/typecheck.ml b/lib/typecheck.ml index d13de2b0..d5eb5a3c 100644 --- a/lib/typecheck.ml +++ b/lib/typecheck.ml @@ -254,12 +254,18 @@ let rec expr_start_span (e : expr) : Span.t option = (** The error for calling [callee] whose type [ty] is not a function: [StatementContinued] when the callee is a statement `if`/`match` continued by `(` (#644), else [NotAFunction]; located when the - callee's start is known. *) + callee's start is known. + + The evidence for "a statement was continued" is the callee's type: a + statement `if`/`match` has the value Unit. A value-position + `(if c { 1 } else { 2 })(3)` calls an Int and keeps [NotAFunction], + so it is not told to add a `;` it does not need. *) let not_a_function_error (callee : expr) (ty : ty) : type_error = let rec strip = function ExprSpan (e, _) -> strip e | e -> e in + let is_unit = (match ty with TCon "Unit" -> true | TTuple [] -> true | _ -> false) in let err = match strip callee with - | ExprIf _ -> StatementContinued { kind = "if"; ty } - | ExprMatch _ -> StatementContinued { kind = "match"; ty } + | ExprIf _ when is_unit -> StatementContinued { kind = "if"; ty } + | ExprMatch _ when is_unit -> StatementContinued { kind = "match"; ty } | _ -> NotAFunction ty in match expr_start_span callee with diff --git a/test/test_call_diagnostics.ml b/test/test_call_diagnostics.ml index c2d8b67b..c063f73f 100644 --- a/test/test_call_diagnostics.ml +++ b/test/test_call_diagnostics.ml @@ -64,6 +64,18 @@ let continued_match_is_named_and_located () = | Typecheck.Located (Typecheck.StatementContinued { kind = "match"; _ }, _) -> () | _ -> Alcotest.failf "expected StatementContinued match, got %s" (Typecheck.format_type_error e) +(* A value-position `if` that is not Unit was not a continued statement: + plain E0104, located, with no `;` advice (CodeRabbit review on #862). *) +let value_position_if_keeps_not_a_function () = + let e = expect_error + "pub fn f(c: Bool) -> Int {\n\ + \ let y = (if c { 1 } else { 2 })(3);\n\ + \ y\n\ + }\n" in + match e with + | Typecheck.Located (Typecheck.NotAFunction _, _) -> () + | _ -> Alcotest.failf "expected located NotAFunction, got %s" (Typecheck.format_type_error e) + let the_documented_remedy_typechecks () = match typecheck "pub fn f(t: Int) -> (Int, Int) {\n\ @@ -106,6 +118,7 @@ let tests = [ Alcotest.test_case "continued if: named and located" `Quick continued_if_is_named_and_located; Alcotest.test_case "continued match: named and located" `Quick continued_match_is_named_and_located; Alcotest.test_case "the ; remedy type-checks" `Quick the_documented_remedy_typechecks; + Alcotest.test_case "value-position if keeps NotAFunction" `Quick value_position_if_keeps_not_a_function; Alcotest.test_case "plain call on a non-function is located" `Quick plain_bad_call_is_located; Alcotest.test_case "text and JSON carry the location" `Quick text_and_json_carry_the_location; Alcotest.test_case "char_to_string : Char -> String" `Quick char_to_string_types; From d272e53afd9769fcbb9ff2de8d42c28a23c965f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 21:01:03 +0000 Subject: [PATCH 3/3] fix(diagnostics): continued if/match also needs statement position CodeRabbit follow-up on #862: Unit alone is not evidence of a continued statement. `let y = (if c { () } else { () })(3);` is a Unit-valued call in value position, and it was still told to add a `;`. A #644 continuation can only appear as a call that stands as a whole statement or as a block's final expression. synth_block_body now records those calls (statement_calls, compared by physical identity, reset by each check_program). StatementContinued requires that position and the Unit type. The known limit is in the doc comment: parentheses are not in the AST, so `(if c { () } else { () })(3);` standing alone as a statement is still read as a continuation. Tests: unit_valued_value_position_keeps_not_a_function (if and match). dune runtest: 858 pass. Ledger: 5/5. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK --- lib/typecheck.ml | 46 ++++++++++++++++++++++++++--------- test/test_call_diagnostics.ml | 12 +++++++++ 2 files changed, 47 insertions(+), 11 deletions(-) diff --git a/lib/typecheck.ml b/lib/typecheck.ml index d5eb5a3c..b49f914c 100644 --- a/lib/typecheck.ml +++ b/lib/typecheck.ml @@ -251,21 +251,42 @@ let rec expr_start_span (e : expr) : Span.t option = | ExprTuple (f :: _) | ExprArray (f :: _) -> expr_start_span f | _ -> None +(** Calls that stand as a whole statement, or as a block's final + expression, with an `if`/`match` callee: the only places a #644 + continuation can produce. Recorded by [synth_block_body], compared by + physical identity. *) +let statement_calls : expr list ref = ref [] + +let rec strip_spans = function ExprSpan (e, _) -> strip_spans e | e -> e + +let note_statement_call (e : expr) : unit = + match strip_spans e with + | ExprApp (f, _) as app -> + (match strip_spans f with + | ExprIf _ | ExprMatch _ -> statement_calls := app :: !statement_calls + | _ -> ()) + | _ -> () + (** The error for calling [callee] whose type [ty] is not a function: [StatementContinued] when the callee is a statement `if`/`match` continued by `(` (#644), else [NotAFunction]; located when the callee's start is known. - The evidence for "a statement was continued" is the callee's type: a - statement `if`/`match` has the value Unit. A value-position - `(if c { 1 } else { 2 })(3)` calls an Int and keeps [NotAFunction], - so it is not told to add a `;` it does not need. *) -let not_a_function_error (callee : expr) (ty : ty) : type_error = - let rec strip = function ExprSpan (e, _) -> strip e | e -> e in - let is_unit = (match ty with TCon "Unit" -> true | TTuple [] -> true | _ -> false) in - let err = match strip callee with - | ExprIf _ when is_unit -> StatementContinued { kind = "if"; ty } - | ExprMatch _ when is_unit -> StatementContinued { kind = "match"; ty } + The evidence for "a statement was continued" is twofold: the call + stands as a statement or as a block's final expression + ([statement_calls]), and the callee's value is Unit, as a statement + `if`/`match` has. A value-position call such as + `let y = (if c { () } else { () })(3);` keeps [NotAFunction], so it is + not told to add a `;` it does not need. (A parenthesised callee is not + visible in the AST, so `(if c { () } else { () })(3);` standing alone + as a statement is still read as a continuation.) *) +let not_a_function_error (app : expr) (callee : expr) (ty : ty) : type_error = + let continued = + List.memq app !statement_calls + && (match ty with TCon "Unit" -> true | TTuple [] -> true | _ -> false) in + let err = match strip_spans callee with + | ExprIf _ when continued -> StatementContinued { kind = "if"; ty } + | ExprMatch _ when continued -> StatementContinued { kind = "match"; ty } | _ -> NotAFunction ty in match expr_start_span callee with @@ -1120,7 +1141,7 @@ let rec synth (ctx : context) (expr : expr) : ty result = | ExprApp (fn_expr, args) as app_node -> let* fn_ty = synth ctx fn_expr in let locate_call r = match r with - | Error (NotAFunction t) -> Error (not_a_function_error fn_expr t) + | Error (NotAFunction t) -> Error (not_a_function_error app_node fn_expr t) | r -> r in (* #560: remember the instantiated type at `slice`/`show` calls; the @@ -1682,6 +1703,8 @@ and synth_block (ctx : context) (blk : block) : ty result = Fun.protect ~finally:restore (fun () -> synth_block_body ctx blk) and synth_block_body (ctx : context) (blk : block) : ty result = + List.iter (function StmtExpr e -> note_statement_call e | _ -> ()) blk.blk_stmts; + Option.iter note_statement_call blk.blk_expr; (* Type-check each statement for side effects *) let* () = List.fold_left (fun acc stmt -> let* () = acc in @@ -2758,6 +2781,7 @@ let check_program ?(import_types : (string, scheme) Hashtbl.t option) (symbols : Symbol.t) (prog : Ast.program) : (context, type_error) Result.t = try + statement_calls := []; let ctx = create_context symbols in register_builtins ctx; (* ADR-014 / #228: record `use Mod;` qualifiers so qualified type/effect diff --git a/test/test_call_diagnostics.ml b/test/test_call_diagnostics.ml index c063f73f..57d010bb 100644 --- a/test/test_call_diagnostics.ml +++ b/test/test_call_diagnostics.ml @@ -76,6 +76,17 @@ let value_position_if_keeps_not_a_function () = | Typecheck.Located (Typecheck.NotAFunction _, _) -> () | _ -> Alcotest.failf "expected located NotAFunction, got %s" (Typecheck.format_type_error e) +(* Unit-valued value-position calls: Unit alone is not evidence of a + continued statement; the call must also stand as a statement or a + block's final expression (CodeRabbit follow-up on #862). *) +let unit_valued_value_position_keeps_not_a_function () = + List.iter (fun src -> + match expect_error src with + | Typecheck.Located (Typecheck.NotAFunction _, _) -> () + | e -> Alcotest.failf "expected located NotAFunction, got %s" (Typecheck.format_type_error e)) + [ "pub fn f(c: Bool) -> Int {\n let y = (if c { () } else { () })(3);\n 0\n}\n"; + "pub fn f(n: Int) -> Int {\n let y = (match n { 0 => (), _ => () })(3);\n 0\n}\n" ] + let the_documented_remedy_typechecks () = match typecheck "pub fn f(t: Int) -> (Int, Int) {\n\ @@ -119,6 +130,7 @@ let tests = [ Alcotest.test_case "continued match: named and located" `Quick continued_match_is_named_and_located; Alcotest.test_case "the ; remedy type-checks" `Quick the_documented_remedy_typechecks; Alcotest.test_case "value-position if keeps NotAFunction" `Quick value_position_if_keeps_not_a_function; + Alcotest.test_case "Unit-valued value-position if/match keep NotAFunction" `Quick unit_valued_value_position_keeps_not_a_function; Alcotest.test_case "plain call on a non-function is located" `Quick plain_bad_call_is_located; Alcotest.test_case "text and JSON carry the location" `Quick text_and_json_carry_the_location; Alcotest.test_case "char_to_string : Char -> String" `Quick char_to_string_types;