Skip to content

Commit a56f60f

Browse files
cknittclaude
andauthored
Make @unboxed apply to a whole variant only (#9040)
* Make @unboxed apply to a whole variant only Why: `@unboxed` on a single constructor made that constructor untagged and left the others tagged. Such mixed variants missed the checks of untagged ones (#9020) and interface and coercion checks (#9038), and their matches crashed or picked the wrong case. Public code uses the attribute on every payload constructor or on the only one, which the type-level `@unboxed` says, but no code mixes tagged and untagged cases. `@unboxed` on a constructor is an error that says to write it on the type. The layout of a variant is untagged exactly when its type is `@unboxed`, so `check_invariant` no longer considers tagged and untagged blocks together, the type's `@unboxed` is no longer copied onto constructors, and `process_untagged`, a twin of `has_untagged`, is gone. Diagnostic added (@unboxed on a constructor): Example: type t = | @unboxed A(int) | B({x: int}) | C Before (diagnostic): none; `A(3)` is `3` and `B` is `{TAG: "B", x: 1}` After (diagnostic): @unboxed applies to a whole variant: write it on the type, as in `@unboxed type t = ...`, instead of on constructor A. Diagnostic added (@unboxed on a single-field inline record constructor): Example: type t = | @unboxed A({x: int}) Before (diagnostic): none; `A({x: 1})` is `{x: 1}` After (diagnostic): @unboxed applies to a whole variant: write it on the type, as in `@unboxed type t = ...`, instead of on constructor A. For a constructor whose payload is an inline record with one field, `@unboxed type t = A({...})` makes the value that field. To keep the record object, give the record type a name: `@unboxed type t = A(r)`. Breaking: `@unboxed` on a constructor no longer compiles. Moving it to the type keeps the representation, except for a constructor whose payload is an inline record with one field, whose value becomes the field; a named record type keeps the object. 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> * Name the unboxed variant correctly in the coercion error The error for a coercion between variants with different `@unboxed` configurations said that the wrong one was unboxed. Diagnostic modified (unboxed configurations): Example: @unboxed type x = One(bool) | Two type y = One(bool) | Two Before (diagnostic): - Variant x is not unboxed. - Variant y is unboxed. After (diagnostic): - Variant x is unboxed. - Variant y is not unboxed. 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 5689a30 commit a56f60f

26 files changed

Lines changed: 218 additions & 305 deletions

‎changes/mixed-variant-checks.fix.md‎

Lines changed: 0 additions & 1 deletion
This file was deleted.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- `@unboxed` applies to a whole variant and can no longer be written on a constructor. Write `@unboxed type t = ...` instead. A constructor whose payload is an inline record with one field became that record object, while `@unboxed` on its type makes the value the field: give the record type a name to keep the object.

‎compiler/ml/UntaggedVariants.md‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,35 @@ directory is named.
2020

2121
### 1. Declaration
2222

23-
`@unboxed` and `@tag(...)` on a variant type are copied onto every
24-
constructor. `@unboxed` on a single constructor of an ordinary variant makes
25-
that constructor untagged and leaves the others tagged:
23+
`@unboxed` on a variant type makes the whole variant untagged: every case with
24+
a payload is represented by its payload. `@tag(...)` on the type is copied
25+
onto every constructor. A constructor cannot have its own `@unboxed`: it would
26+
mix tagged and untagged cases in one variant, and is an error telling to write
27+
it on the type. For a constructor whose payload is an inline record with one
28+
field, `@unboxed` on the type makes the value that field (the legacy unboxed
29+
representation), so the error also tells to give the record type a name to
30+
keep the record object.
2631

2732
| Declaration | Value | JavaScript |
2833
| --- | --- | --- |
29-
| `type mixed = \| @unboxed MA(int) \| MB({x: int}) \| MC` | `MA(3)` | `3` |
30-
| | `MB({x: 1})` | `{TAG: "MB", x: 1}` |
31-
| | `MC` | `"MC"` |
34+
| `@unboxed type whole = WA(int) \| WB({x: int}) \| WC` | `WA(3)` | `3` |
35+
| | `WB({x: 1})` | `{x: 1}` |
36+
| | `WC` | `"WC"` |
37+
38+
| Declaration | Error | Fixture |
39+
| --- | --- | --- |
40+
| `type t = \| @unboxed A(int) \| B({x: int}) \| C` | @unboxed applies to a whole variant: write it on the type, ... | `unboxed_on_constructor.res` |
41+
| `type t = \| @unboxed A({x: int})` | the same, and how to keep the record object | `unboxed_on_single_field_record_constructor.res` |
3242

3343
The layout of a declaration is computed once, after its recursive group is in
3444
the environment, and stored on the declaration.
3545

36-
- Implementation: `typedecl.ml` (`copy_tag_attr_from_decl` in
37-
`transl_declaration`; the layout pass in `transl_type_decl`),
38-
`variant_layout.ml:layout_from_type_variant`.
39-
- Tests: `spec_test` rule 1.
40-
- Shaped by #7320 (recursive groups), #8579 (layout stored once).
46+
- Implementation: `typedecl.ml` (the constructor check and
47+
`copy_tag_attr_from_decl` in `transl_declaration`; the layout pass in
48+
`transl_type_decl`), `variant_layout.ml:layout_from_type_variant`.
49+
- Tests: `spec_test` rule 1; the fixtures above.
50+
- Shaped by #7320 (recursive groups), #8579 (layout stored once), #9020 and
51+
#9038 (constructor-level `@unboxed` removed).
4152

4253
### 2. Representation
4354

‎compiler/ml/ast_untagged_variants.ml‎

Lines changed: 43 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ type error =
2020
| InvalidVariantTagAnnotation
2121
| InvalidUntaggedVariantDefinition of untagged_error
2222
| TagFieldNameConflict of string * string * string
23+
| UnboxedOnConstructor of {constructor: string; single_field_record: bool}
2324
exception Error of Location.t * error
2425

2526
let report_error ppf =
@@ -71,6 +72,18 @@ let report_error ppf =
7172
value of inline record field \"%s\". Use a different @tag name or \
7273
rename the field."
7374
constructor_name runtime_value field_name
75+
| UnboxedOnConstructor {constructor; single_field_record} ->
76+
fprintf ppf
77+
"@@unboxed applies to a whole variant: write it on the type, as in \
78+
`@@unboxed type t = ...`, instead of on constructor %s."
79+
constructor;
80+
if single_field_record then
81+
fprintf ppf
82+
" For a constructor whose payload is an inline record with one field, \
83+
`@@unboxed type t = %s({...})` makes the value that field. To keep \
84+
the record object, give the record type a name: `@@unboxed type t = \
85+
%s(r)`."
86+
constructor constructor
7487

7588
(*
7689
Type of the runtime representation of a tag.
@@ -91,14 +104,6 @@ let untagged = "unboxed"
91104
let has_untagged (attrs : Parsetree.attributes) =
92105
Ext_list.exists attrs (function {txt}, _ -> txt = untagged)
93106

94-
let process_untagged (attrs : Parsetree.attributes) =
95-
let st = ref false in
96-
Ext_list.iter attrs (fun ({txt}, _) ->
97-
match txt with
98-
| "unboxed" -> st := true
99-
| _ -> ());
100-
!st
101-
102107
let runtime_tag_of_parsetree ~loc = function
103108
| Parsetree.Pct_string s -> String (String_literal.string_semantic s)
104109
| Pct_int source -> (
@@ -211,7 +216,7 @@ let is_nullary_variant (x : Types.constructor_arguments) =
211216
(* A literal's JavaScript value, which a [switch] compares with [===]. Ints
212217
are emitted as 32-bit numbers, so [1], [1.0] and [4294967297] are one
213218
number, while [1n] is a bigint. *)
214-
let check_invariant ~is_untagged_def ~(consts : (Location.t * tag) list)
219+
let check_invariant ~(consts : (Location.t * tag) list)
215220
~(blocks : (Location.t * block) list) =
216221
let module String_set = Set.Make (String) in
217222
let module String_map = Map.Make (String) in
@@ -297,61 +302,40 @@ let check_invariant ~is_untagged_def ~(consts : (Location.t * tag) list)
297302

298303
Ext_list.rev_iter consts (fun (loc, literal) ->
299304
check_literal ~is_const:true ~loc literal);
300-
(* A tagged block is told apart from the others by its tag; an untagged one
301-
is its payload, whatever its [@as] *)
305+
(* The blocks of a variant are all tagged or, when the type is [@unboxed],
306+
all untagged. A tagged block is told apart from the others by its tag; an
307+
untagged one by the kind of its payload, whatever its [@as]. *)
302308
Ext_list.rev_iter blocks (fun (loc, block) ->
303309
match block with
304310
| Tagged {tag} -> check_literal ~is_const:false ~loc tag
305-
| Untagged _ -> ());
306-
(* The payload kinds are checked as soon as one case is untagged, even when
307-
the type itself is not [@unboxed] *)
308-
let has_untagged_block =
309-
List.exists
310-
(function
311-
| _, Untagged _ -> true
312-
| _, Tagged _ -> false)
313-
blocks
314-
in
315-
if is_untagged_def || has_untagged_block then (
316-
(* Tagged blocks are objects with a tag field: together one object case *)
317-
if
318-
List.exists
319-
(function
320-
| _, Tagged _ -> true
321-
| _, Untagged _ -> false)
322-
blocks
323-
then incr object_types;
324-
Ext_list.rev_iter blocks (fun (loc, block) ->
325-
match block with
326-
| Untagged {tag; block_type} ->
327-
(match block_type with
328-
| UnknownType -> incr unknown_types
329-
| ObjectType -> incr object_types
330-
| InstanceType i ->
331-
let count =
332-
Hashtbl.find_opt instance_types i |> Option.value ~default:0
333-
in
334-
Hashtbl.replace instance_types i (count + 1)
335-
| FunctionType -> incr function_types
336-
| IntType | FloatType -> incr number_types
337-
| BigintType -> incr bigint_types
338-
| BooleanType ->
339-
(* Literal cases are matched before payload cases, so a boolean
311+
| Untagged {tag; block_type} ->
312+
(match block_type with
313+
| UnknownType -> incr unknown_types
314+
| ObjectType -> incr object_types
315+
| InstanceType i ->
316+
let count =
317+
Hashtbl.find_opt instance_types i |> Option.value ~default:0
318+
in
319+
Hashtbl.replace instance_types i (count + 1)
320+
| FunctionType -> incr function_types
321+
| IntType | FloatType -> incr number_types
322+
| BigintType -> incr bigint_types
323+
| BooleanType ->
324+
(* Literal cases are matched before payload cases, so a boolean
340325
payload only receives the booleans that are not literal cases.
341326
A partial overlap is allowed, like for strings and numbers. *)
342-
if
343-
String_map.mem "true" !nonstring_literals_consts
344-
&& String_map.mem "false" !nonstring_literals_consts
345-
then
346-
raise
347-
(Error
348-
( loc,
349-
InvalidUntaggedVariantDefinition
350-
(UnreachableBoolean tag.name) ));
351-
incr boolean_types
352-
| StringType -> incr string_types);
353-
invariant loc tag.name
354-
| Tagged _ -> ()))
327+
if
328+
String_map.mem "true" !nonstring_literals_consts
329+
&& String_map.mem "false" !nonstring_literals_consts
330+
then
331+
raise
332+
(Error
333+
( loc,
334+
InvalidUntaggedVariantDefinition
335+
(UnreachableBoolean tag.name) ));
336+
incr boolean_types
337+
| StringType -> incr string_types);
338+
invariant loc tag.name)
355339

356340
let get_cstr_loc_tag (cstr : Types.constructor_declaration) =
357341
(cstr.cd_loc, {name = Ident.name cstr.cd_id; literal = cstr.cd_runtime_tag})

‎compiler/ml/printtyp.ml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1604,7 +1604,7 @@ let print_variant_configuration_issue ppf
16041604
let print_unboxed_status ppf unboxed name =
16051605
fprintf ppf "@ - Variant @{<info>%s@} is @{<error>%s@}unboxed."
16061606
(Path.name name)
1607-
(if unboxed then "not " else "")
1607+
(if unboxed then "" else "not ")
16081608
in
16091609
print_unboxed_status ppf left_unboxed left_variant_name;
16101610
print_unboxed_status ppf right_unboxed right_variant_name;

‎compiler/ml/typedecl.ml‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -472,10 +472,31 @@ let transl_declaration ~type_record_as_object env sdecl id =
472472
raise (Error (sdecl.ptype_loc, Duplicate_constructor name));
473473
all_constrs := String_set.add name !all_constrs)
474474
scstrs;
475+
(* [@unboxed] applies to the whole variant, so a constructor cannot have
476+
its own *)
477+
List.iter
478+
(fun {pcd_name = {txt = constructor}; pcd_args; pcd_attributes} ->
479+
match
480+
Ext_list.find_first pcd_attributes (fun ({txt}, _) ->
481+
txt = Ast_untagged_variants.untagged)
482+
with
483+
| Some ({loc}, _) ->
484+
raise
485+
(Ast_untagged_variants.Error
486+
( loc,
487+
UnboxedOnConstructor
488+
{
489+
constructor;
490+
single_field_record =
491+
(match pcd_args with
492+
| Pcstr_record [_] -> true
493+
| Pcstr_record _ | Pcstr_tuple _ -> false);
494+
} ))
495+
| None -> ())
496+
scstrs;
475497
let copy_tag_attr_from_decl attr =
476498
let tag_attrs =
477-
Ext_list.filter sdecl.ptype_attributes (fun ({txt}, _) ->
478-
txt = "tag" || txt = Ast_untagged_variants.untagged)
499+
Ext_list.filter sdecl.ptype_attributes (fun ({txt}, _) -> txt = "tag")
479500
in
480501
if tag_attrs = [] then attr else tag_attrs @ attr
481502
in

‎compiler/ml/variant_coercion.ml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,8 @@ let variant_configuration_can_be_coerced_raises ~is_spread_context ~left_loc
198198
~right_loc ~(left_attributes : Parsetree.attributes)
199199
~(right_attributes : Parsetree.attributes) =
200200
(match
201-
( Ast_untagged_variants.process_untagged left_attributes,
202-
Ast_untagged_variants.process_untagged right_attributes )
201+
( Ast_untagged_variants.has_untagged left_attributes,
202+
Ast_untagged_variants.has_untagged right_attributes )
203203
with
204204
| true, true | false, false -> ()
205205
| left, _right ->

‎compiler/ml/variant_layout.ml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ let layout_from_type_variant ~(configuration : configuration) ~env
6161
let get_block (cstr : Types.constructor_declaration) : block =
6262
let tag = {name = Ident.name cstr.cd_id; literal = cstr.cd_runtime_tag} in
6363
let tag_name = process_tag_name cstr.cd_attributes in
64-
if process_untagged cstr.cd_attributes then
64+
if configuration.unboxed then
6565
Untagged {tag; block_type = get_block_type ~env cstr}
6666
else Tagged {tag; tag_name}
6767
in
@@ -81,7 +81,7 @@ let layout_from_type_variant ~(configuration : configuration) ~env
8181
| Constant tag -> ((loc, tag) :: consts, blocks)
8282
| Block block -> (consts, (loc, block) :: blocks))
8383
in
84-
check_invariant ~is_untagged_def:configuration.unboxed ~consts ~blocks;
84+
check_invariant ~consts ~blocks;
8585
let constructors =
8686
Array.of_list
8787
(List.map (fun (_, constructor) -> constructor) located_constructors)

‎tests/build_tests/super_errors/expected/UntaggedConstructorAttributeMoreThanOneArg.res.expected‎

Lines changed: 0 additions & 8 deletions
This file was deleted.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/unboxed_on_constructor.res:1:12-19
4+
5+
1 │ type t = | @unboxed A(int) | B({x: int}) | C
6+
2 │
7+
8+
@unboxed applies to a whole variant: write it on the type, as in `@unboxed type t = ...`, instead of on constructor A.

0 commit comments

Comments
 (0)