diff --git a/changes/inline-option-result.polish.md b/changes/inline-option-result.polish.md new file mode 100644 index 0000000000..e830aa9eac --- /dev/null +++ b/changes/inline-option-result.polish.md @@ -0,0 +1 @@ +- Return the result of an inlined function such as `Option.map` without `Primitive_option.some` when the caller's type says the payload cannot be `undefined`; a cast or external inside the inlined function, or a cast of the function itself at the call site, that hides an `undefined` payload, as in `Some(a->Array.getUnsafe(5))`, now behaves as the same `Some` written at the call site. diff --git a/compiler/backend/lam_beta_reduce.ml b/compiler/backend/lam_beta_reduce.ml index dea66b1261..34238a4fd8 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -135,7 +135,7 @@ let unmark_arguments params (body : Lambda.t) (args : Lambda.t list) = | 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} -> + | Lapply {ap_func; ap_args; ap_loc; ap_result_not_nested} -> let mark (arg : Lambda.t) = match arg with | Lvar param when Set_ident.mem param marked -> @@ -145,14 +145,94 @@ let unmark_arguments params (body : Lambda.t) (args : Lambda.t list) = let ap_func' = unwrap ap_func in let ap_args' = Ext_list.map_sharing ap_args mark in if ap_func' == ap_func && ap_args' == ap_args then lam - else Lambda.apply ap_func' ap_args' ap_loc + else + Lambda.apply ~result_not_nested:ap_result_not_nested ap_func' 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 +(* [body] is the body of a function inlined at a call whose own type is an + option whose payload cannot be [undefined] ([ap_result_not_nested]). So a + [Some(v)] the body returns needs no wrapping, and a call it returns gets + the same mark, so that it can be inlined the same way. Only the code in + return position is rewritten: a [Some] bound to a variable first is left + as it is. The entry points below run this before the arguments are + substituted, so that only the body's own [Some]s and calls are + rewritten, not an argument that ends up in return position. *) +let rec mark_result (body : Lambda.t) : Lambda.t = + match body with + | Lprim {primitive = Psome; args = [v]; loc} -> + Lambda.prim ~primitive:Psome_not_nest ~args:[v] loc + | Lapply {ap_func; ap_args; ap_loc; ap_result_not_nested = false} -> + (* Every call is built by [Lambda.apply], whose shortcuts depend on the + function and arguments only, so they leave this one a call *) + Lambda.apply ~result_not_nested:true ap_func ap_args ap_loc + | Llet (kind, id, arg, rest) -> + let rest' = mark_result rest in + if rest' == rest then body else Lambda.let_ kind id arg rest' + | Lletrec (bindings, rest) -> + let rest' = mark_result rest in + if rest' == rest then body else Lambda.letrec bindings rest' + | Lsequence (first, rest) -> + let rest' = mark_result rest in + if rest' == rest then body else Lambda.seq first rest' + | Lifthenelse (cond, then_, else_) -> + let then' = mark_result then_ and else' = mark_result else_ in + if then' == then_ && else' == else_ then body + else Lambda.if_ cond then' else' + | Lswitch (arg, sw) -> + let consts = Ext_list.map_snd_sharing sw.sw_consts mark_result in + let blocks = Ext_list.map_snd_sharing sw.sw_blocks mark_result in + let fail = mark_option sw.sw_failaction in + if + consts == sw.sw_consts && blocks == sw.sw_blocks + && fail == sw.sw_failaction + then body + else + Lambda.switch arg + {sw with sw_consts = consts; sw_blocks = blocks; sw_failaction = fail} + | Lstringswitch (arg, cases, default) -> + let cases' = Ext_list.map_snd_sharing cases mark_result in + let default' = mark_option default in + if cases' == cases && default' == default then body + else Lambda.stringswitch arg cases' default' + | Lstaticcatch (rest, handler_id, handler) -> + let rest' = mark_result rest and handler' = mark_result handler in + if rest' == rest && handler' == handler then body + else Lambda.staticcatch rest' handler_id handler' + | Ltrywith (rest, id, handler) -> + let rest' = mark_result rest and handler' = mark_result handler in + if rest' == rest && handler' == handler then body + else Lambda.try_ rest' id handler' + | Ltryfinally (rest, finally) -> + let rest' = mark_result rest in + if rest' == rest then body else Lambda.try_finally rest' finally + (* Already marked, or not a result this body builds: a variable is a + parameter or bound before, a primitive such as an argument mark only + passes on a value, and a function's body returns from that function *) + | Lapply {ap_result_not_nested = true} + | Lprim _ | Lvar _ | Lglobal_module _ | Lconst _ | Lfunction _ + | Lstaticraise _ | Lwhile _ | Lfor _ | Lfor_of _ | Lfor_await_of _ | Lassign _ + | Lbreak | Lcontinue -> + body + +and mark_option (lam : Lambda.t option) = + match lam with + | None -> lam + | Some l -> + let l' = mark_result l in + if l' == l then lam else Some l' + +(* The body of a function inlined at a call: [result_not_nested] is the + call's own mark ([ap_result_not_nested]) *) +let inlined_body ~result_not_nested params body args = + let body = if result_not_nested then mark_result body else body in + unmark_arguments params body args + +let propagate_beta_reduce ~result_not_nested (meta : Lam_stats.t) + (params : Ident.t list) (body : Lambda.t) (args : Lambda.t list) = + let body, args = inlined_body ~result_not_nested params body args in let assignable = meta.assignable in match Lam_beta_reduce_util.simple_beta_reduce ~assignable params body args @@ -195,9 +275,9 @@ let propagate_beta_reduce (meta : Lam_stats.t) (params : Ident.t list) Lam_util.refine_let ~assignable ~kind:Strict param arg l) new_body rest_bindings -let propagate_beta_reduce_with_map (meta : Lam_stats.t) +let propagate_beta_reduce_with_map ~result_not_nested (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 = inlined_body ~result_not_nested 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_beta_reduce.mli b/compiler/backend/lam_beta_reduce.mli index 33568782da..324237cd76 100644 --- a/compiler/backend/lam_beta_reduce.mli +++ b/compiler/backend/lam_beta_reduce.mli @@ -49,9 +49,20 @@ val no_names_beta_reduce : *) val propagate_beta_reduce : - Lam_stats.t -> Ident.t list -> Lambda.t -> Lambda.t list -> Lambda.t + result_not_nested:bool -> + Lam_stats.t -> + Ident.t list -> + Lambda.t -> + Lambda.t list -> + Lambda.t +(** [result_not_nested] is the inlined call's [ap_result_not_nested]. When it + is set, a [Some] the body returns no longer wraps its payload, and a call + it returns gets the same mark; the body is rewritten for that before the + arguments are substituted. The same holds for + [propagate_beta_reduce_with_map]. *) val propagate_beta_reduce_with_map : + result_not_nested:bool -> Lam_stats.t -> Lam_var_stats.stats Map_ident.t -> Ident.t list -> diff --git a/compiler/backend/lam_beta_reduce_util.ml b/compiler/backend/lam_beta_reduce_util.ml index 95fbb25c95..de64519a68 100644 --- a/compiler/backend/lam_beta_reduce_util.ml +++ b/compiler/backend/lam_beta_reduce_util.ml @@ -171,6 +171,7 @@ let simple_beta_reduce ~assignable params body args = f; ap_args; ap_loc; + ap_result_not_nested = result_not_nested; } -> ( add_params (); (*since we adde each param only once, @@ -188,7 +189,8 @@ let simple_beta_reduce ~assignable params body args = let new_args = aux_exn ~conditional_from:max_int 0 ap_args in check_order_exn (); let result = - seq_unused param_hash params (Lambda.apply f new_args ap_loc) + seq_unused param_hash params + (Lambda.apply ~result_not_nested f new_args ap_loc) in Some result with Not_simple_apply -> None) diff --git a/compiler/backend/lam_bounded_vars.ml b/compiler/backend/lam_bounded_vars.ml index 995a2ed5f8..f2294396e6 100644 --- a/compiler/backend/lam_bounded_vars.ml +++ b/compiler/backend/lam_bounded_vars.ml @@ -138,10 +138,10 @@ let rewrite (map : _ Hash_ident.t) (lam : Lambda.t) : Lambda.t = (* here it makes sure that global vars are not rebound *) Lambda.prim ~primitive ~args:(List.map aux args) loc | Lglobal_module _ -> lam - | Lapply {ap_func; ap_args; ap_loc} -> + | Lapply {ap_func; ap_args; ap_loc; ap_result_not_nested} -> let fn = aux ap_func in let args = List.map aux ap_args in - Lambda.apply fn args ap_loc + Lambda.apply ~result_not_nested:ap_result_not_nested fn args ap_loc | Lswitch ( l, { diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index 08e9c75aa0..95c0f24bb8 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -157,6 +157,7 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = } as l1; ap_args = args; ap_loc; + ap_result_not_nested; } -> ( match Lam_compile_env.query_external_id_info ident fld_name with | { @@ -173,25 +174,32 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = in simpl (record_assigned - (Lam_beta_reduce.propagate_beta_reduce_with_map (current_meta ()) + (Lam_beta_reduce.propagate_beta_reduce_with_map + ~result_not_nested:ap_result_not_nested (current_meta ()) param_map params body args)) | _ -> let fn = simpl l1 in let args' = Ext_list.map_sharing args simpl in - if fn == l1 && args' == args then lam else Lambda.apply fn args' ap_loc) + if fn == l1 && args' == args then lam + else + Lambda.apply ~result_not_nested:ap_result_not_nested fn args' ap_loc) (* Function inlining interact with other optimizations... - parameter attributes - scope issues - code bloat *) - | Lapply {ap_func = Lvar v as fn; ap_args = args; ap_loc} -> ( + | Lapply + {ap_func = Lvar v as fn; ap_args = args; ap_loc; ap_result_not_nested} + -> ( (* Check info for always inlining *) let ap_args = Ext_list.map_sharing args simpl in let[@local] normal () = let fn' = simpl fn in if fn' == fn && ap_args == args then lam - else Lambda.apply fn' ap_args ap_loc + else + Lambda.apply ~result_not_nested:ap_result_not_nested fn' ap_args + ap_loc in match Hash_ident.find_opt meta.ident_tbl v with | Some @@ -214,8 +222,9 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = (* Ir_log.dwarn __LOC__ "beta .. %s/%d" v.name v.stamp ; *) simpl (record_assigned - (Lam_beta_reduce.propagate_beta_reduce (current_meta ()) params - body ap_args)) + (Lam_beta_reduce.propagate_beta_reduce + ~result_not_nested:ap_result_not_nested (current_meta ()) + params body ap_args)) else if Lam_analysis.ok_to_inline_fun_when_app m ap_args then let param_map = Lam_closure.is_closed_with_map meta.export_idents params body @@ -227,7 +236,8 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = | Lam_rec -> record_assigned (Lam_beta_reduce.propagate_beta_reduce_with_map - (current_meta ()) param_map params body ap_args) + ~result_not_nested:ap_result_not_nested (current_meta ()) + param_map params body ap_args) | Lam_self_rec -> normal () | Lam_non_rec -> if @@ -244,6 +254,7 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = simpl (record_assigned (Lam_beta_reduce.propagate_beta_reduce_with_map + ~result_not_nested:ap_result_not_nested (current_meta ()) param_map params body ap_args)) in decr inline_depth; @@ -253,7 +264,11 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = else normal () | Some _ | None -> normal ()) | Lapply - {ap_func = Lfunction ({params; body} as lfunction); ap_args = args; _} + { + ap_func = Lfunction ({params; body} as lfunction); + ap_args = args; + ap_result_not_nested; + } when List.compare_lengths params args = 0 && Lambda.lfunction_can_be_inlined lfunction -> let _, param_map = @@ -261,7 +276,8 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = in simpl (record_assigned - (Lam_beta_reduce.propagate_beta_reduce_with_map (current_meta ()) + (Lam_beta_reduce.propagate_beta_reduce_with_map + ~result_not_nested:ap_result_not_nested (current_meta ()) param_map params body args)) | Lstringswitch (l, sw, d) -> ( let known_constant = diff --git a/compiler/backend/lam_util.ml b/compiler/backend/lam_util.ml index 8589f9939b..e29663f4d4 100644 --- a/compiler/backend/lam_util.ml +++ b/compiler/backend/lam_util.ml @@ -127,7 +127,9 @@ let refine_let ?original ~assignable ~kind param (arg : Lambda.t) (l : Lambda.t) before its argument, which is to read the function, so evaluation order and side effects stay the same. *) Lambda.prim ~primitive ~args:[arg] loc - | _, _, Lapply {ap_func = fn; ap_args = [Lvar w]; ap_loc} + | ( _, + _, + Lapply {ap_func = fn; ap_args = [Lvar w]; ap_loc; ap_result_not_nested} ) when Ident.same w param && (not (Lam_hit.hit_variable param fn)) && may_follow (Lam_analysis.motion ~assignable fn) -> @@ -135,7 +137,7 @@ let refine_let ?original ~assignable ~kind param (arg : Lambda.t) (l : Lambda.t) rewrite to `someFn(value)` as long as the callee does not capture `x` and `value` may run after it: not `{ let x = c.n; next()(x) }`, where `next()` may assign `c.n`. *) - Lambda.apply fn [arg] ap_loc + Lambda.apply ~result_not_nested:ap_result_not_nested fn [arg] ap_loc | (Strict | StrictOpt), arg, _ when is_safe_to_alias arg -> (* `Strict` and `StrictOpt` bindings both evaluate the RHS immediately (with `StrictOpt` allowing later elimination if unused). When that RHS diff --git a/compiler/typing/lambda.ml b/compiler/typing/lambda.ml index 80f6b502e5..3c150336ce 100644 --- a/compiler/typing/lambda.ml +++ b/compiler/typing/lambda.ml @@ -389,7 +389,16 @@ and lfunction = { and prim_info = {primitive: primitive; args: t list; loc: Location.t} -and lambda_apply = {ap_func: t; ap_args: t list; ap_loc: Location.t} +and lambda_apply = { + ap_func: t; + ap_args: t list; + ap_loc: Location.t; + ap_result_not_nested: bool; + (* The call's own type is [option], where [t] cannot be [undefined]: + a body inlined here returns a [Some(v)] as [v], without + [Primitive_option.some] (see + [Lam_beta_reduce.propagate_beta_reduce]) *) +} and switch_key = | Switch_int of int @@ -799,7 +808,8 @@ let rec eq_approx (l1 : t) (l2 : t) = | Lapply app1 -> ( match l2 with | Lapply app2 -> - eq_approx app1.ap_func app2.ap_func + app1.ap_result_not_nested = app2.ap_result_not_nested + && eq_approx app1.ap_func app2.ap_func && eq_approx_list app1.ap_args app2.ap_args | _ -> false) | Lifthenelse (a, b, c) -> ( @@ -1142,10 +1152,11 @@ let prim ~primitive:(prim : primitive) ~args loc : t = let lfunction_can_be_inlined (lfunction : lfunction) = (not lfunction.attr.async) && lfunction.attr.directive = None -let rec apply fn args (ap_loc : Location.t) : t = +let rec apply ?(result_not_nested = false) fn args (ap_loc : Location.t) : t = + let ap_result_not_nested = result_not_nested in match fn with | Lfunction lfunction when not (lfunction_can_be_inlined lfunction) -> - Lapply {ap_func = fn; ap_args = args; ap_loc} + Lapply {ap_func = fn; ap_args = args; ap_loc; ap_result_not_nested} | Lfunction { params; @@ -1164,14 +1175,15 @@ let rec apply fn args (ap_loc : Location.t) : t = prim ~primitive:wrap ~args:[prim ~primitive:primitive_call.primitive ~args ap_loc] ap_loc - | exception Not_simple_form -> Lapply {ap_func = fn; ap_args = args; ap_loc} - ) + | exception Not_simple_form -> + Lapply {ap_func = fn; ap_args = args; ap_loc; ap_result_not_nested}) | Lfunction {params; body = Lprim ({primitive; args = inner_args} as primitive_call)} when evaluates_args_as_call primitive args -> ( match is_eta_conversion_exn params inner_args args with | args -> prim ~primitive:primitive_call.primitive ~args ap_loc - | exception _ -> Lapply {ap_func = fn; ap_args = args; ap_loc}) + | exception _ -> + Lapply {ap_func = fn; ap_args = args; ap_loc; ap_result_not_nested}) | Lfunction { params; @@ -1184,17 +1196,17 @@ let rec apply fn args (ap_loc : Location.t) : t = match is_eta_conversion_exn params inner_args args with | args -> seq (prim ~primitive:primitive_call.primitive ~args ap_loc) const | exception _ -> - Lapply {ap_func = fn; ap_args = args; ap_loc} + Lapply {ap_func = fn; ap_args = args; ap_loc; ap_result_not_nested} (* | Lfunction {params;body} when Ext_list.same_length params args -> Ext_list.fold_right2 (fun p arg acc -> Llet(Strict,p,arg,acc) ) params args body *) (* TODO: more rigirous analysis on [let_kind] *)) | Llet (kind, id, e, (Lfunction _ as fn)) -> - let_ kind id e (apply fn args ap_loc) + let_ kind id e (apply ~result_not_nested fn args ap_loc) (* | Llet (kind0, id0, e0, Llet (kind,id, e, (Lfunction _ as fn))) -> Llet(kind0,id0,e0,Llet (kind, id, e, apply fn args loc status)) *) - | _ -> Lapply {ap_func = fn; ap_args = args; ap_loc} + | _ -> Lapply {ap_func = fn; ap_args = args; ap_loc; ap_result_not_nested} let not_ loc x : t = match x with diff --git a/compiler/typing/lambda.mli b/compiler/typing/lambda.mli index ffd8811c49..b2225df4df 100644 --- a/compiler/typing/lambda.mli +++ b/compiler/typing/lambda.mli @@ -407,7 +407,16 @@ and lfunction = { and prim_info = private {primitive: primitive; args: t list; loc: Location.t} -and lambda_apply = private {ap_func: t; ap_args: t list; ap_loc: Location.t} +and lambda_apply = private { + ap_func: t; + ap_args: t list; + ap_loc: Location.t; + ap_result_not_nested: bool; + (** The call's own type is [option], where [t] cannot be [undefined]: + a body inlined here returns a [Some(v)] as [v], without + [Primitive_option.some]. Set by the translation of a call and by + [Lam_beta_reduce.propagate_beta_reduce]. *) +} and switch_key = | Switch_int of int @@ -494,7 +503,7 @@ val may_skip_operands : primitive -> bool depending on its value, as [&&] and [||] do. Others evaluate all of them, left to right. *) -val apply : t -> t list -> Location.t -> t +val apply : ?result_not_nested:bool -> t -> t list -> Location.t -> t val function_ : loc:Location.t -> diff --git a/compiler/typing/lambda_traverse.ml b/compiler/typing/lambda_traverse.ml index 1a32a6aac3..855ee395ba 100644 --- a/compiler/typing/lambda_traverse.ml +++ b/compiler/typing/lambda_traverse.ml @@ -40,7 +40,7 @@ let shallow_map_sharing (f : t -> t) (lam : t) : t = let fn = f ap.ap_func in let args = Ext_list.map_sharing ap.ap_args f in if fn == ap.ap_func && args == ap.ap_args then lam - else apply fn args ap.ap_loc + else apply ~result_not_nested:ap.ap_result_not_nested fn args ap.ap_loc | Lfunction {params; body; attr; loc} -> let body' = f body in if body' == body then lam else function_ ~loc ~attr ~params ~body:body' @@ -108,8 +108,12 @@ let shallow_map_sharing (f : t -> t) (lam : t) : t = let rec drop_locations (lam : t) : t = let loc = Location.none in match lam with - | Lapply {ap_func; ap_args} -> - apply (drop_locations ap_func) (List.map drop_locations ap_args) loc + | Lapply {ap_func; ap_args; ap_result_not_nested} -> + (* The mark is a fact about the value at this module's types, so it is + kept for the module that inlines this body *) + apply ~result_not_nested:ap_result_not_nested (drop_locations ap_func) + (List.map drop_locations ap_args) + loc | Lfunction {params; body; attr} -> function_ ~loc ~attr ~params ~body:(drop_locations body) | Lprim {primitive; args} -> @@ -137,7 +141,9 @@ let make_key e = | Lvar id -> ( try Ident.find_same id env with Not_found -> e) | Lglobal_module _ | Lconst _ -> e | Lapply ap -> - apply (tr_rec env ap.ap_func) (tr_recs env ap.ap_args) Location.none + (* The mark stays: actions with equal keys are shared *) + apply ~result_not_nested:ap.ap_result_not_nested (tr_rec env ap.ap_func) + (tr_recs env ap.ap_args) Location.none | Llet (Alias, x, ex, e) -> (* Ignore aliases -> substitute *) let ex = tr_rec env ex in diff --git a/compiler/typing/printlambda.ml b/compiler/typing/printlambda.ml index f621dcd5c6..becaa762ec 100644 --- a/compiler/typing/printlambda.ml +++ b/compiler/typing/printlambda.ml @@ -252,7 +252,8 @@ let rec lam ppf = function | Lconst cst -> struct_const ppf cst | Lapply ap -> let lams ppf largs = List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in - fprintf ppf "@[<2>(apply@ %a%a)@]" lam ap.ap_func lams ap.ap_args + let mark = if ap.ap_result_not_nested then " #result_not_nested" else "" in + fprintf ppf "@[<2>(apply%s@ %a%a)@]" mark lam ap.ap_func lams ap.ap_args | Lfunction {params; body; attr} -> let pr_params ppf params = List.iter (fun param -> fprintf ppf "@ %a" Ident.print param) params diff --git a/compiler/typing/translcore.ml b/compiler/typing/translcore.ml index 71c6783f13..f630f084cc 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -1248,6 +1248,11 @@ let check_callee_attributes (funct : expression) = [undefined]. Only when that check fails, or the declaration ends in a bare parameter, is the type expanded. *) let option_cannot_be_nested env ty = + (* Most calls return one of these, which no lookup turns into an option *) + let builtin_not_option path = + Path.same path Predef.path_unit + || Predef.type_is_builtin_path_but_option path = For_sure_yes + in let payload_cannot_be_undefined (ty : Types.type_expr) = match ty.desc with | Tconstr (path, [payload], _) when Path.same path Predef.path_option -> @@ -1258,7 +1263,9 @@ let option_cannot_be_nested env ty = let ty = Btype.repr ty in match ty.desc with | Tconstr (path, _, _) - when fuel > 0 && not (Path.same path Predef.path_option) -> ( + when fuel > 0 + && (not (Path.same path Predef.path_option)) + && not (builtin_not_option path) -> ( match Env.find_type path env with | {type_manifest = Some manifest; type_private = Public} -> declared (fuel - 1) manifest @@ -1279,6 +1286,19 @@ let option_cannot_be_nested env ty = | _ -> false) | _ -> false +(* A full application [e] whose own type is [option], where [t] cannot be + [undefined], is marked as such, so that the body of a function inlined + here returns a [Some(v)] as [v], without [Primitive_option.some], as a + [Some(v)] written here would be. Only the call's own type counts: an + argument mark, from the type the argument is used at, may come from a + cast. *) +let transl_marked_result (e : expression) (lam : Lambda.t) = + match lam with + | Lapply {ap_func; ap_args; ap_loc; ap_result_not_nested = false} + when option_cannot_be_nested e.exp_env e.exp_type -> + Lambda.apply ~result_not_nested:true ap_func ap_args ap_loc + | _ -> lam + let rec transl_exp e = Builtin_attributes.replay_warning_scope (exp_warning_attributes e) (fun () -> List.iter (Translattribute.check_attribute e) e.exp_attributes; @@ -1421,8 +1441,11 @@ and transl_exp0 (e : Typedtree.expression) : Lambda.t = | None -> None else None in - transl_apply ~uncurried_partial_application (transl_exp funct) oargs - e.exp_loc + let lam = + transl_apply ~uncurried_partial_application (transl_exp funct) oargs + e.exp_loc + in + if partial then lam else transl_marked_result e lam | Texp_match (arg, pat_expr_list, exn_pat_expr_list, partial) -> transl_match e arg pat_expr_list exn_pat_expr_list partial | Texp_try (body, pat_expr_list, finally) -> ( diff --git a/tests/compiler_tests/src/flat_make_export_test.mjs b/tests/compiler_tests/src/flat_make_export_test.mjs index 3cedf64bfe..cd888f6645 100644 --- a/tests/compiler_tests/src/flat_make_export_test.mjs +++ b/tests/compiler_tests/src/flat_make_export_test.mjs @@ -2,7 +2,6 @@ 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"; import * as Flat_make_export_use from "./flat_make_export_use.mjs"; Mocha.describe("Flat_make_export_test", () => { @@ -22,7 +21,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(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 ? 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.mjs b/tests/compiler_tests/src/inline_export.mjs index 46139cc55f..8d5ee9cc69 100644 --- a/tests/compiler_tests/src/inline_export.mjs +++ b/tests/compiler_tests/src/inline_export.mjs @@ -24,9 +24,18 @@ function catchMessage(f) { } } +function mapPair(o, f) { + let r = o !== undefined ? f(o) : undefined; + return [ + r, + 1 + ]; +} + export { apply, ordinary, catchMessage, + mapPair, } /* Stdlib_JsExn Not a pure module */ diff --git a/tests/compiler_tests/src/inline_export.res b/tests/compiler_tests/src/inline_export.res index 962852209f..e5dc4b4b72 100644 --- a/tests/compiler_tests/src/inline_export.res +++ b/tests/compiler_tests/src/inline_export.res @@ -10,3 +10,12 @@ let catchMessage = f => | JsExn(e) => JsExn.message(e) | _ => None } + +// Option.map returns an option here, so its inlined copy builds the Some +// without wrapping, and another module that inlines this function gets that +// body. +@inline +let mapPair = (o: option, f: int => int) => { + let r = o->Option.map(f) + (r, 1) +} diff --git a/tests/compiler_tests/src/inline_export_test.mjs b/tests/compiler_tests/src/inline_export_test.mjs index 497d253df5..53bf7d7cdc 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 opt + 1 | 0; } } @@ -87,40 +87,64 @@ try { fromCatch = e.RE_EXN_ID === "JsExn" ? Stdlib_JsExn.message(e._1) : undefined; } +function mapPairValue(o, f) { + let r = o !== undefined ? f(o) : undefined; + return [ + r, + 1 + ]; +} + Mocha.describe("@inline across modules", () => { Mocha.test("Option helpers", () => { - Test_utils.eq("File \"inline_export_test.res\", line 30, characters 7-14", mapped, 3); - Test_utils.eq("File \"inline_export_test.res\", line 31, characters 7-14", flatMapped, 4); - Test_utils.eq("File \"inline_export_test.res\", line 32, characters 7-14", mappedNested, Primitive_option.some(undefined)); - Test_utils.eq("File \"inline_export_test.res\", line 33, characters 7-14", Primitive_option.some(2 + 1 | 0), 3); - Test_utils.eq("File \"inline_export_test.res\", line 34, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_export_test.res\", line 35, characters 7-14", 2 + 2 | 0, 4); - Test_utils.eq("File \"inline_export_test.res\", line 36, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_export_test.res\", line 31, characters 7-14", mapped, 3); + Test_utils.eq("File \"inline_export_test.res\", line 32, characters 7-14", flatMapped, 4); + Test_utils.eq("File \"inline_export_test.res\", line 33, characters 7-14", mappedNested, Primitive_option.some(undefined)); + Test_utils.eq("File \"inline_export_test.res\", line 34, characters 7-14", 2 + 1 | 0, 3); + Test_utils.eq("File \"inline_export_test.res\", line 35, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_export_test.res\", line 36, characters 7-14", 2 + 2 | 0, 4); + Test_utils.eq("File \"inline_export_test.res\", line 37, characters 7-14", undefined, undefined); visited.push(5); - Test_utils.eq("File \"inline_export_test.res\", line 38, characters 7-14", visited, [ + Test_utils.eq("File \"inline_export_test.res\", line 39, characters 7-14", visited, [ 4, 5 ]); }); Mocha.test("only marked exports are inlined", () => { - Test_utils.eq("File \"inline_export_test.res\", line 41, characters 7-14", 4, 4); - Test_utils.eq("File \"inline_export_test.res\", line 42, characters 7-14", fromOrdinary, 4); - Test_utils.eq("File \"inline_export_test.res\", line 43, characters 7-14", fromCatch, "boom"); + Test_utils.eq("File \"inline_export_test.res\", line 42, characters 7-14", 4, 4); + Test_utils.eq("File \"inline_export_test.res\", line 43, characters 7-14", fromOrdinary, 4); + Test_utils.eq("File \"inline_export_test.res\", line 44, characters 7-14", fromCatch, "boom"); + let r = 2 + 1 | 0; + Test_utils.eq("File \"inline_export_test.res\", line 45, characters 7-14", [ + r, + 1 + ], [ + 3, + 1 + ]); + let r$1; + Test_utils.eq("File \"inline_export_test.res\", line 46, characters 7-14", [ + r$1, + 1 + ], [ + undefined, + 1 + ]); }); Mocha.test("additional Option helpers", () => { - Test_utils.eq("File \"inline_export_test.res\", line 46, characters 7-14", 4, 4); - Test_utils.eq("File \"inline_export_test.res\", line 47, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_export_test.res\", line 48, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_export_test.res\", line 49, characters 7-14", 3, 3); - Test_utils.eq("File \"inline_export_test.res\", line 50, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_export_test.res\", line 51, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_export_test.res\", line 52, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_export_test.res\", line 53, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_export_test.res\", line 54, characters 7-14", 3, 3); - Test_utils.eq("File \"inline_export_test.res\", line 55, characters 7-14", true, true); - Test_utils.eq("File \"inline_export_test.res\", line 56, characters 7-14", false, false); - Test_utils.eq("File \"inline_export_test.res\", line 57, characters 7-14", false, false); + Test_utils.eq("File \"inline_export_test.res\", line 49, characters 7-14", 4, 4); + Test_utils.eq("File \"inline_export_test.res\", line 50, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_export_test.res\", line 51, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_export_test.res\", line 52, characters 7-14", 3, 3); + Test_utils.eq("File \"inline_export_test.res\", line 53, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_export_test.res\", line 54, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_export_test.res\", line 55, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_export_test.res\", line 56, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_export_test.res\", line 57, characters 7-14", 3, 3); Test_utils.eq("File \"inline_export_test.res\", line 58, characters 7-14", true, true); + Test_utils.eq("File \"inline_export_test.res\", line 59, characters 7-14", false, false); + Test_utils.eq("File \"inline_export_test.res\", line 60, characters 7-14", false, false); + Test_utils.eq("File \"inline_export_test.res\", line 61, characters 7-14", true, true); }); Mocha.test("eager fallback arguments", () => { let effects = []; @@ -137,12 +161,12 @@ Mocha.describe("@inline across modules", () => { return 0; }; getDefault(); - Test_utils.eq("File \"inline_export_test.res\", line 74, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_export_test.res\", line 77, characters 7-14", 2, 2); mapDefault(); - Test_utils.eq("File \"inline_export_test.res\", line 75, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_export_test.res\", line 78, characters 7-14", 2, 2); other(); - Test_utils.eq("File \"inline_export_test.res\", line 76, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_export_test.res\", line 77, characters 7-14", effects, [ + Test_utils.eq("File \"inline_export_test.res\", line 79, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_export_test.res\", line 80, characters 7-14", effects, [ "getOr", "mapOr", "orElse" @@ -170,5 +194,6 @@ export { fromExport, fromOrdinary, fromCatch, + mapPairValue, } /* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_export_test.res b/tests/compiler_tests/src/inline_export_test.res index 5818403f07..e4df4c2f96 100644 --- a/tests/compiler_tests/src/inline_export_test.res +++ b/tests/compiler_tests/src/inline_export_test.res @@ -24,6 +24,7 @@ None->Option.forEach(_ => visited->Array.push(0)) let fromExport = Inline_export.apply(3, x => x + 1) let fromOrdinary = Inline_export.ordinary(3, x => x + 1) let fromCatch = Inline_export.catchMessage(() => JsError.throwWithMessage("boom")) +let mapPairValue = (o: option, f: int => int) => Inline_export.mapPair(o, f) describe("@inline across modules", () => { test("Option helpers", () => { @@ -41,6 +42,8 @@ describe("@inline across modules", () => { eq(__LOC__, fromExport, 4) eq(__LOC__, fromOrdinary, 4) eq(__LOC__, fromCatch, Some("boom")) + eq(__LOC__, mapPairValue(Some(2), x => x + 1), (Some(3), 1)) + eq(__LOC__, mapPairValue(None, x => x + 1), (None, 1)) }) test("additional Option helpers", () => { eq(__LOC__, filterValue(Some(4), x => x > 3), Some(4)) diff --git a/tests/compiler_tests/src/inline_option_result_test.mjs b/tests/compiler_tests/src/inline_option_result_test.mjs new file mode 100644 index 0000000000..882934d19f --- /dev/null +++ b/tests/compiler_tests/src/inline_option_result_test.mjs @@ -0,0 +1,382 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; +import * as Stdlib_List from "@rescript/runtime/lib/es6/Stdlib_List.mjs"; +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; +import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.mjs"; + +let hide = (x => x); + +function mapNamed(opt, f) { + if (opt !== undefined) { + return f(opt); + } +} + +function mapLambda(opt) { + if (opt !== undefined) { + return opt + 1 | 0; + } +} + +function positive(x) { + if (x > 0) { + return x; + } +} + +function localPositive(x) { + if (x > 0) { + return x; + } +} + +function classify(x) { + if (x !== 0) { + if (x !== 1) { + return "many"; + } else { + return "one"; + } + } +} + +function classifyInt(x) { + if (x !== 0) { + if (x !== 1) { + return "many"; + } else { + return "one"; + } + } +} + +function checked(x) { + try { + if (x < 0) { + throw { + RE_EXN_ID: "Not_found", + Error: new Error() + }; + } + return (x << 1); + } catch (raw_exn) { + let exn = Primitive_exceptions.internalToException(raw_exn); + if (exn.RE_EXN_ID === "Not_found") { + return; + } + throw exn; + } +} + +function checkedInt(x) { + try { + if (x < 0) { + throw { + RE_EXN_ID: "Not_found", + Error: new Error() + }; + } + return (x << 1); + } catch (raw_exn) { + let exn = Primitive_exceptions.internalToException(raw_exn); + if (exn.RE_EXN_ID === "Not_found") { + return; + } + throw exn; + } +} + +function wrapMap(opt, f) { + if (opt !== undefined) { + return Primitive_option.some(f(Primitive_option.valFromOption(opt))); + } +} + +function viaWrapper(opt) { + if (opt !== undefined) { + return (opt << 1); + } +} + +function mapAbbrev(opt) { + if (opt !== undefined) { + return opt + 1 | 0; + } +} + +function mapGenericAbbrev(opt) { + if (opt !== undefined) { + return opt + 1 | 0; + } +} + +function mapNested(opt) { + if (opt !== undefined) { + return Primitive_option.some(opt > 0 ? opt : undefined); + } +} + +function mapNullable(opt) { + if (opt !== undefined) { + return Primitive_option.some(opt > 0 ? opt : undefined); + } +} + +function mapGeneric(opt, f) { + if (opt !== undefined) { + return Primitive_option.some(f(opt)); + } +} + +function castResult(opt) { + if (opt !== undefined) { + return Primitive_option.some(undefined); + } +} + +function castArgument(opt) { + return ( + opt !== undefined ? Primitive_option.some(undefined) : undefined + ) !== undefined; +} + +function castInBlock(opt) { + return ( + opt !== undefined ? Primitive_option.some(undefined) : undefined + ) !== undefined; +} + +function nestedSome(a) { + return Primitive_option.some(a > 0 ? a : undefined); +} + +function keep(o, _b) { + return o; +} + +let keepCast = nestedSome; + +function keepCastMap(opt) { + if (opt !== undefined) { + return Primitive_option.some(undefined); + } +} + +let applyCast = nestedSome; + +function nestedPositive(a) { + return Primitive_option.some(a > 0 ? a : undefined); +} + +function callOpt(g, a) { + return g(a); +} + +function callCast(a) { + return a > 0 ? a : undefined; +} + +function forward(g, o, d) { + return g(o, d); +} + +function useForward(g, next, count) { + return g(next(), count()); +} + +function bindThenCall(f, count) { + return f(count()); +} + +function residueTuple(f, a, b) { + let v = f([ + a, + b + ]); + return [ + v, + v + ]; +} + +function find(_xs, p) { + while (true) { + let xs = _xs; + if (xs === 0) { + return; + } + let x = xs.hd; + if (p(x)) { + return x; + } + _xs = xs.tl; + continue; + }; +} + +function countTo(_n, limit) { + while (true) { + let n = _n; + if (n >= limit) { + return n; + } + _n = n + 1 | 0; + continue; + }; +} + +function findPositive(xs) { + return find(xs, x => x > 0); +} + +Mocha.describe("Inline_option_result_test", () => { + Mocha.test("payload that cannot be undefined", () => { + Test_utils.eq("File \"inline_option_result_test.res\", line 156, characters 7-14", 2 * 3 | 0, 6); + Test_utils.eq("File \"inline_option_result_test.res\", line 157, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 158, characters 7-14", 2 + 1 | 0, 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 159, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 160, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_result_test.res\", line 161, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 162, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 163, characters 7-14", "one", "one"); + Test_utils.eq("File \"inline_option_result_test.res\", line 164, characters 7-14", "many", "many"); + let tmp; + try { + tmp = 6; + } catch (raw_exn) { + let exn = Primitive_exceptions.internalToException(raw_exn); + if (exn.RE_EXN_ID === "Not_found") { + tmp = undefined; + } else { + throw exn; + } + } + Test_utils.eq("File \"inline_option_result_test.res\", line 165, characters 7-14", tmp, 6); + let tmp$1; + try { + throw { + RE_EXN_ID: "Not_found", + Error: new Error() + }; + } catch (raw_exn$1) { + let exn$1 = Primitive_exceptions.internalToException(raw_exn$1); + if (exn$1.RE_EXN_ID === "Not_found") { + tmp$1 = undefined; + } else { + throw exn$1; + } + } + Test_utils.eq("File \"inline_option_result_test.res\", line 166, characters 7-14", tmp$1, undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 167, characters 7-14", (2 << 1), 4); + Test_utils.eq("File \"inline_option_result_test.res\", line 168, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 169, characters 7-14", 2 + 1 | 0, 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 170, characters 7-14", 2 + 1 | 0, 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 171, characters 7-14", undefined, undefined); + }); + Mocha.test("payload that can be undefined", () => { + Test_utils.eq("File \"inline_option_result_test.res\", line 174, characters 7-14", mapNested(2), 2); + Test_utils.eq("File \"inline_option_result_test.res\", line 175, characters 7-14", mapNested(-2), Primitive_option.some(undefined)); + Test_utils.eq("File \"inline_option_result_test.res\", line 176, characters 7-14", mapNested(undefined), undefined); + let match = mapNested(-2); + Test_utils.eq("File \"inline_option_result_test.res\", line 178, characters 6-13", match !== undefined ? ( + Primitive_option.valFromOption(match) !== undefined ? "Some(Some)" : "Some(None)" + ) : "None", "Some(None)"); + Test_utils.eq("File \"inline_option_result_test.res\", line 186, characters 7-14", mapNullable(-2) !== undefined, true); + Test_utils.eq("File \"inline_option_result_test.res\", line 187, characters 7-14", mapNullable(2), 2); + Test_utils.eq("File \"inline_option_result_test.res\", line 188, characters 7-14", true, true); + }); + Mocha.test("casts", () => { + Test_utils.eq("File \"inline_option_result_test.res\", line 191, characters 7-14", true, true); + Test_utils.eq("File \"inline_option_result_test.res\", line 192, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 193, characters 7-14", true, true); + Test_utils.eq("File \"inline_option_result_test.res\", line 194, characters 7-14", false, false); + let opt = hide(1); + Test_utils.eq("File \"inline_option_result_test.res\", line 195, characters 7-14", ( + opt !== undefined ? Primitive_option.some(undefined) : undefined + ) !== undefined, true); + let opt$1 = hide(undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 196, characters 7-14", ( + opt$1 !== undefined ? Primitive_option.some(undefined) : undefined + ) !== undefined, false); + Test_utils.eq("File \"inline_option_result_test.res\", line 197, characters 7-14", nestedSome(hide(-1)), Primitive_option.some(undefined)); + Test_utils.eq("File \"inline_option_result_test.res\", line 198, characters 7-14", nestedSome(hide(1)), 1); + Test_utils.eq("File \"inline_option_result_test.res\", line 199, characters 7-14", keepCastMap(hide(1)), Primitive_option.some(undefined)); + Test_utils.eq("File \"inline_option_result_test.res\", line 200, characters 7-14", keepCastMap(hide(undefined)), undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 201, characters 7-14", nestedSome(hide(-1)), Primitive_option.some(undefined)); + Test_utils.eq("File \"inline_option_result_test.res\", line 202, characters 7-14", nestedSome(hide(1)), 1); + Test_utils.eq("File \"inline_option_result_test.res\", line 203, characters 7-14", nestedSome(hide(-1)) !== undefined, true); + Test_utils.eq("File \"inline_option_result_test.res\", line 204, characters 7-14", nestedSome(hide(-1)) !== undefined, true); + let a = hide(1); + Test_utils.eq("File \"inline_option_result_test.res\", line 205, characters 7-14", a > 0 ? a : undefined, 1); + let a$1 = hide(-1); + Test_utils.eq("File \"inline_option_result_test.res\", line 206, characters 7-14", a$1 > 0 ? a$1 : undefined, undefined); + }); + Mocha.test("other optimizations", () => { + let sum = (o, d) => { + if (o !== undefined) { + return o + d | 0; + } + }; + Test_utils.eq("File \"inline_option_result_test.res\", line 210, characters 7-14", useForward(sum, () => 1, () => 2), 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 211, characters 7-14", 8, 8); + Test_utils.eq("File \"inline_option_result_test.res\", line 212, characters 7-14", residueTuple(param => param[0] - param[1] | 0, 5, 3), [ + 2, + 2 + ]); + }); + Mocha.test("recursive functions", () => { + let long = Stdlib_List.make(100000, 0); + Test_utils.eq("File \"inline_option_result_test.res\", line 216, characters 7-14", findPositive(long), undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 217, characters 7-14", findPositive({hd: 0, tl: {hd: 0, tl: {hd: 3, tl: /* [] */0}}}), 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 218, characters 7-14", countTo(0, 100000), 100000); + }); +}); + +let keepCastNested = keepCast; + +let keepCastMapNested = keepCastMap; + +let applyCastNested = applyCast; + +export { + hide, + mapNamed, + mapLambda, + positive, + localPositive, + classify, + classifyInt, + checked, + checkedInt, + wrapMap, + viaWrapper, + mapAbbrev, + mapGenericAbbrev, + mapNested, + mapNullable, + mapGeneric, + castResult, + castArgument, + castInBlock, + nestedSome, + keep, + keepCast, + keepCastMap, + applyCast, + nestedPositive, + callOpt, + callCast, + keepCastNested, + keepCastMapNested, + applyCastNested, + forward, + useForward, + bindThenCall, + residueTuple, + find, + countTo, + findPositive, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_option_result_test.res b/tests/compiler_tests/src/inline_option_result_test.res new file mode 100644 index 0000000000..2faf4ec84f --- /dev/null +++ b/tests/compiler_tests/src/inline_option_result_test.res @@ -0,0 +1,220 @@ +// An inlined function returns a Some without Primitive_option.some when the +// caller's type says the result's payload cannot be undefined. +open Mocha +open Test_utils + +external magic: 'a => 'b = "%identity" + +// Hides a value from the optimizer. +let hide: 'a => 'a = %raw(`x => x`) + +// Returned without wrapping. +let mapNamed = (opt: option, f: int => int) => opt->Option.map(f) +let mapLambda = (opt: option) => opt->Option.map(x => x + 1) + +@inline +let positive = (x: int) => + if x > 0 { + Some(x) + } else { + None + } + +let localPositive = (x: int) => positive(x) + +// Through a switch and a try. +@inline +let classify = (x: int) => + switch x { + | 0 => None + | 1 => Some("one") + | _ => Some("many") + } + +let classifyInt = (x: int) => classify(x) + +@inline +let checked = (x: int) => + try { + if x < 0 { + throw(Not_found) + } + Some(x * 2) + } catch { + | Not_found => None + } + +let checkedInt = (x: int) => checked(x) + +// A generic wrapper around Option.map, inlined too. +let wrapMap = (opt, f) => opt->Option.map(f) +let viaWrapper = (opt: option) => wrapMap(opt, x => x * 2) + +// Type abbreviations of options. +type maybeInt = option +type maybe<'a> = option<'a> +let mapAbbrev = (opt: option): maybeInt => opt->Option.map(x => x + 1) +let mapGenericAbbrev = (opt: option): maybe => opt->Option.map(x => x + 1) + +// Still wrapped: the payload can be undefined. +let mapNested = (opt: option) => + opt->Option.map(x => + if x > 0 { + Some(x) + } else { + None + } + ) + +let mapNullable = (opt: option) => + opt->Option.map(x => + if x > 0 { + Nullable.make(x) + } else { + Nullable.undefined + } + ) + +let mapGeneric = (opt: option, f: int => 'a) => opt->Option.map(f) + +// A cast of the call's result: the call's own type has a nested payload. +let castResult = (opt: option): option => magic(opt->Option.map((_): option => None)) + +// A cast of the call to an argument's type: the call's own type has a nested +// payload. +let castArgument = (opt: option) => + Option.isSome((magic(opt->Option.map((_): option => None)): option)) + +// A cast in an argument's type is no call's own type: the cast call keeps +// its wrapping. +let castInBlock = (opt: option) => + Option.isSome({ + let y: option = magic(opt->Option.map((_): option => None)) + y + }) + +// A cast argument that ends up as the result of an inlined function is not +// rewritten: only the function's own Somes and calls are. +let nestedSome = (a: int): option> => Some(a > 0 ? Some(a) : None) +let keep = (o: option, _b: bool): option => o +let keepCast = (a: int) => keep(magic(nestedSome(a)), true) + +let keepCastMap = (opt: option): option => + keep(magic(opt->Option.map((_): option => None)), true) + +let applyCast = (a: int): option => ((o: option) => o)(magic(nestedSome(a))) + +// A cast of the called function counts like a cast inside it: the call's +// type comes from the function's type, which the cast changes. Here the +// call `g(a)` has type option, so nestedPositive inlined there returns +// its payload without wrapping, as the same Some written at the call site +// would: at the cast type, a negative number gives None. +@inline +let nestedPositive = (a: int): option> => Some(a > 0 ? Some(a) : None) + +let callOpt = (g: int => option, a: int) => g(a) +let callCast = (a: int) => callOpt(magic(nestedPositive), a) + +// Called at their real type, so that the call itself is not marked. +let keepCastNested: int => option> = magic(keepCast) +let keepCastMapNested: option => option> = magic(keepCastMap) +let applyCastNested: int => option> = magic(applyCast) + +// The mark on a call doesn't block other optimizations: each of these +// compiles without a temporary. +// A forwarding function's arguments go straight into its call. +let forward = (g, o: option, d: int): option => g(o, d) +let useForward = (g, next: unit => option, count: unit => int) => forward(g, next(), count()) + +// `let x = e; f(x)` becomes `f(e)`. +let bindThenCall = (f: int => option, count: unit => int) => { + let x = count() + f(x) +} + +// A binding whose value is `let p = (a, b); f(p)` keeps the tuple in the call. +let residueTuple = (f: ((int, int)) => option, a: int, b: int) => { + let v = { + let p = (a, b) + f(p) + } + (v, v) +} + +// Recursive functions stay loops. +let rec find = (xs: list, p) => + switch xs { + | list{} => None + | list{x, ...rest} => p(x) ? Some(x) : find(rest, p) + } + +let rec countTo = (n: int, limit: int): option => n >= limit ? Some(n) : countTo(n + 1, limit) +let findPositive = (xs: list) => find(xs, x => x > 0) + +describe(__MODULE__, () => { + test("payload that cannot be undefined", () => { + eq(__LOC__, mapNamed(Some(2), x => x * 3), Some(6)) + eq(__LOC__, mapNamed(None, x => x * 3), None) + eq(__LOC__, mapLambda(Some(2)), Some(3)) + eq(__LOC__, mapLambda(None), None) + eq(__LOC__, localPositive(2), Some(2)) + eq(__LOC__, localPositive(-2), None) + eq(__LOC__, classifyInt(0), None) + eq(__LOC__, classifyInt(1), Some("one")) + eq(__LOC__, classifyInt(5), Some("many")) + eq(__LOC__, checkedInt(3), Some(6)) + eq(__LOC__, checkedInt(-3), None) + eq(__LOC__, viaWrapper(Some(2)), Some(4)) + eq(__LOC__, viaWrapper(None), None) + eq(__LOC__, mapAbbrev(Some(2)), Some(3)) + eq(__LOC__, mapGenericAbbrev(Some(2)), Some(3)) + eq(__LOC__, mapGenericAbbrev(None), None) + }) + test("payload that can be undefined", () => { + eq(__LOC__, mapNested(Some(2)), Some(Some(2))) + eq(__LOC__, mapNested(Some(-2)), Some(None)) + eq(__LOC__, mapNested(None), None) + eq( + __LOC__, + switch mapNested(Some(-2)) { + | Some(None) => "Some(None)" + | Some(Some(_)) => "Some(Some)" + | None => "None" + }, + "Some(None)", + ) + eq(__LOC__, mapNullable(Some(-2))->Option.isSome, true) + eq(__LOC__, mapNullable(Some(2)), Some(Nullable.make(2))) + eq(__LOC__, mapGeneric(Some(1), _ => None)->Option.isSome, true) + }) + test("casts", () => { + eq(__LOC__, castResult(Some(1))->Option.isSome, true) + eq(__LOC__, castResult(None), None) + eq(__LOC__, castArgument(Some(1)), true) + eq(__LOC__, castArgument(None), false) + eq(__LOC__, castInBlock(hide(Some(1))), true) + eq(__LOC__, castInBlock(hide(None)), false) + eq(__LOC__, keepCastNested(hide(-1)), Some(None)) + eq(__LOC__, keepCastNested(hide(1)), Some(Some(1))) + eq(__LOC__, keepCastMapNested(hide(Some(1))), Some(None)) + eq(__LOC__, keepCastMapNested(hide(None)), None) + eq(__LOC__, applyCastNested(hide(-1)), Some(None)) + eq(__LOC__, applyCastNested(hide(1)), Some(Some(1))) + eq(__LOC__, keepCast(hide(-1))->Option.isSome, true) + eq(__LOC__, applyCast(hide(-1))->Option.isSome, true) + eq(__LOC__, callCast(hide(1)), Some(1)) + eq(__LOC__, callCast(hide(-1)), None) + }) + test("other optimizations", () => { + let sum = (o, d) => o->Option.map(x => x + d) + eq(__LOC__, useForward(sum, () => Some(1), () => 2), Some(3)) + eq(__LOC__, bindThenCall(x => Some(x * 2), () => 4), Some(8)) + eq(__LOC__, residueTuple(((a, b)) => Some(a - b), 5, 3), (Some(2), Some(2))) + }) + test("recursive functions", () => { + let long = List.make(~length=100_000, 0) + eq(__LOC__, findPositive(long), None) + eq(__LOC__, findPositive(list{0, 0, 3}), Some(3)) + eq(__LOC__, countTo(0, 100_000), Some(100_000)) + }) +}) diff --git a/tests/compiler_tests/src/inline_option_unwrap_test.mjs b/tests/compiler_tests/src/inline_option_unwrap_test.mjs index 7a8fd3d5b9..cc853b603e 100644 --- a/tests/compiler_tests/src/inline_option_unwrap_test.mjs +++ b/tests/compiler_tests/src/inline_option_unwrap_test.mjs @@ -30,7 +30,7 @@ function stdlibIntOr(opt) { function mapped(opt) { if (opt !== undefined) { - return Primitive_option.some(opt + 1 | 0); + return opt + 1 | 0; } } @@ -100,8 +100,8 @@ function sameNestedOr(opt) { function nullableInput(s) { return [ - !(s == null) ? Primitive_option.some(s + "a") : undefined, - !(s == null) ? Primitive_option.some(s + "b") : undefined + !(s == null) ? s + "a" : undefined, + !(s == null) ? s + "b" : undefined ]; } @@ -139,7 +139,7 @@ function castOnce(opt) { } function knownSome(x, f) { - return Primitive_option.some(f(x)); + return f(x); } function knownSomeNested(x, f) { @@ -149,15 +149,15 @@ function knownSomeNested(x, f) { Mocha.describe("Inline_option_unwrap_test", () => { Mocha.test("literal Some with a parameter argument", () => { Test_utils.eq("File \"inline_option_unwrap_test.res\", line 64, characters 7-14", knownSome(2, x => x + 1 | 0), 3); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 65, characters 7-14", Primitive_option.some(true), true); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 66, characters 7-14", Primitive_option.some(false), false); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 65, characters 7-14", true, true); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 66, characters 7-14", false, false); }); Mocha.test("payload that cannot be undefined", () => { Test_utils.eq("File \"inline_option_unwrap_test.res\", line 69, characters 7-14", 2, 2); Test_utils.eq("File \"inline_option_unwrap_test.res\", line 70, characters 7-14", 0, 0); Test_utils.eq("File \"inline_option_unwrap_test.res\", line 71, characters 7-14", 2, 2); Test_utils.eq("File \"inline_option_unwrap_test.res\", line 72, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 73, characters 7-14", Primitive_option.some(2 + 1 | 0), 3); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 73, characters 7-14", 2 + 1 | 0, 3); Test_utils.eq("File \"inline_option_unwrap_test.res\", line 74, characters 7-14", undefined, undefined); Test_utils.eq("File \"inline_option_unwrap_test.res\", line 75, characters 7-14", 2, 2); Test_utils.eq("File \"inline_option_unwrap_test.res\", line 76, characters 7-14", 2, 2); diff --git a/tests/compiler_tests/src/int_overflow_test.mjs b/tests/compiler_tests/src/int_overflow_test.mjs index f9e3b05873..2eb02561bb 100644 --- a/tests/compiler_tests/src/int_overflow_test.mjs +++ b/tests/compiler_tests/src/int_overflow_test.mjs @@ -3,7 +3,6 @@ import * as Mocha from "mocha"; import * as Test_utils from "./test_utils.mjs"; import * as Stdlib_Float from "@rescript/runtime/lib/es6/Stdlib_Float.mjs"; -import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; function hash_variant(s) { let accu = 0; @@ -51,11 +50,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(opt | 0) : undefined, 3); + Test_utils.eq("File \"int_overflow_test.res\", line 65, characters 7-14", opt !== undefined ? 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(opt | 0) : undefined, 3); + Test_utils.eq("File \"int_overflow_test.res\", line 68, characters 7-14", opt !== undefined ? 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 160440005d..1e3586f0bf 100644 --- a/tests/compiler_tests/src/stdlib/Stdlib_ObjectTests.mjs +++ b/tests/compiler_tests/src/stdlib/Stdlib_ObjectTests.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; @@ -478,10 +477,10 @@ runGetTest({ }), get: i => { let opt = i["a"]; - let opt$1 = opt !== undefined ? Primitive_option.some(opt.concat([ + let opt$1 = opt !== undefined ? opt.concat([ 4, 5 - ])) : undefined; + ]) : undefined; if (opt$1 !== undefined) { return opt$1; } else { diff --git a/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs b/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs index 2cdc4fb58d..a7a385eec0 100644 --- a/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs +++ b/tests/compiler_tests/src/stdlib/Stdlib_TempTests.mjs @@ -203,11 +203,11 @@ console.log(regex.test(string)); let result = regex.exec(string); -console.log(!(result == null) ? Primitive_option.some(result.input) : undefined); +console.log(!(result == null) ? result.input : undefined); -console.log(!(result == null) ? Primitive_option.some(result.index) : undefined); +console.log(!(result == null) ? result.index : undefined); -console.log(!(result == null) ? Primitive_option.some(result.slice(1)) : undefined); +console.log(!(result == null) ? result.slice(1) : undefined); console.info(""); diff --git a/tests/compiler_tests/src/stdlib/Stdlib_TemporalTests.mjs b/tests/compiler_tests/src/stdlib/Stdlib_TemporalTests.mjs index 5af6690503..8cbb1197ab 100644 --- a/tests/compiler_tests/src/stdlib/Stdlib_TemporalTests.mjs +++ b/tests/compiler_tests/src/stdlib/Stdlib_TemporalTests.mjs @@ -339,7 +339,7 @@ Test.run([ 54 ], "getTimeZoneTransition with a transition" -], !(opt == null) ? Primitive_option.some(opt.toString()) : undefined, eq, "2024-03-10T03:00:00-04:00[America/New_York]"); +], !(opt == null) ? opt.toString() : undefined, eq, "2024-03-10T03:00:00-04:00[America/New_York]"); Test.run([ [ diff --git a/tests/compiler_tests/src/stdlib/intl/Stdlib_IntlTests.mjs b/tests/compiler_tests/src/stdlib/intl/Stdlib_IntlTests.mjs index 6b66b2d1fd..d4d46d8b28 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(opt.toLowerCase()) : undefined; + let message = opt !== undefined ? opt.toLowerCase() : undefined; if (message === "invalid key : someinvalidkey") { console.log("Caught expected error"); } else { diff --git a/tests/ounit_tests/ounit_constant_argument_tests.ml b/tests/ounit_tests/ounit_constant_argument_tests.ml index cdc90fc088..66bef99464 100644 --- a/tests/ounit_tests/ounit_constant_argument_tests.ml +++ b/tests/ounit_tests/ounit_constant_argument_tests.ml @@ -54,7 +54,8 @@ let suites = ( "an argument with an identity is bound once, not copied" >:: fun _ -> let b = Ident.create "b" in let lam = - Lam_beta_reduce.propagate_beta_reduce (meta ()) [b] (same b) + Lam_beta_reduce.propagate_beta_reduce ~result_not_nested:false + (meta ()) [b] (same b) [Lambda.const block] in OUnit.assert_equal ~printer:string_of_int 1 (count_constants lam); @@ -66,7 +67,8 @@ let suites = ( "a nested none argument is repeated" >:: fun _ -> let b = Ident.create "b" in let lam = - Lam_beta_reduce.propagate_beta_reduce (meta ()) [b] (same b) + Lam_beta_reduce.propagate_beta_reduce ~result_not_nested:false + (meta ()) [b] (same b) [Lambda.const nested_none] in match lam with