Skip to content

Commit 0822b4d

Browse files
cknittclaude
andauthored
Keep cases handled by a default arm out of the arms a switch names (#9010)
Why: A `switch` on an untagged variant with a `_` arm let the cases it does not name reach the arms it names: a `Date` matched the object arm, since only arrays were guarded, and an `@as("lit")` literal matched the string arm, since the literal test was skipped when the switch names no literal (#8995). The `switch (typeof x)` is preceded by a guard sending every instance case without an arm to the default, as it already did for arrays. The literal test is skipped only when no literal of the variant would pass the check of a payload arm. Rules 7 and 9 of the spec state both. 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"; After (js): if (v instanceof RegExp || v instanceof Date) { return "other"; } switch (typeof v) { case "object" : return "O"; 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"; Fixes: #8995 Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t Signed-off-by: Christoph Knittel <ck@cca.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 44309a2 commit 0822b4d

5 files changed

Lines changed: 174 additions & 34 deletions

File tree

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: 51 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -781,10 +781,34 @@ let compile output_prefix =
781781
| NonComplete, NonComplete -> true
782782
| _ -> false
783783
in
784+
(* A literal handled by the default would otherwise pass the
785+
check of a payload arm of its kind *)
786+
let a_literal_reaches_an_arm () =
787+
let arm_types =
788+
Ext_list.filter_map sw_blocks (fun (key, _) ->
789+
match tag_of_switch_key key with
790+
| Some {tag_type = Some (Payload_shape block_type)} ->
791+
Some block_type
792+
| Some _ | None -> None)
793+
in
794+
Ext_list.exists literal_cases
795+
(fun (literal : Variant_runtime.literal_tag) ->
796+
Ext_list.exists arm_types
797+
(fun (block_type : Variant_runtime.block_type) ->
798+
match (literal, block_type) with
799+
| String _, StringType
800+
| (Int _ | Float _), (IntType | FloatType)
801+
| BigInt _, BigintType
802+
| Bool _, BooleanType
803+
| _, UnknownType ->
804+
true
805+
| _, _ -> false))
806+
in
784807
if
785808
untagged
786809
&& List.length sw_consts = 0
787810
&& eq_default sw_num_default sw_blocks_default
811+
&& not (a_literal_reaches_an_arm ())
788812
then
789813
let has_null_case = List.mem Variant_runtime.Null literal_cases in
790814
compile_cases ~untagged ~cxt
@@ -865,26 +889,25 @@ let compile output_prefix =
865889
| _ -> false)
866890
typeof_clauses
867891
in
868-
let clauses_have_array_case =
869-
List.exists
870-
(function
871-
| Variant_runtime.Payload_shape (InstanceType Array), _ -> true
872-
| _ -> false)
873-
not_typeof_clauses
874-
in
875-
let type_has_array_case =
876-
List.exists
877-
(function
878-
| Variant_runtime.InstanceType Array -> true
879-
| _ -> false)
880-
block_cases
881-
in
882-
(* When there's an ObjectType typeof case, null and arrays can
883-
incorrectly match it (typeof null === typeof [] === "object").
884-
Guard against them when they should fall through to default. *)
892+
(* When there's an ObjectType typeof case, null, arrays and class
893+
instances can incorrectly match it (typeof null === typeof [] ===
894+
"object"). Guard against them when they should fall through to
895+
default: null, and the instance cases without an arm of their own. *)
885896
let needs_null_guard = has_object_typeof && has_null_case in
886-
let needs_array_guard =
887-
has_object_typeof && type_has_array_case && not clauses_have_array_case
897+
let unmatched_instances =
898+
if not has_object_typeof then []
899+
else
900+
Ext_list.filter_map block_cases (function
901+
| Variant_runtime.InstanceType instance
902+
when not
903+
(List.exists
904+
(function
905+
| Variant_runtime.Payload_shape (InstanceType i), _ ->
906+
i = instance
907+
| _ -> false)
908+
not_typeof_clauses) ->
909+
Some instance
910+
| _ -> None)
888911
in
889912
let rec build_if_chain remaining_clauses =
890913
match remaining_clauses with
@@ -899,12 +922,16 @@ let compile output_prefix =
899922
let typeof_switch () =
900923
S.string_switch ?default ?declaration (E.typeof e) typeof_clauses
901924
in
925+
let guards =
926+
(if needs_null_guard then [E.is_null e] else [])
927+
@ List.map
928+
(fun instance -> E.emit_check (IsInstanceOf (instance, Expr e)))
929+
unmatched_instances
930+
in
902931
let guard =
903-
match (needs_null_guard, needs_array_guard) with
904-
| true, true -> Some (E.or_ (E.is_null e) (E.is_array e))
905-
| true, false -> Some (E.is_null e)
906-
| false, true -> Some (E.is_array e)
907-
| false, false -> None
932+
match guards with
933+
| [] -> None
934+
| first :: rest -> Some (List.fold_left E.or_ first rest)
908935
in
909936
match (guard, default) with
910937
| Some guard, Some default_body ->

‎compiler/ml/UntaggedVariants.md‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,10 @@ constructor:
192192
The "is a literal case" test is the smaller of two equivalent expressions: the
193193
disjunction of `x === literal` over the literal cases, or the conjunction of
194194
the negated payload checks (with a payload check replaced by the literal
195-
disjunction where a literal overlaps it).
195+
disjunction where a literal overlaps it). A `switch` whose arms name no
196+
literal case still tests the literals first when one of them would pass the
197+
check of a payload arm, such as `@as("lit")` beside a `string` arm, so that
198+
it reaches the default arm.
196199

