Skip to content

Commit 2d98edf

Browse files
cknittclaude
andcommitted
Keep class checks away from primitives and default-arm cases
Why: Two forms still ran class checks on primitives: the two-arm `if`, with the class arm declared first, and the literal test, in its form of negated payload checks. And a `switch` with a default arm let the cases it does not name reach the arms it names: a `Date` landed in the object arm, and an `@as("lit")` literal in the string arm (#8995). Of a class arm and an arm of another kind, the two-arm form checks the other one. A variant with class cases tests its literals by comparison. The `switch (typeof x)` form is preceded by a guard sending instances of cases without an arm to the default, as it already did for arrays; when that guard has class checks, the primitive arms are tested first. The literal test is skipped only when no literal would pass the check of a payload arm. The spec's rule 10 example of an unchecked branch changes accordingly: with `PPromise(promise<int>) | PFloat(float)`, the float case is checked, so a thenable that is not a `Promise` lands in `PPromise`. JS modified (an instance handled by the default): Example: @unboxed type t = D(Date.t) | R(RegExp.t) | O({x: int}) | S(string) | I(int) | F(int => int) let f = v => switch v { | O(_) => "O" | S(_) => "S" | _ => "other" } Before (js): switch (typeof v) { case "object" : return "O"; case "string" : return "S"; default: return "other"; } After (js): switch (typeof v) { case "string" : return "S"; default: if (v instanceof RegExp || v instanceof Date) { return "other"; } switch (typeof v) { case "object" : return "O"; default: return "other"; } } JS modified (a literal handled by the default): Example: @unboxed type t = | @as("lit") Lit | S(string) | I(int) | B(bool) | O({x: int}) | F(int => int) let f = v => switch v { | S(_) => "S" | O(_) => "O" | _ => "other" } Before (js): switch (typeof v) { case "string" : return "S"; After (js): if (v === "lit") { return "other"; } switch (typeof v) { case "string" : return "S"; JS modified (two arms): Example: @unboxed type t = W(weird) | S(string) Before (js): if (v instanceof Weird) { return "W"; } else { return "S"; } After (js): if (typeof v === "string") { return "S"; } else { return "W"; } Fixes: #8995 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 5a2c126 commit 2d98edf

9 files changed

Lines changed: 346 additions & 61 deletions
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Fix untagged variant switches with a default arm matching class instances in the object case and literals in a payload case of their kind.

‎compiler/core/lam_compile.ml‎

Lines changed: 91 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -780,10 +780,34 @@ let compile output_prefix =
780780
| NonComplete, NonComplete -> true
781781
| _ -> false
782782
in
783+
(* A literal handled by the default would otherwise pass the
784+
check of a payload arm of its kind *)
785+
let a_literal_reaches_an_arm () =
786+
let arm_types =
787+
Ext_list.filter_map sw_blocks (fun (key, _) ->
788+
match tag_of_switch_key key with
789+
| Some {tag_type = Some (Payload_shape block_type)} ->
790+
Some block_type
791+
| Some _ | None -> None)
792+
in
793+
Ext_list.exists literal_cases
794+
(fun (literal : Variant_runtime.literal_tag) ->
795+
Ext_list.exists arm_types
796+
(fun (block_type : Variant_runtime.block_type) ->
797+
match (literal, block_type) with
798+
| String _, StringType
799+
| (Int _ | Float _), (IntType | FloatType)
800+
| BigInt _, BigintType
801+
| Bool _, BooleanType
802+
| _, UnknownType ->
803+
true
804+
| _, _ -> false))
805+
in
783806
if
784807
untagged
785808
&& List.length sw_consts = 0
786809
&& eq_default sw_num_default sw_blocks_default
810+
&& not (a_literal_reaches_an_arm ())
787811
then
788812
let has_null_case = List.mem Variant_runtime.Null literal_cases in
789813
compile_cases ~untagged ~cxt
@@ -873,42 +897,59 @@ let compile output_prefix =
873897
let not_typeof_clauses, typeof_clauses =
874898
List.partition clause_is_not_typeof clauses
875899
in
876-
(* A class instance is never a primitive, so the primitive kinds can be
877-
tested first: their values then skip the instance checks, which
878-
throw when a class is missing at run time *)
879-
let primitive_clauses, typeof_clauses =
880-
if (not has_class_case) || not_typeof_clauses = [] then
881-
([], typeof_clauses)
882-
else
883-
List.partition (fun (tag, _) -> tag_is_primitive tag) typeof_clauses
884-
in
885900
let has_object_typeof =
886901
List.exists
887902
(function
888903
| Variant_runtime.Payload_shape ObjectType, _ -> true
889904
| _ -> false)
890905
typeof_clauses
891906
in
892-
let clauses_have_array_case =
893-
List.exists
894-
(function
895-
| Variant_runtime.Payload_shape (InstanceType Array), _ -> true
896-
| _ -> false)
897-
not_typeof_clauses
898-
in
899-
let type_has_array_case =
907+
let has_function_typeof =
900908
List.exists
901909
(function
902-
| Variant_runtime.InstanceType Array -> true
910+
| Variant_runtime.Payload_shape FunctionType, _ -> true
903911
| _ -> false)
904-
block_cases
912+
typeof_clauses
905913
in
906914
(* When there's an ObjectType typeof case, null and arrays can
907-
incorrectly match it (typeof null === typeof [] === "object").
908-
Guard against them when they should fall through to default. *)
915+
incorrectly match it (typeof null === typeof [] === "object"), and so
916+
can class instances, which can be functions too. Guard against the
917+
instance cases without an arm of their own, which belong to the
918+
default. *)
909919
let needs_null_guard = has_object_typeof && has_null_case in
910-
let needs_array_guard =
911-
has_object_typeof && type_has_array_case && not clauses_have_array_case
920+
let unmatched_instances =
921+
Ext_list.filter_map block_cases (function
922+
| Variant_runtime.InstanceType instance
923+
when not
924+
(List.exists
925+
(function
926+
| Variant_runtime.Payload_shape (InstanceType i), _ ->
927+
i = instance
928+
| _ -> false)
929+
not_typeof_clauses) -> (
930+
match instance with
931+
| Array -> if has_object_typeof then Some instance else None
932+
| Class _ ->
933+
if has_object_typeof || has_function_typeof then Some instance
934+
else None)
935+
| _ -> None)
936+
in
937+
(* A class instance is never a primitive, so the primitive kinds can be
938+
tested first: their values then skip the instance checks and guards,
939+
which throw when a class is missing at run time *)
940+
let primitive_clauses, typeof_clauses =
941+
if
942+
(not has_class_case)
943+
|| not_typeof_clauses = []
944+
&& not
945+
(List.exists
946+
(function
947+
| Variant_runtime.Instance.Class _ -> true
948+
| Array -> false)
949+
unmatched_instances)
950+
then ([], typeof_clauses)
951+
else
952+
List.partition (fun (tag, _) -> tag_is_primitive tag) typeof_clauses
912953
in
913954
let instances =
914955
Ext_list.filter_map block_cases (function
@@ -935,12 +976,19 @@ let compile output_prefix =
935976
| [], _ ->
936977
S.string_switch ?default ?declaration (E.typeof e) typeof_clauses
937978
in
979+
let guards =
980+
(if needs_null_guard then [E.is_null e] else [])
981+
@ List.map
982+
(fun instance ->
983+
E.emit_check
984+
(Ast_untagged_variants.Dynamic_checks.is_instance instance
985+
(Expr e)))
986+
unmatched_instances
987+
in
938988
let guard =
939-
match (needs_null_guard, needs_array_guard) with
940-
| true, true -> Some (E.or_ (E.is_null e) (E.is_array e))
941-
| true, false -> Some (E.is_null e)
942-
| false, true -> Some (E.is_array e)
943-
| false, false -> None
989+
match guards with
990+
| [] -> None
991+
| first :: rest -> Some (List.fold_left E.or_ first rest)
944992
in
945993
match (guard, default) with
946994
| Some guard, Some default_body ->
@@ -961,6 +1009,21 @@ let compile output_prefix =
9611009
(not (tag_is_not_typeof tag1 || tag_is_not_typeof tag2))
9621010
&& ((not has_class_case) || tag_is_primitive tag1 = tag_is_primitive tag2)
9631011
in
1012+
(* Two arms are compiled to one check of the first. When it is a class
1013+
check and the other arm's check is not, check the other arm instead,
1014+
so that primitives never reach [instanceof] *)
1015+
let cases =
1016+
match (cases, default) with
1017+
| ( [
1018+
((Variant_runtime.Payload_shape (InstanceType (Class _)), _) as
1019+
class_case);
1020+
((tag, _) as other_case);
1021+
],
1022+
Complete )
1023+
when not (tag_is_not_typeof tag) ->
1024+
[other_case; class_case]
1025+
| _ -> cases
1026+
in
9641027
cases
9651028
|> compile_general_cases ~make_exp:E.tag_type ~eq_exp:mk_eq ~cxt ~switch
9661029
~switch_exp ~default ~merge_cases

‎compiler/ml/UntaggedVariants.md‎

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,11 @@ constructor:
275275
The "is a literal case" test is the smaller of two equivalent expressions: the
276276
disjunction of `x === literal` over the literal cases, or the conjunction of
277277
the negated payload checks (with a payload check replaced by the literal
278-
disjunction where a literal overlaps it).
278+
disjunction where a literal overlaps it). A variant with class cases always
279+
uses the first, so that literals never reach a class check. A `switch` whose
280+
arms name no literal case still tests the literals first when one of them
281+
would pass the check of a payload arm, such as `@as("lit")` beside a
282+
`string` arm, so that it reaches the default arm.
279283

