Skip to content

Commit 80bb28f

Browse files
cknittclaude
andcommitted
Match untagged variants with a literal switch and one typeof dispatch
Why: The payload dispatch of an untagged variant ran its instance checks before the `typeof` checks, so strings and numbers reached `instanceof`: a class missing at run time threw for them, and a `Symbol.hasInstance` could claim them. Literals were tested by a size heuristic that chose between two equivalent expressions, the object case by a guard per instance case, and a subclass by negating it in its superclass's check. The literals come first, compared with `===` by one `switch (x)` (an `if` per body for at most two), whose default is the payload dispatch: one `switch (typeof x)` over the primitive kinds, whose default is an `if` chain over the instance cases (a subclass first), the function case, the tagged constructors and the object case. In a complete match the last arm is not checked. A literal without an arm skips the `switch` when no payload check would accept it, and a `null` that only the object check would accept adds `x !== null` to it. Checks leading to the default before the last checked arm fold into its check, so class checks run only on objects. `Dynamic_checks.is_a_literal_case` and the per-instance guards are gone. JS modified (primitives before classes): Example: @unboxed type t = Missing(missing) | Text(string) | Count(float) let kind = value => switch value { | Missing(_) => "missing" | Text(text) => text | Count(_) => "count" } Before (js): if (value instanceof UntaggedMissingClass) { return "missing"; } switch (typeof value) { case "string" : return value; case "number" : return "count"; } After (js): switch (typeof value) { case "string" : return value; case "number" : return "count"; default: return "missing"; } JS modified (instances without an arm): Example: @unboxed type t = D(Date.t) | R(RegExp.t) | O({x: int}) | S(string) | I(int) | F(int => int) let kind = value => switch value { | O(_) => "O" | S(_) => "S" | _ => "other" } Before (js): if (value instanceof RegExp || value instanceof Date) { return "other"; } switch (typeof value) { case "object" : return "O"; case "string" : return "S"; default: return "other"; } After (js): if (typeof value === "string") { return "S"; } else if (typeof value === "object" && !(value instanceof RegExp) && !(value instanceof Date)) { return "O"; } else { return "other"; } JS modified (a subclass first): Example: @unboxed type upload = Blob(Blob.t) | File(File.t) let kind = upload => switch upload { | Blob(_) => "blob" | File(_) => "file" } Before (js): if (upload instanceof Blob && !(upload instanceof File)) { return "blob"; } else { return "file"; } After (js): if (upload instanceof File) { return "file"; } else { return "blob"; } Review: Does `break` in an arm leave the generated `switch` instead of the loop? No: every arm placed in a generated `switch` is compiled in a switch context, where `break` and `continue` are labeled; `untagged_loop_control_test.res` checks arms of every part. Review: What changes for a value outside every case? It lands in the last arm of the chain: with `PPromise | PFloat` the float case is now checked, so a thenable lands in `PPromise` (rule 10). 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 0ddbc12 commit 80bb28f

23 files changed

Lines changed: 1326 additions & 760 deletions
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Match an untagged variant with one `switch` over its literals and one `switch (typeof x)` over its primitive cases before any class check, so that strings and numbers skip `instanceof` and a class missing at run time no longer throws for them.

‎compiler/core/js_exp_make.ml‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1428,13 +1428,6 @@ let rec emit_check (check : t Ast_untagged_variants.Dynamic_checks.t) =
14281428
| Not x -> not (emit_check x)
14291429
| Expr x -> x
14301430

1431-
let is_a_literal_case ~literal_cases ~block_cases (e : t) =
1432-
let check =
1433-
Ast_untagged_variants.Dynamic_checks.is_a_literal_case ~literal_cases
1434-
~block_cases (Expr e)
1435-
in
1436-
emit_check check
1437-
14381431
let is_int_tag ?has_null_undefined_other e =
14391432
let check =
14401433
Ast_untagged_variants.Dynamic_checks.is_int_tag ?has_null_undefined_other

