From d4b83335a432b34e93cf34a08a623e58716948e2 Mon Sep 17 00:00:00 2001 From: Jono Prest Date: Mon, 9 Nov 2026 15:23:51 +0000 Subject: [PATCH] Look up the modules of a namespace by name instead of listing them all Why: Every module of a package with a namespace opens the namespace's module, which maps each module of the package to its compiled name (`module Price = Price-Shop`). Opening a module builds its components, and building them walked every item of its signature, with a substitution entry, two table insertions and an environment binding per item, all kept for the rest of the compile. Each module of a namespaced package therefore did work proportional to the size of the package, and a clean build did quadratic work: on a package of about 4,900 modules, 46% of the build's CPU time went to building these components. The components of a signature made only of aliases to persistent modules, such as a namespace's, are now looked up per name: `Tbl.of_source` makes a table whose entries are computed when a name is first looked up or visited, from an index of the signature's items. Folds and iterations visit the names in the order of the table the eager loop built, which decides, for example, the order of the candidates in a "did you mean" hint. The entries are the ones the eager loop made: an alias to a persistent module mentions no other item of its signature, so the substitution and the environment that the loop extended item by item can't change what it resolves to. Each entry still gets its own path and a substitution with its own item, so the declarations it returns are copies, shared as before in the `.cmi` and `.cmt` files. While the build system keeps decoded interfaces across the compiles of a build, each domain also keeps the indexes of the 16 most recently used such interfaces, by physical signature, until the build's files change. Build modified (clean builds, default domains, medians of 15 interleaved pairs on a shared 8-core machine): Before (text): 4,900 modules, namespace wall 40.4 s user 169.6 s peak RSS 2,536 MB 480 modules, namespace wall 1.09 s user 3.45 s 4,900 modules, none wall 6.03 s user 29.3 s After (text): 4,900 modules, namespace wall 8.70 s user 38.7 s peak RSS 1,180 MB 480 modules, namespace wall 1.02 s user 3.09 s 4,900 modules, none wall 6.16 s user 29.8 s (no change: 95% CIs include 1) Every artifact of the 11 projects of a benchmark corpus (88,523 files, `.cmt` files included), of the runtime and of Belt is byte-identical to master's, with one domain and with the default number. Review: Do error messages and editor tools see the same modules in the same order? Lookups, folds and iterations over the table return what the eager table held, folds in the order of its keys. The new build test checks the "did you mean" hint, which lists the namespace's modules in that order, the type printed in an error, a module named like the namespace and a local module that hides one of the package. Review: How long are the indexes kept? Only while the build file store is enabled, one per decoded interface: a domain keeps the 16 most recently used and drops them when the store's generation changes, as it drops its decoded interfaces. `bsc` and other compiles outside a build index the signature on each compile. Signed-off-by: Jono Prest --- .../namespace-components-on-demand.polish.md | 1 + compiler/ml/env.ml | 121 ++++++++++++++++++ compiler/ml/tbl.ml | 17 ++- compiler/ml/tbl.mli | 8 ++ .../namespace_components/.gitignore | 1 + .../build_tests/namespace_components/input.js | 42 ++++++ .../namespace_components/rescript.json | 13 ++ .../namespace_components/src/Cart.res | 13 ++ .../namespace_components/src/Price.res | 3 + .../namespace_components/src/Pride.res | 2 + .../namespace_components/src/Prime.res | 2 + .../namespace_components/src/Prize.res | 2 + .../namespace_components/src/Shadow.res | 6 + .../namespace_components/src/Shop.res | 1 + .../namespace_components/src/Tax.res | 1 + 15 files changed, 231 insertions(+), 2 deletions(-) create mode 100644 changes/namespace-components-on-demand.polish.md create mode 100644 tests/build_tests/namespace_components/.gitignore create mode 100644 tests/build_tests/namespace_components/input.js create mode 100644 tests/build_tests/namespace_components/rescript.json create mode 100644 tests/build_tests/namespace_components/src/Cart.res create mode 100644 tests/build_tests/namespace_components/src/Price.res create mode 100644 tests/build_tests/namespace_components/src/Pride.res create mode 100644 tests/build_tests/namespace_components/src/Prime.res create mode 100644 tests/build_tests/namespace_components/src/Prize.res create mode 100644 tests/build_tests/namespace_components/src/Shadow.res create mode 100644 tests/build_tests/namespace_components/src/Shop.res create mode 100644 tests/build_tests/namespace_components/src/Tax.res diff --git a/changes/namespace-components-on-demand.polish.md b/changes/namespace-components-on-demand.polish.md new file mode 100644 index 00000000000..ffc765ed485 --- /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 06590447734..6278d4c23af 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 54fa8c9c092..64910e4a57c 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 9b678307153..cc825e3c45c 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 00000000000..74870206b69 --- /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 00000000000..523bdaa7abf --- /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 00000000000..a7c6bb9e30d --- /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 00000000000..3a0cc4defef --- /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 00000000000..065500db24d --- /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 00000000000..e68fcd074e3 --- /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 00000000000..e68fcd074e3 --- /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 00000000000..e68fcd074e3 --- /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 00000000000..34c8ff84c54 --- /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 00000000000..327c5e92f99 --- /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 00000000000..45f0345e602 --- /dev/null +++ b/tests/build_tests/namespace_components/src/Tax.res @@ -0,0 +1 @@ +let rate = 2