Skip to content

js_printer: print a valid expression for an unused require() operand - #42448

Open
robobun wants to merge 4 commits into
mainfrom
robobun/c4f12fc0/unused-require-empty-expr
Open

robobun wants to merge 4 commits into
mainfrom
robobun/c4f12fc0/unused-require-empty-expr

Conversation

@robobun

@robobun robobun commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • bun build prints wrong or unparsable code when a require() of a bundled ES module is an operand of an expression statement. c ? require("./a") : require("./b"); prints c ? __toCommonJS(exports_a) : ; (SyntaxError: Unexpected token ';'). require("./a") ? x() : y(); always calls y().
  • The EIf and EIndex arms (src/js_printer/lib.rs:3803, :3739) pass the printer flag ExprResultIsUnused to their operands.
  • With that flag, print_require_or_import_expr (lib.rs:2780) prints nothing for a module with no init_* wrapper.

Fix

  • EIf passes only ForbidIn to its test. EIndex passes only HasNonOptionalChainParent | ForbidCall to its target. esbuild has the same masks.
  • An unused require() that printed nothing now prints 0, which nothing reads: log(1),0,log(2), if(c)0, 0;.
  • Verified: three new tests in test/bundler/bundler_edgecase.test.ts fail on main (179664e). Other suites: Notes. Self-reviewed: 10 concerns raised, 9 addressed, 1 rejected (Notes).

Background

Downsides

Notes

Merge of main (179664e). The branch was 596 commits behind. The merge has no conflict, and the diff of src/js_printer/lib.rs is the same. Two lines of the inline snapshot of edgecase/EsmWrapperEliminationUnusedRequire changed. They are the output of const { name } = require("./b.js"); log.push(name);:

tree prints
the old base of this PR (4b5862f) 0; and log.push(name2);
main with this PR const { name } = __toCommonJS(exports_b); and log.push(name);

The cause is #42471. It binds a require() pattern local only to a function declaration or a namespace object. The pattern of a const export is a copy again, so it does not fold to an unused require(). The local has the name name because #41286 (1.4.1) lets a nested binding keep its name. No other line of the snapshot changed.

The byte count in Downsides. A pattern of a function export is still folded. b.js is export function name() { return "b"; }. entry.js is export function f() { const { name } = require("./b.js"); return name(); } console.log(f());. With --target=bun --minify-syntax --minify-whitespace, 1.4.4 prints function f(){;return name()} (90 bytes for the file). This PR prints function f(){0;return name()} (91 bytes).

Cost when the bug is not hit, from the diff. Each printed require() or import() of a bundled module reads the output length one time and tests one flag. Each conditional applies one mask. No allocation.

History. No user report exists. #42376 found the first form and left it for a separate change. So did #41638, for the mask. The wrong branch (init_a() ? x() : y()) is in 1.0.0. The unparsable forms start in v1.1.21, the first release with #12729. 1.1.20 prints flag ? (init_st(), __toCommonJS(exports_st)) : init_ot();.

Before and after, bun build --target=bun. ./a and ./b have no wrapper, ./w has one. 1.4.3 prints the same as 1.4.4:

source 1.4.4 this PR
flag ? require("./a") : require("./b"); flag ? __toCommonJS(exports_a) : ; flag ? __toCommonJS(exports_a) : __toCommonJS(exports_b);
require("./a") ? x() : y(); ? x() : y(); __toCommonJS(exports_a) ? x() : y();
require("./a")[k]; [k]; __toCommonJS(exports_a)[k];
require("./a"), x(); , x(); 0, x();
x(), require("./b"); x(), ; x(), 0;
require("./a"); ; 0;
for (require("./a");;) for (;; ) for (0;; )
require("./w") ? x() : y(); init_w() ? x() : y(); (calls y) (init_w(), __toCommonJS(exports_w)) ? x() : y();
require("./w")[k]; init_w()[k]; (TypeError) (init_w(), __toCommonJS(exports_w))[k];

With --minify: function f(c){if(c)} is now if(c)0, while(c)} is now while(c)0, if(c);else} is now if(c)0;else 0, return,String(c) is now return 0,String(c), and log(1),,log(2) is now log(1),0,log(2).