‎compiler/core/js_exp_make.mli‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -181,12 +181,6 @@ val neq_null_undefined_boolean : ?comment:string -> t -> t -> t
181181

182182
val is_int_tag : ?has_null_undefined_other:bool * bool * bool -> t -> t
183183

184-
val is_a_literal_case :
185-
literal_cases:Variant_runtime.literal_tag list ->
186-
block_cases:Variant_runtime.block_type list ->
187-
t ->
188-
t
189-
190184
val is_type_object : t -> t
191185

192186
val typeof : ?comment:string -> t -> t

‎compiler/core/js_stmt_make.mli‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ val string_switch :
7676
(Variant_runtime.tag_type * J.case_clause) list ->
7777
t
7878

79+
val block_last_is_return_throw_or_continue : J.block -> bool
80+
(** Whether control never falls out of the end of the block *)
81+
7982
val declare_variable :
8083
?comment:string ->
8184
?ident_info:J.ident_info ->

‎compiler/core/lam_compile.ml‎

Lines changed: 412 additions & 144 deletions
Large diffs are not rendered by default.

‎compiler/ml/UntaggedVariants.md‎

Lines changed: 77 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -277,71 +277,86 @@ constructor:
277277
| `@as(true) LitTrue \| AnyBool(bool)` | `AnyBool(false)` | `AnyBool` |
278278
| `@as(null) LitNull \| AnyObject({x: int})` | `LitNull` | `LitNull` |
279279

280-
The "is a literal case" test is the smaller of two equivalent expressions: the
281-
disjunction of `x === literal` over the literal cases, or the conjunction of
282-
the negated payload checks (with a payload check replaced by the literal
283-
disjunction where a literal overlaps it). A `switch` whose arms name no
284-
literal case still tests the literals first when one of them would pass the
285-
check of a payload arm, such as `@as("lit")` beside a `string` arm, so that
286-
it reaches the default arm.
287-
288-
- Implementation: `lam_compile.ml:compile_switch`,
289-
`ast_untagged_variants.ml:Dynamic_checks.is_a_literal_case`.
280+
The literals are compared with `===`: by one `switch (x)` over the literal
281+
arms, whose default holds the payload dispatch, or, with at most two
282+
literals, by an `if` per arm body. A literal without an arm of its own goes
283+
to the default arm. It gets a `case` leading there when it could pass a
284+
check of the payload dispatch (a string literal beside a `string` arm, any
285+
literal beside an unknown-kind arm) or when the variant has class cases;
286+
otherwise it reaches the default through the payload dispatch, which then
287+
checks its last arm. A `null` literal that only the object check would
288+
accept adds `x !== null` to that check instead (rule 9).
289+
290+
- Implementation: `lam_compile.ml:compile_switch`.
290291
- Tests: `spec_test` rule 7; `tests/tests/src/untagged_variants_heuristic.res`
291-
(choice of expression).
292+
(literals that skip the `switch`).
292293
- Shaped by #6125, #7128, #7135.
293294

294295
### 8. Payload cases
295296

296-
The payload arms compile in one of two forms.
297+
The payload arms compile to one `switch (typeof x)` over the arms of
298+
primitive kinds (string, number, bigint, boolean, symbol), an `if` for one
299+
kind, whose default is an `if` chain over the other arms:
297300

