diff --git a/changes/array-record-rest-coercion.breaking.md b/changes/array-record-rest-coercion.breaking.md new file mode 100644 index 0000000000..c995bbc79d --- /dev/null +++ b/changes/array-record-rest-coercion.breaking.md @@ -0,0 +1 @@ +- A record rest pattern whose rest type is a record with the runtime names `"0"`, `"1"`, …, a coercion between such a record and a record represented as an object (in either direction), and an untagged variant with such a record and an array or tuple case are now errors, as they produced an object where the type promises a JavaScript array, or matched the wrong case. diff --git a/changes/array-record-spread.fix.md b/changes/array-record-spread.fix.md new file mode 100644 index 0000000000..ad024835c7 --- /dev/null +++ b/changes/array-record-spread.fix.md @@ -0,0 +1 @@ +- Keep records whose fields have the runtime names `"0"`, `"1"`, … JavaScript arrays when they are spread or written as `{}`, and match them as arrays when they are untagged variant payloads. diff --git a/compiler/core/js_dump.ml b/compiler/core/js_dump.ml index 6da3d45853..c8ad659754 100644 --- a/compiler/core/js_dump.ml +++ b/compiler/core/js_dump.ml @@ -860,9 +860,8 @@ and expression_desc cxt ~(level : int) f x : cxt = (Ext_list.map_combine fields el (fun x -> Js_op.Lit (Ext_ident.convert x))))) (*name convention of Record is slight different from modules*) - | Caml_block (el, _, Blk_record {fields}) -> - if Lambda.record_fields_are_array fields then - expression_desc cxt ~level f (Array el) + | Caml_block (el, _, Blk_record {fields; array}) -> + if array then expression_desc cxt ~level f (Array el) else let fields = Ext_list.array_list_filter_map fields el (fun (f, opt) x -> diff --git a/compiler/gentype/translate_type_declarations.ml b/compiler/gentype/translate_type_declarations.ml index de9efa656d..c91b544ab7 100644 --- a/compiler/gentype/translate_type_declarations.ml +++ b/compiler/gentype/translate_type_declarations.ml @@ -227,7 +227,8 @@ let traslate_declaration_kind ~config ~loc ~output_file_relative ~resolver let unboxed = match representation with | Record_unboxed _ -> true - | Record_regular | Record_inlined _ | Record_extension -> false + | Record_regular | Record_array | Record_inlined _ | Record_extension -> + false in let {Translate_type_expr_from_types.dependencies; type_} = label_declarations |> translate_label_declarations ~unboxed diff --git a/compiler/ml/UntaggedVariants.md b/compiler/ml/UntaggedVariants.md index 86d080c8ae..dbb70f6959 100644 --- a/compiler/ml/UntaggedVariants.md +++ b/compiler/ml/UntaggedVariants.md @@ -292,7 +292,7 @@ The type checker rejects an untagged variant, with | Condition | Reason | Fixture | | --- | --- | --- | | two object cases | At most one case can be an object type. | `UntaggedAtMostOneObject.res` | -| two cases of one instance class, compared by path (arrays and tuples share `Array`) | At most one case can be an instance of C; for `Array`, an array or tuple type. | `UntaggedAtMostOneInstance.res`, `UntaggedTupleAndArray.res`, `untagged_same_class_twice.res` | +| two cases of one instance class, compared by path (arrays, tuples and records represented as arrays share `Array`) | At most one case can be an instance of C; for `Array`, an array, a tuple or a record represented as an array. | `UntaggedAtMostOneInstance.res`, `UntaggedTupleAndArray.res`, `untagged_array_record_and_array.res`, `untagged_same_class_twice.res` | | two function cases | At most one case can be a function type. | `UntaggedAtMostOneFunction.res` | | two string cases | At most one case can be a string type. | `UntaggedAtMostOneString.res` | | two number cases (`int` and `float` count together) | At most one case can be a number type (int or float). | `UntaggedAtMostOneNumber.res` | diff --git a/compiler/ml/ast_untagged_variants.ml b/compiler/ml/ast_untagged_variants.ml index d9d746eb5e..1ab02ef0e1 100644 --- a/compiler/ml/ast_untagged_variants.ml +++ b/compiler/ml/ast_untagged_variants.ml @@ -65,7 +65,8 @@ let report_error ppf = "At most one case can be " ^ (match kind with | ObjectType -> "an object type" - | InstanceType Array -> "an array or tuple type" + | InstanceType Array -> + "an array, a tuple or a record represented as an array" | InstanceType i -> "an instance of " ^ Instance.to_string i | FunctionType -> "a function type" | StringType -> "a string type" diff --git a/compiler/ml/ctype.ml b/compiler/ml/ctype.ml index ed1f1b2122..e48ad8f482 100644 --- a/compiler/ml/ctype.ml +++ b/compiler/ml/ctype.ml @@ -88,6 +88,10 @@ type subtype_context = issues: Record_coercion.record_field_subtype_violation list; } | Coercion_into_private_type of {typename: Path.t} + | Record_array_mismatch of { + array_record_name: Path.t; + object_record_name: Path.t; + } exception Subtype of type_pairs * type_pairs * subtype_context option @@ -3863,7 +3867,10 @@ let rec subtype_rec env trace t1 t2 cstrs = (p2, _, {type_kind = Type_record (fields2, repr2)}) ) -> let same_repr = match (repr1, repr2) with - | Record_regular, Record_regular -> + (* Not between [Record_array] and [Record_regular]: an object is + no array, and an array coerced to an object record would + still pass for the array case of an untagged variant *) + | Record_regular, Record_regular | Record_array, Record_array -> true (* handled in the fields checks *) | Record_unboxed b1, Record_unboxed b2 -> b1 = b2 | Record_inlined _, Record_inlined _ -> repr1 = repr2 @@ -3893,7 +3900,16 @@ let rec subtype_rec env trace t1 t2 cstrs = t1, t2, !(current_univar_pairs ()), - None (* TODO(subtype-errors) Record representation *) ) + match (repr1, repr2) with + | Record_regular, Record_array -> + Some + (Record_array_mismatch + {array_record_name = p2; object_record_name = p1}) + | Record_array, Record_regular -> + Some + (Record_array_mismatch + {array_record_name = p1; object_record_name = p2}) + | _ -> None (* TODO(subtype-errors) Record representation *) ) :: cstrs | (p1, _, {type_kind = tk1}), (p2, _, {type_kind = tk2}) -> ( trace, diff --git a/compiler/ml/ctype.mli b/compiler/ml/ctype.mli index 53071dff8d..3f81dcd15f 100644 --- a/compiler/ml/ctype.mli +++ b/compiler/ml/ctype.mli @@ -54,6 +54,12 @@ type subtype_context = | Coercion_into_private_type of {typename: Path.t} (** The target is a private record or variant, whose values only its own module can build. *) + | Record_array_mismatch of { + array_record_name: Path.t; + object_record_name: Path.t; + } + (** One record is represented as a JavaScript array, the other as an + object. *) type type_pairs = (type_expr * type_expr) list exception Unify of type_pairs diff --git a/compiler/ml/lambda.ml b/compiler/ml/lambda.ml index b5982c69d1..3beb078fec 100644 --- a/compiler/ml/lambda.ml +++ b/compiler/ml/lambda.ml @@ -31,6 +31,9 @@ type tag_info = | Blk_record of { fields: (string * bool (* optional *)) array; mutable_flag: Asttypes.mutable_flag; + array: bool; + (* [Record_array]: the fields are the elements of a JavaScript + array *) } | Blk_module of string list | Blk_module_export of Ident.t list @@ -59,14 +62,16 @@ let mutable_flag_of_tag_info (tag : tag_info) = | Blk_module_export _ | Blk_extension -> Immutable -let blk_record fields mutable_flag = Blk_record {fields; mutable_flag} +let blk_record fields mutable_flag ~array = + Blk_record {fields; mutable_flag; array} let blk_record_ext fields mutable_flag = Blk_record_ext {fields; mutable_flag} let blk_record_inlined fields name num_nonconst ~runtime mutable_flag = Blk_record_inlined {fields; name; num_nonconst; mutable_flag; runtime} let ref_tag_info : tag_info = - Blk_record {fields = [|("contents", false)|]; mutable_flag = Mutable} + Blk_record + {fields = [|("contents", false)|]; mutable_flag = Mutable; array = false} type field_dbg_info = | Fld_record of {name: string} @@ -801,16 +806,6 @@ and eq_option l1 l2 = and eq_approx_list ls ls1 = Ext_list.for_all2_no_exn ls ls1 eq_approx -let runtime_names_are_array runtime_name fields = - let len = Array.length fields in - let rec loop i = - if i = len then true - else string_of_int i = runtime_name fields.(i) && loop (i + 1) - in - len <> 0 && loop 0 - -let record_fields_are_array fields = runtime_names_are_array fst fields - (* The JavaScript value a constant is emitted as by [Lam_compile_const] and [Js_dump], not its source constructor. A constant of another representation keeps the dispatch at run time. *) @@ -828,8 +823,8 @@ let untagged_value (c : structured_constant) : Untagged_dispatch.value option = | Const_bigint (sign, digits) -> Some (Literal (BigInt (Bigint_utils.to_string sign digits))) | Const_block (Blk_tuple, _) -> Some Array - | Const_block (Blk_record {fields}, _) -> - if record_fields_are_array fields then Some Array else Some Object + | Const_block (Blk_record {array}, _) -> + if array then Some Array else Some Object | Const_block ( ( Blk_constructor _ | Blk_record_inlined _ | Blk_poly_var | Blk_record_ext _ | Blk_module _ | Blk_module_export _ | Blk_extension diff --git a/compiler/ml/lambda.mli b/compiler/ml/lambda.mli index 9241560a49..3e34980539 100644 --- a/compiler/ml/lambda.mli +++ b/compiler/ml/lambda.mli @@ -37,6 +37,9 @@ type tag_info = | Blk_record of { fields: (string * bool (* optional *)) array; mutable_flag: mutable_flag; + array: bool; + (* [Record_array]: the fields are the elements of a JavaScript + array *) } | Blk_module of string list | Blk_module_export of Ident.t list @@ -54,7 +57,7 @@ type tag_info = val tag_label_of_tag_info : tag_info -> string val mutable_flag_of_tag_info : tag_info -> mutable_flag -val blk_record : (string * bool) array -> mutable_flag -> tag_info +val blk_record : (string * bool) array -> mutable_flag -> array:bool -> tag_info val blk_record_ext : string array -> mutable_flag -> tag_info @@ -547,13 +550,3 @@ val name_lambda : let_kind -> t -> (Ident.t -> t) -> t val bind : let_kind -> Ident.t -> t -> t -> t val default_function_attribute : function_attribute - -val record_fields_are_array : (string * bool) array -> bool -(** Whether a nonempty record has consecutive field names starting at ["0"], - so it is represented as a JavaScript array. Optionality does not affect - the layout. *) - -val runtime_names_are_array : ('a -> string) -> 'a array -> bool -(** [record_fields_are_array] over fields of any shape, given their runtime - name, so that a caller holding the labels of a large record (JSX props) - need not build a copy of them. *) diff --git a/compiler/ml/matching.ml b/compiler/ml/matching.ml index 614efd4a49..76db3a04e4 100644 --- a/compiler/ml/matching.ml +++ b/compiler/ml/matching.ml @@ -1656,7 +1656,7 @@ let make_record_matching loc all_labels def = function let lbl = all_labels.(pos) in let access = match lbl.lbl_repres with - | Record_regular -> + | Record_regular | Record_array -> prim ~primitive: (Pfield (lbl.lbl_pos, Lambda.fld_record lbl.lbl_runtime_name)) diff --git a/compiler/ml/printlambda.ml b/compiler/ml/printlambda.ml index 5b63855108..88bd921410 100644 --- a/compiler/ml/printlambda.ml +++ b/compiler/ml/printlambda.ml @@ -76,8 +76,10 @@ let print_taginfo ppf = function | Blk_constructor {name; num_nonconst} -> fprintf ppf "%s/%i" name num_nonconst | Blk_poly_var -> fprintf ppf "polyvar" - | Blk_record {fields = ss} -> - fprintf ppf "[%s]" (String.concat ";" (List.map fst (Array.to_list ss))) + | Blk_record {fields = ss; array} -> + fprintf ppf "%s[%s]" + (if array then "array" else "") + (String.concat ";" (List.map fst (Array.to_list ss))) | Blk_module ss -> fprintf ppf "[%s]" (String.concat ";" ss) | Blk_module_export _ -> fprintf ppf "module/exports" | Blk_record_inlined {fields = ss} -> diff --git a/compiler/ml/printtyp.ml b/compiler/ml/printtyp.ml index 030d84ea8d..9dc4436f07 100644 --- a/compiler/ml/printtyp.ml +++ b/compiler/ml/printtyp.ml @@ -1831,7 +1831,15 @@ let report_subtyping_error ppf env tr1 txt1 tr2 ctx = fprintf ppf "@ @{%s@} is private: its values can only be built in the \ module that defines it, so another type cannot be coerced to it." - (Path.name typename)) + (Path.name typename) + | Record_array_mismatch {array_record_name; object_record_name} -> + fprintf ppf + "@ The record @{%s@} is represented as a JavaScript array \ + (its fields have the runtime names \"0\", \"1\", ...) and \ + @{%s@} as an object, so neither can be coerced to the \ + other." + (Path.name array_record_name) + (Path.name object_record_name)) | None -> ()) let report_ambiguous_type_error ppf env (tp0, tp0') tpl txt1 txt2 txt3 = diff --git a/compiler/ml/printtyped.ml b/compiler/ml/printtyped.ml index a8b453aca0..10687d520f 100644 --- a/compiler/ml/printtyped.ml +++ b/compiler/ml/printtyped.ml @@ -127,6 +127,7 @@ let record_representation i ppf = let open Types in function | Record_regular -> line i ppf "Record_regular\n" + | Record_array -> line i ppf "Record_array\n" | Record_unboxed b -> line i ppf "Record_unboxed %b\n" b | Record_inlined {name} -> line i ppf "Record_inlined %s\n" name | Record_extension -> line i ppf "Record_extension\n" diff --git a/compiler/ml/rec_check.ml b/compiler/ml/rec_check.ml index a5990c95e5..fb95cde412 100644 --- a/compiler/ml/rec_check.ml +++ b/compiler/ml/rec_check.ml @@ -294,7 +294,8 @@ let rec expression : Env.env -> Typedtree.expression -> Use.t = let use = match rep with | Record_unboxed _ -> fun x -> x - | Record_regular | Record_inlined _ | Record_extension -> Use.guard + | Record_regular | Record_array | Record_inlined _ | Record_extension -> + Use.guard in let field env (_, _, e) = expression env e in Use.join (use (array field env es)) (option expression env eo) diff --git a/compiler/ml/record_runtime.ml b/compiler/ml/record_runtime.ml index 848c65b755..57bd1ed34e 100644 --- a/compiler/ml/record_runtime.ml +++ b/compiler/ml/record_runtime.ml @@ -22,6 +22,15 @@ let declaration_name (lbl : Types.label_declaration) = | Some name -> name | None -> Ident.name lbl.ld_id +(* A record whose fields have the runtime names "0", "1", ... in declaration + order is represented as a JavaScript array ([Record_array]). *) +let is_array (lbls : Types.label_declaration list) = + let rec loop i = function + | [] -> true + | lbl :: rest -> declaration_name lbl = string_of_int i && loop (i + 1) rest + in + lbls <> [] && loop 0 lbls + (* Two fields collide when they end up with the same runtime name, which a rename can cause between fields whose declared names differ. *) let rec check_duplicated_labels_aux (lbls : Parsetree.label_declaration list) diff --git a/compiler/ml/record_runtime.mli b/compiler/ml/record_runtime.mli index dc24d0abea..e382b6dc2d 100644 --- a/compiler/ml/record_runtime.mli +++ b/compiler/ml/record_runtime.mli @@ -17,6 +17,10 @@ val declaration_name : Types.label_declaration -> string +val is_array : Types.label_declaration list -> bool +(** Whether the fields have the runtime names ["0"], ["1"], ... in declaration + order, so the record is represented as a JavaScript array. *) + val extra_as_attribute : Parsetree.label_declaration -> Location.t option (** The location of a second [@as] naming the field, which is one too many. *) diff --git a/compiler/ml/translcore.ml b/compiler/ml/translcore.ml index 94ec677966..b0aac24935 100644 --- a/compiler/ml/translcore.ml +++ b/compiler/ml/translcore.ml @@ -1039,7 +1039,8 @@ let fields_by_position fields = (* How [transl_record] builds a record: by copying the fields of [init] one by one (or with no [init] at all), or by taking a shallow copy of [init] - and setting the other fields. JSX props follow the same rule. + and setting the other fields. JSX props follow the same rule. A shallow + copy is an object spread, so an array record always copies its fields. TODO: More strategies 3 + 2 * List.length lbl_expr_list >= size (density) *) let record_copies_fields @@ -1047,10 +1048,13 @@ let record_copies_fields ~(init : expression option) = match init with | None -> true - | Some _ -> + | Some _ -> ( let lbl_all = all_labels fields in - Array.length lbl_all < 20 - && not (Array.exists (fun lbl -> lbl.lbl_optional) lbl_all) + match lbl_all.(0).lbl_repres with + | Record_array -> true + | Record_regular | Record_unboxed _ | Record_inlined _ | Record_extension -> + Array.length lbl_all < 20 + && not (Array.exists (fun lbl -> lbl.lbl_optional) lbl_all)) let jsx_props_of ~multi (props : expression) = match props.exp_desc with @@ -1074,14 +1078,7 @@ let jsx_props_of ~multi (props : expression) = let record children = Some (Jsx_props_record {fields; init; copy_fields; children}) in - let is_array = - Lambda.runtime_names_are_array - (fun (lbl : label_description) -> lbl.lbl_runtime_name) - (all_labels fields) - in match children with - (* a record with the runtime names "0", "1", ... is an array *) - | _ when is_array -> None | None -> record None (* children printed as JSX children must be the [children] prop *) | Some (lbl, _) when lbl.lbl_runtime_name <> "children" -> None @@ -1089,6 +1086,8 @@ let jsx_props_of ~multi (props : expression) = match jsx_children ~multi lbl child with | Some children -> record (Some children) | None -> None)) + (* props that are a JavaScript array: an ordinary call *) + | Texp_record {representation = Record_array} -> None | _ -> Some (Jsx_props_spread props) (* [None] when the call doesn't have the shape the PPX produces; it then @@ -1419,7 +1418,7 @@ and transl_exp0 (e : Typedtree.expression) : Lambda.t = | Texp_field (arg, _, lbl) -> ( let targ = transl_exp arg in match lbl.lbl_repres with - | Record_regular -> + | Record_regular | Record_array -> prim ~primitive: (Pfield (lbl.lbl_pos, Lambda.fld_record lbl.lbl_runtime_name)) @@ -1439,7 +1438,7 @@ and transl_exp0 (e : Typedtree.expression) : Lambda.t = | Texp_setfield (arg, _, lbl, newval) -> let access = match lbl.lbl_repres with - | Record_regular -> + | Record_regular | Record_array -> Psetfield (lbl.lbl_pos, Lambda.fld_record_set lbl.lbl_runtime_name) | Record_inlined _ -> Psetfield @@ -1802,7 +1801,7 @@ and transl_record loc env fields repres opt_init_expr = | None, Some _ -> let access = match repres with - | Record_regular -> + | Record_regular | Record_array -> Pfield (i, Lambda.fld_record lbl.lbl_runtime_name) | Record_inlined _ -> Pfield (i, Lambda.fld_record_inline lbl.lbl_runtime_name) @@ -1823,8 +1822,12 @@ and transl_record loc env fields repres opt_init_expr = if mut = Mutable then raise Not_constant; let cl = List.map extract_constant ll in match repres with - | Record_regular -> - const (Const_block (Lambda.blk_record (field_shape ()) mut, cl)) + | Record_regular | Record_array -> + const + (Const_block + ( Lambda.blk_record (field_shape ()) mut + ~array:(repres = Record_array), + cl )) | Record_inlined {name; representation} -> let runtime = match Variant_runtime.representation representation with @@ -1848,9 +1851,12 @@ and transl_record loc env fields repres opt_init_expr = | Record_extension -> raise Not_constant with Not_constant -> ( match repres with - | Record_regular -> + | Record_regular | Record_array -> prim - ~primitive:(Pmakeblock (Lambda.blk_record (field_shape ()) mut)) + ~primitive: + (Pmakeblock + (Lambda.blk_record (field_shape ()) mut + ~array:(repres = Record_array))) ~args:ll loc | Record_inlined {name; representation} -> let runtime = @@ -1901,6 +1907,8 @@ and transl_record loc env fields repres opt_init_expr = Psetfield (lbl.lbl_pos, Lambda.fld_record_inline_set lbl.lbl_runtime_name) | Record_unboxed _ -> assert false + (* [record_copies_fields] holds for an array record *) + | Record_array -> assert false | Record_extension -> Psetfield ( lbl.lbl_pos + 1, diff --git a/compiler/ml/typecore_record_rest.ml b/compiler/ml/typecore_record_rest.ml index 536ffd4f8f..b96bc5400f 100644 --- a/compiler/ml/typecore_record_rest.ml +++ b/compiler/ml/typecore_record_rest.ml @@ -15,6 +15,7 @@ type error = rest_runtime_name: string; } | Unboxed_record + | Array_record | Mutable_source_record exception Error of Location.t * Env.t * error @@ -151,6 +152,9 @@ let type_record_pat_rest ~env ~pattern_force ~loc ~record_ty ~lbl_pat_list ~rest match rest_decl.type_kind with | Type_record (_, Record_unboxed _) -> raise_error rest_type_lid.loc env Unboxed_record + (* the rest is an object spread, which can't produce an array *) + | Type_record (_, Record_array) -> + raise_error rest_type_lid.loc env Array_record | Type_record (labels, _) -> (rest_decl, labels) | _ -> raise_error rest_type_lid.loc env (Not_record rest_type_lid.txt)) | None -> raise_error rest_type_lid.loc env (Not_record rest_type_lid.txt) @@ -303,6 +307,10 @@ let report_error ppf = function field Printtyp.longident rest_type rest_runtime_name source_runtime_name | Unboxed_record -> fprintf ppf "Record rest patterns cannot be used with unboxed record types." + | Array_record -> + fprintf ppf + "The rest of a record pattern cannot have a record type represented as \ + an array (fields with the runtime names \"0\", \"1\", ...)." | Mutable_source_record -> fprintf ppf "Record rest patterns cannot be used on records with mutable fields." diff --git a/compiler/ml/typecore_record_rest.mli b/compiler/ml/typecore_record_rest.mli index f8ddf7f46a..6ef3824aa6 100644 --- a/compiler/ml/typecore_record_rest.mli +++ b/compiler/ml/typecore_record_rest.mli @@ -14,6 +14,7 @@ type error = rest_runtime_name: string; } | Unboxed_record + | Array_record | Mutable_source_record exception Error of Location.t * Env.t * error diff --git a/compiler/ml/typedecl.ml b/compiler/ml/typedecl.ml index 658d3c9301..2ffd1258d7 100644 --- a/compiler/ml/typedecl.ml +++ b/compiler/ml/typedecl.ml @@ -683,12 +683,11 @@ let transl_declaration ~type_record_as_object env sdecl id = match lbls_opt with | Some (lbls, lbls') -> check_duplicates sdecl.ptype_loc lbls String_set.empty; - let optional = Ext_list.exists lbls (fun lbl -> lbl.ld_optional) in ( Ttype_record lbls, Type_record ( lbls', if unbox then Record_unboxed false - else if optional then Record_regular + else if Record_runtime.is_array lbls' then Record_array else Record_regular ), sdecl ) | None -> ( diff --git a/compiler/ml/types.ml b/compiler/ml/types.ml index 55208050a7..6095ac1853 100644 --- a/compiler/ml/types.ml +++ b/compiler/ml/types.ml @@ -157,6 +157,9 @@ and type_kind = and record_representation = | Record_regular (* All fields are boxed / tagged *) + | Record_array + (* A regular record whose fields have the runtime names "0", "1", ... + in declaration order, represented as a JavaScript array *) | Record_unboxed of bool (* Unboxed single-field record, inlined or not *) | Record_inlined of (* Inlined record *) @@ -327,6 +330,7 @@ type label_description = { let same_record_representation x y = match x with | Record_regular -> y = Record_regular + | Record_array -> y = Record_array | Record_inlined {name} -> ( match y with | Record_inlined y -> name = y.name diff --git a/compiler/ml/types.mli b/compiler/ml/types.mli index 73de4a2bb5..b348dc2ec5 100644 --- a/compiler/ml/types.mli +++ b/compiler/ml/types.mli @@ -257,6 +257,9 @@ and type_kind = and record_representation = | Record_regular (* All fields are boxed / tagged *) + | Record_array + (* A regular record whose fields have the runtime names "0", "1", ... + in declaration order, represented as a JavaScript array *) | Record_unboxed of bool (* Unboxed single-field record, inlined or not *) | Record_inlined of (* Inlined record *) diff --git a/compiler/ml/variant_layout.ml b/compiler/ml/variant_layout.ml index 1c23edee71..72c6834454 100644 --- a/compiler/ml/variant_layout.ml +++ b/compiler/ml/variant_layout.ml @@ -50,6 +50,7 @@ let payload_kind ~env (t : Types.type_expr) : block_type option = | Tconstr (path, _, _) -> ( match Env.find_type path env with | {type_kind = Type_record (_, Record_unboxed _)} -> None + | {type_kind = Type_record (_, Record_array)} -> Some (InstanceType Array) | {type_kind = Type_record _} -> Some ObjectType | _ -> None | exception Not_found -> None) diff --git a/tests/build_tests/super_errors/expected/UntaggedTupleAndArray.res.expected b/tests/build_tests/super_errors/expected/UntaggedTupleAndArray.res.expected index f472163a70..aa98b12c33 100644 --- a/tests/build_tests/super_errors/expected/UntaggedTupleAndArray.res.expected +++ b/tests/build_tests/super_errors/expected/UntaggedTupleAndArray.res.expected @@ -7,4 +7,4 @@ 4 │ | Tuple((int, int)) 5 │ - This untagged variant definition is invalid: At most one case can be an array or tuple type. \ No newline at end of file + This untagged variant definition is invalid: At most one case can be an array, a tuple or a record represented as an array. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/record_coercion_array_to_object.res.expected b/tests/build_tests/super_errors/expected/record_coercion_array_to_object.res.expected new file mode 100644 index 0000000000..0d0befb2c3 --- /dev/null +++ b/tests/build_tests/super_errors/expected/record_coercion_array_to_object.res.expected @@ -0,0 +1,12 @@ + + We've found a bug for you! + /.../fixtures/record_coercion_array_to_object.res:11:43-51 + + 9 │ } + 10 │ + 11 │ let fromPair = (r: pair) => classify(Tail(r :> tail)) + 12 │ + + Type pair is not a subtype of tail + + The record pair is represented as a JavaScript array (its fields have the runtime names "0", "1", ...) and tail as an object, so neither can be coerced to the other. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/record_coercion_into_array_record.res.expected b/tests/build_tests/super_errors/expected/record_coercion_into_array_record.res.expected new file mode 100644 index 0000000000..53793054c4 --- /dev/null +++ b/tests/build_tests/super_errors/expected/record_coercion_into_array_record.res.expected @@ -0,0 +1,12 @@ + + We've found a bug for you! + /.../fixtures/record_coercion_into_array_record.res:4:26-33 + + 2 │ type arr = {@as("0") a: int, @as("1") b: int} + 3 │ + 4 │ let toArr = (x: obj) => (x :> arr) + 5 │ + + Type obj is not a subtype of arr + + The record arr is represented as a JavaScript array (its fields have the runtime names "0", "1", ...) and obj as an object, so neither can be coerced to the other. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/record_rest_array_record.res.expected b/tests/build_tests/super_errors/expected/record_rest_array_record.res.expected new file mode 100644 index 0000000000..c5fa8c6708 --- /dev/null +++ b/tests/build_tests/super_errors/expected/record_rest_array_record.res.expected @@ -0,0 +1,11 @@ + + We've found a bug for you! + /.../fixtures/record_rest_array_record.res:5:15-18 + + 3 │ + 4 │ let split = (r: source) => { + 5 │ let {s2, ...head as rest} = r + 6 │ (s2, rest) + 7 │ } + + The rest of a record pattern cannot have a record type represented as an array (fields with the runtime names "0", "1", ...). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/untagged_array_record_and_array.res.expected b/tests/build_tests/super_errors/expected/untagged_array_record_and_array.res.expected new file mode 100644 index 0000000000..c351866ca8 --- /dev/null +++ b/tests/build_tests/super_errors/expected/untagged_array_record_and_array.res.expected @@ -0,0 +1,10 @@ + + We've found a bug for you! + /.../fixtures/untagged_array_record_and_array.res:3:30-47 + + 1 │ type pair = {@as("0") x?: int, @as("1") y?: int} + 2 │ + 3 │ @unboxed type v = Pair(pair) | List(array) + 4 │ + + This untagged variant definition is invalid: At most one case can be an array, a tuple or a record represented as an array. \ No newline at end of file diff --git a/tests/build_tests/super_errors/fixtures/record_coercion_array_to_object.res b/tests/build_tests/super_errors/fixtures/record_coercion_array_to_object.res new file mode 100644 index 0000000000..99d03aa311 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/record_coercion_array_to_object.res @@ -0,0 +1,11 @@ +type pair = {@as("0") a: int, @as("1") b: int} +type tail = {@as("1") b: int} +@unboxed type v = Pair(pair) | Tail(tail) + +let classify = (v: v) => + switch v { + | Pair(_) => "pair" + | Tail(_) => "tail" + } + +let fromPair = (r: pair) => classify(Tail(r :> tail)) diff --git a/tests/build_tests/super_errors/fixtures/record_coercion_into_array_record.res b/tests/build_tests/super_errors/fixtures/record_coercion_into_array_record.res new file mode 100644 index 0000000000..a317d69023 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/record_coercion_into_array_record.res @@ -0,0 +1,4 @@ +type obj = {@as("0") a: int, @as("1") b: int, x: int} +type arr = {@as("0") a: int, @as("1") b: int} + +let toArr = (x: obj) => (x :> arr) diff --git a/tests/build_tests/super_errors/fixtures/record_rest_array_record.res b/tests/build_tests/super_errors/fixtures/record_rest_array_record.res new file mode 100644 index 0000000000..014353a855 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/record_rest_array_record.res @@ -0,0 +1,7 @@ +type source = {@as("0") s0: int, @as("1") s1: int, @as("2") s2: int} +type head = {@as("0") s0: int, @as("1") s1: int} + +let split = (r: source) => { + let {s2, ...head as rest} = r + (s2, rest) +} diff --git a/tests/build_tests/super_errors/fixtures/untagged_array_record_and_array.res b/tests/build_tests/super_errors/fixtures/untagged_array_record_and_array.res new file mode 100644 index 0000000000..6b3371e8c3 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/untagged_array_record_and_array.res @@ -0,0 +1,3 @@ +type pair = {@as("0") x?: int, @as("1") y?: int} + +@unboxed type v = Pair(pair) | List(array) diff --git a/tests/ounit_tests/ounit_lambda_constant_tests.ml b/tests/ounit_tests/ounit_lambda_constant_tests.ml index d218cbac14..949a5d8ee4 100644 --- a/tests/ounit_tests/ounit_lambda_constant_tests.ml +++ b/tests/ounit_tests/ounit_lambda_constant_tests.ml @@ -131,12 +131,12 @@ let switch_tests = assert_fold sw (Const_block (Blk_tuple, [Const_int 1l])) "array"; assert_fold sw (Const_block - ( Lambda.blk_record [|("0", false)|] Asttypes.Immutable, + ( Lambda.blk_record [|("0", false)|] Asttypes.Immutable ~array:true, [Const_int 1l] )) "array"; assert_fold sw (Const_block - ( Lambda.blk_record [|("x", false)|] Asttypes.Immutable, + ( Lambda.blk_record [|("x", false)|] Asttypes.Immutable ~array:false, [Const_int 1l] )) "object" ); ( "null without a null case is an object" >:: fun _ -> @@ -258,18 +258,32 @@ let suites = =~ Typecore.constant (Pconst_integer ("999999999999999999999999999", None)) ); ( "record array layout" >:: fun _ -> + (* a field [name], renamed to [runtime] by [@as] if given *) + let field (name, runtime) : Types.label_declaration = + { + ld_id = Ident.create name; + ld_runtime_name = runtime; + ld_mutable = Asttypes.Immutable; + ld_optional = false; + ld_type = Ctype.newvar (); + ld_loc = Location.none; + ld_attributes = []; + } + in List.iter (fun (fields, expected) -> OUnit.assert_equal expected - (Lambda.record_fields_are_array fields)) + (Record_runtime.is_array (List.map field fields))) [ - ([||], false); - ([|("0", false)|], true); - ([|("0", true); ("1", false)|], true); - ([|("1", false)|], false); - ([|("0", false); ("2", false)|], false); - ([|("00", false)|], false); - ([|("name", false)|], false); + ([], false); + ([("a", Some "0")], true); + ([("a", Some "0"); ("b", Some "1")], true); + ([("a", Some "1")], false); + ([("a", Some "1"); ("b", Some "0")], false); + ([("a", Some "0"); ("b", Some "2")], false); + ([("a", Some "0"); ("b", None)], false); + ([("a", Some "00")], false); + ([("name", None)], false); ] ); ( "regexp literals lower to raw JavaScript" >:: fun _ -> let expression = Ast_helper.Exp.regexp {|a\/b\d|} "ig" in diff --git a/tests/ounit_tests/ounit_sroa_tests.ml b/tests/ounit_tests/ounit_sroa_tests.ml index bfc79011d2..52ce22dd02 100644 --- a/tests/ounit_tests/ounit_sroa_tests.ml +++ b/tests/ounit_tests/ounit_sroa_tests.ml @@ -59,6 +59,7 @@ let pair_info = { fields = [|("left", false); ("right", false)|]; mutable_flag = Asttypes.Mutable; + array = false; } let suites = diff --git a/tests/tests/src/array_record_test.mjs b/tests/tests/src/array_record_test.mjs new file mode 100644 index 0000000000..7b5bc63f3a --- /dev/null +++ b/tests/tests/src/array_record_test.mjs @@ -0,0 +1,256 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; + +function updateOptional(r) { + return [ + r[0], + 2 + ]; +} + +let bigValue = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19 +]; + +function updateBig(r) { + return [ + r[0], + 100, + r[2], + r[3], + r[4], + r[5], + r[6], + r[7], + r[8], + r[9], + r[10], + r[11], + r[12], + r[13], + r[14], + r[15], + r[16], + r[17], + r[18], + r[19] + ]; +} + +function makeMutable(x, y) { + return [ + x, + y + ]; +} + +function updateMutable(r) { + return [ + r[0], + "z" + ]; +} + +let emptyValue = []; + +let tripleValue = [ + 1, + 2, + 3 +]; + +let swappedValue = { + "1": 1, + "0": 2 +}; + +function split(r) { + let {"0": __rest_field0, ...rest} = r; + return [ + __rest_field0, + rest + ]; +} + +function classify(p) { + if (typeof p === "string") { + return "text"; + } else if (Array.isArray(p)) { + return "point"; + } else { + return "named"; + } +} + +Mocha.describe("Array_record_test", () => { + Mocha.test("an untagged array record payload dispatches as an array", () => Test_utils.eq("File \"array_record_test.res\", line 108, characters 6-13", [ + [ + 1, + 2 + ], + [], + { + name: "n" + }, + "t" + ].map(classify), [ + "point", + "point", + "named", + "text" + ])); + Mocha.test("spread over a record with an optional field is an array", () => { + let r_0 = 1; + let r = [ + r_0, + 2 + ]; + Test_utils.ok("File \"array_record_test.res\", line 116, characters 7-14", Array.isArray(r)); + Test_utils.eq("File \"array_record_test.res\", line 117, characters 7-14", [ + 1, + 2 + ], [ + 1, + 2 + ]); + let r$1 = [ + undefined, + 2 + ]; + Test_utils.ok("File \"array_record_test.res\", line 119, characters 7-14", Array.isArray(r$1)); + Test_utils.eq("File \"array_record_test.res\", line 120, characters 7-14", [ + undefined, + 2 + ], [ + undefined, + 2 + ]); + }); + Mocha.test("spread over a record with 20 fields is an array", () => { + let r = updateBig(bigValue); + Test_utils.ok("File \"array_record_test.res\", line 125, characters 7-14", Array.isArray(r)); + Test_utils.eq("File \"array_record_test.res\", line 126, characters 7-14", r.length, 20); + Test_utils.eq("File \"array_record_test.res\", line 127, characters 7-14", [ + r[0], + r[1], + r[19] + ], [ + 0, + 100, + 19 + ]); + }); + Mocha.test("mutable fields write the array element", () => { + let r = [ + 1, + "a" + ]; + r[0] = 5; + let r$1 = updateMutable(r); + Test_utils.ok("File \"array_record_test.res\", line 134, characters 7-14", Array.isArray(r$1)); + Test_utils.eq("File \"array_record_test.res\", line 135, characters 7-14", [ + r$1[0], + r$1[1] + ], [ + 5, + "z" + ]); + }); + Mocha.test("an empty literal is an array", () => { + Test_utils.ok("File \"array_record_test.res\", line 139, characters 7-14", Array.isArray(emptyValue)); + Test_utils.eq("File \"array_record_test.res\", line 140, characters 7-14", emptyValue[0], undefined); + }); + Mocha.test("a type spread keeps the array layout", () => { + Test_utils.ok("File \"array_record_test.res\", line 144, characters 7-14", Array.isArray(tripleValue)); + Test_utils.eq("File \"array_record_test.res\", line 145, characters 7-14", 3, 3); + }); + Mocha.test("runtime names out of order give an object", () => { + Test_utils.ok("File \"array_record_test.res\", line 149, characters 7-14", !Array.isArray(swappedValue)); + Test_utils.eq("File \"array_record_test.res\", line 150, characters 7-14", [ + 1, + 2 + ], [ + 1, + 2 + ]); + }); + Mocha.test("pattern matching reads the elements", () => { + let classify = r => { + if (r[0] === 0) { + return r[1]; + } + let s2 = r[2]; + if (s2 !== undefined) { + return s2; + } else { + return -1; + } + }; + Test_utils.eq("File \"array_record_test.res\", line 160, characters 7-14", classify([ + 0, + 7, + undefined + ]), 7); + Test_utils.eq("File \"array_record_test.res\", line 161, characters 7-14", classify([ + 1, + 7, + 9 + ]), 9); + Test_utils.eq("File \"array_record_test.res\", line 162, characters 7-14", classify([ + 1, + 7, + undefined + ]), -1); + }); + Mocha.test("rest of an array record", () => { + let match = split([ + 1, + 2, + 3 + ]); + let rest = match[1]; + Test_utils.eq("File \"array_record_test.res\", line 167, characters 7-14", match[0], 1); + Test_utils.eq("File \"array_record_test.res\", line 168, characters 7-14", [ + rest[1], + rest[2] + ], [ + 2, + 3 + ]); + }); +}); + +export { + updateOptional, + bigValue, + updateBig, + makeMutable, + updateMutable, + emptyValue, + tripleValue, + swappedValue, + split, + classify, +} +/* Not a pure module */ diff --git a/tests/tests/src/array_record_test.res b/tests/tests/src/array_record_test.res new file mode 100644 index 0000000000..1daee06eb4 --- /dev/null +++ b/tests/tests/src/array_record_test.res @@ -0,0 +1,170 @@ +open Mocha +open Test_utils + +// Records whose fields have the runtime names "0", "1", ... in declaration +// order are JavaScript arrays + +@scope("Array") @val external isArray: 'a => bool = "isArray" +@get external length: 'a => int = "length" + +type withOptional = {@as("0") a?: int, @as("1") b: int} + +let updateOptional = (r: withOptional) => {...r, b: 2} + +type big = { + @as("0") f0: int, + @as("1") f1: int, + @as("2") f2: int, + @as("3") f3: int, + @as("4") f4: int, + @as("5") f5: int, + @as("6") f6: int, + @as("7") f7: int, + @as("8") f8: int, + @as("9") f9: int, + @as("10") f10: int, + @as("11") f11: int, + @as("12") f12: int, + @as("13") f13: int, + @as("14") f14: int, + @as("15") f15: int, + @as("16") f16: int, + @as("17") f17: int, + @as("18") f18: int, + @as("19") f19: int, +} + +let bigValue: big = { + f0: 0, + f1: 1, + f2: 2, + f3: 3, + f4: 4, + f5: 5, + f6: 6, + f7: 7, + f8: 8, + f9: 9, + f10: 10, + f11: 11, + f12: 12, + f13: 13, + f14: 14, + f15: 15, + f16: 16, + f17: 17, + f18: 18, + f19: 19, +} + +let updateBig = (r: big) => {...r, f1: 100} + +type mutablePair = {@as("0") mutable x: int, @as("1") y: string} + +let makeMutable = (x, y) => {x, y} +let updateMutable = (r: mutablePair) => {...r, y: "z"} + +type empty = {@as("0") e?: int} + +let emptyValue: empty = {} + +// Extending an array record with the next index is an array record too +type pair = {@as("0") first: int, @as("1") second: int} +type triple = {...pair, @as("2") third: int} + +let tripleValue: triple = {first: 1, second: 2, third: 3} + +// Runtime names out of declaration order: an object +type swapped = {@as("1") p: int, @as("0") q: int} + +let swappedValue = {p: 1, q: 2} + +// Rest of an array record into an object record +type source = {@as("0") s0: int, @as("1") s1: int, @as("2") s2?: int} +type tail = {@as("1") s1: int, @as("2") s2?: int} + +let split = (r: source) => { + let {s0, ...tail as rest} = r + (s0, rest) +} + +// As an untagged payload, an array record is told apart as an array +type point = {@as("0") px?: int, @as("1") py?: int} +type named = {name: string} + +@unboxed type payload = Point(point) | Named(named) | Text(string) + +let classify = (p: payload) => + switch p { + | Point(_) => "point" + | Named(_) => "named" + | Text(_) => "text" + } + +describe(__MODULE__, () => { + test("an untagged array record payload dispatches as an array", () => { + // Through Array.map, so that the match runs instead of being folded + eq( + __LOC__, + [Point({px: 1, py: 2}), Point({}), Named({name: "n"}), Text("t")]->Array.map(classify), + ["point", "point", "named", "text"], + ) + }) + + test("spread over a record with an optional field is an array", () => { + let r = updateOptional({a: 1, b: 0}) + ok(__LOC__, isArray(r)) + eq(__LOC__, (r.a, r.b), (Some(1), 2)) + let r = updateOptional({b: 0}) + ok(__LOC__, isArray(r)) + eq(__LOC__, (r.a, r.b), (None, 2)) + }) + + test("spread over a record with 20 fields is an array", () => { + let r = updateBig(bigValue) + ok(__LOC__, isArray(r)) + eq(__LOC__, length(r), 20) + eq(__LOC__, (r.f0, r.f1, r.f19), (0, 100, 19)) + }) + + test("mutable fields write the array element", () => { + let r = makeMutable(1, "a") + r.x = 5 + let r = updateMutable(r) + ok(__LOC__, isArray(r)) + eq(__LOC__, (r.x, r.y), (5, "z")) + }) + + test("an empty literal is an array", () => { + ok(__LOC__, isArray(emptyValue)) + eq(__LOC__, emptyValue.e, None) + }) + + test("a type spread keeps the array layout", () => { + ok(__LOC__, isArray(tripleValue)) + eq(__LOC__, tripleValue.third, 3) + }) + + test("runtime names out of order give an object", () => { + ok(__LOC__, !isArray(swappedValue)) + eq(__LOC__, (swappedValue.p, swappedValue.q), (1, 2)) + }) + + test("pattern matching reads the elements", () => { + let classify = (r: source) => + switch r { + | {s0: 0, s1} => s1 + | {s2} => s2 + | _ => -1 + } + eq(__LOC__, classify({s0: 0, s1: 7}), 7) + eq(__LOC__, classify({s0: 1, s1: 7, s2: 9}), 9) + eq(__LOC__, classify({s0: 1, s1: 7}), -1) + }) + + test("rest of an array record", () => { + let (s0, rest) = split({s0: 1, s1: 2, s2: 3}) + eq(__LOC__, s0, 1) + eq(__LOC__, (rest.s1, rest.s2), (2, Some(3))) + }) +})