Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/inline-functions-across-modules.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Inline `@inline` functions in the modules that use them too, not only in their own module, and mark `Option.map`, `flatMap`, `getOr`, `mapOr`, `orElse`, `filter`, `forEach`, `isSome` and `isNone` as `@inline`, so calls to them compile to the code they run. This applies to functions defined at the top level of a module.
3 changes: 3 additions & 0 deletions compiler/backend/js_cmj_format.ml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ let get_result mid_val =
(Const_js_null | Const_js_undefined _ | Const_js_true | Const_js_false))
| None ->
mid_val
(* Stored because the function is [@inline]: inlined with or without
-bs-cross-module-opt. *)
| Some (Lfunction {attr = {inline = Always_inline; _}; _}) -> mid_val
| Some _ ->
if !((Js_config.current ()).cross_module_inline) then mid_val
else {mid_val with persistent_closed_lambda = None}
Expand Down
14 changes: 11 additions & 3 deletions compiler/backend/js_pass_external_shadow.ml
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,17 @@ let imported_modules (js : J.program) =
self.program self js;
!names

let program (js : J.program) : J.program =
(* printed names of the bindings in scope at the current point *)
let in_scope = ref (imported_modules js) in
let program ~(imports : J.module_id list) (js : J.program) : J.program =
(* printed names of the bindings in scope at the current point. [imports]
are the modules imported for their side effects, which the program may
name nowhere, as when every use of them was inlined. *)
let in_scope =
ref
(List.fold_left
(fun names (m : J.module_id) ->
if m.dynamic_import then names else add_binding m.id names)
(imported_modules js) imports)
in
let with_bindings add f =
let outer = !in_scope in
in_scope := add outer;
Expand Down
2 changes: 1 addition & 1 deletion compiler/backend/js_pass_external_shadow.mli
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)

(* Rewrite to using globalThis when shadowing would break @val/@scope globals. *)
val program : J.program -> J.program
val program : imports:J.module_id list -> J.program -> J.program
15 changes: 10 additions & 5 deletions compiler/backend/lam_compile_env.ml
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,16 @@ let is_pure_module (oid : Lam_module_ident.t) =
| Some (Ml {cmj_table}) -> cmj_table.pure
| Some (External _) -> false)

let populate_required_modules extras
(hard_dependencies : unit Lam_module_ident.Hash_set.t) =
let side_effect_modules extras =
let modules = ref [] in
Lam_module_ident.Hash.iter
(fun id _ -> if not (is_pure_module id) then add hard_dependencies id)
(fun id _ -> if not (is_pure_module id) then modules := id :: !modules)
(cached_tbl ());
Lam_module_ident.Hash_set.iter
(fun id () -> if not (is_pure_module id) then add hard_dependencies id)
extras
(fun id () -> if not (is_pure_module id) then modules := id :: !modules)
extras;
!modules

let populate_required_modules extras
(hard_dependencies : unit Lam_module_ident.Hash_set.t) =
List.iter (add hard_dependencies) (side_effect_modules extras)
6 changes: 6 additions & 0 deletions compiler/backend/lam_compile_env.mli
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,9 @@ val get_package_info_from_cmj :
*)
val populate_required_modules :
unit Lam_module_ident.Hash_set.t -> unit Lam_module_ident.Hash_set.t -> unit