298-
- **Two arms, or one arm and a default**: one `if` on the check of the arm
299-
declared first, with the other branch unchecked (rule 10). The object check is
300-
`typeof x === "object"`, followed by `x !== null` when the variant has an
301-
`@as(null)` case, and by `!(x instanceof C)` (`!Array.isArray(x)` for
302-
arrays) for every instance case of the variant. The function check is
303-
followed by `!(x instanceof C)` for every class case.
304-
- **Three or more arms**: an `if` chain of the instance checks, in the
305-
declaration order of the cases, then one `switch (typeof x)` over the other
306-
arms.
307-
308-
In both forms a value of an instance case never lands in the object or
309-
function case. A class check is followed by `!(x instanceof D)` for every
310-
case whose class `D` is a subclass of it (rule 5), so a subclass instance
311-
never lands in its superclass's case, whatever the declaration order:
301+
1. the instance cases (arrays, tuples and classes), a subclass before its
302+
superclasses (rule 5), otherwise in declaration order;
303+
2. the function case, `typeof x === "function"`;
304+
3. the tagged constructors of a variant with some untagged ones, an object
305+
whose tag a `switch` tells apart;
306+
4. the object case, `typeof x === "object"`;
307+
5. the unknown-kind case, unchecked.
312308

313309
```js
314-
if (v instanceof Animal && !(v instanceof Dog)) { ... }
310+
switch (typeof x) {
311+
case "string": ...
312+
case "number": ...
313+
default:
314+
if (x instanceof Dog) { ... }
315+
else if (x instanceof Animal) { ... }
316+
else if (typeof x === "object") { ... }
317+
}
315318
```
316319

320+
An instance case without an arm leads to the default arm, so an array or a
321+
class instance never lands in the function or object case. Before the last
322+
checked arm such checks are folded into its check, which then guards them:
323+
`typeof x === "object" && !(x instanceof Date)`. A primitive never reaches a
324+
class check: it is taken by the `switch (typeof x)`, where a primitive kind
325+
of the variant without an arm has a `case` leading to the default when a
326+
class check could follow. In a complete match the last arm is not checked
327+
(rule 10).
328+
317329
A value upcast to the superclass and wrapped in its case lands in the
318330
subclass case, as a payload equal to a literal lands in the literal's case
319-
(rule 7). Classes not declared to be related are tested in declaration order.
320-
`instanceof` consults `Symbol.hasInstance`, which is trusted.
331+
(rule 7). `instanceof` consults `Symbol.hasInstance`, which is trusted for
332+
the values that reach the check: objects and functions, and values outside
333+
every case (rule 10).
321334
An `int` case is recognized by `typeof x === "number"` and so receives every
322335
number, integral or not.
323336

337+
`break` and `continue` in an arm leave or continue the enclosing loop: every
338+
arm placed in a generated `switch` is compiled in a `switch` context, where
339+
they are labeled.
340+
324341
- Implementation: `lam_compile.ml:compile_untagged_cases`,
325-
`compile_general_cases`;
326-
`ast_untagged_variants.ml:Dynamic_checks.add_runtime_type_check`,
327-
`is_case_instance`.
342+
`compile_general_cases`.
328343
- Tests: `spec_test` rules 4, 5 and 8 (`instanceName` shows the chain in
329-
declaration order, `objectFirst` both forms); `tests/tests/src/UntaggedVariants.res`
330-
(`AllInstanceofTypes`, `MergeCases`);
331-
`tests/tests/src/untagged_runtime_annotations_test.res` (subclasses, the
332-
function case).
344+
declaration order, `objectFirst` the unchecked last arm);
345+
`tests/tests/src/UntaggedVariants.res` (`AllInstanceofTypes`,
346+
`MergeCases`); `tests/tests/src/untagged_runtime_annotations_test.res`
347+
(subclasses, the function case, a missing class);
348+
`untagged_default_arm_test.res` (`Symbol.hasInstance`, incomplete
349+
matches); `untagged_loop_control_test.res` (`break`, `continue`).
333350
- Shaped by #6103, #6383, #6792, #7144, #7149.
334351

335352
### 9. `null` and arrays are not objects
336353