280284
- Implementation: `lam_compile.ml:compile_switch`,
281285
`ast_untagged_variants.ml:Dynamic_checks.is_a_literal_case`.
@@ -288,7 +292,9 @@ disjunction where a literal overlaps it).
288292
The payload arms compile in one of two forms.
289293

290294
- **Two arms, or one arm and a default**: one `if` on the check of the arm
291-
declared first, with the other branch unchecked (rule 10). The object check is
295+
declared first, with the other branch unchecked (rule 10). Of a class arm
296+
and an arm of another kind, the other one is checked, so that primitives
297+
never reach a class check. The object check is
292298
`typeof x === "object"`, followed by `x !== null` when the variant has an
293299
`@as(null)` case, and by `!(x instanceof C)` (`!Array.isArray(x)` for
294300
arrays) for every instance case of the variant. The function check is
@@ -322,9 +328,11 @@ A value upcast to the superclass and wrapped in its case lands in the
322328
subclass case, as a payload equal to a literal lands in the literal's case
323329
(rule 7). Classes not declared to be related are tested in declaration order.
324330
`instanceof` consults `Symbol.hasInstance`, which is trusted for objects and
325-
functions. A primitive whose kind is a case of the variant lands in that case
326-
before any class check runs, even if a class's `Symbol.hasInstance` would
327-
accept it: the values of a class type are instances, never primitives.
331+
functions. A literal, and a primitive whose kind has an arm of the `switch`,
332+
land in their case before any class check runs, even if a class's
333+
`Symbol.hasInstance` would accept them: the values of a class type are
334+
instances, never primitives. With one class arm and a default, every value
335+
reaches the class check.
328336
An `int` case is recognized by `typeof x === "number"` and so receives every
329337
number, integral or not.
330338

