Skip to content

js_parser: substitute undefined, not null, for top-level this in an ES module - #32173

Closed
robobun wants to merge 1 commit into
mainfrom
farm/bdb20eae/esm-top-level-this-undefined
Closed

robobun wants to merge 1 commit into
mainfrom
farm/bdb20eae/esm-top-level-this-undefined

Conversation

@robobun

@robobun robobun commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #32167

Problem

  • Top-level this in an ES module is null. Node and ECMA-262 give undefined. export {}; console.log(typeof this, this === undefined) prints object false.
  • Cause: value_for_this (src/js_parser/p.rs:6190) replaces a module-scope this at compile time. Its ES module arm built E::Null.

Fix

  • The ES module arm returns E::Undefined. The unused null_value_expr is removed.
  • EXPECTED_VERSION (src/jsc/RuntimeTranspilerCache.rs) goes from 35 to 36. Cached entries hold the old text.
  • Correct: esbuild's valueForThis, the source of this port, returns undefined. this === eval("this") now holds.
  • Verified: transpiler.test.js, runtime-transpiler.test.ts, transpiler-cache.test.ts, esbuild/default.test.ts, esbuild/extra.test.ts. 11 of 11 new or corrected cases fail on main.

Background

  • The visit pass replaces each this outside a function or class body: exports in CommonJS, a literal in an ES module. typeof this folds from it.
  • The runtime transpiler cache stores printed output for files of 4 KiB or more. A version bump drops old entries.
  • Considered leaving this to JavaScriptCore at runtime: no extra case fixed, and the bundler still needs the literal.

Downsides

Notes

Scope. This PR now holds only the constant fix, the cache version bump and tests. It is +3/-6 lines in src/.

What changes for users.

  • Runtime: entry file, static import, import(), require() of an ES module, Worker entry, bun -e, bun test files.
  • Text output of bun build, Bun.build and Bun.Transpiler: null becomes undefined (void 0 with minify.syntax), typeof this folds to "undefined", this === undefined folds to true, typeof this !== "undefined" ? this : globalThis folds to globalThis, delete this prints delete (0, undefined).
  • A file counts as an ES module here when it has import, export, import.meta, a top-level await, or a TypeScript type-only import or export.

Measurements. A is main 6c1eb06, B is this PR. Release builds, linux x64.

  • visit pass, this path: +0 instructions, +0 branches, +0 calls. visit_expr_in_out is 0x451e -> 0x451e bytes (JavaScript copy) and 0x4753 -> 0x4753 bytes (TypeScript copy). Differing instructions: 1 per copy, the tag immediate (mov $0x25,%al -> mov $0x26,%al). Tool: nm -S and objdump -d on bun-profile. valgrind and perf are not installed in the build container.
  • release binary: .text +0 bytes (65,818,853), total +0 bytes (91,088,996). Every section has the same size. Tool: size -A.
  • transpiler cache after upgrade: 35 of 35 entries rewritten on the first run, 0 on the second (sha256sum of the cache directory, 35 modules of 5 KB). +6 syscalls per rewritten entry: +2 openat, +2 close, +1 unlink, +1 fallocate, +1 pwritev, +1 renameat, -2 pread64. strace is not installed, so a small ptrace counter made the count. Two runs that only read the cache differ by 9 of about 900 syscalls.
  • Bun.Transpiler output over test/node_modules (.js, .mjs, .cjs, .ts): 0 of 46,398 files differ, 202,569,024 bytes on both sides. A module with 1,000 module-scope this nodes grows 5 bytes per node unminified and 2 bytes with minify.syntax.
  • module-scope this printed as a bare undefined that a local binding can capture (export {}; const f = (undefined) => [this]): 4 of 6 paths on this PR (Bun.Transpiler default, bun build --no-bundle, bun --inspect, bun test --coverage). Not on bun file.mjs and not on bun build. A user-written void 0 on main: 3 of 6 paths (the same without coverage). On main the same this is null on 6 of 6.
  • existing assertions changed: 1 (default/ThisUndefinedWarningESM). bundler_bytecode_portable.test.ts pinned hashes changed: 0 of 27. New or corrected cases that fail with USE_SYSTEM_BUN=1 on a release build of main: 11 of 11. The 4 control cases pass on both.

Tests.

  • test/bundler/transpiler/transpiler.test.js: printed forms with the js and ts loaders, with and without minify.syntax.
  • test/bundler/transpiler/runtime-transpiler.test.ts: the repro from the issue, and one module reached as entry file, static import, import(), require(), Worker entry and -e. Two controls keep this === module.exports for CommonJS.
  • test/cli/run/transpiler-cache.test.ts: a cached ES module prints the same value on the miss and on the hit. No test can cover the version bump itself. The cache measurement above does.
  • extra/CommonJSSymbol8 now runs its bundle. It asserted ns.b !== void 0 but was never run.
  • default/ThisWithES6Syntax stays todo. For an import-only file esbuild's expected bundle output is {} and Node gives undefined.

Other suites run with the debug build, all pass: esbuild/ts.test.ts, esbuild/dce.test.ts, esbuild/importstar.test.ts, esbuild/packagejson.test.ts, bundler_cjs.test.ts, bundler_edgecase.test.ts, es-decorators.test.ts, es-decorators-esbuild.test.ts, decorators.test.ts, macro-test.test.ts. A macro call with a module-scope this argument still transpiles.

