Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
143 changes: 88 additions & 55 deletions src/bundler/linker_context/mergeSmallChunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,14 +202,18 @@ fn collect_newly_loaded(
/// entry load more code), the second only for chunks smaller than
/// `min_chunk_size` (summed source bytes):
///
/// 1. An `import()` entry point `D` is redundant in a key when some other entry
/// in that key is guaranteed to already be loaded whenever `D` is loaded
/// (`guaranteed` below). Keys that are equal after dropping their redundant
/// entries describe chunks that are always loaded together: with one user
/// entry `main` and a lazy `import("./x")` only reachable from `main`, the
/// `{main, x}` chunk is loaded iff `main` runs, the same as `main`'s own
/// chunk, so its files can live there and `x`'s chunk imports what it needs
/// from the `main` chunk.
/// 1. An `import()` entry point `D` is redundant in a key when, whichever way
/// `D` gets loaded, some other entry in that key has already been loaded
/// (`load_class` below: no importer of `D` can be reached from a process
/// root without passing through the key). Keys that are equal
/// after dropping their redundant entries describe chunks that are always
/// loaded together: with one user entry `main` and a lazy `import("./x")`
/// only reachable from `main`, the `{main, x}` chunk is loaded iff `main`
/// runs, the same as `main`'s own chunk, so its files can live there and
/// `x`'s chunk imports what it needs from the `main` chunk. Different
/// entries may cover different importers: with `import("./cmd")` in both
/// `main` and a lazy `repl`, the `{main, repl, cmd}` chunk loads iff `main`
/// or `repl` does.
/// 2. A chunk whose live parts have no top-level side effects may join a chunk
/// loaded by a superset of its entries, as long as everything it imports is
/// already loaded wherever that target is (or is side-effect free too); the
Expand Down Expand Up @@ -307,6 +311,10 @@ pub(crate) fn merge_small_chunks(
}
}
}
// A self-`import()` cannot be the load that comes first.
for (entry_id, importers) in importer_bits.iter_mut().enumerate() {
importers.unset(entry_id);
}

// An entry whose chunk (or a chunk it imports) uses top-level await can
// still be mid-evaluation when an `import()` it started links, so it
Expand All @@ -321,57 +329,90 @@ pub(crate) fn merge_small_chunks(
}
}