Why 0 also for a whole statement. A first version kept ; for a statement that is only the require(). That is not valid under --minify-whitespace: the printer drops the ; before }, so if (c) require("./a") as the last statement prints if(c)}. One rule for every position is smaller and has no such case.

The filler applies only when the result is unused. A used require() that has nothing to print stays a loud syntax error and does not become a silent 0. The known case was var R = ; for a CommonJS module with no wrapper (#16941). #46021 gave that module a wrapper, and 1.4.4 prints var b = require_b();.

The masks also remove redundant parentheses in plain transpiler output. All forms are valid before and after:

source before after
new (a() ? c : d)() new ((a()) ? c : d) new (a() ? c : d)
(a?.b ? c : d).e ((a?.b) ? c : d).e (a?.b ? c : d).e
(a?.b ? c : d)[e] ((a?.b) ? c : d)[e] (a?.b ? c : d)[e]
(a.b?.c ? d : e)() ((a.b?.c) ? d : e)() (a.b?.c ? d : e)()

The no branch of a conditional still gets ForbidIn in every context (a ? b : (c in d)). esbuild passes it only inside a for initializer. This PR does not change that.

Rejected review concern. return require("./a") with --minify-whitespace printed return__toCommonJS(exports_a). The cause is different: the arm printed a used result with no print_space_before_identifier(). This PR left it out. #42681 has since put that call in on main.

Related. #27176 fixed the import() form of cause 2 in the same function (Promise.resolve().then(() => )).

With --react-compiler and without #42376, the compiler folds const m = flag ? require("./a") : require("./b") to the first module and leaves the statement from the first table row. On main that is a syntax error. With this PR alone the bundle has flag ? __toCommonJS(exports_a) : __toCommonJS(exports_b); and reads __toCommonJS(exports_a).name on both paths.

The other fix for cause 2 is to always create the wrapper, as esbuild does (the gate at src/js_parser/p.rs:9264). Then require() always prints init_x() and no filler is needed. The cost is an empty __esm wrapper for each such module, which #12729 removed on purpose. This PR does not do that. A maintainer can ask for it.

Suites on the merged tree, debug build.

  • test/bundler/bundler_edgecase.test.ts: 191 pass, 0 fail.
  • bundler_dynamic_import_dce, bundler_minify, bundler_cjs2esm, bundler_cjs: 575 pass, 0 fail.
  • transpiler/{transpiler,react-compiler,runtime-transpiler,function-tostring-require,simplifier-side-effects}, transpiler_constant_fold_eqeq, test/regression/issue/24709.test.ts: 398 pass, 0 fail.
  • bundler_bun, bundler_browser, bundler_splitting, bundler_promiseall_deadcode, bundler_loader, bundler_plugin, bundler_naming, bundler_defer, bundler_allow_unresolved, metafile, bundler_regressions, bundler_barrel, bundler_jsx, bundler_string, bundler_comments, bundler_drop, bundler_feature_flag, bundler_merged_enum, bundler_minify_symbol_for, bundler_banner, bundler_footer, bundler_env: 847 pass, 0 fail.
  • test/bundler/esbuild/ (13 files): 865 pass, 0 fail in the latest run. An earlier run had 864 pass, 1 fail: default/TopLevelAwaitForbiddenRequireSourceMapCLI timed out. It starts 40 bun build processes and has the default 5 s timeout. On the debug build it takes 3.9 s to 5.0 s (4.5 s in the latest run), with and without this PR: a debug build of main also timed out one time in two runs.

[human-review] gate passed · iteration 0 · 2 files touched

fails on main (without fix)
ASAN without fix: 3 failed, 11 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_edgecase.test.ts
bun test v1.4.3 (6a92015fc)

test/bundler/bundler_edgecase.test.ts:
(pass) bundler > edgecase/EmptyFile [1015.75ms]
(pass) bundler > edgecase/EmptyCommonJSModule [1053.97ms]
(pass) bundler > edgecase/NestedRedirectToABuiltin [756.73ms]
(pass) bundler > edgecase/ImportStarFunction [865.84ms]
(pass) bundler > edgecase/ImportStarSyntaxErrorBug [769.18ms]
(todo) bundler > edgecase/BunPluginTreeShakeImport
(pass) bundler > edgecase/TemplateStringIssue622 [309.14ms]
(pass) bundler > edgecase/ImportNamedFromExportStarCJS [910.28ms]
(pass) bundler > edgecase/NodeEnvDefaultUnset [962.68ms]
(pass) bundler > edgecase/NodeEnvDefaultDevelopment [1007.44ms]
(pass) bundler > edgecase/NodeEnvDefaultProduction [598.92ms]
(todo) bundler > edgecase/NodeEnvOptionalChaining
(pass) bundler > edgecase/StarExternal [510.41ms]
(pass) bundler > edgecase/ImportNamespaceAndDefault [1253.92ms]
(todo) bundler > edgecase/ExternalES6ConvertedToCommonJSSimplified
(pass) bundler > edgecase/ImportTrailingSlash [676.24ms]
(pass) bundl
... (truncated)

release without fix: 3 failed, 11 skipped
bun test v1.4.3-canary.1 (6a92015fc)

test/bundler/bundler_edgecase.test.ts:
(pass) bundler > edgecase/EmptyFile [21.43ms]
(pass) bundler > edgecase/EmptyCommonJSModule [18.66ms]
(pass) bundler > edgecase/NestedRedirectToABuiltin [19.49ms]
(pass) bundler > edgecase/ImportStarFunction [17.25ms]
(pass) bundler > edgecase/ImportStarSyntaxErrorBug [18.25ms]
(todo) bundler > edgecase/BunPluginTreeShakeImport
(pass) bundler > edgecase/TemplateStringIssue622 [6.38ms]
(pass) bundler > edgecase/ImportNamedFromExportStarCJS [17.86ms]
(pass) bundler > edgecase/NodeEnvDefaultUnset [20.88ms]
(pass) bundler > edgecase/NodeEnvDefaultDevelopment [8.94ms]
(pass) bundler > edgecase/NodeEnvDefaultProduction [8.78ms]
(todo) bundler > edgecase/NodeEnvOptionalChaining
(pass) bundler > edgecase/StarExternal [7.78ms]
(pass) bundler > edgecase/ImportNamespaceAndDefault [17.86ms]
(todo) bundler > edgecase/ExternalES6ConvertedToCommonJSSimplified
(pass) bundler > edgecase/ImportTrailingSlash [17.39ms]
(pass) bundler > edgecase/ValidLoaderSeenAsInvalid [6.43ms]
(pass) bundler > edgecase/InvalidLoaderSegfault [4.19ms]
(todo) bundler > edgecase/ScriptTagEscape
(pass) bundler > edgecase/JSONDefau
... (truncated)
passes on PR (with fix)
ASAN with fix: 11 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_edgecase.test.ts
bun test v1.4.3 (6a92015fc)

test/bundler/bundler_edgecase.test.ts:
(pass) bundler > edgecase/EmptyFile [919.40ms]
(pass) bundler > edgecase/EmptyCommonJSModule [642.46ms]
(pass) bundler > edgecase/NestedRedirectToABuiltin [741.55ms]
(pass) bundler > edgecase/ImportStarFunction [730.41ms]
(pass) bundler > edgecase/ImportStarSyntaxErrorBug [707.04ms]
(todo) bundler > edgecase/BunPluginTreeShakeImport
(pass) bundler > edgecase/TemplateStringIssue622 [179.87ms]
(pass) bundler > edgecase/ImportNamedFromExportStarCJS [750.12ms]
(pass) bundler > edgecase/NodeEnvDefaultUnset [343.53ms]
(pass) bundler > edgecase/NodeEnvDefaultDevelopment [335.99ms]
(pass) bundler > edgecase/NodeEnvDefaultProduction [332.09ms]
(todo) bundler > edgecase/NodeEnvOptionalChaining
(pass) bundler > edgecase/StarExternal [206.08ms]
(pass) bundler > edgecase/ImportNamespaceAndDefault [614.74ms]
(todo) bundler > edgecase/ExternalES6ConvertedToCommonJSSimplified
(pass) bundler > edgecase/ImportTrailingSlash [593.73ms]
(pass) bundler >
... (truncated)

release with fix: 11 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 1265ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/138] gen NodeModuleModule.lut.h
Generating /workspace/bun/build/release/codegen/NodeModuleModule.lut.h from /workspace/bun/src/jsc/modules/NodeModuleModule.cpp
[2/138] gen cpp.rs (cppbind)
[3/138] gen BunProcess.lut.h
Generating /workspace/bun/build/release/codegen/BunProcess.lut.h from /workspace/bun/src/jsc/bindings/BunProcess.cpp
[4/138] gen generated_host_exports.rs
generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited
[5/138] gen JS modules (bundle-modules)
Preprocess modules (14107ms)
Bundle modules (72ms)
Postprocesss modules (173ms)
Bundle Functions (674ms)
Generate Code (47ms)

