Skip to content

js_printer: parenthesize the folded import.meta.main node and the left operand of ** by level - #33447

Closed
robobun wants to merge 2 commits into
mainfrom
farm/86cb103d/import-meta-main-precedence
Closed

robobun wants to merge 2 commits into
mainfrom
farm/86cb103d/import-meta-main-precedence

Conversation

@robobun

@robobun robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #45776

Problem

  • bun x.cjs prints false for "main: " + (require.main === module). Node.js prints main: true.
  • The parser folds require.main === module and import.meta.main into one node. Its printer arm (src/js_printer/lib.rs:3328) writes require.main == module or !import.meta.main and ignores the level of its slot.
  • !import.meta.main ** 2 and -1 /* A */ ** 2 (an inlined enum) are a SyntaxError: Unexpected token '**'.

Fix

  • Commit 1: the arm, now a cold method, adds parentheses at level >= Equals for the comparison and at level >= Prefix for !import.meta.main.
  • Commit 2: the left operand of ** prints at Level::Prefix, except ++x and x--. Arms that print unary text wrap at that level, so the list of node kinds is gone.
  • Verified: 17 new tests in run-importmetamain.test.ts, bundler_edgecase.test.ts and transpiler.test.js fail on main.
  • Self-reviewed: 20 concerns raised, 17 addressed, 3 not taken (Notes).

