From ccb241867aac5300283c3f8e113273c6ed224251 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 18:58:22 +0000 Subject: [PATCH] Inline functions marked @inline(crossModule) across modules Why: Calls to small stdlib helpers such as `Option.map` stay calls into `Stdlib_Option` unless the whole build enables cross-module optimization. `@inline(crossModule)` marks a closed function whose body the .cmj exports, so other modules inline its calls as they would a local function. Option's forEach, map, flatMap, filter, mapOr, getOr, orElse, isSome and isNone use it. JS modified (Option helper calls): Example: let bign = BigInt.fromFloat(Number.MAX_VALUE)->Option.getOr(0n) Before (js): let bign = Stdlib_Option.getOr(Stdlib_BigInt.fromFloat(Number.MAX_VALUE), 0n); After (js): let opt = Stdlib_BigInt.fromFloat(Number.MAX_VALUE); let bign = opt !== undefined ? Primitive_option.valFromOption(opt) : 0n; Diagnostic modified (@inline payload): Example: @inline(sometimes) let f = x => x Before (diagnostic): illegal payload for attribute @inline. It must be either empty, 'always' or 'never' After (diagnostic): illegal payload for attribute @inline. It must be empty, 'always', 'never' or 'crossModule' An async or directed function, or one capturing local values, is rejected with an error. The build system recompiles dependents when a module's .cmj changes, not only its .cmi, since an inline body can change without its type: during a build when the published .cmj differs, and on startup when a dependency's .cmi or .cmj is newer than the dependent's .cmt. Review: Does every implementation change now recompile dependents? Only those whose .cmj bytes change. Review: Why does Lam_closure.free_variables change? Its `Ltrywith` case never bound the exception, so a function whose `catch` reads it counted as capturing a local value and was rejected. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKsWykY6KH4QSJ9Wrs Signed-off-by: Christoph Knittel --- changes/cross-module-inline-option.feature.md | 1 + compiler/core/js_cmj_format.ml | 1 + compiler/core/js_cmj_format.mli | 5 +- compiler/core/lam_analysis.ml | 2 +- compiler/core/lam_closure.ml | 6 +- compiler/core/lam_stats_export.ml | 13 ++ compiler/ml/lambda.ml | 1 + compiler/ml/lambda.mli | 1 + compiler/ml/printlambda.ml | 1 + compiler/ml/translattribute.ml | 13 +- packages/@rescript/runtime/Stdlib_Option.res | 9 + rewatch-ocaml/README.md | 7 +- rewatch-ocaml/build_state.ml | 3 +- rewatch-ocaml/build_state.mli | 1 + rewatch-ocaml/compile_assets.ml | 15 +- rewatch-ocaml/compile_assets.mli | 8 + rewatch-ocaml/compiler_process.ml | 64 ++++--- rewatch-ocaml/module_graph.ml | 6 +- scripts/test.js | 8 +- tests/belt_tests/src/bs_stack_test.mjs | 9 +- .../build_tests/cross_module_inline/input.js | 35 ++++ .../cross_module_inline/rescript.json | 5 + .../build_tests/cross_module_inline/src/A.res | 2 + .../build_tests/cross_module_inline/src/B.res | 1 + .../.gitignore | 2 + .../input.js | 41 ++++ .../node_modules/inline-exporter/package.json | 1 + .../inline-exporter/rescript.json | 5 + .../inline-exporter/src/Exporter.res | 2 + .../rescript.json | 6 + .../src/B.res | 1 + .../warning_47_attribute_payload.res.expected | 2 +- .../compile_assets_tests.ml | 14 ++ .../tests/src/cross_module_inline_export.mjs | 32 ++++ .../tests/src/cross_module_inline_export.res | 11 ++ .../src/cross_module_inline_opt_in_test.mjs | 175 ++++++++++++++++++ .../src/cross_module_inline_opt_in_test.res | 77 ++++++++ tests/tests/src/flat_make_export_test.mjs | 4 +- tests/tests/src/int_overflow_test.mjs | 12 +- tests/tests/src/stdlib/Stdlib_ObjectTests.mjs | 22 ++- tests/tests/src/stdlib/Stdlib_TempTests.mjs | 17 +- .../tests/src/stdlib/Stdlib_TemporalTests.mjs | 7 +- tests/tests/src/stdlib/Stdlib_TestTests.mjs | 6 +- .../src/stdlib/intl/Stdlib_IntlTests.mjs | 4 +- 44 files changed, 573 insertions(+), 85 deletions(-) create mode 100644 changes/cross-module-inline-option.feature.md create mode 100644 tests/build_tests/cross_module_inline/input.js create mode 100644 tests/build_tests/cross_module_inline/rescript.json create mode 100644 tests/build_tests/cross_module_inline/src/A.res create mode 100644 tests/build_tests/cross_module_inline/src/B.res create mode 100644 tests/build_tests/cross_module_inline_separate_builds/.gitignore create mode 100644 tests/build_tests/cross_module_inline_separate_builds/input.js create mode 100644 tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/package.json create mode 100644 tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/rescript.json create mode 100644 tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/src/Exporter.res create mode 100644 tests/build_tests/cross_module_inline_separate_builds/rescript.json create mode 100644 tests/build_tests/cross_module_inline_separate_builds/src/B.res create mode 100644 tests/tests/src/cross_module_inline_export.mjs create mode 100644 tests/tests/src/cross_module_inline_export.res create mode 100644 tests/tests/src/cross_module_inline_opt_in_test.mjs create mode 100644 tests/tests/src/cross_module_inline_opt_in_test.res diff --git a/changes/cross-module-inline-option.feature.md b/changes/cross-module-inline-option.feature.md new file mode 100644 index 00000000000..5eb9e571167 --- /dev/null +++ b/changes/cross-module-inline-option.feature.md @@ -0,0 +1 @@ +- Allow selected functions to opt into cross-module inlining with `@inline(crossModule)` and inline common `Option` helpers in application code. diff --git a/compiler/core/js_cmj_format.ml b/compiler/core/js_cmj_format.ml index b31bb916d70..240b52b6642 100644 --- a/compiler/core/js_cmj_format.ml +++ b/compiler/core/js_cmj_format.ml @@ -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} diff --git a/compiler/core/js_cmj_format.mli b/compiler/core/js_cmj_format.mli index c6a8d17bd1b..177f112dc81 100644 --- a/compiler/core/js_cmj_format.mli +++ b/compiler/core/js_cmj_format.mli @@ -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} diff --git a/compiler/core/lam_analysis.ml b/compiler/core/lam_analysis.ml index 2eaba3240d7..15e9f6e5a79 100644 --- a/compiler/core/lam_analysis.ml +++ b/compiler/core/lam_analysis.ml @@ -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 diff --git a/compiler/core/lam_closure.ml b/compiler/core/lam_closure.ml index 97bd1b47a7e..1cd3e10fe53 100644 --- a/compiler/core/lam_closure.ml +++ b/compiler/core/lam_closure.ml @@ -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) -> diff --git a/compiler/core/lam_stats_export.ml b/compiler/core/lam_stats_export.ml index e3051f300f8..e2cc3504808 100644 --- a/compiler/core/lam_stats_export.ml +++ b/compiler/core/lam_stats_export.ml @@ -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" + else optlam | Some lambda -> if not !((Js_config.current ()).cross_module_inline) then None else if diff --git a/compiler/ml/lambda.ml b/compiler/ml/lambda.ml index afe4b1464ee..93a51ba45a0 100644 --- a/compiler/ml/lambda.ml +++ b/compiler/ml/lambda.ml @@ -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 diff --git a/compiler/ml/lambda.mli b/compiler/ml/lambda.mli index 4b5e70dd05f..90a11e466de 100644 --- a/compiler/ml/lambda.mli +++ b/compiler/ml/lambda.mli @@ -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': diff --git a/compiler/ml/printlambda.ml b/compiler/ml/printlambda.ml index 12f340fc9ba..87340ad2b88 100644 --- a/compiler/ml/printlambda.ml +++ b/compiler/ml/printlambda.ml @@ -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 diff --git a/compiler/ml/translattribute.ml b/compiler/ml/translattribute.ml index bceb8f54b28..2f9d23d3bd5 100644 --- a/compiler/ml/translattribute.ml +++ b/compiler/ml/translattribute.ml @@ -34,11 +34,12 @@ 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 @@ -46,6 +47,7 @@ let parse_inline_attribute (attr : t option) : Lambda.inline_attribute = 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) @@ -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 diff --git a/packages/@rescript/runtime/Stdlib_Option.res b/packages/@rescript/runtime/Stdlib_Option.res index 660f5a60a30..3a4ccc9800c 100644 --- a/packages/@rescript/runtime/Stdlib_Option.res +++ b/packages/@rescript/runtime/Stdlib_Option.res @@ -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) @@ -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) => diff --git a/rewatch-ocaml/README.md b/rewatch-ocaml/README.md index 48b47847bfc..3af3a66d9ed 100644 --- a/rewatch-ocaml/README.md +++ b/rewatch-ocaml/README.md @@ -69,9 +69,10 @@ 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 + interface. A `.cmj` counts like the `.cmi`, since dependents also inline + what it 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 diff --git a/rewatch-ocaml/build_state.ml b/rewatch-ocaml/build_state.ml index 853f5b8e0ac..9ca90429db4 100644 --- a/rewatch-ocaml/build_state.ml +++ b/rewatch-ocaml/build_state.ml @@ -111,8 +111,7 @@ let record_published_cmi ?dirty_propagation state ~compile_assets module_ ~path mark_dependents_compile_dirty ?visited:dirty_propagation state module_); Compile_assets.refresh_cmi compile_assets ~key:module_.key ~path; module_.last_compiled_cmi <- - Compile_assets.cmi compile_assets module_.key - |> Option.map (fun entry -> entry.Compile_assets.modified) + Compile_assets.published compile_assets module_.key let record_successful_compile ~compile_assets module_ ~cmt_path = Compile_assets.refresh_cmt compile_assets ~key:module_.key ~path:cmt_path; diff --git a/rewatch-ocaml/build_state.mli b/rewatch-ocaml/build_state.mli index f9988a20cbf..0ecf301a98a 100644 --- a/rewatch-ocaml/build_state.mli +++ b/rewatch-ocaml/build_state.mli @@ -15,6 +15,7 @@ type module_ = { mutable dependents: String_set.t; mutable compile_dirty: bool; mutable last_compiled_cmi: float option; + (** See {!Compile_assets.published}. *) mutable last_compiled_cmt: float option; } diff --git a/rewatch-ocaml/compile_assets.ml b/rewatch-ocaml/compile_assets.ml index 96bb5c3ac52..cc73a0a4bf0 100644 --- a/rewatch-ocaml/compile_assets.ml +++ b/rewatch-ocaml/compile_assets.ml @@ -8,6 +8,7 @@ type t = { ast_by_source: (string, entry) Hashtbl.t; cmi_by_module: (string, entry) Hashtbl.t; cmt_by_module: (string, entry) Hashtbl.t; + cmj_by_module: (string, entry) Hashtbl.t; } let ast_header path = @@ -24,7 +25,7 @@ let is_managed_basename basename = || String.starts_with ~prefix:File_util.atomic_write_prefix basename let state_extension = function - | ".ast" | ".iast" | ".cmi" | ".cmt" -> true + | ".ast" | ".iast" | ".cmi" | ".cmj" | ".cmt" -> true | _ -> false let read_directory directory = @@ -66,6 +67,7 @@ let add_module_artifact state (entry, name) = match Filename.extension name with | ".cmi" -> Hashtbl.replace state.cmi_by_module (module_key name) entry | ".cmt" -> Hashtbl.replace state.cmt_by_module (module_key name) entry + | ".cmj" -> Hashtbl.replace state.cmj_by_module (module_key name) entry | _ -> () let create directories = @@ -77,6 +79,7 @@ let create directories = ast_by_source = Hashtbl.create 64; cmi_by_module = Hashtbl.create 64; cmt_by_module = Hashtbl.create 64; + cmj_by_module = Hashtbl.create 64; } in let directories = @@ -146,6 +149,12 @@ let ast state source = Hashtbl.find_opt state.ast_by_source (source_key source) let cmi state key = Hashtbl.find_opt state.cmi_by_module key let cmt state key = Hashtbl.find_opt state.cmt_by_module key +let published state key = + match (cmi state key, Hashtbl.find_opt state.cmj_by_module key) with + | None, _ -> None + | Some cmi, None -> Some cmi.modified + | Some cmi, Some cmj -> Some (Float.max cmi.modified cmj.modified) + let replace_from_path table key path = try Hashtbl.replace table key {path; modified = (Unix.stat path).Unix.st_mtime} @@ -153,7 +162,9 @@ let replace_from_path table key path = Hashtbl.remove table key let refresh_cmi state ~key ~path = - replace_from_path state.cmi_by_module key path + replace_from_path state.cmi_by_module key path; + replace_from_path state.cmj_by_module key + (Filename.remove_extension path ^ ".cmj") let refresh_cmt state ~key ~path = replace_from_path state.cmt_by_module key path diff --git a/rewatch-ocaml/compile_assets.mli b/rewatch-ocaml/compile_assets.mli index b915655f1b4..900c60d1eff 100644 --- a/rewatch-ocaml/compile_assets.mli +++ b/rewatch-ocaml/compile_assets.mli @@ -17,6 +17,14 @@ val ast_dependencies : t -> string -> string list val ast : t -> string -> entry option val cmi : t -> string -> entry option val cmt : t -> string -> entry option + +val published : t -> string -> float option +(** When the module's CMI, or its CMJ if newer, was last written; [None] without + a CMI. A CMJ can change without its CMI, for example when an exported inline + body changes, and dependents compiled before it are stale too. *) + val refresh_cmi : t -> key:string -> path:string -> unit +(** Also refreshes the CMJ next to [path]. *) + val refresh_cmt : t -> key:string -> path:string -> unit val refresh_ast : t -> source:string -> path:string -> unit diff --git a/rewatch-ocaml/compiler_process.ml b/rewatch-ocaml/compiler_process.ml index d38435b28b4..b361f772844 100644 --- a/rewatch-ocaml/compiler_process.ml +++ b/rewatch-ocaml/compiler_process.ml @@ -112,8 +112,8 @@ 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 @@ -121,7 +121,7 @@ let run_requests requests = requests |> List.map task |> run_tasks 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 @@ -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). *) @@ -197,26 +206,24 @@ 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. *) + match + ( publish_if_changed + (Filename.concat artifact_dir (basename ^ ".cmj")), + !cmi_change ) + with + | true, _ -> 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))) @@ -285,13 +292,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}); }) @@ -340,6 +347,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) @@ -367,13 +375,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 diff --git a/rewatch-ocaml/module_graph.ml b/rewatch-ocaml/module_graph.ml index 0b1d801ee5c..507b20bb445 100644 --- a/rewatch-ocaml/module_graph.ml +++ b/rewatch-ocaml/module_graph.ml @@ -312,8 +312,7 @@ let initialize ~(root_config : Config.t) ~package_plans ~compile_assets List.iter (fun ((node : module_node), _) -> Build_state.add build_state ~key:node.key ~kind:Build_state.Source_module - ~last_compiled_cmi: - (Compile_assets.cmi compile_assets node.key |> modified) + ~last_compiled_cmi:(Compile_assets.published compile_assets node.key) ~last_compiled_cmt: (Compile_assets.cmt compile_assets node.key |> modified)) source_graph_nodes; @@ -322,8 +321,7 @@ let initialize ~(root_config : Config.t) ~package_plans ~compile_assets Build_state.add build_state ~key:namespace_map.key ~kind:Build_state.Namespace_map ~last_compiled_cmi: - (Compile_assets.cmi compile_assets namespace_map.compiler_name - |> modified) + (Compile_assets.published compile_assets namespace_map.compiler_name) ~last_compiled_cmt: (Compile_assets.cmt compile_assets namespace_map.compiler_name |> modified)) diff --git a/scripts/test.js b/scripts/test.js index 7465a250b4d..baae3c64850 100644 --- a/scripts/test.js +++ b/scripts/test.js @@ -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", diff --git a/tests/belt_tests/src/bs_stack_test.mjs b/tests/belt_tests/src/bs_stack_test.mjs index 0729f2a230d..e6c8f4b34d1 100644 --- a/tests/belt_tests/src/bs_stack_test.mjs +++ b/tests/belt_tests/src/bs_stack_test.mjs @@ -2,7 +2,6 @@ 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"; @@ -10,7 +9,7 @@ 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; @@ -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; @@ -33,7 +32,7 @@ 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; @@ -41,7 +40,7 @@ function inOrder3(v) { 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; diff --git a/tests/build_tests/cross_module_inline/input.js b/tests/build_tests/cross_module_inline/input.js new file mode 100644 index 00000000000..d06d5f45f56 --- /dev/null +++ b/tests/build_tests/cross_module_inline/input.js @@ -0,0 +1,35 @@ +// @ts-check + +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.js"); +const cmj = path.join(import.meta.dirname, "lib", "rescript", "A.cmj"); +const original = await fs.readFile(source, "utf8"); + +await execClean(); +try { + await execBuildOrThrow(); + assert.match(await fs.readFile(output, "utf8"), /let result = 2;/); + await fs.access(cmj); + await execClean(); + await assert.rejects(fs.access(cmj)); + await execBuildOrThrow(); + + // The public type stays the same, but the saved inline body changes. + await fs.writeFile(source, original.replace("x + 1", "x + 2")); + await execBuildOrThrow(); + assert.match(await fs.readFile(output, "utf8"), /let result = 3;/); + + // Removing the marker restores a normal call. + await fs.writeFile(source, original.replace("@inline(crossModule)\n", "")); + await execBuildOrThrow(); + assert.match(await fs.readFile(output, "utf8"), /A\.bump\(1\)/); +} finally { + await fs.writeFile(source, original); + await execClean(); +} diff --git a/tests/build_tests/cross_module_inline/rescript.json b/tests/build_tests/cross_module_inline/rescript.json new file mode 100644 index 00000000000..ba764d8f55a --- /dev/null +++ b/tests/build_tests/cross_module_inline/rescript.json @@ -0,0 +1,5 @@ +{ + "name": "cross-module-inline-build-test", + "sources": [{ "dir": "src" }], + "package-specs": { "module": "commonjs", "in-source": true } +} diff --git a/tests/build_tests/cross_module_inline/src/A.res b/tests/build_tests/cross_module_inline/src/A.res new file mode 100644 index 00000000000..1224d11fc7d --- /dev/null +++ b/tests/build_tests/cross_module_inline/src/A.res @@ -0,0 +1,2 @@ +@inline(crossModule) +let bump = x => x + 1 diff --git a/tests/build_tests/cross_module_inline/src/B.res b/tests/build_tests/cross_module_inline/src/B.res new file mode 100644 index 00000000000..ffe66e169ff --- /dev/null +++ b/tests/build_tests/cross_module_inline/src/B.res @@ -0,0 +1 @@ +let result = A.bump(1) diff --git a/tests/build_tests/cross_module_inline_separate_builds/.gitignore b/tests/build_tests/cross_module_inline_separate_builds/.gitignore new file mode 100644 index 00000000000..d64bd833ba7 --- /dev/null +++ b/tests/build_tests/cross_module_inline_separate_builds/.gitignore @@ -0,0 +1,2 @@ +!node_modules +node_modules/**/lib diff --git a/tests/build_tests/cross_module_inline_separate_builds/input.js b/tests/build_tests/cross_module_inline_separate_builds/input.js new file mode 100644 index 00000000000..a2215ecbe4d --- /dev/null +++ b/tests/build_tests/cross_module_inline_separate_builds/input.js @@ -0,0 +1,41 @@ +// @ts-check + +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { projectDir } from "#dev/paths"; +import { setup } from "#dev/process"; + +const root = import.meta.dirname; +const exporter = path.join(root, "node_modules", "inline-exporter"); +const source = path.join(exporter, "src", "Exporter.res"); +const output = path.join(root, "src", "B.js"); +const original = await fs.readFile(source, "utf8"); +const rootBuild = setup(root); +const exporterBuild = setup(exporter); +const exporterOptions = { + env: { + ...process.env, + RESCRIPT_RUNTIME: path.join(projectDir, "packages/@rescript/runtime"), + }, +}; + +await rootBuild.execClean(); +try { + await exporterBuild.execBuildOrThrow([], exporterOptions); + await rootBuild.execBuildOrThrow(); + assert.match(await fs.readFile(output, "utf8"), /let result = 2;/); + + await fs.writeFile(source, original.replace("x + 1", "x + 2")); + await exporterBuild.execBuildOrThrow([], exporterOptions); + await rootBuild.execBuildOrThrow(); + assert.match(await fs.readFile(output, "utf8"), /let result = 3;/); + + await fs.writeFile(source, original.replace("@inline(crossModule)\n", "")); + await exporterBuild.execBuildOrThrow([], exporterOptions); + await rootBuild.execBuildOrThrow(); + assert.match(await fs.readFile(output, "utf8"), /Exporter\.bump\(1\)/); +} finally { + await fs.writeFile(source, original); + await rootBuild.execClean(); +} diff --git a/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/package.json b/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/package.json new file mode 100644 index 00000000000..b8ad3897565 --- /dev/null +++ b/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/package.json @@ -0,0 +1 @@ +{"name": "inline-exporter", "version": "0.0.0"} diff --git a/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/rescript.json b/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/rescript.json new file mode 100644 index 00000000000..e85feb794a9 --- /dev/null +++ b/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/rescript.json @@ -0,0 +1,5 @@ +{ + "name": "inline-exporter", + "sources": [{"dir": "src"}], + "package-specs": {"module": "commonjs", "in-source": true} +} diff --git a/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/src/Exporter.res b/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/src/Exporter.res new file mode 100644 index 00000000000..1224d11fc7d --- /dev/null +++ b/tests/build_tests/cross_module_inline_separate_builds/node_modules/inline-exporter/src/Exporter.res @@ -0,0 +1,2 @@ +@inline(crossModule) +let bump = x => x + 1 diff --git a/tests/build_tests/cross_module_inline_separate_builds/rescript.json b/tests/build_tests/cross_module_inline_separate_builds/rescript.json new file mode 100644 index 00000000000..441e424116a --- /dev/null +++ b/tests/build_tests/cross_module_inline_separate_builds/rescript.json @@ -0,0 +1,6 @@ +{ + "name": "cross-module-inline-separate-builds", + "sources": [{ "dir": "src" }], + "package-specs": { "module": "commonjs", "in-source": true }, + "dependencies": ["inline-exporter"] +} diff --git a/tests/build_tests/cross_module_inline_separate_builds/src/B.res b/tests/build_tests/cross_module_inline_separate_builds/src/B.res new file mode 100644 index 00000000000..516009f1f90 --- /dev/null +++ b/tests/build_tests/cross_module_inline_separate_builds/src/B.res @@ -0,0 +1 @@ +let result = Exporter.bump(1) diff --git a/tests/build_tests/super_errors/expected/warning_47_attribute_payload.res.expected b/tests/build_tests/super_errors/expected/warning_47_attribute_payload.res.expected index c5bd7a58c4c..95d9436707e 100644 --- a/tests/build_tests/super_errors/expected/warning_47_attribute_payload.res.expected +++ b/tests/build_tests/super_errors/expected/warning_47_attribute_payload.res.expected @@ -7,4 +7,4 @@ 3 │ illegal payload for attribute @inline. -It must be either empty, 'always' or 'never' \ No newline at end of file +It must be empty, 'always', 'never' or 'crossModule' diff --git a/tests/rewatch_ounit_tests/compile_assets_tests.ml b/tests/rewatch_ounit_tests/compile_assets_tests.ml index 68d35f491ba..b4de9ad3014 100644 --- a/tests/rewatch_ounit_tests/compile_assets_tests.ml +++ b/tests/rewatch_ounit_tests/compile_assets_tests.ml @@ -109,11 +109,25 @@ let tests = check (Option.is_none (Compile_assets.cmi state "Nested")) "the compiler asset directory is scanned non-recursively"; + Unix.utimes first 100. 100.; + Unix.utimes cleanup_only 200. 200.; + Compile_assets.refresh_cmi state ~key:"Example" ~path:first; + check + (Compile_assets.published state "Example" = Some 200.) + "a CMJ newer than its CMI counts as a publication"; + Unix.utimes first 300. 300.; + Compile_assets.refresh_cmi state ~key:"Example" ~path:first; + check + (Compile_assets.published state "Example" = Some 300.) + "an older CMJ leaves the CMI publication time"; Sys.remove first; Compile_assets.refresh_cmi state ~key:"Example" ~path:first; check (Option.is_none (Compile_assets.cmi state "Example")) "refresh removes a deleted CMI"; + check + (Option.is_none (Compile_assets.published state "Example")) + "a CMJ without a CMI is not a complete publication"; let replacement_ast = Filename.concat root "Replacement.ast" in write replacement_ast "replacement"; Compile_assets.refresh_ast state ~source ~path:replacement_ast; diff --git a/tests/tests/src/cross_module_inline_export.mjs b/tests/tests/src/cross_module_inline_export.mjs new file mode 100644 index 00000000000..46139cc55f7 --- /dev/null +++ b/tests/tests/src/cross_module_inline_export.mjs @@ -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 */ diff --git a/tests/tests/src/cross_module_inline_export.res b/tests/tests/src/cross_module_inline_export.res new file mode 100644 index 00000000000..a23824f684c --- /dev/null +++ b/tests/tests/src/cross_module_inline_export.res @@ -0,0 +1,11 @@ +@inline(crossModule) +let apply = (value, f) => f(value) + +let ordinary = (value, f) => f(value) + +@inline(crossModule) +let catchMessage = f => + try f() catch { + | JsExn(e) => JsExn.message(e) + | _ => None + } diff --git a/tests/tests/src/cross_module_inline_opt_in_test.mjs b/tests/tests/src/cross_module_inline_opt_in_test.mjs new file mode 100644 index 00000000000..563ad66e272 --- /dev/null +++ b/tests/tests/src/cross_module_inline_opt_in_test.mjs @@ -0,0 +1,175 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; +import * as Stdlib_JsExn from "@rescript/runtime/lib/es6/Stdlib_JsExn.mjs"; +import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.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"; +import * as Cross_module_inline_export from "./cross_module_inline_export.mjs"; + +let mapped = 3; + +let flatMapped = 4; + +let nested = Primitive_option.some(undefined); + +let mappedNested = Primitive_option.some(Primitive_option.valFromOption(nested)); + +function mapValue(opt) { + if (opt !== undefined) { + return Primitive_option.some((x => x + 1 | 0)(Primitive_option.valFromOption(opt))); + } +} + +function flatMapValue(opt) { + if (opt !== undefined) { + let x = Primitive_option.valFromOption(opt); + return x + 2 | 0; + } +} + +function forEachValue(opt, f) { + if (opt !== undefined) { + return f(Primitive_option.valFromOption(opt)); + } +} + +function filterValue(opt, p) { + if (opt !== undefined && p(Primitive_option.valFromOption(opt))) { + return opt; + } +} + +function mapOrValue(opt, $$default, f) { + if (opt !== undefined) { + return f(Primitive_option.valFromOption(opt)); + } else { + return $$default; + } +} + +function getOrValue(opt, $$default) { + if (opt !== undefined) { + return Primitive_option.valFromOption(opt); + } else { + return $$default; + } +} + +function orElseValue(opt, other) { + if (opt !== undefined) { + return opt; + } else { + return other; + } +} + +function isSomeValue(opt) { + return opt !== undefined; +} + +function isNoneValue(opt) { + return opt === undefined; +} + +let visited = []; + +visited.push(4); + +let fromOrdinary = Cross_module_inline_export.ordinary(3, x => x + 1 | 0); + +let fromCatch; + +try { + fromCatch = Stdlib_JsError.throwWithMessage("boom"); +} catch (raw_e) { + let e = Primitive_exceptions.internalToException(raw_e); + fromCatch = e.RE_EXN_ID === "JsExn" ? Stdlib_JsExn.message(e._1) : undefined; +} + +Mocha.describe("cross-module inline opt-in", () => { + Mocha.test("Option helpers", () => { + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 28, characters 7-14", mapped, 3); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 29, characters 7-14", flatMapped, 4); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 30, characters 7-14", mappedNested, Primitive_option.some(undefined)); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 31, characters 7-14", mapValue(2), 3); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 32, characters 7-14", mapValue(undefined), undefined); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 33, characters 7-14", flatMapValue(2), 4); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 34, characters 7-14", flatMapValue(undefined), undefined); + visited.push(5); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 36, characters 7-14", visited, [ + 4, + 5 + ]); + }); + Mocha.test("only marked exports are inlined", () => { + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 39, characters 7-14", 4, 4); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 40, characters 7-14", fromOrdinary, 4); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 41, characters 7-14", fromCatch, "boom"); + }); + Mocha.test("additional Option helpers", () => { + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 44, characters 7-14", 4, 4); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 45, characters 7-14", undefined, undefined); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 46, characters 7-14", undefined, undefined); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 47, characters 7-14", 3, 3); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 48, characters 7-14", 0, 0); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 49, characters 7-14", 2, 2); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 50, characters 7-14", 0, 0); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 51, characters 7-14", 2, 2); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 52, characters 7-14", 3, 3); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 53, characters 7-14", true, true); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 54, characters 7-14", false, false); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 55, characters 7-14", false, false); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 56, characters 7-14", true, true); + }); + Mocha.test("eager fallback arguments", () => { + let effects = []; + let getDefault = () => { + effects.push("getOr"); + return 0; + }; + let mapDefault = () => { + effects.push("mapOr"); + return 0; + }; + let other = () => { + effects.push("orElse"); + return 0; + }; + getDefault(); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 72, characters 7-14", 2, 2); + mapDefault(); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 73, characters 7-14", 2, 2); + other(); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 74, characters 7-14", 2, 2); + Test_utils.eq("File \"cross_module_inline_opt_in_test.res\", line 75, characters 7-14", effects, [ + "getOr", + "mapOr", + "orElse" + ]); + }); +}); + +let fromExport = 4; + +export { + mapped, + flatMapped, + nested, + mappedNested, + mapValue, + flatMapValue, + forEachValue, + filterValue, + mapOrValue, + getOrValue, + orElseValue, + isSomeValue, + isNoneValue, + visited, + fromExport, + fromOrdinary, + fromCatch, +} +/* Not a pure module */ diff --git a/tests/tests/src/cross_module_inline_opt_in_test.res b/tests/tests/src/cross_module_inline_opt_in_test.res new file mode 100644 index 00000000000..a88b3ab5b51 --- /dev/null +++ b/tests/tests/src/cross_module_inline_opt_in_test.res @@ -0,0 +1,77 @@ +open Mocha +open Test_utils + +let mapped = Some(2)->Option.map(x => x + 1) +let flatMapped = Some(2)->Option.flatMap(x => Some(x + 2)) +let nested: option> = Some(None) +let mappedNested = nested->Option.map(x => x) +let mapValue = opt => opt->Option.map(x => x + 1) +let flatMapValue = opt => opt->Option.flatMap(x => Some(x + 2)) +let forEachValue = (opt, f) => opt->Option.forEach(f) +let filterValue = (opt, p) => opt->Option.filter(p) +let mapOrValue = (opt, default, f) => opt->Option.mapOr(default, f) +let getOrValue = (opt, default) => opt->Option.getOr(default) +let orElseValue = (opt, other) => opt->Option.orElse(other) +let isSomeValue = opt => opt->Option.isSome +let isNoneValue = opt => opt->Option.isNone + +let visited: array = [] +let _ = Some(4)->Option.forEach(x => visited->Array.push(x)) +let _ = None->Option.forEach(_ => visited->Array.push(0)) + +let fromExport = Cross_module_inline_export.apply(3, x => x + 1) +let fromOrdinary = Cross_module_inline_export.ordinary(3, x => x + 1) +let fromCatch = Cross_module_inline_export.catchMessage(() => JsError.throwWithMessage("boom")) + +describe("cross-module inline opt-in", () => { + test("Option helpers", () => { + eq(__LOC__, mapped, Some(3)) + eq(__LOC__, flatMapped, Some(4)) + eq(__LOC__, mappedNested, Some(None)) + eq(__LOC__, mapValue(Some(2)), Some(3)) + eq(__LOC__, mapValue(None), None) + eq(__LOC__, flatMapValue(Some(2)), Some(4)) + eq(__LOC__, flatMapValue(None), None) + forEachValue(Some(5), x => visited->Array.push(x)) + eq(__LOC__, visited, [4, 5]) + }) + test("only marked exports are inlined", () => { + eq(__LOC__, fromExport, 4) + eq(__LOC__, fromOrdinary, 4) + eq(__LOC__, fromCatch, Some("boom")) + }) + test("additional Option helpers", () => { + eq(__LOC__, filterValue(Some(4), x => x > 3), Some(4)) + eq(__LOC__, filterValue(Some(2), x => x > 3), None) + eq(__LOC__, filterValue(None, _ => true), None) + eq(__LOC__, mapOrValue(Some(2), 0, x => x + 1), 3) + eq(__LOC__, mapOrValue(None, 0, x => x + 1), 0) + eq(__LOC__, getOrValue(Some(2), 0), 2) + eq(__LOC__, getOrValue(None, 0), 0) + eq(__LOC__, orElseValue(Some(2), Some(3)), Some(2)) + eq(__LOC__, orElseValue(None, Some(3)), Some(3)) + eq(__LOC__, isSomeValue(Some(2)), true) + eq(__LOC__, isSomeValue(None), false) + eq(__LOC__, isNoneValue(Some(2)), false) + eq(__LOC__, isNoneValue(None), true) + }) + test("eager fallback arguments", () => { + let effects = [] + let getDefault = () => { + effects->Array.push("getOr") + 0 + } + let mapDefault = () => { + effects->Array.push("mapOr") + 0 + } + let other = () => { + effects->Array.push("orElse") + Some(0) + } + eq(__LOC__, Some(2)->Option.getOr(getDefault()), 2) + eq(__LOC__, Some(2)->Option.mapOr(mapDefault(), x => x), 2) + eq(__LOC__, Some(2)->Option.orElse(other()), Some(2)) + eq(__LOC__, effects, ["getOr", "mapOr", "orElse"]) + }) +}) diff --git a/tests/tests/src/flat_make_export_test.mjs b/tests/tests/src/flat_make_export_test.mjs index 8b3f96f0d7c..d780da41cc8 100644 --- a/tests/tests/src/flat_make_export_test.mjs +++ b/tests/tests/src/flat_make_export_test.mjs @@ -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", () => { @@ -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"); diff --git a/tests/tests/src/int_overflow_test.mjs b/tests/tests/src/int_overflow_test.mjs index 82554707887..667e82d1ef9 100644 --- a/tests/tests/src/int_overflow_test.mjs +++ b/tests/tests/src/int_overflow_test.mjs @@ -3,7 +3,7 @@ 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 Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; function hash_variant(s) { let accu = 0; @@ -49,8 +49,14 @@ Mocha.describe("Int_overflow_test", () => { Mocha.test("hash_variant_test2", () => Test_utils.eq("File \"int_overflow_test.res\", line 61, characters 38-45", hash_variant2("xxyyzxzzyy"), -449896130)); Mocha.test("int_literal_flow", () => Test_utils.eq("File \"int_overflow_test.res\", line 62, characters 36-43", -1, -1)); 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", () => Test_utils.eq("File \"int_overflow_test.res\", line 65, characters 7-14", Stdlib_Option.map(Stdlib_Float.fromString("3"), prim => prim | 0), 3)); - Mocha.test("float_conversion_test2", () => Test_utils.eq("File \"int_overflow_test.res\", line 68, characters 7-14", Stdlib_Option.map(Stdlib_Float.fromString("3.2"), prim => prim | 0), 3)); + Mocha.test("float_conversion_test1", () => { + let opt = Stdlib_Float.fromString("3"); + Test_utils.eq("File \"int_overflow_test.res\", line 65, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) | 0) : undefined, 3); + }); + Mocha.test("float_conversion_test2", () => { + let opt = Stdlib_Float.fromString("3.2"); + Test_utils.eq("File \"int_overflow_test.res\", line 68, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) | 0) : undefined, 3); + }); }); let max_int = 2147483647; diff --git a/tests/tests/src/stdlib/Stdlib_ObjectTests.mjs b/tests/tests/src/stdlib/Stdlib_ObjectTests.mjs index eee989fd219..82a12bde359 100644 --- a/tests/tests/src/stdlib/Stdlib_ObjectTests.mjs +++ b/tests/tests/src/stdlib/Stdlib_ObjectTests.mjs @@ -2,8 +2,8 @@ import * as Test from "./Test.mjs"; import * as Stdlib_BigInt from "@rescript/runtime/lib/es6/Stdlib_BigInt.mjs"; -import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.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; @@ -445,7 +445,7 @@ runGetTest({ source: () => ({ a: 1 }), - get: i => Stdlib_Option.isSome(i["toString"]), + get: i => i["toString"] !== undefined, expected: true }); @@ -476,10 +476,20 @@ runGetTest({ 3 ] }), - get: i => Stdlib_Option.getOr(Stdlib_Option.map(i["a"], i => i.concat([ - 4, - 5 - ])), []), + get: i => { + let opt = i["a"]; + let f = i => i.concat([ + 4, + 5 + ]); + let opt$1 = opt !== undefined ? Primitive_option.some(f(Primitive_option.valFromOption(opt))) : undefined; + let $$default = []; + if (opt$1 !== undefined) { + return Primitive_option.valFromOption(opt$1); + } else { + return $$default; + } + }, expected: [ 1, 2, diff --git a/tests/tests/src/stdlib/Stdlib_TempTests.mjs b/tests/tests/src/stdlib/Stdlib_TempTests.mjs index af63b4cbd79..8a18db36c38 100644 --- a/tests/tests/src/stdlib/Stdlib_TempTests.mjs +++ b/tests/tests/src/stdlib/Stdlib_TempTests.mjs @@ -5,7 +5,6 @@ import * as Stdlib_Dict from "@rescript/runtime/lib/es6/Stdlib_Dict.mjs"; import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.mjs"; import * as Stdlib_Float from "@rescript/runtime/lib/es6/Stdlib_Float.mjs"; import * as Stdlib_BigInt from "@rescript/runtime/lib/es6/Stdlib_BigInt.mjs"; -import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; import * as Primitive_bigint from "@rescript/runtime/lib/es6/Primitive_bigint.mjs"; import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; import * as Stdlib_IntlTests from "./intl/Stdlib_IntlTests.mjs"; @@ -137,7 +136,11 @@ console.info("BigInt"); console.info("---"); -console.log(Primitive_bigint.div(BigInt(1), Stdlib_Option.getOr(Stdlib_BigInt.fromFloat(12.0), 0n))); +let tmp$1 = BigInt(1); + +let opt = Stdlib_BigInt.fromFloat(12.0); + +console.log(Primitive_bigint.div(tmp$1, opt !== undefined ? Primitive_option.valFromOption(opt) : 0n)); console.info(""); @@ -202,13 +205,11 @@ console.log(regex.test(string)); let result = regex.exec(string); -let result$1 = result == null ? undefined : Primitive_option.some(result); - -console.log(Stdlib_Option.map(result$1, prim => prim.input)); +console.log(!(result == null) ? Primitive_option.some(result.input) : undefined); -console.log(Stdlib_Option.map(result$1, prim => prim.index)); +console.log(!(result == null) ? Primitive_option.some(result.index) : undefined); -console.log(Stdlib_Option.map(result$1, prim => prim.slice(1))); +console.log(!(result == null) ? Primitive_option.some(result.slice(1)) : undefined); console.info(""); @@ -321,6 +322,8 @@ let formatter = Stdlib_IntlTests.formatter; let segments = Stdlib_IntlTests.segments; +let result$1 = result == null ? undefined : Primitive_option.some(result); + export { _collator, collator, diff --git a/tests/tests/src/stdlib/Stdlib_TemporalTests.mjs b/tests/tests/src/stdlib/Stdlib_TemporalTests.mjs index 18c76469a96..5af66905034 100644 --- a/tests/tests/src/stdlib/Stdlib_TemporalTests.mjs +++ b/tests/tests/src/stdlib/Stdlib_TemporalTests.mjs @@ -2,7 +2,6 @@ import * as Test from "./Test.mjs"; import * as Stdlib_JsExn from "@rescript/runtime/lib/es6/Stdlib_JsExn.mjs"; -import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.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"; @@ -328,7 +327,9 @@ Test.run([ 57 ], "getTimeZoneTransition without a transition" -], Stdlib_Option.isNone(Primitive_option.fromNullable(utc.getTimeZoneTransition("previous"))), eq, true); +], Primitive_option.fromNullable(utc.getTimeZoneTransition("previous")) === undefined, eq, true); + +let opt = utc.withTimeZone("America/New_York").getTimeZoneTransition("next"); Test.run([ [ @@ -338,7 +339,7 @@ Test.run([ 54 ], "getTimeZoneTransition with a transition" -], Stdlib_Option.map(Primitive_option.fromNullable(utc.withTimeZone("America/New_York").getTimeZoneTransition("next")), transition => transition.toString()), eq, "2024-03-10T03:00:00-04:00[America/New_York]"); +], !(opt == null) ? Primitive_option.some(opt.toString()) : undefined, eq, "2024-03-10T03:00:00-04:00[America/New_York]"); Test.run([ [ diff --git a/tests/tests/src/stdlib/Stdlib_TestTests.mjs b/tests/tests/src/stdlib/Stdlib_TestTests.mjs index bca6b692aad..67b37cff720 100644 --- a/tests/tests/src/stdlib/Stdlib_TestTests.mjs +++ b/tests/tests/src/stdlib/Stdlib_TestTests.mjs @@ -2,8 +2,8 @@ import * as Test from "./Test.mjs"; import * as Stdlib_BigInt from "@rescript/runtime/lib/es6/Stdlib_BigInt.mjs"; -import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.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; @@ -11,7 +11,9 @@ let nan = NaN; let infinity = Number.POSITIVE_INFINITY; -let bign = Stdlib_Option.getOr(Stdlib_BigInt.fromFloat(Number.MAX_VALUE), 0n); +let opt = Stdlib_BigInt.fromFloat(Number.MAX_VALUE); + +let bign = opt !== undefined ? Primitive_option.valFromOption(opt) : 0n; let bign$1 = bign + bign; diff --git a/tests/tests/src/stdlib/intl/Stdlib_IntlTests.mjs b/tests/tests/src/stdlib/intl/Stdlib_IntlTests.mjs index 85e250c1b5e..7945fa8b097 100644 --- a/tests/tests/src/stdlib/intl/Stdlib_IntlTests.mjs +++ b/tests/tests/src/stdlib/intl/Stdlib_IntlTests.mjs @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE import * as Stdlib_JsExn from "@rescript/runtime/lib/es6/Stdlib_JsExn.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 Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.mjs"; import * as Stdlib_Intl_LocaleTest from "./Stdlib_Intl_LocaleTest.mjs"; @@ -58,7 +57,8 @@ try { let e$2 = Primitive_exceptions.internalToException(raw_e$2); if (e$2.RE_EXN_ID === "JsExn") { let e$3 = e$2._1; - let message = Stdlib_Option.map(Stdlib_JsExn.message(e$3), prim => prim.toLowerCase()); + let opt = Stdlib_JsExn.message(e$3); + let message = opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt).toLowerCase()) : undefined; if (message === "invalid key : someinvalidkey") { console.log("Caught expected error"); } else {