Skip to content

Commit 356ef58

Browse files
cknittclaude
andcommitted
Drop literal arms that a complete payload dispatch runs anyway
A complete payload dispatch with one body runs it unchecked, so a literal arm with the same body needs no case of its own. JS modified (literal arm equal to the payload arm): Example: @unboxed type rec t = | @as(null) Null | @as(undefined) Undefined | WhyNotAnotherOne | Point({x: int, y: int}) let plus = (x, y) => switch y { | Null | Undefined => x | WhyNotAnotherOne => WhyNotAnotherOne | Point(_) => WhyNotAnotherOne } Before (js): switch (y) { case null : case undefined : return x; case "WhyNotAnotherOne" : return "WhyNotAnotherOne"; default: return "WhyNotAnotherOne"; } After (js): if (y == null) { return x; } else { return "WhyNotAnotherOne"; } Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent e99e3ae commit 356ef58

2 files changed

Lines changed: 17 additions & 8 deletions

File tree

‎compiler/core/lam_compile.ml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,19 @@ let compile output_prefix =
886886
| Some arms -> arms @ unnamed
887887
| None -> assert false
888888
in
889+
(* A complete payload dispatch with one body runs it unchecked,
890+
so a literal arm with the same body can go there too *)
891+
let literal_arms =
892+
match (blocks_default, sw_blocks) with
893+
| Complete, (_, body) :: rest
894+
when List.for_all
895+
(fun (_, other) -> Lambda.eq_approx body other)
896+
rest ->
897+
List.filter
898+
(fun (_, lam) -> not (Lambda.eq_approx body lam))
899+
literal_arms
900+
| _ -> literal_arms
901+
in
889902
let payload =
890903
Compiled
891904
(fun cxt ->

‎tests/tests/src/variantsMatching.mjs‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -287,14 +287,10 @@ function plus$3(x, y) {
287287
};
288288
}
289289
}
290-
switch (y) {
291-
case null :
292-
case undefined :
293-
return x;
294-
case "WhyNotAnotherOne" :
295-
return "WhyNotAnotherOne";
296-
default:
297-
return "WhyNotAnotherOne";
290+
if (y == null) {
291+
return x;
292+
} else {
293+
return "WhyNotAnotherOne";
298294
}
299295
}
300296

0 commit comments

Comments
 (0)