Skip to content

Commit 27b5460

Browse files
cknittclaude
andauthored
Decide the untagged dispatch's literal cases by routing them (#9047)
* Decide the untagged dispatch's literal cases by routing them Why: A literal without an arm got a case whenever the variant had a class case, even where no class check runs on it, and arms of different kinds with one body kept the checks telling them apart. The literal arm left to a complete payload dispatch with one body assumed that dispatch runs no check, which held only because matching shares such bodies. A literal without an arm skips the literal switch when the payload dispatch, evaluated on it with `select`, takes it to the default without a class check. The plan is simplified: a test whose branches run the same, and a case that runs what its default runs, are left out, and a literal with the body of a payload dispatch that runs one body unchecked gets no case. The property test also checks that no literal or primitive reaches a class check. `Variant_runtime.literal_passes` is gone. Generated code changed (a literal without an arm beside a class case): Example: @unboxed type t = | @as("a") A | S(string) | N(float) | D(Date.t) | O({x: int}) let f = (x: t) => switch x { | D(_) => 1 | O(_) => 2 | _ => 3 } Before (JS): if (x === "a") { return 3; } switch (typeof x) { case "string" : case "number" : return 3; default: ... } After (JS): switch (typeof x) { case "string" : case "number" : return 3; default: ... } Generated code changed (arms of different kinds with one body): Example: @unboxed type t = | @as(null) NoPoint | Point({x: int}) | Name(string) switch x { | NoPoint => Console.log("null") | Point(_) => Console.log("payload") | Name(_) => Console.log("payload") } Before (JS): if (x === null) { console.log("null"); return; } if (typeof x === "string") { console.log("payload"); return; } console.log("payload"); After (JS): if (x === null) { console.log("null"); return; } console.log("payload"); 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> * Leave the cases falling through to the default of a complete typeof switch Why: In a complete dispatch on primitive kinds only, the last arm becomes the default, but the cases of other kinds sharing its body stayed in the switch, falling through into `default:`. That also kept the dispatch from being one unchecked body, so a literal with that body kept its case. The cases falling through to the last arm are left out with it. Generated code changed (kinds sharing the last arm's body): Example: @unboxed type t = Num(int) | Text(string) | Flag(bool) let f = (x: t) => switch x { | Num(_) => 1 | Text(_) => 2 | Flag(_) => 2 } Before (JS): switch (typeof x) { case "number" : return 1; case "string" : default: return 2; } After (JS): if (typeof x === "number") { return 1; } else { return 2; } 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> --------- Signed-off-by: Christoph Knittel <ck@cca.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2f7b4d2 commit 27b5460

9 files changed

Lines changed: 290 additions & 133 deletions
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Leave out checks of an untagged variant switch whose outcome runs the same code, and test a literal without an arm with `===` only when the payload dispatch would run a class check on it.

‎compiler/ml/UntaggedVariants.md‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -334,12 +334,17 @@ constructor:
334334
The literals are compared with `===`: by one `switch (x)` over the literal
335335
arms, whose default holds the payload dispatch, or, when at most two
336336
literals get a `case`, by an `if` per arm body. A literal without an arm of its own goes
337-
to the default arm. It gets a `case` leading there when it could pass a
338-
check of the payload dispatch (a string literal beside a `string` arm, any
339-
literal beside an unknown-kind arm) or when the variant has class cases;
340-
otherwise it reaches the default through the payload dispatch, which then
341-
checks its last arm. A `null` literal that only the object check would
342-
accept adds `x !== null` to that check instead (rule 9).
337+
to the default arm. It reaches the default through the payload dispatch,
338+
which then checks its last arm, when the payload dispatch takes it there
339+
without a class check; otherwise, as for a string literal beside a `string`
340+
arm, any literal beside an unknown-kind arm, or a literal whose kind meets a
341+
class check, it gets a `case` leading there. A `null` literal that only the
342+
object check would accept adds `x !== null` to that check instead (rule 9).
343+
344+
The dispatch tests nothing whose outcome runs the same body: arms of
345+
different kinds with one body, also arms with the default's body, are left
346+
to one unchecked branch, and a literal with the body of a payload dispatch
347+
that runs one body unchecked gets no `case`.
343348

