From a717faf3358086893a3a63132c6226101abd49da Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 1 Dec 2026 21:29:23 +0000 Subject: [PATCH 1/3] Unwrap option arguments of inlined functions directly when they can't be nested Why: An inlined function such as `Option.getOr` is compiled for any `'a`, so its body unwraps its option with `Primitive_option.valFromOption`, in case the payload is itself an option. The caller knows the payload type. A `switch` written at the call site reads the value directly when the payload can't be `undefined`; the inlined copy now does the same. The translation of a call marks each option argument whose payload type can't be `undefined` with an identity primitive, `Pnot_nested_option`. When the call is inlined, the body is rewritten for that call: unwrapping a marked parameter becomes a plain read. The marks are dropped after the last inlining pass. Lambda added (Pnot_nested_option): Example: let intOr = (opt: option) => opt->Option.getOr(0) Before (lambda): (function opt/1002 (apply (field:getOr/6 global Stdlib_Option!) opt/1002 0)) After (lambda): (function opt/1002 (apply (field:getOr/6 global Stdlib_Option!) (#not_nested_option opt/1002) 0)) JS modified (an inlined Option helper): Example: let intOr = (opt: option) => opt->Option.getOr(0) let nestedOr = (opt: option>) => opt->Option.getOr(Some(0)) Before (js): function intOr(opt) { if (opt !== undefined) { return Primitive_option.valFromOption(opt); } else { return 0; } } function nestedOr(opt) { if (opt !== undefined) { return Primitive_option.valFromOption(opt); } else { return 0; } } After (js): function intOr(opt) { if (opt !== undefined) { return opt; } else { return 0; } } function nestedOr(opt) { if (opt !== undefined) { return Primitive_option.valFromOption(opt); } else { return 0; } } Review: Why is the fact kept per call and not per variable? A variable can reach a call with a type of its own: `f((Obj.magic(y): option))` or a coercion translates to plain `y`. Recording `y` as not nested would also turn a correct `switch y` elsewhere into a plain read. So only the inlined body is rewritten, and `y` keeps `valFromOption` everywhere else. Review: What stays? `Option.map` still wraps its result with `Primitive_option.some`, since the body doesn't know the result type either. That needs a second mark, on the result, and is left for later. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- changes/inline-option-unwrap.polish.md | 2 + compiler/backend/lam_analysis.ml | 30 +++--- compiler/backend/lam_beta_reduce.ml | 33 ++++++ compiler/backend/lam_compile_main.ml | 10 ++ compiler/backend/lam_compile_primitive.ml | 3 +- compiler/typing/lambda.ml | 57 +++++----- compiler/typing/lambda.mli | 2 + compiler/typing/lambda_effects.ml | 2 +- compiler/typing/printlambda.ml | 1 + compiler/typing/translcore.ml | 32 +++++- .../src/flat_make_export_test.mjs | 2 +- .../compiler_tests/src/inline_export_test.mjs | 5 +- .../src/inline_option_unwrap_test.mjs | 102 ++++++++++++++++++ .../src/inline_option_unwrap_test.res | 56 ++++++++++ .../compiler_tests/src/int_overflow_test.mjs | 4 +- .../src/stdlib/Stdlib_ObjectTests.mjs | 4 +- .../src/stdlib/Stdlib_TempTests.mjs | 12 +-- .../src/stdlib/Stdlib_TestTests.mjs | 3 +- .../src/stdlib/intl/Stdlib_IntlTests.mjs | 2 +- 19 files changed, 302 insertions(+), 60 deletions(-) create mode 100644 changes/inline-option-unwrap.polish.md create mode 100644 tests/compiler_tests/src/inline_option_unwrap_test.mjs create mode 100644 tests/compiler_tests/src/inline_option_unwrap_test.res diff --git a/changes/inline-option-unwrap.polish.md b/changes/inline-option-unwrap.polish.md new file mode 100644 index 00000000000..33fc34833cf --- /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 92145b27639..bdee8bc76ca 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 _)) diff --git a/compiler/backend/lam_beta_reduce.ml b/compiler/backend/lam_beta_reduce.ml index b155ad68316..fb60ffbca54 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -111,8 +111,40 @@ 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 without + [Primitive_option.valFromOption]. 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 | Pval_from_option_not_nest; + args = [(Lvar param as var)]; + } + when Set_ident.mem param marked -> + var + | _ -> 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 +188,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 diff --git a/compiler/backend/lam_compile_main.ml b/compiler/backend/lam_compile_main.ml index 9bb2998f13f..0fa54a65f5f 100644 --- a/compiler/backend/lam_compile_main.ml +++ b/compiler/backend/lam_compile_main.ml @@ -238,6 +238,13 @@ let assigned_variables (group : Lam_group.t) = Set_ident.union acc (Lambda_traverse.assigned_variables lam)) Set_ident.empty bindings +(* Drops the [Pnot_nested_option] marks, once no pass looks at them. *) +let rec strip_not_nested_options (lam : Lambda.t) = + match lam with + | Lprim {primitive = Pnot_nested_option; args = [arg]} -> + strip_not_nested_options arg + | _ -> Lambda_traverse.shallow_map_sharing strip_not_nested_options lam + (* See [Lam_stats.awaited_units]. *) let awaited_units (groups : Lam_group.t list) = let units = ref Set_ident.empty in @@ -347,6 +354,9 @@ let compile ?on_optimized_lambda (output_prefix : string) lam |> d "simplify_exits 2" |> Lam_pass_remove_alias.simplify_alias meta |> d "simplify_alias 3" + (* The last pass that uses [Pnot_nested_option] is done: later passes see + the arguments without it. *) + |> strip_not_nested_options (* we should investigate a better way to put different passes : )*) |> Lam_pass_lets_dce.simplify_lets |> d "simplify_lets" |> Lam_pass_sroa.simplify |> d "sroa" diff --git a/compiler/backend/lam_compile_primitive.ml b/compiler/backend/lam_compile_primitive.ml index b460ee12438..7ac5b60893d 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/typing/lambda.ml b/compiler/typing/lambda.ml index 5c289e56dfc..374792a0068 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 4b5e70dd05f..a65d27df824 100644 --- a/compiler/typing/lambda.mli +++ b/compiler/typing/lambda.mli @@ -145,6 +145,8 @@ 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]. *) (* 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 e8e60c9eb54..7006186a94c 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 12f340fc9ba..f621dcd5c6e 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 f4741f028f8..3e5912767d9 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -1702,10 +1702,40 @@ 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 | Pnot_nested_option | 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 d780da41cc8..3cedf64bfec 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 76504a74a77..b88054bc51c 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(opt + 1 | 0); } } 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 00000000000..090755a9e3c --- /dev/null +++ b/tests/compiler_tests/src/inline_option_unwrap_test.mjs @@ -0,0 +1,102 @@ +// 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(opt + 1 | 0); + } +} + +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 38, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 39, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 40, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 41, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 42, characters 7-14", mapped(2), 3); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 43, characters 7-14", mapped(undefined), undefined); + }); + Mocha.test("payload that can be undefined", () => { + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 46, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 47, characters 7-14", 1, 1); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 48, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 49, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 50, 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 54, characters 7-14", match[1], undefined); + }); +}); + +export { + getOr, + intOr, + stdlibIntOr, + mapped, + 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 00000000000..373915dda21 --- /dev/null +++ b/tests/compiler_tests/src/inline_option_unwrap_test.res @@ -0,0 +1,56 @@ +// 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) + +// 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) + }) + 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 667e82d1ef9..f9e3b058734 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 82a12bde359..c3fb13eec49 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 1933f5155f9..24bc508b4e1 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(""); @@ -203,11 +203,13 @@ console.log(regex.test(string)); let result = regex.exec(string); -console.log(!(result == null) ? Primitive_option.some(result.input) : undefined); +let result$1 = result == null ? undefined : Primitive_option.some(result); + +console.log(!(result == null) ? Primitive_option.some(result$1.input) : undefined); -console.log(!(result == null) ? Primitive_option.some(result.index) : undefined); +console.log(!(result == null) ? Primitive_option.some(result$1.index) : undefined); -console.log(!(result == null) ? Primitive_option.some(result.slice(1)) : undefined); +console.log(!(result == null) ? Primitive_option.some(result$1.slice(1)) : undefined); console.info(""); @@ -322,8 +324,6 @@ let formatter = Stdlib_IntlTests.formatter; let segments = Stdlib_IntlTests.segments; -let result$1 = result == null ? undefined : Primitive_option.some(result); - export { _collator, collator, diff --git a/tests/compiler_tests/src/stdlib/Stdlib_TestTests.mjs b/tests/compiler_tests/src/stdlib/Stdlib_TestTests.mjs index 67b37cff720..ee70dda8dc3 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 7945fa8b097..6b66b2d1fdc 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 { From 88fa10878a3a723954ab00caa0a78a30b2256fe5 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Wed, 2 Dec 2026 06:28:49 +0000 Subject: [PATCH 2/3] Keep known option values and cross-module inlining with marked arguments Why: A review found three gaps in the first commit. Rewriting the unwrap to the bare parameter skipped the rule that reads the value a known option was built from, so `let opt = Nullable.toOption(x)` kept a wrapper variable. Each mark counted toward the inlining size, so small wrappers stopped being inlined. And calls to another module's function with a parameter as an argument are inlined only during JavaScript compilation, after the marks were gone, so `opt->Option.getOr(default)` kept `valFromOption`. Now the unwrap becomes `Pval_from_option_not_nest` for a variable bound to a known option, the size ignores the mark, the marks stay on the arguments of calls to other modules' functions, and the inlining guard treats a marked parameter like a plain one. JS modified (another module's function with a parameter argument): Example: let paramOr = (opt: option, default) => opt->Option.getOr(default) Before (js): function paramOr(opt, $$default) { if (opt !== undefined) { return Primitive_option.valFromOption(opt); } else { return $$default; } } After (js): function paramOr(opt, $$default) { if (opt !== undefined) { return opt; } else { return $$default; } } JS modified (a variable bound to a nullable conversion): Example: type r = {input: string} @send external exec: (string, string) => Nullable.t = "exec" let r1 = (s: string) => { let result = exec(s, s)->Nullable.toOption (result->Option.map(x => x.input), result->Option.map(x => x.input ++ "a")) } Before (js): function r1(s) { let result = s.exec(s); let result$1 = result == null ? undefined : Primitive_option.some(result); return [ !(result == null) ? Primitive_option.some(result$1.input) : undefined, !(result == null) ? Primitive_option.some(result$1.input + "a") : undefined ]; } After (js): function r1(s) { let result = s.exec(s); return [ !(result == null) ? Primitive_option.some(result.input) : undefined, !(result == null) ? Primitive_option.some(result.input + "a") : undefined ]; } Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- compiler/backend/lam_analysis.ml | 4 +- compiler/backend/lam_beta_reduce.ml | 44 ++++++++----- compiler/backend/lam_compile_main.ml | 26 +++++++- compiler/backend/lam_pass_remove_alias.ml | 4 +- compiler/typing/translcore.ml | 3 +- .../compiler_tests/src/inline_export_test.mjs | 2 +- .../src/inline_option_unwrap_test.mjs | 64 +++++++++++++++---- .../src/inline_option_unwrap_test.res | 15 +++++ .../src/stdlib/Stdlib_TempTests.mjs | 10 +-- 9 files changed, 130 insertions(+), 42 deletions(-) diff --git a/compiler/backend/lam_analysis.ml b/compiler/backend/lam_analysis.ml index bdee8bc76ca..5bc85123406 100644 --- a/compiler/backend/lam_analysis.ml +++ b/compiler/backend/lam_analysis.ml @@ -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 fb60ffbca54..eae7fa805b6 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -114,37 +114,49 @@ let effects_after args = (* An argument marked [Pnot_nested_option] holds an option whose payload cannot be [undefined], so [body] unwraps its parameter without [Primitive_option.valFromOption]. 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) = + 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. Unwrapping becomes a + plain read, or [Pval_from_option_not_nest] for a variable bound to a known + option ([ident_tbl]), so that [Lam_pass_remove_alias] still reads the + value it was built from. *) +let unmark_arguments (meta : Lam_stats.t) 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) + let known = + match arg with + | Lvar v -> ( + match Hash_ident.find_opt meta.ident_tbl v with + | Some (OptionalBlock _ | Normal_optional _) -> true + | _ -> false) + | _ -> false + in + (Map_ident.add param known marked, arg :: args) | _ -> (marked, arg :: args)) - params args (Set_ident.empty, []) + params args (Map_ident.empty, []) in - if Set_ident.is_empty marked then (body, args) + if Map_ident.is_empty marked then (body, args) else let rec unwrap (lam : Lambda.t) = match lam with - | Lprim - { - primitive = Pval_from_option | Pval_from_option_not_nest; - args = [(Lvar param as var)]; - } - when Set_ident.mem param marked -> - var + | Lprim {primitive = Pval_from_option; args = [(Lvar param as var)]; loc} + -> ( + match Map_ident.find_opt param marked with + | Some false -> var + | Some true -> + Lambda.prim ~primitive:Pval_from_option_not_nest ~args:[var] loc + | None -> lam) | _ -> 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 body, args = unmark_arguments meta params body args in let assignable = meta.assignable in match Lam_beta_reduce_util.simple_beta_reduce ~assignable params body args @@ -188,7 +200,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 body, args = unmark_arguments meta params body args in let assignable = meta.assignable in match Lam_beta_reduce_util.simple_beta_reduce ~assignable params body args diff --git a/compiler/backend/lam_compile_main.ml b/compiler/backend/lam_compile_main.ml index 0fa54a65f5f..f1948a5ea0f 100644 --- a/compiler/backend/lam_compile_main.ml +++ b/compiler/backend/lam_compile_main.ml @@ -238,11 +238,32 @@ let assigned_variables (group : Lam_group.t) = Set_ident.union acc (Lambda_traverse.assigned_variables lam)) Set_ident.empty bindings -(* Drops the [Pnot_nested_option] marks, once no pass looks at them. *) +(* Drops the [Pnot_nested_option] marks once the passes that inline are done, + except on the arguments of a call to another module's function: + [Lam_compile] may still inline that one. *) let rec strip_not_nested_options (lam : Lambda.t) = match lam with | Lprim {primitive = Pnot_nested_option; args = [arg]} -> strip_not_nested_options arg + | Lapply + { + ap_func = + Lprim + {primitive = Pfield (_, Fld_module _); args = [Lglobal_module _]} as + ap_func; + ap_args; + ap_loc; + } -> + let strip_inside (arg : Lambda.t) = + match arg with + | Lprim {primitive = Pnot_nested_option; args = [inner]; loc} -> + let inner' = strip_not_nested_options inner in + if inner' == inner then arg + else Lambda.prim ~primitive:Pnot_nested_option ~args:[inner'] loc + | _ -> strip_not_nested_options arg + in + let ap_args' = Ext_list.map_sharing ap_args strip_inside in + if ap_args' == ap_args then lam else Lambda.apply ap_func ap_args' ap_loc | _ -> Lambda_traverse.shallow_map_sharing strip_not_nested_options lam (* See [Lam_stats.awaited_units]. *) @@ -354,8 +375,7 @@ let compile ?on_optimized_lambda (output_prefix : string) lam |> d "simplify_exits 2" |> Lam_pass_remove_alias.simplify_alias meta |> d "simplify_alias 3" - (* The last pass that uses [Pnot_nested_option] is done: later passes see - the arguments without it. *) + (* The passes that inline are done. *) |> strip_not_nested_options (* we should investigate a better way to put different passes : )*) |> Lam_pass_lets_dce.simplify_lets diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index 0c12d7c657a..c7cf549409b 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/translcore.ml b/compiler/typing/translcore.ml index 3e5912767d9..022995e7060 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -1724,8 +1724,7 @@ and transl_marked_argument (e : expression) = | Lprim { primitive = - ( Psome | Psome_not_nest | Pnot_nested_option | Pnull_to_opt - | Pnull_undefined_to_opt ); + Psome | Psome_not_nest | Pnull_to_opt | Pnull_undefined_to_opt; } -> lam | _ -> ( diff --git a/tests/compiler_tests/src/inline_export_test.mjs b/tests/compiler_tests/src/inline_export_test.mjs index b88054bc51c..5b76b2b6a7f 100644 --- a/tests/compiler_tests/src/inline_export_test.mjs +++ b/tests/compiler_tests/src/inline_export_test.mjs @@ -18,7 +18,7 @@ let mappedNested = Primitive_option.some(Primitive_option.valFromOption(nested)) function mapValue(opt) { if (opt !== undefined) { - return Primitive_option.some(opt + 1 | 0); + return Primitive_option.some((x => x + 1 | 0)(opt)); } } diff --git a/tests/compiler_tests/src/inline_option_unwrap_test.mjs b/tests/compiler_tests/src/inline_option_unwrap_test.mjs index 090755a9e3c..42da20dfdc9 100644 --- a/tests/compiler_tests/src/inline_option_unwrap_test.mjs +++ b/tests/compiler_tests/src/inline_option_unwrap_test.mjs @@ -30,10 +30,33 @@ function stdlibIntOr(opt) { function mapped(opt) { if (opt !== undefined) { - return Primitive_option.some(opt + 1 | 0); + 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 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); @@ -69,23 +92,35 @@ function castOnce(opt) { Mocha.describe("Inline_option_unwrap_test", () => { Mocha.test("payload that cannot be undefined", () => { - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 38, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 39, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 40, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 41, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 42, characters 7-14", mapped(2), 3); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 43, characters 7-14", mapped(undefined), undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 47, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 48, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 49, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 50, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 51, characters 7-14", mapped(2), 3); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 52, characters 7-14", mapped(undefined), undefined); + 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", 1, 1); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 55, characters 7-14", "ab".length, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 56, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 57, characters 7-14", nullableInput("x"), [ + "xa", + "xb" + ]); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 58, characters 7-14", nullableInput(null), [ + undefined, + undefined + ]); }); Mocha.test("payload that can be undefined", () => { - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 46, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 47, characters 7-14", 1, 1); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 48, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 49, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 50, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 61, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 62, characters 7-14", 1, 1); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 63, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 64, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 65, 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 54, characters 7-14", match[1], undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 69, characters 7-14", match[1], undefined); }); }); @@ -94,6 +129,9 @@ export { intOr, stdlibIntOr, mapped, + paramOr, + paramMapOr, + nullableInput, nestedOr, nullableOr, genericOr, diff --git a/tests/compiler_tests/src/inline_option_unwrap_test.res b/tests/compiler_tests/src/inline_option_unwrap_test.res index 373915dda21..d132de5d266 100644 --- a/tests/compiler_tests/src/inline_option_unwrap_test.res +++ b/tests/compiler_tests/src/inline_option_unwrap_test.res @@ -17,6 +17,15 @@ let getOr = (opt, default) => 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 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)) @@ -41,6 +50,12 @@ describe(__MODULE__, () => { 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__, 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) diff --git a/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs b/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs index 24bc508b4e1..2cdc4fb58d9 100644 --- a/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs +++ b/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs @@ -203,13 +203,11 @@ console.log(regex.test(string)); let result = regex.exec(string); -let result$1 = result == null ? undefined : Primitive_option.some(result); - -console.log(!(result == null) ? Primitive_option.some(result$1.input) : undefined); +console.log(!(result == null) ? Primitive_option.some(result.input) : undefined); -console.log(!(result == null) ? Primitive_option.some(result$1.index) : undefined); +console.log(!(result == null) ? Primitive_option.some(result.index) : undefined); -console.log(!(result == null) ? Primitive_option.some(result$1.slice(1)) : undefined); +console.log(!(result == null) ? Primitive_option.some(result.slice(1)) : undefined); console.info(""); @@ -324,6 +322,8 @@ let formatter = Stdlib_IntlTests.formatter; let segments = Stdlib_IntlTests.segments; +let result$1 = result == null ? undefined : Primitive_option.some(result); + export { _collator, collator, From ae67fffd50b35a4ccf938c77d76bcbda812851fa Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Wed, 2 Dec 2026 07:36:24 +0000 Subject: [PATCH 3/3] Keep option marks to the end and pass them through forwarding calls Why: A second review found a simpler design and a regression. The marks no longer need removing: a mark compiles to nothing, and the passes after inlining don't look at the shape of call arguments. So the strip pass goes, and the unwrap always becomes `Pval_from_option_not_nest`, which the alias pass still resolves for a variable bound to a known option. The regression: `simple_beta_reduce` refused a body whose call arguments were marked, so a small forwarding wrapper got temporaries for its arguments. It now substitutes through a mark. And an inlined body that passes a marked parameter on to another call marks it there too, so a generic wrapper of `getOr` reads the value directly as well. JS modified (a forwarding wrapper): Example: @val external h: unit => option = "h" @val external k: unit => int = "k" let w2 = (f, o: option, d: int): int => f(o, d) let useW2 = f => w2(f, h(), k()) Before (js): function useW2(f) { let o = h(); let d = k(); return f(o, d); } After (js): function useW2(f) { return f(h(), k()); } JS modified (a generic wrapper): Example: @inline let getOr = (opt, default) => switch opt { | Some(v) => v | None => default } let wrapOr = (opt, default) => getOr(opt, default) let viaWrapper = (opt: option) => wrapOr(opt, 0) Before (js): function viaWrapper(opt) { if (opt !== undefined) { return Primitive_option.valFromOption(opt); } else { return 0; } } After (js): function viaWrapper(opt) { if (opt !== undefined) { return opt; } else { return 0; } } Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- compiler/backend/lam_beta_reduce.ml | 48 ++++++++--------- compiler/backend/lam_beta_reduce_util.ml | 9 ++++ compiler/backend/lam_compile_main.ml | 30 ----------- compiler/typing/lambda.mli | 6 ++- .../src/inline_option_unwrap_test.mjs | 54 +++++++++++++------ .../src/inline_option_unwrap_test.res | 6 +++ 6 files changed, 78 insertions(+), 75 deletions(-) diff --git a/compiler/backend/lam_beta_reduce.ml b/compiler/backend/lam_beta_reduce.ml index eae7fa805b6..5ef58751310 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -112,51 +112,44 @@ let effects_after args = args (false, [])) (* An argument marked [Pnot_nested_option] holds an option whose payload - cannot be [undefined], so [body] unwraps its parameter without - [Primitive_option.valFromOption]. That holds for this call only: the + 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. Unwrapping becomes a - plain read, or [Pval_from_option_not_nest] for a variable bound to a known - option ([ident_tbl]), so that [Lam_pass_remove_alias] still reads the - value it was built from. *) -let unmark_arguments (meta : Lam_stats.t) params (body : Lambda.t) - (args : Lambda.t list) = + 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]} -> - let known = - match arg with - | Lvar v -> ( - match Hash_ident.find_opt meta.ident_tbl v with - | Some (OptionalBlock _ | Normal_optional _) -> true - | _ -> false) - | _ -> false - in - (Map_ident.add param known marked, arg :: args) + (Set_ident.add param marked, arg :: args) | _ -> (marked, arg :: args)) - params args (Map_ident.empty, []) + params args (Set_ident.empty, []) in - if Map_ident.is_empty marked then (body, args) + 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} - -> ( - match Map_ident.find_opt param marked with - | Some false -> var - | Some true -> - Lambda.prim ~primitive:Pval_from_option_not_nest ~args:[var] loc - | None -> lam) + 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 meta params body args in + 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 @@ -200,7 +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 meta params body args in + 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 @@ -252,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 c6d873fa48e..be44483603a 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_main.ml b/compiler/backend/lam_compile_main.ml index f1948a5ea0f..9bb2998f13f 100644 --- a/compiler/backend/lam_compile_main.ml +++ b/compiler/backend/lam_compile_main.ml @@ -238,34 +238,6 @@ let assigned_variables (group : Lam_group.t) = Set_ident.union acc (Lambda_traverse.assigned_variables lam)) Set_ident.empty bindings -(* Drops the [Pnot_nested_option] marks once the passes that inline are done, - except on the arguments of a call to another module's function: - [Lam_compile] may still inline that one. *) -let rec strip_not_nested_options (lam : Lambda.t) = - match lam with - | Lprim {primitive = Pnot_nested_option; args = [arg]} -> - strip_not_nested_options arg - | Lapply - { - ap_func = - Lprim - {primitive = Pfield (_, Fld_module _); args = [Lglobal_module _]} as - ap_func; - ap_args; - ap_loc; - } -> - let strip_inside (arg : Lambda.t) = - match arg with - | Lprim {primitive = Pnot_nested_option; args = [inner]; loc} -> - let inner' = strip_not_nested_options inner in - if inner' == inner then arg - else Lambda.prim ~primitive:Pnot_nested_option ~args:[inner'] loc - | _ -> strip_not_nested_options arg - in - let ap_args' = Ext_list.map_sharing ap_args strip_inside in - if ap_args' == ap_args then lam else Lambda.apply ap_func ap_args' ap_loc - | _ -> Lambda_traverse.shallow_map_sharing strip_not_nested_options lam - (* See [Lam_stats.awaited_units]. *) let awaited_units (groups : Lam_group.t list) = let units = ref Set_ident.empty in @@ -375,8 +347,6 @@ let compile ?on_optimized_lambda (output_prefix : string) lam |> d "simplify_exits 2" |> Lam_pass_remove_alias.simplify_alias meta |> d "simplify_alias 3" - (* The passes that inline are done. *) - |> strip_not_nested_options (* we should investigate a better way to put different passes : )*) |> Lam_pass_lets_dce.simplify_lets |> d "simplify_lets" |> Lam_pass_sroa.simplify |> d "sroa" diff --git a/compiler/typing/lambda.mli b/compiler/typing/lambda.mli index a65d27df824..13a07812ae0 100644 --- a/compiler/typing/lambda.mli +++ b/compiler/typing/lambda.mli @@ -146,7 +146,11 @@ type primitive = (** [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]. *) + (** 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/tests/compiler_tests/src/inline_option_unwrap_test.mjs b/tests/compiler_tests/src/inline_option_unwrap_test.mjs index 42da20dfdc9..2f4c4afb0ce 100644 --- a/tests/compiler_tests/src/inline_option_unwrap_test.mjs +++ b/tests/compiler_tests/src/inline_option_unwrap_test.mjs @@ -50,6 +50,22 @@ function paramMapOr(opt, f) { } } +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, @@ -92,35 +108,37 @@ function castOnce(opt) { Mocha.describe("Inline_option_unwrap_test", () => { Mocha.test("payload that cannot be undefined", () => { - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 47, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 48, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 49, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 50, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 51, characters 7-14", mapped(2), 3); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 52, characters 7-14", mapped(undefined), 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", 1, 1); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 55, characters 7-14", "ab".length, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 56, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 57, characters 7-14", nullableInput("x"), [ + 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 58, characters 7-14", nullableInput(null), [ + 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 61, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 62, characters 7-14", 1, 1); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 63, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 64, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 65, characters 7-14", undefined, 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 69, characters 7-14", match[1], undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 75, characters 7-14", match[1], undefined); }); }); @@ -131,6 +149,8 @@ export { mapped, paramOr, paramMapOr, + wrapOr, + viaWrapper, nullableInput, nestedOr, nullableOr, diff --git a/tests/compiler_tests/src/inline_option_unwrap_test.res b/tests/compiler_tests/src/inline_option_unwrap_test.res index d132de5d266..cdd2f9b83a2 100644 --- a/tests/compiler_tests/src/inline_option_unwrap_test.res +++ b/tests/compiler_tests/src/inline_option_unwrap_test.res @@ -21,6 +21,10 @@ let mapped = (opt: option) => opt->Option.map(x => x + 1) 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 @@ -51,6 +55,8 @@ describe(__MODULE__, () => { 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)