Skip to content

Commit ea15824

Browse files
cknittclaude
andauthored
Match untagged variants with a literal switch and one typeof dispatch (#9015)
* 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> * Drop literal arms that a complete payload dispatch runs anyway A complete payload dispatch with one body runs it unchecked, so a literal arm with the same body needs no case of its own. JS modified (literal arm equal to the payload arm): Example: @unboxed type rec t = | @as(null) Null | @as(undefined) Undefined | WhyNotAnotherOne | Point({x: int, y: int}) let plus = (x, y) => switch y { | Null | Undefined => x | WhyNotAnotherOne => WhyNotAnotherOne | Point(_) => WhyNotAnotherOne } Before (js): switch (y) { case null : case undefined : return x; case "WhyNotAnotherOne" : return "WhyNotAnotherOne"; default: return "WhyNotAnotherOne"; } After (js): if (y == null) { return x; } else { return "WhyNotAnotherOne"; } 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> * Update the gentype example for the untagged dispatch The gentype example matches an untagged variant too; its output follows the new dispatch. 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> * Say precisely when literals use an if and what folds Rule 7 counts the literals that get a case, as the code does, and rule 11 names the values constant folding sees: literals and blocks of constants. 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> * Emit untagged checks directly instead of through Dynamic_checks The check AST in Ast_untagged_variants only encoded the int-tag test of tagged variants and the instance checks. Js_exp_make now builds both directly (is_int_tag from the literal list, is_instance_of), and matching_facts no longer carries has_null, has_undefined and has_other_literal, which that test derived. A class is never a switch key, so block_type_name no longer pretends to emit one. No output changes. 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> * Share which literal passes which payload check Code generation and constant folding each had a table of the literals a payload case accepts, and they disagreed on null and an object case. Variant_runtime.literal_passes is now the one table; folding follows the generated code, where `typeof null` is "object", so null without a null case folds into the object case as it is matched at run time. 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> * Keep the checks an empty arm or a tagged block needs Why: The payload dispatch decided that a match had no arm besides its primitive ones from the compiled chain of the others, which is empty when their bodies do nothing, and then ran the last primitive arm unchecked. A literal arm sharing the body of the payload dispatch was dropped, although two tagged blocks are told apart by reading their tag, which a literal such as `null` does not have. Whether there are other arms comes from the dispatch entries. A literal arm joins the payload dispatch only when at most one tagged block is matched, and the last tag of a complete match is not checked, as the last arm of every other complete match. JS modified (an arm that does nothing): Example: @unboxed type t = S(string) | O({x: int}) let f = v => { switch v { | S(_) => Console.log("s") | O(_) => () } Console.log("after") } Before (js): switch (typeof v) { default: console.log("s"); } console.log("after"); After (js): if (typeof v === "string") { console.log("s"); } console.log("after"); JS modified (a literal sharing the body of tagged blocks): Example: type t = | @unboxed MS(string) | MB({x: int}) | MC(int) | @as(null) MNull | @as(1) MOne let f = v => switch v { | MB(_) => "other" | MC(_) => "other" | MOne => "one" | MNull | MS(_) => "other" } Before (js): if (v === 1) { return "one"; } if (typeof v === "string") { return "other"; } switch (v.TAG) { case "MB" : case "MC" : return "other"; } After (js): if (v === null) { return "other"; } if (v === 1) { return "one"; } if (typeof v === "string") { return "other"; } switch (v.TAG) { case "MB" : default: return "other"; } 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> * Drop the tagged blocks of mixed variants from the dispatch Since #9040 a variant is untagged as a whole or not at all, so the payload dispatch of an untagged variant never meets a tagged block. The `switch` on the tag inside its `if` chain, the merging of tagged clauses, the count of tagged blocks before dropping literal arms and the tag-name parameter are gone, and rule 8 no longer lists tagged constructors. 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> * Give a literal a case where skipping would add a check Why: A literal without an arm skipped the literal switch whenever the payload dispatch led it to the default, even where that made a complete dispatch check its last arm or added `x !== null`, although the switch existed for other literals anyway. When other literals get a case, a literal whose skipping would add such a check gets a case too. Literals that reach the default without a new check still skip. The fallback for tagged blocks is gone: an untagged variant has none since #9040. Rule 10 now says where a value outside every case lands when the match shares a default. Generated code changed (a bool literal beside string literals): Example: @unboxed type t = | @as("a") A | @as("b") B | @as(true) T | S(string) | O({x: int}) let f = (x: t) => switch x { | S(_) => 1 | O(_) => 2 | _ => 3 } Before (JS): switch (x) { case "a" : case "b" : return 3; default: if (typeof x === "string") { return 1; } else if (typeof x === "object") { return 2; } else { return 3; } } After (JS): switch (x) { case "a" : case "b" : case true : return 3; default: if (typeof x === "string") { 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> * Let literals skip the switch whatever other literals do Why: Giving a literal a case where skipping would add a check saves one typeof or null check in a narrow situation, at the price of two more predicates in the most intricate part of the dispatch. This undoes that rule, keeping the removal of the tagged-block fallback and the rule 10 clause from the same commit. Generated code changed (a bool literal beside string literals): Example: @unboxed type t = | @as("a") A | @as("b") B | @as(true) T | S(string) | O({x: int}) let f = (x: t) => switch x { | S(_) => 1 | O(_) => 2 | _ => 3 } Before (JS): switch (x) { case "a" : case "b" : case true : return 3; default: if (typeof x === "string") { return 1; } else { return 2; } } After (JS): switch (x) { case "a" : case "b" : return 3; default: if (typeof x === "string") { return 1; } else if (typeof x === "object") { return 2; } else { return 3; } } 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> * Regenerate the callable-instance test for the typeof dispatch Why: The test added to the bottom of the stack is compiled by this pull request's dispatch, which checks the function arm against the classes. 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 6217c4e commit ea15824

28 files changed

Lines changed: 1422 additions & 907 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: 32 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1409,52 +1409,44 @@ let class_constructor (instance : Variant_runtime.Instance.t) =
14091409
| [] -> assert false
14101410
| global :: properties -> List.fold_left dot (js_global global) properties
14111411

1412-
(* The [typeof] string an untagged payload answers to. *)
1413-
let block_type_name = function
1414-
| Variant_runtime.InstanceType i -> class_constructor i
1415-
| block_type -> (
1416-
match Variant_runtime.typeof_name block_type with
1417-
| Some name -> str name
1418-
| None ->
1419-
(* An unknown payload has no check: it is the only payload case *)
1420-
assert false)
1412+
(* The [typeof] string an untagged payload answers to, as a [switch] key.
1413+
Instances are told apart by [is_instance_of], an unknown payload is not
1414+
checked *)
1415+
let block_type_name block_type =
1416+
match Variant_runtime.typeof_name block_type with
1417+
| Some name -> str name
1418+
| None -> assert false
14211419

14221420
let tag_type = function
14231421
| Variant_runtime.Literal d -> literal_tag d
14241422
| Payload_shape b -> block_type_name b
14251423

1426-
let rec emit_check (check : t Ast_untagged_variants.Dynamic_checks.t) =
1427-
match check with
1428-
| TagType t -> tag_type t
1429-
| BinOp (op, x, y) ->
1430-
let op =
1431-
match op with
1432-
| EqEqEq -> Js_op.EqEqEq
1433-
| NotEqEq -> NotEqEq
1434-
| And -> And
1435-
| Or -> Or
1436-
in
1437-
bin op (emit_check x) (emit_check y)
1438-
| TypeOf x -> typeof (emit_check x)
1439-
| IsInstanceOf (Array, x) -> is_array (emit_check x)
1440-
| IsInstanceOf (instance, x) ->
1441-
instanceof (emit_check x) (class_constructor instance)
1442-
| Not x -> not (emit_check x)
1443-
| Expr x -> x
1444-
1445-
let is_a_literal_case ~literal_cases ~block_cases (e : t) =
1446-
let check =
1447-
Ast_untagged_variants.Dynamic_checks.is_a_literal_case ~literal_cases
1448-
~block_cases (Expr e)
1449-
in
1450-
emit_check check
1451-
1452-
let is_int_tag ?has_null_undefined_other e =
1453-
let check =
1454-
Ast_untagged_variants.Dynamic_checks.is_int_tag ?has_null_undefined_other
1455-
(Expr e)
1424+
let is_instance_of (instance : Variant_runtime.Instance.t) e =
1425+
match instance with
1426+
| Array -> is_array e
1427+
| Class _ -> instanceof e (class_constructor instance)
1428+
1429+
(* Whether a value of a tagged variant is a constant rather than a block,
1430+
given the literals of its constants *)
1431+
let is_int_tag ~(literal_tags : Variant_runtime.literal_tag list) e =
1432+
let has_null = List.mem Variant_runtime.Null literal_tags in
1433+
let has_undefined = List.mem Variant_runtime.Undefined literal_tags in
1434+
let has_other =
1435+
List.exists
1436+
(function
1437+
| Variant_runtime.Null | Undefined -> false
1438+
| String _ | Int _ | Float _ | BigInt _ | Bool _ -> true)
1439+
literal_tags
14561440
in
1457-
emit_check check
1441+
let is_null = bin EqEqEq e nil in
1442+
let is_undefined = bin EqEqEq e undefined in
1443+
let not_an_object = bin NotEqEq (typeof e) (str "object") in
1444+
match (has_null, has_undefined, has_other) with
1445+
| true, false, false -> is_null
1446+
| true, true, false -> bin Or is_null is_undefined
1447+
| false, true, false -> is_undefined
1448+
| true, _, true -> bin Or is_null not_an_object
1449+
| false, _, _ -> not_an_object
14581450

14591451
let tag ?comment ?(name = Js_dump_lit.tag) e : t =
14601452
{expression_desc = Caml_block_tag (e, name); comment; source_loc = None}

‎compiler/core/js_exp_make.mli‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,8 @@ val assign : ?comment:string -> t -> t -> t
164164
val literal_tag : Variant_runtime.literal_tag -> t
165165
val tag_type : Variant_runtime.tag_type -> t
166166

167-
val emit_check : t Ast_untagged_variants.Dynamic_checks.t -> t
167+
val is_instance_of : Variant_runtime.Instance.t -> t -> t
168+
(** [Array.isArray(e)] or [e instanceof C] *)
168169

169170
val triple_equal : ?comment:string -> t -> t -> t
170171
(* TODO: reduce [triple_equal] use *)
@@ -179,13 +180,7 @@ val eq_null_undefined_boolean : ?comment:string -> t -> t -> t
179180

180181
val neq_null_undefined_boolean : ?comment:string -> t -> t -> t
181182

182-
val is_int_tag : ?has_null_undefined_other:bool * bool * bool -> t -> t
183-
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
183+
val is_int_tag : literal_tags:Variant_runtime.literal_tag list -> t -> t
189184

190185
val is_type_object : t -> t
191186

‎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 ->

0 commit comments

Comments
 (0)