Skip to content

Commit 4245a93

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 the guard that sends instance cases without an arm to the default (#9010) knew only object instances, while a declared class can have callable instances, and its class checks ran before the primitive arms. 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 guard for instance cases without an arm also protects a function arm from class instances, and when the guard has class checks, the primitive arms are tested first. 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): if (v instanceof RegExp || v instanceof Date) { return "other"; } switch (typeof v) { case "object" : return "O"; case "string" : return "S"; 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"; 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"; } 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 6e76059 commit 4245a93

8 files changed

Lines changed: 220 additions & 76 deletions

‎compiler/core/lam_compile.ml‎

Lines changed: 62 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -898,41 +898,59 @@ let compile output_prefix =
898898
let not_typeof_clauses, typeof_clauses =
899899
List.partition clause_is_not_typeof clauses
900900
in
901-
(* A class instance is never a primitive, so the primitive kinds can be
902-
tested first: their values then skip the instance checks, which
903-
throw when a class is missing at run time *)
904-
let primitive_clauses, typeof_clauses =
905-
if (not has_class_case) || not_typeof_clauses = [] then
906-
([], typeof_clauses)
907-
else
908-
List.partition (fun (tag, _) -> tag_is_primitive tag) typeof_clauses
909-
in
910901
let has_object_typeof =
911902
List.exists
912903
(function
913904
| Variant_runtime.Payload_shape ObjectType, _ -> true
914905
| _ -> false)
915906
typeof_clauses
916907
in
917-
(* When there's an ObjectType typeof case, null, arrays and class
918-
instances can incorrectly match it (typeof null === typeof [] ===
919-
"object"). Guard against them when they should fall through to
920-
default: null, and the instance cases without an arm of their own. *)
908+
let has_function_typeof =
909+
List.exists
910+
(function
911+
| Variant_runtime.Payload_shape FunctionType, _ -> true
912+
| _ -> false)
913+
typeof_clauses
914+
in
915+
(* When there's an ObjectType typeof case, null and arrays can
916+
incorrectly match it (typeof null === typeof [] === "object"), and so
917+
can class instances, which can be functions too. Guard against the
918+
instance cases without an arm of their own, which belong to the
919+
default. *)
921920
let needs_null_guard = has_object_typeof && has_null_case in
922921
let unmatched_instances =
923-
if not has_object_typeof then []
922+
Ext_list.filter_map block_cases (function
923+
| Variant_runtime.InstanceType instance
924+
when not
925+
(List.exists
926+
(function
927+
| Variant_runtime.Payload_shape (InstanceType i), _ ->
928+
i = instance
929+
| _ -> false)
930+
not_typeof_clauses) -> (
931+
match instance with
932+
| Array -> if has_object_typeof then Some instance else None
933+
| Class _ ->
934+
if has_object_typeof || has_function_typeof then Some instance
935+
else None)
936+
| _ -> None)
937+
in
938+
(* A class instance is never a primitive, so the primitive kinds can be
939+
tested first: their values then skip the instance checks and guards,
940+
which throw when a class is missing at run time *)
941+
let primitive_clauses, typeof_clauses =
942+
if
943+
(not has_class_case)
944+
|| not_typeof_clauses = []
945+
&& not
946+
(List.exists
947+
(function
948+
| Variant_runtime.Instance.Class _ -> true
949+
| Array -> false)
950+
unmatched_instances)
951+
then ([], typeof_clauses)
924952
else
925-
Ext_list.filter_map block_cases (function
926-
| Variant_runtime.InstanceType instance
927-
when not
928-
(List.exists
929-
(function
930-
| Variant_runtime.Payload_shape (InstanceType i), _ ->
931-
i = instance
932-
| _ -> false)
933-
not_typeof_clauses) ->
934-
Some instance
935-
| _ -> None)
953+
List.partition (fun (tag, _) -> tag_is_primitive tag) typeof_clauses
936954
in
937955
let instances =
938956
Ext_list.filter_map block_cases (function
@@ -962,7 +980,10 @@ let compile output_prefix =
962980
let guards =
963981
(if needs_null_guard then [E.is_null e] else [])
964982
@ List.map
965-
(fun instance -> E.emit_check (IsInstanceOf (instance, Expr e)))
983+
(fun instance ->
984+
E.emit_check
985+
(Ast_untagged_variants.Dynamic_checks.is_instance instance
986+
(Expr e)))
966987
unmatched_instances
967988
in
968989
let guard =
@@ -989,6 +1010,21 @@ let compile output_prefix =
9891010
(not (tag_is_not_typeof tag1 || tag_is_not_typeof tag2))
9901011
&& ((not has_class_case) || tag_is_primitive tag1 = tag_is_primitive tag2)
9911012
in
1013+
(* Two arms are compiled to one check of the first. When it is a class
1014+
check and the other arm's check is not, check the other arm instead,
1015+
so that primitives never reach [instanceof] *)
1016+
let cases =
1017+
match (cases, default) with
1018+
| ( [
1019+
((Variant_runtime.Payload_shape (InstanceType (Class _)), _) as
1020+
class_case);
1021+
((tag, _) as other_case);
1022+
],
1023+
Complete )
1024+
when not (tag_is_not_typeof tag) ->
1025+
[other_case; class_case]
1026+
| _ -> cases
1027+
in
9921028
cases
9931029
|> compile_general_cases ~make_exp:E.tag_type ~eq_exp:mk_eq ~cxt ~switch
9941030
~switch_exp ~default ~merge_cases

‎compiler/ml/UntaggedVariants.md‎

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -275,10 +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). A `switch` whose arms name no
279-
literal case still tests the literals first when one of them would pass the
280-
check of a payload arm, such as `@as("lit")` beside a `string` arm, so that
281-
it reaches the default arm.
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.
282283

283284
- Implementation: `lam_compile.ml:compile_switch`,
284285
`ast_untagged_variants.ml:Dynamic_checks.is_a_literal_case`.
@@ -291,7 +292,9 @@ it reaches the default arm.
291292
The payload arms compile in one of two forms.
292293

293294
- **Two arms, or one arm and a default**: one `if` on the check of the arm
294-
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
295298
`typeof x === "object"`, followed by `x !== null` when the variant has an
296299
`@as(null)` case, and by `!(x instanceof C)` (`!Array.isArray(x)` for
297300
arrays) for every instance case of the variant. The function check is
@@ -325,9 +328,11 @@ A value upcast to the superclass and wrapped in its case lands in the
325328
subclass case, as a payload equal to a literal lands in the literal's case
326329
(rule 7). Classes not declared to be related are tested in declaration order.
327330
`instanceof` consults `Symbol.hasInstance`, which is trusted for objects and
328-
functions. A primitive whose kind is a case of the variant lands in that case
329-
before any class check runs, even if a class's `Symbol.hasInstance` would
330-
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.
331336
An `int` case is recognized by `typeof x === "number"` and so receives every
332337
number, integral or not.
333338

@@ -339,19 +344,18 @@ number, integral or not.
339344
declaration order, `objectFirst` both forms); `tests/tests/src/UntaggedVariants.res`
340345
(`AllInstanceofTypes`, `MergeCases`);
341346
`tests/tests/src/untagged_runtime_annotations_test.res` (subclasses, the
342-
function case).
347+
function case), `untagged_default_arm_test.res` (`Symbol.hasInstance`).
343348
- Shaped by #6103, #6383, #6792, #7144, #7149.
344349