Failures of the debug build that are the same on main's debug build (5 s timeouts): default/TopLevelAwaitForbiddenRequireSourceMapCLI, default/TopLevelAwaitForbiddenRequireSourceMapAPI, transpiler-cache --define invalidates cache and --drop invalidates cache.

Not fixed here.

@robobun

robobun commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:05 AM PT - Oct 17th, 2026

❌ @robobun, your commit 255a208 has 1 failures in Build #127076 (All Failures):

  • ❌ CPU instruction violation on Windows x64 — 1 check(s) failed
  • The baseline build contains instructions not available on Nehalem (SSE4.2, no AVX/AVX2/AVX512).

    • Static instruction scan

    Static scan violations

    _powf_special  [AVX]  (1 insns)
    

    If these are runtime-dispatched behind a CPUID gate: add each symbol to scripts/verify-baseline-static/allowlist-x64-windows.txt with a comment pointing at the gate.

    If there's no gate: this is a real bug — a -march leaked into a subbuild.


🧪   To try this PR locally:

bunx bun-pr 32173

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

bun-32173 --bun

@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Rewrites top-level this to undefined for ES modules in the parser/printer, updates runtime transpiler cache hashing and versioning, and adds/updates unit and runtime tests plus a bundler expectation change.

Changes

Top-level this undefined substitution tests and compiler updates

Layer / File(s) Summary
Transpiler unit tests for top-level this rewriting
test/bundler/transpiler/transpiler.test.js
Added unit tests covering ES module top-level this → undefined for export/import, top-level arrow substitution, CommonJS this → exports, delete this rewrite, and non-substitution inside functions.
Runtime fixture tests verifying actual this at runtime
test/bundler/transpiler/runtime-transpiler.test.ts
Added runtime tests that create temporary ESM (.mjs/type: module) and CommonJS fixtures, spawn them, assert exact stdout showing undefined for ESM and module.exports for CJS, and verify exit codes; updated harness import to include tempDir.
Bundler test expectation and bundler cache bump
test/bundler/esbuild/default.test.ts, src/bundler/cache.rs
Updated default/ThisUndefinedWarningESM expected output from [ null, null ] to [ undefined, undefined ]; incremented RUNTIME_TRANSPILER_CACHE_VERSION.
Parser: treat module-type files as ESM and substitute undefined
src/js_parser/p.rs
value_for_this now treats files with options.module_type == Esm (when no commonjs named exports) as ES modules and substitutes top-level this with an undefined expression at compile time.
Remove public null helper
src/js_parser/p.rs
Removed the exported null_value_expr() helper.
Printer: treat undefined as identifier-like operand
src/js_printer/lib.rs
is_identifier_or_numeric_constant_or_property_access now returns true for ExprData::EUndefined so unary-expression printing treats substituted undefined appropriately and documents wrapping rules for delete undefined.
JSC runtime transpiler cache version bump
src/jsc/RuntimeTranspilerCache.rs
Bumped expected runtime transpiler cache format version and documented that ES-module top-level this is undefined for cache validity checks.
Include module_type in runtime transpiler hasher
src/js_parser/parse/parse_entry.rs
hash_for_runtime_transpiler now incorporates self.module_type (as a u8) into the hasher so ESM vs CJS module-type contexts produce distinct cache keys.
CLI transpiler-cache integration test
test/cli/run/transpiler-cache.test.ts
Adds an integration test that writes identical JS into ESM/CJS dirs with different package.json "type" values and asserts cache isolation and correct runtime semantics per module type.

Possibly related PRs

  • oven-sh/bun#31226: Both PRs modify src/js_parser/p.rs’s P::value_for_this logic for top-level this substitution—main PR changes when this becomes undefined (ESM/module_type) and retrieved PR adds a REPL-mode exception to avoid rewriting this to exports.

Suggested reviewers

  • Jarred-Sumner
  • dylan-conway
  • RiskyMH
Pre-merge checks: Passed 4
Check name Status Explanation
Linked Issues check Passed The PR fully addresses issue #32167 by changing top-level this substitution from null to undefined in ES modules, matching ECMA-262 and Node behavior, with cache invalidation and printer safety improv…
Out of Scope Changes check Passed All changes directly support the primary objective of fixing top-level this substitution; cache version bumps, parser logic, printer safety, and test additions are all necessary and scoped to the issu…
Title check Passed The title clearly and concisely describes the primary change: substituting top-level this with undefined in ES modules.
Description check Passed The description is detailed and covers the problem, fix, verification, tests, cache changes, scope, and known limitations. It does not use the exact template headings, but it provides the required inf…
Full details: Linked Issues check

Explanation

The PR fully addresses issue #32167 by changing top-level this substitution from null to undefined in ES modules, matching ECMA-262 and Node behavior, with cache invalidation and printer safety improvements.

Full details: Out of Scope Changes check

Explanation

All changes directly support the primary objective of fixing top-level this substitution; cache version bumps, parser logic, printer safety, and test additions are all necessary and scoped to the issue.

Full details: Description check

Explanation

The description is detailed and covers the problem, fix, verification, tests, cache changes, scope, and known limitations. It does not use the exact template headings, but it provides the required information in equivalent sections.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

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

5616-5623: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle module_type == Esm in this branch too.

