diff --git a/CHANGELOG.md b/CHANGELOG.md index bf68dd98dec..78e042bd9d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ #### :bug: Bug fix +- Fix the formatter dropping attributes on dict literals and flattening nested dict spreads. https://github.com/rescript-lang/rescript/pull/8746 - Fix attributes on patterns being duplicated before `as` and dropped on constants when formatting. https://github.com/rescript-lang/rescript/pull/8750 - Fix compiler crashes when wrapping values in `Some` or passing optional arguments whose types come from a transitive dependency. https://github.com/rescript-lang/rescript/pull/8719 - Fix unused-pattern warnings for variant spreads reported without a location. https://github.com/rescript-lang/rescript/pull/8744 @@ -51,6 +52,7 @@ #### :house: Internal +- Represent dict literals with dedicated `Pexp_dict` and `Texp_dict` nodes. https://github.com/rescript-lang/rescript/pull/8746 - Forward-port integer range pattern regression coverage from v12 to v13. https://github.com/rescript-lang/rescript/pull/8718 - Remove the unused `res.iflet` encoding of `if let`, which the parser always rejects with a syntax error suggesting a `switch`. The error is unchanged. https://github.com/rescript-lang/rescript/pull/8741 - Represent variant spread patterns (`...t`) with a dedicated `Ppat_variant_spread` parsetree node instead of `Ppat_type` with a `res.patVariantSpread` attribute, which remains only in the PPX wire representation. https://github.com/rescript-lang/rescript/pull/8742 diff --git a/analysis/reanalyze/src/arnold.ml b/analysis/reanalyze/src/arnold.ml index bc901d48718..93d7e412d51 100644 --- a/analysis/reanalyze/src/arnold.ml +++ b/analysis/reanalyze/src/arnold.ml @@ -990,6 +990,11 @@ module Compile = struct [e1; e2] |> List.map (expression ~ctx) |> Command.unordered_sequence | Texp_tuple expressions | Texp_array expressions -> expressions |> List.map (expression ~ctx) |> Command.unordered_sequence + | Texp_dict entries -> + entries + |> List.map (function Typedtree.Tdict_entry (_, e) | Tdict_spread e -> + expression ~ctx e) + |> Command.unordered_sequence | Texp_assert _ -> Command.nothing | Texp_try (e, cases) -> let c_e = e |> expression ~ctx in diff --git a/analysis/reanalyze/src/side_effects.ml b/analysis/reanalyze/src/side_effects.ml index 14a5334a0d9..156f7b067e4 100644 --- a/analysis/reanalyze/src/side_effects.ml +++ b/analysis/reanalyze/src/side_effects.ml @@ -56,6 +56,12 @@ let rec expr_no_side_effects (expr : Typedtree.expression) = | Texp_field (e, _lid, _ld) -> e |> expr_no_side_effects | Texp_setfield _ -> false | Texp_array el -> el |> List.for_all expr_no_side_effects + | Texp_dict entries -> + entries + |> List.for_all (function + | Typedtree.Tdict_entry (_, e) -> e |> expr_no_side_effects + (* Object.assign reads the spread dicts *) + | Tdict_spread _ -> false) | Texp_ifthenelse (e1, e2, eo) -> e1 |> expr_no_side_effects && e2 |> expr_no_side_effects && eo |> expr_opt_no_side_effects diff --git a/analysis/src/completion_back_end.ml b/analysis/src/completion_back_end.ml index ad44aae76c4..4405527ee4a 100644 --- a/analysis/src/completion_back_end.ml +++ b/analysis/src/completion_back_end.ml @@ -983,6 +983,12 @@ and get_completions_for_context_path ~state ~debug ~full ~opens ~raw_opens ~pos Completion.create "array" ~env ~kind:(Completion.Value (Ctype.newconstr Predef.path_array [])); ] + | CPDict -> + if Debug.verbose () then print_endline "[ctx_path]--> CPDict"; + [ + Completion.create "dict" ~env + ~kind:(Completion.Value (Ctype.newconstr Predef.path_dict [])); + ] | CPArray (Some cp) -> ( if Debug.verbose () then print_endline "[ctx_path]--> CPArray (with payload)"; diff --git a/analysis/src/completion_front_end.ml b/analysis/src/completion_front_end.ml index add09af21a6..a1fd9299659 100644 --- a/analysis/src/completion_front_end.ml +++ b/analysis/src/completion_front_end.ml @@ -231,6 +231,7 @@ let rec expr_to_context_path_inner ~(in_jsx_context : bool) (match exprs with | [] -> None | exp :: _ -> expr_to_context_path ~in_jsx_context exp)) + | Pexp_dict _ -> Some CPDict | Pexp_ident {txt = Lident "->"} -> None | Pexp_ident {txt; loc} -> Some diff --git a/analysis/src/dump_ast.ml b/analysis/src/dump_ast.ml index 12a3b728877..0083dcf453a 100644 --- a/analysis/src/dump_ast.ml +++ b/analysis/src/dump_ast.ml @@ -197,6 +197,23 @@ and print_expr_item expr ~pos ~indentation = ^ "\n" ^ add_indentation indentation ^ ")" + | Pexp_dict entries -> + "Pexp_dict(\n" + ^ (entries + |> List.map (fun entry -> + add_indentation (indentation + 1) + ^ + match entry with + | Parsetree.Pdict_entry (key, expr) -> + (key |> print_loc_denominator_loc ~pos) + ^ "\"" ^ key.txt ^ "\": " + ^ print_expr_item expr ~pos ~indentation:(indentation + 1) + | Pdict_spread expr -> + "..." ^ print_expr_item expr ~pos ~indentation:(indentation + 1)) + |> String.concat "\n") + ^ "\n" + ^ add_indentation indentation + ^ ")" | Pexp_match (match_expr, cases) -> "Pexp_match(" ^ print_expr_item match_expr ~pos ~indentation:0 diff --git a/analysis/src/hint.ml b/analysis/src/hint.ml index 654d829e5b5..6e04653b214 100644 --- a/analysis/src/hint.ml +++ b/analysis/src/hint.ml @@ -57,7 +57,7 @@ let inlay ~source ~kind_file ~pos ~max_length ~full ~state ~debug = match expr.pexp_desc with | Pexp_constant _ | Pexp_tuple _ | Pexp_record _ | Pexp_variant _ | Pexp_apply _ | Pexp_match _ | Pexp_construct _ | Pexp_ifthenelse _ - | Pexp_ternary _ | Pexp_array _ | Pexp_ident _ | Pexp_try _ + | Pexp_ternary _ | Pexp_array _ | Pexp_dict _ | Pexp_ident _ | Pexp_try _ | Pexp_object_get _ | Pexp_object_set _ | Pexp_field _ | Pexp_open _ | Pexp_fun _ | Pexp_template _ | Pexp_tagged_template _ -> push vb.pvb_pat.ppat_loc Type diff --git a/analysis/src/semantic_tokens.ml b/analysis/src/semantic_tokens.ml index 0be8854d713..1e0219e2d01 100644 --- a/analysis/src/semantic_tokens.ml +++ b/analysis/src/semantic_tokens.ml @@ -265,9 +265,6 @@ let command ~debug ~emitter ~source ~kind_file = |> List.exists (fun ({Location.txt}, _) -> txt = "res.spread") in not has_spread_attr - (* Dict syntax (`dict{...}`) is converted to `Primitive_dict.make` *) - | Ldot (Lident "Primitive_dict", "make") -> false - | Lident "Primitive_dict" -> false (* Array access (`arr[index]`) is converted to `Array.get` *) | Ldot (Lident "Array", "get") -> false (* Array mutation (`arr[index]`) is converted to `Array.set` *) diff --git a/analysis/src/shared_types.ml b/analysis/src/shared_types.ml index e5b33277c0b..e89900b12f3 100644 --- a/analysis/src/shared_types.ml +++ b/analysis/src/shared_types.ml @@ -633,6 +633,7 @@ module Completable = struct type context_path = | CPString | CPArray of context_path option + | CPDict | CPInt | CPFloat | CPBool @@ -734,6 +735,7 @@ module Completable = struct | CPArray (Some ctx_path) -> "array<" ^ context_path_to_string ctx_path ^ ">" | CPArray None -> "array" + | CPDict -> "dict" | CPId {path; completion_context} -> completion_context_to_string completion_context ^ list path | CPField {context_path = cp; field_name = s} -> diff --git a/analysis/src/utils.ml b/analysis/src/utils.ml index 34df53e0044..b488c330480 100644 --- a/analysis/src/utils.ml +++ b/analysis/src/utils.ml @@ -121,6 +121,7 @@ let identify_pexp pexp = | Pexp_await _ -> "Pexp_await" | Pexp_jsx_element _ -> "Pexp_jsx_element" | Pexp_regexp _ -> "Pexp_regexp" + | Pexp_dict _ -> "Pexp_dict" | Pexp_template _ -> "Pexp_template" | Pexp_tagged_template _ -> "Pexp_tagged_template" diff --git a/compiler/core/lam_analysis.ml b/compiler/core/lam_analysis.ml index 1b90637c489..1a8a763b261 100644 --- a/compiler/core/lam_analysis.ml +++ b/compiler/core/lam_analysis.ml @@ -97,7 +97,7 @@ let rec no_side_effects (lam : Lambda.t) : bool = true (* A tagged template invokes its tag at runtime, so it always has side effects. *) - | Ptagged_template _ | Pjs_call _ | Pinit_mod | Pupdate_mod + | Ptagged_template _ | Pjs_call _ | Pdict_spread | Pinit_mod | Pupdate_mod | Pjs_object_get _ | Pjs_object_set _ | Pdebugger | Pjs_fn_method (* Await promise *) | Pawait diff --git a/compiler/core/lam_compile_primitive.ml b/compiler/core/lam_compile_primitive.ml index c1d859b02d5..579d85296e0 100644 --- a/compiler/core/lam_compile_primitive.ml +++ b/compiler/core/lam_compile_primitive.ml @@ -580,6 +580,11 @@ let translate output_prefix loc (cxt : Lam_compile_context.t) Some (Js_op.Lit txt, expr) | _ -> None)) | _ -> assert false) + | Pdict_spread -> + E.call + ~info:(Js_call_info.na_full_call false) + (E.js_global "Object.assign") + args | Pdict_has -> ( match args with | [obj; prop] -> E.in_ prop obj diff --git a/compiler/ext/config.ml b/compiler/ext/config.ml index b7dede6436d..7a53fb8a959 100644 --- a/compiler/ext/config.ml +++ b/compiler/ext/config.ml @@ -2,9 +2,9 @@ let cmi_magic_number = "Caml1999I035" (* Magic numbers for marshaled values of the *current* parsetree, whose layout changes across compiler versions. *) -and ast_impl_magic_number = "ResImpl01313" +and ast_impl_magic_number = "ResImpl01314" -and ast_intf_magic_number = "ResIntf01313" +and ast_intf_magic_number = "ResIntf01314" (* Magic numbers of the frozen Parsetree0 (OCaml 4.06) layout used on the external-PPX wire. They must never be written in front of a @@ -13,6 +13,6 @@ and ast0_impl_magic_number = "Caml1999M022" and ast0_intf_magic_number = "Caml1999N022" -and cmt_magic_number = "Caml1999T039" +and cmt_magic_number = "Caml1999T040" let load_path = ref ([] : string list) diff --git a/compiler/ml/ast_dict.ml b/compiler/ml/ast_dict.ml new file mode 100644 index 00000000000..98bb83ca5cd --- /dev/null +++ b/compiler/ml/ast_dict.ml @@ -0,0 +1,105 @@ +(* Dict literals, [Pexp_dict]: [dict{"a": 1, ...d}]. They used to be parsed + into calls of the runtime's [Primitive_dict], which remain their encoding on + the v0 PPX wire: + - without spreads, [Primitive_dict.make([("a", 1)])]; + - with spreads, [Primitive_dict.spread(target, [part, ...])], whose + [spread] carries the [res.dictSpread] marker. The target is + [Primitive_dict.make(rows)] with the rows before the first spread, and + the parts are the spreads and [Primitive_dict.make(rows)] for the rows + between them, like [Object.assign]. *) + +open Parsetree + +type ('row, 'spread) part = Rows of 'row list | Spread of 'spread + +(* Group consecutive rows *) +let group (entries : [`Row of 'row | `Spread of 'spread] list) : + ('row, 'spread) part list = + let flush rows acc = + match rows with + | [] -> acc + | _ -> Rows (List.rev rows) :: acc + in + let rec loop rows acc = function + | [] -> List.rev (flush rows acc) + | `Row row :: rest -> loop (row :: rows) acc rest + | `Spread spread :: rest -> loop [] (Spread spread :: flush rows acc) rest + in + loop [] [] entries + +(* The rows of a dict without spreads, or the target and the sources it's + built from *) +let target_and_sources (parts : ('row, 'spread) part list) = + match parts with + | [] -> `Rows [] + | [Rows rows] -> `Rows rows + | Rows target :: sources -> `Spread (target, sources) + | sources -> `Spread ([], sources) + +let entries (entries : dict_entry list) = + List.map + (function + | Pdict_entry (key, value) -> `Row (key, value) + | Pdict_spread spread -> `Spread spread) + entries + +let parts dict_entries = group (entries dict_entries) + +let mk_loc loc_start loc_end = {Location.loc_start; loc_end; loc_ghost = false} + +(* From the first key to the last value *) +let rows_loc ~loc (rows : (string Location.loc * expression) list) = + match (rows, List.rev rows) with + | (first_key, _) :: _, (_, last_value) :: _ -> + mk_loc first_key.loc.loc_start last_value.pexp_loc.loc_end + | _ -> loc + +(* [[("a", 1), ...]], the argument of [Primitive_dict.make] *) +let rows_array ~loc (rows : (string Location.loc * expression) list) = + Ast_helper.Exp.array ~loc + (List.map + (fun ((key : string Location.loc), value) -> + Ast_helper.Exp.tuple + ~loc:(mk_loc key.loc.loc_start value.pexp_loc.loc_end) + [ + Ast_helper.Exp.constant ~loc:key.loc + (Ast_helper.Const.string key.txt); + value; + ]) + rows) + +let primitive_dict ~loc ?attrs name = + Ast_helper.Exp.ident ~loc ?attrs + (Location.mkloc + (Longident.Ldot (Longident.Lident Primitive_modules.dict, name)) + loc) + +let spread_marker = "res.dictSpread" + +let make ~loc rows = + Ast_helper.Exp.apply ~loc + (primitive_dict ~loc "make") + [(Asttypes.Nolabel, rows_array ~loc rows)] + +(* The calls encoding the dict literal [dict{entries}] at [loc] *) +let to_calls ~loc ~attrs dict_entries = + let e = + match target_and_sources (parts dict_entries) with + | `Rows rows -> make ~loc rows + | `Spread (target, sources) -> + Ast_helper.Exp.apply ~loc + (primitive_dict ~loc + ~attrs:[(Location.mknoloc spread_marker, PStr [])] + "spread") + [ + (Nolabel, make ~loc:(rows_loc ~loc target) target); + ( Nolabel, + Ast_helper.Exp.array ~loc + (List.map + (function + | Rows rows -> make ~loc:(rows_loc ~loc rows) rows + | Spread spread -> spread) + sources) ); + ] + in + {e with pexp_attributes = attrs} diff --git a/compiler/ml/ast_helper.ml b/compiler/ml/ast_helper.ml index bd0bf8b2bae..96270b8133d 100644 --- a/compiler/ml/ast_helper.ml +++ b/compiler/ml/ast_helper.ml @@ -176,6 +176,7 @@ module Exp = struct let field ?loc ?attrs a b = mk ?loc ?attrs (Pexp_field (a, b)) let setfield ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_setfield (a, b, c)) let array ?loc ?attrs a = mk ?loc ?attrs (Pexp_array a) + let dict ?loc ?attrs a = mk ?loc ?attrs (Pexp_dict a) let ifthenelse ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_ifthenelse (a, b, c)) let ternary ?loc ?attrs condition consequent alternate = mk ?loc ?attrs (Pexp_ternary (condition, consequent, alternate)) diff --git a/compiler/ml/ast_helper.mli b/compiler/ml/ast_helper.mli index 04657603f2d..ff1a95c323a 100644 --- a/compiler/ml/ast_helper.mli +++ b/compiler/ml/ast_helper.mli @@ -172,6 +172,7 @@ module Exp : sig val setfield : ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression -> expression val array : ?loc:loc -> ?attrs:attrs -> expression list -> expression + val dict : ?loc:loc -> ?attrs:attrs -> dict_entry list -> expression val ifthenelse : ?loc:loc -> ?attrs:attrs -> diff --git a/compiler/ml/ast_iterator.ml b/compiler/ml/ast_iterator.ml index 1459f19cf18..e6b2c77f25e 100644 --- a/compiler/ml/ast_iterator.ml +++ b/compiler/ml/ast_iterator.ml @@ -341,6 +341,14 @@ module E = struct iter_loc sub lid; sub.expr sub e2 | Pexp_array el -> List.iter (sub.expr sub) el + | Pexp_dict entries -> + List.iter + (function + | Pdict_entry (key, e) -> + iter_loc sub key; + sub.expr sub e + | Pdict_spread e -> sub.expr sub e) + entries | Pexp_ifthenelse (e1, e2, e3) -> sub.expr sub e1; sub.expr sub e2; diff --git a/compiler/ml/ast_mapper.ml b/compiler/ml/ast_mapper.ml index a93a2e66de8..d61728f1992 100644 --- a/compiler/ml/ast_mapper.ml +++ b/compiler/ml/ast_mapper.ml @@ -341,6 +341,14 @@ module E = struct | Pexp_setfield (e1, lid, e2) -> setfield ~loc ~attrs (sub.expr sub e1) (map_loc sub lid) (sub.expr sub e2) | Pexp_array el -> array ~loc ~attrs (List.map (sub.expr sub) el) + | Pexp_dict entries -> + dict ~loc ~attrs + (List.map + (function + | Pdict_entry (key, e) -> + Pdict_entry (map_loc sub key, sub.expr sub e) + | Pdict_spread e -> Pdict_spread (sub.expr sub e)) + entries) | Pexp_ifthenelse (e1, e2, e3) -> ifthenelse ~loc ~attrs (sub.expr sub e1) (sub.expr sub e2) (map_opt (sub.expr sub) e3) diff --git a/compiler/ml/ast_mapper_from0.ml b/compiler/ml/ast_mapper_from0.ml index 38a8bed744a..d1b06e798c4 100644 --- a/compiler/ml/ast_mapper_from0.ml +++ b/compiler/ml/ast_mapper_from0.ml @@ -549,6 +549,79 @@ end module E = struct (* Value expressions for the core language *) + (* The rows of [Primitive_dict.make([("a", 1), ...])] *) + let dict_rows (e : expression) = + match e.pexp_desc with + | Pexp_apply + ( { + pexp_desc = Pexp_ident {txt = Ldot (Lident "Primitive_dict", "make")}; + pexp_attributes = []; + }, + [ + ( Asttypes.Noloc.Nolabel, + {pexp_desc = Pexp_array items; pexp_attributes = []} ); + ] ) -> + let row = function + | { + pexp_desc = + Pexp_tuple + [ + { + pexp_desc = + Pexp_constant + (Pconst_string (_, (None | Some ("js" | "*j"))) as key); + pexp_loc = key_loc; + pexp_attributes = []; + }; + value; + ]; + pexp_attributes = []; + } -> ( + match map_constant ~loc:key_loc key with + | Pt.Pconst_string key -> + Some + ({txt = String_literal.string_semantic key; loc = key_loc}, value) + | _ -> None) + | _ -> None + in + let rows = List.filter_map row items in + if List.length rows = List.length items then Some rows else None + | _ -> None + + (* The entries of a dict literal encoded as calls, see [Ast_dict] *) + let dict_entries (e : expression) = + let chunk (e : expression) = + match e.pexp_attributes with + | [] -> dict_rows e + | _ -> None + in + let rows = List.map (fun row -> `Row row) in + match e.pexp_desc with + | Pexp_apply + ( { + pexp_desc = + Pexp_ident {txt = Ldot (Lident "Primitive_dict", "spread")}; + pexp_attributes = [({txt}, PStr [])]; + }, + [ + (Asttypes.Noloc.Nolabel, target); + ( Asttypes.Noloc.Nolabel, + {pexp_desc = Pexp_array sources; pexp_attributes = []} ); + ] ) + when txt = Ast_dict.spread_marker -> ( + match chunk target with + | Some target_rows -> + Some + (rows target_rows + @ List.concat_map + (fun source -> + match chunk source with + | Some source_rows -> rows source_rows + | None -> [`Spread source]) + sources) + | None -> None) + | _ -> Option.map rows (dict_rows e) + let has_await_attribute attrs = List.exists (function @@ -784,6 +857,15 @@ module E = struct fun_ ~loc ~attrs [{p_attrs = []; p_lbl = Nolabel; p_default = None; p_pat = pat}] body + | Pexp_apply _ when Option.is_some (dict_entries e) -> + let entries = Option.get (dict_entries e) in + dict ~loc ~attrs + (List.map + (function + | `Row (key, value) -> + Pt.Pdict_entry (map_loc sub key, sub.expr sub value) + | `Spread spread -> Pt.Pdict_spread (sub.expr sub spread)) + entries) | Pexp_apply ( {pexp_desc = Pexp_ident {txt = Longident.Lident "#="}}, [ diff --git a/compiler/ml/ast_mapper_to0.ml b/compiler/ml/ast_mapper_to0.ml index 8c93dba9e06..f60dcca6f96 100644 --- a/compiler/ml/ast_mapper_to0.ml +++ b/compiler/ml/ast_mapper_to0.ml @@ -448,7 +448,8 @@ module E = struct (* Value expressions for the core language *) - let map sub {pexp_loc = loc; pexp_desc = desc; pexp_attributes = attrs} = + let map sub ({pexp_loc = loc; pexp_desc = desc; pexp_attributes = attrs} as e) + = let open Exp in let loc = sub.location sub loc in let is_ppx_context_string = has_ppx_context_string_attr attrs in @@ -634,6 +635,11 @@ module E = struct | Pexp_setfield (e1, lid, e2) -> setfield ~loc ~attrs (sub.expr sub e1) (map_loc sub lid) (sub.expr sub e2) | Pexp_array el -> array ~loc ~attrs (List.map (sub.expr sub) el) + | Pexp_dict entries -> + (* v0 has no dict literals: they're the calls they used to be parsed + into *) + sub.expr sub + (Ast_dict.to_calls ~loc:e.pexp_loc ~attrs:e.pexp_attributes entries) | Pexp_ifthenelse (e1, e2, e3) -> ifthenelse ~loc ~attrs (sub.expr sub e1) (sub.expr sub e2) (map_opt (sub.expr sub) e3) diff --git a/compiler/ml/depend.ml b/compiler/ml/depend.ml index ad3c0761785..bc844930936 100644 --- a/compiler/ml/depend.ml +++ b/compiler/ml/depend.ml @@ -250,6 +250,11 @@ let rec add_expr bv exp = add bv fld; add_expr bv e2 | Pexp_array el -> List.iter (add_expr bv) el + | Pexp_dict entries -> + List.iter + (function + | Pdict_entry (_, e) | Pdict_spread e -> add_expr bv e) + entries | Pexp_ifthenelse (e1, e2, opte3) -> add_expr bv e1; add_expr bv e2; diff --git a/compiler/ml/lambda.ml b/compiler/ml/lambda.ml index e19a0670c2b..83a587090aa 100644 --- a/compiler/ml/lambda.ml +++ b/compiler/ml/lambda.ml @@ -274,6 +274,10 @@ type primitive = and the primitive arguments contain [value]. The source forms are retained for JavaScript output; semantic forms are used by optimizations. *) | Ptemplate of Asttypes.template_segment list + (* Object.assign(target, ...sources). Kept after all other constant + constructors: .cmj files marshal Lambda.t without a version check, so + inserting it earlier would shift the tags of existing primitives. *) + | Pdict_spread and comparison = Ceq | Cneq | Clt | Cgt | Cle | Cge @@ -476,7 +480,7 @@ let eq_primitive_approx (lhs : primitive) (rhs : primitive) = (* List primitives *) | Pmakelist (* dict primitives *) - | Pmakedict | Pdict_has + | Pmakedict | Pdict_spread | Pdict_has (* promise *) | Pawait (* etc *) diff --git a/compiler/ml/lambda.mli b/compiler/ml/lambda.mli index 30741c141ba..9e0b8806d6c 100644 --- a/compiler/ml/lambda.mli +++ b/compiler/ml/lambda.mli @@ -274,6 +274,10 @@ type primitive = and the primitive arguments contain [value]. The source forms are retained for JavaScript output; semantic forms are used by optimizations. *) | Ptemplate of template_segment list + (* Object.assign(target, ...sources). Kept after all other constant + constructors: .cmj files marshal Lambda.t without a version check, so + inserting it earlier would shift the tags of existing primitives. *) + | Pdict_spread and comparison = Ceq | Cneq | Clt | Cgt | Cle | Cge diff --git a/compiler/ml/parsetree.ml b/compiler/ml/parsetree.ml index 0297655b8e2..3cda967c15a 100644 --- a/compiler/ml/parsetree.ml +++ b/compiler/ml/parsetree.ml @@ -344,6 +344,7 @@ and expression_desc = | Pexp_field of expression * Longident.t loc (* E.l *) | Pexp_setfield of expression * Longident.t loc * expression (* E1.l <- E2 *) | Pexp_array of expression list (* [| E1; ...; En |] *) + | Pexp_dict of dict_entry list (* dict{"k1": E1, ...E2} *) | Pexp_ifthenelse of expression * expression * expression option (* if E1 then E2 else E3 *) | Pexp_ternary of expression * expression * expression @@ -414,6 +415,10 @@ and expression_desc = (* an element of a record pattern or expression *) and 'a record_element = {lid: Longident.t loc; x: 'a; opt: bool (* optional *)} +and dict_entry = + | Pdict_entry of string loc * expression (* "k": E *) + | Pdict_spread of expression (* ...E *) + and jsx_element = | Jsx_fragment of jsx_fragment | Jsx_unary_element of jsx_unary_element diff --git a/compiler/ml/pprintast.ml b/compiler/ml/pprintast.ml index 35351aa46f1..2e9e58f1f0f 100644 --- a/compiler/ml/pprintast.ml +++ b/compiler/ml/pprintast.ml @@ -865,6 +865,13 @@ and simple_expr ctxt f x = pp f "@[<0>@[<2>[|%a|]@]@]" (list (simple_expr (under_semi ctxt)) ~sep:";") l + | Pexp_dict entries -> + let dict_entry f = function + | Pdict_entry (key, e) -> + pp f "@[%S:@;%a@]" key.txt (simple_expr ctxt) e + | Pdict_spread e -> pp f "...%a" (simple_expr ctxt) e + in + pp f "@[dict{%a}@]" (list dict_entry ~sep:",@;") entries | Pexp_break -> pp f "break" | Pexp_continue -> pp f "continue" | Pexp_while (e1, e2) -> diff --git a/compiler/ml/printast.ml b/compiler/ml/printast.ml index e14a6dcabb6..93fd757cf01 100644 --- a/compiler/ml/printast.ml +++ b/compiler/ml/printast.ml @@ -320,6 +320,9 @@ and expression i ppf x = | Pexp_array l -> line i ppf "Pexp_array\n"; list i expression ppf l + | Pexp_dict l -> + line i ppf "Pexp_dict\n"; + list i dict_entry ppf l | Pexp_ifthenelse (e1, e2, eo) -> line i ppf "Pexp_ifthenelse\n"; expression i ppf e1; @@ -437,6 +440,14 @@ and expression i ppf x = line i ppf "closing_tag =%a\n" fmt_jsx_tag_name closing_tag.jsx_closing_container_tag_name) +and dict_entry i ppf = function + | Pdict_entry (key, e) -> + line i ppf "Pdict_entry %a\n" fmt_string_loc key; + expression (i + 1) ppf e + | Pdict_spread e -> + line i ppf "Pdict_spread\n"; + expression (i + 1) ppf e + and jsx_children i ppf children = line i ppf "jsx_children =\n"; list (i + 1) expression ppf children diff --git a/compiler/ml/printlambda.ml b/compiler/ml/printlambda.ml index 9a0316ce604..c4d82cedd5d 100644 --- a/compiler/ml/printlambda.ml +++ b/compiler/ml/printlambda.ml @@ -194,6 +194,7 @@ let primitive ppf = function | Parrayrefs -> fprintf ppf "array.get" | Pmakelist -> fprintf ppf "makelist" | Pmakedict -> fprintf ppf "makedict" + | Pdict_spread -> fprintf ppf "dict.spread" | Pdict_has -> fprintf ppf "dict.has" | Pis_null -> fprintf ppf "is_null" | Pis_undefined -> fprintf ppf "is_undefined" diff --git a/compiler/ml/printtyped.ml b/compiler/ml/printtyped.ml index 292a853b0d4..95af9e2cded 100644 --- a/compiler/ml/printtyped.ml +++ b/compiler/ml/printtyped.ml @@ -329,6 +329,9 @@ and expression i ppf x = | Texp_array l -> line i ppf "Texp_array\n"; list i expression ppf l + | Texp_dict l -> + line i ppf "Texp_dict\n"; + list i dict_entry ppf l | Texp_ifthenelse (e1, e2, eo) -> line i ppf "Texp_ifthenelse\n"; expression i ppf e1; @@ -698,6 +701,14 @@ and longident_x_pattern i ppf (li, _, p, opt) = line i ppf "%a%s\n" fmt_longident li (if opt then "?" else ""); pattern (i + 1) ppf p +and dict_entry i ppf = function + | Tdict_entry (key, e) -> + line i ppf "Tdict_entry %S\n" key.txt; + expression (i + 1) ppf e + | Tdict_spread e -> + line i ppf "Tdict_spread\n"; + expression (i + 1) ppf e + and case i ppf {c_lhs; c_guard; c_rhs} = line i ppf "\n"; pattern (i + 1) ppf c_lhs; diff --git a/compiler/ml/rec_check.ml b/compiler/ml/rec_check.ml index 2fdd4eb1846..069d8df092a 100644 --- a/compiler/ml/rec_check.ml +++ b/compiler/ml/rec_check.ml @@ -207,9 +207,10 @@ let rec classify_expression : Typedtree.expression -> sd = Static | Texp_apply {funct = {exp_desc = Texp_ident (_, _, vd)}} when is_ref vd -> Static - | Texp_apply _ | Texp_match _ | Texp_ifthenelse _ | Texp_object_get _ - | Texp_object_set _ | Texp_field _ | Texp_assert _ | Texp_try _ - | Texp_tagged_template _ | Texp_template _ -> + (* A dict is built by calls, see [Translcore] *) + | Texp_apply _ | Texp_dict _ | Texp_match _ | Texp_ifthenelse _ + | Texp_object_get _ | Texp_object_set _ | Texp_field _ | Texp_assert _ + | Texp_try _ | Texp_tagged_template _ | Texp_template _ -> Dynamic let rec expression : Env.env -> Typedtree.expression -> Use.t = @@ -267,6 +268,11 @@ let rec expression : Env.env -> Typedtree.expression -> Use.t = | Texp_template {values} -> Use.guard (list expression env values) | Texp_tuple exprs -> Use.guard (list expression env exprs) | Texp_array exprs -> Use.guard (list expression env exprs) + | Texp_dict entries -> + let entry env = function + | Tdict_entry (_, e) | Tdict_spread e -> expression env e + in + Use.inspect (list entry env entries) | Texp_construct (_, desc, exprs) -> let access_constructor = match desc.cstr_kind with diff --git a/compiler/ml/tast_iterator.ml b/compiler/ml/tast_iterator.ml index c7a698921d1..cb760c46267 100644 --- a/compiler/ml/tast_iterator.ml +++ b/compiler/ml/tast_iterator.ml @@ -177,6 +177,11 @@ let expr sub {exp_extra; exp_desc; exp_env; _} = sub.expr sub exp1; sub.expr sub exp2 | Texp_array list -> List.iter (sub.expr sub) list + | Texp_dict entries -> + List.iter + (function + | Tdict_entry (_, exp) | Tdict_spread exp -> sub.expr sub exp) + entries | Texp_ifthenelse (exp1, exp2, expo) -> sub.expr sub exp1; sub.expr sub exp2; diff --git a/compiler/ml/tast_mapper.ml b/compiler/ml/tast_mapper.ml index 1e7b17bb319..fa4c07f87a6 100644 --- a/compiler/ml/tast_mapper.ml +++ b/compiler/ml/tast_mapper.ml @@ -237,6 +237,13 @@ let expr sub x = | Texp_setfield (exp1, lid, ld, exp2) -> Texp_setfield (sub.expr sub exp1, lid, ld, sub.expr sub exp2) | Texp_array list -> Texp_array (List.map (sub.expr sub) list) + | Texp_dict entries -> + Texp_dict + (List.map + (function + | Tdict_entry (key, exp) -> Tdict_entry (key, sub.expr sub exp) + | Tdict_spread exp -> Tdict_spread (sub.expr sub exp)) + entries) | Texp_ifthenelse (exp1, exp2, expo) -> Texp_ifthenelse (sub.expr sub exp1, sub.expr sub exp2, opt (sub.expr sub) expo) diff --git a/compiler/ml/translcore.ml b/compiler/ml/translcore.ml index 17670ed5ab1..92e0fa03211 100644 --- a/compiler/ml/translcore.ml +++ b/compiler/ml/translcore.ml @@ -1251,6 +1251,41 @@ and transl_exp0 (e : Typedtree.expression) : Lambda.t = | Texp_array expr_list -> let ll = transl_list expr_list in prim ~primitive:Pmakearray ~args:ll e.exp_loc + | Texp_dict entries -> ( + (* [%makedict] of the rows ([Primitive_dict.make]), and [Object.assign] + of a dict of the rows before the first spread with the spreads and the + dicts of the rows between them ([Primitive_dict.spread]) *) + let make rows = + let row ((key : string loc), value) = + let ll = [const (Const_string key.txt); transl_exp value] in + try const (Const_block (Blk_tuple, List.map extract_constant ll)) + with Not_constant -> + prim ~primitive:(Pmakeblock Blk_tuple) ~args:ll e.exp_loc + in + prim ~primitive:Pmakedict + ~args:[prim ~primitive:Pmakearray ~args:(List.map row rows) e.exp_loc] + e.exp_loc + in + let parts = + Ast_dict.group + (List.map + (function + | Tdict_entry (key, value) -> `Row (key, value) + | Tdict_spread spread -> `Spread spread) + entries) + in + match Ast_dict.target_and_sources parts with + | `Rows rows -> make rows + | `Spread (target, sources) -> + prim ~primitive:Pdict_spread + ~args: + (make target + :: List.map + (function + | Ast_dict.Rows rows -> make rows + | Spread spread -> transl_exp spread) + sources) + e.exp_loc) | Texp_ifthenelse (cond, ifso, Some ifnot) -> if_ (transl_exp cond) (transl_exp ifso) (transl_exp ifnot) | Texp_ifthenelse (cond, ifso, None) -> diff --git a/compiler/ml/typecore.ml b/compiler/ml/typecore.ml index 2297c3d0b9b..fa5ea61768e 100644 --- a/compiler/ml/typecore.ml +++ b/compiler/ml/typecore.ml @@ -228,6 +228,11 @@ let iter_expression f e = expr e; module_expr me | Pexp_pack me -> module_expr me + | Pexp_dict entries -> + List.iter + (function + | Pdict_entry (_, e) | Pdict_spread e -> expr e) + entries | Pexp_await _ -> assert false (* should be handled earlier *) | Pexp_jsx_element _ -> raise (Error (e.pexp_loc, Env.empty, Jsx_not_enabled)) @@ -2355,10 +2360,6 @@ let extract_function_name funct = let should_unify_expected_result_before_typing_lowered_apply funct sargs = match (extract_function_name funct, sargs) with - | ( Some (Longident.Ldot (Longident.Lident "Primitive_dict", "make")), - [(Asttypes.Nolabel, {Parsetree.pexp_desc = Parsetree.Pexp_array _})] ) -> - (* Dict literals *) - true | ( Some (Longident.Ldot (Longident.Lident "Primitive_promise", "unsafe_async")), [(Asttypes.Nolabel, _)] ) -> @@ -3047,6 +3048,28 @@ and type_expect_ ?deprecated_context ~context ?(recarg = Rejected) env sexp exp_attributes = sexp.pexp_attributes; exp_env = env; } + | Pexp_dict entries -> + let dict_type ty = newgenty (Tconstr (Predef.path_dict, [ty], ref Mnil)) in + let ty = newgenvar () in + unify_exp_types ~context:None loc env (dict_type ty) ty_expected; + let entries = + List.map + (function + | Pdict_entry (key, svalue) -> + Tdict_entry (key, type_expect ~context:None env svalue ty) + | Pdict_spread sspread -> + Tdict_spread (type_expect ~context:None env sspread (dict_type ty))) + entries + in + re + { + exp_desc = Texp_dict entries; + exp_loc = loc; + exp_extra = []; + exp_type = instance env ty_expected; + exp_attributes = sexp.pexp_attributes; + exp_env = env; + } | (Pexp_ifthenelse _ | Pexp_ternary _) as conditional -> ( let scond, sifso, sifnot, return_context = match conditional with diff --git a/compiler/ml/typedtree.ml b/compiler/ml/typedtree.ml index 5333777e95e..93ba73a89ed 100644 --- a/compiler/ml/typedtree.ml +++ b/compiler/ml/typedtree.ml @@ -114,6 +114,7 @@ and expression_desc = | Texp_setfield of expression * Longident.t loc * label_description * expression | Texp_array of expression list + | Texp_dict of dict_entry list | Texp_ifthenelse of expression * expression * expression option | Texp_sequence of expression * expression | Texp_break @@ -159,6 +160,10 @@ and expression_desc = and case = {c_lhs: pattern; c_guard: expression option; c_rhs: expression} +and dict_entry = + | Tdict_entry of string loc * expression + | Tdict_spread of expression + and function_param = { fp_lbl: arg_label; fp_param: Ident.t; (* the name the compiled parameter binds to *) diff --git a/compiler/ml/typedtree.mli b/compiler/ml/typedtree.mli index 7ba4f69c876..144b6c7a8eb 100644 --- a/compiler/ml/typedtree.mli +++ b/compiler/ml/typedtree.mli @@ -222,6 +222,7 @@ and expression_desc = | Texp_setfield of expression * Longident.t loc * label_description * expression | Texp_array of expression list + | Texp_dict of dict_entry list | Texp_ifthenelse of expression * expression * expression option | Texp_sequence of expression * expression | Texp_break @@ -267,6 +268,10 @@ and expression_desc = and case = {c_lhs: pattern; c_guard: expression option; c_rhs: expression} +and dict_entry = + | Tdict_entry of string loc * expression + | Tdict_spread of expression + and function_param = { fp_lbl: arg_label; fp_param: Ident.t; (* the name the compiled parameter binds to *) diff --git a/compiler/ml/typedtree_iter.ml b/compiler/ml/typedtree_iter.ml index ba9b7016b12..ba87d6b2169 100644 --- a/compiler/ml/typedtree_iter.ml +++ b/compiler/ml/typedtree_iter.ml @@ -262,6 +262,11 @@ end = struct iter_expression exp1; iter_expression exp2 | Texp_array list -> List.iter iter_expression list + | Texp_dict entries -> + List.iter + (function + | Tdict_entry (_, exp) | Tdict_spread exp -> iter_expression exp) + entries | Texp_ifthenelse (exp1, exp2, expo) -> ( iter_expression exp1; iter_expression exp2; diff --git a/compiler/syntax/src/res_ast_debugger.ml b/compiler/syntax/src/res_ast_debugger.ml index dc5bc8851ae..6cec464727f 100644 --- a/compiler/syntax/src/res_ast_debugger.ml +++ b/compiler/syntax/src/res_ast_debugger.ml @@ -695,6 +695,20 @@ module Sexp_ast = struct | Pexp_array exprs -> Sexp.list [Sexp.atom "Pexp_array"; Sexp.list (map_empty ~f:expression exprs)] + | Pexp_dict entries -> + Sexp.list + [ + Sexp.atom "Pexp_dict"; + Sexp.list + (map_empty + ~f:(function + | Parsetree.Pdict_entry (key, e) -> + Sexp.list + [Sexp.atom "Pdict_entry"; string key.txt; expression e] + | Pdict_spread e -> + Sexp.list [Sexp.atom "Pdict_spread"; expression e]) + entries); + ] | Pexp_ifthenelse (expr1, expr2, opt_expr) -> Sexp.list [ diff --git a/compiler/syntax/src/res_comments_table.ml b/compiler/syntax/src/res_comments_table.ml index 8aeef1ff32e..53822fa382b 100644 --- a/compiler/syntax/src/res_comments_table.ml +++ b/compiler/syntax/src/res_comments_table.ml @@ -1399,22 +1399,23 @@ and walk_expression expr t comments = attach t.trailing expr.pexp_loc after_expr; walk_list (cases |> List.map (fun case -> Case case)) t rest (* unary expression: todo use parsetreeviewer *) - | Pexp_apply _ - when Option.is_some - (Res_parsetree_viewer.collect_spread_dict_expr_parts expr) -> ( - match Res_parsetree_viewer.collect_spread_dict_expr_parts expr with - | Some parts -> - let part_exprs = - List.map - (function - | Res_parsetree_viewer.DictExprRows rows_expr -> - Expression rows_expr - | Res_parsetree_viewer.DictExprSpread spread_expr -> - Expression spread_expr) - parts - in - walk_list part_exprs t comments - | None -> assert false) + | Pexp_dict entries when Res_parsetree_viewer.dict_has_spread entries -> + let part_exprs = + List.map + (function + | Res_parsetree_viewer.DictExprRows rows_expr -> Expression rows_expr + | Res_parsetree_viewer.DictExprSpread spread_expr -> + Expression spread_expr) + (Res_parsetree_viewer.dict_expr_parts ~loc:expr.pexp_loc entries) + in + walk_list part_exprs t comments + | Pexp_dict entries -> + walk_list + [ + Expression + (Res_parsetree_viewer.dict_expr_rows ~loc:expr.pexp_loc entries); + ] + t comments | Pexp_apply { funct = @@ -1488,18 +1489,6 @@ and walk_expression expr t comments = walk_list [Expression parent_expr; Expression member_expr; Expression target_expr] t comments - | Pexp_apply - { - funct = - { - pexp_desc = - Pexp_ident - {txt = Longident.Ldot (Lident "Primitive_dict", "make")}; - }; - args = [(Nolabel, key_values)]; - } - when Res_parsetree_viewer.is_tuple_array key_values -> - walk_list [Expression key_values] t comments | Pexp_tagged_template {tag; values} -> walk_list (List.map (fun e -> Expression e) (tag :: values)) t comments | Pexp_template {values} -> diff --git a/compiler/syntax/src/res_core.ml b/compiler/syntax/src/res_core.ml index a57cdad12c4..1a4f88dc684 100644 --- a/compiler/syntax/src/res_core.ml +++ b/compiler/syntax/src/res_core.ml @@ -265,7 +265,6 @@ module Error_messages = struct end let spread_attr = (Location.mknoloc "res.spread", Parsetree.PStr []) -let dict_spread_attr = (Location.mknoloc "res.dictSpread", Parsetree.PStr []) (* Emit a deprecation warning when the legacy [(. ...)] uncurried syntax is encountered. Uncurried is the default since ReScript v11, so the leading @@ -3330,23 +3329,28 @@ and parse_dict_expr_part p = | DotDotDot -> Parser.next p; let spread_expr = parse_constrained_or_coerced_expr p in - Some (`Spread spread_expr) + Some (Parsetree.Pdict_spread spread_expr) | String s -> ( let loc = mk_loc (Parser.start_pos p) (Parser.end_pos p) in Parser.next p; - let field = Location.mkloc (Longident.Lident s) loc in + let key = Location.mkloc s loc in match Parser.peek p with | Colon -> Parser.next p; let field_expr = parse_expr p in - Some (`Row (field, field_expr)) + Some (Parsetree.Pdict_entry (key, field_expr)) | Equal -> Parser.err ~start_pos:(Parser.start_pos p) ~end_pos:(Parser.end_pos p) p (Diagnostics.message Error_messages.dict_field_missing_colon); Parser.next p; let field_expr = parse_expr p in - Some (`Row (field, field_expr)) - | _ -> Some (`Row (field, Ast_helper.Exp.ident ~loc:field.loc field))) + Some (Pdict_entry (key, field_expr)) + | _ -> + Some + (Pdict_entry + ( key, + Ast_helper.Exp.ident ~loc (Location.mkloc (Longident.Lident s) loc) + ))) | _ -> None and parse_record_expr_with_string_keys ~start_pos first_row p = @@ -4182,92 +4186,13 @@ and parse_list_expr ~start_pos p = [(Asttypes.Nolabel, Ast_helper.Exp.array ~loc list_exprs)] and parse_dict_expr ~start_pos p = - let parts = + let entries = parse_comma_delimited_region ~grammar:Grammar.DictRows ~closing:Rbrace ~f:parse_dict_expr_part p in let loc = mk_loc start_pos (Parser.end_pos p) in - let to_key_value_pair - (record_item : Longident.t Location.loc * Parsetree.expression) = - match record_item with - | ( {Location.txt = Longident.Lident key; loc = key_loc}, - ({pexp_loc = value_loc} as value_expr) ) -> - Some - (Ast_helper.Exp.tuple - ~loc:(mk_loc key_loc.loc_start value_loc.loc_end) - [ - Ast_helper.Exp.constant ~loc:key_loc (Ast_helper.Const.string key); - value_expr; - ]) - | _ -> None - in - let dict_rows_loc - (rows : (Longident.t Location.loc * Parsetree.expression) list) = - match (rows, List.rev rows) with - | (first_key, _) :: _, (_, last_expr) :: _ -> - mk_loc first_key.loc.loc_start last_expr.pexp_loc.loc_end - | _ -> loc - in - let make_dict_chunk ?loc_override rows = - let chunk_loc = - match loc_override with - | Some loc -> loc - | None -> dict_rows_loc rows - in - let key_value_pairs = List.filter_map to_key_value_pair rows in - Ast_helper.Exp.apply ~loc:chunk_loc - (Ast_helper.Exp.ident ~loc:chunk_loc - (Location.mkloc - (Longident.Ldot (Longident.Lident Primitive_modules.dict, "make")) - chunk_loc)) - [(Asttypes.Nolabel, Ast_helper.Exp.array ~loc:chunk_loc key_value_pairs)] - in - let make_dict_spread target_expr source_parts = - let spread_ident = - Ast_helper.Exp.ident ~loc ~attrs:[dict_spread_attr] - (Location.mkloc - (Longident.Ldot (Longident.Lident Primitive_modules.dict, "spread")) - loc) - in - Ast_helper.Exp.apply ~loc spread_ident - [ - (Asttypes.Nolabel, target_expr); - ( Asttypes.Nolabel, - Ast_helper.Exp.array ~loc - (List.map - (function - | `Rows rows -> make_dict_chunk rows - | `Spread spread_expr -> spread_expr) - source_parts) ); - ] - in - let grouped_parts = - let rec loop current_rows acc = function - | [] -> - let acc = - match current_rows with - | [] -> acc - | rows -> `Rows (List.rev rows) :: acc - in - List.rev acc - | `Row row :: rest -> loop (row :: current_rows) acc rest - | `Spread spread_expr :: rest -> - let acc = - match current_rows with - | [] -> `Spread spread_expr :: acc - | rows -> `Spread spread_expr :: `Rows (List.rev rows) :: acc - in - loop [] acc rest - in - loop [] [] parts - in Parser.expect Rbrace p; - match grouped_parts with - | [] -> make_dict_chunk ~loc_override:loc [] - | [`Rows rows] -> make_dict_chunk ~loc_override:loc rows - | `Rows target_rows :: source_parts -> - make_dict_spread (make_dict_chunk target_rows) source_parts - | source_parts -> make_dict_spread (make_dict_chunk []) source_parts + Ast_helper.Exp.dict ~loc entries and parse_array_exp p = let start_pos = Parser.start_pos p in diff --git a/compiler/syntax/src/res_parsetree_viewer.ml b/compiler/syntax/src/res_parsetree_viewer.ml index 12f22310fbd..8efb1f2461c 100644 --- a/compiler/syntax/src/res_parsetree_viewer.ml +++ b/compiler/syntax/src/res_parsetree_viewer.ml @@ -36,12 +36,6 @@ let has_dict_pattern_attribute attrs = txt = "res.dictPattern") |> Option.is_some -let has_dict_spread_attribute attrs = - attrs - |> List.find_opt (fun (({txt}, _) : Parsetree.attribute) -> - txt = "res.dictSpread") - |> Option.is_some - type dict_expr_part = | DictExprRows of Parsetree.expression | DictExprSpread of Parsetree.expression @@ -214,7 +208,7 @@ let rec unwrap_braces expr = (* Attributes the parser adds to encode syntax; they are never printed *) let is_parsing_attr (attr : Parsetree.attribute) = match attr with - | {Location.txt = "res.dictPattern" | "res.dictSpread"}, _ -> true + | {Location.txt = "res.dictPattern"}, _ -> true | _ -> false let filter_parsing_attrs attrs = @@ -561,67 +555,31 @@ let is_spread_array expr = has_spread_attr expr.pexp_attributes | _ -> false -let is_tuple_array (expr : Parsetree.expression) = - let is_plain_tuple (expr : Parsetree.expression) = - match expr with - | {pexp_desc = Pexp_tuple _} -> true - | _ -> false - in - match expr with - | {pexp_desc = Pexp_array items} -> List.for_all is_plain_tuple items - | _ -> false - -let collect_spread_dict_expr_parts expr = - let extract_literal_dict_rows (expr : Parsetree.expression) = - match expr with - | { - pexp_desc = - Pexp_apply - { - funct = - { - pexp_desc = - Pexp_ident - {txt = Longident.Ldot (Lident "Primitive_dict", "make")}; - }; - args = [(Nolabel, key_values)]; - }; - } - when is_tuple_array key_values -> - Some key_values - | _ -> None - in - let is_empty_tuple_array (expr : Parsetree.expression) = - match expr.pexp_desc with - | Pexp_array [] -> true - | _ -> false - in - match expr with - | { - pexp_desc = - Pexp_apply - { - funct = - { - pexp_desc = - Pexp_ident - {txt = Longident.Ldot (Lident "Primitive_dict", "spread")}; - pexp_attributes; - }; - args = - [(Nolabel, target_expr); (Nolabel, {pexp_desc = Pexp_array sources})]; - }; - } - when has_dict_spread_attribute pexp_attributes -> - let to_part expr = - match extract_literal_dict_rows expr with - | Some rows_expr -> - if is_empty_tuple_array rows_expr then None - else Some (DictExprRows rows_expr) - | None -> Some (DictExprSpread expr) - in - Some (List.filter_map to_part (target_expr :: sources)) - | _ -> None +let dict_has_spread entries = + List.exists + (function + | Parsetree.Pdict_spread _ -> true + | Pdict_entry _ -> false) + entries + +(* The rows of a dict literal without spreads as the array + [[("a", 1), ...]], which the printer prints, see [Ast_dict] *) +let dict_expr_rows ~loc entries = + Ast_dict.rows_array ~loc + (List.filter_map + (function + | Parsetree.Pdict_entry (key, value) -> Some (key, value) + | Pdict_spread _ -> None) + entries) + +(* The parts of a dict literal with spreads: the spreads, and such arrays for + the rows between them *) +let dict_expr_parts ~loc entries = + Ast_dict.parts entries + |> List.map (function + | Ast_dict.Rows rows -> + DictExprRows (Ast_dict.rows_array ~loc:(Ast_dict.rows_loc ~loc rows) rows) + | Spread spread -> DictExprSpread spread) (* Blue | Red | Green -> [Blue; Red; Green] *) let collect_or_pattern_chain pat = diff --git a/compiler/syntax/src/res_parsetree_viewer.mli b/compiler/syntax/src/res_parsetree_viewer.mli index 9f4e521776e..1da594f06fe 100644 --- a/compiler/syntax/src/res_parsetree_viewer.mli +++ b/compiler/syntax/src/res_parsetree_viewer.mli @@ -123,8 +123,11 @@ val is_spread_list : Parsetree.expression -> bool val is_spread_array : Parsetree.expression -> bool -val collect_spread_dict_expr_parts : - Parsetree.expression -> dict_expr_part list option +val dict_has_spread : Parsetree.dict_entry list -> bool +val dict_expr_rows : + loc:Location.t -> Parsetree.dict_entry list -> Parsetree.expression +val dict_expr_parts : + loc:Location.t -> Parsetree.dict_entry list -> dict_expr_part list val collect_or_pattern_chain : Parsetree.pattern -> Parsetree.pattern list @@ -152,8 +155,6 @@ val is_rewritten_underscore_apply_sugar : Parsetree.expression -> bool val is_fun_expr : Parsetree.expression -> bool -val is_tuple_array : Parsetree.expression -> bool - val get_jsx_prop_loc : Parsetree.jsx_prop -> Warnings.loc val container_element_closing_tag_loc : diff --git a/compiler/syntax/src/res_printer.ml b/compiler/syntax/src/res_printer.ml index 8c4d40eb8d3..a9de40118ea 100644 --- a/compiler/syntax/src/res_printer.ml +++ b/compiler/syntax/src/res_printer.ml @@ -3525,6 +3525,20 @@ and print_expression ~state (e : Parsetree.expression) cmt_tbl = else if Parsetree_viewer.is_binary_expression e then print_binary_expression ~state ~force_pipe_breaks e cmt_tbl else print_pexp_apply ~state e cmt_tbl + | Pexp_dict entries when Parsetree_viewer.dict_has_spread entries -> + print_spread_dict_expr ~state + (Parsetree_viewer.dict_expr_parts ~loc:e.pexp_loc entries) + e cmt_tbl + | Pexp_dict entries -> + Doc.concat + [ + Doc.text "dict{"; + print_comments_inside cmt_tbl e.pexp_loc; + print_literal_dict_expr ~state + (Parsetree_viewer.dict_expr_rows ~loc:e.pexp_loc entries) + cmt_tbl; + Doc.rbrace; + ] | Pexp_field (expr, longident_loc) -> let lhs = let doc = print_expression_with_comments ~state expr cmt_tbl in @@ -4435,30 +4449,6 @@ and print_pexp_apply ~state expr cmt_tbl = member; Doc.rbracket; ]) - | Pexp_apply _ - when Option.is_some - (Res_parsetree_viewer.collect_spread_dict_expr_parts expr) -> ( - match Res_parsetree_viewer.collect_spread_dict_expr_parts expr with - | Some parts -> print_spread_dict_expr ~state parts expr cmt_tbl - | None -> assert false) - | Pexp_apply - { - funct = - { - pexp_desc = - Pexp_ident - {txt = Longident.Ldot (Lident "Primitive_dict", "make")}; - }; - args = [(Nolabel, key_values)]; - } - when Res_parsetree_viewer.is_tuple_array key_values -> - Doc.concat - [ - Doc.text "dict{"; - print_comments_inside cmt_tbl expr.pexp_loc; - print_literal_dict_expr ~state key_values cmt_tbl; - Doc.rbrace; - ] | Pexp_apply { funct = diff --git a/tests/ERROR_VARIANTS.md b/tests/ERROR_VARIANTS.md index 7987b7a35f8..a386cfb3f5e 100644 --- a/tests/ERROR_VARIANTS.md +++ b/tests/ERROR_VARIANTS.md @@ -207,7 +207,7 @@ Source: `type error` in [typecore.ml](../compiler/ml/typecore.ml). | `Or_pattern_type_clash` | ✓ | `or_pattern_type_clash.res` | | | `Multiply_bound_variable` | ✓ | `multiply_bound_variable.res` | | | `Orpat_vars` | ✓ | `orpat_vars_unbalanced.res` | | -| `Expr_type_clash` | ✓ | many `*.res` | Most-fired expression error. Trace-shape sub-cases covered: `if_return_type_mismatch.res` (IfReturn), `string_concat_non_string.res` (StringConcat), `labeled_fn_argument_type_clash.res` (FunctionArgument with explicit label), `math_operator_*.res` (MathOperator family), `ternary_branch_mismatch.res`, `switch_different_types.res`, `try_catch_same_type.res`, `comparison_operator.res`, `array_item_type_mismatch.res`, `array_literal_passed_to_tuple.res`, `if_condition_mismatch.res`, `while_condition.res`, `for_loop_condition.res`, `assert_condition.res`, `function_call_mismatch.res`, `awaiting_non_promise.res`, `maybe_unwrap_option.res`, multiple `jsx_*` fixtures (including `jsx_preserve_external_function.res` for a plain-function external in a JSX component position), `object_literal_for_poly_field.res` (object literal against a polymorphic field annotation). | +| `Expr_type_clash` | ✓ | many `*.res` | Most-fired expression error. Trace-shape sub-cases covered: `if_return_type_mismatch.res` (IfReturn), `string_concat_non_string.res` (StringConcat), `labeled_fn_argument_type_clash.res` (FunctionArgument with explicit label), `math_operator_*.res` (MathOperator family), `ternary_branch_mismatch.res`, `switch_different_types.res`, `try_catch_same_type.res`, `comparison_operator.res`, `array_item_type_mismatch.res`, `array_literal_passed_to_tuple.res`, `if_condition_mismatch.res`, `while_condition.res`, `for_loop_condition.res`, `assert_condition.res`, `function_call_mismatch.res`, `awaiting_non_promise.res`, `maybe_unwrap_option.res`, multiple `jsx_*` fixtures (including `jsx_preserve_external_function.res` for a plain-function external in a JSX component position), `object_literal_for_poly_field.res` (object literal against a polymorphic field annotation), `dict_spread_type_mismatch.res` (dict spread of an incompatible dict type, located at the spread expression). | | `Apply_non_function` | ✓ | `apply_non_function.res` | | | `Apply_wrong_label` | ✓ | `apply_wrong_label.res` | | | `Label_multiply_defined` | ✓ | `label_multiply_defined_literal.res` | | diff --git a/tests/analysis_tests/tests/src/AstDict.res b/tests/analysis_tests/tests/src/AstDict.res new file mode 100644 index 00000000000..49023a218b0 --- /dev/null +++ b/tests/analysis_tests/tests/src/AstDict.res @@ -0,0 +1,4 @@ +let other = dict{"b": 2} + +let d = dict{"a": 1, ...other} +// ^ast diff --git a/tests/analysis_tests/tests/src/CompletionDictLiteral.res b/tests/analysis_tests/tests/src/CompletionDictLiteral.res new file mode 100644 index 00000000000..f1ff227e2f6 --- /dev/null +++ b/tests/analysis_tests/tests/src/CompletionDictLiteral.res @@ -0,0 +1,21 @@ +module Colors = { + let red = "red" + let green = "green" +} + +let base = dict{"a": Colors.red} + +// let x = dict{"a": Colors.} +// ^com + +// let x = dict{"a": 1, ...ba} +// ^com + +// let x = dict{...base, "b": Colors.g} +// ^com + +// let x = dict{"a": 1}-> +// ^com + +// let x = dict{"a": 1}->ge +// ^com diff --git a/tests/analysis_tests/tests/src/InlayHintDict.res b/tests/analysis_tests/tests/src/InlayHintDict.res new file mode 100644 index 00000000000..865b9156d62 --- /dev/null +++ b/tests/analysis_tests/tests/src/InlayHintDict.res @@ -0,0 +1,5 @@ +// Dict literals get an inferred-type hint +let ints = dict{"a": 1} +let spread = dict{...ints, "b": 2} + +//^hin diff --git a/tests/analysis_tests/tests/src/expected/AstDict.res.txt b/tests/analysis_tests/tests/src/expected/AstDict.res.txt new file mode 100644 index 00000000000..6a562784a41 --- /dev/null +++ b/tests/analysis_tests/tests/src/expected/AstDict.res.txt @@ -0,0 +1,16 @@ +Dump AST src/AstDict.res 2:8 + +Source: +// let d = dict{"a": 1, ...other} +// ^ast + +<*>Pstr_value( + value: + Ppat_var(d) + expr: + <*>Pexp_dict( + "a": Pexp_constant(Pconst_integer(1)) + ...Pexp_ident:other + ) +) + diff --git a/tests/analysis_tests/tests/src/expected/Completion.res.txt b/tests/analysis_tests/tests/src/expected/Completion.res.txt index d93a1cd2659..b8890fa6829 100644 --- a/tests/analysis_tests/tests/src/expected/Completion.res.txt +++ b/tests/analysis_tests/tests/src/expected/Completion.res.txt @@ -1767,6 +1767,13 @@ Path As "kind": 9, "label": "AstBraces", "tags": [] + }, + { + "data": { "modulePath": "AstDict", "filePath": "src/Completion.res" }, + "detail": "module AstDict", + "kind": 9, + "label": "AstDict", + "tags": [] } ] diff --git a/tests/analysis_tests/tests/src/expected/CompletionDictLiteral.res.txt b/tests/analysis_tests/tests/src/expected/CompletionDictLiteral.res.txt new file mode 100644 index 00000000000..d497efe5ead --- /dev/null +++ b/tests/analysis_tests/tests/src/expected/CompletionDictLiteral.res.txt @@ -0,0 +1,270 @@ +Complete src/CompletionDictLiteral.res 7:28 +pos_cursor:[7:28] pos_no_white:[7:27] Found expr:[7:11->7:29] +pos_cursor:[7:28] pos_no_white:[7:27] Found expr:[7:21->7:28] +Pexp_ident Colors.:[7:21->7:28] +Completable: Cpath Value[Colors, ""] +Package opens Stdlib.place holder Pervasives.JsxModules.place holder +Resolved opens 1 Stdlib +ContextPath Value[Colors, ""] +Path Colors. +[ + { "detail": "string", "kind": 12, "label": "red", "tags": [] }, + { "detail": "string", "kind": 12, "label": "green", "tags": [] } +] + +Complete src/CompletionDictLiteral.res 10:29 +pos_cursor:[10:29] pos_no_white:[10:28] Found expr:[10:11->10:30] +pos_cursor:[10:29] pos_no_white:[10:28] Found expr:[10:27->10:29] +Pexp_ident ba:[10:27->10:29] +Completable: Cpath Value[ba] +Package opens Stdlib.place holder Pervasives.JsxModules.place holder +Resolved opens 1 Stdlib +ContextPath Value[ba] +Path ba +[ { "detail": "dict", "kind": 12, "label": "base", "tags": [] } ] + +Complete src/CompletionDictLiteral.res 13:37 +pos_cursor:[13:37] pos_no_white:[13:36] Found expr:[13:11->13:39] +pos_cursor:[13:37] pos_no_white:[13:36] Found expr:[13:30->13:38] +Pexp_ident Colors.g:[13:30->13:38] +Completable: Cpath Value[Colors, g] +Package opens Stdlib.place holder Pervasives.JsxModules.place holder +Resolved opens 1 Stdlib +ContextPath Value[Colors, g] +Path Colors.g +[ { "detail": "string", "kind": 12, "label": "green", "tags": [] } ] + +Complete src/CompletionDictLiteral.res 16:25 +pos_cursor:[16:25] pos_no_white:[16:24] Found expr:[16:11->0:-1] +Completable: Cpath dict-> +Package opens Stdlib.place holder Pervasives.JsxModules.place holder +Resolved opens 1 Stdlib +ContextPath dict-> +ContextPath dict +Path Stdlib.Dict. +Path +[ + { + "detail": "(dict<'a>, string) => 'a", + "documentation": { + "kind": "markdown", + "value": "\n`getUnsafe(dict, key)` Returns the `value` at the provided `key`.\n\nThis is _unsafe_, meaning it will return `undefined` value if `key` does not exist in `dict`.\n\nUse `Dict.getUnsafe` only when you are sure the key exists (i.e. when iterating `Dict.keys` result).\n\n## Examples\n```rescript\nlet dict = dict{\"key1\": \"value1\", \"key2\": \"value2\"}\nlet value = dict->Dict.getUnsafe(\"key1\")\nConsole.log(value) // value1\n```\n" + }, + "kind": 12, + "label": "Dict.getUnsafe", + "tags": [] + }, + { + "detail": "dict<'a> => array<'a>", + "documentation": { + "kind": "markdown", + "value": "\n`valuesToArray(dictionary)` returns an array of all the values of the dictionary.\n\n## Examples\n```rescript\nlet dict = Dict.make()\ndict->Dict.set(\"someKey\", 1)\ndict->Dict.set(\"someKey2\", 2)\nlet values = dict->Dict.valuesToArray\nConsole.log(values) // Logs `[1, 2]` to the console\n```\n" + }, + "kind": 12, + "label": "Dict.valuesToArray", + "tags": [] + }, + { + "detail": "(dict<'a>, dict<'a>) => dict<'a>", + "documentation": { + "kind": "markdown", + "value": "\n`concat(dictionary1, dictionary2)` [shallowly](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) merges `dictionary1` and `dictionary2` into a fresh dictionary, and returns the new dictionary.\n\nNeither input dictionary is mutated. If both dictionaries contain the same key, the value from `dictionary2` overwrites the one from `dictionary1`.\n\n## Examples\n```rescript\nlet dict1 = dict{\"firstKey\": 1}\nlet dict2 = dict{\"firstKey\": 2, \"someKey\": 3}\n\nlet merged = dict1->Dict.concat(dict2)\n\ndict1 == dict{\"firstKey\": 1}\nmerged == dict{\"firstKey\": 2, \"someKey\": 3}\n(merged === dict1) == false\n```\n" + }, + "kind": 12, + "label": "Dict.concat", + "tags": [] + }, + { + "detail": "dict<'a> => array", + "documentation": { + "kind": "markdown", + "value": "\n`keysToArray(dictionary)` returns an array of all the keys of the dictionary.\n\n## Examples\n```rescript\nlet dict = Dict.make()\ndict->Dict.set(\"someKey\", 1)\ndict->Dict.set(\"someKey2\", 2)\nlet keys = dict->Dict.keysToArray\nConsole.log(keys) // Logs `[\"someKey\", \"someKey2\"]` to the console\n```\n" + }, + "kind": 12, + "label": "Dict.keysToArray", + "tags": [] + }, + { + "detail": "(dict<'a>, string) => unit", + "documentation": { + "kind": "markdown", + "value": "\n`delete(dictionary, key)` deletes the value at `key`, if it exists.\n\n## Examples\n```rescript\nlet dict = dict{\"someKey\": \"someValue\"}\n\ndict->Dict.delete(\"someKey\")\n```\n" + }, + "kind": 12, + "label": "Dict.delete", + "tags": [] + }, + { + "detail": "dict<'a> => array<(string, 'a)>", + "documentation": { + "kind": "markdown", + "value": "\n`toArray(dictionary)` returns an array of all the key/value pairs of the dictionary.\n\n## Examples\n```rescript\nlet dict = Dict.make()\ndict->Dict.set(\"someKey\", 1)\ndict->Dict.set(\"someKey2\", 2)\nlet asArray = dict->Dict.toArray\nConsole.log(asArray) // Logs `[[\"someKey\", 1], [\"someKey2\", 2]]` to the console\n```\n" + }, + "kind": 12, + "label": "Dict.toArray", + "tags": [] + }, + { + "detail": "dict<'a> => int", + "documentation": { + "kind": "markdown", + "value": "\n`size(dictionary)` returns the number of key/value pairs in the dictionary.\n\n## Examples\n```rescript\nlet dict = Dict.make()\ndict->Dict.size->assertEqual(0)\n\ndict->Dict.set(\"someKey\", 1)\ndict->Dict.set(\"someKey2\", 2)\ndict->Dict.size->assertEqual(2)\n\n// After deleting a key\ndict->Dict.delete(\"someKey\")\ndict->Dict.size->assertEqual(1)\n```\n" + }, + "kind": 12, + "label": "Dict.size", + "tags": [] + }, + { + "detail": "(dict<'a>, array>) => dict<'a>", + "documentation": { + "kind": "markdown", + "value": "\n`assignMany(target, sources)` [shallowly](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) merges each dictionary in `sources` into `target`, and returns `target`.\n\nBeware this will *mutate* `target`. Later dictionaries overwrite earlier ones. If you're looking for a fresh merged dictionary instead, check out `Dict.concatMany`.\n\n## Examples\n```rescript\nlet target = dict{\"firstKey\": 1}\nlet result = target->Dict.assignMany([\n dict{\"someKey\": 2},\n dict{\"someKey\": 3, \"someKey2\": 4},\n])\n\nresult == dict{\"firstKey\": 1, \"someKey\": 3, \"someKey2\": 4}\n(result === target) == true\n```\n" + }, + "kind": 12, + "label": "Dict.assignMany", + "tags": [] + }, + { + "detail": "(dict<'a>, array>) => dict<'a>", + "documentation": { + "kind": "markdown", + "value": "\n`concatMany(target, sources)` [shallowly](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) merges `target` and each dictionary in `sources` into a fresh dictionary, and returns the new dictionary.\n\nNeither `target` nor any dictionary in `sources` is mutated. Later dictionaries overwrite earlier ones when they contain the same key.\n\n## Examples\n```rescript\nlet target = dict{\"firstKey\": 1}\nlet merged = target->Dict.concatMany([\n dict{\"someKey\": 2},\n dict{\"someKey\": 3, \"someKey2\": 4},\n])\n\ntarget == dict{\"firstKey\": 1}\nmerged == dict{\"firstKey\": 1, \"someKey\": 3, \"someKey2\": 4}\n(merged === target) == false\n```\n" + }, + "kind": 12, + "label": "Dict.concatMany", + "tags": [] + }, + { + "detail": "(dict<'a>, ('a, string) => unit) => unit", + "documentation": { + "kind": "markdown", + "value": "\n`forEachWithKey(dictionary, f)` iterates through all values of the dict, including the key for each value.\n\n## Examples\n```rescript\nlet dict = dict{\"key1\": \"value1\", \"key2\": \"value2\"}\n\ndict->Dict.forEachWithKey((value, key) => {\n Console.log2(value, key)\n})\n```\n" + }, + "kind": 12, + "label": "Dict.forEachWithKey", + "tags": [] + }, + { + "detail": "dict<'a> => unit", + "documentation": { + "kind": "markdown", + "value": "\n `ignore(dict)` ignores the provided dict and returns unit.\n\n This helper is useful when you want to discard a value (for example, the result of an operation with side effects)\n without having to store or process it further.\n" + }, + "kind": 12, + "label": "Dict.ignore", + "tags": [] + }, + { + "detail": "(dict<'a>, string) => option<'a>", + "documentation": { + "kind": "markdown", + "value": "\nReturns the value at the provided key, if it exists. Returns an option.\n\n## Examples\n```rescript\nlet dict = dict{\"someKey\": \"someValue\"}\n\nswitch dict->Dict.get(\"someKey\") {\n| None => Console.log(\"Nope, didn't have the key.\")\n| Some(value) => Console.log(value)\n}\n```\n\n## Alternative: Pattern Matching with `dict{}`\n\nFor nested dictionary access, consider using the more concise `dict{}` pattern matching syntax:\n\n```rescript\n// More concise approach using pattern matching\nlet decodeImageUrl = (json: JSON.t) => {\n switch json {\n | JSON.Object(dict{\"data\": JSON.Object(dict{\"image_url\": JSON.String(url)})}) => Some(url)\n | _ => None\n }\n}\n\n// Alternative using Dict.get\nlet decodeImageUrl = (json: JSON.t) => {\n switch json {\n | JSON.Object(obj) =>\n switch Dict.get(obj, \"data\") {\n | Some(JSON.Object(data)) =>\n switch Dict.get(data, \"image_url\") {\n | Some(JSON.String(url)) => Some(url)\n | _ => None\n }\n | _ => None\n }\n | _ => None\n }\n}\n```\n" + }, + "kind": 12, + "label": "Dict.get", + "tags": [] + }, + { + "detail": "dict<'a> => dict<'a>", + "documentation": { + "kind": "markdown", + "value": "\n`copy(dictionary)` [shallowly copies](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) the provided dictionary to a new dictionary.\n\n## Examples\n```rescript\nlet dict = dict{\"key1\": \"value1\", \"key2\": \"value2\"}\nlet dict2 = dict->Dict.copy\n\n// Both log `[\"key1\", \"key2\"]` here.\nConsole.log2(dict->Dict.keysToArray, dict2->Dict.keysToArray)\n```\n" + }, + "kind": 12, + "label": "Dict.copy", + "tags": [] + }, + { + "detail": "(dict<'a>, dict<'a>) => dict<'a>", + "documentation": { + "kind": "markdown", + "value": "\n`assign(dictionary1, dictionary2)` [shallowly](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) merges dictionary2 into dictionary1, and returns dictionary1.\n\nBeware this will *mutate* dictionary1. If you're looking for a fresh merged dictionary instead, check out `Dict.concat`.\n\n## Examples\n```rescript\nlet dict1 = Dict.make()\ndict1->Dict.set(\"firstKey\", 1)\nConsole.log(dict1->Dict.keysToArray) // Logs `[\"firstKey\"]`\n\nlet dict2 = Dict.make()\ndict2->Dict.set(\"someKey\", 2)\ndict2->Dict.set(\"someKey2\", 3)\n\nlet dict1 = dict1->Dict.assign(dict2)\n\nConsole.log(dict1->Dict.keysToArray) // Logs `[\"firstKey\", \"someKey\", \"someKey2\"]`\n```\n" + }, + "kind": 12, + "label": "Dict.assign", + "tags": [] + }, + { + "detail": "(dict<'a>, 'a => 'b) => dict<'b>", + "documentation": { + "kind": "markdown", + "value": "\n`mapValues(dictionary, f)` returns a new dictionary with the same keys, and `f` applied to each value in the original dictionary.\n\n## Examples\n\n```rescript\nlet dict = dict{\"key1\": 1, \"key2\": 2}\n\ndict->Dict.mapValues(v => v + 10)->Dict.toArray // [(\"key1\", 11), (\"key2\", 12)]\ndict->Dict.mapValues(v => Int.toString(v))->Dict.toArray // [(\"key1\", \"1\"), (\"key2\", \"2\")]\n```\n" + }, + "kind": 12, + "label": "Dict.mapValues", + "tags": [] + }, + { + "detail": "(dict<'a>, string) => bool", + "documentation": { + "kind": "markdown", + "value": "\n`has(dictionary, \"key\")` returns true if the \"key\" is present in the dictionary.\n\nBe aware that it uses the JavaScript `in` operator under the hood.\n\n## Examples\n\n```rescript\nlet dict = dict{\"key1\": Some(1), \"key2\": None}\n\ndict->Dict.has(\"key1\") == true\ndict->Dict.has(\"key2\") == true\ndict->Dict.has(\"key3\") == false\ndict->Dict.has(\"toString\") == true\n```\n" + }, + "kind": 12, + "label": "Dict.has", + "tags": [] + }, + { + "detail": "(dict<'a>, string, 'a) => unit", + "documentation": { + "kind": "markdown", + "value": "\n`set(dictionary, key, value)` sets the value at the provided key to the provided value.\n\n## Examples\n```rescript\nlet dict = Dict.make()\n\ndict->Dict.set(\"someKey\", \"someValue\")\n```\n" + }, + "kind": 12, + "label": "Dict.set", + "tags": [] + }, + { + "detail": "(dict<'a>, 'a => unit) => unit", + "documentation": { + "kind": "markdown", + "value": "\n`forEach(dictionary, f)` iterates through all values of the dict.\n\n> Please note that this is *without the keys*, just the values. If you need the key as well, use `Dict.forEachWithKey`.\n\n## Examples\n```rescript\nlet dict = dict{\"key1\": \"value1\", \"key2\": \"value2\"}\n\ndict->Dict.forEach(value => {\n Console.log(value)\n})\n```\n" + }, + "kind": 12, + "label": "Dict.forEach", + "tags": [] + }, + { + "detail": "dict<'a> => bool", + "documentation": { + "kind": "markdown", + "value": "\n`isEmpty(dictionary)` returns `true` if the dictionary is empty (has no key/value pairs), `false` otherwise.\n\n## Examples\n```rescript\nlet emptyDict = Dict.make()\nemptyDict->Dict.isEmpty->assertEqual(true)\n\nlet dict = Dict.make()\ndict->Dict.set(\"someKey\", 1)\ndict->Dict.isEmpty->assertEqual(false)\n\n// After clearing all keys\ndict->Dict.delete(\"someKey\")\ndict->Dict.isEmpty->assertEqual(true)\n```\n" + }, + "kind": 12, + "label": "Dict.isEmpty", + "tags": [] + } +] + +Complete src/CompletionDictLiteral.res 19:27 +pos_cursor:[19:27] pos_no_white:[19:26] Found expr:[19:11->19:27] +Completable: Cpath dict->ge +Package opens Stdlib.place holder Pervasives.JsxModules.place holder +Resolved opens 1 Stdlib +ContextPath dict->ge +ContextPath dict +Path Stdlib.Dict.ge +Path ge +[ + { + "detail": "(dict<'a>, string) => 'a", + "documentation": { + "kind": "markdown", + "value": "\n`getUnsafe(dict, key)` Returns the `value` at the provided `key`.\n\nThis is _unsafe_, meaning it will return `undefined` value if `key` does not exist in `dict`.\n\nUse `Dict.getUnsafe` only when you are sure the key exists (i.e. when iterating `Dict.keys` result).\n\n## Examples\n```rescript\nlet dict = dict{\"key1\": \"value1\", \"key2\": \"value2\"}\nlet value = dict->Dict.getUnsafe(\"key1\")\nConsole.log(value) // value1\n```\n" + }, + "kind": 12, + "label": "Dict.getUnsafe", + "tags": [] + }, + { + "detail": "(dict<'a>, string) => option<'a>", + "documentation": { + "kind": "markdown", + "value": "\nReturns the value at the provided key, if it exists. Returns an option.\n\n## Examples\n```rescript\nlet dict = dict{\"someKey\": \"someValue\"}\n\nswitch dict->Dict.get(\"someKey\") {\n| None => Console.log(\"Nope, didn't have the key.\")\n| Some(value) => Console.log(value)\n}\n```\n\n## Alternative: Pattern Matching with `dict{}`\n\nFor nested dictionary access, consider using the more concise `dict{}` pattern matching syntax:\n\n```rescript\n// More concise approach using pattern matching\nlet decodeImageUrl = (json: JSON.t) => {\n switch json {\n | JSON.Object(dict{\"data\": JSON.Object(dict{\"image_url\": JSON.String(url)})}) => Some(url)\n | _ => None\n }\n}\n\n// Alternative using Dict.get\nlet decodeImageUrl = (json: JSON.t) => {\n switch json {\n | JSON.Object(obj) =>\n switch Dict.get(obj, \"data\") {\n | Some(JSON.Object(data)) =>\n switch Dict.get(data, \"image_url\") {\n | Some(JSON.String(url)) => Some(url)\n | _ => None\n }\n | _ => None\n }\n | _ => None\n }\n}\n```\n" + }, + "kind": 12, + "label": "Dict.get", + "tags": [] + } +] + diff --git a/tests/analysis_tests/tests/src/expected/InlayHintDict.res.txt b/tests/analysis_tests/tests/src/expected/InlayHintDict.res.txt new file mode 100644 index 00000000000..50a3506fc48 --- /dev/null +++ b/tests/analysis_tests/tests/src/expected/InlayHintDict.res.txt @@ -0,0 +1,18 @@ +Inlay Hint src/InlayHintDict.res 1:34 +[ + { + "kind": 1, + "label": ": dict", + "paddingLeft": true, + "paddingRight": false, + "position": { "character": 10, "line": 2 } + }, + { + "kind": 1, + "label": ": dict", + "paddingLeft": true, + "paddingRight": false, + "position": { "character": 8, "line": 1 } + } +] + diff --git a/tests/build_tests/super_errors/expected/dict_spread_type_mismatch.res.expected b/tests/build_tests/super_errors/expected/dict_spread_type_mismatch.res.expected new file mode 100644 index 00000000000..bdd46287f8c --- /dev/null +++ b/tests/build_tests/super_errors/expected/dict_spread_type_mismatch.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/dict_spread_type_mismatch.res:4:47-50 + + 2 │ + 3 │ // The error points at the spread dict + 4 │ let strings: dict = dict{"b": "x", ...ints} + 5 │ + + This has type: dict + But it's expected to have type: dict + + The incompatible parts: + int vs string + + You can convert int to string with Int.toString. \ No newline at end of file diff --git a/tests/build_tests/super_errors/fixtures/dict_spread_type_mismatch.res b/tests/build_tests/super_errors/fixtures/dict_spread_type_mismatch.res new file mode 100644 index 00000000000..d3c7fc65686 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/dict_spread_type_mismatch.res @@ -0,0 +1,4 @@ +let ints = dict{"a": 1} + +// The error points at the spread dict +let strings: dict = dict{"b": "x", ...ints} diff --git a/tests/ounit_tests/ounit_ast_mapper0_tests.ml b/tests/ounit_tests/ounit_ast_mapper0_tests.ml index 28746474ae1..307dfa8d123 100644 --- a/tests/ounit_tests/ounit_ast_mapper0_tests.ml +++ b/tests/ounit_tests/ounit_ast_mapper0_tests.ml @@ -1476,6 +1476,76 @@ let test_raw_extension_payloads_roundtrip_through_ast0 _ = (map_expr0 (map_expr_to0 expression))) ["raw"; "ffi"] +(* On the v0 wire, dict literals are the calls they used to be parsed into: + [Primitive_dict.make] without spreads, [Primitive_dict.spread] marked with + [res.dictSpread] with them. They come back as [Pexp_dict]. *) +let test_dict_literal_through_ast0 _ = + let strip_locs = + {Ast_mapper.default_mapper with location = (fun _ _ -> Location.none)} + in + let strip e = strip_locs.expr strip_locs e in + List.iter + (fun (source, wire_function) -> + let parsed = + Res_driver.parse_implementation_from_source ~display_filename:"Dict.res" + ~source:("let x = " ^ source) + in + match parsed.parsetree with + | [{pstr_desc = Pstr_value (_, [{pvb_expr = e}])}] when not parsed.invalid + -> ( + let wire = map_expr_to0 e in + (match wire.pexp_desc with + | Parsetree0.Pexp_apply + ( { + pexp_desc = + Pexp_ident + {txt = Longident.Ldot (Lident "Primitive_dict", name)}; + pexp_attributes; + }, + _ ) -> + OUnit.assert_equal ~msg:source wire_function name; + OUnit.assert_equal ~msg:source ~printer:(String.concat ", ") + (if name = "spread" then ["res.dictSpread"] else []) + (attr_names pexp_attributes) + | _ -> assert_failure ("Expected a Primitive_dict call: " ^ source)); + match map_expr0 wire with + | {pexp_desc = Pexp_dict _} as back -> + OUnit.assert_bool + (source ^ " roundtrips through ast0") + (strip back = strip e) + | _ -> assert_failure ("Expected Pexp_dict back: " ^ source)) + | _ -> assert_failure ("Expected a let binding: " ^ source)) + [ + ("dict{}", "make"); + ({|dict{"a": 1, "b": "x"}|}, "make"); + ({|dict{"a\"b": 1}|}, "make"); + ("dict{...a}", "spread"); + ({|dict{"a": 1, ...b, "c": 3, ...d}|}, "spread"); + ]; + (* A call a PPX writes, with a semantic string key *) + let make = + Ast_helper0.Exp.apply ~loc + (Ast_helper0.Exp.ident ~loc + (located_string + (Longident.Ldot (Longident.Lident "Primitive_dict", "make")))) + [ + ( Asttypes.Noloc.Nolabel, + Ast_helper0.Exp.array ~loc + [ + Ast_helper0.Exp.tuple ~loc + [ + Ast_helper0.Exp.constant ~loc + (Parsetree0.Pconst_string ("k", None)); + Ast_helper0.Exp.constant ~loc + (Parsetree0.Pconst_integer ("1", None)); + ]; + ] ); + ] + in + match (map_expr0 make).pexp_desc with + | Pexp_dict [Pdict_entry ({txt = "k"}, _)] -> () + | _ -> assert_failure "Expected a dict literal from Primitive_dict.make" + let test_removed_regexp_extension _ = List.iter (fun source -> @@ -1970,6 +2040,7 @@ let suites = >:: test_module_await_v0_attribute_order; "variant_spread_pattern_through_ast0" >:: test_variant_spread_pattern_through_ast0; + "dict_literal_through_ast0" >:: test_dict_literal_through_ast0; "inline_record_definition_roundtrips_through_ast0" >:: test_inline_record_definition_roundtrips_through_ast0; "this_on_braced_function_reaches_builtin_ppx" diff --git a/tests/syntax_tests/data/ast-mapping/DictLiterals.res b/tests/syntax_tests/data/ast-mapping/DictLiterals.res new file mode 100644 index 00000000000..466a37f3051 --- /dev/null +++ b/tests/syntax_tests/data/ast-mapping/DictLiterals.res @@ -0,0 +1,11 @@ +let empty = dict{} +let rows = dict{"a": 1, "b": x} +let punned = dict{"a"} +let spreadOnly = dict{...a} +let spreadFirst = dict{...a, "b": 2} +let rowsFirst = dict{"a": 1, ...b} +let mixed = dict{"a": 1, ...b, "c": 3, "d": 4, ...e} +let spreads = dict{...a, ...b} +let attributed = @attr dict{"a": 1} +let attributedSpread = @attr dict{"a": 1, ...b} +let nested = dict{"a": dict{"b": 1}} diff --git a/tests/syntax_tests/data/ast-mapping/expected/DictLiterals.res.txt b/tests/syntax_tests/data/ast-mapping/expected/DictLiterals.res.txt new file mode 100644 index 00000000000..73fac34ce89 --- /dev/null +++ b/tests/syntax_tests/data/ast-mapping/expected/DictLiterals.res.txt @@ -0,0 +1,11 @@ +let empty = dict{} +let rows = dict{"a": 1, "b": x} +let punned = dict{"a": a} +let spreadOnly = dict{...a} +let spreadFirst = dict{...a, "b": 2} +let rowsFirst = dict{"a": 1, ...b} +let mixed = dict{"a": 1, ...b, "c": 3, "d": 4, ...e} +let spreads = dict{...a, ...b} +let attributed = @attr dict{"a": 1} +let attributedSpread = @attr dict{"a": 1, ...b} +let nested = dict{"a": dict{"b": 1}} diff --git a/tests/syntax_tests/data/parsing/errors/other/expected/dict_spread.res.txt b/tests/syntax_tests/data/parsing/errors/other/expected/dict_spread.res.txt index bade296433f..55a3b856f00 100644 --- a/tests/syntax_tests/data/parsing/errors/other/expected/dict_spread.res.txt +++ b/tests/syntax_tests/data/parsing/errors/other/expected/dict_spread.res.txt @@ -7,6 +7,4 @@ Missing expression -let x = - ((Primitive_dict.spread)[@res.dictSpread ]) (Primitive_dict.make [||]) - [|([%rescript.exprhole ])|] \ No newline at end of file +let x = dict{...([%rescript.exprhole ])} \ No newline at end of file diff --git a/tests/syntax_tests/data/parsing/grammar/expressions/expected/dict.res.txt b/tests/syntax_tests/data/parsing/grammar/expressions/expected/dict.res.txt index 922e373c2e6..f8580ab3071 100644 --- a/tests/syntax_tests/data/parsing/grammar/expressions/expected/dict.res.txt +++ b/tests/syntax_tests/data/parsing/grammar/expressions/expected/dict.res.txt @@ -1,22 +1,10 @@ -let x = Primitive_dict.make [||] -let x = Primitive_dict.make [|({js|foo|js}, {js|bar|js})|] -let x = - Primitive_dict.make - [|({js|foo|js}, {js|bar|js});({js|bar|js}, {js|baz|js})|] +let x = dict{} +let x = dict{"foo": {js|bar|js}} +let x = dict{"foo": {js|bar|js}, "bar": {js|baz|js}} let baz = {js|foo|js} -let x = - Primitive_dict.make - [|({js|foo|js}, {js|bar|js});({js|bar|js}, {js|baz|js});({js|baz|js}, - baz)|] -let foo = Primitive_dict.make [|({js|a|js}, 1)|] -let qux = Primitive_dict.make [|({js|c|js}, 3)|] -let x = - ((Primitive_dict.spread)[@res.dictSpread ]) (Primitive_dict.make [||]) - [|foo;(Primitive_dict.make [|({js|bar|js}, 2)|]);qux|] -let x = - ((Primitive_dict.spread)[@res.dictSpread ]) - (Primitive_dict.make [|({js|before|js}, 1)|]) - [|foo;(Primitive_dict.make [|({js|after|js}, 2)|])|] -let x = - ((Primitive_dict.spread)[@res.dictSpread ]) (Primitive_dict.make [||]) - [|foo|] \ No newline at end of file +let x = dict{"foo": {js|bar|js}, "bar": {js|baz|js}, "baz": baz} +let foo = dict{"a": 1} +let qux = dict{"c": 3} +let x = dict{...foo, "bar": 2, ...qux} +let x = dict{"before": 1, ...foo, "after": 2} +let x = dict{...foo} \ No newline at end of file diff --git a/tests/syntax_tests/data/parsing/grammar/pattern/expected/dict.res.txt b/tests/syntax_tests/data/parsing/grammar/pattern/expected/dict.res.txt index f75a11eed20..5712566f74a 100644 --- a/tests/syntax_tests/data/parsing/grammar/pattern/expected/dict.res.txt +++ b/tests/syntax_tests/data/parsing/grammar/pattern/expected/dict.res.txt @@ -1,4 +1,4 @@ -let someDict = Primitive_dict.make [|({js|one|js}, {js|one|js})|] +let someDict = dict{"one": {js|one|js}} let (({ one?;_})[@res.dictPattern ]) = someDict let foo [arity:1]() = match someDict with diff --git a/tests/syntax_tests/data/printer/expr/dict.res b/tests/syntax_tests/data/printer/expr/dict.res index 3c562a41f02..47cb8c2f52a 100644 --- a/tests/syntax_tests/data/printer/expr/dict.res +++ b/tests/syntax_tests/data/printer/expr/dict.res @@ -83,3 +83,12 @@ let x = dict{ "bar": 2, ...qux /* after qux */, } + +// Attributes on a dict literal are kept +let x = @attr dict{"a": 1} +let x = @attr dict{...foo, "bar": 2} +let x = (@attr dict{"a": 1})->f + +// A dict spread into a dict stays a spread +let x = dict{...dict{"a": 1}} +let x = dict{"a": 1, ...dict{"b": 2}} diff --git a/tests/syntax_tests/data/printer/expr/expected/dict.res.txt b/tests/syntax_tests/data/printer/expr/expected/dict.res.txt index e30515371f6..0c9c8c7b6fa 100644 --- a/tests/syntax_tests/data/printer/expr/expected/dict.res.txt +++ b/tests/syntax_tests/data/printer/expr/expected/dict.res.txt @@ -82,3 +82,12 @@ let x = dict{ "bar": 2, ...qux /* after qux */, } + +// Attributes on a dict literal are kept +let x = @attr dict{"a": 1} +let x = @attr dict{...foo, "bar": 2} +let x = (@attr dict{"a": 1})->f + +// A dict spread into a dict stays a spread +let x = dict{...dict{"a": 1}} +let x = dict{"a": 1, ...dict{"b": 2}}