diff --git a/changes/namespace-components-on-demand.polish.md b/changes/namespace-components-on-demand.polish.md new file mode 100644 index 0000000000..ffc765ed48 --- /dev/null +++ b/changes/namespace-components-on-demand.polish.md @@ -0,0 +1 @@ +- Compile packages with a namespace faster: each module no longer walks every entry of the namespace when it opens it, which made a clean build of a large namespaced package quadratic in its number of modules (4.6 times faster on a package of about 4,900 modules). diff --git a/compiler/ml/env.ml b/compiler/ml/env.ml index 0659044773..6278d4c23a 100644 --- a/compiler/ml/env.ml +++ b/compiler/ml/env.ml @@ -1419,6 +1419,80 @@ let prefix_idents root sub sg = (* Compute structure descriptions *) +(* The module of a package with a namespace maps each module of the package to + its compiled name, [module X = X-Ns], and every module of the package opens + it. Building the components of a signature walks all of its items, which + for this one costs O(package size) per compiled module, so the components of + a signature made only of aliases to persistent modules are looked up per + name instead, through an index of its items. They are the same components: + such an alias refers to no other item of the signature, so neither the + substitution from [prefix_idents] nor the environment extended item by item + in [components_of_module_maker] can change what it resolves to. *) +let rec is_alias_map = function + | [] -> true + | Sig_module (_, {md_type = Mty_alias (_, Pident id)}, _) :: rest -> + Ident.persistent id && is_alias_map rest + | _ -> false + +type alias_map_index = { + names: string array; + (** Sorted by [String.compare], the order of [compare] on strings, which + [Tbl] uses. *) + items: (string, Ident.t * module_declaration * int) Hashtbl.t; + (** The item and position of each name. *) +} + +let index_alias_map sg = + let items = Hashtbl.create (List.length sg) in + List.iteri + (fun pos item -> + match item with + | Sig_module (id, md, _) -> + Hashtbl.replace items (Ident.name id) (id, md, pos) + | _ -> assert false) + sg; + let names = Array.of_seq (Hashtbl.to_seq_keys items) in + Array.sort String.compare names; + {names; items} + +(* While a build system keeps interfaces decoded across the requests of a + build ([Bs_cmi_load]), each request on a domain gets the same signature for + an unchanged interface. The indexes of the last few interfaces that are + alias maps are therefore kept per domain, by physical signature, and + dropped when the build's files change, as the decoded interfaces are. *) +type alias_map_indexes = { + mutable generation: int; + mutable indexes: (signature * alias_map_index) list; +} + +let alias_map_indexes_key = + Domain.DLS.new_key (fun () -> {generation = -1; indexes = []}) + +let max_alias_map_indexes = 16 + +let interface_alias_map_index sg = + let cache = Domain.DLS.get alias_map_indexes_key in + let generation = Build_file_store.generation () in + if cache.generation <> generation then ( + cache.generation <- generation; + cache.indexes <- []); + match List.assq_opt sg cache.indexes with + | Some index -> + (* Most recently used first, so that the namespace every compile opens + stays cached while other alias-only interfaces come and go. *) + (match cache.indexes with + | (first, _) :: _ when first == sg -> () + | indexes -> + cache.indexes <- + (sg, index) :: List.filter (fun (s, _) -> s != sg) indexes); + index + | None -> + let index = index_alias_map sg in + cache.indexes <- + (sg, index) + :: List.filteri (fun i _ -> i < max_alias_map_indexes - 1) cache.indexes; + index + let add_to_tbl id decl tbl = let decls = try Tbl.find_str id tbl with Not_found -> [] in Tbl.add id (decl :: decls) tbl @@ -1428,6 +1502,8 @@ let rec components_of_module ~deprecated ~loc env sub path mty = and components_of_module_maker (env, sub, path, mty) = match scrape_alias env mty with + | Mty_signature (_ :: _ as sg) when is_alias_map sg -> + Some (alias_map_components env sub path sg) | Mty_signature sg -> let c = { @@ -1511,6 +1587,51 @@ and components_of_module_maker (env, sub, path, mty) = }) | Mty_ident _ | Mty_alias _ -> None +and alias_map_components env sub path sg = + let index = + match path with + | Pident id when Ident.persistent id && Build_file_store.enabled () -> + interface_alias_map_index sg + | _ -> index_alias_map sg + in + (* As in the eager loop, an item's path is the one [prefix_idents] gives it, + made with the item's own name, and its substitution maps the item to that + path. The entries for the other items map identifiers that an alias to a + persistent module never mentions, so they are left out, but the + substitution must not be the identity: [subst_modtype_maker] and + [prefix_idents] would then share what they return instead of copying it, + and .cmt files show what is shared. *) + let memoize make = + let values = Hashtbl.create 16 in + fun name -> + match Hashtbl.find_opt values name with + | Some value -> value + | None -> + let id, md, pos = Hashtbl.find index.items name in + let p = Pdot (path, Ident.name id, pos) in + let value = (make (Subst.add_module id p sub) p md, pos) in + Hashtbl.add values name value; + value + in + let modules = memoize (fun sub _ md -> Env_lazy.create (sub, md)) in + let components = + memoize (fun sub p md -> + let deprecated = + Builtin_attributes.deprecated_of_attrs md.md_attributes + in + components_of_module ~deprecated ~loc:md.md_loc env sub p md.md_type) + in + Structure_comps + { + comp_values = Tbl.empty; + comp_constrs = Tbl.empty; + comp_labels = Tbl.empty; + comp_types = Tbl.empty; + comp_modules = Tbl.of_source ~keys:index.names ~find:modules; + comp_modtypes = Tbl.empty; + comp_components = Tbl.of_source ~keys:index.names ~find:components; + } + (* Insertion of bindings by identifier + path *) and check_usage loc id warn tbl = diff --git a/compiler/ml/tbl.ml b/compiler/ml/tbl.ml index 54fa8c9c09..64910e4a57 100644 --- a/compiler/ml/tbl.ml +++ b/compiler/ml/tbl.ml @@ -13,12 +13,18 @@ (* *) (**************************************************************************) -type ('k, 'v) t = Empty | Node of ('k, 'v) t * 'k * 'v * ('k, 'v) t * int +type ('k, 'v) t = + | Empty + | Node of ('k, 'v) t * 'k * 'v * ('k, 'v) t * int + | Source of 'k array * ('k -> 'v) + (** The keys, sorted by [compare], and the lookup of their values. *) let empty = Empty +let of_source ~keys ~find = Source (keys, find) + let height = function - | Empty -> 0 + | Empty | Source _ -> 0 | Node (_, _, _, _, h) -> h let create l x d r = @@ -44,6 +50,8 @@ let bal l x d r = else create l x d r let rec add x data = function + | Source (keys, find) -> + add x data (Array.fold_left (fun t k -> add k (find k) t) Empty keys) | Empty -> Node (Empty, x, data, Empty, 1) | Node (l, v, d, r, h) -> let c = compare x v in @@ -52,18 +60,21 @@ let rec add x data = function else bal l v d (add x data r) let rec find x = function + | Source (_, find) -> find x | Empty -> raise Not_found | Node (l, v, d, r, _) -> let c = compare x v in if c = 0 then d else find x (if c < 0 then l else r) let rec find_str (x : string) = function + | Source (_, find) -> find x | Empty -> raise Not_found | Node (l, v, d, r, _) -> let c = compare x v in if c = 0 then d else find_str x (if c < 0 then l else r) let rec iter f = function + | Source (keys, find) -> Array.iter (fun k -> f k (find k)) keys | Empty -> () | Node (l, v, d, r, _) -> iter f l; @@ -72,5 +83,7 @@ let rec iter f = function let rec fold f m accu = match m with + | Source (keys, find) -> + Array.fold_left (fun accu k -> f k (find k) accu) accu keys | Empty -> accu | Node (l, v, d, r, _) -> fold f r (f v d (fold f l accu)) diff --git a/compiler/ml/tbl.mli b/compiler/ml/tbl.mli index 9b67830715..cc825e3c45 100644 --- a/compiler/ml/tbl.mli +++ b/compiler/ml/tbl.mli @@ -19,6 +19,14 @@ type ('k, 'v) t val empty : ('k, 'v) t + +val of_source : keys:'k array -> find:('k -> 'v) -> ('k, 'v) t +(** [of_source ~keys ~find] maps each of [keys] to [find key], computed when + the key is looked up or visited, so [find] should memoize. [keys] must be + sorted by [compare] without duplicates, so that [iter] and [fold] visit + them in the same order as for a table built with [add], and [find] must + raise [Not_found] for any other key. [add] builds the whole table. *) + val add : 'k -> 'v -> ('k, 'v) t -> ('k, 'v) t val find : 'k -> ('k, 'v) t -> 'v val find_str : string -> (string, 'v) t -> 'v diff --git a/tests/build_tests/namespace_components/.gitignore b/tests/build_tests/namespace_components/.gitignore new file mode 100644 index 0000000000..74870206b6 --- /dev/null +++ b/tests/build_tests/namespace_components/.gitignore @@ -0,0 +1 @@ +*.res.mjs diff --git a/tests/build_tests/namespace_components/input.js b/tests/build_tests/namespace_components/input.js new file mode 100644 index 0000000000..523bdaa7ab --- /dev/null +++ b/tests/build_tests/namespace_components/input.js @@ -0,0 +1,42 @@ +// @ts-check + +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { stripVTControlCharacters } from "node:util"; +import { setup } from "#dev/process"; + +const { execBuild, execBuildOrThrow, execClean } = setup(import.meta.dirname); + +await execClean(); +await execBuildOrThrow(); + +const cart = await import(new URL("./src/Cart.res.mjs", import.meta.url).href); +assert.equal(cart.total, 42); +assert.equal(cart.viaAlias, 1); +assert.equal(cart.viaOpen, 3); +assert.equal(cart.shopName, "shop"); + +const shadow = await import( + new URL("./src/Shadow.res.mjs", import.meta.url).href +); +assert.equal(shadow.label, "local"); + +// Errors name the modules of the package as found through the namespace +const typo = path.join(import.meta.dirname, "src", "Typo.res"); +const typeError = path.join(import.meta.dirname, "src", "TypeError.res"); +await fs.writeFile(typo, "let x = Prise.make(1)\n"); +await fs.writeFile(typeError, "let x: string = Price.make(1)\n"); +try { + const output = await execBuild(); + const stderr = stripVTControlCharacters(output.stderr); + assert.match(stderr, /The module or file Prise can't be found\./); + // Candidates come in the order of the namespace's modules + assert.match(stderr, /Hint: Did you mean Prize, Prime, Pride or Price\?/); + assert.match(stderr, /This has type: Shop\.Price\.t\r?\n/); +} finally { + await fs.rm(typo, { force: true }); + await fs.rm(typeError, { force: true }); +} + +await execClean(); diff --git a/tests/build_tests/namespace_components/rescript.json b/tests/build_tests/namespace_components/rescript.json new file mode 100644 index 0000000000..a7c6bb9e30 --- /dev/null +++ b/tests/build_tests/namespace_components/rescript.json @@ -0,0 +1,13 @@ +{ + "name": "namespace_components", + "sources": ["src"], + "namespace": "Shop", + "package-specs": { + "module": "esmodule", + "in-source": true + }, + "suffix": ".res.mjs", + "warnings": { + "error": true + } +} diff --git a/tests/build_tests/namespace_components/src/Cart.res b/tests/build_tests/namespace_components/src/Cart.res new file mode 100644 index 0000000000..3a0cc4defe --- /dev/null +++ b/tests/build_tests/namespace_components/src/Cart.res @@ -0,0 +1,13 @@ +// Modules of the package, found through the namespace it opens +let total = Price.add(Price.make(40), Price.make(Tax.rate)).cents + +module P = Price +let viaAlias = P.make(1).cents + +let viaOpen = { + open Price + make(3).cents +} + +// The module named like the namespace +let shopName = Shop.name diff --git a/tests/build_tests/namespace_components/src/Price.res b/tests/build_tests/namespace_components/src/Price.res new file mode 100644 index 0000000000..065500db24 --- /dev/null +++ b/tests/build_tests/namespace_components/src/Price.res @@ -0,0 +1,3 @@ +type t = {cents: int} +let make = cents => {cents: cents} +let add = (a, b) => {cents: a.cents + b.cents} diff --git a/tests/build_tests/namespace_components/src/Pride.res b/tests/build_tests/namespace_components/src/Pride.res new file mode 100644 index 0000000000..e68fcd074e --- /dev/null +++ b/tests/build_tests/namespace_components/src/Pride.res @@ -0,0 +1,2 @@ +// Spelled like Price, for the hint below +let v = 1 diff --git a/tests/build_tests/namespace_components/src/Prime.res b/tests/build_tests/namespace_components/src/Prime.res new file mode 100644 index 0000000000..e68fcd074e --- /dev/null +++ b/tests/build_tests/namespace_components/src/Prime.res @@ -0,0 +1,2 @@ +// Spelled like Price, for the hint below +let v = 1 diff --git a/tests/build_tests/namespace_components/src/Prize.res b/tests/build_tests/namespace_components/src/Prize.res new file mode 100644 index 0000000000..e68fcd074e --- /dev/null +++ b/tests/build_tests/namespace_components/src/Prize.res @@ -0,0 +1,2 @@ +// Spelled like Price, for the hint below +let v = 1 diff --git a/tests/build_tests/namespace_components/src/Shadow.res b/tests/build_tests/namespace_components/src/Shadow.res new file mode 100644 index 0000000000..34c8ff84c5 --- /dev/null +++ b/tests/build_tests/namespace_components/src/Shadow.res @@ -0,0 +1,6 @@ +// A local module hides the module of the package with the same name +module Price = { + let make = _ => "local" +} + +let label = Price.make(1) diff --git a/tests/build_tests/namespace_components/src/Shop.res b/tests/build_tests/namespace_components/src/Shop.res new file mode 100644 index 0000000000..327c5e92f9 --- /dev/null +++ b/tests/build_tests/namespace_components/src/Shop.res @@ -0,0 +1 @@ +let name = "shop" diff --git a/tests/build_tests/namespace_components/src/Tax.res b/tests/build_tests/namespace_components/src/Tax.res new file mode 100644 index 0000000000..45f0345e60 --- /dev/null +++ b/tests/build_tests/namespace_components/src/Tax.res @@ -0,0 +1 @@ +let rate = 2