@@ -336,17 +344,18 @@ number, integral or not.
336344
declaration order, `objectFirst` both forms); `tests/tests/src/UntaggedVariants.res`
337345
(`AllInstanceofTypes`, `MergeCases`);
338346
`tests/tests/src/untagged_runtime_annotations_test.res` (subclasses, the
339-
function case).
347+
function case), `untagged_default_arm_test.res` (`Symbol.hasInstance`).
340348
- Shaped by #6103, #6383, #6792, #7144, #7149.
341349

342350
### 9. `null` and arrays are not objects
343351

344-
`typeof null` and `typeof []` are `"object"`. The object case never receives
345-
`null` when the variant has an `@as(null)` case, and never receives an array
346-
when the variant has an array or tuple case: the two-arm form adds the checks
347-
of rule 8, and the `switch (typeof x)` form is preceded by
348-
`x === null` / `Array.isArray(x)` guards that send those values to the default
349-
arm when their own arm is absent. A case declared with `@typeOf("object")`
352+
`typeof null` and `typeof []` are `"object"`, and a class instance is an
353+
object or a function. The object case never receives `null` when the variant
354+
has an `@as(null)` case, and neither the object nor the function case
355+
receives an instance of another case: the two-arm form adds the checks of
356+
rule 8, and the `switch (typeof x)` form is preceded by `x === null`,
357+
`Array.isArray(x)` and `x instanceof C` guards that send those values to the
358+
default arm when their own case has no arm. A case declared with `@typeOf("object")`
350359
(rule 5) is an object case: without an `@as(null)` case, it receives `null`,
351360
as a record case does.
352361