[15.08s] Bundled "src/js" for production
  2599 kb
  197 internal modules
  13 native modules
  50 internal functions across 16 files
[5/137] cargo bun_runtime → libbun_runtime.a
^[[1m^[[92m   Compiling^[[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
^[[1m^[[92m   Compiling^[[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
^[[1m^[[92m   Compiling^[[0m bun_ptr v0.0.0 (/work
... (truncated)
diff hotspot
src/js_printer/lib.rs                 |  12 +++-
 test/bundler/bundler_edgecase.test.ts | 102 ++++++++++++++++++++++++++++++++++
 2 files changed, 112 insertions(+), 2 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                                   reads  edits  tests
src/js_printer/lib.rs                     14     16     27
test/bundler/bundler_edgecase.test.ts      4      8     27

A require() of a bundled ES module whose result is unused printed wrong
or unparsable code when it was an operand.

- The conditional and index arms passed the flags of the parent to
  their operands. With ExprResultIsUnused, the test of a conditional
  and the target of an index printed as init_x() alone, or as nothing
  when the module has no wrapper. The operands now get only the flags
  that apply to them, as in esbuild.
- When the module has no wrapper to call, an unused require() printed
  nothing. The comma operator marks its operands as unused, so
  --minify-syntax printed `a(), , b()`, and --minify-whitespace printed
  `if(c)}`. It now prints 0.
@robobun

robobun commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: the fix is complete and ready for review. The branch has main (179664e) merged in.

CI (132712): the diff is green. test/bundler/bundler_edgecase.test.ts passes on every lane: Linux x64 and aarch64 (glibc, musl, ASAN), Windows x64 and aarch64, and macOS x64 and aarch64. No bundler, printer or transpiler test failed or was retried. One job is red: test/js/first_party/ws/ws-proxy.test.ts on Windows x64. This PR does not touch WebSocket code, and the same test is red in three other recent builds of unrelated PRs (132682, 132681, 132676). It is reported as a break on main.

The merge of main

  • The branch was 596 commits behind main. The merge has no conflict, and the diff of src/js_printer/lib.rs is the same.
  • Two lines of the inline snapshot of edgecase/EsmWrapperEliminationUnusedRequire were stale. Since bundler: keep a destructured require() local a copy unless the export has its value from the start #42471, const { name } = require("./b.js") of a const export prints const { name } = __toCommonJS(exports_b);. Before, it printed 0;. The next line is now log.push(name);, not log.push(name2);.
  • On a debug build of main (179664e) without the fix, the three tests of this PR fail. With the fix, all of test/bundler/bundler_edgecase.test.ts passes (191 pass, 0 fail).

How to reproduce (any directory, Bun 1.1.21 to 1.4.4, and main):

// a.js
export const name = "a";
// b.js
export const name = "b";
// w.js
globalThis.ran = true; export const name = "w";
// e.js
export function f(flag, k) {
  flag ? require("./a") : require("./b");
  require("./w") ? console.log("truthy") : console.log("falsy");
  return String(flag);
}
f(true);
$ bun build --target=bun e.js --outfile=out.js && bun out.js
SyntaxError: Unexpected token ';'

The bundle has flag ? __toCommonJS(exports_a) : ;. Remove that line from e.js and the bundle runs, but it prints falsy: the test prints as init_w(), which returns undefined.

For the --minify forms, put console.log(1); require("./a"); console.log(2); in a function and build with --minify-syntax. The output has console.log(1), , console.log(2).

This PR: #42448. The tests are edgecase/EsmWrapperEliminationUnusedRequire, edgecase/EsmWrapperEliminationUnusedRequireMinify and edgecase/RequireOfEsmAsConditionalTestOrIndexTarget in test/bundler/bundler_edgecase.test.ts.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between fa44d74 and 6e463b9.

Files selected for processing: 2
  • src/js_printer/lib.rs
  • test/bundler/bundler_edgecase.test.ts

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

Walkthrough

The printer now preserves valid output for unused internal require() expressions and limits propagated flags for indexed expressions and conditional tests. Bundler tests cover expression contexts, minified output, and wrapped ESM modules.

Changes

Require printing behavior

Layer / File(s) Summary
Preserve unused require expressions
src/js_printer/lib.rs, test/bundler/bundler_edgecase.test.ts
The printer records the output position and emits 0 when an unused internal require() produces no output. Tests cover conditional, member, comma, loop, destructuring, and minified contexts.
Restrict operand flags
src/js_printer/lib.rs, test/bundler/bundler_edgecase.test.ts
Indexed-expression targets receive only HasNonOptionalChainParent and ForbidCall. Conditional tests receive only ForbidIn. Tests cover wrapped ESM require() results and module initialization side effects.

Suggested reviewers: jarred-sumner

Priority: Normal

Merge Risk: Minimal · up to 6e463

No actionable merge-blocking issue is identified; the change is mergeable after normal checks.

Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: the printer now emits a valid expression for an unused require() operand.
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.
Description check Passed The description clearly explains the problem, the implementation, expected behavior changes, limitations, and verification results. It does not use the template headings exactly, but it provides the r…
Full details: Description check

Explanation

The description clearly explains the problem, the implementation, expected behavior changes, limitations, and verification results. It does not use the template headings exactly, but it provides the required information through the Problem, Fix, and Notes sections.

Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
  • 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.

@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.

I reviewed this and didn't find any bugs. The printer is output-critical for every bundle and the EIf/EIndex flag masks change parenthesization for all conditionals and index expressions (not just the require() case), so a maintainer should confirm the mask choice and the open question about always emitting a wrapper.

What was reviewed:

  • The 0 fallback is gated on ExprResultIsUnused and written() == start, so a used require() with nothing to print stays a loud syntax error rather than a silent 0; the dynamic-import path prints Promise.resolve() before start is compared, so it's unaffected.
  • The new EIndex mask is byte-identical to the existing EDot mask at src/js_printer/lib.rs:3697; EBinary already rebuilds flags from empty, so EIf/EIndex were the remaining leak sites for ExprResultIsUnused.
  • e.no still receives ForbidIn unconditionally after the mask (pre-existing behavior preserved); e.yes was already ExprFlag::none().
  • Read the inline snapshot: const { name } = require("./b.js") → 0; with name bound to name2 is the linker's namespace-unused rewrite, and the run: stdout assertion confirms it executes correctly.
Extended reasoning...

Overview

The PR fixes bun build emitting syntactically invalid JavaScript when a bundled require() of a wrapper-eliminated ESM module appears as an operand whose result is unused (comma arm, ternary branch, for-init, bare statement). Three changes in src/js_printer/lib.rs: (1) print_require_or_import_expr captures the writer position and prints 0 if nothing was emitted under ExprResultIsUnused; (2) EIndex now masks flags to HasNonOptionalChainParent | ForbidCall before printing its target, matching the existing EDot arm; (3) EIf masks flags to ForbidIn before printing its test, so caller-context flags like ExprResultIsUnused and ForbidCall no longer leak into operands whose values are read. Three itBundled tests are added to test/bundler/bundler_edgecase.test.ts covering the unminified snapshot, a --minify variant, and the wrapper-present case where init_w()'s undefined return was previously used as a conditional test.

Security risks

None. This is code-generation correctness in the bundler's printer; no auth, crypto, network, or filesystem trust boundaries are involved. The change cannot introduce injection — it only affects whether a placeholder token is emitted and which parent flags propagate to child expressions.

Level of scrutiny

Medium-high. The JS printer is on the hot path for every bun build and every runtime transpile, and incorrect output silently breaks user applications. The EIf and EIndex flag masks are not scoped to the require() bug — they change flag propagation for every conditional and index expression, with observable side effects on parenthesization (the PR's own table shows new ((a()) ? c : d) → new (a() ? c : d), etc.). REVIEW.md directs that for ported code "the reference implementation (esbuild) is the spec"; the PR claims esbuild uses the same masks, and the EIndex mask does match the existing EDot arm exactly, but a maintainer should confirm the EIf mask against esbuild's printExpr and weigh the open design question the author raised (always emit the wrapper vs. print a filler 0).

Other factors

The tests are well-placed (existing bundler_edgecase.test.ts, itBundled helper), exercise both run: execution and an inline output snapshot, and cover the variant matrix (minified/unminified, wrapper/no-wrapper, comma/ternary/index/for-init/destructure positions). I traced the 0 fallback's guards: ExprResultIsUnused sets meta.exports_ref = Ref::NONE earlier, wrap_comma_operator and wrap_with_to_esm would each move written() past start before the check, and the dynamic-import branch prints Promise.resolve() first — so the fallback fires only in the exact nothing-printed case. print_space_before_identifier() before 0 handles else0/do0 hazards using the same pattern the printer already uses for number literals. The written() position-compare idiom is already used in this file (e.g., prev_num_end). The added per-call cost is one i32 read on the internal-require path only.

@robobun

robobun commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator Author

Reference for the mask check. These are the same arms in esbuild, internal/js_printer/js_printer.go at f6058f8:

  • EIf: the test gets (flags&forbidIn)|parentWasUnaryOrBinaryOrIfTest (L2698), the yes branch gets 0 (L2704), and the no branch gets flags&forbidIn (L2710).
  • EIndex and EDot: the target gets (flags&(isNewTarget|hasNonOptionalChainParent))|isPropertyAccessTarget (L2623, L2567). isNewTarget is the current name of forbidCall: ENew sets it on its target and a call wraps itself when it sees it.

Bun has no parentWasUnaryOrBinaryOrIfTest and no isPropertyAccessTarget, so the masks in this PR keep the same flags as esbuild. One difference stays as it was: the no branch in Bun gets ForbidIn in every context, and esbuild passes it only when the parent had it.

@robobun

robobun commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:57 PM PT - Oct 25th, 2026

❌ @robobun, your commit 6e463b9 has 1 failures in Build #132712 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 42448

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

bun-42448 --bun

… of a const export

Since #42471 a destructured require() local is bound only to an export
that has its value from the start. `const { name } = require("./b.js")`
of a `const` export no longer folds to an unused require(), so the
snapshot of edgecase/EsmWrapperEliminationUnusedRequire now has the
pattern itself, and the local keeps its own name.

@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.

I reviewed the merged tree (through 6e463b9) and found no bugs; because this changes bundler output for every unused require() of a wrapper-less ES module and the 0 filler is a design choice the description leaves to a maintainer (versus always emitting an __esm wrapper), a human look is still worthwhile.

What was reviewed:

  • print_require_or_import_expr: the start marker is taken after the wrap paren and 0 is emitted only when ExprResultIsUnused is set and nothing was written, so (0), 0,, 0;, for (0;;) and return 0, are all well-formed; Promise.resolve()/__toESM( paths always write bytes first and are unaffected.
  • ExprResultIsUnused is consumed only in this function and in comma-operand propagation, so the new EIndex/EIf masks change nothing except require printing; dropping ForbidIn from an EIndex target at Level::Postfix is safe since any in there is already parenthesized, matching the existing EDot arm and esbuild.
  • The filler 0 can never become a ./[ target because EDot, EIndex, ECall and tagged-template targets never carry the unused flag, so the missing prev_num_end update is not reachable.
  • All three tests execute the bundle (run.stdout), so the syntax-error and wrong-branch regressions cannot pass on the unfixed printer; the inline snapshot output was read and is consistent with the runtime expectations.
Extended reasoning...

The change touches two files: three small hunks in src/js_printer/lib.rs (a 0 filler for an unused require() that printed nothing, and flag masks on the EIndex target and EIf test) and three new itBundled cases in test/bundler/bundler_edgecase.test.ts. It touches no security-sensitive surface. The code mirrors esbuild's flag handling and the only consumer of the masked flag is the require printer, so the behavior change is narrow and verified by executed bundles. Defer rather than approve because the output of every bundled project with this pattern changes (extra 0; statements, fewer redundant parentheses) and the author explicitly offers the alternative of always creating the wrapper for a maintainer to decide; no CODEOWNERS entry covers these paths and no CHANGES_REQUESTED review is outstanding.

This branch has not been deployed

No deployments
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