344349
A payload pattern whose every value is a literal case's can therefore never
345350
match, and is reported: warning 11 for an arm, such as `S("a")` beside

‎compiler/ml/untagged_dispatch.ml‎

Lines changed: 175 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -208,10 +208,148 @@ let payload_part ~same ~block_cases ~null_guard ~fallback ~has_default arms =
208208
| Body tree -> tree
209209
| Falls_through _ -> Skip
210210
in
211-
Switch_typeof (List.rev rest, default)
211+
(* The cases falling through to that arm go to the default too *)
212+
let rec without_fall_through = function
213+
| (_, Falls_through _) :: rest -> without_fall_through rest
214+
| rest -> rest
215+
in
216+
Switch_typeof (List.rev (without_fall_through rest), default)
212217
| _ -> Switch_typeof (primitive_clauses, Fallback))
213218
| _ :: _ -> Switch_typeof (primitive_clauses, chain entries))
214219

220+
type value = Literal of literal_tag | Object | Array
221+
222+
type 'a outcome = Arm of 'a | Default | Nothing
223+
224+
(* What [typeof] returns for a value, as a kind *)
225+
let kind_of = function
226+
| Literal (String _) -> Some StringType
227+
| Literal (Int _ | Float _) -> Some NumberType
228+
| Literal (BigInt _) -> Some BigintType
229+
| Literal (Bool _) -> Some BooleanType
230+
| Literal Null | Object | Array -> Some ObjectType
231+
| Literal Undefined -> None
232+
233+
let select ?(on_test = ignore) tree value =
234+
(* JavaScript semantics, including the short circuits of [&&] and [||] *)
235+
let rec holds test =
236+
on_test test;
237+
match (test, value) with
238+
| Equals literal, Literal v -> same_literal_value v literal
239+
| Equals _, (Object | Array) -> false
240+
| Typeof kind, _ -> kind_of value = Some kind
241+
| Instance Array, _ -> value = Array
242+
| Instance (Class _), _ -> false
243+
| Not_null, _ -> value <> Literal Null
244+
| Not test, _ -> not (holds test)
245+
| And (test1, test2), _ -> holds test1 && holds test2
246+
| Or (test1, test2), _ -> holds test1 || holds test2
247+
in
248+
let rec run = function
249+
| Run body -> Arm body
250+
| Fallback -> Default
251+
| Skip -> Nothing
252+
| If (test, then_, else_) -> if holds test then run then_ else run else_
253+
| Block tree -> run tree
254+
| Switch_value (clauses, default) -> (
255+
match value with
256+
| Literal v ->
257+
from_clauses
258+
(fun literal -> same_literal_value v literal)
259+
clauses default
260+
| Object | Array -> run default)
261+
| Switch_typeof (clauses, default) -> (
262+
match kind_of value with
263+
| Some kind -> from_clauses (fun k -> k = kind) clauses default
264+
| None -> run default)
265+
(* A matching case runs its body, or falls through to the next one *)
266+
and from_clauses : 'k. ('k -> bool) -> ('k * _ clause) list -> _ =
267+
fun matches clauses default ->
268+
let rec fall = function
269+
| (_, Body tree) :: _ -> run tree
270+
| (_, Falls_through _) :: rest -> fall rest
271+
| [] -> run default
272+
in
273+
let rec find = function
274+
| [] -> run default
275+
| (key, _) :: _ as clauses when matches key -> fall clauses
276+
| _ :: rest -> find rest
277+
in
278+
find clauses
279+
in
280+
run tree
281+
282+
(* Two trees that run the same bodies after the same tests *)
283+
let rec same_tree ~same tree1 tree2 =
284+
match (tree1, tree2) with
285+
| Run body1, Run body2 -> same body1 body2
286+
| Fallback, Fallback | Skip, Skip -> true
287+
| If (test1, then1, else1), If (test2, then2, else2) ->
288+
test1 = test2 && same_tree ~same then1 then2 && same_tree ~same else1 else2
289+
| Block tree1, Block tree2 -> same_tree ~same tree1 tree2
290+
| Switch_value (clauses1, default1), Switch_value (clauses2, default2) ->
291+
same_clauses ~same clauses1 clauses2 && same_tree ~same default1 default2
292+
| Switch_typeof (clauses1, default1), Switch_typeof (clauses2, default2) ->
293+
same_clauses ~same clauses1 clauses2 && same_tree ~same default1 default2
294+
| ( ( Run _ | Fallback | Skip | If _ | Block _ | Switch_value _
295+
| Switch_typeof _ ),
296+
_ ) ->
297+
false
298+
299+
and same_clauses : 'k. same:_ -> ('k * _) list -> ('k * _) list -> bool =
300+
fun ~same clauses1 clauses2 ->
301+
List.length clauses1 = List.length clauses2
302+
&& List.for_all2
303+
(fun (key1, clause1) (key2, clause2) ->
304+
key1 = key2
305+
&&
306+
match (clause1, clause2) with
307+
| Falls_through _, Falls_through _ -> true
308+
| Body tree1, Body tree2 -> same_tree ~same tree1 tree2
309+
| (Falls_through _ | Body _), _ -> false)
310+
clauses1 clauses2
311+
312+
(* A test whose branches run the same is not run, and a case of a switch that
313+
runs what its default runs is left to the default, with the cases falling
314+
through to it *)
315+
let rec simplify ~same tree =
316+
match tree with
317+
| Run _ | Fallback | Skip -> tree
318+
| If (test, then_, else_) ->
319+
let then_ = simplify ~same then_ and else_ = simplify ~same else_ in
320+
if same_tree ~same then_ else_ then then_ else If (test, then_, else_)
321+
| Block tree -> Block (simplify ~same tree)
322+
| Switch_value (clauses, default) -> (
323+
let default = simplify ~same default in
324+
match simplify_clauses ~same ~default clauses with
325+
| [] -> default
326+
| clauses -> Switch_value (clauses, default))
327+
| Switch_typeof (clauses, default) -> (
328+
let default = simplify ~same default in
329+
match simplify_clauses ~same ~default clauses with
330+
| [] -> default
331+
| clauses -> Switch_typeof (clauses, default))
332+
333+
and simplify_clauses : 'k. same:_ -> default:_ -> ('k * _) list -> ('k * _) list
334+
=
335+
fun ~same ~default clauses ->
336+
(* The cases falling through to a body, then the body *)
337+
let rec groups pending = function
338+
| [] -> if pending = [] then [] else [List.rev pending]
339+
| ((_, Falls_through _) as clause) :: rest ->
340+
groups (clause :: pending) rest
341+
| ((_, Body _) as clause) :: rest ->
342+
List.rev (clause :: pending) :: groups [] rest
343+
in
344+
groups [] clauses
345+
|> List.concat_map (fun group ->
346+
match List.rev group with
347+
| (key, Body tree) :: members ->
348+
let tree = simplify ~same tree in
349+
if same_tree ~same tree default then []
350+
else List.rev ((key, Body tree) :: members)
351+
| _ -> group)
352+
215353
let plan ~same
216354
({
217355
facts = {block_types = block_cases; literal_tags = literal_cases};
@@ -225,34 +363,38 @@ let plan ~same
225363
let literal_default = if literals_complete then None else fallback in
226364
let payload_has_default = (not payloads_complete) && fallback <> None in
227365
if literals_complete && literal_arms = [] then
228-
payload_part ~same ~block_cases ~null_guard:false ~fallback
229-
~has_default:payload_has_default payload_arms
366+
simplify ~same
367+
(payload_part ~same ~block_cases ~null_guard:false ~fallback
368+
~has_default:payload_has_default payload_arms)
230369
else
231370
(* The literals first, compared with [===] by one switch whose default is
232371
the payload dispatch. A literal without an arm goes to the match's
233372
default, never to a payload arm *)
234373
let named = List.map fst literal_arms in
235-
(* A literal reaches the same default through the payload dispatch when no
236-
payload arm accepts its kind and no class check runs on it *)
237-
let payload_kinds = List.map fst payload_arms in
238-
let reaches_a_payload_arm literal =
239-
List.exists (literal_passes literal) payload_kinds
240-
in
241-
let has_class_case =
242-
List.exists
243-
(function
244-
| InstanceType (Class _) -> true
245-
| _ -> false)
246-
block_cases
247-
in
248374
let unnamed =
249375
List.filter (fun literal -> not (List.mem literal named)) literal_cases
250376
in
251-
(* [null] passes only the object check, which then tests [x !== null] *)
252-
let skips_the_switch literal =
253-
(not has_class_case)
254-
&& ((not (reaches_a_payload_arm literal))
255-
|| (literal = Null && not (List.mem UnknownType payload_kinds)))
377+
(* A literal without an arm skips the switch when the payload dispatch
378+
takes it to the default without a class check, which could throw when
379+
the class does not exist. [null] passes the object check only without
380+
[x !== null], which is added when [null] skips. *)
381+
let skips_the_switch =
382+
match literal_default with
383+
| None -> fun _ -> false
384+
| Some _ -> (
385+
let payload =
386+
payload_part ~same ~block_cases ~null_guard:(List.mem Null unnamed)
387+
~fallback ~has_default:true payload_arms
388+
in
389+
fun literal ->
390+
let class_check = ref false in
391+
let on_test = function
392+
| Instance (Class _) -> class_check := true
393+
| _ -> ()
394+
in
395+
match select ~on_test payload (Literal literal) with
396+
| Default -> not !class_check
397+
| Arm _ | Nothing -> false)
256398
in
257399
(* Values no payload arm takes are the literals without an arm: a complete
258400
payload dispatch checks its last arm, and these literals skip the
@@ -276,20 +418,19 @@ let plan ~same
276418
| None -> []
277419
in
278420
let literal_arms = literal_arms @ unnamed in
279-
(* A complete payload dispatch with one body runs it unchecked, so a
280-
literal arm with the same body can go there too *)
421+
let payload =
422+
simplify ~same
423+
(payload_part ~same ~block_cases ~null_guard ~fallback
424+
~has_default:payload_has_default payload_arms)
425+
in
426+
(* A payload dispatch that runs one body unchecked takes the literals with
427+
that body too *)
281428
let literal_arms =
282-
match payload_arms with
283-
| (_, body) :: rest
284-
when (not payload_has_default)
285-
&& List.for_all (fun (_, other) -> same body other) rest ->
429+
match payload with
430+
| Run body ->
286431
List.filter (fun (_, other) -> not (same body other)) literal_arms
287432
| _ -> literal_arms
288433
in
289-
let payload =
290-
payload_part ~same ~block_cases ~null_guard ~fallback
291-
~has_default:payload_has_default payload_arms
292-
in
293434
if List.length literal_arms <= 2 then
294435
(* An [if] per body, testing its literals with [===] *)
295436
let rec group = function
@@ -313,67 +454,6 @@ let plan ~same
313454
If (test, Run body, rest))
314455
(group literal_arms) payload
315456
else
316-
Switch_value
317-
(clauses ~same literal_arms ~shares:(fun _ _ -> true), payload)
318-
319-
type value = Literal of literal_tag | Object | Array
320-
321-
type 'a outcome = Arm of 'a | Default | Nothing
322-
323-
(* What [typeof] returns for a value, as a kind *)
324-
let kind_of = function
325-
| Literal (String _) -> Some StringType
326-
| Literal (Int _ | Float _) -> Some NumberType
327-
| Literal (BigInt _) -> Some BigintType
328-
| Literal (Bool _) -> Some BooleanType
329-
| Literal Null | Object | Array -> Some ObjectType
330-
| Literal Undefined -> None
331-
332-
let select ?(on_test = ignore) tree value =
333-
(* JavaScript semantics, including the short circuits of [&&] and [||] *)
334-
let rec holds test =
335-
on_test test;
336-
match (test, value) with
337-
| Equals literal, Literal v -> same_literal_value v literal
338-
| Equals _, (Object | Array) -> false
339-
| Typeof kind, _ -> kind_of value = Some kind
340-
| Instance Array, _ -> value = Array
341-
| Instance (Class _), _ -> false
342-
| Not_null, _ -> value <> Literal Null
343-
| Not test, _ -> not (holds test)
344-
| And (test1, test2), _ -> holds test1 && holds test2
345-
| Or (test1, test2), _ -> holds test1 || holds test2
346-
in
347-
let rec run = function
348-
| Run body -> Arm body
349-
| Fallback -> Default
350-
| Skip -> Nothing
351-
| If (test, then_, else_) -> if holds test then run then_ else run else_
352-
| Block tree -> run tree
353-
| Switch_value (clauses, default) -> (
354-
match value with
355-
| Literal v ->
356-
from_clauses
357-
(fun literal -> same_literal_value v literal)
358-
clauses default
359-
| Object | Array -> run default)
360-
| Switch_typeof (clauses, default) -> (
361-
match kind_of value with
362-
| Some kind -> from_clauses (fun k -> k = kind) clauses default
363-
| None -> run default)
364-
(* A matching case runs its body, or falls through to the next one *)
365-
and from_clauses : 'k. ('k -> bool) -> ('k * _ clause) list -> _ =
366-
fun matches clauses default ->
367-
let rec fall = function
368-
| (_, Body tree) :: _ -> run tree
369-
| (_, Falls_through _) :: rest -> fall rest
370-
| [] -> run default
371-
in
372-
let rec find = function
373-
| [] -> run default
374-
| (key, _) :: _ as clauses when matches key -> fall clauses
375-
| _ :: rest -> find rest
376-
in
377-
find clauses
378-
in
379-
run tree
457+
simplify ~same
458+
(Switch_value
459+
(clauses ~same literal_arms ~shares:(fun _ _ -> true), payload))

‎compiler/ml/variant_runtime.ml‎

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -91,20 +91,6 @@ let literal_value_key = function
9191

9292
let same_literal_value a b = literal_value_key a = literal_value_key b
9393

94-
let literal_passes (literal : literal_tag) (block_type : block_type) =
95-
match (block_type, literal) with
96-
| UnknownType, _
97-
| StringType, String _
98-
| NumberType, (Int _ | Float _)
99-
| BigintType, BigInt _
100-
| BooleanType, Bool _
101-
| ObjectType, Null ->
102-
true
103-
| ( ( StringType | NumberType | BigintType | BooleanType | ObjectType
104-
| InstanceType _ | SymbolType | FunctionType ),
105-
_ ) ->
106-
false
107-
10894
(** Information used to recognize a constructor during matching. A literal
10995
identifies a constant or an object's tag; a payload shape identifies a
11096
value represented directly by its payload. *)

‎compiler/ml/variant_runtime.mli‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,6 @@ val literal_value_key : literal_tag -> string
6161

6262
val same_literal_value : literal_tag -> literal_tag -> bool
6363

64-
val literal_passes : literal_tag -> block_type -> bool
65-
(** Whether a literal passes the check of a payload case of this kind, as
66-
[typeof] sees it: ["a"] a string case, [null] an object case, anything an
67-
unknown case, which is not checked *)
68-
6964
(** Information used to recognize a constructor during matching. A literal
7065
identifies a constant or an object's tag; a payload shape identifies a
7166
value represented directly by its payload. *)

‎tests/ounit_tests/ounit_untagged_dispatch_tests.ml‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,19 @@ let suites =
192192
in
193193
List.iter
194194
(fun value ->
195-
let outcome = D.select tree value in
195+
let class_checks = ref 0 in
196+
let on_test : D.test -> unit = function
197+
| Instance (Class _) -> incr class_checks
198+
| _ -> ()
199+
in
200+
let outcome = D.select ~on_test tree value in
201+
(* A literal or a primitive never reaches a class check *)
202+
(match value with
203+
| Literal _ when !class_checks > 0 ->
204+
OUnit.assert_failure
205+
("a class check on " ^ value_to_string value ^ " in "
206+
^ tree_to_string tree)
207+
| Literal _ | Object | Array -> ());
196208
match
197209
oracle ~literals ~kinds ~literal_arms ~payload_arms value
198210
with

0 commit comments

Comments
 (0)