Skip to content

Compiler: split compile.ts by stage; shared templates keep their strings - #162

Merged
tiavision merged 33 commits into
mainfrom
ccr-eba7a8ac-oel4v3
Dec 6, 2026
Merged

tiavision merged 33 commits into
mainfrom
ccr-eba7a8ac-oel4v3

Conversation

@tiavision

@tiavision tiavision commented Dec 6, 2026 •

Copy link
Copy Markdown
Member

Splits src/compiler/compile.ts (15,757 lines) into modules by compile stage, and fixes one miscompile the work turned up. The maintainer asked for this change directly, in place of an issue.

What changes

  • Helpers and pass orchestration out of the class. The code after the Compiler class moved into small modules (dom.ts, url-code.ts, first-paint.ts, row-program.ts, plain-data.ts, …). Option and result types are in types.ts; compileParts, compileTwice, the route switches and the audits are in passes.ts.
  • The class's methods as stage functions. They became functions taking the compiler as their first argument (cx), one module per stage: positions, component-files, expand, instances, walk, bindings, declarations, prerender, second-pass, finish, from-walk, aliases, early-parts, space. compile.ts (2,132 lines) keeps the fields, the constructor and the methods that run the pipeline in order. fn and unitChild stay methods: link.ts patches child.fn on the instance.
  • A typed linker. units.ts and link.ts take a Compiler instead of any, so a stage call there is type-checked. Where they reach tables by field name, as LINK_FIELDS names them, they say so (byName).
  • No setters. B1's walk state (FW_COUNTING, FW_WALKING) lives in from-walk.ts, which assigns it itself; walkExpanded records through whileWalking, and a decided branch's expansion collects what it applies with collectApplied. They stay module state: a unit's compiler, made during the page's walk, records into that walk.
  • Fix: a shared template's strings are no longer renamed. shareRun compared the copies of a template, and renamed the kept copy's props to $pp, with a regular expression over the code's text. A string literal that spelled a definition's props name ('$p2') was renamed too, and a production build printed $pp. Both now rename through renameCode (canon.ts), which renames identifiers and member names only. There's a test in test/behaviour/shared-templates.test.ts, and a CHANGELOG bullet.
  • Smaller changes:
    • Five renames to avoid name clashes: lineCol → lineColOf, binding → devBinding, late → loadsLate, openapi → openapiMatch, and a local fromWalk → tryFromWalk.
    • Removed the unused notUnrolled field.
    • Many members lost private, because stage modules use them.
    • bench/tools time the stage functions per pass; the docs and tests that named compile.ts follow the moves.

Verification

  • Every refactor commit is byte-identical. Each commit's build output (231 files of 7 apps, scripts/baseline.mjs) matches the main branch's; the only commit that changes output is the shareRun fix.
  • npm run typecheck, and npm test (3,601 tests), both pass, and so does npm test under SN_FROM_WALK_AUDIT=1.
  • SN_FUZZ_SEEDS=3000 component fuzz passes.
  • The five route audits all pass on static-site, dashboard and multilingual-site: SN_RENDER_AUDIT, SN_FROM_WALK_AUDIT, SN_ONE_PASS_AUDIT, SN_ROW_FN_AUDIT and SN_UNITS_SHIFT_AUDIT.
  • Compile time is unchanged within noise. Interleaved builds of main and this branch, 12 rounds by wall clock and 20 by CPU time; every 95% interval of the median change includes 0 (e.g. bench-live-files −5.8%, CI −12% … +2%).

For reviewers

  • The commits go one stage at a time and are meant to be read that way; the stage commits are mechanical moves made with a TypeScript codemod.
  • let-cache also edits compile.ts, and will conflict: its changes go into the stage module that now holds the code.
  • Fixed on this branch: a B1 divergence under jiti. Running SN_FROM_WALK_AUDIT=1 over the whole suite failed two tests in test/check-cli.test.ts on this branch, and passed on main.
    • The cause was an earlier commit here: fn() in compile.ts read B1's walk state as bindings imported from from-walk.ts (and passes.ts exported unitShift, passAuditing).
    • jiti, which runs src/cli.ts in those tests, didn't keep the imports live across the import cycle. Native ESM does, so builds were never affected.
    • Each module now exports a function that reads its state, and test/compiler/module-state.test.ts fails on any export let in src.
    • The whole suite passes under SN_FROM_WALK_AUDIT=1.

https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t


Generated by Claude Code

claude added 30 commits December 6, 2026 10:00
Comment-only: nine doc comments sat above the wrong declaration (hasBase's above
stateReaders, makeCode's above bodyOf, frozenPlain's above cloneArg, ...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
compile.ts's free helpers, moved unchanged (each declaration as it was, with its
doc comment; `export` added where compile.ts imports it):

