diff --git a/changes/inline-option-unwrap.polish.md b/changes/inline-option-unwrap.polish.md new file mode 100644 index 0000000000..33fc34833c --- /dev/null +++ b/changes/inline-option-unwrap.polish.md @@ -0,0 +1,2 @@ +- Inlined functions such as `Option.getOr` and `Option.map` no longer call + `Primitive_option.valFromOption` on an argument whose payload cannot be `undefined`. diff --git a/compiler/backend/lam_analysis.ml b/compiler/backend/lam_analysis.ml index 92145b2763..5bc8512340 100644 --- a/compiler/backend/lam_analysis.ml +++ b/compiler/backend/lam_analysis.ml @@ -47,21 +47,21 @@ let rec delay_safe ~assignable (lam : Lambda.t) : bool = ( Fld_module _ | Fld_tuple | Fld_poly_var_tag | Fld_poly_var_content | Fld_extension | Fld_variant | Fld_cons ) ) (* values and fresh blocks *) - | Ptypeof | Psome | Psome_not_nest | Pmakeblock _ | Pjs_object_create _ - | Pmakearray | Pmakelist | Pmakedict | Ptemplate _ | Pstringadd - | Pstringlength | Pstringcomp _ | Pstringorder | Pstringmin | Pstringmax - | Psequand | Psequor | Pnot | Pboolcomp _ | Pboolorder | Pboolmin | Pboolmax - | Pnegint | Paddint | Psubint | Pmulint | Ppowint | Pandint | Porint - | Pxorint | Pnotint | Plslint | Plsrint | Pasrint | Pintcomp _ | Pintorder - | Pintmin | Pintmax | Pintoffloat | Pfloatofint | Pnegfloat | Pmodfloat - | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat | Ppowfloat | Pfloatcomp _ - | Pfloatorder | Pfloatmin | Pfloatmax | Pnegbigint | Paddbigint | Psubbigint - | Pmulbigint | Pandbigint | Porbigint | Pxorbigint | Pnotbigint | Plslbigint - | Pasrbigint | Pbigintcomp _ | Pbigintorder | Pbigintmin | Pbigintmax - | Phash_mixint | Phash_mixstring | Phash_finalmix | Pis_null_undefined - | Pjscomp _ | Pnull_to_opt | Pnull_undefined_to_opt | Pis_null - | Pis_not_none | Pval_from_option | Pval_from_option_not_nest - | Pis_poly_var_block -> + | Ptypeof | Psome | Psome_not_nest | Pnot_nested_option | Pmakeblock _ + | Pjs_object_create _ | Pmakearray | Pmakelist | Pmakedict | Ptemplate _ + | Pstringadd | Pstringlength | Pstringcomp _ | Pstringorder | Pstringmin + | Pstringmax | Psequand | Psequor | Pnot | Pboolcomp _ | Pboolorder + | Pboolmin | Pboolmax | Pnegint | Paddint | Psubint | Pmulint | Ppowint + | Pandint | Porint | Pxorint | Pnotint | Plslint | Plsrint | Pasrint + | Pintcomp _ | Pintorder | Pintmin | Pintmax | Pintoffloat | Pfloatofint + | Pnegfloat | Pmodfloat | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat + | Ppowfloat | Pfloatcomp _ | Pfloatorder | Pfloatmin | Pfloatmax + | Pnegbigint | Paddbigint | Psubbigint | Pmulbigint | Pandbigint | Porbigint + | Pxorbigint | Pnotbigint | Plslbigint | Pasrbigint | Pbigintcomp _ + | Pbigintorder | Pbigintmin | Pbigintmax | Phash_mixint | Phash_mixstring + | Phash_finalmix | Pis_null_undefined | Pjscomp _ | Pnull_to_opt + | Pnull_undefined_to_opt | Pis_null | Pis_not_none | Pval_from_option + | Pval_from_option_not_nest | Pis_poly_var_block -> true (* reads of the heap, and primitives with side effects *) | Pfield (_, (Fld_record _ | Fld_record_inline _ | Fld_record_extension _)) @@ -140,7 +140,9 @@ let size_upto ~limit (lam : Lambda.t) = _; } -> add 1 - | Lprim {primitive = Praise | Pis_not_none; args = [l]; _} -> size l + | Lprim {primitive = Praise | Pis_not_none | Pnot_nested_option; args = [l]} + -> + size l | Lglobal_module _ -> add 1 | Lprim {primitive = Praw_js_code _} -> add too_big | Lprim {args = ll; _} -> diff --git a/compiler/backend/lam_beta_reduce.ml b/compiler/backend/lam_beta_reduce.ml index b155ad6831..5ef5875131 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -111,8 +111,45 @@ let effects_after args = (effects || not (Lam_analysis.no_side_effects arg), effects :: acc)) args (false, [])) +(* An argument marked [Pnot_nested_option] holds an option whose payload + cannot be [undefined], so [body] unwraps its parameter with + [Pval_from_option_not_nest], which reads the value directly, and passes + it on to other calls marked too. That holds for this call only: the + argument may be a variable whose own type differs, through [Obj.magic] or + a coercion. So [body] is rewritten and the argument passed without the + mark, so that a variable can still be substituted. *) +let unmark_arguments params (body : Lambda.t) (args : Lambda.t list) = + let marked, args = + List.fold_right2 + (fun param (arg : Lambda.t) (marked, args) -> + match arg with + | Lprim {primitive = Pnot_nested_option; args = [arg]} -> + (Set_ident.add param marked, arg :: args) + | _ -> (marked, arg :: args)) + params args (Set_ident.empty, []) + in + if Set_ident.is_empty marked then (body, args) + else + let rec unwrap (lam : Lambda.t) = + match lam with + | Lprim {primitive = Pval_from_option; args = [(Lvar param as var)]; loc} + when Set_ident.mem param marked -> + Lambda.prim ~primitive:Pval_from_option_not_nest ~args:[var] loc + | Lapply {ap_func; ap_args; ap_loc} -> + let mark (arg : Lambda.t) = + match arg with + | Lvar param when Set_ident.mem param marked -> + Lambda.prim ~primitive:Pnot_nested_option ~args:[arg] ap_loc + | _ -> unwrap arg + in + Lambda.apply (unwrap ap_func) (List.map mark ap_args) ap_loc + | _ -> Lambda_traverse.shallow_map_sharing unwrap lam + in + (unwrap body, args) + let propagate_beta_reduce (meta : Lam_stats.t) (params : Ident.t list) (body : Lambda.t) (args : Lambda.t list) = + let body, args = unmark_arguments params body args in let assignable = meta.assignable in match Lam_beta_reduce_util.simple_beta_reduce ~assignable params body args @@ -156,6 +193,7 @@ let propagate_beta_reduce (meta : Lam_stats.t) (params : Ident.t list) let propagate_beta_reduce_with_map (meta : Lam_stats.t) (map : Lam_var_stats.stats Map_ident.t) params body args = + let body, args = unmark_arguments params body args in let assignable = meta.assignable in match Lam_beta_reduce_util.simple_beta_reduce ~assignable params body args @@ -207,6 +245,7 @@ let propagate_beta_reduce_with_map (meta : Lam_stats.t) new_body rest_bindings let no_names_beta_reduce ~assignable params body args = + let body, args = unmark_arguments params body args in match Lam_beta_reduce_util.simple_beta_reduce ~assignable params body args with diff --git a/compiler/backend/lam_beta_reduce_util.ml b/compiler/backend/lam_beta_reduce_util.ml index c6d873fa48..be44483603 100644 --- a/compiler/backend/lam_beta_reduce_util.ml +++ b/compiler/backend/lam_beta_reduce_util.ml @@ -101,6 +101,15 @@ let simple_beta_reduce ~assignable params body args = let u = match u with | Lvar x -> find_param_exn ~conditional:(i >= conditional_from) x u + | Lprim {primitive = Pnot_nested_option; args = [(Lvar x as var)]; loc} + -> ( + (* The value substituted for [x] is the one [x] was bound to, so + the mark still holds for it. *) + match find_param_exn ~conditional:(i >= conditional_from) x var with + | Lprim {primitive = Pnot_nested_option} as arg -> arg + | arg -> + if arg == var then u + else Lambda.prim ~primitive:Pnot_nested_option ~args:[arg] loc) | Lconst _ -> u | _ -> raise_notrace Not_simple_apply in diff --git a/compiler/backend/lam_compile_primitive.ml b/compiler/backend/lam_compile_primitive.ml index b460ee1243..7ac5b60893 100644 --- a/compiler/backend/lam_compile_primitive.ml +++ b/compiler/backend/lam_compile_primitive.ml @@ -181,7 +181,8 @@ let translate output_prefix loc (cxt : Lam_compile_context.t) tag_info args | Pval_from_option -> Js_of_lam_option.val_from_option (Ext_list.singleton_exn args) - | Pval_from_option_not_nest -> Ext_list.singleton_exn args + | Pval_from_option_not_nest | Pnot_nested_option -> + Ext_list.singleton_exn args | Pfield (i, fld_info) -> Js_of_lam_block.field fld_info (Ext_list.singleton_exn args) diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index 0c12d7c657..c7cf549409 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -167,7 +167,9 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = && List.for_all (fun (arg : Lambda.t) -> match arg with - | Lvar p -> ( + | Lvar p + | Lprim {primitive = Pnot_nested_option; args = [Lvar p]} + -> ( match Hash_ident.find_opt meta.ident_tbl p with | Some v -> v <> Parameter | None -> true) diff --git a/compiler/typing/lambda.ml b/compiler/typing/lambda.ml index 5c289e56df..374792a006 100644 --- a/compiler/typing/lambda.ml +++ b/compiler/typing/lambda.ml @@ -145,6 +145,12 @@ type primitive = | Psome_not_nest (** [Some x] where [x] cannot itself be [undefined], so no wrapping is needed. *) + | Pnot_nested_option + (** The identity on an option whose payload cannot be [undefined], so + it is never the block that represents [Some] of undefined. The + translation of a call marks such arguments, so that the body of an + inlined function unwraps them without + [Primitive_option.valFromOption]. *) (* Operations on heap blocks *) | Pmakeblock of tag_info | Pfield of int * field_dbg_info @@ -499,10 +505,10 @@ let eq_primitive_approx (lhs : primitive) (rhs : primitive) = (* etc *) | Pval_from_option | Pval_from_option_not_nest | Pnull_to_opt | Pnull_undefined_to_opt | Pis_null | Pis_not_none | Psome | Psome_not_nest - | Pis_null_undefined | Ptypeof | Pis_poly_var_block | Pdebugger | Pinit_mod - | Pupdate_mod | Pduprecord | Pmakearray | Parraylength | Parrayrefu - | Parraysetu | Parrayrefs | Pjs_fn_method | Phash | Phash_mixstring - | Phash_mixint | Phash_finalmix | Precord_rest _ -> + | Pnot_nested_option | Pis_null_undefined | Ptypeof | Pis_poly_var_block + | Pdebugger | Pinit_mod | Pupdate_mod | Pduprecord | Pmakearray | Parraylength + | Parrayrefu | Parraysetu | Parrayrefs | Pjs_fn_method | Phash + | Phash_mixstring | Phash_mixint | Phash_finalmix | Precord_rest _ -> rhs = lhs (* Reachable only via the optimizer's term-equality comparison, which the test suite doesn't exercise for template primitives. *) @@ -721,27 +727,28 @@ let rec is_eta_conversion_exn params inner_args outer_args : t list = let may_skip_operands (primitive : primitive) = match primitive with | Psequand | Psequor -> true - | Pdebugger | Ptypeof | Psome | Psome_not_nest | Pmakeblock _ | Pfield _ - | Psetfield _ | Pduprecord | Precord_rest _ | Pjs_call _ | Pjsx _ - | Pjs_object_create _ | Pjs_object_get _ | Pjs_object_set _ | Praise - | Pobjcomp _ | Pobjorder | Pobjmin | Pobjmax | Pobjtag | Pobjsize | Pnot - | Pboolcomp _ | Pboolorder | Pboolmin | Pboolmax | Pnegint | Paddint | Psubint - | Pmulint | Pdivint | Pmodint | Ppowint | Pandint | Porint | Pxorint | Pnotint - | Plslint | Plsrint | Pasrint | Pintcomp _ | Pintorder | Pintmin | Pintmax - | Pintoffloat | Pfloatofint | Pnegfloat | Pmodfloat | Paddfloat | Psubfloat - | Pmulfloat | Pdivfloat | Ppowfloat | Pfloatcomp _ | Pfloatorder | Pfloatmin - | Pfloatmax | Pnegbigint | Paddbigint | Psubbigint | Ppowbigint | Pmulbigint - | Pdivbigint | Pmodbigint | Pandbigint | Porbigint | Pxorbigint | Pnotbigint - | Plslbigint | Pasrbigint | Pbigintcomp _ | Pbigintorder | Pbigintmin - | Pbigintmax | Pstringlength | Pstringrefu | Pstringrefs | Pstringcomp _ - | Pstringorder | Pstringmin | Pstringmax | Pstringadd | Pmakearray - | Parraylength | Parrayrefu | Parraysetu | Parrayrefs | Pmakelist | Pmakedict - | Pdict_has | Pawait | Pimport _ | Pinit_mod | Pupdate_mod | Phash - | Phash_mixint | Phash_mixstring | Phash_finalmix | Pis_null_undefined - | Pcreate_extension _ | Pjscomp _ | Pnull_to_opt | Pnull_undefined_to_opt - | Pis_null | Pis_not_none | Pval_from_option | Pval_from_option_not_nest - | Pis_poly_var_block | Praw_js_code _ | Pjs_fn_method | Ptagged_template _ - | Ptemplate _ | Pdict_spread | Parray_spread | Plist_spread -> + | Pdebugger | Ptypeof | Psome | Psome_not_nest | Pnot_nested_option + | Pmakeblock _ | Pfield _ | Psetfield _ | Pduprecord | Precord_rest _ + | Pjs_call _ | Pjsx _ | Pjs_object_create _ | Pjs_object_get _ + | Pjs_object_set _ | Praise | Pobjcomp _ | Pobjorder | Pobjmin | Pobjmax + | Pobjtag | Pobjsize | Pnot | Pboolcomp _ | Pboolorder | Pboolmin | Pboolmax + | Pnegint | Paddint | Psubint | Pmulint | Pdivint | Pmodint | Ppowint + | Pandint | Porint | Pxorint | Pnotint | Plslint | Plsrint | Pasrint + | Pintcomp _ | Pintorder | Pintmin | Pintmax | Pintoffloat | Pfloatofint + | Pnegfloat | Pmodfloat | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat + | Ppowfloat | Pfloatcomp _ | Pfloatorder | Pfloatmin | Pfloatmax | Pnegbigint + | Paddbigint | Psubbigint | Ppowbigint | Pmulbigint | Pdivbigint | Pmodbigint + | Pandbigint | Porbigint | Pxorbigint | Pnotbigint | Plslbigint | Pasrbigint + | Pbigintcomp _ | Pbigintorder | Pbigintmin | Pbigintmax | Pstringlength + | Pstringrefu | Pstringrefs | Pstringcomp _ | Pstringorder | Pstringmin + | Pstringmax | Pstringadd | Pmakearray | Parraylength | Parrayrefu + | Parraysetu | Parrayrefs | Pmakelist | Pmakedict | Pdict_has | Pawait + | Pimport _ | Pinit_mod | Pupdate_mod | Phash | Phash_mixint | Phash_mixstring + | Phash_finalmix | Pis_null_undefined | Pcreate_extension _ | Pjscomp _ + | Pnull_to_opt | Pnull_undefined_to_opt | Pis_null | Pis_not_none + | Pval_from_option | Pval_from_option_not_nest | Pis_poly_var_block + | Praw_js_code _ | Pjs_fn_method | Ptagged_template _ | Ptemplate _ + | Pdict_spread | Parray_spread | Plist_spread -> false (* Whether [primitive] on [args], the arguments of a call, evaluates them as diff --git a/compiler/typing/lambda.mli b/compiler/typing/lambda.mli index 4b5e70dd05..13a07812ae 100644 --- a/compiler/typing/lambda.mli +++ b/compiler/typing/lambda.mli @@ -145,6 +145,12 @@ type primitive = | Psome_not_nest (** [Some x] where [x] cannot itself be [undefined], so no wrapping is needed. *) + | Pnot_nested_option + (** The identity on an option whose payload cannot be [undefined], so + it is never the block that represents [Some] of undefined. The + translation of a call marks such arguments, so that the body of an + inlined function unwraps them without + [Primitive_option.valFromOption]. *) (* Operations on heap blocks *) | Pmakeblock of tag_info | Pfield of int * field_dbg_info diff --git a/compiler/typing/lambda_effects.ml b/compiler/typing/lambda_effects.ml index e8e60c9eb5..7006186a94 100644 --- a/compiler/typing/lambda_effects.ml +++ b/compiler/typing/lambda_effects.ml @@ -52,7 +52,7 @@ let rec no_side_effects (lam : Lambda.t) : bool = | [_; Lconst (Const_bigint (true, _))] -> true | _ -> false) | Pcreate_extension _ | Ptypeof | Pis_null | Pis_not_none | Psome - | Psome_not_nest | Pis_null_undefined | Pnull_to_opt + | Psome_not_nest | Pnot_nested_option | Pis_null_undefined | Pnull_to_opt | Pnull_undefined_to_opt | Pjs_object_create _ | Pimport _ (* TODO: check *) | Pmakeblock _ diff --git a/compiler/typing/printlambda.ml b/compiler/typing/printlambda.ml index 12f340fc9b..f621dcd5c6 100644 --- a/compiler/typing/printlambda.ml +++ b/compiler/typing/printlambda.ml @@ -104,6 +104,7 @@ let primitive ppf = function | Ptypeof -> fprintf ppf "typeof" | Psome -> fprintf ppf "some" | Psome_not_nest -> fprintf ppf "some_not_nest" + | Pnot_nested_option -> fprintf ppf "#not_nested_option" | Pmakeblock taginfo -> let what = if Lambda.mutable_flag_of_tag_info taginfo = Immutable then "makeblock" diff --git a/compiler/typing/translcore.ml b/compiler/typing/translcore.ml index f4741f028f..022995e706 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -1702,10 +1702,39 @@ and transl_apply ?(uncurried_partial_application = None) lam sargs loc = | _ -> (build_apply lam [] (List.map - (fun (l, x) -> (Option.map transl_exp x, Btype.is_optional l)) + (fun (l, x) -> + let optional = Btype.is_optional l in + ( Option.map + (fun e -> + if optional then transl_exp e else transl_marked_argument e) + x, + optional )) sargs) : Lambda.t) +(* An argument of type [option], where [t] cannot be [undefined], is + marked as such, so that the body of a function inlined here unwraps it + without [Primitive_option.valFromOption], as a [switch] written here + would. [Some(x)], constants and conversions from [null] are known + already, and marking them would hide what they are. *) +and transl_marked_argument (e : expression) = + let lam = transl_exp e in + match lam with + | Lconst _ + | Lprim + { + primitive = + Psome | Psome_not_nest | Pnull_to_opt | Pnull_undefined_to_opt; + } -> + lam + | _ -> ( + match (Ctype.expand_head e.exp_env e.exp_type).desc with + | Tconstr (path, [payload], _) + when Path.same path Predef.path_option + && Typeopt.type_cannot_contain_undefined payload e.exp_env -> + Lambda.prim ~primitive:Pnot_nested_option ~args:[lam] e.exp_loc + | _ -> lam) + and transl_function loc (params : function_param list) body = match params with | [] -> assert false diff --git a/tests/compiler_tests/src/flat_make_export_test.mjs b/tests/compiler_tests/src/flat_make_export_test.mjs index d780da41cc..3cedf64bfe 100644 --- a/tests/compiler_tests/src/flat_make_export_test.mjs +++ b/tests/compiler_tests/src/flat_make_export_test.mjs @@ -22,7 +22,7 @@ Mocha.describe("Flat_make_export_test", () => { Test_utils.eq("File \"flat_make_export_test.res\", line 23, characters 7-14", Flat_make_export_use.nested, "nested"); Test_utils.eq("File \"flat_make_export_test.res\", line 24, characters 7-14", Flat_make_export_use.recursive, "recursive"); Test_utils.eq("File \"flat_make_export_test.res\", line 25, characters 7-14", Flat_make_export_use.coerced, "coerced"); - Test_utils.eq("File \"flat_make_export_test.res\", line 26, characters 7-14", Flat_make_export_use.rebound !== undefined ? Primitive_option.some(Primitive_option.valFromOption(Flat_make_export_use.rebound)()) : undefined, "rebound"); + Test_utils.eq("File \"flat_make_export_test.res\", line 26, characters 7-14", Flat_make_export_use.rebound !== undefined ? Primitive_option.some(Flat_make_export_use.rebound()) : undefined, "rebound"); Test_utils.eq("File \"flat_make_export_test.res\", line 27, characters 7-14", Flat_make_export_use.applied, "applied"); Test_utils.eq("File \"flat_make_export_test.res\", line 28, characters 7-14", Flat_make_export_use.included, "one"); Test_utils.eq("File \"flat_make_export_test.res\", line 29, characters 7-14", Flat_make_export_use.aliased, "one"); diff --git a/tests/compiler_tests/src/inline_export_test.mjs b/tests/compiler_tests/src/inline_export_test.mjs index 76504a74a7..5b76b2b6a7 100644 --- a/tests/compiler_tests/src/inline_export_test.mjs +++ b/tests/compiler_tests/src/inline_export_test.mjs @@ -18,14 +18,13 @@ let mappedNested = Primitive_option.some(Primitive_option.valFromOption(nested)) function mapValue(opt) { if (opt !== undefined) { - return Primitive_option.some((x => x + 1 | 0)(Primitive_option.valFromOption(opt))); + return Primitive_option.some((x => x + 1 | 0)(opt)); } } function flatMapValue(opt) { if (opt !== undefined) { - let x = Primitive_option.valFromOption(opt); - return x + 2 | 0; + return opt + 2 | 0; } } diff --git a/tests/compiler_tests/src/inline_option_unwrap_test.mjs b/tests/compiler_tests/src/inline_option_unwrap_test.mjs new file mode 100644 index 0000000000..2f4c4afb0c --- /dev/null +++ b/tests/compiler_tests/src/inline_option_unwrap_test.mjs @@ -0,0 +1,160 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; + +function getOr(opt, $$default) { + if (opt !== undefined) { + return Primitive_option.valFromOption(opt); + } else { + return $$default; + } +} + +function intOr(opt) { + if (opt !== undefined) { + return opt; + } else { + return 0; + } +} + +function stdlibIntOr(opt) { + if (opt !== undefined) { + return opt; + } else { + return 0; + } +} + +function mapped(opt) { + if (opt !== undefined) { + return Primitive_option.some((x => x + 1 | 0)(opt)); + } +} + +function paramOr(opt, $$default) { + if (opt !== undefined) { + return opt; + } else { + return $$default; + } +} + +function paramMapOr(opt, f) { + if (opt !== undefined) { + return f(opt); + } else { + return 0; + } +} + +function wrapOr(opt, $$default) { + if (opt !== undefined) { + return Primitive_option.valFromOption(opt); + } else { + return $$default; + } +} + +function viaWrapper(opt) { + if (opt !== undefined) { + return opt; + } else { + return 0; + } +} + +function nullableInput(s) { + return [ + !(s == null) ? Primitive_option.some(s + "a") : undefined, + !(s == null) ? Primitive_option.some(s + "b") : undefined + ]; +} + +function nestedOr(opt) { + if (opt !== undefined) { + return Primitive_option.valFromOption(opt); + } else { + return 0; + } +} + +function nullableOr(opt) { + if (opt !== undefined) { + return Primitive_option.valFromOption(opt); + } else { + return 0; + } +} + +function genericOr(opt, $$default) { + if (opt !== undefined) { + return Primitive_option.valFromOption(opt); + } else { + return $$default; + } +} + +function castOnce(opt) { + let unwrapped = opt !== undefined ? opt : 0; + let inner = opt !== undefined ? Primitive_option.valFromOption(opt) : 1; + return [ + unwrapped, + inner + ]; +} + +Mocha.describe("Inline_option_unwrap_test", () => { + Mocha.test("payload that cannot be undefined", () => { + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 51, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 52, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 53, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 54, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 55, characters 7-14", mapped(2), 3); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 56, characters 7-14", mapped(undefined), undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 57, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 58, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 59, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 60, characters 7-14", 1, 1); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 61, characters 7-14", "ab".length, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 62, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 63, characters 7-14", nullableInput("x"), [ + "xa", + "xb" + ]); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 64, characters 7-14", nullableInput(null), [ + undefined, + undefined + ]); + }); + Mocha.test("payload that can be undefined", () => { + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 67, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 68, characters 7-14", 1, 1); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 69, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 70, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 71, characters 7-14", undefined, undefined); + }); + Mocha.test("cast at one call", () => { + let match = castOnce(Primitive_option.some(undefined)); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 75, characters 7-14", match[1], undefined); + }); +}); + +export { + getOr, + intOr, + stdlibIntOr, + mapped, + paramOr, + paramMapOr, + wrapOr, + viaWrapper, + nullableInput, + nestedOr, + nullableOr, + genericOr, + castOnce, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_option_unwrap_test.res b/tests/compiler_tests/src/inline_option_unwrap_test.res new file mode 100644 index 0000000000..cdd2f9b83a --- /dev/null +++ b/tests/compiler_tests/src/inline_option_unwrap_test.res @@ -0,0 +1,77 @@ +// An inlined function unwraps an option argument without +// Primitive_option.valFromOption when the argument's payload type cannot be +// undefined. +open Mocha +open Test_utils + +external magic: 'a => 'b = "%identity" + +@inline +let getOr = (opt, default) => + switch opt { + | Some(v) => v + | None => default + } + +// Unwrapped directly. +let intOr = (opt: option) => getOr(opt, 0) +let stdlibIntOr = (opt: option) => opt->Option.getOr(0) +let mapped = (opt: option) => opt->Option.map(x => x + 1) +// Another module's function, with parameters as the other arguments. +let paramOr = (opt: option, default) => opt->Option.getOr(default) +let paramMapOr = (opt: option, f) => opt->Option.mapOr(0, f) + +// A generic wrapper of getOr, inlined too. +let wrapOr = (opt, default) => getOr(opt, default) +let viaWrapper = (opt: option) => wrapOr(opt, 0) + +// A variable bound to a conversion from nullable still reads the value. +let nullableInput = (s: Nullable.t) => { + let opt = s->Nullable.toOption + (opt->Option.map(x => x ++ "a"), opt->Option.map(x => x ++ "b")) +} + +// Unwrapped with valFromOption: the payload can be undefined. +let nestedOr = (opt: option>) => getOr(opt, Some(0)) +let nullableOr = (opt: option>) => getOr(opt, Nullable.make(0)) +let genericOr = (opt: option<'a>, default) => getOr(opt, default) + +// A cast at one call says nothing about the variable elsewhere. +let castOnce = (opt: option>) => { + let unwrapped = getOr((magic(opt): option), 0) + let inner = switch opt { + | Some(inner) => inner + | None => Some(1) + } + (unwrapped, inner) +} + +describe(__MODULE__, () => { + test("payload that cannot be undefined", () => { + eq(__LOC__, intOr(Some(2)), 2) + eq(__LOC__, intOr(None), 0) + eq(__LOC__, stdlibIntOr(Some(2)), 2) + eq(__LOC__, stdlibIntOr(None), 0) + eq(__LOC__, mapped(Some(2)), Some(3)) + eq(__LOC__, mapped(None), None) + eq(__LOC__, paramOr(Some(2), 0), 2) + eq(__LOC__, viaWrapper(Some(2)), 2) + eq(__LOC__, viaWrapper(None), 0) + eq(__LOC__, paramOr(None, 1), 1) + eq(__LOC__, paramMapOr(Some("ab"), String.length), 2) + eq(__LOC__, paramMapOr(None, String.length), 0) + eq(__LOC__, nullableInput(Nullable.make("x")), (Some("xa"), Some("xb"))) + eq(__LOC__, nullableInput(Nullable.null), (None, None)) + }) + test("payload that can be undefined", () => { + eq(__LOC__, nestedOr(Some(None)), None) + eq(__LOC__, nestedOr(Some(Some(1))), Some(1)) + eq(__LOC__, nestedOr(None), Some(0)) + eq(__LOC__, nullableOr(Some(Nullable.undefined)), Nullable.undefined) + eq(__LOC__, genericOr(Some(None), Some(3)), None) + }) + test("cast at one call", () => { + let (_, inner) = castOnce(Some(None)) + eq(__LOC__, inner, None) + }) +}) diff --git a/tests/compiler_tests/src/int_overflow_test.mjs b/tests/compiler_tests/src/int_overflow_test.mjs index 667e82d1ef..f9e3b05873 100644 --- a/tests/compiler_tests/src/int_overflow_test.mjs +++ b/tests/compiler_tests/src/int_overflow_test.mjs @@ -51,11 +51,11 @@ Mocha.describe("Int_overflow_test", () => { Mocha.test("int_literal_flow2", () => Test_utils.eq("File \"int_overflow_test.res\", line 63, characters 37-44", -1, -1)); Mocha.test("float_conversion_test1", () => { let opt = Stdlib_Float.fromString("3"); - Test_utils.eq("File \"int_overflow_test.res\", line 65, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) | 0) : undefined, 3); + Test_utils.eq("File \"int_overflow_test.res\", line 65, characters 7-14", opt !== undefined ? Primitive_option.some(opt | 0) : undefined, 3); }); Mocha.test("float_conversion_test2", () => { let opt = Stdlib_Float.fromString("3.2"); - Test_utils.eq("File \"int_overflow_test.res\", line 68, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) | 0) : undefined, 3); + Test_utils.eq("File \"int_overflow_test.res\", line 68, characters 7-14", opt !== undefined ? Primitive_option.some(opt | 0) : undefined, 3); }); }); diff --git a/tests/compiler_tests/src/stdlib/Stdlib_ObjectTests.mjs b/tests/compiler_tests/src/stdlib/Stdlib_ObjectTests.mjs index 82a12bde35..c3fb13eec4 100644 --- a/tests/compiler_tests/src/stdlib/Stdlib_ObjectTests.mjs +++ b/tests/compiler_tests/src/stdlib/Stdlib_ObjectTests.mjs @@ -482,10 +482,10 @@ runGetTest({ 4, 5 ]); - let opt$1 = opt !== undefined ? Primitive_option.some(f(Primitive_option.valFromOption(opt))) : undefined; + let opt$1 = opt !== undefined ? Primitive_option.some(f(opt)) : undefined; let $$default = []; if (opt$1 !== undefined) { - return Primitive_option.valFromOption(opt$1); + return opt$1; } else { return $$default; } diff --git a/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs b/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs index 1933f5155f..2cdc4fb58d 100644 --- a/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs +++ b/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs @@ -138,7 +138,7 @@ let tmp$1 = BigInt(1); let opt = Stdlib_BigInt.fromFloat(12.0); -console.log(Primitive_bigint.div(tmp$1, opt !== undefined ? Primitive_option.valFromOption(opt) : 0n)); +console.log(Primitive_bigint.div(tmp$1, opt !== undefined ? opt : 0n)); console.info(""); diff --git a/tests/compiler_tests/src/stdlib/Stdlib_TestTests.mjs b/tests/compiler_tests/src/stdlib/Stdlib_TestTests.mjs index 67b37cff72..ee70dda8dc 100644 --- a/tests/compiler_tests/src/stdlib/Stdlib_TestTests.mjs +++ b/tests/compiler_tests/src/stdlib/Stdlib_TestTests.mjs @@ -3,7 +3,6 @@ import * as Test from "./Test.mjs"; import * as Stdlib_BigInt from "@rescript/runtime/lib/es6/Stdlib_BigInt.mjs"; import * as Primitive_object from "@rescript/runtime/lib/es6/Primitive_object.mjs"; -import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; let eq = Primitive_object.equal; @@ -13,7 +12,7 @@ let infinity = Number.POSITIVE_INFINITY; let opt = Stdlib_BigInt.fromFloat(Number.MAX_VALUE); -let bign = opt !== undefined ? Primitive_option.valFromOption(opt) : 0n; +let bign = opt !== undefined ? opt : 0n; let bign$1 = bign + bign; diff --git a/tests/compiler_tests/src/stdlib/intl/Stdlib_IntlTests.mjs b/tests/compiler_tests/src/stdlib/intl/Stdlib_IntlTests.mjs index 7945fa8b09..6b66b2d1fd 100644 --- a/tests/compiler_tests/src/stdlib/intl/Stdlib_IntlTests.mjs +++ b/tests/compiler_tests/src/stdlib/intl/Stdlib_IntlTests.mjs @@ -58,7 +58,7 @@ try { if (e$2.RE_EXN_ID === "JsExn") { let e$3 = e$2._1; let opt = Stdlib_JsExn.message(e$3); - let message = opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt).toLowerCase()) : undefined; + let message = opt !== undefined ? Primitive_option.some(opt.toLowerCase()) : undefined; if (message === "invalid key : someinvalidkey") { console.log("Caught expected error"); } else {