Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 42 additions & 6 deletions src/bundler/linker_context/renameSymbolsInChunk.zig
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,17 @@
var sorted = &sorted_;
defer sorted.deinit();

// Two passes are required so that every top-level symbol is registered in
// `r.root` before any nested scope is visited. Without this, a local
// binding in file/part N could collide-rename into a name that is later
// claimed by a top-level symbol in file/part M (M > N), silently shadowing
// it in the output. See https://github.com/oven-sh/bun/issues/30269.
//
// Pass 1 adds all top-level symbols for the chunk (across every file).
// Pass 2 recurses into the nested scopes; by then `r.root` is fully
// populated so `findUnusedName` sees every potential top-level collision.

// Pass 1: add every top-level symbol in the chunk to `r.root`.
for (files_in_order) |source_index| {
const wrap = all_flags[source_index].wrap;
const parts: []const Part = all_parts[source_index].slice();
Expand Down Expand Up @@ -213,7 +224,10 @@
}
}
}
r.assignNamesRecursiveWithNumberScope(&r.root, &all_module_scopes[source_index], source_index, sorted);
// The module body is inside the CJS wrapper closure, so all
// of its symbols are treated as nested by the renamer; pass 2
// will walk `all_module_scopes[source_index]`. No per-part
// top-level symbols to add here.
continue;
},

Expand All @@ -240,15 +254,37 @@

for (parts) |*part| {
if (!part.is_live) continue;

r.addTopLevelDeclaredSymbols(part.declared_symbols);
for (part.scopes) |scope| {
r.assignNamesRecursiveWithNumberScope(&r.root, scope, source_index, sorted);
}
r.number_scope_pool.hive.used = @TypeOf(r.number_scope_pool.hive.used).initEmpty();
}
}

// Pass 2: now that `r.root` has every top-level symbol in the chunk,
// recurse into each file's nested scopes to rename collisions.
for (files_in_order) |source_index| {
const wrap = all_flags[source_index].wrap;
switch (wrap) {
.cjs => {
// For CJS-wrapped modules, the entire module scope is nested
// (it lives inside the wrapper closure). Walk it directly.
r.assignNamesRecursiveWithNumberScope(&r.root, &all_module_scopes[source_index], source_index, sorted);
},
else => {
const parts: []const Part = all_parts[source_index].slice();
for (parts) |*part| {
if (!part.is_live) continue;
for (part.scopes) |scope| {
r.assignNamesRecursiveWithNumberScope(&r.root, scope, source_index, sorted);
}
}
},
}
// Bulk-release every NumberScope we borrowed from the pool while
// processing this file. The recursive walk has already put each scope
// back individually; this is just a defensive reset that matches the
// previous per-part behavior.
r.number_scope_pool.hive.used = @TypeOf(r.number_scope_pool.hive.used).initEmpty();

Check warning on line 285 in src/bundler/linker_context/renameSymbolsInChunk.zig

View check run for this annotation

Claude / Claude Code Review

Misleading comment: number_scope_pool reset is not purely defensive

nit: this comment is inaccurate on both points. (1) The recursive walk does *not* put every scope back individually — `assignNamesRecursiveWithNumberScope`'s linear single-child-chain loop (renamer.zig:600-617) calls `number_scope_pool.get()` per scope-with-members but the `defer` only puts back the final `s`; intermediate NumberScopes stay marked used in the hive until this bulk reset reclaims them, so the reset is load-bearing for hive-slot reuse, not "just defensive". (2) It no longer "matche
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}

return r.toRenamer();
}

