diff --git a/packages/router-utils/src/compiler/README.md b/packages/router-utils/src/compiler/README.md index db4996846c..943b01254c 100644 --- a/packages/router-utils/src/compiler/README.md +++ b/packages/router-utils/src/compiler/README.md @@ -219,24 +219,19 @@ createColumnHelper(); const columns = [columnHelper.accessor('name')]`, both nee (the chunk loads after the route module). Effects have no order of their own (no order rule): what moves keeps its source order in its output, what stays its order in the route module, and code moves by the bindings it reads and writes. A call the model does not know writes nothing it is handed (`snapshot(table)` reads `table`). A - bare statement (it declares nothing: a call, an assignment, an `if`/`try`/loop block) follows what it changes - (R146 amendment, `Events.statementChanges`): the module bindings it assigns, writes a member of or calls a method - on, directly or in what it runs (`ReadIndex.runs`), and the objects their values hold (`MutationModel.heldBy`, - the owner of "the object a binding names"); calling, reading or passing a binding or an import changes nothing - (`plugins.push(sentryPlugin())`, `reg.client = createClient()`, in an `if` or not, move with their binding), but a - function the module declares shows what it does with what it is handed (`fill(k)` with `function fill(o) { o.v = - 3 }` changes `k`: `changesAsArgument`). It - moves into a chunk when everything it changes goes to that chunk, what only it touches following it, in source - order there (`const table = createTable(); const columns = snapshot(table); table.addColumn('x')`, only the - component reading `columns`, all move; what it only reads may stay, and the chunk imports it); a statement that - changes no binding follows what it reads (`log(client)`); where none of that decides, the imports it reads do - (their users' one chunk), and an extracted export's module never does (a reader anywhere imports it). It stays in the route module, keeping what it touches, - when it changes something the rest of the app sees (`OutsideChange`: another module's object, `Sentry.init(cfg)`, - `i18n.use(x)`; a global, `window.x = …`, `console.log(…)`; `import.meta`; a module it imports dynamically), also - through a local function it calls, or when what it changes stays or goes to several outputs - (`placement/settle.ts`, followers); a declaration's own write (`Page.x = …`) is judged the same way, and the - warning (`eager-split:written`) names the cause with the statement's line. A call the purity model knows changes - nothing (`JSON.parse`, a pure export) is none; inside imported code the compiler sees nothing + bare statement (it declares nothing: a call, an assignment, an `if`/`try`/loop block), and dead code (R148), + follows the module bindings it uses (R149, `Events.statementChanges`): those it names or runs (`ReadIndex.runs`) + and the objects their values hold (`MutationModel.heldBy`, the owner of "the object a binding names"), into the + one chunk they all go to, in source order there (`const table = createTable(); const columns = snapshot(table); + table.addColumn('x')`, only the component reading `columns`, all move); otherwise it stays, keeping what it uses: + a binding it uses stays (the route module needs it, it is exported) or goes to another output. Nothing outside the + module keeps it (`Sentry.init(cfg)`, `window.x = cfg`, `console.log(cfg)`, `import()`, `import.meta.hot` move with + `cfg`); a statement using no binding that moves stays (`Sentry.init({ dsn })`, `i18n.use(backend)`); a write of + an import's member is no write of a declaration of the module (the import is not joined by it). Unused code that + runs nothing and uses only imports goes with their users' one chunk. Followers are judged together in settle's + round 0 (`placement/settle.ts`); the warning (`eager-split:written`) names the binding that keeps the statement + (or the unused code) with its line, `changes` or `uses` as the statement does each (`changesObject`, + `changesAsArgument`). Inside imported code the compiler sees nothing (`registry.install()` patching `fetch` runs when the chunk loads). Both sides are judged on their slots in one fixed point (a demoted read cluster re-judges its reader). It never moves into an extracted export's module: that module is side-effect free (every bundler may skip it while diff --git a/packages/router-utils/src/compiler/kept-diagnostics.ts b/packages/router-utils/src/compiler/kept-diagnostics.ts index d82443584d..971a3bb93f 100644 --- a/packages/router-utils/src/compiler/kept-diagnostics.ts +++ b/packages/router-utils/src/compiler/kept-diagnostics.ts @@ -128,20 +128,36 @@ export function keptDiagnostic( fix = `move ${subject} to ${own} own module${annotatable(plan, k.syms) ? `, or mark ${initialiser} \`/* @__PURE__ */\` if ${itHas} none` : ''}` break case 'written': { - // a statement changing it stays (R146 amendment): what else it - // changes keeps it, or several split options use what it changes - const statement = `the statement on ${line(k.at!)}, which ${k.uses === true ? 'uses' : 'changes'} ${them}, stays there` + // a statement using it stays (R149): another binding it uses stays + // or goes elsewhere, several split options use what it changes, or + // code that runs later changes it; or it is unused code (R148) + const unused = + k.unused === undefined ? null : `\`${symbols.name(k.unused)}\`` + const stays = + unused !== null + ? `${unused} (${line(k.at!)}), which nothing uses, stays there` + : `the statement on ${line(k.at!)}, which ${k.uses === true ? 'uses' : 'changes'} ${them}, stays there` const users = [ ...new Set([...k.needers, ...(k.in === undefined ? [] : [k.in])]), ] because = - k.read !== undefined - ? `${statement}: it also ${k.uses === true ? 'uses' : 'changes'} ${read}, which ${k.in === undefined ? `the ${module} keeps` : `${plan.outputs.get(k.in)!.kind === 'export' ? '' : 'the split '}${output(k.in)} uses`}` - : `${statement}: several split options use what it changes (${users.map(output).join(', ')})` + k.later !== undefined + ? `${stays}: code that runs later changes ${them} too (${line(k.later)})` + : k.read !== undefined + ? `${stays}: it also ${k.readChanged === true ? 'changes' : 'uses'} ${read}, which ${k.in === undefined ? `the ${module} keeps` : `${plan.outputs.get(k.in)!.kind === 'export' ? '' : 'the split '}${output(k.in)} uses`}` + : `${stays}: several split options use what it changes (${users.map(output).join(', ')})` fix = - k.read !== undefined - ? `change ${read} in a statement of its own` - : `move ${subject} and that statement to their own module` + unused !== null + ? `delete ${unused}` + : k.later !== undefined + ? `move ${subject} and the statements changing ${them} to their own module` + : k.read === undefined + ? `move ${subject} and that statement to their own module` + : k.split === true + ? `change ${read} in a statement of its own` + : k.in === undefined + ? `run that statement in the code that needs ${them}` + : `move ${subject}, ${read} and that statement to their own module` break } case 'shared': diff --git a/packages/router-utils/src/compiler/placement/clusters.ts b/packages/router-utils/src/compiler/placement/clusters.ts index 6f59316378..9147f1745e 100644 --- a/packages/router-utils/src/compiler/placement/clusters.ts +++ b/packages/router-utils/src/compiler/placement/clusters.ts @@ -518,11 +518,20 @@ export function buildClusters(input: PlacementInput): ClusterGraph { // writes in source order. A unit that writes a member only inside a // function (`function set() { cfg.v = 1 }`) is a late writer, not joined // (V orders it); a sub-region assigning it is the single-writer rule's. + // A write of an import (a member, an augmentation) joins nothing: it is no + // declaration of the module (another module evaluates it; every output + // imports it itself), and the write table still orders it (R149: a + // statement writing one follows the module bindings it uses). const writersOfMember = new Map>() // declaring member → writer sub-regions const regionWrittenSyms = new Set() for (const w of writes) { const d = declMember.get(w.sym) - if (!w.live || d === undefined || w.owner === null) { + if ( + !w.live || + d === undefined || + w.owner === null || + t1.symbols.isImport(w.sym) + ) { continue } const unitOwner = regions.get(w.owner).kind === 'unit' diff --git a/packages/router-utils/src/compiler/placement/events.ts b/packages/router-utils/src/compiler/placement/events.ts index 443d4a4a99..f0ee817fb2 100644 --- a/packages/router-utils/src/compiler/placement/events.ts +++ b/packages/router-utils/src/compiler/placement/events.ts @@ -101,8 +101,16 @@ export interface Pin { binding?: SymbolId /** `written`: the split output using `binding` (another than the subject's), or the subject's second one. */ in?: OutputId - /** `written`: the statement only uses the subject (it changes no binding of the module). */ + /** `written`: the statement only uses the subject (it changes none of its bindings). */ uses?: boolean + /** `written`: the statement changes `binding` (else it uses it). */ + bindingChanged?: boolean + /** `written`: the statement is several statements, one of which can change `binding` on its own. */ + split?: boolean + /** `written`: the follower is unused code (R148), this declaration. */ + unused?: SymbolId + /** `written`: code that runs later changes what the statement uses, there (V). */ + later?: number } export interface Events { @@ -664,7 +672,16 @@ export function eventTable( return false } noteRead(ref) - // what it changes (the warnings word it: `changes` or `uses`) + // what it changes (the warnings word it: `changes` or `uses`): in + // its text or a function body it runs, not a writer of a name it + // reads (`cfg.n = 1` after `table.setup(cfg)`) + if ( + (ref.range.start < unit.range.start || + ref.range.end > unit.range.end) && + !t1.isLazyAt(ref.range.start) + ) { + return false + } let changed: ReadonlyArray = [] if (ref.kind === 'write') { changed = [ref.sym] diff --git a/packages/router-utils/src/compiler/placement/kept.ts b/packages/router-utils/src/compiler/placement/kept.ts index 8bb8b1638f..98d9ec57dd 100644 --- a/packages/router-utils/src/compiler/placement/kept.ts +++ b/packages/router-utils/src/compiler/placement/kept.ts @@ -64,6 +64,10 @@ export function keptDeclarations( ...(pin.binding !== undefined && { read: pin.binding }), ...(pin.in !== undefined && { in: pin.in }), ...(pin.uses === true && { uses: true }), + ...(pin.bindingChanged === true && { readChanged: true }), + ...(pin.split === true && { split: true }), + ...(pin.unused !== undefined && { unused: pin.unused }), + ...(pin.later !== undefined && { later: pin.later }), } } /** `reassigned`: the binding and its first live assignment (the declaration aside). */ @@ -167,18 +171,44 @@ export function keptDeclarations( // (what the env module evaluates with it: a binding whose value holds // a claimed option value does not keep that value there) const kept = reads.reach('env', [c]) - const followed = events.statementChanges(c).clusters + const changes = events.statementChanges(c) + const named: Array = [] + const reported = (d: ClusterId) => + !causes.has(d) && + kept.has(d) && + clusters[d]!.kind !== 'import' && + !clusters[d]!.copyable && + derivedNeeds(input, derivedReach, d) for (const d of clusters[c]!.declares.size > 0 - ? [c, ...followed] - : followed) { - if ( - d !== blocker && - !causes.has(d) && - kept.has(d) && - clusters[d]!.kind !== 'import' && - derivedNeeds(input, derivedReach, d) - ) { - causes.set(d, pin) + ? [c, ...changes.clusters] + : changes.clusters) { + if (d !== blocker && reported(d)) { + named.push(d) + // (the statement changes it, or only uses it) + const changed = changes.syms.some((s) => clusters[d]!.declares.has(s)) + causes.set(d, changed ? pin : { ...pin, uses: true }) + } + } + // unused code (R148, R149 answers E) names everything it keeps eager: + // the binding that keeps it too, with another one it keeps + if ( + pin.unused !== undefined && + blocker !== undefined && + reported(blocker) + ) { + const another = changes.reads.find((s) => { + const d = clusterOfSym.get(s) + return d !== undefined && named.includes(d) + }) + const elsewhere = + another === undefined ? [] : lazyNeeders(clusterOfSym.get(another)!) + if (another !== undefined) { + causes.set(blocker, { + ...pin, + uses: true, + binding: another, + in: elsewhere[0], + }) } } } diff --git a/packages/router-utils/src/compiler/placement/settle.ts b/packages/router-utils/src/compiler/placement/settle.ts index 4b558d178e..f56adea5d0 100644 --- a/packages/router-utils/src/compiler/placement/settle.ts +++ b/packages/router-utils/src/compiler/placement/settle.ts @@ -9,6 +9,7 @@ * rounds end within the cluster count (past it, an error naming the file); * nothing is rooted after it. */ +import { statementsIn } from '../units' import { isDuplicable } from './clusters' import type { Cluster, ClusterGraph, ClusterId } from './clusters' import type { Events, Pin } from './events' @@ -65,7 +66,7 @@ export function settleRoots( seeds: Seeds, ): Roots { const { t1, outputs } = input - const { refs } = t1 + const { refs, symbols } = t1 const { regions } = input.rewrites const { clusters, clusterOfRegion } = graph const { envRoots, pinned, derivedRoots, candidates, followers } = seeds @@ -194,6 +195,7 @@ export function settleRoots( c: ClusterId, d: ClusterId | null, other?: OutputId, + later?: number, ): Pin => { const changes = events.statementChanges(c) const sym = @@ -202,8 +204,14 @@ export function settleRoots( : [...changes.syms, ...changes.reads].find( (s) => graph.clusterOfSym.get(s) === d, ) + // unused code (R148): a follower with no statement of its own + const cl = clusters[c]! + const unused = cl.units.every((u) => t1.units[u]!.kind !== 'effect') + ? [...cl.declares].find((s) => symbols.isModuleLevel(s)) + : undefined let at: number | undefined - for (const u of clusters[c]!.units) { + let split = false + for (const u of cl.units) { const unit = t1.units[u]! if (unit.kind !== 'effect' && unit.kind !== 'declaration') { continue @@ -215,6 +223,13 @@ export function settleRoots( : one.syms.includes(sym) || one.reads.includes(sym) ) { at = unit.range.start + // a statement of several statements changing the binding can + // change it in one of its own (one call cannot be split) + split = + sym !== undefined && + one.syms.includes(sym) && + unit.node.type !== 'ExpressionStatement' && + statementsIn(unit.node) > 1 break } } @@ -222,8 +237,49 @@ export function settleRoots( reason: 'written', ...(at !== undefined && { other: { at } }), ...(sym !== undefined && { binding: sym }), + ...(sym !== undefined && + changes.syms.includes(sym) && { bindingChanged: true }), ...(other !== undefined && { in: other }), - ...(changes.syms.length === 0 && { uses: true }), + ...(split && { split: true }), + ...(unused !== undefined && { unused }), + ...(later !== undefined && { later }), + } + } + /** + * Keeps follower `c` in the env module, recording why for the report + * (`kept.ts`): a `written` pin as is, V's (code that runs later writes + * what it uses) as `written` with that write's position. + */ + const keepFollower = (c: ClusterId, pin: Pin): void => { + envRoots.add(c) + if (pin.reason === 'written') { + seeds.stayPins.set(c, pin) + } else if (pin.reason === 'state' && pin.other !== undefined) { + const sym = pin.binding + const d = sym === undefined ? undefined : graph.clusterOfSym.get(sym) + // the later write another statement makes, if one does (a function + // the statement itself hands to a call is its own) + const other = + sym === undefined + ? undefined + : graph.writesOfSym + .get(sym) + ?.find( + (w) => + w.live && + !w.eager && + w.owner !== null && + graph.clusterOfRegion.get(w.owner) !== c, + ) + seeds.stayPins.set(c, { + ...stayPin( + c, + d === undefined || d === c ? null : d, + undefined, + other?.at ?? pin.other.at, + ), + binding: undefined, + }) } } /** `c` and the clusters it follows (`Events.statementChanges`). */ @@ -231,6 +287,10 @@ export function settleRoots( function followSlot(c: ClusterId): OutputId | Pin { let to: OutputId | null = null for (const d of followed(c)) { + // (a primitive `const` is copied into every output that reads it) + if (d !== c && clusters[d]!.copyable) { + continue + } if (liveEnv.has(d) || envRoots.has(d)) { return d === c ? { reason: 'needers' } : stayPin(c, d) } @@ -276,6 +336,9 @@ export function settleRoots( return { reason: 'needers' } } for (const d of events.statementChanges(c).clusters) { + if (clusters[d]!.copyable) { + continue + } if (stays(d)) { return stayPin(c, d) } @@ -662,10 +725,7 @@ export function settleRoots( follows.set(c, to) derivedRoots.get(to)!.add(c) } else { - envRoots.add(c) - if (to.reason === 'written') { - seeds.stayPins.set(c, to) - } + keepFollower(c, to) } } derivedStale = true @@ -686,10 +746,7 @@ export function settleRoots( // as an augmented root's write, `kept.ts`) follows.delete(c) derivedRoots.get(follow)!.delete(c) - envRoots.add(c) - if (pin.reason === 'written') { - seeds.stayPins.set(c, pin) - } + keepFollower(c, pin) derivedStale = true changed = true continue diff --git a/packages/router-utils/src/compiler/reach.ts b/packages/router-utils/src/compiler/reach.ts index 43b4449c6d..233dc82371 100644 --- a/packages/router-utils/src/compiler/reach.ts +++ b/packages/router-utils/src/compiler/reach.ts @@ -137,8 +137,16 @@ export interface KeptDeclaration { read?: SymbolId /** `written`: the split output using `read`, or the subject's second one. */ in?: OutputId - /** `written`: the statement only uses it (it changes no binding of the module). */ + /** `written`: the statement only uses it (it changes none of its bindings). */ uses?: boolean + /** `written`: the statement changes `read` (else it uses it). */ + readChanged?: boolean + /** `written`: the statement can change `read` in a statement of its own. */ + split?: boolean + /** `written`: the statement is this unused declaration (R148). */ + unused?: SymbolId + /** `written`: code that runs later changes it, there. */ + later?: number } export interface ExtractedExport { diff --git a/packages/router-utils/src/compiler/units.ts b/packages/router-utils/src/compiler/units.ts index 683f36317f..ad7f5e3561 100644 --- a/packages/router-utils/src/compiler/units.ts +++ b/packages/router-utils/src/compiler/units.ts @@ -1347,6 +1347,25 @@ export function callsWhenEvaluated(node: Node): EvaluatedCalls { return { calls, callbacks } } +/** How many expression statements `node` holds, function bodies aside (a block of several can be split; one call cannot). */ +export function statementsIn(node: Node): number { + let n = 0 + walk(node, { + enter: (x, wctx) => { + if ( + x.type === 'FunctionExpression' || + x.type === 'ArrowFunctionExpression' || + x.type === 'FunctionDeclaration' + ) { + wctx.skip() + } else if (x.type === 'ExpressionStatement') { + n++ + } + }, + }) + return n +} + /** * Whether the reference `node` (an identifier) changes the object it names * where it evaluates: the root of a member write