Background

  • level is the precedence of the operator around a node. An arm that prints a weaker operator adds parentheses.
  • The text depends on the module format. The runtime knows it only after the parse, so real nodes from the parser (bundler: use the native import.meta.main in ESM output for Node.js #43687) cannot cover bun x.cjs.
  • esbuild has no such fold. Its print-time text (void 0, !0) checks level in the printer, as commit 1 does. Its ** list has the same gaps.

Downsides

Notes

Question for a maintainer. Commit 2 replaces the list of node kinds for the left operand of ** with a rule by level. The list is a port of esbuild's (case js_ast.BinOpPow in js_printer.go), and esbuild 0.21.5 prints the same SyntaxError for the inputs below. Keep the rule, or keep the list? To keep the list, drop commit 2: commit 1 alone adds this node to the list, and the other kinds stay as on main.

What changed against the old head 586c7c2

  • Rebased onto main 179664e. The one conflict was the cache version.
  • The printed text stays == / !=. The old head printed === / !==. That fixed nothing and changed each output that has the idiom.
  • The arm is one cold method with one wrap. Commit 2 is new.
  • 44 is the next free cache version today. main had 20 bumps since 2026-08-13, so this line conflicts again at the next one. Renumber it at merge.

Repro. bun 1.4.3-canary (367d939) and main 179664e. #45776 reports it on 1.4.4-canary. The fold came with #12867.

// x.cjs
const concat = 'x=' + (require.main === module) + '!';
const arith  = 1 + (require.main === module);
const neg    = 'x' + !(require.main !== module);
console.log(JSON.stringify({ concat, arith, neg }));

node: {"concat":"x=true!","arith":2,"neg":"xtrue"}
bun:  {"concat":false,"arith":false,"neg":false}
  • bun build --format=cjs prints if (!import.meta.main) as if (!require.main == module). A file that requires the output takes the main branch.
  • bun --inspect entry.cjs: a required file with if (!(require.main === module)) takes its main branch. Without the inspector the runtime makes the ! a part of the node, and the text is right. bun test --coverage turns that off too (src/runtime/cli/test_command.rs:2002).
  • A const with one use: function f() { const m = require.main === module; return "x=" + m; } prints return "x=" + require.main == module;.
  • ES module: (require.main !== module).toString() prints !import.meta.main.toString().

The left operand of **. main prints the text below. esbuild 0.21.5 prints the same text for the first and the third input:

input printed
enum E { A = -1 }, E.A ** 2, in one file or across two -1 /* A */ ** 2
import.meta.hot ** 2 with --minify-syntax void 0 ** 2
ns.missing ** 2 with --minify-syntax void 0 ** 2
  • The list names EUnary, EAwait, EUndefined, ENumber and EBoolean. These operands are other kinds, and they get their unary text when they are printed.
  • With the slot at Level::Prefix, the arms that print unary text add their own parentheses: print_undefined, print_number, EBoolean, EAwait, EUnary, and this node.
  • Identity: 67 kinds of left operand on 24 routes give 1,512 printed ** lines. 1,445 are byte-identical to main. The 67 that differ are the import.meta.main rows.
  • The four inputs above and (require.main !== module) ** 2: 5 of 5 outputs fail node --check on main, 0 of 5 here.

The esbuild question (the comment of dylan-conway, 2026-07-07).

  • esbuild does not fold require.main === module. It keeps the binary node and prints "x=" + (require.main === module) + "!".
  • This node cannot be a binary node for bun x.cjs. The printer takes the module format from exports_kind, after the parse (src/bundler/transpiler.rs:2429).
  • For text that esbuild picks at print time, its printer arm checks level and writes the parentheses: (void 0) in printUndefined, (!0) for EBoolean, and a bundled require() in printRequireOrImportExpr (at LNew and at LComma). Commit 1 does the same for this node: == at Equals, ! at Prefix.
  • My comment of 2026-07-07 said that esbuild has no node that prints operator text from the printer. That was wrong. It also proposed ===. This head keeps the == of main.
  • js_printer: re-wrap delete of folded import/cjs-export identifier #36740 (merged 2026-08-04) is an earlier printer fix for this node, at one parent (delete).

Measurements. Release bun-profile of main 179664e and of this head, with llvm-nm, llvm-size and llvm-objdump.

  • print_expr, five instantiations: 77,088 B to 74,916 B (-283 to -739 B each).
  • print_import_meta_main, five instantiations: +7,634 B. .text: +3,840 B. Stripped bun: +4,096 B.
  • One printed ** with an identifier on the left: 9 to 4 instructions, 4 to 1 conditional branches. With a unary expression on the left: 16 to 9 instructions, 5 to 2 conditional branches (read in one instantiation).
  • Calls in print_import_meta_main (one instantiation): 20, to three targets. 13 go to the grow path of the output buffer, 3 to Renamer::name_for_symbol, 4 to a helper that llvm-objdump shows without a name.
  • Cache: for a 6 KB CommonJS file, this build rewrites 1 entry on the first run and 0 on the second. main printed false from its entry. This build prints x=true.
  • Not measured: instructions and syscalls at run time. valgrind, perf and strace are not installed in my container, and its package mirror is not reachable.

Output that was right on main.

  • 34,319 files (test/node_modules, scripts/*.ts, the repo files with the idiom) through Bun.Transpiler for targets bun, browser and node, with and without minify.syntax: 205,911 of 205,914 outputs are byte-identical. The 3 that differ were wrong.
  • The 58 repo files with the idiom, each built as the only entry point for 6 pairs of target and format, with and without --minify-syntax, and with --no-bundle --target=bun --format=cjs: 680 of 688 outputs are byte-identical. The 8 that differ were wrong: typeof import.meta.main !== "boolean" in scripts/agent.ts and a ! guard in test/js/bun/resolve/main-test-script.js.
  • One right output changes. delete (null ?? import.meta.main) in CommonJS text prints delete (0, (require.main == module)): 2 bytes more, same value.

Grid. 64 contexts (an operator next to the node) x 8 spellings x 26 settings (bun x.cjs, bun x.mjs, bun build for 3 targets x 2 formats x --minify-syntax on and off x CommonJS and ES module source) x 2 launches (entry point, loaded by another file) = 16,640 cells. The expected value is the same context with the boolean literal. main: 5,349 wrong, 35 of them a SyntaxError in the output. This head: 0. In this grid a CommonJS file loads the node ESM output.

Not fixed here.

Other open PRs.

Self-review. 20 concerns. Not taken:

  • Keep esbuild's ** list and move the rule to its own PR. The rule is a separate commit, and the question above asks for the decision.
  • One test table for each leaf that prints compound text. That is a follow-up.
  • Edits to bundler: define __require in iife output #38077 and to a branch of another session.

Tests.

  • test/cli/run/run-importmetamain.test.ts replaces run-importmetamain.ts, which had no .test in its name and never ran. Its two tests are kept. 7 new tests: the repro of transpiler: parenthesized (require.main === module) loses its parentheses inside a larger expression #45776, bun -e, a const with one use, --inspect, 27 operators in CommonJS and in an ES module (entry point and loaded file), and a second run from the transpiler cache.
  • test/bundler/bundler_edgecase.test.ts: 8 new cases. Two pin the text. Four build for Node.js as CommonJS and ESM, plain and minified, and run the output as the entry point and loaded by another file. Two are for commit 2.
  • test/bundler/transpiler/transpiler.test.js: 2 new tests through Bun.Transpiler.
  • Existing assertions changed: 0. One stale test comment is rewritten.
  • With the debug build, all of these files pass except edgecase/DeepImportDiamondDAG, a 20,000-module build with a 60 s limit. It fails the same way with a debug build of main in my container.
  • Also run: bundler_minify, bundler_cjs2esm, esbuild/ts, esbuild/default, bundler_compile, transpiler-cache. Five tests there pass the 5 s limit by a small margin or not at all in my container, with this build and with a debug build of main: default/TopLevelAwaitForbiddenRequireSourceMapAPI and CLI, compile/BannerNonAsciiUTF8, compile/FooterNonAsciiUTF8, and --drop invalidates cache.

no test proof · iteration 10 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/bundler/bundler_edgecase.test.ts

@coderabbitai

coderabbitai Bot commented Jul 6, 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 47d06b5 and a8d1f21.

Files selected for processing: 5
  • src/js_printer/lib.rs
  • src/jsc/RuntimeTranspilerCache.rs
  • test/bundler/bundler_edgecase.test.ts
  • test/bundler/transpiler/transpiler.test.js
  • test/cli/run/run-importmetamain.test.ts

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

Walkthrough

The JavaScript printer now applies precedence-aware output to import.meta.main and require.main expressions and adjusts the left-operand precedence for **. The change increments the transpiler cache version and adds bundler, transpiler, and CLI coverage.

Changes

Expression printing and validation

Layer / File(s) Summary
Printer precedence and cache version
src/js_printer/lib.rs, src/jsc/RuntimeTranspilerCache.rs
The printer adjusts exponentiation left-operand precedence and moves main-module expression output into a helper that applies precedence-based wrapping. The transpiler cache version changes to 44.
Bundler and transpiler regression coverage
test/bundler/bundler_edgecase.test.ts, test/bundler/transpiler/transpiler.test.js
Tests cover main-module expression output across targets and minification settings, plus exponentiation with unary expressions, enum values, and literals.
CLI main-module runtime coverage
test/cli/run/run-importmetamain.test.ts, test/cli/run/run-importmetamain.ts
The new CLI suite checks main and imported-file behavior in ESM and CommonJS, expression contexts, inspector mode, and transpiler-cache restore. The prior CLI test file is removed.

Suggested reviewers: jarred-sumner, dylan-conway

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Minimal · up to a8d1f

No concrete issue in the changed printing behavior is established. The change is mergeable after normal validation, including the deferred bundler tests.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Out of Scope Changes check Warning The folded-node printer and related tests support #45776. The BinPow change in src/js_printer/lib.rs is a separate general rule for left operands of **. The added ExponentLeftInlinedEnum and `… Move the BinPow rule and its exponentiation tests to a separate pull request, or link an active issue that requires this behavior and keep that scope explicitly approved.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: precedence-based parenthesization for folded import.meta.main output and the left operand of **.
Description check Passed The description is complete and relevant. It explains the problem, the implementation, known limitations, cache impact, and verification results, including the tests added and the cases that still req…
Linked Issues check Passed Issue #45776 requires correct values for require.main === module and its negation inside larger expressions. src/js_printer/lib.rs now wraps the folded comparison at Level::Equals and the invert…
Full details: Description check

Explanation

The description is complete and relevant. It explains the problem, the implementation, known limitations, cache impact, and verification results, including the tests added and the cases that still require CI validation.

Full details: Linked Issues check

Explanation

Issue #45776 requires correct values for require.main === module and its negation inside larger expressions. src/js_printer/lib.rs now wraps the folded comparison at Level::Equals and the inverted form at Level::Prefix. test/cli/run/run-importmetamain.test.ts covers the issue reproduction and entry versus required files. The implementation meets the linked coding requirement.

Full details: Out of Scope Changes check

Explanation

The folded-node printer and related tests support #45776. The BinPow change in src/js_printer/lib.rs is a separate general rule for left operands of **. The added ExponentLeftInlinedEnum and ExponentLeftUndefinedMinify tests cover enum and undefined-like operands, not the linked issue. These changes are unrelated to #45776.

Resolution

Move the BinPow rule and its exponentiation tests to a separate pull request, or link an active issue that requires this behavior and keep that scope explicitly approved.

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

@github-actions github-actions Bot added the claude label Jul 6, 2026
@robobun

robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:09 AM PT - Oct 25th, 2026

✅ @robobun, your commit a8d1f21e104a152be21e3816485ca3a2700a92d7 passed in Build #132457! 🎉


🧪   To try this PR locally:

bunx bun-pr 33447

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

bun-33447 --bun

@robobun

robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: rebased onto main 179664e, head a8d1f21. Ready for review. This PR fixes #45776.

Reproduced with the script of #45776 on bun 1.4.3-canary (367d939) and on a release build of main 179664e, against node v26.3.0:

$ cat issue.cjs
console.log("main: " + (require.main === module));
console.log("not main: " + !(require.main === module));

$ node issue.cjs
main: true
not main: false

$ bun issue.cjs          # 1.4.3-canary and main
false
true

$ bun issue.cjs          # this head
main: true
not main: false

Fail before, pass after, with debug builds of main and of this head:

file main this head
test/cli/run/run-importmetamain.test.ts 2 pass, 7 fail 9 pass
test/bundler/bundler_edgecase.test.ts, the 8 new cases 8 fail 8 pass
test/bundler/transpiler/transpiler.test.js 258 pass, 2 fail 260 pass

Two items for a maintainer:

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

No bugs found — the precedence-wrap logic and BinPow special case follow the established printer patterns and tests are thorough, but since this changes transpiler output for every module (plus the == → === emission change), it's worth a quick human sanity check.

Extended reasoning...

Overview

This PR fixes a precedence bug in src/js_printer/lib.rs where EImportMetaMain (the folded form of require.main === module / import.meta.main) was printed without consulting the surrounding level, so enclosing operators re-associated around it. The fix adds level.gte(...) wrap checks to both the ESM (!import.meta.main, wrap at Level::Prefix) and non-ESM (require.main === module, wrap at Level::Equals) branches, adds the inverted form to the BinPow left-operand special case (matching the existing EUnary arm), switches emitted ==/!= to ===/!==, bumps the runtime transpiler cache version, and renames a previously-uncollected test file to .test.ts while adding runtime and itBundled coverage.

Security risks

None. This is a JS-printer precedence fix; no auth, crypto, filesystem, or network surface is touched.

Level of scrutiny

Moderate. The change is small (~30 printer lines) and follows the printer's established let wrap = level.gte(...) idiom exactly, and the BinPow addition mirrors the neighboring EUnary/EAwait/ENumber arms. However, the JS printer runs on every transpiled/bundled file, so any regression has wide blast radius. The == → === emission change is argued to be behavior-neutral (both operands are objects or undefined), which looks right, but is a judgment call worth a maintainer confirming. The cache version bump is correct and necessary.

Other factors

  • No CODEOWNER covers the touched paths.
  • Tests are comprehensive: runtime spawns for CJS entry, required non-main module, ESM inverted form, and the ** SyntaxError case, plus two itBundled capture tests for both printer branches. The existing ImportMetaMainTargetNode / build-cjs-module#20308 snapshots were updated for the === change.
  • The rename of run-importmetamain.ts → .test.ts is a good catch (the file was never being collected).
  • No prior human review comments; CI build was still in progress at review time.

@robobun
robobun force-pushed the farm/86cb103d/import-meta-main-precedence branch from 0329c21 to bd486cc Compare July 6, 2026 11:01
@robobun

robobun commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

since this changes transpiler output for every module (plus the == → === emission change), it's worth a quick human sanity check

Agreed, and to make that check cheap, here is the full argument for the === part.

EImportMetaMain is only ever constructed from four fold sites in src/js_parser/visit/visit_binary.rs (==, ===, !=, !== between require.main and module) and from import.meta.main in src/js_parser/fold.rs. In all of them the two operands the printer re-emits are require.main and module (or __require.main / __require.module). module is always a Module object. require.main is either a Module object or undefined. Abstract and strict equality only diverge when one side is null and the other undefined, which no combination here can produce, so the emitted comparison evaluates identically either way.

What it buys: the output now matches the lowering already documented above value_for_import_meta_main in src/js_parser/p.rs, and a file that wrote === round-trips as ===. What it costs: one byte per occurrence under --minify. If you would rather keep the byte, the ws!(b".main == ") / ws!(b".main != ") lines revert independently of the precedence fix and no test in this PR depends on them other than the two updated capture strings.

The precedence wrap itself is the part that has to land: without it bun x.cjs silently computes a different value than node x.cjs, and (require.main !== module) ** 2 emits !import.meta.main ** 2, which does not parse.


Rebased onto main to pick up #33425. The two hard CI failures on the previous push were test/js/bun/cookie/cookie-map.test.ts asserting the pre-IMF-fixdate Expires format, fixed by that commit one revision after my branch point. The other two annotations (dev-and-prod.test.ts hmr rapid edits, bun-install-lifecycle-scripts.test.ts) were filed under flaky and passed on retry.

@robobun

robobun commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@dylan-conway

Copy link
Copy Markdown
Member

@robobun please check what esbuild does. if they don't have this bug we want the same exact solution has esbuild for preventing the bug

@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Checked esbuild. Short version: esbuild cannot have this exact bug because it never folds require.main === module into a special node, and the mechanism this PR uses to prevent the bug is esbuild's own precedence idiom.

What esbuild does

esbuild leaves the expression as a normal binary AST node and prints it through its precedence-aware printer, so it parenthesizes for free:

// esbuild es-in.js --format=cjs --platform=node
const concat = "x=" + (require.main === module) + "!";
const arith = 1 + (require.main === module);

The same holds for the two edge cases in this PR. esbuild parenthesizes a unary on the left of **, and wraps an equality inside + (and keeps strict equality, even applying De Morgan under --minify):

// esbuild es4.mjs
export const a = (!x) ** 2;

// esbuild es5.js --minify    (input: 'x' + !(a === b) + '!')
const n="x"+(a!==b)+"!";

When esbuild itself synthesizes an expression (e.g. lowering import.meta for a CJS output), it emits a real AST node, not text:

// esbuild es3.js --format=cjs --platform=node
const import_meta = {};
const u = "url=" + import_meta.url + "!";

So esbuild's rule is: every synthesized/lowered expression is a real AST node, printed recursively with a level argument, and each node wraps itself when level >= op.Level. There is no node that renders a compound expression as raw text and skips the precedence machinery. That is the whole reason esbuild can't hit this.

Why Bun can't just build a real binary node instead

EImportMetaMain is a deliberate print-time leaf because its shape is not known until after linking:

  • import.meta.main (member expression) for ESM non-node
  • require.main === module (binary) for CJS
  • __require.main === __require.module for target=node

The choice reads module_type / target / commonjs_module_ref / require_ref (src/js_printer/lib.rs:3261-3305). Those come from the bundle output_format and the per-module exports_kind, and exports_kind is rewritten during the linker's scanImportsAndExports pass (src/bundler/LinkerContext.rs:569), after parsing. The CJS/node shapes also reference require_ref / commonjs_module_ref, which are allocated during linking and symbol renaming (has_run_symbol_renamer: true, src/bundler/LinkerContext.rs:2238). The parser emits the deferred leaf precisely because the same parsed AST can be printed to any of the three forms later (value_for_import_meta_main, src/js_parser/p.rs:5690).

So a fixed real-binary AST at parse time isn't possible for the bundler path. The node has to stay a print-time leaf.

The fix is esbuild's mechanism applied to that leaf

Given the leaf has to render a compound expression, the fix makes it honor the same level contract every real node in this printer already follows:

  • binary shape wraps at level.gte(Level::Equals) (the level of ===)
  • !import.meta.main shape wraps at level.gte(Level::Prefix)
  • the inverted form is added to the existing BinPow left-operand carve-out, next to the EUnary arm, so (require.main !== module) ** 2 emits (!import.meta.main) ** 2 instead of the invalid !import.meta.main ** 2

That let wrap = level.gte(...) pattern is the same one used for EAwait, EYield, EUnary, ECall, the arrow/conditional branches, and the BinaryExpressionVisitor throughout src/js_printer/lib.rs (the port of esbuild's wrap := level >= entry.Level). The == -> === change also matches esbuild, which keeps strict equality as shown above.

If you would still prefer I avoid the manual wrap entirely, the only way to do that is to push the shape decision into the linker and have it rewrite EImportMetaMain into a real AST node before printing (esbuild-style AST rewriting during linking), which is a larger change. Happy to take that route if you want it; otherwise this is the minimal version of esbuild's approach.

@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 `@test/bundler/bundler_edgecase.test.ts`:
- Line 2101: Remove the leftover debug logging from the test by deleting the
console.log call in the bundler edgecase test; keep the surrounding test logic
intact and rely on the existing assertions instead. Locate it in the test case
that reads "/out.js" via api.readFile, and ensure no other stray debug output
remains in that block.

In `@test/cli/run/run-importmetamain.test.ts`:
- Around line 6-137: The four subprocess-based tests in import.meta.main are
independent and should run concurrently instead of sequentially. Update each
test definition to use test.concurrent (or wrap them in describe.concurrent if
you prefer grouping) so the Bun.spawn/Bun.spawnSync and temp file setup in these
cases can execute in parallel. Keep the existing test bodies and assertions
intact, just change the test registration for the import.meta.main, common.js,
precedence CJS, precedence ESM, and exponent ESM cases.
- Around line 13-20: The spawn-based tests in the run-importmetamain suite only
validate stdout and ignore whether the child process succeeded. Update the
affected test cases that call Bun.spawnSync to also capture and assert the
exitCode is 0, using the Bun.spawnSync result alongside stdout so failures in
index1.js or the related spawned script are not missed. Keep the check close to
the existing Bun.spawnSync assertions in the test body.
- Around line 6-38: The two import.meta.main tests are creating temporary
directories with tmpdirSync() but never disposing them, and the extra
mkdirSync(dir, { recursive: true }) is redundant. Update the test bodies to
match the tempDir/using pattern used by the other cases in
run-importmetamain.test.ts so the directories are automatically cleaned up, and
keep the rest of the test logic unchanged around Bun.write, Bun.spawnSync, and
the assertions.
🪄 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: 21458186-7d21-4e10-9adb-b0c3d4258e4e

📥 Commits

Reviewing files that changed from the base of the PR and between a780f57 and 47d06b5.

📒 Files selected for processing (6)
  • src/ast/e.rs
  • src/js_printer/lib.rs
  • src/jsc/RuntimeTranspilerCache.rs
  • test/bundler/bundler_edgecase.test.ts
  • test/cli/run/run-importmetamain.test.ts
  • test/cli/run/run-importmetamain.ts
💤 Files with no reviewable changes (1)
  • test/cli/run/run-importmetamain.ts

Comment thread test/bundler/bundler_edgecase.test.ts Resolved
Comment thread test/cli/run/run-importmetamain.test.ts Resolved
Comment thread test/cli/run/run-importmetamain.test.ts Resolved
Comment thread test/cli/run/run-importmetamain.test.ts Resolved
Comment thread src/jsc/RuntimeTranspilerCache.rs Resolved

@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 didn't find any bugs, but deferring for a human sign-off: dylan-conway asked for parity with esbuild's approach and hasn't yet confirmed the answer (that esbuild never synthesizes this node, so the fix applies esbuild's level.gte(...) idiom to the print-time leaf instead). Given this changes transpiler output for every occurrence of require.main === module / import.meta.main (including the == → === emission), a maintainer ack seems warranted.

What was reviewed:

  • Wrap thresholds match the Level enum: Equals for the binary form, Prefix for !import.meta.main, and the BinPow left-operand carve-out routes through Level::Call so (…) ** 2 is legal.
  • Non-inverted ESM (import.meta.main, a member expr) correctly needs no wrap; right-of-** cases checked for both branches.
  • Cache version bump to 24 covers the emission change; the two updated capture strings in existing bundler tests were checked.
  • The renamed run-importmetamain.test.ts preserves the two pre-existing tests' assertions and adds fail-before/pass-after coverage for CJS entry, required non-main, ESM inverted, and **.
Extended reasoning...

Overview

The PR fixes a printer-precedence bug in src/js_printer/lib.rs: EImportMetaMain (the folded form of require.main === module / import.meta.main) was emitted as raw text without consulting the surrounding level, so enclosing operators re-associated around it. The fix adds let wrap = level.gte(...) guards to both printer branches, adds the inverted form to the BinPow left-operand special case, switches the emitted comparison to strict equality, updates a doc comment in src/ast/e.rs, bumps RuntimeTranspilerCache to v24, and adds bundler + runtime tests (including renaming a previously-uncollected run-importmetamain.ts to .test.ts).

Security risks

None. This is JS printer output correctness; no auth, crypto, filesystem, or untrusted-input parsing surface.

Level of scrutiny

Medium-high. The printer change is small and follows the file's existing let wrap = level.gte(...) idiom used by EAwait/EYield/EUnary/etc., and I verified the thresholds against src/ast/op.rs's Level ordering (Equals=12 for the binary form, Prefix=18 for !import.meta.main, BinPow left carve-out bumps to Call=21). But it changes emitted JS for a very common idiom in every transpiled module, and the == → === change — while argued to be behavior-neutral (both operands are Module|undefined) — is a deliberate output-format decision the author flagged as worth a human check.

Other factors

  • Outstanding maintainer question: dylan-conway asked to verify esbuild's approach and use "the same exact solution". The author's reply explains esbuild never folds this into a special node (so it can't hit the bug) and that a "real AST node at link time" alternative exists but is a larger change. That design call — accept the leaf-level wrap vs. rewrite in the linker — hasn't been acknowledged by the maintainer.
  • All CodeRabbit and comment-cop threads are resolved; the debug console.log, tmpdirSync→tempDir, exit-code assertions, and describe.concurrent feedback were addressed.
  • Tests cover both printer branches (CJS/ESM/target-node), both polarity, the ** syntax-error case, member access, string concat, and the required-non-main path. The bundler capture assertions and the new run:{stdout} case give both textual-output and behavioral coverage.
  • No prior review from me on this PR.

@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 didn't find any bugs, but this changes printer output for every EImportMetaMain occurrence and dylan-conway asked for an esbuild comparison that hasn't been explicitly signed off on — worth a quick human look before merging.

What was reviewed:

  • Verified the Level thresholds against src/ast/op.rs: Equals for the === shape and Prefix for !import.meta.main are the correct wrap points; the BinPow left-operand carve-out is needed because Exponentiation < Prefix.
  • Checked that non-inverted EImportMetaMain on the left of ** (both ESM and CJS shapes) is already handled by the existing left_level/new Equals wrap, so the if left.inverted guard is not a gap.
  • Confirmed print_space_before_identifier() after the new ( is a no-op (prev char is not an identifier-continue), so no stray space.
  • The renamed run-importmetamain.test.ts was previously never collected (no .test suffix); the two migrated tests preserve the original assertions.
Extended reasoning...

Overview

This PR fixes a precedence bug in js_printer where EImportMetaMain (the folded form of require.main === module / import.meta.main) was printed as raw text without consulting the surrounding level, so enclosing operators re-associated around it. Changes: src/js_printer/lib.rs (three wrap points + ==→===), a doc comment in src/ast/e.rs, a RuntimeTranspilerCache version bump (23→24), three new itBundled cases in bundler_edgecase.test.ts, and a renamed/extended run-importmetamain.test.ts (the old file was never collected by the runner).

Security risks

None. This is printer precedence logic; no untrusted-input parsing, auth, or I/O is touched.

Level of scrutiny

High. The JS printer runs on every transpiled module, and a wrong precedence threshold silently miscompiles user code. I traced the Level enum in src/ast/op.rs to confirm Equals < Add < Exponentiation < Prefix < Call, which validates all three thresholds: the CJS shape wraps at gte(Equals) (so +, typeof, member access all wrap it), the inverted ESM shape wraps at gte(Prefix) (so .toString() and ** wrap it via the new BinPow arm forcing left_level = Call), and the non-inverted ESM shape (import.meta.main, a member expression) correctly needs no wrap. I also checked that print_space_before_identifier() after the new ( doesn't emit a stray space (( is not identifier-continue), and that the BinPow guard if left.inverted doesn't leave a gap for the non-inverted CJS shape (that path already wraps because Exponentiation >= Equals).

Other factors

  • dylan-conway asked to check what esbuild does and use "the same exact solution". robobun's response explains esbuild never folds this into a leaf node so can't hit the bug, and that the fix applies esbuild's own level >= op.Level idiom to Bun's print-time leaf. That reasoning is sound, but the maintainer hasn't confirmed acceptance of the approach vs. the alternative (rewriting to a real AST node in the linker).
  • The ==→=== emission change is argued to be behavior-preserving (both operands are Module|undefined, never null), and matches the documented lowering in p.rs. I agree, but it does change bundler output byte-for-byte and updates two existing capture: snapshots.
  • The cache-version bump invalidates every user's transpiler cache — appropriate here since stale entries would keep serving the miscompiled output.
  • Test coverage is thorough: entry vs. required-dep CJS, ESM inverted form, the ** SyntaxError case, and --target=node with run: executing the bundled output. All CodeRabbit threads are resolved.

Given this is a printer change on a critical path with an open maintainer thread on the approach, deferring rather than approving.

Comment thread src/jsc/RuntimeTranspilerCache.rs Resolved
Comment thread test/bundler/bundler_edgecase.test.ts Resolved

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

LGTM — the stale-comment nit from my earlier pass was addressed in 9640f46.

What was reviewed:

  • Verified the Level enum ordering: Equals (12) and Prefix (18) are the correct wrap thresholds for the two printed shapes, and the BinPow left-operand bump to Level::Call composes with both branches.
  • Confirmed the if wrap { print("(") } → print_space_before_identifier() ordering matches the existing pattern at lib.rs:3346/3377.
  • Checked that non-inverted ESM (import.meta.main, a member expression) is never wrapped, and that non-inverted CJS under ** still wraps via Exponentiation >= Equals.
  • All prior review threads (CodeRabbit ×4, comment-cop, my stale-comment note) are resolved in the current diff.
Extended reasoning...

Overview

This PR fixes a printer-precedence bug where EImportMetaMain (the AST node the parser folds require.main === module / import.meta.main into) was re-emitted without consulting the surrounding precedence level, causing enclosing operators to re-associate around it — e.g. "x=" + (require.main === module) + "!" printed as "x=" + require.main == module + "!". Changes: src/js_printer/lib.rs adds level-aware wrapping to both printer branches and adds inverted EImportMetaMain to the BinPow left-operand special case; src/ast/e.rs updates a doc comment; RuntimeTranspilerCache.rs bumps EXPECTED_VERSION 25→26; three new itBundled capture tests plus a renamed/modernized run-importmetamain.test.ts with three new runtime tests.

Security risks

None. This is a pure printer-output correctness fix with no auth, crypto, permissions, or untrusted-input parsing surface.

Level of scrutiny

Medium — it changes transpiler output, which affects every CJS module using this idiom, but the change is narrow and mechanical: two let wrap = level.gte(...) guards following the exact pattern used at lib.rs:3346/3377/3521, plus one match arm added to an existing special case. I verified against src/ast/op.rs that Level::Equals and Level::Prefix are the correct thresholds for x === y and !x respectively, and traced the BinPow interaction for all four (branch × inverted) combinations. The ==→=== change is behavior-neutral (both operands are objects or undefined) and matches the fold's source form.

Other factors

  • The transpiler-cache version bump is required by the file's own convention and follows the established changelog format (comment-cop's flag was a false positive, correctly explained by the author).
  • Test coverage is thorough: bundler capture: assertions for all three printer branches, runtime assertions for main/non-main CJS, ESM inverted, and the **-left-operand SyntaxError case; existing capture: arrays and the DeleteFoldedImportMetaMainRef comment were updated for the === output.
  • All prior review feedback (CodeRabbit's four items in 4174cf9, my stale-comment note in 9640f46) is addressed; no bugs found by the bug-hunting system on this pass.

@robobun
robobun force-pushed the farm/86cb103d/import-meta-main-precedence branch from 9640f46 to 586c7c2 Compare August 14, 2026 03:46

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

LGTM — the stale comment I flagged last run is fixed, and the precedence fix itself checks out.

What was reviewed:

  • Level::Equals / Level::Prefix wrap thresholds against the op::Level enum ordering; both branches wrap exactly when the emitted expression's own precedence would be captured by the surrounding operator.
  • The new BinPow left-operand arm: without it, left_level = Exponentiation < Prefix so the ESM !import.meta.main wouldn't wrap and would emit a SyntaxError; with it, Call ≥ Prefix triggers the wrap. The arm is redundant-but-harmless in the non-ESM path (already wraps at ≥ Equals).
  • == → ===: both operands are object-or-undefined in every reachable case, so no observable change; matches the source form the fold came from.
  • Cache version bump follows the file's changelog convention; test file rename (was never collected without .test) plus runtime and itBundled coverage across all three printer branches.
Extended reasoning...

Overview

Fixes a printer-precedence bug where the EImportMetaMain node (the parser's fold of require.main === module / import.meta.main) was emitted without consulting the surrounding level, letting enclosing operators re-associate around it. Touches src/js_printer/lib.rs (the wrap logic + BinPow special case + ===), a one-line doc comment in src/ast/e.rs, the RuntimeTranspilerCache version bump, and tests in bundler_edgecase.test.ts plus a renamed/rewritten run-importmetamain.test.ts.

Security risks

None. This is code-generation output shape only; no untrusted input parsing, auth, or filesystem paths involved.

Level of scrutiny

The printer is production-critical, but this change applies the printer's standard let wrap = level.gte(...) idiom that every other multi-token expression node already uses — it's a targeted mechanical fix, not a redesign. I traced the Level enum ordering (Equals < ... < Exponentiation < Prefix < ... < Call) against each threshold and against the BinPow right-associative left_level = e_level default to confirm the new arm is load-bearing exactly for the ESM inverted case and a no-op elsewhere.

Other factors

All prior review feedback (CodeRabbit's exit-code/tempDir/concurrent nits, my own stale-comment note on DeleteFoldedImportMetaMainRef, the comment-cop false positive) has been addressed and resolved. Test coverage is thorough: runtime tests exercise the CJS entry, a non-main required module, the ESM inverted form, and the ** SyntaxError case; three itBundled capture tests cover the CJS, bun-ESM, and target=node printer branches; and the two pre-existing capture: arrays were updated for == → ===. The dead run-importmetamain.ts (never collected — no .test suffix) is now a real test file.

@robobun

robobun commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator Author

Independent report of the same bug at main 0e395c2, for the record. With bun build --target=node --format=esm, console.log("main=" + import.meta.main) prints console.log("main=" + __require.main == __require.module), which evaluates to false. The ImportMetaMainPrecedenceTargetNode test in this PR covers that case.

The branch now conflicts with main in one place: src/jsc/RuntimeTranspilerCache.rs has EXPECTED_VERSION = 26 on main, so the bump in this PR needs to move to 27. The printer and test hunks merge cleanly.

@robobun

robobun commented Sep 11, 2026

Copy link
Copy Markdown
Collaborator Author

A second independent report of this bug, at main 4b5862f. It shows that the guard idiom if (!import.meta.main) is affected under bun build --target=node without --minify-syntax:

// guard.js
if (!import.meta.main) console.log("loaded as a library");
else console.log("run as main");
$ bun build --target=node --format=cjs guard.js --outfile=out.cjs
if (!require.main == module)

$ node -e 'require("./out.cjs")'
run as main

! binds tighter than ==, so the test is false == module. It is false in every case. The library branch never runs, also when another module loads the bundle. --format=esm prints if (!__require.main == __require.module) with the same result. The ImportMetaMainPrecedenceTargetNode test in this PR covers !import.meta.main and typeof import.meta.main, so no new test is necessary.

The branch still conflicts with main in src/jsc/RuntimeTranspilerCache.rs only. EXPECTED_VERSION is 30 on main now, so the bump in this PR moves to 31.

…vel of its slot

The parser folds `require.main === module` and `import.meta.main` into
one node. The printer wrote it back as `require.main == module` or
`!import.meta.main` and did not read the precedence level of its slot.
An operator around the node then bound into the text:

    'x=' + (require.main === module) + '!'
    "x=" + require.main == module + "!"        (printed)

The arm is now one cold method. It adds parentheses at
`level >= Equals` for the comparison and at `level >= Prefix` for
`!import.meta.main`. The left operand of `**` counts the node as text
that can start with a unary operator. The printed text stays `==`.
Output that was right keeps its bytes, with one exception:
`delete (0, require.main == module)` gets a second pair of parentheses.

The transpiler cache version goes to 44: an older entry can hold the
wrong text.

test/cli/run/run-importmetamain.ts had no `.test` in its name and never
ran. It is now run-importmetamain.test.ts.
@robobun robobun changed the title Parenthesize require.main === module per its surrounding precedence js_printer: parenthesize the folded import.meta.main node and the left operand of ** by level Oct 25, 2026
@robobun
robobun force-pushed the farm/86cb103d/import-meta-main-precedence branch from 586c7c2 to 9f8c012 Compare October 25, 2026 06:29
Comment thread src/js_printer/lib.rs Resolved
@robobun

robobun commented Oct 25, 2026

Copy link
Copy Markdown
Collaborator Author

@dylan-conway, this is a corrected answer to your question of 2026-07-07, for the new head.

  • esbuild does not fold require.main === module, so it has no such node. It prints "x=" + (require.main === module) + "!" from the binary node. Bun cannot do that for bun x.cjs: the printer takes the module format from exports_kind, after the parse.
  • Where esbuild picks text at print time, its printer arm checks level and writes the parentheses: (void 0) in printUndefined, (!0) for EBoolean, a bundled require() in printRequireOrImportExpr. Commit 1 does the same for this node, and the printed text stays the == of main. My earlier comment said that esbuild has no node that prints operator text from the printer. That was wrong.
  • One place is not esbuild's shape. Commit 2 replaces the list of node kinds for the left operand of ** with a rule by level. esbuild 0.21.5 has that list and prints -1 /* A */ ** 2 for an inlined enum, which is a SyntaxError. So there is no esbuild fix to copy.

The question: keep the rule, or keep the list? If you prefer the list, I drop commit 2. Commit 1 is complete without it.

The left operand of `**` must be an UpdateExpression. The printer had a
list of node kinds that print unary text and need parentheses there. A
node that gets its unary text at print time was not in the list, and
the output was a SyntaxError:

    enum E { A = -1 }  E.A ** 2        -1 /* A */ ** 2
    import.meta.hot ** 2               void 0 ** 2     (--minify-syntax)
    lib.missing ** 2                   void 0 ** 2     (--minify-syntax)

Each arm that prints unary text adds parentheses at `level >= Prefix`.
The slot now has that level, except for `++x` and `x--`, and the list
is gone. Output for the kinds that were in the list does not change.
@robobun
robobun force-pushed the farm/86cb103d/import-meta-main-precedence branch from 9f8c012 to a8d1f21 Compare October 25, 2026 06:30

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

Beyond the inline findings, I also checked two things and found no problem: every printer arm that can emit a leading unary token at print time (print_number, print_undefined, EBoolean under minify, EAwait, EUnary, EInlinedEnum which forwards level) already wraps at level >= Prefix, so handing the left operand of ** Level::Prefix does not produce an unwrapped -x ** y from any other arm; and the two cases from the deleted test/cli/run/run-importmetamain.ts are carried over verbatim as the first two tests of run-importmetamain.test.ts.

Extended reasoning...

The change moves the EImportMetaMain printer arm into a cold method that wraps by level and replaces the ** left-operand kind list with a Level::Prefix rule in src/js_printer/lib.rs, bumps the transpiler cache version, and adds bundler, transpiler and CLI tests; it touches no security-sensitive surface. Three inline findings already signal that a human must look, so this note only records the additional checks that were ruled out.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread src/js_printer/lib.rs
Comment on lines +2741 to +2748
if self.options.target == bun_ast::Target::Node {
// "__require.module"
if let Some(require) = self.options.require_ref {
self.print_symbol(require);
self.print(b".module");
} else {
self.print(b"module");
}

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.

🔴 Libraries built with bun build --target=node --format=esm that guard typeof import.meta.main === "boolean" now run their main branch when imported from an ES module under Node; on the base branch they took the fallback. The Node form at src/js_printer/lib.rs:2741-2748 prints __require.main == __require.module, which under a Node ESM entry is undefined == undefined, i.e. true even in a required library; the new parens make typeof return "boolean" so the guard no longer hides that. Fix: emit a Node-ESM expression that is false when the file is not the entry (e.g. compare process.argv[1] to fileURLToPath(import.meta.url)), covering the inverted form too, and add the ESM-loaded-from-ESM variant to the Node matrix test. [also at: src/js_printer/lib.rs:2704 - Libraries bundled with --target=node --format=esm that guard import.meta.main behind a typeof check now run their main-only code when an ES module imports them. src/js_printer/lib.rs:2704 parenthesizes the Node ESM text __require.main == __require.module, so typeof (...) === "boolean" becomes true and the guard stops using its fallback.]

Why this was flagged

Source if (typeof import.meta.main === "boolean" ? import.meta.main : fallback()) runCli(); bundled with bun build --target=node --format=esm, then imported by an ES-module entry under Node. src/js_printer/lib.rs:2741-2748 prints __require.main == __require.module, where __require is createRequire(import.meta.url); under an ESM entry __require.main is undefined (no process.mainModule) and __require.module is never set, so the comparison is true in every file. On base the typeof applied to __require.main only (typeof __require.main == __require.module is "undefined" == undefined, false), so the guard failed and the fallback ran. With the new wrap at src/js_printer/lib.rs:2704 the output is typeof (__require.main == __require.module), which is "boolean", so the guard passes and the library sees true and runs its CLI on import. The new Node matrix test at test/bundler/bundler_edgecase.test.ts:2475-2477 loads the ESM output only from a CommonJS loader (loader.cjs), which sets require.main and so does not exercise this path.

Verification: src/js_printer/lib.rs:4480 prints the typeof operand at Level::Prefix.sub(1), and the new print_import_meta_main (src/js_printer/lib.rs:2700-2706) wraps when level.gte(Level::Equals), so the output is now typeof (__require.main == __require.module). After this change the guard reports "boolean" and the consequent evaluates to true even in an imported library.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is right. It is the first item under Downsides in the description. The decision that it needs is the merge order with #43687, so I leave this thread open for a maintainer.

Measured with bun 1.4.3-canary (367d939) and node v26.3.0, on a bundle from bun build --target=node --format=esm. "Guarded" is typeof import.meta.main === "boolean" ? import.meta.main : "fallback". "Plain" is import.meta.main ? "main" : "library". For the third column I added the parentheses of this PR to the base output by hand.

launch guarded, base guarded, with the parentheses plain, base and this PR
entry point fallback true main
imported by an ES module fallback true main
loaded by a CommonJS file fallback false library
  • On the base the guard passes in no launch. The text is typeof __require.main == __require.module === "boolean", which is false === "boolean". The fallback runs because of the same missing parentheses.
  • With the parentheses the guard passes, and the expression gets the value that the plain form already has on the base. That value is wrong in one cell: __require.main == __require.module is undefined == undefined under an ES module entry point.
  • That value is the subject of bundler: use the native import.meta.main in ESM output for Node.js #43687. It builds import.meta.main ?? __require.main == __require.module for this output, so I did not copy an expression for it into this PR. Its tests run the output from an ES module importer and expect typeof to be "boolean" with the value false. On a Node.js without the property, an imported bundle still gets true there, which bundler: use the native import.meta.main in ESM output for Node.js #43687 lists as a downside.
  • An ES module importer in the matrix of this PR would pin the wrong value. The comment on loader.cjs in that test names bundler: use the native import.meta.main in ESM output for Node.js #43687 for this reason.

The description asks to land #43687 first or in the same release. If that order cannot be kept, the alternative is one condition in print_import_meta_main: no parentheses for the Node.js ESM text until #43687 replaces it. That keeps the guard on its fallback. It also keeps the wrong values of that text on the base. One example: if (!import.meta.main) prints as if (!__require.main == __require.module), and a bundle that a CommonJS file loads takes its main branch.

Comment thread test/bundler/bundler_edgecase.test.ts Resolved
Comment thread src/js_printer/lib.rs Resolved
@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-25.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 2026
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.

transpiler: parenthesized (require.main === module) loses its parentheses inside a larger expression

3 participants