Expand Down
111 changes: 111 additions & 0 deletions test/regression/issue/30269.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// https://github.com/oven-sh/bun/issues/30269
//
// The ESM bundler renamer used to interleave two operations per part:
// 1. register that part's top-level symbols in the root scope, and
// 2. walk that part's nested scopes to rename collisions with the root.
//
// Because nested-scope walking for part N happened before part M>N's
// top-level symbols had been registered, a local binding in part N could be
// renamed to a name (`r` → `r2`) that later became a top-level symbol in
// part M (here the `r2` function). The local `r2` then shadowed the
// top-level `r2`, and callers inside `typecheck` invoked an `Expression`
// instance instead of the function.
//
// Fix: split the single-pass interleaved loop into two passes — register
// all top-level symbols for the whole chunk first, then walk nested scopes.
// Matches esbuild's structure.
import { expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";

test("#30269 bundler doesn't rename a nested local into another top-level symbol's name", async () => {
using dir = tempDir("bun-issue-30269", {
// Importing this forces Bun's ESM renamer to treat `r` as a conflicting
// name at the chunk's root scope. Removing `conflict.r()` from main.js
// hides the bug.
"conflict.js": `
export function r() {
return "top-level r";
}
`,
// `typecheck` has a nested \`let r\`. The renamer picks \`r2\` for it —
// but \`r2\` is already a top-level function in the same file.
Comment on lines +30 to +31

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.

🟡 Tiny cosmetic nit: the \`` sequences in these //comments render as a literal backslash followed by a backtick, since line comments don't process escapes (note ``typecheck`` on the same line is already unescaped). Just drop the four backslashes so it reads ``let r`` / ``r2` ``.

Extended reasoning...

What this is

Lines 30-31 of the new test file are ordinary // line comments sitting between two object-literal properties — after the closing backtick of the conflict.js template literal on line 29 and before the opening backtick of module.js on line 32:

    `,
    // `typecheck` has a nested \`let r\`. The renamer picks \`r2\` for it —
    // but \`r2\` is already a top-level function in the same file.
    "module.js": `

Because these are plain TypeScript line comments (not inside any template literal), the source bytes are taken verbatim — \`` is not an escape sequence here, so it renders as a literal backslash followed by a backtick. The very same line already writes `` typecheck`` with an unescaped backtick, which confirms the`` instances are leftovers from when this prose lived inside a template literal and needed escaping.

Step-by-step

  1. The TypeScript scanner sees // on line 30 and enters single-line-comment mode.
  2. In single-line-comment mode, every byte up to the newline is consumed literally; there is no escape processing (ECMA-262 §12.4: SingleLineComment :: // SingleLineCommentChars, where the chars are any source character except line terminators).
  3. The byte sequence \ ` therefore stays as two characters — backslash, backtick — in the comment text.
  4. A reader (or anything that surfaces the comment, e.g. an IDE hover, GitHub diff view) sees nested \`let r\`. The renamer picks \`r2\` … with stray backslashes.
  5. Contrast: `typecheck` earlier on line 30 is written without \ and reads correctly — the inconsistency is the giveaway that the escapes are accidental.

Why nothing prevents it

There is nothing to prevent — the parser, the test runner, and the bundled fixture are all completely unaffected. Comments are discarded before execution. No linter in this repo flags ``` in comments. This is purely a readability / consistency issue in newly-added prose.

Impact

Zero functional impact. The test compiles, runs, and catches the #30269 regression identically with or without the backslashes. The only effect is that the explanatory comment reads slightly oddly with four stray \ characters, and is internally inconsistent (`typecheck` vs. \`r2\` ).

Fix

Delete the four backslashes:

-    // `typecheck` has a nested \`let r\`. The renamer picks \`r2\` for it —
-    // but \`r2\` is already a top-level function in the same file.
+    // `typecheck` has a nested `let r`. The renamer picks `r2` for it —
+    // but `r2` is already a top-level function in the same file.

"module.js": `
class Expression {}

export function run() {
const result = typecheck({ left: new Expression(), op: {}, right: {} });
if (result !== true) throw new Error("expected true");
return result;
}

function typecheck(node) {
let r, t, c;
block: {
let k = node.left;
let I = node.op;
let q = node.right;
r = k;
t = I;
c = q;
break block;
}

let d = r;
let n = t;
let s = c;
return r2().bo4(d, n, s).a();
}

function r2() {
return {
bo4() {
return {
a() {
return true;
},
};
},
};
}
`,
"main.js": `
import * as conflict from "./conflict.js";
import { run } from "./module.js";

conflict.r();
console.log("ok:", run());
`,
});

// Bundle, then run the bundled file. The renamer bug is triggered during
// bundling; executing the bundle is what surfaces the TypeError.
await using build = Bun.spawn({
cmd: [bunExe(), "build", "--outfile", "out.js", "main.js"],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
{
const [stdout, stderr, exitCode] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]);
// `stdout` carries the "Bundled N modules" banner; assert on it before
// the exit-code check so a build failure shows what bun actually printed.
expect(stdout).toContain("out.js");
expect(exitCode, stderr).toBe(0);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

await using run = Bun.spawn({
cmd: [bunExe(), "out.js"],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
// On the buggy build this stderr contains:
// TypeError: r2 is not a function. (In 'r2()', 'r2' is an instance of Expression)
// Asserting on stdout + exit code is enough; stderr can hold unrelated
// debug-build warnings (e.g. MADV_DONTNEED) that we don't want to flake on.
expect(stdout).toBe("ok: true\n");
expect(exitCode).toBe(0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
Loading