337-
`typeof null` and `typeof []` are `"object"`, and so is the `typeof` of a
338-
class instance. The object case never receives `null` when the variant has an
339-
`@as(null)` case, and never receives a value of another instance case (array,
340-
tuple or class): the two-arm form adds the checks of rule 8, and the
341-
`switch (typeof x)` form is preceded by `x === null`, `Array.isArray(x)` and
342-
`x instanceof C` guards that send those values to the default arm when their
343-
own arm is absent.
344-
A case declared with `@typeOf("object")`
354+
`typeof null` and `typeof []` are `"object"`, and a class instance is an
355+
object or a function. The object case never receives `null` when the variant
356+
has an `@as(null)` case: the literal comparisons run first (rule 7), or the
357+
object check tests `x !== null` when `null` goes to the default arm. Neither
358+
the object nor the function case receives an instance of another case: the
359+
instance checks come first (rule 8). A case declared with `@typeOf("object")`
345360
(rule 5) is an object case: without an `@as(null)` case, it receives `null`,
346361
as a record case does.
347362

@@ -351,34 +366,33 @@ as a record case does.
351366
| | all | `null` | `GNull` |
352367
| | `GObject(_)`, `_` | `[]`, `null` | `_` |
353368

354-
- Implementation: `lam_compile.ml:compile_untagged_cases` (`needs_null_guard`,
355-
`unmatched_instances`), `Dynamic_checks.add_runtime_type_check`.
369+
- Implementation: `lam_compile.ml:compile_switch` (`null_guard`),
370+
`compile_untagged_cases`.
356371
- Tests: `spec_test` rule 9; `UntaggedVariants.res` (`ObjectAndNull`, `Json`);
357372
`tests/tests/src/untagged_default_arm_test.res`.
358373
- Shaped by #6219, #7303, #8253, #8255, #8279, #8995.
359374

360375
### 10. Values outside every case
361376

362-
Recognition trusts the type. A value that belongs to no case is not rejected:
363-
364-
- in the two-arm form it lands in the unchecked branch: with
365-
`I(int) | S(string)`, `true` lands in `S`; with
366-
`TDate(Date.t) | TRegExp(RegExp.t)`, `{x: 1}` lands in `TRegExp`; with
367-
`PPromise(promise<int>) | PFloat(float)`, a thenable that is not a
368-
`Promise` lands in `PFloat`;
369-
- in the `switch (typeof x)` form it matches no arm, and the `switch`
370-
completes without running any arm.
377+
Recognition trusts the type. A value that belongs to no case is not
378+
rejected: in a complete match it lands in the arm that is not checked, the
379+
last one of the `if` chain, or the last primitive arm when there is no other
380+
arm. With `I(int) | S(string)`, `true` lands in `S`; with
381+
`TDate(Date.t) | TRegExp(RegExp.t)`, `{x: 1}` lands in `TRegExp`; with
382+
`PPromise(promise<int>) | PFloat(float)`, the float case is checked, so a
383+
thenable that is not a `Promise` lands in `PPromise`.
371384

372385
A value from another JavaScript realm fails every `instanceof` check and is
373386
recognized the same way (by the semantics of `instanceof`; not tested):
374387
recognition is local to a realm. A class that does not exist where the
375-
`switch` runs makes its check throw, for every value: the instance checks
376-
precede the `typeof` checks, so primitives reach them too.
388+
`switch` runs makes its check throw for every value that reaches it: objects
389+
and functions, and values outside every case. The literals and the
390+
primitives of the variant never reach it.
377391

378-
- Implementation: `lam_compile.ml:compile_general_cases` (a complete match
379-
emits no check for its last clause).
380-
- Tests: `spec_test` rule 10 (two-arm form); `kindName` in
381-
`untagged_variants_spec_test.mjs` shows the `switch` form.
392+
- Implementation: `lam_compile.ml:compile_untagged_cases` (a complete match
393+
emits no check for its last arm).
394+
- Tests: `spec_test` rule 10; `untagged_runtime_annotations_test.res` (a
395+
missing class).
382396

383397
### 11. Constant folding
384398