// `guaranteed[D]`: entries that are already evaluated whenever the dynamic
// entry `D` is loaded, excluding `D` itself. Greatest fixpoint of
// guaranteed[D] = ∩ over importers E of D: ({E} ∪ guaranteed[E])
// where an importer is an entry that statically reaches a file holding an
// `import()` of D. User entries are process roots, even when something
// also `import()`s them: nothing precedes them. A dynamic entry no live
// code imports is left alone (empty set).
let mut guaranteed: Vec<AutoBitSet> = Vec::with_capacity(entry_points_len);
let has_guarantors = |entry_id: usize| {
is_dynamic_entry(entry_id)
// A dynamic entry can stand in for its importers when some live code
// `import()`s it, nothing `require()`s it, and no importer is mid-evaluation
// at a top-level await while it loads. Every other entry is a root: it may
// be the first thing loaded (a user entry), or nothing says what precedes it.
let mut guaranteed = AutoBitSet::init_empty(entry_points_len)?;
let mut roots: Vec<usize> = Vec::new();
for entry_id in 0..entry_points_len {
if is_dynamic_entry(entry_id)
&& !required_sync.is_set(entry_id)
&& importer_bits[entry_id].find_first_set().is_some()
};
&& !importer_bits[entry_id].has_intersection(&awaits)
{
guaranteed.set(entry_id);
} else {
roots.push(entry_id);
}
}
// The guaranteed entries each entry `import()`s.
let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); entry_points_len];
for entry_id in 0..entry_points_len {
let mut bits = AutoBitSet::init_empty(entry_points_len)?;
if has_guarantors(entry_id) {
bits.set_all(true);
bits.unset(entry_id);
if !guaranteed.is_set(entry_id) {
continue;
}
let mut iter = importer_bits[entry_id].iterator::<true, true>();
while let Some(importer) = iter.next() {
dependents[importer].push(entry_id);
}
guaranteed.push(bits);
}
let mut next = AutoBitSet::init_empty(entry_points_len)?;
loop {
let mut changed = false;
for (entry_id, importers) in importer_bits.iter().enumerate() {
if !has_guarantors(entry_id) {
continue;
// `load_class(key)`: `key` minus each guaranteed entry none of whose
// importers a root reaches through `import()`s without passing through the
// key; such an importer ran after some entry of the key, so that entry's
// chunk was loaded first. (An importer cycle no root reaches never loads,
// so it does not count either.) A key whose every entry is redundant is
// never loaded and left alone.
let mut reached: Vec<u32> = vec![0; entry_points_len];
let mut epoch: u32 = 0;
let mut worklist: Vec<usize> = Vec::new();
let mut candidates: Vec<usize> = Vec::new();
let mut load_class = |key: &AutoBitSet| -> crate::Result<AutoBitSet> {
let mut class = key.clone()?;
candidates.clear();
let mut iter = key.iterator::<true, true>();
while let Some(entry_id) = iter.next() {
if guaranteed.is_set(entry_id) {
candidates.push(entry_id);
}
next.set_all(true);
let mut iter = importers.iterator::<true, true>();
}
if candidates.is_empty() {
return Ok(class);
}
epoch += 1;
worklist.clear();
for &root in &roots {
if !key.is_set(root) {
reached[root] = epoch;
worklist.push(root);
}
}
while let Some(entry_id) = worklist.pop() {
for &dependent in &dependents[entry_id] {
if !key.is_set(dependent) && reached[dependent] != epoch {
reached[dependent] = epoch;
worklist.push(dependent);
}
}
}
for &entry_id in &candidates {
let mut iter = importer_bits[entry_id].iterator::<true, true>();
let mut preceded = true;
while let Some(importer) = iter.next() {
if awaits.is_set(importer) {
next.set_all(false);
if reached[importer] == epoch {
preceded = false;
break;
}
let keep = next.is_set(importer);
next.set_intersection(&guaranteed[importer]);
if keep {
next.set(importer);
}
}
next.unset(entry_id);
if !next.eql(&guaranteed[entry_id]) {
core::mem::swap(&mut guaranteed[entry_id], &mut next);
changed = true;
if preceded {
class.unset(entry_id);
}
}
if !changed {
break;
if class.find_first_set().is_none() {
return Ok(key.clone()?);
}
}
Ok(class)
};

// Group the live JS files by their chunk key, and the groups by their
// load-condition class (the key with redundant dynamic entries removed).
Expand Down Expand Up @@ -440,15 +481,7 @@ pub(crate) fn merge_small_chunks(
}
}
MapEntry::Vacant(entry) => {
// Drop each dynamic entry that some entry still in `class` is
// guaranteed to precede; `guaranteed[d]` never contains `d`.
let mut class = bits.clone()?;
let mut iter = bits.iterator::<true, true>();
while let Some(entry_id) = iter.next() {
if is_dynamic_entry(entry_id) && class.has_intersection(&guaranteed[entry_id]) {
class.unset(entry_id);
}
}
let class = load_class(bits)?;
match classes.entry(temp.alloc_slice_copy(class.bytes(entry_points_len))) {
MapEntry::Occupied(e) => e.into_mut().1.push(group_index),
MapEntry::Vacant(e) => {
Expand Down
90 changes: 90 additions & 0 deletions test/bundler/bundler_splitting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1263,6 +1263,96 @@ describe("bundler", () => {
run: { file: "/out/b.js", stdout: "b\nd 42" },
});

// `cmd` is import()ed from main and from `sub`, which only repl loads, so
// whichever way it loads, main or repl came first: the {main, repl, cmd}
// chunk is loaded exactly when the {main, repl} chunk is and folds into it,
// even though no single entry precedes `cmd` on every path.
itBundled("splitting/FoldsChunkWhoseImportersTheKeyCovers", {
files: {
"/main.js": /* js */ `
import { shared } from './shared.js'
import { common } from './common.js'
console.log('main', shared(), common())
import('./cmd.js').then(m => console.log('cmd', m.cmd()))
`,
"/repl.js": /* js */ `
import { shared } from './shared.js'
import { common } from './common.js'
console.log('repl', shared(), common())
import('./sub.js')
`,
"/sub.js": /* js */ `
console.log('sub')
import('./cmd.js').then(m => console.log('cmd', m.cmd()))
`,
"/cmd.js": /* js */ `
import { shared } from './shared.js'
export function cmd() { return shared() + 1 }
`,
"/shared.js": /* js */ `
console.log('shared evaluated')
export function shared() { return 41 }
`,
"/common.js": /* js */ `
export function common() { return 'common' }
`,
},
entryPoints: ["/main.js", "/repl.js"],
splitting: true,
outdir: "/out",
format: "esm",
onAfterBundle(api) {
// main, repl, sub, cmd, and one {main, repl} chunk holding common.js
// and shared.js.
expect(jsFilesIn(api)).toHaveLength(5);
const sharedChunk = chunkContaining(api, "shared evaluated");
api.expectFile("/out/" + sharedChunk).toContain("common");
expect(jsOutput(api, "cmd")).toContain(`from "./${sharedChunk}"`);
},
run: [
{ file: "/out/main.js", stdout: "shared evaluated\nmain 41 common\ncmd 42" },
{ file: "/out/repl.js", stdout: "shared evaluated\nrepl 41 common\nsub\ncmd 42" },
],
});

// Lazy modules that import() each other: `d` is only reached through `x`,
// which `main` or `y` loads, and `y` only through `x`, so `main` always
// comes first and the {main, d} chunk folds into main.js.
itBundled("splitting/FoldsChunkBehindDynamicImportCycle", {
files: {
"/main.js": /* js */ `
import { shared } from './shared.js'
console.log('main', shared())
import('./x.js')
`,
"/x.js": /* js */ `
console.log('x')
export const y = () => import('./y.js')
import('./d.js').then(m => console.log('d', m.d()))
`,
"/y.js": /* js */ `
export const x = () => import('./x.js')
`,
"/d.js": /* js */ `
import { shared } from './shared.js'
export function d() { return shared() + 1 }
`,
"/shared.js": /* js */ `
export function shared() { return 41 }
`,
},
entryPoints: ["/main.js"],
splitting: true,
outdir: "/out",
format: "esm",
onAfterBundle(api) {
expect(jsOutputs(api)).toEqual(["d.js", "main.js", "x.js", "y.js"]);
api.expectFile("/out/main.js").toContain("41");
expect(jsOutput(api, "d")).toContain('from "./main.js"');
},
run: { file: "/out/main.js", stdout: "main 41\nx\nd 42" },
});

// Folding a chunk with side effects into a pure one (rule 1) makes the
// result impure, so it may not then move into a superset chunk (rule 2).
itBundled("splitting/MinChunkSizeFoldedImpurityBlocksSupersetFold", {
Expand Down
Loading