(* The modules [populate_required_modules extras] adds: the ones with side
effects, which are imported even when the generated code names none of
their values, as when all uses were inlined. *)
val side_effect_modules :
unit Lam_module_ident.Hash_set.t -> Lam_module_ident.t list
3 changes: 3 additions & 0 deletions compiler/backend/lam_compile_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,9 @@ let compile ?on_optimized_lambda (output_prefix : string)
(* After the passes that add bindings, so that a JS global read in one of
them, as in [let t_0 = t_0], is not captured by the binding *)
|> Js_pass_external_shadow.program
~imports:
(if !((Js_config.current ()).all_module_aliases) then []
else Lam_compile_env.side_effect_modules may_required_modules)
|> j "external_shadow"
|> (fun js ->
ignore @@ Js_pass_scope.program js;
Expand Down
43 changes: 20 additions & 23 deletions compiler/backend/lam_stats_export.ml
Original file line number Diff line number Diff line change
Expand Up @@ -72,34 +72,32 @@ let values_of_export (meta : Lam_stats.t) (export_map : Lambda.t Map_ident.t) :
| Const_js_false ))
| None ->
optlam
| Some lambda ->
if not !((Js_config.current ()).cross_module_inline) then None
else if calls_relative_external lambda then None
else if
Lam_analysis.safe_to_inline lambda
(* when inlning a non function, we have to be very careful,
only truly immutable values can be inlined
*)
then
| Some lambda -> (
if calls_relative_external lambda then None
else
match lambda with
| Lfunction {attr = {inline = Always_inline}}
(* FIXME: is_closed lambda is too restrictive
It precludes ues cases
- inline forEach but not forEachU
*)
| Lfunction {attr = {is_a_functor = true}} ->
if Lam_closure.is_closed lambda (* TODO: seriealize more*) then
optlam
| Lfunction ({attr = {inline = Always_inline}} as fn) ->
(* An [@inline] function or functor: other modules inline its
body too, with or without -bs-cross-module-opt, when they
can. It must be closed, since the body is copied without
its environment. *)
if
Lambda.lfunction_can_be_inlined fn
&& Lam_closure.is_closed lambda
then optlam
else None
| _ when not !((Js_config.current ()).cross_module_inline) -> None
| _ when not (Lam_analysis.safe_to_inline lambda) ->
(* when inlining a non function, we have to be very careful,
only truly immutable values can be inlined *)
None
| Lfunction {attr = {is_a_functor = true}} ->
if Lam_closure.is_closed lambda then optlam else None
| _ ->
let lam_size =
Lam_analysis.size_upto ~limit:Lam_analysis.small_inline_size
lambda
in
(* TODO:
1. global need re-assocate when do the beta reduction
2. [lambda_exports] is not precise
*)
let free_variables =
Lam_closure.free_variables Set_ident.empty Map_ident.empty
lambda
Expand All @@ -110,8 +108,7 @@ let values_of_export (meta : Lam_stats.t) (export_map : Lambda.t Map_ident.t) :
then (
Ir_log.dwarn ~__POS__ "%s recorded for inlining @." x.name;
optlam)
else None
else None
else None)
in
match (arity, persistent_closed_lambda) with
| Single Arity_na, (None | Some (Lconst Const_module_alias)) -> acc
Expand Down
9 changes: 9 additions & 0 deletions packages/@rescript/runtime/Stdlib_Option.res
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
*/
type t<'a> = option<'a> = None | Some('a)

@inline
let filter = (opt, p) =>
switch opt {
| Some(x) as option if p(x) => option
| _ => None
}

@inline
let forEach = (opt, f) =>
switch opt {
| Some(x) => f(x)
Expand All @@ -31,42 +33,49 @@ let getOrThrow = (x, ~message=?) =>

external getUnsafe: option<'a> => 'a = "%identity"

@inline
let mapOr = (opt, default, f) =>
switch opt {
| Some(x) => f(x)
| None => default
}

@inline
let map = (opt, f) =>
switch opt {
| Some(x) => Some(f(x))
| None => None
}

@inline
let flatMap = (opt, f) =>
switch opt {
| Some(x) => f(x)
| None => None
}

@inline
let getOr = (opt, default) =>
switch opt {
| Some(x) => x
| None => default
}

@inline
let orElse = (opt, other) =>
switch opt {
| Some(_) as some => some
| None => other
}

@inline
let isSome = x =>
switch x {
| Some(_) => true
| None => false
}

@inline
let isNone = x => x == None

let equal = (a, b, eq) =>
Expand Down
9 changes: 4 additions & 5 deletions tests/belt_tests/src/bs_stack_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@

import * as Mocha from "mocha";
import * as Test_utils from "./test_utils.mjs";
import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs";
import * as Belt_MutableQueue from "@rescript/belt/src/Belt_MutableQueue.mjs";
import * as Belt_MutableStack from "@rescript/belt/src/Belt_MutableStack.mjs";

function inOrder(v) {
let current = v;
let s = Belt_MutableStack.make();
let q = Belt_MutableQueue.make();
while (Stdlib_Option.isSome(current)) {
while (current !== undefined) {
let v$1 = current;
Belt_MutableStack.push(s, v$1);
current = v$1.left;
Expand All @@ -20,7 +19,7 @@ function inOrder(v) {
let v$2 = current;
Belt_MutableQueue.add(q, v$2.value);
current = v$2.right;
while (Stdlib_Option.isSome(current)) {
while (current !== undefined) {
let v$3 = current;
Belt_MutableStack.push(s, v$3);
current = v$3.left;
Expand All @@ -33,15 +32,15 @@ function inOrder3(v) {
let current = v;
let s = Belt_MutableStack.make();
let q = Belt_MutableQueue.make();
while (Stdlib_Option.isSome(current)) {
while (current !== undefined) {
let v$1 = current;
Belt_MutableStack.push(s, v$1);
current = v$1.left;
};
Belt_MutableStack.dynamicPopIter(s, popped => {
Belt_MutableQueue.add(q, popped.value);
let current = popped.right;
while (Stdlib_Option.isSome(current)) {
while (current !== undefined) {
let v = current;
Belt_MutableStack.push(s, v);
current = v.left;
Expand Down
2 changes: 2 additions & 0 deletions tests/build_tests/projects/inline_function_rebuild/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
lib
src/**/*.mjs
33 changes: 33 additions & 0 deletions tests/build_tests/projects/inline_function_rebuild/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// @ts-check

// Without -bs-cross-module-opt, B inlines A's @inline function, and is
// compiled again when that body changes although A's interface does not.

import * as assert from "node:assert";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { setup } from "#dev/process";

const { execBuildOrThrow, execClean } = setup(import.meta.dirname);
const source = path.join(import.meta.dirname, "src", "A.res");
const output = path.join(import.meta.dirname, "src", "B.mjs");
const original = await fs.readFile(source, "utf8");

await execClean();
try {
await execBuildOrThrow();
assert.match(await fs.readFile(output, "utf8"), /let result = 2;/);

// Same line, same type: only A's .cmj changes.
await fs.writeFile(source, original.replace("x + 1", "x + 2"));
await execBuildOrThrow();
assert.match(await fs.readFile(output, "utf8"), /let result = 3;/);

// Without @inline, B calls the function.
await fs.writeFile(source, original.replace("@inline\n", ""));
await execBuildOrThrow();
assert.match(await fs.readFile(output, "utf8"), /A\.bump\(1\)/);
} finally {
await fs.writeFile(source, original);
await execClean();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "inline_function_rebuild",
"sources": { "dir": "src" },
"package-specs": { "module": "esmodule", "in-source": true },
"suffix": ".mjs",
"warnings": { "error": true }
}
2 changes: 2 additions & 0 deletions tests/build_tests/projects/inline_function_rebuild/src/A.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@inline
let bump = x => x + 1
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
let result = A.bump(1)
33 changes: 32 additions & 1 deletion tests/ounit_tests/ounit_external_shadow_tests.ml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,31 @@ let switch_on_global () =
export_set = Set_ident.empty;
}
in
Js_pass_external_shadow.program program
Js_pass_external_shadow.program ~imports:[] program

(* [f(<global g>)] in a module that imports a module printed as [g], with
[dynamic_import] as given, which no expression names. *)
let read_global_with_import ~dynamic_import =
let program : J.program =
{
block =
[
statement
(Exp
(E.call ~info:Js_call_info.na_full_call (E.js_global "f")
[E.js_global "g"]));
];
exports = [];
export_set = Set_ident.empty;
}
in
let import =
Lam_module_ident.of_ml ~dynamic_import (Ident.create_persistent "g")
in
match Js_pass_external_shadow.program ~imports:[import] program with
| {block = [{statement_desc = Exp {expression_desc = Call (_, [arg], _)}}]} ->
arg
| _ -> OUnit.assert_failure "unexpected program shape"

let is_global_read (e : J.expression) =
match e.expression_desc with
Expand Down Expand Up @@ -60,4 +84,11 @@ let suites =
(List.exists is_global_this_read args)
| _ -> OUnit.assert_failure "unexpected case body")
| _ -> OUnit.assert_failure "unexpected program shape" );
( "a module imported only for its side effects is a binding in scope"
>:: fun _ ->
OUnit.assert_bool "the read goes through globalThis"
(is_global_this_read
(read_global_with_import ~dynamic_import:false));
OUnit.assert_bool "a dynamic import declares no binding"
(is_global_read (read_global_with_import ~dynamic_import:true)) );
]
4 changes: 2 additions & 2 deletions tests/tests/src/flat_make_export_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import * as Mocha from "mocha";
import * as Test_utils from "./test_utils.mjs";
import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.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", () => {
Expand All @@ -22,7 +22,7 @@ Mocha.describe("Flat_make_export_test", () => {
Test_utils.eq("File \"flat_make_export_test.res\", line 23, characters 7-14", Flat_make_export_use.nested, "nested");
Test_utils.eq("File \"flat_make_export_test.res\", line 24, characters 7-14", Flat_make_export_use.recursive, "recursive");
Test_utils.eq("File \"flat_make_export_test.res\", line 25, characters 7-14", Flat_make_export_use.coerced, "coerced");
Test_utils.eq("File \"flat_make_export_test.res\", line 26, characters 7-14", Stdlib_Option.map(Flat_make_export_use.rebound, f => f()), "rebound");
Test_utils.eq("File \"flat_make_export_test.res\", line 26, characters 7-14", Flat_make_export_use.rebound !== undefined ? Primitive_option.some(Primitive_option.valFromOption(Flat_make_export_use.rebound)()) : undefined, "rebound");
Test_utils.eq("File \"flat_make_export_test.res\", line 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");
Expand Down
32 changes: 32 additions & 0 deletions tests/tests/src/inline_export.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as Stdlib_JsExn from "@rescript/runtime/lib/es6/Stdlib_JsExn.mjs";
import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.mjs";

function apply(value, f) {
return f(value);
}

function ordinary(value, f) {
return f(value);
}

function catchMessage(f) {
try {
return f();
} catch (raw_e) {
let e = Primitive_exceptions.internalToException(raw_e);
if (e.RE_EXN_ID === "JsExn") {
return Stdlib_JsExn.message(e._1);
} else {
return;
}
}
}

export {
apply,
ordinary,
catchMessage,
}
/* Stdlib_JsExn Not a pure module */
Loading
Loading