Skip to content

Share one scope visitor across parses to stop leaking memory - #109

Merged
nstepien merged 1 commit into
mainfrom
hoist-scope-visitor
Oct 17, 2026
Merged

nstepien merged 1 commit into
mainfrom
hoist-scope-visitor

Conversation

@nstepien

@nstepien nstepien commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

parseFile created a Visitor from rolldown/utils for every parse, along with about 25 closures (its callbacks and the scope helpers) over the state of that parse. Besides allocating and compiling them every time, this leaked: Visitor keeps the { enter, exit } objects of every instance in a module-level cache that is never cleared (oxc-project/oxc#25510, whose fix has been waiting for review since August). So the callbacks of each parse stayed alive for the rest of the process, along with the function bodies, scopes, and templates they reached.

  • The visitor, its callbacks, and the scope helpers (pushScope, popScope, findFunctionScope, recordBindingPattern, recordParams, and addCssTagCandidate) now live at module level. The state of a visit is held in module-level variables, which visitProgram(program, rootScope) resets before each visit. A visit is synchronous, so visits cannot interleave.
  • functionBodies and firstSwitchCases test membership with delete() instead of has(), so they empty out as their nodes are visited instead of keeping the nodes of every file.
  • extractCssTagCandidates, called once per parse, is inlined into parseFile.
  • hashText uses the one-shot crypto.hash(), stable since Node 24.13.1, instead of createHash(): same output, about 2.3× faster on these short strings.
  • unicorn/consistent-function-scoping is enabled: the override and its TODO: enable are gone, and the suspicious category turns the rule on. It has no findings, and it flags nested functions that capture nothing from their parent scope.
  • AGENTS.md says not to create a Visitor per file, as no test would catch the leak.

Most of the diff moves code. git diff --color-moved=dimmed-zebra --color-moved-ws=allow-indentation-change shows only the edits.

Left as is:

  • resolveValue and resolveBinding. They close over the state of one transform (context, filePath, constValues, and stylesheetDependencies), so moving them out would mean passing a state object through every call, to save about two small allocations per transform.
  • isWaitingFor, parseFile, and extractCssFromCode, created once per plugin instance.
  • Option literals like { encoding: 'utf8' } and { hires: 'boundary' }, warning objects, and the ?? [] fallbacks in watchChange and hotUpdate. Each is one short-lived object next to a file read or sourcemap generation, or on a path that rarely runs.

Test plan

  • node --run test (locally and with CI=true against dist/), lint, typecheck, format:check, build, and lint:package pass, with no snapshot changes. src/index.ts coverage is unchanged: the TSParameterProperty branch is still the only uncovered statement.
  • Replaying the transforms of react-data-grid's 15 ecij modules 2,000 times with a stub plugin context, calling buildEnd between rounds: the heap grew from 109 to 1,115 MB before, and stays at about 8 MB now. Each file takes about 264 µs instead of 277 µs.
  • oxlint flags a nested function that captures nothing now that unicorn/consistent-function-scoping is enabled.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Improved handling of CSS tagged templates across lexical, function, loop, switch, class, and other nested scopes.
  • Chores
    • Updated lint configuration so the function-scoping rule is no longer disabled.
    • Updated project guidance about how file parsing and visitor state are managed.

parseFile created a Visitor from rolldown/utils for every parse, along
with about 25 closures (its callbacks and the scope helpers) over the
state of that parse. Visitor keeps the { enter, exit } objects of every
instance in a module-level cache that is never cleared
(oxc-project/oxc#25510), so the callbacks of each parse stayed alive for
the rest of the process, with the function bodies, scopes, and templates
they reached.

The visitor, its callbacks, and the scope helpers now live at module
level, and visitProgram resets the module-level state of the visit
before each one. A visit is synchronous, so visits cannot interleave.
functionBodies and firstSwitchCases test membership with delete(), so
they empty out as their nodes are visited. extractCssTagCandidates is
inlined into parseFile.

Also:
- hashText uses the one-shot crypto.hash(), stable since Node 24.13.1:
  same output, about 2.3x faster on these short strings.
- unicorn/consistent-function-scoping is enabled through the suspicious
  category, resolving its TODO. It has no findings.
- AGENTS.md says not to create a Visitor per file.

Replaying the transforms of react-data-grid's 15 ecij modules 2,000
times, with buildEnd between rounds, the heap grew from 109 to 1,115 MB
before and stays at about 8 MB now, and each file takes about 264 us
instead of 277 us.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 66f3b820-2eea-47e1-b083-4afe7a4b7ee7
📥 Commits

Reviewing files that changed from the base of the PR and between d69fe0e and 150c86e.

📒 Files selected for processing: 3
  • .oxlintrc.json
  • AGENTS.md
  • src/index.ts

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

📝 Walkthrough

The parser now uses a shared module-level visitor to track scopes and collect CSS tag candidates. parseFile resolves candidates after visiting each program. The lint configuration removes an override that disabled unicorn/consistent-function-scoping.

Changes: Parser Visitor

Layer / File(s) Summary
Shared scope tracking
src/index.ts, AGENTS.md
Module-level helpers and SCOPE_VISITOR track bindings and candidates across AST scopes. AGENTS.md documents the shared visitor and its retained callback state.
Program visits and declaration creation
src/index.ts
visitProgram initializes and runs the shared visitor. parseFile filters candidates, creates declarations, and uses hash from node:crypto for declaration identifiers.

Lint Configuration

Layer / File(s) Summary
Rule override removal
.oxlintrc.json
The unicorn/consistent-function-scoping override and its TODO comment are removed.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 150c8

No issue requiring a change before merge is established by the supplied evidence.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 45.45% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 1 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: sharing one scope visitor across parses to prevent memory leaks.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 45.45% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 1 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@nstepien
nstepien merged commit 0f7435e into main Oct 17, 2026
8 checks passed
@nstepien
nstepien deleted the hoist-scope-visitor branch October 17, 2026 19:10
nstepien added a commit that referenced this pull request Oct 17, 2026
## Summary

`parseFile` created a `Visitor` from `rolldown/utils` for every parse,
along with about 25 closures (its callbacks and the scope helpers) over
the state of that parse. Besides allocating and compiling them every
time, this leaked: `Visitor` keeps the `{ enter, exit }` objects of
every instance in a module-level cache that is never cleared
([oxc-project/oxc#25510](oxc-project/oxc#25510),
whose fix has been waiting for review since August). So the callbacks of
each parse stayed alive for the rest of the process, along with the
function bodies, scopes, and templates they reached.

- The visitor, its callbacks, and the scope helpers (`pushScope`,
`popScope`, `findFunctionScope`, `recordBindingPattern`, `recordParams`,
and `addCssTagCandidate`) now live at module level. The state of a visit
is held in module-level variables, which `visitProgram(program,
rootScope)` resets before each visit. A visit is synchronous, so visits
cannot interleave.
- `functionBodies` and `firstSwitchCases` test membership with
`delete()` instead of `has()`, so they empty out as their nodes are
visited instead of keeping the nodes of every file.
- `extractCssTagCandidates`, called once per parse, is inlined into
`parseFile`.
- `hashText` uses the one-shot `crypto.hash()`, stable since Node
24.13.1, instead of `createHash()`: same output, about 2.3× faster on
these short strings.
- `unicorn/consistent-function-scoping` is enabled: the override and its
`TODO: enable` are gone, and the `suspicious` category turns the rule
on. It has no findings, and it flags nested functions that capture
nothing from their parent scope.
- AGENTS.md says not to create a `Visitor` per file, as no test would
catch the leak.

Most of the diff moves code. `git diff --color-moved=dimmed-zebra
--color-moved-ws=allow-indentation-change` shows only the edits.

Left as is:
- `resolveValue` and `resolveBinding`. They close over the state of one
transform (`context`, `filePath`, `constValues`, and
`stylesheetDependencies`), so moving them out would mean passing a state
object through every call, to save about two small allocations per
transform.
- `isWaitingFor`, `parseFile`, and `extractCssFromCode`, created once
per plugin instance.
- Option literals like `{ encoding: 'utf8' }` and `{ hires: 'boundary'
}`, warning objects, and the `?? []` fallbacks in `watchChange` and
`hotUpdate`. Each is one short-lived object next to a file read or
sourcemap generation, or on a path that rarely runs.

## Test plan

- `node --run test` (locally and with `CI=true` against `dist/`),
`lint`, `typecheck`, `format:check`, `build`, and `lint:package` pass,
with no snapshot changes. `src/index.ts` coverage is unchanged: the
`TSParameterProperty` branch is still the only uncovered statement.
- Replaying the transforms of react-data-grid's 15 ecij modules 2,000
times with a stub plugin context, calling `buildEnd` between rounds: the
heap grew from 109 to 1,115 MB before, and stays at about 8 MB now. Each
file takes about 264 µs instead of 277 µs.
- oxlint flags a nested function that captures nothing now that
`unicorn/consistent-function-scoping` is enabled.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
nstepien added a commit that referenced this pull request Oct 17, 2026
## Summary

When CodeRabbit reviews a PR, it appends a "Summary by CodeRabbit" block
to the PR description by default. Squash merges use the description as
the commit message, so #109's summary landed in `main` until its message
was rewritten.

The new `.coderabbit.yaml` sets
`reviews.high_level_summary_in_walkthrough: true`, which [places the
summary at the top of the walkthrough comment instead of the
description](https://docs.coderabbit.ai/pr-reviews/summaries#moving-the-summary-to-the-walkthrough).
The rest keeps CodeRabbit's defaults. A repository file takes precedence
over settings made in CodeRabbit's UI, but #109's review reported
"Configuration used: defaults", so there were none to lose. The first
line points editors to CodeRabbit's schema for validation and
completion.

## Test plan

- CodeRabbit uses the `.coderabbit.yaml` of the branch under review: its
comment here reports "Configuration used: Repository:
nstepien/ecij/.coderabbit.yaml". Once a review is triggered, it should
put the summary in its walkthrough comment and leave this description
untouched
- `node --run format:check` (which now includes this file), `lint`,
`typecheck`, `build`, `lint:package`, and `test` pass

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
nstepien added a commit that referenced this pull request Nov 4, 2026
main reshaped the code this branch builds on since the last merge, so
the merge ports the branch onto main's design again:

- The scope visitor is shared across parses (#109), so the callbacks
  for raw TypeScript bindings and `export default` join it, and the
  default export is recorded through its visit state.
- Imported modules are resolved, loaded, and parsed once per transform
  through main's loadImportedModule (#124), which now also skips
  external modules, keys modules by moduleKey, and records dependencies
  by file.
- Modules are parsed as the language the bundler assigned them through
  main's parseLangOf (#125), which this branch had too.
- extractCssFromCode keeps main's single pass (#114), and hotUpdate its
  early return, with this branch's handling of query variants.
- readModuleCode moved to module level, as consistent-function-scoping
  is on since #109.

Tests: the inline snapshots of this branch's tests follow Rolldown's new
module comments (`// path` instead of `//#region path` and
`//#endregion`), with no other change. The dev server test of virtual
modules uses main's shared getCode and getStylesheets helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

1 participant