Skip to content
Open
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/cross-module-inline-option.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Allow selected functions to opt into cross-module inlining with `@inline(crossModule)` and inline common `Option` helpers in application code.
1 change: 1 addition & 0 deletions compiler/core/js_cmj_format.ml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ let get_result mid_val =
(Const_js_null | Const_js_undefined _ | Const_js_true | Const_js_false))
| None ->
mid_val
| Some (Lfunction f) when f.attr.inline = Cross_module_inline -> mid_val
| Some _ ->
if !((Js_config.current ()).cross_module_inline) then mid_val
else {mid_val with persistent_closed_lambda = None}
Expand Down
5 changes: 2 additions & 3 deletions compiler/core/js_cmj_format.mli
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,8 @@ val single_na : arity

val from_file : string -> t

(*
Note writing the file if its content is not changed
*)
(* Write the .cmj. Unchanged files are not rewritten when [check_exists] is
true, so Rewatch can use changes to this file to invalidate callers. *)
val to_file : string -> check_exists:bool -> t -> unit

type cmj_load_info = {cmj_table: t}
2 changes: 1 addition & 1 deletion compiler/core/lam_analysis.ml
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ let destruct_pattern (body : Lambda.t) params args =
(** Hints to inlining *)
let ok_to_inline_fun_when_app (m : Lambda.lfunction) (args : Lambda.t list) =
match m.attr.inline with
| Always_inline -> true
| Always_inline | Cross_module_inline -> true
| Never_inline -> false
| Default_inline -> (
match m with
Expand Down
6 changes: 5 additions & 1 deletion compiler/core/lam_closure.ml
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,11 @@ let free_variables (export_idents : Set_ident.t) (params : stats Map_ident.t)
iter sink_pos e1;
local_add_list vars;
iter sink_pos e2
| Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) ->
| Ltrywith (e1, exn, e2) ->
iter top e1;
local_add exn;
iter sink_pos e2
| Ltryfinally (e1, e2) ->
iter top e1;
iter sink_pos e2
| Lifthenelse (e1, e2, e3) ->
Expand Down
13 changes: 13 additions & 0 deletions compiler/core/lam_stats_export.ml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@ let values_of_export (meta : Lam_stats.t) (export_map : Lambda.t Map_ident.t) :
| Const_js_false ))
| None ->
optlam
| Some
(Lfunction
({attr = {inline = Cross_module_inline}; loc} as lfunction) as
lambda) ->
if not (Lambda.lfunction_can_be_inlined lfunction) then
Location.raise_errorf ~loc
"@inline(crossModule) cannot be used on an async or directed \
function"
else if not (Lam_closure.is_closed lambda) then
Location.raise_errorf ~loc
"@inline(crossModule) requires a function without captured local \
values"
Comment thread
cknitt marked this conversation as resolved.
Resolved
else optlam
| Some lambda ->
if not !((Js_config.current ()).cross_module_inline) then None
else if
Expand Down
1 change: 1 addition & 0 deletions compiler/ml/lambda.ml
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ type inline_attribute =
| Always_inline (* [@inline] or [@inline always] *)
| Never_inline (* [@inline never] *)
| Default_inline (* no [@inline] attribute *)
| Cross_module_inline (* [@inline(crossModule)] *)

type let_kind = Strict | Alias | StrictOpt | Variable

Expand Down
1 change: 1 addition & 0 deletions compiler/ml/lambda.mli
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ type inline_attribute =
| Always_inline (* [@inline] or [@inline always] *)
| Never_inline (* [@inline never] *)
| Default_inline (* no [@inline] attribute *)
| Cross_module_inline (* [@inline(crossModule)] *)

