From b853bc112c0d28dafb41c910c2fc0e94de6e6532 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Thu, 29 Oct 2026 19:36:44 +0100 Subject: [PATCH] refactor(compiler): the core cleans up function-scope orphans once Function-local declarators and destructuring leaves only erased code read were cleaned by each planner that erased code (start-env, Hydrate's server fallbacks, route-split's `deleteNodes`), each with its own scope: a new erasing planner had to remember the call, and a compile with three of them walked the bindings three times. `AnalysisPlan.resolve()` now runs `cleanOrphanedDeclarations` once, after every planner, when the env module erases anything. The scope of each removal follows from what orphaned it: every output when edits addressed to every output alone erased its readers (and what its run encloses that went before), else the env module, whose liveness decides every orphan. That is the planners' choice in each case (start-env with a separate provider and route-split erase in the env module only; start-env without one and Hydrate's fallbacks everywhere), decided per removal instead of per planner. Co-Authored-By: Claude Opus 5.5 --- packages/router-utils/src/compiler/orphans.ts | 160 +++++++++++------- packages/router-utils/src/compiler/plan.ts | 6 + packages/router-utils/tests/orphans.test.ts | 18 +- 3 files changed, 111 insertions(+), 73 deletions(-) diff --git a/packages/router-utils/src/compiler/orphans.ts b/packages/router-utils/src/compiler/orphans.ts index 3de19de9a2..ae558d9430 100644 --- a/packages/router-utils/src/compiler/orphans.ts +++ b/packages/router-utils/src/compiler/orphans.ts @@ -1,25 +1,56 @@ /** * Declarations only erased code read, below the units placement decides * (SPEC G16 "destructuring", J4.12): function-local declarators and - * destructuring leaves of kept declarations. A service for the planners - * that erase code (start-env's removals, the router planner's `deleteNodes`): each - * calls it after its erasures, on the liveness of the output it erased in. - * Module-level declarations, imports and their provenance are placement's - * (`reach.ts`). + * destructuring leaves of kept declarations. The core runs it once, after + * every planner erased what it erases (`AnalysisPlan.resolve`), on the env + * module's liveness. Module-level declarations, imports and their + * provenance are placement's (`reach.ts`). */ import { walk } from 'yuku' import { extendOverTrailingLine } from './header' import { isPureClass, isPureExpression } from './purity' import { patternIdentifiers } from './source' import type { Node } from 'yuku' +import type { ClassifiedRef } from './analysis' import type { Range } from './header' import type { PlanContext } from './plan' -import type { EditScope, Frag, LivenessView } from './rewrite' +import type { EditScope, Frag, LivenessView, OutputId } from './rewrite' const text = (part: string): Frag => ({ k: 'text', parts: [part] }) const slice = (range: Range): Frag => ({ k: 'slice', range }) const rangeOf = (n: Node): Range => ({ start: n.start, end: n.end }) +const BY = 'core:orphans' +/** An output no planner addresses: its tree holds the edits addressed to every output. */ +const EVERY_OUTPUT: OutputId = 'derived:\0every-output' + +/** A removal's scope (`scopeOf`) from what orphans it and what it encloses that went before. */ +type ScopeOf = ( + refs: ReadonlyArray, + gone?: ReadonlyArray, +) => EditScope + +/** The items of one list pruned in a round, with the references of the bindings they declare. */ +interface Pruned { + items: Set + refs: Array +} + +const prune = ( + map: Map, + list: Node, + item: Node, + refs: ReadonlyArray, +) => { + let p = map.get(list) + if (!p) { + p = { items: new Set(), refs: [] } + map.set(list, p) + } + p.items.add(item) + p.refs.push(...refs) +} + /** * Function-local declarators (and `var`/block declarators of the module * level the core's units do not model) and destructuring leaves all of @@ -28,11 +59,7 @@ const rangeOf = (n: Node): Range => ({ start: n.start, end: n.end }) * expression statement (its hook calls keep running); module level drops it * with the declaration (J4.12, documented removal). Iterates to a fixpoint. */ -export function cleanOrphanedDeclarations( - ctx: PlanContext, - scope: EditScope, - by: string, -): void { +export function cleanOrphanedDeclarations(ctx: PlanContext): void { const { t1, symbols, rewrites } = ctx const file = ctx.analysis.file const code = ctx.analysis.source.code @@ -41,12 +68,28 @@ export function cleanOrphanedDeclarations( // each only the next one reads is cleaned however long it is for (;;) { const live = ctx.liveness('env') + let shared: LivenessView | null = null + /** + * Where a removal applies: in every output when edits addressed to every + * output alone erased what orphans it (the references of what it + * removes) and what it encloses that went before (`gone`), else in the + * env module, whose liveness decides every orphan (an erasure in the env + * module only leaves the code live where another output renders it: a + * server-function provider, a split chunk). + */ + const scopeOf: ScopeOf = (refs, gone = []) => { + shared ??= ctx.liveness(EVERY_OUTPUT) + return refs.every((r) => !shared!.live(r)) && + gone.every((r) => shared!.isErased(r)) + ? 'all-outputs' + : ['env'] + } let changed = false // object pattern properties pruned this round, removed together per pattern - const prunedProps = new Map>() + const prunedProps = new Map() // declarators of multi-declarator statements pruned this round, removed // together per statement (one edit per statement from the final set) - const prunedDecls = new Map>() + const prunedDecls = new Map() // declarators removed whole this round (every binding of a pattern) const removedDeclarators = new Set() for (const b of file.bindings) { @@ -107,7 +150,7 @@ export function cleanOrphanedDeclarations( handled.add(b.id) continue } - if (removeDeclarator(ctx, declarator, scope, by, live, prunedDecls)) { + if (removeDeclarator(ctx, declarator, scopeOf, live, prunedDecls)) { removedDeclarators.add(declarator) handled.add(b.id) changed = true @@ -115,7 +158,7 @@ export function cleanOrphanedDeclarations( } } if (inPattern) { - if (prunePatternElement(ctx, decl, scope, by, prunedProps, live)) { + if (prunePatternElement(ctx, decl, refs, scopeOf, prunedProps, live)) { handled.add(b.id) changed = true } @@ -145,16 +188,16 @@ export function cleanOrphanedDeclarations( end: extendOverTrailingLine(code, parent.end), }, body: [], - scope, - by, + scope: scopeOf(refs), + by: BY, }) } } for (const [pattern, props] of prunedProps) { - removePatternProperties(ctx, pattern, props, live, scope, by) + removePatternProperties(ctx, pattern, props, live, scopeOf) } for (const [statement, decls] of prunedDecls) { - removeDeclarators(ctx, statement, decls, live, scope, by) + removeDeclarators(ctx, statement, decls, live, scopeOf) } if (!changed) { break @@ -171,14 +214,18 @@ export function cleanOrphanedDeclarations( function removeDeclarator( ctx: PlanContext, declarator: Node, - scope: EditScope, - by: string, + scopeOf: ScopeOf, live: LivenessView, - prunedDecls: Map>, + prunedDecls: Map, ): boolean { if (declarator.type !== 'VariableDeclarator') { return false } + // the references of every binding it declares + const refs = patternIdentifiers(declarator.id).flatMap((id) => { + const b = ctx.analysis.file.bindingOf(id) + return b ? ctx.t1.refs.refsOf(ctx.symbols.ofBinding(b)) : [] + }) const file = ctx.analysis.file const code = ctx.analysis.source.code const statement = file.parentOf(declarator) @@ -204,14 +251,14 @@ function removeDeclarator( end: extendOverTrailingLine(code, statement.end), }, body: [], - scope, - by, + scope: scopeOf(refs), + by: BY, } : { range: { start: statement.start, end: statement.end }, body: expressionStatement(code, declarator.init!), - scope, - by, + scope: scopeOf(refs), + by: BY, }, ) return true @@ -219,12 +266,7 @@ function removeDeclarator( if (!effectsGo) { return false } - let set = prunedDecls.get(statement) - if (!set) { - set = new Set() - prunedDecls.set(statement, set) - } - set.add(declarator) + prune(prunedDecls, statement, declarator, refs) return true } @@ -302,10 +344,9 @@ function expressionStatement(code: string, init: Node): Array { function removeDeclarators( ctx: PlanContext, statement: Node, - pruned: ReadonlySet, - live: ReturnType, - scope: EditScope, - by: string, + { items: pruned, refs }: Pruned, + live: LivenessView, + scopeOf: ScopeOf, ): void { if (statement.type !== 'VariableDeclaration') { return @@ -313,6 +354,7 @@ function removeDeclarators( const code = ctx.analysis.source.code const decls = statement.declarations as ReadonlyArray const gone = (d: Node) => pruned.has(d) || live.isErased(rangeOf(d)) + const scope = scopeOf(refs, goneBefore(decls, pruned, live)) if (decls.every(gone)) { const stmtParent = ctx.analysis.file.parentOf(statement) const asStatement = @@ -329,7 +371,7 @@ function removeDeclarators( }, body: [], scope, - by, + by: BY, }) return } @@ -339,10 +381,18 @@ function removeDeclarators( const last = decls[decls.length - 1]! const keepLast = decls.every(gone) const isGone = (d: Node) => gone(d) && !(keepLast && d === last) - removeListItems(ctx, decls, isGone, pruned, null, { - scope, - by, - }) + removeListItems(ctx, decls, isGone, pruned, null, { scope, by: BY }) +} + +/** The ranges of the items of a list an earlier erasure removed (what a removal of their run encloses). */ +function goneBefore( + items: ReadonlyArray, + pruned: ReadonlySet, + live: LivenessView, +): Array { + return items + .filter((item) => !pruned.has(item) && live.isErased(rangeOf(item))) + .map(rangeOf) } /** @@ -352,10 +402,9 @@ function removeDeclarators( function removePatternProperties( ctx: PlanContext, pattern: Node, - pruned: ReadonlySet, - live: ReturnType, - scope: EditScope, - by: string, + { items: pruned, refs }: Pruned, + live: LivenessView, + scopeOf: ScopeOf, ): void { if (pattern.type !== 'ObjectPattern') { return @@ -370,8 +419,8 @@ function removePatternProperties( closing = nextToken(code, closing + 1) } removeListItems(ctx, props, gone, pruned, closing, { - scope, - by, + scope: scopeOf(refs, goneBefore(props, pruned, live)), + by: BY, }) } @@ -504,9 +553,9 @@ function callsHook(init: Node): boolean { function prunePatternElement( ctx: PlanContext, decl: Node, - scope: EditScope, - by: string, - prunedProps: Map>, + refs: ReadonlyArray, + scopeOf: ScopeOf, + prunedProps: Map, live: LivenessView, ): boolean { const file = ctx.analysis.file @@ -532,20 +581,15 @@ function prunePatternElement( ) { return false } - let set = prunedProps.get(pattern) - if (!set) { - set = new Set() - prunedProps.set(pattern, set) - } - set.add(parent) + prune(prunedProps, pattern, parent, refs) return true } if (parent.type === 'ArrayPattern') { ctx.rewrites.add({ range: { start: node.start, end: node.end }, body: commaFollows(ctx.analysis.source.code, node.end) ? [] : [text(',')], - scope, - by, + scope: scopeOf(refs), + by: BY, }) return true } diff --git a/packages/router-utils/src/compiler/plan.ts b/packages/router-utils/src/compiler/plan.ts index 03982715d5..3b3fed4b35 100644 --- a/packages/router-utils/src/compiler/plan.ts +++ b/packages/router-utils/src/compiler/plan.ts @@ -11,6 +11,7 @@ import { NameAllocator } from './names' import { computePlacement } from './reach' import { firstImpure, keptDiagnostic } from './kept-diagnostics' import { freezePlan } from './freeze' +import { cleanOrphanedDeclarations } from './orphans' import { RewriteSet } from './rewrite' import type { Fallback, @@ -435,6 +436,11 @@ export class AnalysisPlan implements PlanContext { /** The core phase after all planners: placement over the live rewrite tree. */ resolve(): Placement { + // function-scope declarations only erased code read go once every + // planner erased what it erases (placement decides the module level) + if (this.rewrites.tree('env').erasedParts().length > 0) { + cleanOrphanedDeclarations(this) + } const benign = new Map() const placement = computePlacement({ t1: this.t1, diff --git a/packages/router-utils/tests/orphans.test.ts b/packages/router-utils/tests/orphans.test.ts index eaf1a505d2..c5bda77809 100644 --- a/packages/router-utils/tests/orphans.test.ts +++ b/packages/router-utils/tests/orphans.test.ts @@ -1,20 +1,8 @@ import { describe, expect, it } from 'vitest' -import { cleanOrphanedDeclarations } from '../src/compiler' import { MemoryHost, dedent, toyEnvPlanner } from './helpers' -import type { Planner } from '../src/compiler' - -/** The toy env planner (client: `wrapServer(arg)` → `tsrStub()`), cleaning up after its erasures. */ -function erasingPlanner(): Planner { - const env = toyEnvPlanner() - return { - ...env, - plan(ctx) { - env.plan(ctx) - cleanOrphanedDeclarations(ctx, 'all-outputs', env.name) - }, - } -} +// The core cleans up after every planner's erasures (the toy env planner: +// client `wrapServer(arg)` → `tsrStub()`, in every output). async function client(code: string) { const host = new MemoryHost({ files: { @@ -22,7 +10,7 @@ async function client(code: string) { '/app/db.ts': `export const secret = () => 's'\n`, }, }) - return (await host.compile('/app/m.ts', [erasingPlanner()]))!.code + return (await host.compile('/app/m.ts', [toyEnvPlanner()]))!.code } describe('destructured bindings only erased code read', () => {