@@ -549,6 +563,5 @@ had to answer, and the answers of rule 5:
549563
9. **Globals.** A shadowed class is read through `globalThis`. A missing
550564
class throws when the check runs (rule 10).
551565

552-
Still open: a class imported from a module cannot be named; the `typeof`
553-
checks could precede the instance checks, so that a missing class affects
554-
only objects; and the typed arrays share one type (#8955).
566+
Still open: a class imported from a module cannot be named, and the typed
567+
arrays share one type (#8955).

‎compiler/ml/ast_untagged_variants.ml‎

Lines changed: 0 additions & 148 deletions
Original file line numberDiff line numberDiff line change
@@ -570,128 +570,16 @@ module Dynamic_checks = struct
570570
| Not of 'a t
571571
| Expr of 'a
572572

573-
let rec size = function
574-
| BinOp (_, x, y) -> 1 + size x + size y
575-
| TagType _ -> 1
576-
| TypeOf x -> 1 + size x
577-
| IsInstanceOf (_, x) -> 1 + size x
578-
| Not x -> 1 + size x
579-
| Expr _ -> 1
580-
581573
let bin op x y = BinOp (op, x, y)
582574
let tag_type t = TagType t
583575
let typeof x = TypeOf x
584-
let str s = Literal (String s) |> tag_type
585-
let is_instance i x = IsInstanceOf (i, x)
586-
let not x = Not x
587576
let nil = Literal Null |> tag_type
588577
let undefined = Literal Undefined |> tag_type
589578
let object_ = Payload_shape ObjectType |> tag_type
590579

591-
let function_ = Payload_shape FunctionType |> tag_type
592-
let string = Payload_shape StringType |> tag_type
593-
let number = Payload_shape NumberType |> tag_type
594-
595-
let bigint = Payload_shape BigintType |> tag_type
596-
597-
let boolean = Payload_shape BooleanType |> tag_type
598-
599-
let symbol = Payload_shape SymbolType |> tag_type
600-
601580
let ( == ) x y = bin EqEqEq x y
602581
let ( != ) x y = bin NotEqEq x y
603582
let ( ||| ) x y = bin Or x y
604-
let ( &&& ) x y = bin And x y
605-
606-
let rec is_a_literal_case ~(literal_cases : literal_tag list) ~block_cases
607-
~list_literal_cases (e : _ t) =
608-
let overlaps p = Ext_list.exists literal_cases p in
609-
let literals_overlaps_with_string () =
610-
overlaps (function
611-
| String _ -> true
612-
| _ -> false)
613-
in
614-
let literals_overlaps_with_number () =
615-
overlaps (function
616-
| Int _ | Float _ -> true
617-
| _ -> false)
618-
in
619-
let literals_overlaps_with_bigint () =
620-
overlaps (function
621-
| BigInt _ -> true
622-
| _ -> false)
623-
in
624-
let literals_overlaps_with_boolean () =
625-
overlaps (function
626-
| Bool _ -> true
627-
| _ -> false)
628-
in
629-
let literals_overlaps_with_object () =
630-
overlaps (function
631-
| Null -> true
632-
| _ -> false)
633-
in
634-
let is_literal_case (t : literal_tag) : _ t = e == tag_type (Literal t) in
635-
let is_not_block_case (c : block_type) : _ t =
636-
match c with
637-
| StringType
638-
when literals_overlaps_with_string () = false (* No overlap *) ->
639-
typeof e != string
640-
| NumberType when literals_overlaps_with_number () = false ->
641-
typeof e != number
642-
| BigintType when literals_overlaps_with_bigint () = false ->
643-
typeof e != bigint
644-
| BooleanType when literals_overlaps_with_boolean () = false ->
645-
typeof e != boolean
646-
| InstanceType i -> not (is_instance i e)
647-
| SymbolType -> typeof e != symbol
648-
| FunctionType -> typeof e != function_
649-
| ObjectType when literals_overlaps_with_object () = false ->
650-
typeof e != object_
651-
| ObjectType (* overlap *) -> e == nil ||| (typeof e != object_)
652-
| StringType (* overlap *)
653-
| NumberType (* overlap *)
654-
| BigintType (* overlap *)
655-
| BooleanType (* overlap *)
656-
| UnknownType -> (
657-
(* We don't know the type of unknown, so we need to express:
658-
this is not one of the literals *)
659-
match literal_cases with
660-
| [] ->
661-
(* this should not happen *)
662-
assert false
663-
| l1 :: others ->
664-
let is_literal_1 = is_literal_case l1 in
665-
Ext_list.fold_right others is_literal_1 (fun literal_n acc ->
666-
is_literal_case literal_n ||| acc))
667-
in
668-
if list_literal_cases then
669-
let rec mk cases =
670-
match List.rev cases with
671-
| [case] -> is_literal_case case
672-
| case :: rest -> is_literal_case case ||| mk rest
673-
| [] -> assert false
674-
in
675-
mk literal_cases
676-
else
677-
match block_cases with
678-
| [c] -> is_not_block_case c
679-
| c1 :: (_ :: _ as rest) ->
680-
is_not_block_case c1
681-
&&& is_a_literal_case ~literal_cases ~block_cases:rest
682-
~list_literal_cases e
683-
| [] -> assert false
684-
685-
let is_a_literal_case ~literal_cases ~block_cases e =
686-
let with_literal_cases =
687-
is_a_literal_case ~literal_cases ~block_cases ~list_literal_cases:true e
688-
in
689-
let without_literal_cases =
690-
is_a_literal_case ~literal_cases ~block_cases ~list_literal_cases:false e
691-
in
692-
if size with_literal_cases <= size without_literal_cases then
693-
with_literal_cases
694-
else without_literal_cases
695583

696584
let is_int_tag ?(has_null_undefined_other = (false, false, false)) (e : _ t) :
697585
_ t =
@@ -710,40 +598,4 @@ module Dynamic_checks = struct
710598
e == nil ||| typeof e != object_
711599
else (* (undefiled + other) || other *)
712600
typeof e != object_
713-
714-
(* An instance of the case's class [i] that is not an instance of a subclass
715-
of [i] that is a case of its own: [instanceof] holds for superclasses
716-
too. *)
717-
let is_case_instance ~(instances : Instance.t list) i y =
718-
Ext_list.fold_left instances (is_instance i y) (fun check other ->
719-
if Instance.is_subclass other ~of_:i then
720-
check &&& not (is_instance other y)
721-
else check)
722-
723-
let add_runtime_type_check ~tag_type ~has_null_case
724-
~(block_cases : block_type list) x y =
725-
let instances =
726-
Ext_list.filter_map block_cases (function
727-
| InstanceType i -> Some i
728-
| _ -> None)
729-
in
730-
(* Instances of a class can be objects or functions, so the cases of
731-
those kinds exclude the class cases *)
732-
let not_one_of_the_instances case =
733-
Ext_list.fold_right instances case (fun i x ->
734-
x &&& not (is_instance i y))
735-
in
736-
match tag_type with
737-
| Payload_shape
738-
(NumberType | StringType | BigintType | BooleanType | SymbolType) ->
739-
typeof y == x
740-
| Payload_shape FunctionType -> not_one_of_the_instances (typeof y == x)
741-
| Payload_shape ObjectType ->
742-
not_one_of_the_instances
743-
(if has_null_case then typeof y == x &&& (y != nil) else typeof y == x)
744-
| Payload_shape (InstanceType i) -> is_case_instance ~instances i y
745-
| Payload_shape UnknownType ->
746-
(* This should not happen because unknown must be the only non-literal case *)
747-
assert false
748-
| Literal _ -> x
749601
end

0 commit comments

Comments
 (0)