197200
- Implementation: `lam_compile.ml:compile_switch`,
198201
`ast_untagged_variants.ml:Dynamic_checks.is_a_literal_case`.
@@ -227,12 +230,13 @@ number, integral or not.
227230

228231
### 9. `null` and arrays are not objects
229232

230-
`typeof null` and `typeof []` are `"object"`. The object case never receives
231-
`null` when the variant has an `@as(null)` case, and never receives an array
232-
when the variant has an array or tuple case: the two-arm form adds the checks
233-
of rule 8, and the `switch (typeof x)` form is preceded by
234-
`x === null` / `Array.isArray(x)` guards that send those values to the default
235-
arm when their own arm is absent.
233+
`typeof null` and `typeof []` are `"object"`, and so is the `typeof` of a
234+
class instance. The object case never receives `null` when the variant has an
235+
`@as(null)` case, and never receives a value of another instance case (array,
236+
tuple or class): the two-arm form adds the checks of rule 8, and the
237+
`switch (typeof x)` form is preceded by `x === null`, `Array.isArray(x)` and
238+
`x instanceof C` guards that send those values to the default arm when their
239+
own arm is absent.
236240

237241
| Declaration | `switch` arms | Value | Arm |
238242
| --- | --- | --- | --- |
@@ -241,9 +245,10 @@ arm when their own arm is absent.
241245
| | `GObject(_)`, `_` | `[]`, `null` | `_` |
242246

243247
- Implementation: `lam_compile.ml:compile_untagged_cases` (`needs_null_guard`,
244-
`needs_array_guard`), `Dynamic_checks.add_runtime_type_check`.
245-
- Tests: `spec_test` rule 9; `UntaggedVariants.res` (`ObjectAndNull`, `Json`).
246-
- Shaped by #6219, #7303, #8253, #8255, #8279.
248+
`unmatched_instances`), `Dynamic_checks.add_runtime_type_check`.
249+
- Tests: `spec_test` rule 9; `UntaggedVariants.res` (`ObjectAndNull`, `Json`);
250+
`tests/tests/src/untagged_default_arm_test.res`.
251+
- Shaped by #6219, #7303, #8253, #8255, #8279, #8995.
247252

248253
### 10. Values outside every case
249254

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
function id(x) {
7+
return x;
8+
}
9+
10+
function objectOrString(value) {
11+
if (value instanceof RegExp || value instanceof Date) {
12+
return "other";
13+
}
14+
switch (typeof value) {
15+
case "object" :
16+
return "O";
17+
case "string" :
18+
return "S";
19+
default:
20+
return "other";
21+
}
22+
}
23+
24+
function textOrRecord(value) {
25+
if (value === "lit") {
26+
return "other";
27+
}
28+
switch (typeof value) {
29+
case "string" :
30+
return "text";
31+
case "object" :
32+
return "record";
33+
default:
34+
return "other";
35+
}
36+
}
37+
38+
Mocha.describe("Untagged_default_arm_test", () => {
39+
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({
43+
x: 1
44+
})));
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)));
47+
});
48+
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({
52+
x: 1
53+
})));
54+
Test_utils.eq("File \"untagged_default_arm_test.res\", line 42, characters 7-14", "other", textOrRecord(id(1)));
55+
});
56+
});
57+
58+
export {
59+
id,
60+
objectOrString,
61+
textOrRecord,
62+
}
63+
/* Not a pure module */
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
open Mocha
2+
open Test_utils
3+
4+
@inline(never) let id = x => x
5+
6+
// A switch with a default arm keeps the cases it does not name out of the
7+
// arms it names (#8995)
8+
@unboxed
9+
type instances = D(Date.t) | R(RegExp.t) | O({x: int}) | S(string) | I(int) | F(int => int)
10+
11+
let objectOrString = value =>
12+
switch value {
13+
| O(_) => "O"
14+
| S(_) => "S"
15+
| _ => "other"
16+
}
17+
18+
@unboxed
19+
type literals =
20+
| @as("lit") Lit | Text(string) | Count(int) | Flag(bool) | Rec({x: int}) | Fn(int => int)
21+
22+
let textOrRecord = value =>
23+
switch value {
24+
| Text(_) => "text"
25+
| Rec(_) => "record"
26+
| _ => "other"
27+
}
28+
29+
describe(__MODULE__, () => {
30+
test("an instance handled by the default is not an object case", () => {
31+
eq(__LOC__, "other", objectOrString(id(D(Date.make()))))
32+
eq(__LOC__, "other", objectOrString(id(R(/a/))))
33+
eq(__LOC__, "O", objectOrString(id(O({x: 1}))))
34+
eq(__LOC__, "S", objectOrString(id(S("s"))))
35+
eq(__LOC__, "other", objectOrString(id(I(1))))
36+
})
37+
38+
test("a literal handled by the default is not a string case", () => {
39+
eq(__LOC__, "other", textOrRecord(id(Lit)))
40+
eq(__LOC__, "text", textOrRecord(id(Text("lit2"))))
41+
eq(__LOC__, "record", textOrRecord(id(Rec({x: 1}))))
42+
eq(__LOC__, "other", textOrRecord(id(Count(1))))
43+
})
44+
})

0 commit comments

Comments
 (0)