Line 5616 still keys only on has_es_module_syntax. prepare_for_visit_pass() separately marks files as ESM when self.options.module_type == options::ModuleType::Esm, so a .mjs/type: "module" file with no explicit import/export tokens will still fall through to the CommonJS exports rewrite instead of getting undefined.

💡 Suggested fix
-            if self.has_es_module_syntax && self.commonjs_named_exports.count() == 0 {
+            if (self.has_es_module_syntax
+                || self.options.module_type == options::ModuleType::Esm)
+                && self.commonjs_named_exports.count() == 0
+            {
                 // In an ES6 module, "this" is supposed to be undefined. Instead of
                 // doing this at runtime using "fn.call(undefined)", we do it at
                 // compile time using expression substitution here.
                 return Some(Expr {
                     loc,
                     data: js_ast::ExprData::EUndefined(E::Undefined),
                 });
             } else {

As per coding guidelines, "Fix the whole bug class in the same PR - grep for every sibling site sharing the pattern."

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

In `@src/js_parser/p.rs` around lines 5616 - 5623, The branch that substitutes
"this" for undefined only checks self.has_es_module_syntax and misses files
marked ESM via options; update the condition to also consider
self.options.module_type == options::ModuleType::Esm (or an equivalent
module_type == Esm flag) so that when has_es_module_syntax OR the module_type is
Esm and commonjs_named_exports.count() == 0 you return the EUndefined Expr;
search for other sibling sites that check has_es_module_syntax (e.g., other
CommonJS rewrites called after prepare_for_visit_pass()) and apply the same
module_type check to fix the whole bug class.

Source: Coding guidelines

🤖 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/transpiler/runtime-transpiler.test.ts`:
- Around line 236-239: The test captures stderr but never asserts it; update the
subprocess tests that read Promise.all([proc.stdout.text(), proc.stderr.text(),
proc.exited]) to assert stderr before checking exitCode—either add
expect(stderr).toBe("") (or the expected stderr string) immediately after the
stdout assertion or include stderr in the same object assertion (e.g., expect({
file, stdout, stderr }).toEqual({ file, stdout: "undefined true\n", stderr: ""
})), then keep expect(exitCode).toBe(0); apply the same change for the other
occurrence around the variables stdout, stderr, exitCode.

---

Outside diff comments:
In `@src/js_parser/p.rs`:
- Around line 5616-5623: The branch that substitutes "this" for undefined only
checks self.has_es_module_syntax and misses files marked ESM via options; update
the condition to also consider self.options.module_type ==
options::ModuleType::Esm (or an equivalent module_type == Esm flag) so that when
has_es_module_syntax OR the module_type is Esm and
commonjs_named_exports.count() == 0 you return the EUndefined Expr; search for
other sibling sites that check has_es_module_syntax (e.g., other CommonJS
rewrites called after prepare_for_visit_pass()) and apply the same module_type
check to fix the whole bug class.
🪄 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: 2aa73306-b322-4419-9f80-9e0f1ad174c4

📥 Commits

Reviewing files that changed from the base of the PR and between 885c44f and 72653f0.

📒 Files selected for processing (4)
  • src/js_parser/p.rs
  • test/bundler/esbuild/default.test.ts
  • test/bundler/transpiler/runtime-transpiler.test.ts
  • test/bundler/transpiler/transpiler.test.js

Comment thread src/js_parser/p.rs Resolved
Comment thread src/js_parser/p.rs Resolved

@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: 2

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

Inline comments:
In `@src/js_parser/p.rs`:
- Around line 5616-5621: The strict-mode check in P::prepare_for_visit_pass
should use the same forced-ESM predicate as P::value_for_this: replace the
current branch that only checks
esm_import_keyword/esm_export_keyword/top_level_await_keyword with a predicate
that uses self.has_es_module_syntax || self.options.module_type ==
options::ModuleType::Esm (and still ensure commonjs_named_exports.count() == 0
if that was part of the original module detection), so files forced to ESM (e.g.
.mjs or package.json "type":"module") enable implicit strict mode and match the
behavior of value_for_this; update the branch in prepare_for_visit_pass
accordingly, referencing prepare_for_visit_pass, value_for_this,
has_es_module_syntax, and options::ModuleType::Esm.

In `@src/jsc/RuntimeTranspilerCache.rs`:
- Line 46: Update the runtime-transpiler cache version constant so both modules
agree: change the RUNTIME_TRANSPILER_CACHE_VERSION constant in the bundler cache
to match EXPECTED_VERSION (23) defined in RuntimeTranspilerCache.rs; locate the
RUNTIME_TRANSPILER_CACHE_VERSION symbol in src/bundler/cache.rs and set its
value to 23 to prevent existing cache entries from being treated as stale.
🪄 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: d0e6225c-9432-42eb-b1d3-c5f940a4c837

📥 Commits

Reviewing files that changed from the base of the PR and between 72653f0 and 84e22c4.

📒 Files selected for processing (5)
  • src/js_parser/p.rs
  • src/js_printer/lib.rs
  • src/jsc/RuntimeTranspilerCache.rs
  • test/bundler/transpiler/runtime-transpiler.test.ts
  • test/bundler/transpiler/transpiler.test.js

Comment thread src/js_parser/p.rs Resolved
Comment thread src/jsc/RuntimeTranspilerCache.rs Resolved

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

♻️ Duplicate comments (1)
src/js_parser/p.rs (1)

5616-5620: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep forced-ESM detection in sync with implicit strict-mode setup.

Lines 5619-5620 now classify syntax-less .mjs / "type":"module" files as ESM for top-level this, but prepare_for_visit_pass() still only enables implicit strict mode from import/export/top-level-await. That leaves the same file with module this semantics and sloppy-mode parsing rules, which is an observable correctness break for forced-ESM files. Please drive both sites from the same forced-ESM predicate/helper.

As per coding guidelines, "Rust code: fix the whole bug class in the same PR - grep for every sibling site sharing the pattern."

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

In `@src/js_parser/p.rs` around lines 5616 - 5620, The code currently treats files
as forced-ESM in the TLA/`this` check using the condition
(self.has_es_module_syntax || self.options.module_type ==
options::ModuleType::Esm) && self.commonjs_named_exports.count() == 0 but
`prepare_for_visit_pass()` still enables implicit strict mode only when
import/export/top-level-await are present, causing mismatched semantics; extract
that forced-ESM logic into a single helper (e.g., is_forced_esm(&self) or
ModuleType::is_forced_esm) and replace both the top-level `this`/TLA check and
the implicit strict-mode decision in `prepare_for_visit_pass()` to call this
helper so forced `.mjs`/package-"type":"module" files get both module `this`
semantics and implicit strict parsing consistently (ensure to reference and
remove the duplicated conditionals: has_es_module_syntax, options.module_type ==
options::ModuleType::Esm, and commonjs_named_exports.count()).

Source: Coding guidelines

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

Duplicate comments:
In `@src/js_parser/p.rs`:
- Around line 5616-5620: The code currently treats files as forced-ESM in the
TLA/`this` check using the condition (self.has_es_module_syntax ||
self.options.module_type == options::ModuleType::Esm) &&
self.commonjs_named_exports.count() == 0 but `prepare_for_visit_pass()` still
enables implicit strict mode only when import/export/top-level-await are
present, causing mismatched semantics; extract that forced-ESM logic into a
single helper (e.g., is_forced_esm(&self) or ModuleType::is_forced_esm) and
replace both the top-level `this`/TLA check and the implicit strict-mode
decision in `prepare_for_visit_pass()` to call this helper so forced
`.mjs`/package-"type":"module" files get both module `this` semantics and
implicit strict parsing consistently (ensure to reference and remove the
duplicated conditionals: has_es_module_syntax, options.module_type ==
options::ModuleType::Esm, and commonjs_named_exports.count()).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 49a8f0a4-b2af-4de9-85fc-49152ae63652

📥 Commits

Reviewing files that changed from the base of the PR and between 9f8b044 and 63de048.

📒 Files selected for processing (3)
  • src/js_parser/p.rs
  • src/js_printer/lib.rs
  • src/jsc/RuntimeTranspilerCache.rs

Comment thread src/js_parser/p.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.

All my earlier feedback has been addressed and I didn't find anything new, but since this changes transpiler semantics (the module_type == Esm expansion of value_for_this, the printer's delete-operand wrap, and the runtime cache key derivation) it's worth a human maintainer's sign-off.

Extended reasoning...

Overview

This PR fixes #32167 by changing top-level this substitution in ES modules from null to undefined, matching ECMA-262 and Node. It touches five source files in the parser/printer/cache layer plus four test files:

  • src/js_parser/p.rs — value_for_this returns EUndefined instead of ENull, and now also treats options.module_type == Esm as ESM (so .mjs / "type": "module" files with no import/export syntax get undefined instead of falling through to exports). The now-unused null_value_expr helper is removed (verified no remaining references).
  • src/js_printer/lib.rs — EUndefined added to the delete-operand wrap predicate so substituted delete this prints as delete (0, undefined) instead of the strict-mode-invalid delete undefined.
  • src/jsc/RuntimeTranspilerCache.rs — EXPECTED_VERSION bumped 22→23 with a changelog line.
  • src/bundler/cache.rs — RUNTIME_TRANSPILER_CACHE_VERSION mirror synced 20→23.
  • src/js_parser/parse/parse_entry.rs — module_type (which is #[repr(u8)] with stable discriminants) folded into the runtime-transpiler features hash, closing a pre-existing cache-aliasing gap where byte-identical files in ESM vs CJS packages shared a cache entry.

All three of my earlier inline comments (cache version bump, delete undefined printer wrap, module_type in features hash) and CodeRabbit's comments have been addressed and resolved across commits 84e22c4, 9f8b044, 63de048, and 1a6c6fa. The bug-hunting pass on the current revision found no new issues.

Security risks

None identified. No auth, crypto, permissions, or untrusted-input parsing surface is touched. The cache-key change strictly narrows which entries are considered hits, and the version bump invalidates all prior on-disk entries.

Level of scrutiny

This is core transpiler/parser infrastructure — value_for_this runs on every top-level this in every transpiled file, and the features-hash change affects cache keying for every cached module. The primary fix (ENull→EUndefined) is a one-liner that restores the upstream esbuild behavior, but the PR also includes a deliberate behavioral expansion: the || module_type == Esm clause changes what bare .mjs / "type": "module" files (with no import/export syntax) see for top-level this from {} (via the exports substitution) to undefined. That is the spec-correct outcome and is well-tested here, but it is a user-visible semantic change beyond the original bug report.

Other factors

  • None of the changed files are CODEOWNER-protected.
  • Test coverage is thorough: transform-output unit tests, runtime subprocess tests across import-only/export-only/bare-.mjs/type:module/CJS, an updated bundler expectation, and a transpiler-cache integration test that exercises the ESM/CJS cache-poisoning scenario in both orders.
  • The author appropriately scoped out the related implicit-strict-mode question to a separate issue (#32175).

Given the transpiler-semantics scope and the multi-commit evolution across review rounds, I'm deferring to a human maintainer rather than auto-approving.

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

All my earlier feedback is addressed and I found nothing new on this revision — deferring only because this is a transpiler-semantics change (widened ESM predicate, printer delete-operand wrap, cache-key shape) that's worth a maintainer glance before merge.

Extended reasoning...

Overview

This PR fixes #32167 by changing the compile-time substitution of top-level this in ES modules from null to undefined (matching ECMA-262 and Node). What started as a one-line ENull → EUndefined swap in value_for_this (src/js_parser/p.rs) grew through review into five source-file changes:

  • src/js_parser/p.rs — return EUndefined instead of ENull; widen the ESM predicate to include module_type == Esm (so syntax-less .mjs / "type": "module" files also get undefined); remove the now-unused null_value_expr helper (verified no remaining references).
  • src/js_printer/lib.rs — add EUndefined to is_identifier_or_numeric_constant_or_property_access so delete this in a module prints delete (0, undefined) instead of the strict-mode-invalid delete undefined.
  • src/jsc/RuntimeTranspilerCache.rs — bump EXPECTED_VERSION 22 → 23.
  • src/bundler/cache.rs — sync the mirror constant 20 → 23.
  • src/js_parser/parse/parse_entry.rs — fold module_type into the runtime-transpiler features hash so byte-identical files in ESM vs CJS package contexts no longer alias one cache entry.

Plus four test files: bundler expectation update, new runtime subprocess tests, new transform-output tests, and a new transpiler-cache integration test.

Security risks

None. No auth, crypto, network, or filesystem-permission surface is touched. The cache-key change only adds a discriminator; it cannot cause stale entries to be accepted that weren't before.

Level of scrutiny

Moderate-to-high. The parser, printer, and runtime transpiler cache are on the hot path for every JS/TS file Bun executes. Each individual change is small and well-reasoned, but together they alter (a) ESM classification for this-substitution purposes, (b) printer output for an edge-case delete operand, and (c) the shape of the on-disk cache key. None of these are mechanical; they're semantic decisions about transpiler behavior. The widened ESM predicate in particular (treating module_type == Esm as ESM even with no import/export syntax) is a deliberate behavior change beyond the original bug report — it's correct per spec, but a maintainer should confirm it doesn't conflict with any intentional Bun-specific interop heuristic.

Other factors

  • All three of my earlier inline comments (cache version bump, delete undefined wrap, module_type in features hash) were addressed in commits 84e22c4 and 1a6c6fa, with tests covering each.
  • The bug-hunting system found nothing on the latest revision.
  • No CODEOWNERS paths are touched.
  • The author appropriately scoped out the related implicit-strict-mode question to a follow-up issue (#32175) rather than expanding this PR further.
  • Test coverage is thorough: transform-output assertions, runtime subprocess checks across four ESM-forcing variants plus a CJS negative control, and a cache-aliasing integration test that fails on the pre-fix build.

This is good work and I'd expect it to merge cleanly — I'm deferring purely because parser/cache semantics changes of this scope benefit from a maintainer sign-off rather than bot-only approval.

@robobun

This comment has been minimized.

@robobun
robobun force-pushed the farm/bdb20eae/esm-top-level-this-undefined branch from 24c6b77 to 4b66440 Compare June 20, 2026 02:08

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

All prior review feedback has been addressed and the change looks correct to me, but since this alters transpiler output semantics for every ES module (and broadens the ESM classification for this-substitution via module_type), it's worth a human sign-off.

Extended reasoning...

Overview

This PR fixes #32167 by changing the compile-time substitution of top-level this in ES modules from null to undefined (per ECMA-262 §16.2.1.6 and matching Node/esbuild). It touches:

  • src/js_parser/p.rs — value_for_this returns EUndefined instead of ENull; the ESM predicate is broadened to include options.module_type == Esm (so .mjs / "type": "module" files without import/export syntax also get undefined instead of falling through to the CJS exports substitution). The now-unused null_value_expr helper is removed.
  • src/js_printer/lib.rs — adds EUndefined to the delete-operand wrap helper so delete this → delete (0, undefined) instead of strict-mode-invalid delete undefined.
  • src/jsc/RuntimeTranspilerCache.rs — bumps EXPECTED_VERSION 22→23.
  • src/bundler/cache.rs — syncs the mirror constant 20→23.
  • src/js_parser/parse/parse_entry.rs — folds module_type into the features hash so byte-identical files in ESM vs CJS contexts no longer alias one cache entry.
  • Tests: transform-output assertions, runtime subprocess tests across import-only/export-only/bare-.mjs/type:module fixtures, a CJS negative control, and a transpiler-cache test for the module_type aliasing.

All three issues I raised on earlier revisions (cache version bump, delete undefined strict-mode SyntaxError, module_type missing from the features hash) have been addressed and resolved, as has CodeRabbit's feedback. The bug-hunting pass on the current revision found nothing.

Security risks

None. No auth, crypto, filesystem permissions, or untrusted-input parsing surface is changed. The transpiler-cache changes only add a discriminant byte to an existing hash and bump a version constant.

Level of scrutiny

Moderate-to-high. The diff is small and each piece is well-reasoned, but the JS parser/printer is on the hot path for every module Bun executes, and this is a runtime-observable semantics change. Two aspects in particular warrant a maintainer's eye:

  1. Broadening the ESM predicate (|| module_type == Esm) changes what .mjs/"type":"module" files with no import/export syntax see for top-level this — from exports ({}) to undefined. That's spec-correct and matches Node, but it's a behavior change for a class of files beyond the original bug report, and it interacts with Bun's intentional CJS-interop leniency for forced-ESM files (the author explicitly scoped out the related strict-mode question into #32175).
  2. Cache-key change — adding module_type to features_hash is correct, but it's a structural change to how cache entries are keyed.

Other factors

  • Test coverage is thorough (transform output, runtime behavior across all four ESM-detection paths, CJS control, delete-operand edge case, cache-aliasing regression test).
  • CI is green on the PR's own tests across all lanes; remaining failures are documented as unrelated flakes.
  • The default/ThisUndefinedWarningESM expectation update aligns with esbuild's original fixture.
  • No outstanding unresolved review threads.

I'm not approving solely because transpiler-semantics changes are the kind of thing a Bun maintainer should sign off on, not because I see anything wrong.

@robobun

This comment has been minimized.

@robobun
robobun force-pushed the farm/bdb20eae/esm-top-level-this-undefined branch from 4b66440 to e13bbdf Compare July 5, 2026 01:42
@robobun

This comment has been minimized.

Comment thread src/js_parser/parse/parse_entry.rs Resolved
Comment thread src/jsc/RuntimeTranspilerCache.rs Resolved
@robobun

This comment has been minimized.

@robobun

This comment has been minimized.

@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 — all three earlier concerns are addressed in the current diff: EXPECTED_VERSION is bumped to 30, module_type is folded into the features hash (with a test proving byte-identical ESM/CJS files no longer alias), and the delete this → delete (0, undefined) case is covered by the printer and locked in by a transpiler test.

Checked that null_value_expr has no remaining call sites, that options::ModuleType is #[repr(u8)] so the as u8 hash write is well-defined, and that the runtime test matrix covers both the sync entry-point and async imported-dep transpiler paths plus .cjs-under-"type":"module" staying exports.

Extended reasoning...

Overview

The PR fixes #32167: top-level this in an ES module was being substituted with null instead of undefined, contrary to the ECMAScript spec, Node, and the esbuild code this was ported from. The core change is one line in src/js_parser/p.rs (ENull → EUndefined), plus removal of the now-dead null_value_expr() helper. Supporting changes: EXPECTED_VERSION bumped 29→30 in RuntimeTranspilerCache.rs to invalidate stale on-disk entries, and module_type added to the features hash in parse_entry.rs so byte-identical .js files under "type": "module" vs "type": "commonjs" no longer share a cache entry. Four test files are extended: bundler snapshot updated to match esbuild, transpiler printed-output tests (including constant folding, arrow capture, delete this, and nested-function this left alone), a describe.concurrent runtime matrix over ESM/CJS entry and dep paths, and a transpiler-cache test proving the ESM/CJS cache separation via strict-vs-sloppy observable behavior.

Security risks

None. This is a spec-correctness fix to a compile-time literal substitution in the transpiler. No user input parsing, no auth, no crypto, no filesystem or network surface. The module_type as u8 hash write is safe — options::ModuleType is #[repr(u8)] with three variants.

Level of scrutiny

Moderate. The parser is a critical path, but the semantic change is a one-token substitution that aligns with the spec and the reference implementation (the comment above the changed line already said "undefined"). The remaining changes are the cache-invalidation infrastructure I asked for in earlier review rounds. I verified null_value_expr has no remaining callers repo-wide, the ModuleType enum has a stable #[repr(u8)], and the new test file already imports tempDir/bunExe/bunEnv from harness.

Other factors

All three of my prior inline concerns (cache version bump, delete undefined strict-mode SyntaxError, module_type missing from the cache key) are demonstrably fixed in the current diff — verified from code, not from the author's self-resolution. All coderabbitai threads were resolved by non-authors. Test coverage is thorough and follows the CLAUDE.md/REVIEW.md conventions: describe.concurrent for independent subprocess tests, Promise.all draining stdout/stderr/exited, combined-object assertion before exit code, tempDir from harness, real issue number cited, and the transpiler-cache test reuses that file's existing temp_dir/dummyFile fixture pattern. The PR description transparently documents scope that was tried and backed out (widening module_type == Esm into the branch condition) with a clear reason and a locking test for the current .cjs behavior.

@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 — all three concerns from earlier rounds are addressed: EXPECTED_VERSION is bumped to 30, module_type is now folded into the features hash, and the printer already wraps EUndefined for delete (verified at src/js_printer/lib.rs:1544, covered by the new delete (0, undefined) assertion).

Also checked: null_value_expr has no remaining callers, the module_type as u8 cast is sound (options_types::bundle_enums::ModuleType is #[repr(u8)]), and the earlier module_type == Esm widening is indeed dropped from value_for_this — the imports-cjs.js test locks in .cjs-under-"type":"module" keeping this === module.exports.

Extended reasoning...

Overview

The PR swaps a single literal in value_for_this (ENull → EUndefined) so top-level this in ES modules matches Node and the spec, deletes the now-orphaned null_value_expr() helper, bumps the runtime transpiler cache EXPECTED_VERSION from 29 to 30, and adds module_type to the features hash so byte-identical .js files under different package.json "type" settings no longer alias one cache entry. Test coverage spans the Bun.Transpiler printed output (including typeof/equality folding, arrow capture, delete this, and function-body this left alone), runtime spawns for entry-point and imported ESM plus CJS-under-ESM, an updated esbuild bundler snapshot, and a transpiler-cache test proving the ESM/CJS split.

Security risks

None. This is a compile-time expression substitution in the parser and a hash-input addition; no untrusted-input parsing, no auth/crypto/permissions, no I/O surface.

Level of scrutiny

Low-to-moderate. The core change is a one-token literal fix that brings Bun in line with the esbuild reference (js_parser.go emits EUndefined here) and Node. The two knock-on cache concerns — stale on-disk entries and the module_type key gap — were the substantive review risk, and both are handled with the version bump plus the hash addition (backed by a targeted test). Tests are added alongside existing cases in the right files, use tempDir/bunExe/bunEnv, drain pipes concurrently, assert output before exit code, and run under describe.concurrent.

Other factors

This is a follow-up push after my earlier inline comments; every point raised is now visible in the diff. I confirmed null_value_expr has zero remaining references, is_identifier_or_numeric_constant_or_property_access already includes EUndefined on main (so delete this prints delete (0, undefined)), and bundle_enums::ModuleType is #[repr(u8)] so the as u8 hash write is well-defined. The value_for_this condition is unchanged from base (has_es_module_syntax && commonjs_named_exports.count() == 0), so the dropped module_type == Esm widening described in the PR notes is not present — and the imports-cjs.js runtime test guards against a future regression there. No outstanding third-party CHANGES_REQUESTED reviews; the coderabbit threads are non-author-resolved. Exit reason is dry_streak.

@robobun

This comment has been minimized.

@robobun
robobun force-pushed the farm/bdb20eae/esm-top-level-this-undefined branch from d798cdd to 95d120b Compare October 11, 2026 14:56
@robobun robobun changed the title Substitute top-level this with undefined in ES modules js_parser: substitute undefined, not null, for top-level this in an ES module Oct 11, 2026
@robobun

robobun commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (6c1eb06) as one commit, 95d120b, and reduced to the constant fix.

Reproduced on 1.4.3 and on a release build of main: export {}; console.log(typeof this, this === undefined, this === null) prints object false true. Node v26.3.0 prints undefined true false.

Changes in this revision:

  • The module_type hunk in the transpiler cache features hash and its test are removed. this does not read module_type, and the two runtime load paths do not pass the same module_type for one file yet. Decide a file's module type with one rule on every runtime load path #40940 makes them agree and carries that hunk.
  • EXPECTED_VERSION is now 35, because main moved to 34.
  • The tests cover each load path (entry file, static import, import(), require(), Worker entry, -e), the printed forms with both loaders and with minify.syntax, and a replay from the transpiler cache. extra/CommonJSSymbol8 now runs its bundle.

The PR body has the measurements. The change adds 0 instructions and 0 bytes of binary size. Each cached transpiler entry is rewritten once after the upgrade.

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings: the two points I raised on earlier revisions are now in place on this one — EXPECTED_VERSION is bumped (34 -> 35) and the printer's delete operand wrap already covers EUndefined on main, so delete this prints delete (0, undefined). I also checked print_undefined for the extends / computed-key positions under minify (it parenthesizes void 0 at prefix level and above) and the REPL early return (it sits above the ESM gate, so REPL this is unchanged).

Extended reasoning...

The source change is a one-token substitution in value_for_this in src/js_parser/p.rs (ENull to EUndefined for top-level this in a file with ES module syntax), deletion of the now-unused null_value_expr helper, and a transpiler cache version bump in src/jsc/RuntimeTranspilerCache.rs; the rest is tests. It touches no security-sensitive surface. The inline findings (the PR description claims a module_type features-hash change that is not in the diff, and the TS type-only-import gate) are what keep this from an approve; the printer and REPL paths named in the body were read and ruled out.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟣 src/js_parser/p.rs — Pre-existing: a TypeScript CommonJS file whose only ES syntax is a type-only or type-elided import still runs under the CJS wrapper, but its top-level this is printed as undefined (base: null) where Node gives module.exports. The gate at src/js_parser/p.rs:6184 uses has_es_module_syntax, which is set from esm_import_keyword that import type {...} never restores (parse_stmt.rs:2323/2338/2348), while exports_kind for the same file is decided as Cjs at parse_entry.rs:2037. Fix: substitute top-level this consistently with the exports_kind the file is finally given (undefined only when it will run as ESM, exports when it gets the CJS wrapper), while keeping import-only .js files, which the runtime loads as ESM, at undefined.

    Why this was flagged

    Input: a .ts file such as import type { Foo } from "./types"; module.exports = { self: this }; (or a value import used only in type positions), run with bun file.ts or required from CJS. parse_stmt.rs:2102 records esm_import_keyword and the type-only branches at parse_stmt.rs:2323, 2338 and 2348 return S::TypeScript without restoring it. p.rs:3413-3416 then sets has_es_module_syntax from that keyword, so value_for_this at p.rs:6184 takes the ESM branch and the visit pass replaces this with EUndefined (p.rs:6190). Yet parse_entry.rs:2037-2043 classifies the same file as ExportsKind::Cjs with WrapMode::BunCommonjs because module is used, and the import-rejection at parse_entry.rs:2630-2639 skips IS_UNUSED records, so the file loads without error inside the CJS wrapper. The user gets this === undefined (base branch: this === null), whereas Node/tsc give this === module.exports; the CJS substitution to exports at p.rs:6196 never runs.

    Verification: Pre-existing (base prints null; this PR prints undefined, neither is Node's module.exports). Trigger: a TypeScript file whose only ES syntax is a type-only import and that uses CommonJS, run or required. parse_stmt.rs:2323, 2338 and 2348 never restore previous_import_keyword, so value_for_this (p.rs:6184-6191) makes this EUndefined, while parse_entry.rs:2037-2043 decides exports_kind = Cjs.

Comment thread src/jsc/RuntimeTranspilerCache.rs Resolved
Comment thread src/js_parser/parse/parse_entry.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.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline finding, I checked the rest of the diff: the value_for_this ESM arm now matches esbuild's valueForThis, null_value_expr has no remaining callers in src/, and the EXPECTED_VERSION bump covers the changed printed output. One note: the PR description's Scope section says the module_type cache-key hunk and its test were removed, but commit cf2f971 at HEAD adds them (src/js_parser/parse/parse_entry.rs:324-326 and the two "byte-identical files" cases in test/cli/run/transpiler-cache.test.ts) — the description and the code should agree before merge.

Extended reasoning...

The change substitutes EUndefined for top-level this in ES modules in src/js_parser/p.rs, deletes the now-unused null_value_expr helper, hashes module_type into the runtime transpiler cache key in parse_entry.rs, and bumps EXPECTED_VERSION to 35, with tests across transpiler, runtime-transpiler, cache, and esbuild-ported suites. No security-sensitive surface is touched. A confirmed inline finding on the module_type hash (sync and async load paths pass different module_type for .mjs/.cjs files, so one file gets two cache entries) plus the description contradicting the code on that very hunk mean a human should still look.

Comment thread src/js_parser/parse/parse_entry.rs Resolved
…S module

The parser replaces a module-scope `this` at compile time. In a file with
ES module syntax it put `null` there. The language says `undefined`.

- value_for_this returns E::Undefined for the ES module case and the
  now unused null_value_expr helper is removed.
- The runtime transpiler cache version goes from 34 to 35, because
  cached entries hold the old printed text.
@robobun
robobun force-pushed the farm/bdb20eae/esm-top-level-this-undefined branch from 95d120b to 255a208 Compare October 17, 2026 01:02

@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 trimmed-down revision is a one-literal change that matches esbuild's valueForThis, with the cache version bumped and the output change covered end to end.

What was reviewed:

  • value_for_this in src/js_parser/p.rs: only the ES-module arm changes (ENull -> EUndefined); the CJS exports arm and REPL early-return are untouched, and null_value_expr had no remaining callers.
  • delete this -> delete (0, undefined): the printer's is_identifier_or_numeric_constant_or_property_access in src/js_printer/lib.rs already lists EUndefined, so strict-mode output stays valid (and the transpiler test pins it).
  • EXPECTED_VERSION 35 -> 36 in src/jsc/RuntimeTranspilerCache.rs with the cache-hit replay test on an 8 KiB .mjs; the PR description's "34 to 35" wording is stale relative to the code.
  • Tests: printed-form matrix (js/ts, minified or not), runtime paths (entry, static/dynamic import, require, Worker, -e) plus CJS controls, and the two esbuild-port expectations updated rather than new inputs substituted.
Extended reasoning...

The diff is +3/-6 lines in src/ (one ExprData literal in the parser's top-level this substitution and a transpiler-cache format version bump) plus about 170 lines of tests across five test files. It touches no security-sensitive surface: no auth, crypto, input parsing of untrusted data, or memory management. The change is a direct port of esbuild's behavior, the printer already handles the delete undefined edge case, no CODEOWNERS entry covers the changed paths, all third-party review threads were resolved by non-authors, and the scope has shrunk since the last review by dropping the module_type hashing hunk that earlier findings concerned. The bug hunt exited on dry_streak with no findings.

@robobun

robobun commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator Author

CI on the rebased head 255a208 (build 127076): the PR's own tests pass on all lanes. Two red items, neither from this diff:

  • :windows: x64 - verify-baseline (hard error): the static instruction scan reports one AVX instruction (vphsubw) inside _powf_special, a CRT math routine. This diff is one parser literal and a u32 constant, which cannot add AVX to the CRT. The other five verify-baseline lanes passed, and three main builds after this one (127749, 127880, 127915) passed the check; the scanner also has a known decoder-desync false-positive history (verify-baseline: resync the x86 decoder at symbol starts (fixes x64-musl lane on main) #41549 and its revert). My Buildkite token is read-only, so I could not retry the job; it is job 01a14762-1128-448c-9fa6-8818053e1370 on build 127076 if a maintainer wants to re-run it rather than the whole build.
  • test/cli/run/run-autoinstall.test.ts (aarch64): flaky-new, passed on retry.

Mergeable, no open review threads, ready for a maintainer.

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

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.

Different output when logging this

2 participants