From 3e4638373dfe7ac09c9499969cdbeedf93cc6113 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 1 Dec 2026 19:42:23 +0000 Subject: [PATCH] Fix inlined char switches losing their result Why: When a function with a switch is inlined into a call such as `classify('d')`, the switch's argument is a constant, so constant folding can replace the switch with the matching case. Lambda did this for int constants but not for char constants, so JavaScript generation folded the switch instead. It took only the body of the matching case. But cases with the same action share one body: case 100 has an empty body and falls through to case 101. So nothing assigned the result. JavaScript generation now follows the fall-through when it folds a switch: it takes the first body that isn't empty. Lambda also folds a switch on a char constant, as it does for an int. JS modified (inlined switch on a char constant): Example: @inline let classify = x => switch x { | 'a' => "a" | 98 => "b" | 'c' .. 'e' => "c-e" | 102 | 'g' => "f-g" | _ => "other" } @inline let check = (actual, expected) => Console.log((actual, expected)) check(classify('d'), "c-e") Before (js): let actual; console.log([actual, "c-e"]); After (js): console.log(["c-e", "c-e"]); Fixes #9489 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gH9cXWp3xtBmfRV3Du Signed-off-by: Christoph Knittel --- changes/inline-char-switch-result.fix.md | 1 + compiler/backend/js_stmt_make.ml | 53 +++++++++------- compiler/typing/lambda.ml | 34 +++++----- .../src/char_int_alias_test.mjs | 6 +- .../src/inline_constant_switch_test.mjs | 45 +++++++++++++ .../src/inline_constant_switch_test.res | 32 ++++++++++ .../ounit_constant_switch_tests.ml | 63 +++++++++++++++++++ tests/ounit_tests/ounit_tests_main.ml | 1 + 8 files changed, 192 insertions(+), 43 deletions(-) create mode 100644 changes/inline-char-switch-result.fix.md create mode 100644 tests/compiler_tests/src/inline_constant_switch_test.mjs create mode 100644 tests/compiler_tests/src/inline_constant_switch_test.res create mode 100644 tests/ounit_tests/ounit_constant_switch_tests.ml diff --git a/changes/inline-char-switch-result.fix.md b/changes/inline-char-switch-result.fix.md new file mode 100644 index 0000000000..fe26536ff2 --- /dev/null +++ b/changes/inline-char-switch-result.fix.md @@ -0,0 +1 @@ +- Fix an inlined switch on a char constant that lost its result when its case shared an action with the next case. diff --git a/compiler/backend/js_stmt_make.ml b/compiler/backend/js_stmt_make.ml index 52d00f39cf..33da5c1f44 100644 --- a/compiler/backend/js_stmt_make.ml +++ b/compiler/backend/js_stmt_make.ml @@ -75,22 +75,37 @@ let define_variable ~kind (v : Ident.t) (exp : J.expression) : t = source_loc = None; } +(* The statements a switch on a constant runs. A case with an empty body + that does not break shares the body of the case after it, as + [Lam_compile] groups cases with the same action. Falling off the last case + runs the default, which is printed after the cases. *) +let constant_switch_body ~(default : J.block option) ~matches + (clauses : ('a * J.case_clause) list) : J.block = + let rec from_clause = function + | (_, {J.switch_body = []; should_break = false}) :: rest -> + from_clause rest + | (_, (x : J.case_clause)) :: _ -> x.switch_body + | [] -> Option.value default ~default:[] + in + let rec find = function + | (key, _) :: _ as clauses when matches key -> from_clause clauses + | _ :: rest -> find rest + | [] -> ( + match default with + | Some x -> x + | None -> assert false) + in + find clauses + let int_switch ?(declaration : (J.property * Ident.t) option) ?(default : J.block option) (e : J.expression) (clauses : (int * J.case_clause) list) : t = match e.expression_desc with | Number (Int {i; _}) -> ( let continuation = - match + constant_switch_body ~default + ~matches:(fun switch_case -> switch_case = Int32.to_int i) clauses - |> List.find_map (fun (switch_case, (x : J.case_clause)) -> - if switch_case = Int32.to_int i then Some x.switch_body else None) - with - | Some case -> case - | None -> ( - match default with - | Some x -> x - | None -> assert false) in match (declaration, continuation) with | ( Some (kind, did), @@ -135,22 +150,12 @@ let string_switch ?(declaration : (J.property * Ident.t) option) match e.expression_desc with | Str txt -> ( let continuation = - match + constant_switch_body ~default + ~matches:(fun (switch_case : Variant_runtime.tag_type) -> + match switch_case with + | Literal (String s) -> s = txt + | Literal _ | Payload_shape _ -> false) clauses - |> List.find_map - (fun - ((switch_case : Variant_runtime.tag_type), (x : J.case_clause)) - -> - match switch_case with - | Literal (String s) -> - if s = txt then Some x.switch_body else None - | Literal _ | Payload_shape _ -> None) - with - | Some case -> case - | None -> ( - match default with - | Some x -> x - | None -> assert false) in match (declaration, continuation) with | ( Some (kind, did), diff --git a/compiler/typing/lambda.ml b/compiler/typing/lambda.ml index 5c289e56df..f38a5cc450 100644 --- a/compiler/typing/lambda.ml +++ b/compiler/typing/lambda.ml @@ -914,6 +914,22 @@ let switch lam (lam_switch : lambda_switch) : t = | Some action -> action | None -> Lswitch (lam, lam_switch)) in + let switch_on_int i = + (* Because of inlining and dead code, we might be looking at a value of unexpected type + e.g. an integer, so the const case might not be found *) + let action = + lam_switch.sw_consts + |> List.find_map (fun (key, action) -> + match key with + | Switch_int ordinal when ordinal = i -> Some action + | Switch_constructor (Constant {literal}) + when literal_denotes_same (Int i) literal -> + (* A constant represented as a number, compared by value *) + Some action + | Switch_int _ | Switch_constructor _ -> None) + in + action_or_switch action + in match (lam, lam_switch.sw_dispatch) with | Lconst cst, Switch_variant {block_types = _ :: _} -> ( (* An untagged variant is dispatched on the value, so a constant @@ -938,22 +954,8 @@ let switch lam (lam_switch : lambda_switch) : t = | Switch_int _ | Switch_constructor _ -> None) in action_or_switch action - | Lconst (Const_int i), _ -> - (* Because of inlining and dead code, we might be looking at a value of unexpected type - e.g. an integer, so the const case might not be found *) - let i = Int32.to_int i in - let action = - lam_switch.sw_consts - |> List.find_map (fun (key, action) -> - match key with - | Switch_int ordinal when ordinal = i -> Some action - | Switch_constructor (Constant {literal}) - when literal_denotes_same (Int i) literal -> - (* A constant represented as a number, compared by value *) - Some action - | Switch_int _ | Switch_constructor _ -> None) - in - action_or_switch action + | Lconst (Const_int i), _ -> switch_on_int (Int32.to_int i) + | Lconst (Const_char i), _ -> switch_on_int i | Lconst (Const_block (tag_info, _)), _ -> let runtime = match tag_info with diff --git a/tests/compiler_tests/src/char_int_alias_test.mjs b/tests/compiler_tests/src/char_int_alias_test.mjs index f25916d26b..0b3092c0fc 100644 --- a/tests/compiler_tests/src/char_int_alias_test.mjs +++ b/tests/compiler_tests/src/char_int_alias_test.mjs @@ -76,9 +76,9 @@ Mocha.describe("Char_int_alias_test", () => { }); Mocha.test("mixed patterns", () => { Test_utils.eq("File \"char_int_alias_test.res\", line 55, characters 7-14", "a", "a"); - Test_utils.eq("File \"char_int_alias_test.res\", line 56, characters 7-14", mixed(/* 'b' */98), "b"); - Test_utils.eq("File \"char_int_alias_test.res\", line 57, characters 7-14", mixed(/* 'd' */100), "c-e"); - Test_utils.eq("File \"char_int_alias_test.res\", line 58, characters 7-14", mixed(/* 'f' */102), "f-g"); + Test_utils.eq("File \"char_int_alias_test.res\", line 56, characters 7-14", "b", "b"); + Test_utils.eq("File \"char_int_alias_test.res\", line 57, characters 7-14", "c-e", "c-e"); + Test_utils.eq("File \"char_int_alias_test.res\", line 58, characters 7-14", "f-g", "f-g"); Test_utils.eq("File \"char_int_alias_test.res\", line 59, characters 7-14", "f-g", "f-g"); Test_utils.eq("File \"char_int_alias_test.res\", line 60, characters 7-14", "other", "other"); Test_utils.eq("File \"char_int_alias_test.res\", line 61, characters 7-14", "other", "other"); diff --git a/tests/compiler_tests/src/inline_constant_switch_test.mjs b/tests/compiler_tests/src/inline_constant_switch_test.mjs new file mode 100644 index 0000000000..3706a74610 --- /dev/null +++ b/tests/compiler_tests/src/inline_constant_switch_test.mjs @@ -0,0 +1,45 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; + +function classify(x) { + switch (x) { + case 97 : + return "a"; + case 98 : + return "b"; + case 99 : + case 100 : + case 101 : + return "c-e"; + case 102 : + case 103 : + return "f-g"; + default: + return "other"; + } +} + +function check(actual, expected) { + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", actual, expected); +} + +Mocha.describe("Inline_constant_switch_test", () => { + Mocha.test("an inlined switch on a char constant", () => { + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "a", "a"); + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "b", "b"); + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "c-e", "c-e"); + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "c-e", "c-e"); + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "c-e", "c-e"); + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "f-g", "f-g"); + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "f-g", "f-g"); + Test_utils.eq("File \"inline_constant_switch_test.res\", line 19, characters 37-44", "other", "other"); + }); +}); + +export { + classify, + check, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_constant_switch_test.res b/tests/compiler_tests/src/inline_constant_switch_test.res new file mode 100644 index 0000000000..c6f61d6625 --- /dev/null +++ b/tests/compiler_tests/src/inline_constant_switch_test.res @@ -0,0 +1,32 @@ +open Mocha +open Test_utils + +// Inlining both functions leaves a switch on a char constant. Cases with the +// same action share one body, so the result comes from the last case of a +// group. + +@inline +let classify = x => + switch x { + | 'a' => "a" + | 98 => "b" + | 'c' .. 'e' => "c-e" + | 102 | 'g' => "f-g" + | _ => "other" + } + +@inline +let check = (actual, expected) => eq(__LOC__, actual, expected) + +describe(__MODULE__, () => { + test("an inlined switch on a char constant", () => { + check(classify('a'), "a") + check(classify('b'), "b") + check(classify('c'), "c-e") + check(classify('d'), "c-e") + check(classify('e'), "c-e") + check(classify('f'), "f-g") + check(classify('g'), "f-g") + check(classify('z'), "other") + }) +}) diff --git a/tests/ounit_tests/ounit_constant_switch_tests.ml b/tests/ounit_tests/ounit_constant_switch_tests.ml new file mode 100644 index 0000000000..2f48a87548 --- /dev/null +++ b/tests/ounit_tests/ounit_constant_switch_tests.ml @@ -0,0 +1,63 @@ +let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: )) + +module E = Js_exp_make +module S = Js_stmt_make + +let result = Ident.create "result" + +let clause ?(should_break = true) body : J.case_clause = + {switch_body = body; should_break; comment = None; source_loc = None} + +(* A case with the same action as the case after it, as [Lam_compile] groups + them: an empty body that falls through. *) +let shared = clause ~should_break:false [] + +let assign s = clause [S.assign result (E.str s)] + +let default = [S.assign result (E.str "other")] + +(* The string a block assigns to [result], when that is all it does. *) +let assigned (s : J.statement) = + match s.statement_desc with + | Block [{statement_desc = Exp {expression_desc = Bin (Eq, _, value)}}] + | Exp {expression_desc = Bin (Eq, _, value)} + | Variable {value = Some value} -> ( + match value.expression_desc with + | Str txt -> txt + | _ -> OUnit.assert_failure "assigns something other than a string") + | _ -> OUnit.assert_failure "does more than assign the result" + +(* [switch (n) { case 1: case 2: case 3: result = "1-3"; break; case 4: + result = "4"; break; default: result = "other" }] *) +let int_switch ?declaration n = + S.int_switch ?declaration ~default (E.small_int n) + [(1, shared); (2, shared); (3, assign "1-3"); (4, assign "4")] + +let string_switch s = + S.string_switch ~default (E.str s) + [ + (Literal (String "a"), shared); + (Literal (String "b"), assign "a-b"); + (Literal (String "c"), assign "c"); + ] + +let suites = + __FILE__ + >::: [ + ( "a switch on a constant runs the body its case falls through to" + >:: fun _ -> + OUnit.assert_equal "1-3" (assigned (int_switch 1)); + OUnit.assert_equal "1-3" (assigned (int_switch 2)); + OUnit.assert_equal "1-3" (assigned (int_switch 3)); + OUnit.assert_equal "4" (assigned (int_switch 4)); + OUnit.assert_equal "other" (assigned (int_switch 5)) ); + ( "a declared result is defined by the body the case falls through to" + >:: fun _ -> + OUnit.assert_equal "1-3" + (assigned (int_switch ~declaration:(Lambda.Strict, result) 2)) ); + ( "a string switch on a constant falls through the same way" + >:: fun _ -> + OUnit.assert_equal "a-b" (assigned (string_switch "a")); + OUnit.assert_equal "c" (assigned (string_switch "c")); + OUnit.assert_equal "other" (assigned (string_switch "z")) ); + ] diff --git a/tests/ounit_tests/ounit_tests_main.ml b/tests/ounit_tests/ounit_tests_main.ml index 3c601f70c7..3e4b8ecebd 100644 --- a/tests/ounit_tests/ounit_tests_main.ml +++ b/tests/ounit_tests/ounit_tests_main.ml @@ -30,6 +30,7 @@ let suites = Ounit_pattern_printer_tests.suites; Ounit_js_analyzer_tests.suites; Ounit_external_shadow_tests.suites; + Ounit_constant_switch_tests.suites; Ounit_flow_parser_tests.suites; Ounit_jsx_loc_tests.suites; Ounit_parser_cursor_tests.suites;