- proc.ts: the process and its SN_* switches
- dom.ts: parse5 tree helpers (P5 types, attr/setAttr, findHead, freshCopy, ...)
- file-paths.ts: normalize, dirname, basename, resolvePath
- url-code.ts: URL templates as code (hrefCode, urlCode, requestUrl, preloads, ...)
- expr-queries.ts: what is read off an expression's AST (hrefPrefixes, condOf, ...)
- code-text.ts: compiled code as text (namesIn, stateReaders, makeCode, ...)
- plain-data.ts: plain and frozen build-time data (plainData, frozenData, ...)
- first-paint.ts: writing a binding's value into the HTML (writeFirstPaint, ...)
- row-program.ts: row programs (rowProgram, rowLayout, ...)

Importers in src/ and test/ import from the new modules. The build output of the
seven baseline apps is byte for byte the same as before; the suite passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
CompileOptions, CompiledParts, CompileResult and the other types a compile takes
and gives, moved unchanged from compile.ts; their importers import types.ts.
Type-only: the build output is byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
compileParts and what decides how a page is compiled (once or twice, a page per
entry from a kept first pass, B1's second pass from the first's walk, the units'
pass) and the route switches and audits around them (SN_RENDER, SN_ROW_FN,
SN_FROM_WALK, SN_ONE_PASS and their audits), moved unchanged from compile.ts.
compile.ts keeps the Compiler class and what it shares with the passes, now
exported to them.

With Compiler exported, the declaration emit names the types of its public fields:
thirteen fields and tables whose inferred parse5 types it could not name get their
type written out (`useOf: WeakMap<P5Element, Use> = new WeakMap()`); the emitted
JavaScript is the same.

The build output of the seven baseline apps is byte for byte the same; the suite
passes; SN_RENDER_AUDIT, SN_FROM_WALK_AUDIT, SN_ONE_PASS_AUDIT, SN_ROW_FN_AUDIT and
SN_UNITS_SHIFT_AUDIT builds of three apps run clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
bench/runtime/page.ts imports compileParts from passes.ts; bench/tools/hooks.mjs's
SN_COUNT rewrite of writeFirstPaint goes to first-paint.js, where it now is (each
of its rewrites checked against the built dist/compiler/ files); docs/spec.md
names url-code.ts for urlCode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
…it adds

fieldsOf's `report` parameter (now `reporting`) and compileTwice's `fromWalk`
boolean (now `tryFromWalk`): the methods `report` and `fromWalk` become functions
of those names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
…ns.ts)