345350
### 9. `null` and arrays are not objects
346351

347-
`typeof null` and `typeof []` are `"object"`, and so is the `typeof` of a
348-
class instance. The object case never receives `null` when the variant has an
349-
`@as(null)` case, and never receives a value of another instance case (array,
350-
tuple or class): the two-arm form adds the checks of rule 8, and the
351-
`switch (typeof x)` form is preceded by `x === null`, `Array.isArray(x)` and
352-
`x instanceof C` guards that send those values to the default arm when their
353-
own arm is absent.
354-
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")`
355359
(rule 5) is an object case: without an `@as(null)` case, it receives `null`,
356360
as a record case does.
357361

@@ -374,17 +378,17 @@ Recognition trusts the type. A value that belongs to no case is not rejected:
374378
- in the two-arm form it lands in the unchecked branch: with
375379
`I(int) | S(string)`, `true` lands in `S`; with
376380
`TDate(Date.t) | TRegExp(RegExp.t)`, `{x: 1}` lands in `TRegExp`; with
377-
`PPromise(promise<int>) | PFloat(float)`, a thenable that is not a
378-
`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`;
379383
- in the `switch (typeof x)` form it matches no arm, and the `switch`
380384
completes without running any arm.
381385

382386
A value from another JavaScript realm fails every `instanceof` check and is
383387
recognized the same way (by the semantics of `instanceof`; not tested):
384388
recognition is local to a realm. A class that does not exist where the
385-
`switch` runs makes its check throw for every value that reaches it: in the
386-
`switch` form, objects, functions and primitives outside every case; in the
387-
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.
388392

389393
- Implementation: `lam_compile.ml:compile_general_cases` (a complete match
390394
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) :

‎tests/tests/src/untagged_default_arm_test.mjs‎

Lines changed: 60 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,29 @@
33
import * as Mocha from "mocha";
44
import * as Test_utils from "./test_utils.mjs";
55

6+
globalThis.UntaggedAnyValue = class AnyValue {
7+
static [Symbol.hasInstance]() { return true }
8+
}
9+
;
10+
611
function id(x) {
712
return x;
813
}
914

1015
function objectOrString(value) {
11-
if (value instanceof RegExp || value instanceof Date) {
12-
return "other";
13-
}
1416
switch (typeof value) {
15-
case "object" :
16-
return "O";
1717
case "string" :
1818
return "S";
1919
default:
20-
return "other";
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+
}
2129
}
2230
}
2331

@@ -35,29 +43,66 @@ function textOrRecord(value) {
3543
}
3644
}
3745

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+
3876
Mocha.describe("Untagged_default_arm_test", () => {
3977
Mocha.test("an instance handled by the default is not an object case", () => {
40-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 31, characters 7-14", "other", objectOrString(id(new Date())));
41-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 32, characters 7-14", "other", objectOrString(id(/a/)));
42-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 33, characters 7-14", "O", objectOrString(id({
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({
4381
x: 1
4482
})));
45-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 34, characters 7-14", "S", objectOrString(id("s")));
46-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 35, characters 7-14", "other", objectOrString(id(1)));
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)));
4785
});
4886
Mocha.test("a literal handled by the default is not a string case", () => {
49-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 39, characters 7-14", "other", textOrRecord(id("lit")));
50-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 40, characters 7-14", "text", textOrRecord(id("lit2")));
51-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 41, characters 7-14", "record", textOrRecord(id({
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({
5290
x: 1
5391
})));
54-
Test_utils.eq("File \"untagged_default_arm_test.res\", line 42, characters 7-14", "other", textOrRecord(id(1)));
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")));
5598
});
5699
});
57100

58101
export {
59102
id,
60103
objectOrString,
61104
textOrRecord,
105+
twoArmsKind,
106+
withLiteralsKind,
62107
}
63108
/* Not a pure module */

0 commit comments

Comments
 (0)