Repository navigation
Conversation
…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.
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughREPL completion output now returns ChangesREPL metadata flow
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 12:43 AM PT - Jun 27th, 2026
❌ @robobun, your commit 4ca049e has some failures in 🧪 To try this PR locally: bunx bun-pr 32790That installs a local version of the PR into your bun-32790 --bun |
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
packages/bun-types/bun.d.tssrc/ast/ast_result.rssrc/js_parser/p.rssrc/js_parser/repl_transforms.rssrc/js_printer/lib.rstest/js/bun/transpiler/repl-transform.test.ts
- 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.
There was a problem hiding this comment.
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 winSerialize replayable locals per declarator, not per statement.
repl_local_is_serializable()gates the wholeS::Local, so one unsafe declarator drops every safe sibling, and left-to-right cases likeconst a = 1, b = aare rejected becauseais not admitted until after the full check. That under-populatesfunctionseven when replaying a filtered/left-to-rightvardeclaration 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
📒 Files selected for processing (5)
packages/bun-types/bun.d.tssrc/ast/ast_result.rssrc/js_parser/repl_transforms.rssrc/js_printer/lib.rstest/js/bun/transpiler/repl-transform.test.ts
…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.
|
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 |
There was a problem hiding this comment.
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 inbun.d.tsare user-facing design decisions a maintainer should sign off on. unsafeblock:print_repl_functions_sourceconstructs a bitwise alias ofjs_ast::symbol::Mapviacore::ptr::readparked inManuallyDropso two renamers can share the map across passes. The pattern mirrorsget_source_map_builder'sline_offset_tablesaliasing and the safety comment is reasonable, but it deserves a human eye.- Semantic analysis:
repl_eager_refs_are_admittedis a bespoke expression walker whose correctness determines whether thefunctionsstring 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.
…ler-repl-variables-functions
|
Status: the diff is complete and every review finding from claude and CodeRabbit has been addressed and resolved (latest head CI: the only hard-failing job on the last four builds (65257, 65271, 65301, 65318) is the 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 Locally against the debug build: 55/55 |
There was a problem hiding this comment.
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 winSynthetic declaration assignments now leak into
.value.
repl_finish_with_return()returns the lastSExpr, but the REPL lowering has already turned declaration/import statements into synthetic assignment expressions before this pass runs. For declaration-only snippets likeconst 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 winAdmit 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 likeclass C { static x = C }andclass C { x = C }get excluded fromfunctions. Keep the self-name out ofextendsand 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
📒 Files selected for processing (3)
packages/bun-types/bun.d.tssrc/js_parser/repl_transforms.rstest/js/bun/transpiler/repl-transform.test.ts
Only classes and let/const locals are re-declared as var in the functions string; function declarations are printed unchanged.
|
On CodeRabbit's two out-of-diff comments from the last review:
The docs wording issue is fixed in e0e5112. |
…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.
…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.
…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.
There was a problem hiding this comment.
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.
|
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. |
What
Bun.Transpiler({ replMode: true })output now always evaluates to a result object with two new properties: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 asvar. Running the string in a freshnode:vmcontext 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.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 passclass_can_be_removed_if_unused, and locals whose bindings and initializers passexpr_can_be_removed_if_unused_without_dce_checkand whose eagerly evaluated identifier reads are satisfied by the serialized declarations themselves (solet a = effect(); let b = aserializes neither, and the string never throws a ReferenceError when evaluated).usingdeclarations are never serialized since replaying one asvarwould drop disposal.let/const/classare re-declared asvarin that list so the replayed source persists onto a vm context the same way the REPL evaluation itself does. The wrapperreturnis now always emitted, withvalue: undefinedwhen there is no trailing expression.Ast.repl_functions(new,Noneoutside replMode) carries that statement list plus theE::Stringliteral to fill.js_printer::print_astruns a second print pass over those statements right before printing the tree and stores the result in that string literal. The pass uses its ownNoOpRenamerover aManuallyDropalias of the symbol map (aPrinterpins its renamer's borrow, so the map could not be handed back otherwise); this is the same patternget_source_map_builderuses for a borrowedline_offset_tables.Non-REPL printing is untouched: the only change on that path is one
Optioncheck inprint_ast.Compatibility
bun replevaluates this same wrapper and unwraps.valueas an own property, which is whyvalueis always present; its behavior is unchanged (declaration-only lines still printundefined). The wrapper previously was only returned when the last statement was an expression, so the existingrepl-transform.test.tsassertions 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-endbun 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.