The first stage of the Compiler class split: tag, lineCol (now lineColOf: an import
has the name), valueOffset, callExpr, pageSpec, readPageSpec, legacyPaginate,
loadEffects, swapScripts, report and reporter become functions taking the compiler
first (`cx`), moved unchanged otherwise; every call `x.report(...)` is
`report(x, ...)`. Members they read lose `private`; two fields get their type
written out for the declaration emit. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
…-files.ts)

Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: declaration asKind componentFile librariesKey libOfTag markupFile packageOf
crossesPackage libOfFile libPath rootRel choicePool closeComponentName internalUse.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. plainRoot takes the compiler (it called componentFile as a method). Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: layoutDir isLayoutFile layoutFile mergeLayout rebaseUrls expandComponents choice
emptyStates emptyCondition expandUse rootShape branchShape emptyRootAttrs checkHead
expandHead fillSlots treePlacement placements checkFill place defaultShape
shapeChildren once declaredSlots fillStays dataSlotsOf lateTag canonical
strayAndRepeated accessible rootMarked idSite coexistingIds duplicateIds
componentIds.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: componentScope headMarkup headCaller fillAt fillScope placementData instOf markupOf
stateOf propLets recursionPoint textNode runtimePlacement finishTreeFills
freshChoices slotsPlaced fillsCode fileGraph reach describesNothing inertFill
inertComponent reachesTree pointAttrs defRootBindings finishChoices definition
touchMark touchEl hasDefinitions compileDefinition compileDefinitionIn.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. shiftDepth, read and written only by compileDefinition, moves with it; units.ts's calls of definition and finishChoices (on a compiler typed `any`) are rewritten too. unitChild and fn stay methods: link.ts's runUnit patches `fn` on the unit's compiler and calls both on it. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: declare runTargets runCycles pathPatterns walkChildren element bindings
componentModel foldConstants foldIn keyFilter complexity position newTemplate urlFn
inline binding (now devBinding) devAtOf placeOf repeatCalls devAt sourcesOf expr
emptyExpr ref lazyNames lazyImport addSources resolveSources lets lazyLet
checkNames checkExpr typeLast locOf tagFill guarded recordExpr.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: metaBindable attrBinding hrefBinding remoteImage unsizedFix scaledWidth
objectBinding selection model action applyDef schemaNamed redundantWrites
forTemplate urlTemplate settingsOf encodedBody preloaded anonymous late (now
loadsLate) unembedded signedOut preloadLinks apiTarget apiCheck.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
….ts)

Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: resource fieldsOf pageLocale ownLang pagesOf perCollection contentNs axisOf
markAxisLink axisEntryOf axisResource axisPath contentResource entryResource
fileResource fileUses openapi (now openapiMatch) sync payloadTypeHint event.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: prerender programShape helperCalls embedFolded foldScriptsOut headStart placeFolded
dropFiles fileConstant foldValues foldGain fileConstants expansionWarning
collecting worklist rowRenderer constantSources collectConstants.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: minify layoutAround imageContext prefoldRows prefoldsOutside imagesInRows
minifyHooks respaceRows respaceRowsAs layoutOptions snapshot layoutAnswers
spaceAnswers dryRun constKey prefold instKey choiceKey expandConstants oldRoute
renderedHere inlineInstance inheritSlot cloneTree siteKey.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: anchors dropNodes placeTemplates shareTemplates shareRun dropConstants fixedDeps
dropEmptyStates stateSites placeholders fileScripts reportLate embedReads fileJson
addPlaceholders embedSlots markLowPriority whyNotFolded signedInGuard
inPageLanguage runtimeReasons declareLayers linkStyles injectScript inKept keptOf
urlReads ownPaths seesSameLink checkDroppedQuery checkUrlArrays checkListWrites
urlArrays.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
The B1 methods that assign them become functions of another module (from-walk.ts),
which cannot assign compile.ts's bindings; they call these setters instead. Reads
are unchanged. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: fwFields fwMarks fwStart fwEnd fwDelta fwKeepsUnit fwWatchUnit fwSizes fwSince
fwField fromWalk fromWalkIn renumberIds foldedState freeze fixedState.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: applyAliases pageModules scriptState ownerOf relFile aliasSites resourceWrites
explainWrites explainHelpers writtenState.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: earlyParts predictable firstPrefetch prefetchParts earlyOrigin.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Moved unchanged as functions taking the compiler first (`cx`), every call `x.m(...)` now
`m(x, ...)`: styledRoots planSpace spaceKey spaceFor afterList branchAfterList goneWithRows
waitFor settleSpace.
Members they read lose `private`; fields whose inferred type the declaration emit
cannot name get it written out. Output byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
The phases prerender, worklist, fileConstants and writtenState are
module functions now: the load hook rebinds each one to its timed
wrapper, and the SN_COUNT rewrites target prerender.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
The stage modules add most of them now; the set found is the one
compile.ts had before the split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
units.ts and link.ts took the compiler as `any`, so a call to a
method that had become a stage function compiled and failed at run
time. They take a `Compiler` now; where they read or write its tables
by field name, as LINK_FIELDS and a plan's ops name them, they say so
(`byName`). Types only: the output is the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
FW_COUNTING and FW_WALKING are B1's: they live in from-walk.ts now,
which assigns them itself, and walkExpanded records through
`whileWalking`. A decided branch's expansion collects what it applies
with `collectApplied`, and APPLIED is no longer exported. They stay
module state: a unit's compiler, made during the page's walk, records
into that walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Nothing has read or written it since it was added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
shareRun compared the copies of a template, and rewrote the copy it
kept to read `$pp`, with a regular expression over the functions'
text: a string literal that spelled a definition's props name (`'$p2'`)
was renamed too. Two copies whose strings differed only in that looked
alike, and the page printed `$pp`. Both now rename through renameCode
(canon.ts), which renames identifiers and member names only. The
dependency paths, which hold no strings, keep the expression.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Since B1's walk state moved into from-walk.ts, the compiler's fn() read
it as imported bindings (FW_WALKING, FW_COUNTING), and passes.ts
exported unitShift and passAuditing to compile.ts and instances.ts.
Native ES modules keep such an import live, so builds were unchanged;
jiti, which runs src/cli.ts in the CLI tests, did not keep it live
across the modules' import cycle, and fn() saw the state as it was at
load. Under `sinter check` B1 then recorded the page's sites wrongly,
and its second pass reported message namespaces (`m.docs`, `m.home`)
that the old route folded: SN_FROM_WALK_AUDIT=1 failed two tests in
test/check-cli.test.ts, which pass on main.

Each module keeps its state in a let of its own and exports a function
that reads it (fwWalking, fwCounting, unitShiftBy, auditing). A test
fails on any `export let` in src. The suite passes under
SN_FROM_WALK_AUDIT=1, and the build output is byte-identical to main's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
@tiavision
tiavision merged commit ae530f1 into main Dec 6, 2026
20 checks passed
tiavision pushed a commit that referenced this pull request Dec 6, 2026
A job of its own, as link-audit: `npm test` with SN_FROM_WALK_AUDIT=1,
so every second pass B1 takes is compiled the old way too and must be
the same up to numbering. The audit found a divergence in #162 that
every other check passed; it ran only by hand until now. Its summary
counts the second passes B1 took (SN_FROM_WALK_STATS) and why the others
did not: over the suite today, 415 of 652, all the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AjKzdxQfw4ecAQCBmwDk7t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants