From a507341c7eec0ed782321bc9ed3e5165120b9433 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Fri, 4 Dec 2026 21:39:55 +0000 Subject: [PATCH 1/4] Keep a Some or tuple payload read before its variable is assigned MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: The alias pass replaced the payload of a variable known to be `Some(x)`, and a field of one known to be `(x, _)`, with `x` itself. When `x` is assigned between the binding and the read, the read gets the new value. Since #9022 substituted `Some(x)` payloads, this is reachable through cross-module `@inline` bodies, which are stored after `Lam_pass_sroa` turned their refs into assigned variables. The pass now keeps the binding when the variable is assigned. JS modified (cross-module @inline): Example: // Other.res @inline let f = (n: int, q: 'a, q2: 'a) => { let s = ref(q) let o = Some(s.contents) for _ in 0 to n { s := q2 } switch o { | Some(v) => Some((v, s.contents)) | None => None } } @inline let g = (n: int, q: 'a, q2: 'a) => { let s = ref(q) let t = (s.contents, 1) for _ in 0 to n { s := q2 } let (a, _) = t (a, s.contents) } // Main.res let viaAlias = () => Other.f(3, "a", "b") let viaField = () => Other.g(3, "a", "b") Before (js): both return ["b", "b"] function viaAlias() { let s = "a"; for (let _for = 0; _for <= 3; ++_for) { s = "b"; } return [ s, s ]; } … viaField compiles to the same After (js): both return ["a", "b"] function viaAlias() { let s = "a"; let o = Primitive_option.some(s); for (let _for = 0; _for <= 3; ++_for) { s = "b"; } return [ Primitive_option.valFromOption(o), s ]; } function viaField() { let s = "a"; let t_0 = s; for (let _for = 0; _for <= 3; ++_for) { s = "b"; } return [ t_0, s ]; } Review: Why also guard `Js.Null.toOption(x)` bindings? They record `x` the same way, and the unwrap and the `null` test read it later just like a `Some(x)` payload; no repro was found there, the guard keeps it sound. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- changes/inline-assigned-payload.fix.md | 1 + compiler/backend/lam_pass_remove_alias.ml | 28 ++++-- .../src/inline_assigned_payload_lib.mjs | 47 ++++++++++ .../src/inline_assigned_payload_lib.res | 39 ++++++++ .../src/inline_assigned_payload_test.mjs | 88 +++++++++++++++++++ .../src/inline_assigned_payload_test.res | 25 ++++++ 6 files changed, 219 insertions(+), 9 deletions(-) create mode 100644 changes/inline-assigned-payload.fix.md create mode 100644 tests/compiler_tests/src/inline_assigned_payload_lib.mjs create mode 100644 tests/compiler_tests/src/inline_assigned_payload_lib.res create mode 100644 tests/compiler_tests/src/inline_assigned_payload_test.mjs create mode 100644 tests/compiler_tests/src/inline_assigned_payload_test.res diff --git a/changes/inline-assigned-payload.fix.md b/changes/inline-assigned-payload.fix.md new file mode 100644 index 0000000000..9b45799634 --- /dev/null +++ b/changes/inline-assigned-payload.fix.md @@ -0,0 +1 @@ +- Fix the payload of a `Some` or a tuple field, made from a variable that is assigned later, giving the variable's new value. diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index e4b41b0ae8..888e21aaff 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -69,6 +69,14 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = Set_ident.union !assignable (Lambda_traverse.assigned_variables lam); lam in + (* What [meta.ident_tbl] records about a binding, like [Some(x)] or + [(x, 1)], gives [x] as it was when the binding was made. Moving a read of + [x] to a later use is wrong once something assigns [x] in between. *) + let stable (lam : Lambda.t) = + match lam with + | Lvar x -> not (Set_ident.mem x !assignable) + | _ -> true + in let inline_depth = ref 0 in let rec simpl (lam : Lambda.t) : Lambda.t = match lam with @@ -89,11 +97,13 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = (* ATTENTION: Main use case, we should detect inline all immutable block .. *) match simpl arg with - | Lvar v as l -> - Lam_util.field_flatten_get - (fun _ -> - if l == arg then lam else Lambda.prim ~primitive ~args:[l] loc) - v i info meta.ident_tbl + | Lvar v as l -> ( + let keep _ = + if l == arg then lam else Lambda.prim ~primitive ~args:[l] loc + in + match Lam_util.field_flatten_get keep v i info meta.ident_tbl with + | field when stable field -> field + | _ -> keep ()) | l -> if l == arg then lam else Lambda.prim ~primitive ~args:[l] loc) | Lprim { @@ -101,10 +111,10 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = args = [(Lvar v as lvar)]; } as x -> ( match Hash_ident.find_opt meta.ident_tbl v with - | Some (OptionalBlock (l, _)) -> l + | Some (OptionalBlock (l, _)) when stable l -> l (* [v] bound to [Some(l)]: unwrapping gives back [l], whether or not it was nested. Only substitute forms that are safe to repeat. *) - | Some (Normal_optional (Lvar _ as l)) -> l + | Some (Normal_optional (Lvar _ as l)) when stable l -> l | Some (Normal_optional (Lconst c as l)) when not (Lambda.const_is_allocating c) -> l @@ -114,12 +124,12 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = match Hash_ident.find_opt meta.ident_tbl id with | Some (Constant c) when is_const_some c -> simpl l2 | Some (ImmutableBlock _ | Normal_optional _) -> simpl l2 - | Some (OptionalBlock (l, Null)) -> + | Some (OptionalBlock (l, Null)) when stable l -> Lambda.if_ (Lambda.not_ Location.none (Lambda.prim ~primitive:Pis_null ~args:[l] Location.none)) (simpl l2) (simpl l3) - | Some (OptionalBlock (l, Null_undefined)) -> + | Some (OptionalBlock (l, Null_undefined)) when stable l -> Lambda.if_ (Lambda.not_ Location.none (Lambda.prim ~primitive:Pis_null_undefined ~args:[l] Location.none)) diff --git a/tests/compiler_tests/src/inline_assigned_payload_lib.mjs b/tests/compiler_tests/src/inline_assigned_payload_lib.mjs new file mode 100644 index 0000000000..6a58953438 --- /dev/null +++ b/tests/compiler_tests/src/inline_assigned_payload_lib.mjs @@ -0,0 +1,47 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; + +function someBeforeAssign(n, q, q2) { + let s = q; + let o = Primitive_option.some(s); + for (let _for = 0; _for <= n; ++_for) { + s = q2; + } + return [ + Primitive_option.valFromOption(o), + s + ]; +} + +function tupleBeforeAssign(n, q, q2) { + let s = q; + let t_0 = s; + for (let _for = 0; _for <= n; ++_for) { + s = q2; + } + return [ + t_0, + s + ]; +} + +function nullableBeforeAssign(n, q, q2) { + let s = q; + let o = s; + for (let _for = 0; _for <= n; ++_for) { + s = q2; + } + if (o == null) { + return "none"; + } else { + return o; + } +} + +export { + someBeforeAssign, + tupleBeforeAssign, + nullableBeforeAssign, +} +/* No side effect */ diff --git a/tests/compiler_tests/src/inline_assigned_payload_lib.res b/tests/compiler_tests/src/inline_assigned_payload_lib.res new file mode 100644 index 0000000000..4cd99e717d --- /dev/null +++ b/tests/compiler_tests/src/inline_assigned_payload_lib.res @@ -0,0 +1,39 @@ +// Inlined by inline_assigned_payload_test.res. Each function is stored +// optimized, so [s] is a variable the loop assigns: the payload [o] or the +// field of [t] must keep the value [s] had before the loop. +@inline +let someBeforeAssign = (n: int, q: 'a, q2: 'a) => { + let s = ref(q) + let o = Some(s.contents) + for _ in 0 to n { + s := q2 + } + switch o { + | Some(v) => Some((v, s.contents)) + | None => None + } +} + +@inline +let tupleBeforeAssign = (n: int, q: 'a, q2: 'a) => { + let s = ref(q) + let t = (s.contents, 1) + for _ in 0 to n { + s := q2 + } + let (a, _) = t + (a, s.contents) +} + +@inline +let nullableBeforeAssign = (n: int, q: Nullable.t, q2: Nullable.t) => { + let s = ref(q) + let o = Nullable.toOption(s.contents) + for _ in 0 to n { + s := q2 + } + switch o { + | Some(v) => v + | None => "none" + } +} diff --git a/tests/compiler_tests/src/inline_assigned_payload_test.mjs b/tests/compiler_tests/src/inline_assigned_payload_test.mjs new file mode 100644 index 0000000000..13da510c82 --- /dev/null +++ b/tests/compiler_tests/src/inline_assigned_payload_test.mjs @@ -0,0 +1,88 @@ +// 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 someBeforeAssign() { + let s = "a"; + let o = Primitive_option.some(s); + for (let _for = 0; _for <= 3; ++_for) { + s = "b"; + } + return [ + Primitive_option.valFromOption(o), + s + ]; +} + +function tupleBeforeAssign() { + let s = "a"; + let t_0 = s; + for (let _for = 0; _for <= 3; ++_for) { + s = "b"; + } + return [ + t_0, + s + ]; +} + +function nullableBeforeAssign() { + let s = "a"; + let o = s; + for (let _for = 0; _for <= 3; ++_for) { + s = null; + } + if (o == null) { + return "none"; + } else { + return o; + } +} + +Mocha.describe("Inline_assigned_payload_test", () => { + Mocha.test("the payload of a Some, made before its variable is assigned", () => { + let s = "a"; + let o = Primitive_option.some(s); + for (let _for = 0; _for <= 3; ++_for) { + s = "b"; + } + Test_utils.eq("File \"inline_assigned_payload_test.res\", line 15, characters 7-14", [ + "a", + "b" + ], [ + Primitive_option.valFromOption(o), + s + ]); + }); + Mocha.test("the field of a tuple, made before its variable is assigned", () => { + let s = "a"; + let t_0 = s; + for (let _for = 0; _for <= 3; ++_for) { + s = "b"; + } + Test_utils.eq("File \"inline_assigned_payload_test.res\", line 19, characters 7-14", [ + "a", + "b" + ], [ + t_0, + s + ]); + }); + Mocha.test("a nullable converted to an option before its variable is assigned", () => { + let s = "a"; + let o = s; + for (let _for = 0; _for <= 3; ++_for) { + s = null; + } + Test_utils.eq("File \"inline_assigned_payload_test.res\", line 23, characters 7-14", "a", o == null ? "none" : o); + }); +}); + +export { + someBeforeAssign, + tupleBeforeAssign, + nullableBeforeAssign, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_assigned_payload_test.res b/tests/compiler_tests/src/inline_assigned_payload_test.res new file mode 100644 index 0000000000..bbe6660d5e --- /dev/null +++ b/tests/compiler_tests/src/inline_assigned_payload_test.res @@ -0,0 +1,25 @@ +// A [Some] or a tuple made from a variable that is assigned later must keep +// the value the variable had when it was made. +open Mocha +open Test_utils + +let someBeforeAssign = () => Inline_assigned_payload_lib.someBeforeAssign(3, "a", "b") + +let tupleBeforeAssign = () => Inline_assigned_payload_lib.tupleBeforeAssign(3, "a", "b") + +let nullableBeforeAssign = () => + Inline_assigned_payload_lib.nullableBeforeAssign(3, Nullable.make("a"), Nullable.null) + +describe(__MODULE__, () => { + test("the payload of a Some, made before its variable is assigned", () => { + eq(__LOC__, Some(("a", "b")), someBeforeAssign()) + }) + + test("the field of a tuple, made before its variable is assigned", () => { + eq(__LOC__, ("a", "b"), tupleBeforeAssign()) + }) + + test("a nullable converted to an option before its variable is assigned", () => { + eq(__LOC__, "a", nullableBeforeAssign()) + }) +}) From 9af8bb988f7e8d26737ec6b910647124764fd187 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Fri, 4 Dec 2026 17:58:08 +0000 Subject: [PATCH 2/4] Simplify bodies inlined while compiling to JavaScript Why: A call to another module's function that also passes a parameter of the caller is inlined late, while compiling to JavaScript, after the alias pass has run. So the inlined body kept what that pass removes elsewhere: a `Some(x)` argument was bound and unwrapped again, and a function argument was called instead of inlined. The alias pass now also runs on such a body before it is compiled. JS modified (a literal Some next to a parameter): Example: let knownSome = (x: int, f) => Some(x)->Option.map(f)->Option.getOr(0) Before (js): function knownSome(x, f) { let opt = x; let opt$1 = opt !== undefined ? Primitive_option.some(f(Primitive_option.valFromOption(opt))) : undefined; if (opt$1 !== undefined) { return opt$1; } else { return 0; } } After (js): function knownSome(x, f) { let opt = Primitive_option.some(f(x)); if (opt !== undefined) { return opt; } else { return 0; } } JS modified (a function argument): Example: let mapped = (opt: option) => opt->Option.map(x => x + 1) Before (js): function mapped(opt) { if (opt !== undefined) { return Primitive_option.some((x => x + 1 | 0)(opt)); } } After (js): function mapped(opt) { if (opt !== undefined) { return Primitive_option.some(opt + 1 | 0); } } Review: Why does the late pass get a fresh `ident_tbl`? The table was filled by `collect_info` before `simplify_alias 3`, `simplify_lets`, `sroa` and `simplify_exits` rewrote the program, so at codegen it can give a function body or a `Some` payload naming a variable those passes removed or turned into an assigned one: inlining a let-bound local function from it printed `p + k` with no `k` in scope. The body is now simplified knowing only the parameters it binds; the caller is still compiled with the real `meta`. Review: Which variables count as assigned there? The pass used to take only the ones `lam` assigns, but at codegen `lam` is just the inlined body, so a variable of the caller assigned by a call in it looked immutable and its read moved past that call. The pass now starts from `meta.assignable` as well. In the other direction, the pass may inline a further function that assigns a variable of its own, so the variables the body assigns are collected after the pass, before it is compiled. Review: What stays? `Option.map` still wraps its result with `Primitive_option.some`; that needs a mark on the result of the call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- changes/late-inline-alias-pass.polish.md | 1 + compiler/backend/lam_compile.ml | 24 +- compiler/backend/lam_pass_remove_alias.ml | 11 +- .../compiler_tests/src/inline_export_test.mjs | 2 +- .../src/inline_late_alias_lib.mjs | 75 ++++++ .../src/inline_late_alias_lib.res | 61 +++++ .../src/inline_late_alias_test.mjs | 222 ++++++++++++++++++ .../src/inline_late_alias_test.res | 159 +++++++++++++ .../src/inline_late_alias_wrap.mjs | 20 ++ .../src/inline_late_alias_wrap.res | 4 + .../src/inline_option_unwrap_test.mjs | 66 ++++-- .../src/inline_option_unwrap_test.res | 10 + 12 files changed, 624 insertions(+), 31 deletions(-) create mode 100644 changes/late-inline-alias-pass.polish.md create mode 100644 tests/compiler_tests/src/inline_late_alias_lib.mjs create mode 100644 tests/compiler_tests/src/inline_late_alias_lib.res create mode 100644 tests/compiler_tests/src/inline_late_alias_test.mjs create mode 100644 tests/compiler_tests/src/inline_late_alias_test.res create mode 100644 tests/compiler_tests/src/inline_late_alias_wrap.mjs create mode 100644 tests/compiler_tests/src/inline_late_alias_wrap.res diff --git a/changes/late-inline-alias-pass.polish.md b/changes/late-inline-alias-pass.polish.md new file mode 100644 index 0000000000..11ae786a8a --- /dev/null +++ b/changes/late-inline-alias-pass.polish.md @@ -0,0 +1 @@ +- Simplify the body of a function from another module that is inlined while compiling to JavaScript, so a `Some(x)` argument is read directly and a function argument applied in the body is inlined. diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 0f61772afa..5239df5a38 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -589,12 +589,28 @@ let compile output_prefix = let _, param_map = Lam_closure.is_closed_with_map Set_ident.empty params body in + (* What [meta.ident_tbl] records about the caller's bindings was + collected before the last passes rewrote them, so it may give + bodies or payloads naming variables that are gone. The inlined body + is simplified with a fresh table, which only gets what is known + about the parameters it binds. *) + let ident_tbl = Hash_ident.create 17 in let inlined = - Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta param_map - params body ap_args + Lam_beta_reduce.propagate_beta_reduce_with_map + {lambda_cxt.meta with ident_tbl} + param_map params body ap_args in - (* The inlined body comes from another module, so the variables it - assigns are not in [meta.assignable] yet. *) + (* The alias pass ran before this call was inlined: run it on the + inlined body, so that a known argument, such as a [Some], is + resolved there too *) + let inlined = + Lam_pass_remove_alias.simplify_alias + {lambda_cxt.meta with ident_tbl} + inlined + in + (* The inlined body comes from another module, and the alias pass may + have inlined more into it, so the variables it assigns are not in + [meta.assignable] yet. *) let meta = { lambda_cxt.meta with diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index 888e21aaff..5e771cd606 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -56,9 +56,14 @@ let max_inline_depth = 4 let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = (* Inlining keeps the reads of assigned variables in order (see [Lam_beta_reduce]), so it needs the variables some [Lassign] assigns. - Only [Lam_pass_sroa], which runs later, makes [Lassign]s, so [lam] has - none yet; computing them here keeps the inlining sound if that changes. *) - let assignable = ref (Lambda_traverse.assigned_variables lam) in + Before [Lam_pass_sroa], only bodies inlined from other modules have + [Lassign]s. When this pass runs on a body inlined while compiling to + JavaScript, [lam] is only that body: the variables of the function + around it that are assigned come from [meta.assignable]. *) + let assignable = + ref + (Set_ident.union meta.assignable (Lambda_traverse.assigned_variables lam)) + in let current_meta () = {meta with assignable = !assignable} in (* A body inlined from another module was optimized by [Lam_pass_sroa] there, so it may assign variables, and inlining renamed them. They are diff --git a/tests/compiler_tests/src/inline_export_test.mjs b/tests/compiler_tests/src/inline_export_test.mjs index 5b76b2b6a7..b88054bc51 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((x => x + 1 | 0)(opt)); + return Primitive_option.some(opt + 1 | 0); } } diff --git a/tests/compiler_tests/src/inline_late_alias_lib.mjs b/tests/compiler_tests/src/inline_late_alias_lib.mjs new file mode 100644 index 0000000000..0a3865b11a --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_lib.mjs @@ -0,0 +1,75 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; + +function id(x) { + return x; +} + +let c = id(3); + +function apply(x, f) { + return f(x); +} + +function apply2(p, v, g) { + return g(v, p); +} + +function unwrapG(x, o) { + if (o !== undefined) { + return [ + Primitive_option.valFromOption(o), + x + ]; + } +} + +function weird(p, o, f) { + f(); + if (o !== undefined) { + return o + p | 0; + } else { + return p; + } +} + +function weirdT(p, t, f) { + f(); + return t[0] + p | 0; +} + +function countUp(p, n) { + let r = p; + let tmp = r; + for (let _for = 0; _for <= n; ++_for) { + r = r + 1 | 0; + } + return [ + tmp, + r + ]; +} + +function weirdG(p, o, f) { + f(); + if (o !== undefined) { + return [ + Primitive_option.valFromOption(o), + p + ]; + } +} + +export { + id, + c, + apply, + apply2, + unwrapG, + weird, + weirdT, + countUp, + weirdG, +} +/* c Not a pure module */ diff --git a/tests/compiler_tests/src/inline_late_alias_lib.res b/tests/compiler_tests/src/inline_late_alias_lib.res new file mode 100644 index 0000000000..1849428092 --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_lib.res @@ -0,0 +1,61 @@ +// Inlined by inline_late_alias_test.res. Each call there passes a parameter of +// the caller, so it is inlined while compiling to JavaScript. +@inline(never) let id = x => x + +let c = id(3) + +@inline +let apply = (x, f) => f(x) + +@inline +let apply2 = (p: int, v, g) => g(v, p) + +@inline +let unwrapG = (x: int, o: option<'a>) => + switch o { + | Some(v) => Some((v, x)) + | None => None + } + +// [f] may assign the variable the option or the tuple was made from. +@inline +let weird = (p: int, o: option, f) => { + f() + switch o { + | Some(v) => v + p + | None => p + } +} + +@inline +let weirdT = (p: int, t: (int, int), f) => { + f() + let (a, _) = t + a + p +} + +// Reads [r] before the loop that assigns it. Inlined into +// inline_late_alias_wrap.res's [countUpWrapped] only by the alias pass that +// runs while compiling to JavaScript. +@inline +let countUp = (p: int, n: int) => { + let r = ref(p) + ( + r.contents, + { + for _ in 0 to n { + r := r.contents + 1 + } + r.contents + }, + ) +} + +@inline +let weirdG = (p: int, o: option<'a>, f) => { + f() + switch o { + | Some(v) => Some((v, p)) + | None => None + } +} diff --git a/tests/compiler_tests/src/inline_late_alias_test.mjs b/tests/compiler_tests/src/inline_late_alias_test.mjs new file mode 100644 index 0000000000..808fe2735e --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_test.mjs @@ -0,0 +1,222 @@ +// 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"; +import * as Inline_late_alias_lib from "./inline_late_alias_lib.mjs"; +import * as Inline_late_alias_wrap from "./inline_late_alias_wrap.mjs"; + +function letBoundGlobal(p) { + let h = x => x + Inline_late_alias_lib.c | 0; + return h(p) + h(p) | 0; +} + +function tupleField(p, q) { + let h = x => x + q.length | 0; + return h(p) + h(p) | 0; +} + +function assignedRef(p) { + let r = 0; + let h = x => x + r | 0; + r = 10; + return h(p) + h(p) | 0; +} + +function assignedRecord(p) { + let r_a = 1; + let r_b = 2; + let h = x => x + r_b | 0; + r_b = 10; + r_a = r_a + r_b | 0; + return (h(p) + h(p) | 0) + r_a | 0; +} + +function someGlobal(p) { + let x = Inline_late_alias_lib.c; + return [ + x !== undefined ? [ + x, + p + ] : undefined, + x + ]; +} + +function someField(p, q) { + let x = q[0]; + return [ + x !== undefined ? [ + x, + p + ] : undefined, + x + ]; +} + +function someTupleField(p, q) { + let x = q; + return [ + x !== undefined ? [ + x, + p + ] : undefined, + x + ]; +} + +function readBeforeCall(p, n) { + let r = 1; + let f = () => { + for (let i = 0; i <= n; ++i) { + r = r + i | 0; + } + }; + let x = r; + f(); + let res = x + p | 0; + return [ + res, + r + ]; +} + +function someBeforeCall(p, n) { + let r = 1; + let f = () => { + for (let i = 0; i <= n; ++i) { + r = r + i | 0; + } + }; + let o = r; + f(); + let res = o + p | 0; + return [ + res, + r + ]; +} + +function tupleBeforeCall(p, n) { + let r = 1; + let f = () => { + for (let i = 0; i <= n; ++i) { + r = r + i | 0; + } + }; + let t_0 = r; + f(); + let res = t_0 + p | 0; + return [ + res, + r + ]; +} + +function genericSomeBeforeCall(p, n, q, q2) { + let r = q; + let f = () => { + for (let _for = 0; _for <= n; ++_for) { + r = q2; + } + }; + let o = Primitive_option.some(r); + f(); + let res = [ + Primitive_option.valFromOption(o), + p + ]; + return [ + res, + r + ]; +} + +function nestedAssigned(p, n) { + let r = p; + let tmp = r; + for (let _for = 0; _for <= n; ++_for) { + r = r + 1 | 0; + } + return [ + tmp, + r + ]; +} + +Mocha.describe("Inline_late_alias_test", () => { + Mocha.test("a function reading a let-bound global", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 113, characters 7-14", 8, letBoundGlobal(1))); + Mocha.test("a function reading a field of a known tuple", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 117, characters 7-14", 8, tupleField(1, [ + 1, + 2, + 3 + ]))); + Mocha.test("a function reading a ref assigned before the calls", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 121, characters 7-14", 22, assignedRef(1))); + Mocha.test("a function reading a mutable field assigned before the calls", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 125, characters 7-14", 33, assignedRecord(1))); + Mocha.test("a Some of a let-bound global", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 129, characters 7-14", [ + [ + 3, + 1 + ], + 3 + ], someGlobal(1))); + Mocha.test("a Some of a field of a parameter", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 133, characters 7-14", [ + [ + 5, + 1 + ], + 5 + ], someField(1, [ + 5, + 6 + ]))); + Mocha.test("a Some of a field of a known tuple", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 137, characters 7-14", [ + [ + "a", + 1 + ], + "a" + ], someTupleField(1, "a"))); + Mocha.test("an argument read before a call that assigns it", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 141, characters 7-14", [ + 2, + 7 + ], readBeforeCall(1, 3))); + Mocha.test("a Some made before a call that assigns its variable", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 145, characters 7-14", [ + 2, + 7 + ], someBeforeCall(1, 3))); + Mocha.test("a tuple made before a call that assigns its variable", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 149, characters 7-14", [ + 2, + 7 + ], tupleBeforeCall(1, 3))); + Mocha.test("a generic Some made before a call that assigns its variable", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 153, characters 7-14", [ + [ + "a", + 1 + ], + "b" + ], genericSomeBeforeCall(1, 3, "a", "b"))); + Mocha.test("a variable assigned in a body inlined by the late alias pass", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 157, characters 7-14", [ + 10, + 14 + ], nestedAssigned(10, 3))); +}); + +let L; + +export { + L, + letBoundGlobal, + tupleField, + assignedRef, + assignedRecord, + someGlobal, + someField, + someTupleField, + readBeforeCall, + someBeforeCall, + tupleBeforeCall, + genericSomeBeforeCall, + nestedAssigned, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_late_alias_test.res b/tests/compiler_tests/src/inline_late_alias_test.res new file mode 100644 index 0000000000..bf4a3f1251 --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_test.res @@ -0,0 +1,159 @@ +// A call inlined while compiling to JavaScript is simplified after the other +// passes rewrote the function around it: what was known about that function's +// variables before then must not be used, and its assigned variables must be +// read where they were read. +open Mocha +open Test_utils + +module L = Inline_late_alias_lib + +let letBoundGlobal = p => { + let k = L.c + let h = x => x + k + L.apply(p, h) + L.apply(p, h) +} + +let tupleField = (p, q: array) => { + let t = (q, 1) + let (a, _) = t + let h = x => x + Array.length(a) + L.apply(p, h) + L.apply(p, h) +} + +let assignedRef = p => { + let r = ref(0) + let h = x => x + r.contents + r := 10 + L.apply(p, h) + L.apply(p, h) +} + +type pt = {mutable a: int, mutable b: int} + +let assignedRecord = p => { + let r = {a: 1, b: 2} + let h = x => x + r.b + r.b = 10 + r.a = r.a + r.b + L.apply(p, h) + L.apply(p, h) + r.a +} + +let someGlobal = p => { + let y = L.c + let x = Some(y) + (L.unwrapG(p, x), x) +} + +let someField = (p, q: (int, int)) => { + let (a, _) = q + let x = Some(a) + (L.unwrapG(p, x), x) +} + +let someTupleField = (p, q: string) => { + let t = (q, 1) + let (y, _) = t + let x = Some(y) + (L.unwrapG(p, x), x) +} + +let readBeforeCall = (p, n) => { + let r = ref(1) + let f = () => { + for i in 0 to n { + r := r.contents + i + } + } + let res = L.apply2(p, r.contents, (x, pp) => { + f() + x + pp + }) + (res, r.contents) +} + +let someBeforeCall = (p, n) => { + let r = ref(1) + let f = () => { + for i in 0 to n { + r := r.contents + i + } + } + let res = L.weird(p, Some(r.contents), f) + (res, r.contents) +} + +let tupleBeforeCall = (p, n) => { + let r = ref(1) + let f = () => { + for i in 0 to n { + r := r.contents + i + } + } + let res = L.weirdT(p, (r.contents, 2), f) + (res, r.contents) +} + +let genericSomeBeforeCall = (p, n, q: 'a, q2: 'a) => { + let r = ref(q) + let f = () => { + for _ in 0 to n { + r := q2 + } + } + let res = L.weirdG(p, Some(r.contents), f) + (res, r.contents) +} + +// The late alias pass inlines [countUp] into the wrapper's body, which brings +// in an assigned variable. Not inlined itself, so the test runs this code. +@inline(never) +let nestedAssigned = (p, n) => Inline_late_alias_wrap.countUpWrapped(p, n) + +describe(__MODULE__, () => { + test("a function reading a let-bound global", () => { + eq(__LOC__, 8, letBoundGlobal(1)) + }) + + test("a function reading a field of a known tuple", () => { + eq(__LOC__, 8, tupleField(1, [1, 2, 3])) + }) + + test("a function reading a ref assigned before the calls", () => { + eq(__LOC__, 22, assignedRef(1)) + }) + + test("a function reading a mutable field assigned before the calls", () => { + eq(__LOC__, 33, assignedRecord(1)) + }) + + test("a Some of a let-bound global", () => { + eq(__LOC__, (Some((3, 1)), Some(3)), someGlobal(1)) + }) + + test("a Some of a field of a parameter", () => { + eq(__LOC__, (Some((5, 1)), Some(5)), someField(1, (5, 6))) + }) + + test("a Some of a field of a known tuple", () => { + eq(__LOC__, (Some(("a", 1)), Some("a")), someTupleField(1, "a")) + }) + + test("an argument read before a call that assigns it", () => { + eq(__LOC__, (2, 7), readBeforeCall(1, 3)) + }) + + test("a Some made before a call that assigns its variable", () => { + eq(__LOC__, (2, 7), someBeforeCall(1, 3)) + }) + + test("a tuple made before a call that assigns its variable", () => { + eq(__LOC__, (2, 7), tupleBeforeCall(1, 3)) + }) + + test("a generic Some made before a call that assigns its variable", () => { + eq(__LOC__, (Some(("a", 1)), "b"), genericSomeBeforeCall(1, 3, "a", "b")) + }) + + test("a variable assigned in a body inlined by the late alias pass", () => { + eq(__LOC__, (10, 14), nestedAssigned(10, 3)) + }) +}) diff --git a/tests/compiler_tests/src/inline_late_alias_wrap.mjs b/tests/compiler_tests/src/inline_late_alias_wrap.mjs new file mode 100644 index 0000000000..ceb3f53de4 --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_wrap.mjs @@ -0,0 +1,20 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Inline_late_alias_lib from "./inline_late_alias_lib.mjs"; + +function countUpWrapped(p, n) { + let r = p; + let tmp = r; + for (let _for = 0; _for <= n; ++_for) { + r = r + 1 | 0; + } + return [ + tmp, + r + ]; +} + +export { + countUpWrapped, +} +/* Inline_late_alias_lib Not a pure module */ diff --git a/tests/compiler_tests/src/inline_late_alias_wrap.res b/tests/compiler_tests/src/inline_late_alias_wrap.res new file mode 100644 index 0000000000..71a440d3ad --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_wrap.res @@ -0,0 +1,4 @@ +// Calls a function of inline_late_alias_lib.res with its own parameters, so +// inlining it waits until this wrapper is itself inlined. +@inline +let countUpWrapped = (p: int, n: int) => Inline_late_alias_lib.countUp(p, n) diff --git a/tests/compiler_tests/src/inline_option_unwrap_test.mjs b/tests/compiler_tests/src/inline_option_unwrap_test.mjs index 6e8d6848cd..c6e445124e 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((x => x + 1 | 0)(opt)); + return Primitive_option.some(opt + 1 | 0); } } @@ -138,43 +138,61 @@ function castOnce(opt) { ]; } +function knownSome(x, f) { + let opt = Primitive_option.some(f(x)); + if (opt !== undefined) { + return opt; + } else { + return 0; + } +} + +function knownSomeNested(x, f) { + return Primitive_option.some(f(x)); +} + 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); + }); Mocha.test("payload that cannot be undefined", () => { - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 59, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 60, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 61, characters 7-14", 2, 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", mapped(2), 3); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 64, characters 7-14", mapped(undefined), undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 65, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 66, characters 7-14", 2, 2); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 67, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 68, characters 7-14", 2, 2); 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", 1, 1); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 71, characters 7-14", "ab".length, 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", nullableInput("x"), [ + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 73, characters 7-14", mapped(2), 3); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 74, characters 7-14", mapped(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); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 77, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 78, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 79, characters 7-14", 2, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 80, characters 7-14", 1, 1); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 81, characters 7-14", "ab".length, 2); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 82, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 83, characters 7-14", nullableInput("x"), [ "xa", "xb" ]); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 74, characters 7-14", nullableInput(null), [ + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 84, characters 7-14", nullableInput(null), [ undefined, undefined ]); }); Mocha.test("payload that can be undefined", () => { - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 77, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 78, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 79, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 80, characters 7-14", 1, 1); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 81, characters 7-14", 0, 0); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 82, characters 7-14", undefined, undefined); - Test_utils.eq("File \"inline_option_unwrap_test.res\", line 83, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 87, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 88, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 89, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 90, characters 7-14", 1, 1); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 91, characters 7-14", 0, 0); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 92, characters 7-14", undefined, undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 93, 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 87, characters 7-14", match[1], undefined); + Test_utils.eq("File \"inline_option_unwrap_test.res\", line 97, characters 7-14", match[1], undefined); }); }); @@ -196,5 +214,7 @@ export { nullableOr, genericOr, castOnce, + knownSome, + knownSomeNested, } /* 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 index 3251ba6821..8ae2af01d5 100644 --- a/tests/compiler_tests/src/inline_option_unwrap_test.res +++ b/tests/compiler_tests/src/inline_option_unwrap_test.res @@ -54,7 +54,17 @@ let castOnce = (opt: option>) => { (unwrapped, inner) } +// A call that also passes a parameter is inlined while compiling to +// JavaScript. A literal Some argument is still read directly. +let knownSome = (x: int, f) => Some(x)->Option.map(f)->Option.getOr(0) +let knownSomeNested = (x: option, f) => Some(x)->Option.map(f) + describe(__MODULE__, () => { + test("literal Some with a parameter argument", () => { + eq(__LOC__, knownSome(2, x => x + 1), 3) + eq(__LOC__, knownSomeNested(None, o => o == None), Some(true)) + eq(__LOC__, knownSomeNested(Some(1), o => o == None), Some(false)) + }) test("payload that cannot be undefined", () => { eq(__LOC__, intOr(Some(2)), 2) eq(__LOC__, intOr(None), 0) From 93beda8c1bd221baa2f36379532e927b1614f335 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Fri, 4 Dec 2026 18:18:50 +0000 Subject: [PATCH 3/4] Return Some of inlined functions without wrapping when the payload can't be undefined Why: An inlined function such as `Option.map` is compiled for any `'b`, so the `Some(v)` it returns is `Primitive_option.some(v)`, in case `v` is itself `None`. The caller knows the result type. A `Some(v)` written at the call site is just `v` when the payload can't be `undefined`; the inlined copy now returns it the same way. The translation of a full application whose own type is `option`, where `t` can't be `undefined`, sets a new flag on the call, `ap_result_not_nested`. The beta reduction that inlines a call takes the call's flag and rewrites the callee's body for it before it substitutes the arguments: a `Some` in return position is built without wrapping, and a call in return position gets the flag, so that a wrapper of `Option.map` is inlined the same way. The flag is part of the call, so a flagged call is still a call to every other pass, and a self tail call stays a loop. An `@inline` body in a `.cmj` keeps its calls' flags, so another module inlines it the same way. Lambda modified (result of a call): Example: let mapped = (opt: option, f: int => int) => opt->Option.map(f) Before (lambda): (function opt/1002 f/1003 (apply (field:map/4 global Stdlib_Option!) (#not_nested_option opt/1002) f/1003)) After (lambda): (function opt/1002 f/1003 (apply #result_not_nested (field:map/4 global Stdlib_Option!) (#not_nested_option opt/1002) f/1003)) Lambda modified (body inlined at a flagged call): Example: let mapped = (opt: option, f: int => int) => opt->Option.map(f) Before (lambda): Option.map's body, before its arguments are substituted (if (#is_not_none opt/1002) (some (apply f/1003 (#val_from_option_not_nest opt/1002))) undefined) After (lambda): (if (#is_not_none opt/1002) (some_not_nest (apply f/1003 (#val_from_option_not_nest opt/1002))) undefined) JS modified (inlined Option.map): Example: let mapped = (opt: option, f: int => int) => opt->Option.map(f) let nested = (opt: option) => opt->Option.map(x => x > 0 ? Some(x) : None) Before (js): function mapped(opt, f) { if (opt !== undefined) { return Primitive_option.some(f(opt)); } } function nested(opt) { if (opt === undefined) { return; } let x = opt; return Primitive_option.some(x > 0 ? x : undefined); } After (js): function mapped(opt, f) { if (opt !== undefined) { return f(opt); } } function nested(opt) { if (opt === undefined) { return; } let x = opt; return Primitive_option.some(x > 0 ? x : undefined); } JS modified (a chain of Option helpers): Example: let knownSome = (x: int, f) => Some(x)->Option.map(f)->Option.getOr(0) Before (js): function knownSome(x, f) { let opt = Primitive_option.some(f(x)); if (opt !== undefined) { return opt; } else { return 0; } } After (js): function knownSome(x, f) { let opt = f(x); if (opt !== undefined) { return opt; } else { return 0; } } Review: Why is it sound to trust the caller's type? The rewrite trusts the type of the call itself, never the type an argument is used at, which a cast can change. The flag has its own place on the call, so the argument mark of #9504 is never read as one: `isSome(magic(opt->Option.map(f)))` leaves the cast call's wrapping alone. The body is rewritten before the arguments are substituted, so only its own `Some`s and calls are: a cast argument that the body returns, as in `keep(magic(g(a)), true)` with `keep = (o, _) => o`, keeps its wrapping. A `switch` at the call site on a value of the call's type already reads the payload directly, so a body that returned a wrapped or `undefined` payload under that type, through a cast or an external, would already break the caller; such a body inlined here now returns the payload as a `Some` written here would. A cast of the called function counts the same way, since the call's type comes from the function's type: with `callOpt = (g: int => option, a) => g(a)`, `callOpt(magic(nestedPositive), a)` inlines `nestedPositive`, of type `int => option>`, at the call `g(a)`, and returns its payload unwrapped. Review: Does the flag get in the way of other optimizations? No: a flagged call is still a call, so no pass needs to look through a mark. The tests' forwarding function, `let x = e; f(x)` and a tuple bound before a call compile without a temporary, and a self tail call is still a loop. Apart from the dropped `Primitive_option.some` calls, the generated JavaScript of the tests, the runtime and Belt doesn't change. Review: Why keep the flag in a `.cmj`? It is a fact about the call's value at the types of the module that wrote it, so it holds wherever the body is inlined. Without it, `let v = (o, f) => Inline_export.mapPair(o, f)` in the tests returned `Primitive_option.some(f(o))`: the call to `Option.map` in `mapPair` reads parameters, so it is inlined only after the body is exported. Review: Is a flagged call a marked argument? Yes: an argument whose own call is flagged is an option whose payload can't be `undefined`, by that call's type, so the inlined body unwraps the parameter it is bound to directly, as for an argument marked by its type. Review: What does it cost to compile? Each full application checks its result type the way #9504 checks arguments: abbreviations are read from their declarations first, and a built-in type such as `int` or `unit` is known to be no option without a lookup, which saves the lookups #9504 made for such arguments too. Compiling the runtime and Belt allocates 0.8% fewer words in all; Belt's list and sorted array modules 2.5% fewer; no module more than 0.15% more. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- changes/inline-option-result.polish.md | 1 + compiler/backend/lam_beta_reduce.ml | 102 ++++- compiler/backend/lam_beta_reduce.mli | 13 +- compiler/backend/lam_beta_reduce_util.ml | 4 +- compiler/backend/lam_bounded_vars.ml | 4 +- compiler/backend/lam_compile.ml | 1 + compiler/backend/lam_pass_count.ml | 9 +- compiler/backend/lam_pass_lets_dce.ml | 9 +- compiler/backend/lam_pass_remove_alias.ml | 34 +- compiler/backend/lam_util.ml | 6 +- compiler/typing/lambda.ml | 32 +- compiler/typing/lambda.mli | 13 +- compiler/typing/lambda_traverse.ml | 14 +- compiler/typing/printlambda.ml | 3 +- compiler/typing/translcore.ml | 33 +- .../src/flat_make_export_test.mjs | 3 +- tests/compiler_tests/src/inline_export.mjs | 9 + tests/compiler_tests/src/inline_export.res | 10 + .../compiler_tests/src/inline_export_test.mjs | 81 ++-- .../compiler_tests/src/inline_export_test.res | 3 + .../src/inline_option_result_test.mjs | 388 ++++++++++++++++++ .../src/inline_option_result_test.res | 220 ++++++++++ .../src/inline_option_unwrap_test.mjs | 12 +- .../compiler_tests/src/int_overflow_test.mjs | 5 +- .../src/stdlib/Stdlib_ObjectTests.mjs | 5 +- .../src/stdlib/Stdlib_TempTests.mjs | 6 +- .../src/stdlib/Stdlib_TemporalTests.mjs | 2 +- .../src/stdlib/intl/Stdlib_IntlTests.mjs | 2 +- .../ounit_constant_argument_tests.ml | 6 +- 29 files changed, 932 insertions(+), 98 deletions(-) create mode 100644 changes/inline-option-result.polish.md create mode 100644 tests/compiler_tests/src/inline_option_result_test.mjs create mode 100644 tests/compiler_tests/src/inline_option_result_test.res 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..2481f3f960 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -125,6 +125,10 @@ let unmark_arguments params (body : Lambda.t) (args : Lambda.t list) = match arg with | Lprim {primitive = Pnot_nested_option; args = [arg]} -> (Set_ident.add param marked, arg :: args) + | Lapply {ap_result_not_nested = true} -> + (* The call's own type says the same of its result, which is what + the parameter is bound to *) + (Set_ident.add param marked, arg :: args) | _ -> (marked, arg :: args)) params args (Set_ident.empty, []) in @@ -135,7 +139,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 +149,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 +279,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 @@ -249,8 +333,8 @@ let propagate_beta_reduce_with_map (meta : Lam_stats.t) Lam_util.refine_let ~assignable ~kind:Strict param arg l) new_body rest_bindings -let no_names_beta_reduce ~assignable params body args = - let body, args = unmark_arguments params body args in +let no_names_beta_reduce ~assignable ~result_not_nested params body args = + let body, args = inlined_body ~result_not_nested 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.mli b/compiler/backend/lam_beta_reduce.mli index 33568782da..e1f2dc767c 100644 --- a/compiler/backend/lam_beta_reduce.mli +++ b/compiler/backend/lam_beta_reduce.mli @@ -26,6 +26,7 @@ val no_names_beta_reduce : assignable:Set_ident.t -> + result_not_nested:bool -> Ident.t list -> Lambda.t -> Lambda.t list -> @@ -49,9 +50,19 @@ 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 the other two functions. *) 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_compile.ml b/compiler/backend/lam_compile.ml index 5239df5a38..36086f47d5 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -597,6 +597,7 @@ let compile output_prefix = let ident_tbl = Hash_ident.create 17 in let inlined = Lam_beta_reduce.propagate_beta_reduce_with_map + ~result_not_nested:appinfo.ap_result_not_nested {lambda_cxt.meta with ident_tbl} param_map params body ap_args in diff --git a/compiler/backend/lam_pass_count.ml b/compiler/backend/lam_pass_count.ml index 0df8167add..55e7d5aa00 100644 --- a/compiler/backend/lam_pass_count.ml +++ b/compiler/backend/lam_pass_count.ml @@ -135,11 +135,16 @@ let collect_occurs ~assignable lam : occ_tbl = count bv body (* Note there is a difference here when do beta reduction for *) | 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 -> count bv - (Lam_beta_reduce.no_names_beta_reduce ~assignable params body args) + (Lam_beta_reduce.no_names_beta_reduce ~assignable + ~result_not_nested:ap_result_not_nested params body args) | Lapply {ap_func = l1; ap_args = ll; _} -> count bv l1; List.iter (count bv) ll diff --git a/compiler/backend/lam_pass_lets_dce.ml b/compiler/backend/lam_pass_lets_dce.ml index 6621d1fddd..f055bfec5b 100644 --- a/compiler/backend/lam_pass_lets_dce.ml +++ b/compiler/backend/lam_pass_lets_dce.ml @@ -115,11 +115,16 @@ let lets_helper ~assignable (count_var : Ident.t -> Lam_pass_count.used_info) | _ -> Lam_util.refine_let ~original:lam ~assignable ~kind v l1 (simplif l2)) | 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 -> simplif - (Lam_beta_reduce.no_names_beta_reduce ~assignable params body args) + (Lam_beta_reduce.no_names_beta_reduce ~assignable + ~result_not_nested:ap_result_not_nested params body args) | Lprim {primitive = Pstringadd; args = [l; r]; loc} -> ( let l' = simplif l in let r' = simplif r in diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index 5e771cd606..c8462aad4e 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -172,6 +172,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 | { @@ -199,25 +200,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 @@ -240,8 +248,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 @@ -253,7 +262,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 @@ -270,6 +280,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; @@ -279,7 +290,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 = @@ -287,7 +302,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..23e3844d26 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) -> ( @@ -1762,11 +1785,13 @@ and transl_apply ?(uncurried_partial_application = None) lam sargs loc = 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. *) + already, and marking them would hide what they are, as would marking a + call whose own type is marked already (see [transl_marked_result]). *) and transl_marked_argument (e : expression) = let lam = transl_exp e in match lam with | Lconst _ + | Lapply {ap_result_not_nested = true} | Lprim { primitive = 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..5331fd73f5 100644 --- a/tests/compiler_tests/src/inline_export.res +++ b/tests/compiler_tests/src/inline_export.res @@ -10,3 +10,13 @@ let catchMessage = f => | JsExn(e) => JsExn.message(e) | _ => None } + +// The call to Option.map reads parameters, so it is inlined only when this +// module is compiled to JavaScript: the exported body keeps the call and its +// mark, and another module that inlines this function returns the Some +// without wrapping too. +@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 b88054bc51..0f12e68e93 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", mapValue(2), 3); - Test_utils.eq("File \"inline_export_test.res\", line 34, characters 7-14", mapValue(undefined), undefined); - Test_utils.eq("File \"inline_export_test.res\", line 35, characters 7-14", flatMapValue(2), 4); - Test_utils.eq("File \"inline_export_test.res\", line 36, characters 7-14", flatMapValue(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", mapValue(2), 3); + Test_utils.eq("File \"inline_export_test.res\", line 35, characters 7-14", mapValue(undefined), undefined); + Test_utils.eq("File \"inline_export_test.res\", line 36, characters 7-14", flatMapValue(2), 4); + Test_utils.eq("File \"inline_export_test.res\", line 37, characters 7-14", flatMapValue(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..3ae2695adb --- /dev/null +++ b/tests/compiler_tests/src/inline_option_result_test.mjs @@ -0,0 +1,388 @@ +// 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; + } + let x = opt; + return Primitive_option.some(x > 0 ? x : undefined); +} + +function mapNullable(opt) { + if (opt === undefined) { + return; + } + let x = opt; + return Primitive_option.some(x > 0 ? x : 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", mapLambda(2), 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 159, characters 7-14", mapLambda(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", viaWrapper(2), 4); + Test_utils.eq("File \"inline_option_result_test.res\", line 168, characters 7-14", viaWrapper(undefined), undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 169, characters 7-14", mapAbbrev(2), 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 170, characters 7-14", mapGenericAbbrev(2), 3); + Test_utils.eq("File \"inline_option_result_test.res\", line 171, characters 7-14", mapGenericAbbrev(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); + let opt$2 = hide(1); + Test_utils.eq("File \"inline_option_result_test.res\", line 199, characters 7-14", opt$2 !== undefined ? Primitive_option.some(undefined) : undefined, Primitive_option.some(undefined)); + let opt$3 = hide(undefined); + Test_utils.eq("File \"inline_option_result_test.res\", line 200, characters 7-14", opt$3 !== undefined ? Primitive_option.some(undefined) : 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 c6e445124e..83a1353881 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) { - let opt = Primitive_option.some(f(x)); + let opt = f(x); if (opt !== undefined) { return opt; } else { @@ -154,8 +154,8 @@ 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); 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 From a3d2b7fc11fedf21500362eccb6735e4cb7c25e7 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Sat, 5 Dec 2026 07:36:58 +0000 Subject: [PATCH 4/4] Keep module field reads before their variable is assigned Why: Two more places moved a read of a module field past an assignment to the variable holding the module, reachable through cross-module `@inline` bodies. The alias pass substituted a tuple element recorded as `M.x` with `M` a variable, and the alias check that lets single-use bindings be inlined accepted `M.x` for any variable `M`. Both now check the variable like any other. JS modified (cross-module @inline, module field): Example: // Other.res module type S = { let x: string } module A = { let x = "a" } module B = { let x = "b" } let get = (m: module(S)) => { let module(M) = m M.x } @inline let f = (n: int, q: module(S), q2: module(S)) => { let s = ref(q) let a = get(s.contents) for _ in 0 to n { s := q2 } (a, get(s.contents)) } // Main.res let main = () => Other.f(3, module(Other.A), module(Other.B)) Before (js): returns ["b", "b"] function main() { let s = Other.A; for (let _for = 0; _for <= 3; ++_for) { s = Other.B; } return [ s.x, s.x ]; } After (js): returns ["a", "b"] function main() { let s = Other.A; let a = s.x; for (let _for = 0; _for <= 3; ++_for) { s = Other.B; } return [ a, s.x ]; } JS modified (cross-module @inline, tuple of a module field): Example: // Other.res, with S, A and B as above @inline let f = (n: int, q: module(S), q2: module(S)) => { let s = ref(q) let t = ( { let module(M) = s.contents M.x }, 1, ) for _ in 0 to n { s := q2 } let (a, _) = t let module(M2) = s.contents (a, M2.x) } // Main.res let main = () => Other.f(3, module(Other.A), module(Other.B)) Before (js): returns ["b", "b"] function main() { let s = Other.A; for (let _for = 0; _for <= 3; ++_for) { s = Other.B; } let M2 = s; return [ s.x, M2.x ]; } After (js): returns ["a", "b"] function main() { let s = Other.A; let t_0 = s.x; for (let _for = 0; _for <= 3; ++_for) { s = Other.B; } let M2 = s; return [ t_0, M2.x ]; } Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- changes/assigned-variable-module-field.fix.md | 1 + compiler/backend/lam_pass_remove_alias.ml | 13 +-- compiler/backend/lam_util.ml | 11 +- .../src/inline_assigned_payload_lib.mjs | 42 ++++++++ .../src/inline_assigned_payload_lib.res | 48 +++++++++ .../src/inline_assigned_payload_test.mjs | 101 +++++++++++------- .../src/inline_assigned_payload_test.res | 39 +++++-- 7 files changed, 199 insertions(+), 56 deletions(-) create mode 100644 changes/assigned-variable-module-field.fix.md diff --git a/changes/assigned-variable-module-field.fix.md b/changes/assigned-variable-module-field.fix.md new file mode 100644 index 0000000000..f8e6643979 --- /dev/null +++ b/changes/assigned-variable-module-field.fix.md @@ -0,0 +1 @@ +- Fix a field of a first-class module held in a ref, in a function inlined from another module, being read from the module the ref is set to later. diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index c8462aad4e..1ab2242275 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -74,14 +74,11 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = Set_ident.union !assignable (Lambda_traverse.assigned_variables lam); lam in - (* What [meta.ident_tbl] records about a binding, like [Some(x)] or - [(x, 1)], gives [x] as it was when the binding was made. Moving a read of - [x] to a later use is wrong once something assigns [x] in between. *) - let stable (lam : Lambda.t) = - match lam with - | Lvar x -> not (Set_ident.mem x !assignable) - | _ -> true - in + (* What [meta.ident_tbl] records about a binding, like [Some(x)], [(x, 1)] + or [(M.x, 1)], gives [x] as it was when the binding was made. Moving a + read of [x] to a later use is wrong once something assigns [x] in + between. *) + let stable lam = Lam_analysis.delay_safe ~assignable:!assignable lam in let inline_depth = ref 0 in let rec simpl (lam : Lambda.t) : Lambda.t = match lam with diff --git a/compiler/backend/lam_util.ml b/compiler/backend/lam_util.ml index e29663f4d4..01236f89d3 100644 --- a/compiler/backend/lam_util.ml +++ b/compiler/backend/lam_util.ml @@ -92,15 +92,14 @@ let refine_let ?original ~assignable ~kind param (arg : Lambda.t) (l : Lambda.t) (* A template without interpolations is a JavaScript literal. Repeating it preserves both its runtime value and its source spelling. *) true - | Lprim - { - primitive = Pfield (_, Fld_module _); - args = [(Lglobal_module _ | Lvar _)]; - _; - } -> + | Lprim {primitive = Pfield (_, Fld_module _); args = [Lglobal_module _]; _} + -> (* field read --> access hits an immutable module block; inlining emits the same read the eager binding would have performed once. *) true + | Lprim {primitive = Pfield (_, Fld_module _); args = [Lvar v]; _} -> + (* The same, unless an [Lassign] may make [v] another module. *) + not (Set_ident.mem v assignable) | Lprim {primitive = Psome_not_nest; args = [inner]; _} -> (* some_not_nest(inner) --> expands to two explicit rewrites: let[k] x = inner --> let[Alias] x = inner diff --git a/tests/compiler_tests/src/inline_assigned_payload_lib.mjs b/tests/compiler_tests/src/inline_assigned_payload_lib.mjs index 6a58953438..b4b5916ca9 100644 --- a/tests/compiler_tests/src/inline_assigned_payload_lib.mjs +++ b/tests/compiler_tests/src/inline_assigned_payload_lib.mjs @@ -39,9 +39,51 @@ function nullableBeforeAssign(n, q, q2) { } } +let A = { + x: "a" +}; + +let B = { + x: "b" +}; + +function moduleFieldBeforeAssign(n, q, q2) { + let s = q; + let t_0 = s.x; + for (let _for = 0; _for <= n; ++_for) { + s = q2; + } + let M2 = s; + return [ + t_0, + M2.x + ]; +} + +function get(m) { + return m.x; +} + +function getBeforeAssign(n, q, q2) { + let s = q; + let a = s.x; + for (let _for = 0; _for <= n; ++_for) { + s = q2; + } + return [ + a, + s.x + ]; +} + export { someBeforeAssign, tupleBeforeAssign, nullableBeforeAssign, + A, + B, + moduleFieldBeforeAssign, + get, + getBeforeAssign, } /* No side effect */ diff --git a/tests/compiler_tests/src/inline_assigned_payload_lib.res b/tests/compiler_tests/src/inline_assigned_payload_lib.res index 4cd99e717d..3ad29c7136 100644 --- a/tests/compiler_tests/src/inline_assigned_payload_lib.res +++ b/tests/compiler_tests/src/inline_assigned_payload_lib.res @@ -37,3 +37,51 @@ let nullableBeforeAssign = (n: int, q: Nullable.t, q2: Nullable.t "none" } } + +module type S = { + let x: string +} + +module A = { + let x = "a" +} + +module B = { + let x = "b" +} + +// The field [M.x] in [t] must be read from the module [s] holds before the +// loop. +@inline +let moduleFieldBeforeAssign = (n: int, q: module(S), q2: module(S)) => { + let s = ref(q) + let t = ( + { + let module(M) = s.contents + M.x + }, + 1, + ) + for _ in 0 to n { + s := q2 + } + let (a, _) = t + let module(M2) = s.contents + (a, M2.x) +} + +let get = (m: module(S)) => { + let module(M) = m + M.x +} + +// [a] must be read before the loop. +@inline +let getBeforeAssign = (n: int, q: module(S), q2: module(S)) => { + let s = ref(q) + let a = get(s.contents) + for _ in 0 to n { + s := q2 + } + (a, get(s.contents)) +} diff --git a/tests/compiler_tests/src/inline_assigned_payload_test.mjs b/tests/compiler_tests/src/inline_assigned_payload_test.mjs index 13da510c82..a933469f36 100644 --- a/tests/compiler_tests/src/inline_assigned_payload_test.mjs +++ b/tests/compiler_tests/src/inline_assigned_payload_test.mjs @@ -3,6 +3,7 @@ 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 Inline_assigned_payload_lib from "./inline_assigned_payload_lib.mjs"; function someBeforeAssign() { let s = "a"; @@ -41,48 +42,76 @@ function nullableBeforeAssign() { } } +function moduleFieldBeforeAssign() { + let s = Inline_assigned_payload_lib.A; + let t_0 = s.x; + for (let _for = 0; _for <= 3; ++_for) { + s = Inline_assigned_payload_lib.B; + } + let M2 = s; + return [ + t_0, + M2.x + ]; +} + +function getBeforeAssign() { + let s = Inline_assigned_payload_lib.A; + let a = s.x; + for (let _for = 0; _for <= 3; ++_for) { + s = Inline_assigned_payload_lib.B; + } + return [ + a, + s.x + ]; +} + +function someLate(n, q) { + let s = q; + let o = Primitive_option.some(s); + for (let _for = 0; _for <= n; ++_for) { + s = "b"; + } + return [ + Primitive_option.valFromOption(o), + s + ]; +} + Mocha.describe("Inline_assigned_payload_test", () => { - Mocha.test("the payload of a Some, made before its variable is assigned", () => { - let s = "a"; - let o = Primitive_option.some(s); - for (let _for = 0; _for <= 3; ++_for) { - s = "b"; - } - Test_utils.eq("File \"inline_assigned_payload_test.res\", line 15, characters 7-14", [ - "a", - "b" - ], [ - Primitive_option.valFromOption(o), - s - ]); - }); - Mocha.test("the field of a tuple, made before its variable is assigned", () => { - let s = "a"; - let t_0 = s; - for (let _for = 0; _for <= 3; ++_for) { - s = "b"; - } - Test_utils.eq("File \"inline_assigned_payload_test.res\", line 19, characters 7-14", [ - "a", - "b" - ], [ - t_0, - s - ]); - }); - Mocha.test("a nullable converted to an option before its variable is assigned", () => { - let s = "a"; - let o = s; - for (let _for = 0; _for <= 3; ++_for) { - s = null; - } - Test_utils.eq("File \"inline_assigned_payload_test.res\", line 23, characters 7-14", "a", o == null ? "none" : o); - }); + Mocha.test("the payload of a Some, made before its variable is assigned", () => Test_utils.eq("File \"inline_assigned_payload_test.res\", line 30, characters 7-14", [ + "a", + "b" + ], someBeforeAssign())); + Mocha.test("the field of a tuple, made before its variable is assigned", () => Test_utils.eq("File \"inline_assigned_payload_test.res\", line 34, characters 7-14", [ + "a", + "b" + ], tupleBeforeAssign())); + Mocha.test("a nullable converted to an option before its variable is assigned", () => Test_utils.eq("File \"inline_assigned_payload_test.res\", line 38, characters 7-14", "a", nullableBeforeAssign())); + Mocha.test("a module field, read before its variable is assigned", () => Test_utils.eq("File \"inline_assigned_payload_test.res\", line 42, characters 7-14", [ + "a", + "b" + ], moduleFieldBeforeAssign())); + Mocha.test("a module field bound to a variable before its variable is assigned", () => Test_utils.eq("File \"inline_assigned_payload_test.res\", line 46, characters 7-14", [ + "a", + "b" + ], getBeforeAssign())); + Mocha.test("the payload of a Some, inlined while compiling to JavaScript", () => Test_utils.eq("File \"inline_assigned_payload_test.res\", line 50, characters 7-14", [ + "a", + "b" + ], someLate(3, "a"))); }); +let Lib; + export { + Lib, someBeforeAssign, tupleBeforeAssign, nullableBeforeAssign, + moduleFieldBeforeAssign, + getBeforeAssign, + someLate, } /* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_assigned_payload_test.res b/tests/compiler_tests/src/inline_assigned_payload_test.res index bbe6660d5e..29775dfcbe 100644 --- a/tests/compiler_tests/src/inline_assigned_payload_test.res +++ b/tests/compiler_tests/src/inline_assigned_payload_test.res @@ -1,14 +1,29 @@ -// A [Some] or a tuple made from a variable that is assigned later must keep -// the value the variable had when it was made. +// A [Some], a tuple or a module field made from a variable that is assigned +// later must keep the value the variable had when it was made. open Mocha open Test_utils -let someBeforeAssign = () => Inline_assigned_payload_lib.someBeforeAssign(3, "a", "b") +module Lib = Inline_assigned_payload_lib -let tupleBeforeAssign = () => Inline_assigned_payload_lib.tupleBeforeAssign(3, "a", "b") +@inline(never) +let someBeforeAssign = () => Lib.someBeforeAssign(3, "a", "b") -let nullableBeforeAssign = () => - Inline_assigned_payload_lib.nullableBeforeAssign(3, Nullable.make("a"), Nullable.null) +@inline(never) +let tupleBeforeAssign = () => Lib.tupleBeforeAssign(3, "a", "b") + +@inline(never) +let nullableBeforeAssign = () => Lib.nullableBeforeAssign(3, Nullable.make("a"), Nullable.null) + +@inline(never) +let moduleFieldBeforeAssign = () => Lib.moduleFieldBeforeAssign(3, module(Lib.A), module(Lib.B)) + +@inline(never) +let getBeforeAssign = () => Lib.getBeforeAssign(3, module(Lib.A), module(Lib.B)) + +// With parameters as arguments, the bodies are inlined while compiling to +// JavaScript. +@inline(never) +let someLate = (n, q) => Lib.someBeforeAssign(n, q, "b") describe(__MODULE__, () => { test("the payload of a Some, made before its variable is assigned", () => { @@ -22,4 +37,16 @@ describe(__MODULE__, () => { test("a nullable converted to an option before its variable is assigned", () => { eq(__LOC__, "a", nullableBeforeAssign()) }) + + test("a module field, read before its variable is assigned", () => { + eq(__LOC__, ("a", "b"), moduleFieldBeforeAssign()) + }) + + test("a module field bound to a variable before its variable is assigned", () => { + eq(__LOC__, ("a", "b"), getBeforeAssign()) + }) + + test("the payload of a Some, inlined while compiling to JavaScript", () => { + eq(__LOC__, Some(("a", "b")), someLate(3, "a")) + }) })