type let_kind = Strict | Alias | StrictOpt | Variable
(* Meaning of kinds for let x = e in e':
Expand Down
1 change: 1 addition & 0 deletions compiler/ml/printlambda.ml
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ let function_attribute ppf {inline; is_a_functor; return_unit} =
match inline with
| Default_inline -> ()
| Always_inline -> fprintf ppf "always_inline@ "
| Cross_module_inline -> fprintf ppf "cross_module_inline@ "
| Never_inline -> fprintf ppf "never_inline@ "

let rec lam ppf = function
Expand Down
13 changes: 6 additions & 7 deletions compiler/ml/translattribute.ml
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,20 @@ let parse_inline_attribute (attr : t option) : Lambda.inline_attribute =
| Some ({txt; loc}, payload) -> (
let open Parsetree in
(* the 'inline' attribute can be used as
[@inline], [@inline never] or [@inline always].
[@inline], [@inline never], [@inline always] or
[@inline(crossModule)].
[@inline] is equivalent to [@inline always] *)
let warning txt =
Warnings.Attribute_payload
(txt, "It must be either empty, 'always' or 'never'")
(txt, "It must be empty, 'always', 'never' or 'crossModule'")
in
match payload with
| PStr [] -> Always_inline
| PStr [{pstr_desc = Pstr_eval (expression, [])}] -> (
match (Ast_payload.unwrap_braces expression).pexp_desc with
| Pexp_ident {txt = Longident.Lident "never"} -> Never_inline
| Pexp_ident {txt = Longident.Lident "always"} -> Always_inline
| Pexp_ident {txt = Longident.Lident "crossModule"} -> Cross_module_inline
| _ ->
Location.prerr_warning loc (warning txt);
Default_inline)
Expand All @@ -62,14 +64,11 @@ let add_inline_attribute (expr : Lambda.t) loc attributes =
| Lfunction ({attr} as funct), inline ->
(match attr.inline with
| Default_inline -> ()
| Always_inline | Never_inline ->
| Always_inline | Cross_module_inline | Never_inline ->
Location.prerr_warning loc (Warnings.Duplicated_attribute "inline"));
let attr = {attr with inline} in
Lambda.function_ ~loc:funct.loc ~attr ~params:funct.params ~body:funct.body
| expr, Always_inline ->
Location.prerr_warning loc (Warnings.Misplaced_attribute "inline");
expr
| expr, Never_inline ->
| expr, (Always_inline | Cross_module_inline | Never_inline) ->
Location.prerr_warning loc (Warnings.Misplaced_attribute "inline");
expr

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(crossModule)
let filter = (opt, p) =>
switch opt {
| Some(x) as option if p(x) => option
| _ => None
}

@inline(crossModule)
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(crossModule)
let mapOr = (opt, default, f) =>
switch opt {
| Some(x) => f(x)
| None => default
}

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

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

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

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

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

@inline(crossModule)
let isNone = x => x == None

let equal = (a, b, eq) =>
Expand Down
15 changes: 8 additions & 7 deletions rewatch-ocaml/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,14 @@ there directly; dependencies are on its include path as their

- Freshness is timestamp-based: an AST newer than its source is current, a
`.cmt` records the last compile, and a `.cmi` the last change of an
interface.
- ASTs, interfaces and typed trees are held in memory until their request
finished (`Build_file_store.set_held_writes`), so a failed request leaves
the previous AST and interface on disk. An interface is written only when
it changed, which keeps the modification time that dependents compare
with, and before the typed tree that marks the module compiled, so a build
killed in between compiles the module again. A failed compile publishes its
interface or of its `.cmj`: dependents also inline what a `.cmj`
exports, which can change without the interface.
- ASTs, interfaces, `.cmj` files and typed trees are held in memory until
their request finished (`Build_file_store.set_held_writes`), so a failed
request leaves the previous AST and interface on disk. An interface is
written only when it changed, which keeps the modification time that
dependents compare with, and before the typed tree that marks the module
compiled, so a build killed in between compiles the module again. A failed compile publishes its
partial typed tree for editor tooling after dating its AST back.
- Published files are renamed into place, so neither a reader nor a killed
build sees part of one. On Windows the rename fails while an editor has the
Expand Down
68 changes: 39 additions & 29 deletions rewatch-ocaml/compiler_process.ml
Original file line number Diff line number Diff line change
Expand Up @@ -112,16 +112,16 @@ let run_tasks ?poll ?on_complete tasks =

let run_requests requests = requests |> List.map task |> run_tasks

(* A request writes its ASTs, interfaces and typed trees into the artifact
directory that later requests and builds read. They are held in memory
(* A request writes its ASTs, interfaces, .cmj files and typed trees into the
artifact directory that later requests and builds read. They are held in memory
until the request finished (Build_file_store.set_held_writes, which the
build installs with this predicate), so a failed request leaves the
previous AST and interface on disk, and a build killed before it published
an interface leaves the typed tree that marks its module compiled stale. *)
let is_held path =
List.exists
(Filename.check_suffix path)
[".ast"; ".iast"; ".cmi"; ".cmt"; ".cmti"]
[".ast"; ".iast"; ".cmi"; ".cmj"; ".cmt"; ".cmti"]

(* Renamed into place, so that neither a reader nor a build killed while
writing sees part of a file. On Windows the rename fails while another
Expand Down Expand Up @@ -174,7 +174,16 @@ let run_parses ?poll ?on_complete parses =
result))
|> run_tasks ?poll ?on_complete

type compiler_artifact = Cmi | Required of string | Typed_tree of string
type compiler_artifact = Cmi | Cmj | Typed_tree of string

(* Publishes a held interface or .cmj only when it changed, and tells whether
it did. The compiler does not write one identical to the file on disk
(Cmi_format.create_cmi, Js_cmj_format.to_file). *)
let publish_if_changed path =
try Build_file_store.publish_held ~if_changed:true ~write:write_held path
with Not_found ->
if Build_file_store.exists path then false
else raise (Unix.Unix_error (Unix.ENOENT, "open", path))

(* A typed tree marks its module compiled, so it is published last. Not every
compile writes one (-bs-no-bin-annot). *)
Expand All @@ -197,26 +206,28 @@ let publish_compiler_artifacts ~artifact_dir ~basename artifacts =
(fun artifact ->
match artifact with
| Cmi ->
let path = Filename.concat artifact_dir (basename ^ ".cmi") in
let changed =
try
Build_file_store.publish_held ~if_changed:true ~write:write_held
path
with Not_found ->
(* The compiler does not write an interface identical to the
one on disk (Cmi_format.create_cmi). *)
if Build_file_store.exists path then false
else raise (Unix.Unix_error (Unix.ENOENT, "open", path))
in
cmi_change :=
if changed then Compiler_scheduler.Cmi_changed
if
publish_if_changed
(Filename.concat artifact_dir (basename ^ ".cmi"))
then Compiler_scheduler.Cmi_changed
else Compiler_scheduler.Cmi_unchanged
| Required extension ->
let path =
Filename.concat artifact_dir (basename ^ "." ^ extension)
in
if not (Build_file_store.exists path) then
raise (Unix.Unix_error (Unix.ENOENT, "open", path))
| Cmj -> (
(* Dependents also inline what the .cmj exports, which can change
without the interface. The interface's modification time then
records the change too, which a later build compares with. *)
match
( publish_if_changed
(Filename.concat artifact_dir (basename ^ ".cmj")),
!cmi_change )
with
| true, Compiler_scheduler.Cmi_changed -> ()
| true, (Compiler_scheduler.Cmi_unchanged | Cmi_change_unknown) ->
Unix.utimes (Filename.concat artifact_dir (basename ^ ".cmi")) 0. 0.;
cmi_change := Compiler_scheduler.Cmi_changed
| false, Compiler_scheduler.Cmi_change_unknown ->
cmi_change := Compiler_scheduler.Cmi_unchanged
| false, (Compiler_scheduler.Cmi_changed | Cmi_unchanged) -> ())
| Typed_tree extension ->
publish_typed_tree
(Filename.concat artifact_dir (basename ^ "." ^ extension)))
Expand Down Expand Up @@ -285,13 +296,13 @@ let namespace_task ~runtime ~artifact_dir ~entry ~package_dirty ~force namespace
(fun extension ->
Build_file_store.forget
(Filename.concat artifact_dir (namespace ^ extension)))
[".cmi"; ".cmt"];
[".cmi"; ".cmj"; ".cmt"];
raise
(Compiler_scheduler.Build_failure
(result.Process.stderr ^ result.stdout)));
let cmi_change =
publish_compiler_artifacts ~artifact_dir ~basename:namespace
[Cmi; Required "cmj"; Typed_tree "cmt"]
[Cmi; Cmj; Typed_tree "cmt"]
in
Compiler_scheduler.{stderr = result.stderr; cmi_change});
})
Expand Down Expand Up @@ -340,6 +351,7 @@ let discard_compile ~artifact_dir ~(config : Config.t) path =
(Source.compiler_asset_basename config path ^ extension)
in
Build_file_store.forget (artifact ".cmi");
Build_file_store.forget (artifact ".cmj");
(try
Build_artifacts.invalidate_ast
(Build_artifacts.ast_path ~artifact_dir path)
Expand Down Expand Up @@ -367,13 +379,11 @@ let publish ~artifact_dir ~is_local ~(config : Config.t) ~has_interface
| Source.Implementation when has_interface ->
(* The implementation is compiled with -bs-read-cmi, so its .cmi is
the one published after compiling the interface. *)
ignore
(publish_compiler_artifacts ~artifact_dir ~basename
[Required "cmj"; Typed_tree "cmt"]);
Compiler_scheduler.Cmi_unchanged
publish_compiler_artifacts ~artifact_dir ~basename
[Cmj; Typed_tree "cmt"]
| Source.Implementation ->
publish_compiler_artifacts ~artifact_dir ~basename
[Cmi; Required "cmj"; Typed_tree "cmt"]);
[Cmi; Cmj; Typed_tree "cmt"]);
(* The parse and the typed tree's source digest read the source through
the store. *)
List.iter Build_file_store.evict
Expand Down
8 changes: 6 additions & 2 deletions scripts/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,12 @@ if (mochaTest) {
const beltPackageDir = path.join(projectDir, "packages/@rescript/belt");
const beltTestDir = path.join(projectDir, "tests/belt_tests");

// No need to clean beforehand, rewatch detects changes to the compiler binary
// and rebuilds automatically in that case.
// The runtime is built before this test project. Its inline exports can change
// without changing the compiler binary, so regenerate checked-in JS snapshots.
await execClean([], {
cwd: compilerTestDir,
stdio: "inherit",
});
await execBuild([], {
cwd: compilerTestDir,
stdio: "inherit",
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
Loading
Loading