Skip to content

Bun.Transpiler: add variables and functions to the replMode result object - #32790

Closed
robobun wants to merge 11 commits into
mainfrom
farm/b31b4b96/transpiler-repl-variables-functions
Closed

robobun wants to merge 11 commits into
mainfrom
farm/b31b4b96/transpiler-repl-variables-functions

Conversation

@robobun

@robobun robobun commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

What

Bun.Transpiler({ replMode: true }) output now always evaluates to a result object with two new properties:

{ __proto__: null, value, variables, functions }
  • value: the snippet's completion value. Always an own property (undefined when the snippet has no trailing expression).
  • variables: the names the snippet declares (var/let/const/function/class/import bindings), as an array of strings in source order.
  • functions: printed source of the snippet's replayable declarations (function declarations, plus classes and locals whose initializers have no side effects and only read bindings the string itself declares), re-declared as var. Running the string in a fresh node:vm context re-creates them, so a REPL can accumulate these per evaluation and replay them to resume a session on a new VM. Function bodies are not analyzed: a replayed function that closed over non-replayable state throws when called, not when defined.
const t = new Bun.Transpiler({ loader: "tsx", replMode: true });
const r = vm.runInContext(t.transformSync("function add(a, b) { return a + b } const base = 10; add(base, 5)"), ctx);
r.value;     // 15
r.variables; // ["add", "base"]
r.functions; // "function add(a, b) {\n  return a + b;\n}\nvar base = 10;\n"

vm.runInContext(r.functions, freshCtx); // restores add and base