@@ -357,9 +366,10 @@ as a record case does.
357366
| | `GObject(_)`, `_` | `[]`, `null` | `_` |
358367

359368
- Implementation: `lam_compile.ml:compile_untagged_cases` (`needs_null_guard`,
360-
`needs_array_guard`), `Dynamic_checks.add_runtime_type_check`.
361-
- Tests: `spec_test` rule 9; `UntaggedVariants.res` (`ObjectAndNull`, `Json`).
362-
- Shaped by #6219, #7303, #8253, #8255, #8279.
369+
`unmatched_instances`), `Dynamic_checks.add_runtime_type_check`.
370+
- Tests: `spec_test` rule 9; `UntaggedVariants.res` (`ObjectAndNull`, `Json`);
371+
`tests/tests/src/untagged_default_arm_test.res`.
372+
- Shaped by #6219, #7303, #8253, #8255, #8279, #8995.
363373

364374
### 10. Values outside every case
365375

@@ -368,17 +378,17 @@ Recognition trusts the type. A value that belongs to no case is not rejected:
368378
- in the two-arm form it lands in the unchecked branch: with
369379
`I(int) | S(string)`, `true` lands in `S`; with
370380
`TDate(Date.t) | TRegExp(RegExp.t)`, `{x: 1}` lands in `TRegExp`; with
371-
`PPromise(promise<int>) | PFloat(float)`, a thenable that is not a
372-
`Promise` lands in `PFloat`;
381+
`PPromise(promise<int>) | PFloat(float)`, the float case is checked (rule
382+
8), so a thenable that is not a `Promise` lands in `PPromise`;
373383
- in the `switch (typeof x)` form it matches no arm, and the `switch`
374384
completes without running any arm.
375385

376386
A value from another JavaScript realm fails every `instanceof` check and is
377387
recognized the same way (by the semantics of `instanceof`; not tested):
378388
recognition is local to a realm. A class that does not exist where the
379-
`switch` runs makes its check throw for every value that reaches it: in the
380-
`switch` form, objects, functions and primitives outside every case; in the
381-
two-arm form, every value when the class arm is declared first.
389+
`switch` runs makes its check throw for every value that reaches it:
390+
objects and functions, primitives whose case has no arm of the `switch`, and,
391+
with one class arm and a default, every value.
382392

383393
- Implementation: `lam_compile.ml:compile_general_cases` (a complete match
384394
emits no check for its last clause).

‎compiler/ml/ast_untagged_variants.ml‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -699,8 +699,18 @@ module Dynamic_checks = struct
699699
let without_literal_cases =
700700
is_a_literal_case ~literal_cases ~block_cases ~list_literal_cases:false e
701701
in
702-
if size with_literal_cases <= size without_literal_cases then
703-
with_literal_cases
702+
(* Class checks would run on the literals, which are primitives: a class
703+
missing at run time would throw, and a [Symbol.hasInstance] could
704+
claim them *)
705+
let has_class_case =
706+
List.exists
707+
(function
708+
| InstanceType (Class _) -> true
709+
| _ -> false)
710+
block_cases
711+
in
712+
if has_class_case || size with_literal_cases <= size without_literal_cases
713+
then with_literal_cases
704714
else without_literal_cases
705715

706716
let is_int_tag ?(has_null_undefined_other = (false, false, false)) (e : _ t) :
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// Generated by ReScript, PLEASE EDIT WITH CARE
2+
3+
import * as Mocha from "mocha";
4+
import * as Test_utils from "./test_utils.mjs";
5+
6+
globalThis.UntaggedAnyValue = class AnyValue {
7+
static [Symbol.hasInstance]() { return true }
8+
}
9+
;
10+
11+
function id(x) {
12+
return x;
13+
}
14+
15+
function objectOrString(value) {
16+
switch (typeof value) {
17+
case "string" :
18+
return "S";
19+
default:
20+
if (value instanceof RegExp || value instanceof Date) {
21+
return "other";
22+
}
23+
switch (typeof value) {
24+
case "object" :
25+
return "O";
26+
default:
27+
return "other";
28+
}
29+
}
30+
}
31+
32+
function textOrRecord(value) {
33+
if (value === "lit") {
34+
return "other";
35+
}
36+
switch (typeof value) {
37+
case "string" :
38+
return "text";
39+
case "object" :
40+
return "record";
41+
default:
42+
return "other";
43+
}
44+
}
45+
46+
function twoArmsKind(value) {
47+
if (typeof value === "string") {
48+
return "name";
49+
} else {
50+
return "any";
51+
}
52+
}
53+
54+
function withLiteralsKind(value) {
55+
if (value !== 1 && value !== 5 && value !== 2 && value !== 4 && value !== 3) {
56+
if (typeof value === "string") {
57+
return "name";
58+
} else {
59+
return "any";
60+
}
61+
}
62+
switch (value) {
63+
case 1 :
64+
return "one";
65+
case 2 :
66+
return "two";
67+
case 3 :
68+
return "three";
69+
case 4 :
70+
return "four";
71+
case 5 :
72+
return "five";
73+
}
74+
}
75+
76+
Mocha.describe("Untagged_default_arm_test", () => {
77+
Mocha.test("an instance handled by the default is not an object case", () => {
78+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 71, characters 7-14", "other", objectOrString(id(new Date())));
79+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 72, characters 7-14", "other", objectOrString(id(/a/)));
80+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 73, characters 7-14", "O", objectOrString(id({
81+
x: 1
82+
})));
83+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 74, characters 7-14", "S", objectOrString(id("s")));
84+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 75, characters 7-14", "other", objectOrString(id(1)));
85+
});
86+
Mocha.test("a literal handled by the default is not a string case", () => {
87+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 79, characters 7-14", "other", textOrRecord(id("lit")));
88+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 80, characters 7-14", "text", textOrRecord(id("lit2")));
89+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 81, characters 7-14", "record", textOrRecord(id({
90+
x: 1
91+
})));
92+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 82, characters 7-14", "other", textOrRecord(id(1)));
93+
});
94+
Mocha.test("primitives skip class checks in the two-arm form", () => Test_utils.eq("File \"untagged_default_arm_test.res\", line 86, characters 7-14", "name", twoArmsKind(id("a"))));
95+
Mocha.test("literals skip class checks", () => {
96+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 90, characters 7-14", "one", withLiteralsKind(id(1)));
97+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 91, characters 7-14", "name", withLiteralsKind(id("a")));
98+
});
99+
});
100+
101+
export {
102+
id,
103+
objectOrString,
104+
textOrRecord,
105+
twoArmsKind,
106+
withLiteralsKind,
107+
}
108+
/* Not a pure module */

0 commit comments

Comments
 (0)