How

  • js_parser/repl_transforms.rs: while hoisting declarations it now also collects the declared names (emitted as an array literal in the wrapper) and the statements that are safe to re-run: function declarations, classes that pass class_can_be_removed_if_unused, and locals whose bindings and initializers pass expr_can_be_removed_if_unused_without_dce_check and whose eagerly evaluated identifier reads are satisfied by the serialized declarations themselves (so let a = effect(); let b = a serializes neither, and the string never throws a ReferenceError when evaluated). using declarations are never serialized since replaying one as var would drop disposal. let/const/class are re-declared as var in that list so the replayed source persists onto a vm context the same way the REPL evaluation itself does. The wrapper return is now always emitted, with value: undefined when there is no trailing expression.
  • Ast.repl_functions (new, None outside replMode) carries that statement list plus the E::String literal to fill.
  • js_printer::print_ast runs a second print pass over those statements right before printing the tree and stores the result in that string literal. The pass uses its own NoOpRenamer over a ManuallyDrop alias of the symbol map (a Printer pins its renamer's borrow, so the map could not be handed back otherwise); this is the same pattern get_source_map_builder uses for a borrowed line_offset_tables.

Non-REPL printing is untouched: the only change on that path is one Option check in print_ast.

Compatibility

bun repl evaluates this same wrapper and unwraps .value as an own property, which is why value is always present; its behavior is unchanged (declaration-only lines still print undefined). The wrapper previously was only returned when the last statement was an expression, so the existing repl-transform.test.ts assertions on the exact object shape were updated in this PR.

Verification

  • bun bd test test/js/bun/transpiler/repl-transform.test.ts: 51 pass (the new assertions fail without the src change).
  • bun bd test test/js/bun/repl/repl.test.ts: 117 pass (end-to-end bun repl).
  • bun bd test test/bundler/transpiler/transpiler.test.js: 171 pass, 0 fail.
  • bun test test/integration/bun-types/bun-types.test.ts: 12 pass.

…ject

In replMode, the generated IIFE now always returns
{ __proto__: null, value, variables, functions }:

- value is the snippet's completion value and is always an own property
  (undefined when there is no trailing expression), so consumers that
  unwrap .value, like bun repl, behave the same as before.
- variables lists the names the snippet declares (var/let/const/function/
  class/import bindings) as strings, in source order.
- functions is the printed source of the snippet's function declarations
  and side-effect-free top-level declarations, re-declared as var so the
  string can be replayed on a fresh vm context to restore them.

The parser's REPL transform collects the declared names and the replayable
statement list (Ast.repl_functions); js_printer::print_ast runs a second
print pass over that list before printing the tree and stores the source in
the wrapper's string literal.
@robobun
robobun requested a review from alii as a code owner June 26, 2026 21:49
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 2 minutes and 35 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6d1a0c6e-ed96-4621-a9b2-1e73372767ae

📥 Commits

Reviewing files that changed from the base of the PR and between ffb66fb and 4ca049e.

📒 Files selected for processing (2)
  • src/js_parser/repl_transforms.rs
  • test/js/bun/transpiler/repl-transform.test.ts

Walkthrough

REPL completion output now returns value, variables, and functions. The parser collects replay metadata, the printer serializes replayable statements into the wrapper, and tests validate the new shape and behavior.

Changes

REPL metadata flow

Layer / File(s) Summary
Result contract
packages/bun-types/bun.d.ts, src/ast/ast_result.rs, src/js_parser/p.rs
replMode docs describe the wrapper fields, Ast gains repl_functions, and to_ast stores the optional REPL metadata on the parsed AST.
Collect metadata
src/js_parser/p.rs, src/js_parser/repl_transforms.rs
The REPL transform records declared names and replayable statements, widens helper visibility for reuse, and returns optional replay metadata.
Printer pass
src/js_printer/lib.rs, src/js_printer/renamer.rs
print_ast renders repl_functions.stmts into the wrapper's functions string before the main print pass, with an ownership comment clarification.
REPL tests
test/js/bun/transpiler/repl-transform.test.ts
The REPL tests assert the full metadata wrapper and add coverage for variable enumeration and replayable function capture.

Possibly related PRs

  • oven-sh/bun#31242: Changes the visibility of the same unused-binding/expression DCE helpers in src/js_parser/p.rs.

Suggested reviewers

  • Jarred-Sumner
  • alii
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding variables and functions to replMode's result object.
Description check ✅ Passed The description covers the PR purpose and verification, with only a minor heading mismatch from the template.
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.

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

@robobun

robobun commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:43 AM PT - Jun 27th, 2026

❌ @robobun, your commit 4ca049e has some failures in Build #65318 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 32790

That installs a local version of the PR into your bun-32790 executable, so you can run:

bun-32790 --bun

Comment thread src/js_parser/repl_transforms.rs Resolved
For import def, * as ns from "mod" the default binding was recorded after
the namespace binding. The default binding always comes first in the
import clause grammar, so record it first.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/ast/ast_result.rs`:
- Around line 67-71: Update the ownership-flow comment on repl_functions in
AstResult to match the actual data flow: P::to_ast() populates the field, and
js_printer::print_ast only updates the embedded E::String slot. Adjust the
wording so readers tracing REPL metadata are directed to AstResult/P::to_ast
rather than implying the printer fills the whole field. Keep the reference to
repl_functions and js_printer::print_ast so the comment is easy to locate.

In `@src/js_parser/repl_transforms.rs`:
- Around line 853-865: The repl serialization check is treating top-level using
declarations as safe to replay, which can incorrectly turn `using` and `await
using` into plain variables in the fresh-VM path. Update
repl_local_is_serializable() in repl_transforms.rs to explicitly reject locals
whose declarations are using/await using so they are not emitted into functions
metadata, while keeping the existing purity checks for normal bindings and
initializers.
- Around line 50-51: The zero-statement path in replMode still returns None,
which bypasses the REPL wrapper for blank input and yields bare undefined
instead of the expected result object. Update the early-return logic in replMode
and the related empty-program handling around total_stmts_count so empty
submissions still flow through the wrapper and produce { value: undefined,
variables: [], functions: "" } rather than exiting early.

In `@src/js_printer/lib.rs`:
- Around line 7845-7873: The second-pass REPL printer in print_ast is swallowing
failures and leaving slot.data as an empty string, so propagate any print_stmt,
writer, or done errors instead of treating them like “nothing to print.” Update
the logic around Printer::init, print_stmt, printer.writer.get_error, and
printer.writer.done so failures stop the pass and surface an error rather than
returning success with functions: "".
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0d4d3ca8-5a1a-4325-a93d-2ddae279b522

📥 Commits

Reviewing files that changed from the base of the PR and between 642b9f6 and f8cb26c.

📒 Files selected for processing (6)
  • packages/bun-types/bun.d.ts
  • src/ast/ast_result.rs
  • src/js_parser/p.rs
  • src/js_parser/repl_transforms.rs
  • src/js_printer/lib.rs
  • test/js/bun/transpiler/repl-transform.test.ts

Comment thread src/ast/ast_result.rs Resolved
Comment thread src/js_parser/repl_transforms.rs Resolved
Comment thread src/js_parser/repl_transforms.rs Resolved
Comment thread src/js_printer/lib.rs Resolved
Comment thread src/js_parser/repl_transforms.rs Resolved
- A pure initializer can read a sibling binding that was excluded for
  having side effects (let a = effect(); let b = a), and replaying
  var b = a on a fresh context would throw a ReferenceError. Track the
  bindings the functions string itself declares and only admit
  declarations whose eagerly evaluated identifier reads are satisfied
  by that set. Function and arrow bodies are deferred, so they are not
  analyzed.
- Never serialize using / await using declarations: replaying one as a
  plain var would drop its disposal semantics.
- Propagate second-pass printer errors instead of silently emitting an
  empty functions string.
- Clarify the Ast.repl_functions ownership comment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/js_parser/repl_transforms.rs (1)

147-162: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Serialize replayable locals per declarator, not per statement.

repl_local_is_serializable() gates the whole S::Local, so one unsafe declarator drops every safe sibling, and left-to-right cases like const a = 1, b = a are rejected because a is not admitted until after the full check. That under-populates functions even when replaying a filtered/left-to-right var declaration would be valid.

Also applies to: 873-896

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/js_parser/repl_transforms.rs` around lines 147 - 162, The replay
transform is treating an entire local statement as serializable instead of
checking each declarator independently, which causes safe declarators to be
dropped when one sibling is unsafe and breaks left-to-right cases like `const a
= 1, b = a`. Update `repl_transforms` in the `repl_local_is_serializable` /
`S::Local` path so serialization is decided per declarator, not per statement,
and make sure admitted references are updated incrementally as you walk each
binding in declaration order. Keep the existing `serializable_stmts`,
`admitted_refs`, and `hoisted_decl_list` flow, but filter/split the
`local.decls` before emitting the replayable `S::Local` entries.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/bun-types/bun.d.ts`:
- Around line 2506-2511: The `functions` documentation in `bun.d.ts` is too
broad because it implies all class declarations are replayed, but
`repl_transforms.rs` only serializes classes that are replay-safe. Update the
wording near the `functions` bullet to refer specifically to
replayable/removable classes, and keep the rest of the explanation aligned with
the actual serialization rules used by the REPL transform logic.

---

Outside diff comments:
In `@src/js_parser/repl_transforms.rs`:
- Around line 147-162: The replay transform is treating an entire local
statement as serializable instead of checking each declarator independently,
which causes safe declarators to be dropped when one sibling is unsafe and
breaks left-to-right cases like `const a = 1, b = a`. Update `repl_transforms`
in the `repl_local_is_serializable` / `S::Local` path so serialization is
decided per declarator, not per statement, and make sure admitted references are
updated incrementally as you walk each binding in declaration order. Keep the
existing `serializable_stmts`, `admitted_refs`, and `hoisted_decl_list` flow,
but filter/split the `local.decls` before emitting the replayable `S::Local`
entries.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: face0184-d21a-4a62-9d45-a3f0211fd7ee

📥 Commits

Reviewing files that changed from the base of the PR and between f8cb26c and 27cc736.

📒 Files selected for processing (5)
  • packages/bun-types/bun.d.ts
  • src/ast/ast_result.rs
  • src/js_parser/repl_transforms.rs
  • src/js_printer/lib.rs
  • test/js/bun/transpiler/repl-transform.test.ts

Comment thread packages/bun-types/bun.d.ts Resolved
Comment thread src/js_parser/repl_transforms.rs Resolved
Comment thread src/js_parser/repl_transforms.rs Resolved
…ort-with-namespace

- Check declarators left to right and admit each one's bindings for the
  rest of the statement, so const a = 1, b = a serializes. A rejected
  statement rolls its bindings back and is dropped whole.
- Destructuring defaults and computed pattern keys are evaluated when a
  declaration runs, so they now go through the same admitted-reads check
  as initializers.
- Classes with a non-empty static block are never serialized: the block
  body is a statement list that is not analyzed for references.
- import def, * as ns from 'mod' only bound ns in replMode because the
  default branch of the hoisting chain is unreachable when a namespace
  clause is present. Hoist the default binding and assign it from the
  namespace, matching the other import shapes.
- Narrow the replMode type docs: classes are only replayed when their
  evaluation is side-effect free.
@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

CodeRabbit's out-of-diff comment (serialize locals per declarator) is addressed in b7c71db: declarators are now checked left to right and admit their bindings as they go, so const a = 1, b = a is replayable. A statement with a non-replayable declarator is still dropped whole rather than split, to keep the printed declarations identical to source statements.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

b7c71db addresses both of my open comments (binding defaults / static blocks now go through the admitted-refs check, and import def, * as ns now hoists and assigns def), and the bug hunt found nothing further — but this adds public API surface to Bun.Transpiler and an unsafe symbol-map alias in print_repl_functions_source, so it's worth a human look before merging.

Extended reasoning...

Overview

This PR extends Bun.Transpiler({ replMode: true }) so the emitted IIFE always returns { __proto__: null, value, variables, functions }. It threads a new Ast.repl_functions field from the parser's REPL transform through to a second printer pass that renders replayable declarations into a string literal. The bulk of the change is in src/js_parser/repl_transforms.rs (~500 new lines: name collection, a hand-written eager-evaluation reference walker repl_eager_refs_are_admitted, serializability filtering for locals/classes, and a fix to the pre-existing import def, * as ns hoisting gap), plus ~80 lines in src/js_printer/lib.rs for the second print pass, a small Ast field addition, two visibility widenings in p.rs, type docs in bun.d.ts, and ~180 lines of tests.

Prior review status

I left two inline comments after 27cc736 (eager-read gaps in destructuring defaults / class static blocks; import def, * as ns never binding def). Commit b7c71db addresses both: repl_binding_eager_refs_are_admitted now covers pattern defaults and computed keys, repl_class_eager_refs_are_admitted rejects non-empty static blocks, and the star-import branch now also hoists/assigns the default binding. Each fix has a regression test. All earlier CodeRabbit and claude comments are resolved. The bug-hunting system found no issues on the current revision.

Security risks

None identified. The change is confined to the opt-in replMode transform and the printer; it does not touch auth, filesystem, network, or process boundaries. The functions string is derived from caller-supplied source the caller is already evaluating, so it introduces no new injection surface.

Level of scrutiny

Medium-high, warranting human review rather than auto-approval:

  • New public API: the { value, variables, functions } contract and the documented replay semantics in bun.d.ts are user-facing design decisions a maintainer should sign off on.
  • unsafe block: print_repl_functions_source constructs a bitwise alias of js_ast::symbol::Map via core::ptr::read parked in ManuallyDrop so two renamers can share the map across passes. The pattern mirrors get_source_map_builder's line_offset_tables aliasing and the safety comment is reasonable, but it deserves a human eye.
  • Semantic analysis: repl_eager_refs_are_admitted is a bespoke expression walker whose correctness determines whether the functions string is sound to replay; it has gone through three correctness iterations during review.

Other factors

The non-REPL print path is untouched apart from one Option check. Test coverage is good (51 transform tests, 117 end-to-end repl tests, 171 transpiler tests, type tests all reported passing). The PR has iterated thoughtfully on every piece of feedback. I'm deferring rather than approving solely because the scope (public API + unsafe + custom soundness analysis) is beyond what I'd auto-approve, not because of any outstanding concern.

@robobun

robobun commented Jun 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: the diff is complete and every review finding from claude and CodeRabbit has been addressed and resolved (latest head 4ca049e05f).

CI: the only hard-failing job on the last four builds (65257, 65271, 65301, 65318) is the darwin 26 aarch64 - test-bun lane, which dies before running a single test:

Error: buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun'. Refusing to continue with a partial download

Same agent pool each time, so it needs an agent-side fix or a job retry once the host recovers; it is unrelated to this diff. Build 65318 (the latest head) finished with 280 jobs passed and only those 2 jobs failed. Everything else is green apart from auto-retried known-flaky tests (bake dev server, update-interactive, node-dns on Windows/macOS). An earlier run was also red on test/js/node/tls/node-tls-connect.test.ts asserting an OCSP URI on the live bun.sh certificate; that test was fixed on main in #32789 and this branch includes it.

Locally against the debug build: 55/55 test/js/bun/transpiler/repl-transform.test.ts (the new assertions fail without the src change), 117/117 test/js/bun/repl/repl.test.ts, 171 pass in test/bundler/transpiler/transpiler.test.js, and the bun-types integration test passes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/js_parser/repl_transforms.rs (2)

679-681: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Synthetic declaration assignments now leak into .value.

repl_finish_with_return() returns the last SExpr, but the REPL lowering has already turned declaration/import statements into synthetic assignment expressions before this pass runs. For declaration-only snippets like const x = 1;, that makes the wrapper return the assignment value instead of { value: undefined, ... }, which breaks the new contract for declaration-only input.

Also applies to: 845-887

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/js_parser/repl_transforms.rs` around lines 679 - 681, The REPL wrapper
currently lets synthetic assignment expressions from lowered
declarations/imports become the returned `.value`, which breaks declaration-only
snippets. Update repl_finish_with_return() and the surrounding REPL lowering
flow in js_parser/repl_transforms.rs so that only a real trailing expression is
wrapped as the return value; if the last statement is a synthetic
declaration/import assignment, treat it as non-value-producing and emit
undefined for .value instead. Use the existing symbols
repl_finish_with_return(), inner_stmts, and the declaration/import lowering path
to keep the contract consistent.

264-269: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Admit the class name for field initializers

src/js_parser/repl_transforms.rs:264-269,1127-1162 — repl_class_eager_refs_are_admitted() needs the class self binding when checking eagerly evaluated field initializers, or replayable forms like class C { static x = C } and class C { x = C } get excluded from functions. Keep the self-name out of extends and computed keys.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/js_parser/repl_transforms.rs` around lines 264 - 269,
`repl_class_eager_refs_are_admitted()` is rejecting replayable classes because
it does not admit the class self binding when evaluating field initializers, so
update the class-handling path in `repl_transforms.rs` to treat the class name
as admissible for static/instance field initializer checks. Make the change in
the logic that walks class members so `class C { static x = C }` and `class C {
x = C }` can be included in `functions`, while still excluding the self-name
from `extends` and computed property key evaluation; use the existing
`repl_follow_ref`, `class_can_be_removed_if_unused`, and
`repl_class_eager_refs_are_admitted` flow to localize the fix.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/bun-types/bun.d.ts`:
- Around line 2506-2510: The `functions` documentation in `bun.d.ts` overstates
the replay behavior by saying everything is re-declared as `var`, which
conflicts with the actual handling of function declarations. Update the wording
near the `functions` description to state that function declarations remain
function declarations, while only replayable `class` and `var`/`let`/`const`
locals are rewritten to `var` form; keep the explanation aligned with the
surrounding `replayable declarations` text and the `functions` entry.

---

Outside diff comments:
In `@src/js_parser/repl_transforms.rs`:
- Around line 679-681: The REPL wrapper currently lets synthetic assignment
expressions from lowered declarations/imports become the returned `.value`,
which breaks declaration-only snippets. Update repl_finish_with_return() and the
surrounding REPL lowering flow in js_parser/repl_transforms.rs so that only a
real trailing expression is wrapped as the return value; if the last statement
is a synthetic declaration/import assignment, treat it as non-value-producing
and emit undefined for .value instead. Use the existing symbols
repl_finish_with_return(), inner_stmts, and the declaration/import lowering path
to keep the contract consistent.
- Around line 264-269: `repl_class_eager_refs_are_admitted()` is rejecting
replayable classes because it does not admit the class self binding when
evaluating field initializers, so update the class-handling path in
`repl_transforms.rs` to treat the class name as admissible for static/instance
field initializer checks. Make the change in the logic that walks class members
so `class C { static x = C }` and `class C { x = C }` can be included in
`functions`, while still excluding the self-name from `extends` and computed
property key evaluation; use the existing `repl_follow_ref`,
`class_can_be_removed_if_unused`, and `repl_class_eager_refs_are_admitted` flow
to localize the fix.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 95512e98-485d-49bc-8f8d-1a7bbfa643e1

📥 Commits

Reviewing files that changed from the base of the PR and between 27cc736 and 049a1fb.

📒 Files selected for processing (3)
  • packages/bun-types/bun.d.ts
  • src/js_parser/repl_transforms.rs
  • test/js/bun/transpiler/repl-transform.test.ts

Comment thread packages/bun-types/bun.d.ts Resolved
Only classes and let/const locals are re-declared as var in the
functions string; function declarations are printed unchanged.
@robobun

robobun commented Jun 27, 2026

Copy link
Copy Markdown
Collaborator Author

On CodeRabbit's two out-of-diff comments from the last review:

  • "Synthetic declaration assignments now leak into .value": this is pre-existing replMode behavior, not something this PR added or changed. The REPL lowering has always rewritten a trailing declaration into its assignment expression, so const x = 1 evaluates to { value: 1 } (and bun repl echoes 1 for it today). The contract documented here is "the completion value of the snippet" with value always an own property; changing what counts as the completion value for trailing declarations is a separate behavioral decision from this PR.
  • "Admit the class name for field initializers": deliberate conservatism. A class whose static field initializer references the class itself (class C { static x = C }) is currently not captured in functions, which errs in the safe direction (omission, never a throwing replay). Admitting the self binding only for value and initializer positions, but not for extends or computed keys, means threading an extra parameter through the expression walker; happy to do that as a follow-up if it matters in practice.

The docs wording issue is fixed in e0e5112.

Comment thread src/js_parser/repl_transforms.rs Resolved
Comment thread src/js_printer/lib.rs Resolved
…ns string

Import statements are not serialized into the replay source, so a
declaration that eagerly reads an import binding (const x = foo after
import { foo } from 'mod') would throw a ReferenceError on a fresh VM.
Reject those reads like any other non-admitted binding.

Also note the NoOpRenamer aliasing exception in its ownership comment.
Comment thread src/js_parser/repl_transforms.rs Resolved
Comment thread src/js_parser/repl_transforms.rs Resolved
…tion call

A pure-annotated IIFE passes the side-effect gate but runs its body when
the declaration is evaluated, and bodies are not analyzed for admitted
reads. Reject call and new expressions whose target is an inline function
or arrow so the functions string cannot smuggle in an unsatisfiable read.

Also clarify that only static class field initializers run at definition
time; instance initializers are checked the same way, conservatively.
Comment thread src/js_parser/repl_transforms.rs Resolved
…call

The previous guard only rejected inline function targets, but any
pure-annotated call or new runs a callee body that is never analyzed:
const x = /* @__PURE__ */ f() where f is a snippet function reading
non-replayable state would make the functions string throw on replay.
Calls and new expressions in eagerly evaluated positions are now always
rejected, like non-empty static blocks.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4ca049e addresses my last concern (ECall/ENew now reject unconditionally, with a test covering the admitted-identifier-target case). No further issues from me, but given the unsafe symbol-map aliasing in the printer and the number of rounds it took to converge on the replay-soundness invariant, this is worth a human pass.

Extended reasoning...

Overview

This PR extends Bun.Transpiler({ replMode: true }) so the emitted IIFE always returns { __proto__: null, value, variables, functions }. It touches the parser's REPL transform (src/js_parser/repl_transforms.rs, ~500 new lines), threads a new Option<ReplFunctions> through Ast (src/ast/ast_result.rs), adds a second print pass in src/js_printer/lib.rs that serializes replayable declarations into a string literal before the main pass, widens two DCE-helper visibilities in p.rs, updates an ownership comment in renamer.rs, documents the new shape in bun.d.ts, and adds ~200 lines of tests.

The non-REPL path is untouched apart from one Option match in print_ast, so blast radius is contained to replMode callers (chiefly bun repl).

Security risks

None apparent. The feature is opt-in, operates on already-parsed user source, and emits source text the caller chooses whether to evaluate. No auth, crypto, network, or filesystem surface is touched.

Level of scrutiny

Medium-high. The change is gated and well-tested, but it (a) introduces ~70 lines of new unsafe-adjacent code in print_repl_functions_source that ptr::read-aliases the symbol Map under ManuallyDrop (sound and documented, mirroring the existing get_source_map_builder pattern, but still a second owner of a non-Copy map), and (b) defines a new public API contract ("the functions string evaluates cleanly on a fresh vm context") whose soundness took five review rounds to converge: sibling locals → destructuring defaults/static blocks → import identifiers → inline-IIFE targets → all calls. Each round was a real ReferenceError-on-replay hole; 4ca049e closes the last one I flagged by rejecting ECall/ENew outright, and the test now covers both the inline-IIFE and admitted-identifier-callee cases.

Other factors

All prior inline comments (mine and CodeRabbit's) are addressed in code; the only thread not yet marked resolved is my last one, which 4ca049e fixes exactly as suggested. Test coverage is thorough (each soundness fix has a regression test, several of which actually replay functions on vm.createContext({})). The author reports the relevant local suites and bun repl end-to-end tests pass; CI's only red lane is an unrelated darwin artifact-download timeout. Given the iteration history and the unsafe block, I'd rather a human confirm the final shape than auto-approve.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-06-27, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant