Skip to content

Remove dead code from bun_core, bun_jsc, bun_css, react_compiler, and two C++ bindings - #40367

Closed
robobun wants to merge 3 commits into
mainfrom
claude/farm/1dd9aae5/dead-code-rust-css-react-compiler
Closed

robobun wants to merge 3 commits into
mainfrom
claude/farm/1dd9aae5/dead-code-rust-css-react-compiler

Conversation

@robobun

@robobun robobun commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Net -222 lines across 43 files. Every item has zero references in src/, scripts/, test/, packages/ and the regenerated build/debug/codegen/ output, and the removal builds.

Removed

  • bun_core: ColorCode::Pink, and the env var declarations BUN_NEEDS_PROC_SELF_WORKAROUND, MI_VERBOSE, TODIUM (declared in env_var.rs, read by nothing in Rust or C++).
  • bun_jsc: BindgenTrivial, a Bindgen adapter no binding names. The ExternOptional doc comment in generated.rs that named it is reworded.
  • bun_css: AtRulePrelude::FontFeatureValues (never constructed, its only arm was unreachable!()), the SelectorParseErrorKind::{ExpectedNamespace, UnexpectedIdent} kinds and the SelectorError::{expected_namespace, unexpected_ident} variants they mapped to, and the 24 commented-out // #[cfg(feature = "sourcemap")] / // dest.add_mapping(self.loc) pairs left from the lightningcss port. No sourcemap feature exists in bun_css/Cargo.toml and Printer has no add_mapping.
  • react_compiler: the standalone Hole enum, HirFunction::return_type_annotation (set to None at all four constructors, never read), and Environment::reference_node_ids (always HashSet::new(), never read).
  • bun_bundler: StmtListWhich::AllStmts and its two match arms. The all_stmts list itself stays, it is filled directly.
  • bun_http: the write-only DecodeResult::well_know field. The lshpack_header::hpack_index FFI field it copied from is untouched.
  • C++: keyFromPublicString in JSVerify.cpp (no declaration, no caller) and the static formatStackTraceToJSValueWithoutPrepareStackTrace in FormatStackTraceForJS.cpp.
  • Commented-out Zig code in url/lib.rs (get_name_count), cli/create_command.rs (unsupported_packages), shell/subproc.rs (pub const Pipe = struct), PackageManagerEnqueue.rs (Path.joinAbsStringBuf) and sourcemap_jsc/CodeCoverage.rs (the statements column).

How the Rust items were found

The workspace already denies dead_code and unreachable_pub, so every remaining dead item is a pub item that is reachable from its crate root. For each of the 95 non-proc-macro crates this run rewrote every pub item whose name has no reference outside the crate to pub(crate) (re-exports, pub mod, FFI exports and macro bodies left alone), ran cargo check -p <crate> with --force-warn dead_code, and iterated until no flagged item had an outside reference. The items above are what rustc then reported, minus platform-gated code, MultiArrayList schema fields, test-only helpers and items staged by their authors (see Notes).

Verification

  • bun bd (full debug build) passes.
  • bun run rust:check-all: 12 of 12 target triples ok.
  • cargo fmt --check and clang-format on the two C++ files are clean.
  • test/js/bun/css/css.test.ts, test/bundler/css/css-modules.test.ts, react-compiler-fixtures.test.ts (3293 pass), test/js/node/http2/h2-conformance.test.ts, test/cli/test/coverage.test.ts, test/js/node/crypto/crypto.key-objects.test.ts, node-crypto.test.js, test/js/bun/util/pathToFileURL.test.ts all pass.
Notes

Left in place on purpose:

  • src/runtime/api/bun/h2/: Connection::{begin_header_block, send_header_block, send_push_promise}, hpack::Coder::take_pending_size_update, write_table_size_update, MAX_SIZE_UPDATE_BYTES, wire::MAX_FRAME_SIZE_DEFAULT have no production caller but are covered by unit tests, and the module files carry #![allow(dead_code)] as part of the in-progress rewrite.
  • react_compiler/compile_result.rs (LoggerSourceLocation::from_loc, BindingRenameInfo::declaration_start) and the four logged_severity methods in diagnostics/mod.rs: annotated as staged for logger wiring, same call as Remove dead code from react_compiler, the WebCore/IDL bindings, install_jsc, node-fallbacks, and misc crates #39420.
  • isolated_install::Store::Entry::{peer_hash, entry_hash}, LinkerGraph JSMeta/File fields, LineOffsetTable fields, Graph::content_hash_for_additional_file, BundledAst::tla_check: rustc reports them as never read because they are MultiArrayList schema structs. The generated items_* accessors read them.
  • OutputFile::owned_src_path_text, HTTPResponseMetadata::owned_buf: never read, but they own the buffers that borrowed slices point into.
  • Environment::get_property_type (react_compiler): test-only.
  • bun_core::fmt::ColorCode::{Blue, Orange, Red} are constructed through use ColorCode::* in Keyword::color_code; only Pink was dead.
  • bun_core::strings::rsplit_once has no caller, but clippy.toml names it as the replacement for the disallowed str::rsplitn and bstr::ByteSlice::rsplit_once_str, so it stays (review finding).
  • VM::has_termination_request, AbortSignal__Timeout__run, bun_core::util::EmbedKind and the bun_sys constants are already removed by Remove dead code from the JSC bindings, headers.h, the console builtin, and bun_jsc #40232 / Remove dead code from the Windows bunx shim, bun_sys, libuv_sys and mimalloc_sys #40172.

ZigString::to_slice_fast was also removed on main by #40374 while this PR was open; the rebase dropped the duplicate hunk.

Other scans that came back clean this run: unreferenced extern "C" declarations, FFI exports with no C++ or WebKit caller, .rs files outside every mod tree, .cpp files outside the build glob, src/js exports and top-level helpers, and C++ function definitions whose name appears nowhere else (574 files).

@coderabbitai

coderabbitai Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ec9ca186-be3c-4eda-bfea-12136703a37a

📥 Commits

Reviewing files that changed from the base of the PR and between a73ed27 and f9d8506.

📒 Files selected for processing (44)
  • src/bun_core/env_var.rs
  • src/bun_core/fmt.rs
  • src/bun_core/string/immutable.rs
  • src/bun_core/string/mod.rs
  • src/bundler/LinkerContext.rs
  • src/css/css_parser.rs
  • src/css/error.rs
  • src/css/printer.rs
  • src/css/rules/container.rs
  • src/css/rules/counter_style.rs
  • src/css/rules/custom_media.rs
  • src/css/rules/document.rs
  • src/css/rules/font_face.rs
  • src/css/rules/font_palette_values.rs
  • src/css/rules/import.rs
  • src/css/rules/keyframes.rs
  • src/css/rules/layer.rs
  • src/css/rules/media.rs
  • src/css/rules/namespace.rs
  • src/css/rules/nesting.rs
  • src/css/rules/page.rs
  • src/css/rules/property.rs
  • src/css/rules/scope.rs
  • src/css/rules/starting_style.rs
  • src/css/rules/style.rs
  • src/css/rules/supports.rs
  • src/css/rules/unknown.rs
  • src/css/rules/viewport.rs
  • src/css/selectors/parser.rs
  • src/http/lshpack.rs
  • src/install/PackageManager/PackageManagerEnqueue.rs
  • src/jsc/bindgen.rs
  • src/jsc/bindings/FormatStackTraceForJS.cpp
  • src/jsc/bindings/node/crypto/JSVerify.cpp
  • src/react_compiler/hir/environment.rs
  • src/react_compiler/hir/mod.rs
  • src/react_compiler/inference/analyse_functions.rs
  • src/react_compiler/lowering/build_hir/mod.rs
  • src/react_compiler/optimization/outline_jsx.rs
  • src/react_compiler/ssa/enter_ssa.rs
  • src/runtime/cli/create_command.rs
  • src/runtime/shell/subproc.rs
  • src/sourcemap_jsc/CodeCoverage.rs
  • src/url/lib.rs
💤 Files with no reviewable changes (44)
  • src/react_compiler/inference/analyse_functions.rs
  • src/bun_core/string/mod.rs
  • src/url/lib.rs
  • src/bundler/LinkerContext.rs
  • src/css/rules/keyframes.rs
  • src/css/rules/property.rs
  • src/css/rules/starting_style.rs
  • src/install/PackageManager/PackageManagerEnqueue.rs
  • src/react_compiler/optimization/outline_jsx.rs
  • src/css/rules/import.rs
  • src/css/selectors/parser.rs
  • src/runtime/cli/create_command.rs
  • src/react_compiler/ssa/enter_ssa.rs
  • src/css/rules/viewport.rs
  • src/react_compiler/lowering/build_hir/mod.rs
  • src/css/rules/supports.rs
  • src/bun_core/string/immutable.rs
  • src/css/rules/font_face.rs
  • src/css/rules/unknown.rs
  • src/jsc/bindings/node/crypto/JSVerify.cpp
  • src/css/rules/namespace.rs
  • src/bun_core/fmt.rs
  • src/jsc/bindings/FormatStackTraceForJS.cpp
  • src/sourcemap_jsc/CodeCoverage.rs
  • src/css/rules/page.rs
  • src/css/rules/container.rs
  • src/css/rules/document.rs
  • src/http/lshpack.rs
  • src/css/rules/media.rs
  • src/css/rules/nesting.rs
  • src/runtime/shell/subproc.rs
  • src/css/rules/font_palette_values.rs
  • src/css/error.rs
  • src/css/rules/layer.rs
  • src/bun_core/env_var.rs
  • src/css/rules/counter_style.rs
  • src/react_compiler/hir/mod.rs
  • src/css/printer.rs
  • src/css/rules/scope.rs
  • src/css/css_parser.rs
  • src/css/rules/style.rs
  • src/css/rules/custom_media.rs
  • src/react_compiler/hir/environment.rs
  • src/jsc/bindgen.rs

Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review.


Walkthrough

Summary

The pull request removes unused public APIs, obsolete internal helpers, unreachable CSS parser branches, and commented-out code across Bun core, CSS, networking, bindings, runtime, and React compiler modules.

Changes

Core and bundler API removal

Layer / File(s) Summary
Core and bundler API removal
src/bun_core/*, src/bundler/LinkerContext.rs
Unused environment variables, ColorCode::Pink, ZigString::to_slice_fast, and StmtListWhich::AllStmts are removed.

CSS parser and serialization cleanup

Layer / File(s) Summary
CSS parser and serialization cleanup
src/css/css_parser.rs, src/css/selectors/parser.rs, src/css/printer.rs, src/css/rules/*
Unused CSS parser and selector error variants are removed. Obsolete commented-out source-map code is deleted from CSS serialization paths.

Protocol, binding, and runtime cleanup

Layer / File(s) Summary
Protocol, binding, and runtime cleanup
src/http/lshpack.rs, src/jsc/bindings/*, src/install/PackageManager/*, src/runtime/*, src/sourcemap_jsc/*, src/url/lib.rs
Obsolete decode fields, JavaScript helpers, commented implementations, and unused runtime logic are removed.

React compiler HIR cleanup

Layer / File(s) Summary
React compiler HIR cleanup
src/react_compiler/hir/*, src/react_compiler/inference/*, src/react_compiler/lowering/*, src/react_compiler/optimization/*, src/react_compiler/ssa/*
Unused HIR fields and the standalone Hole enum are removed. Related HirFunction initializers are updated.

Possibly related PRs

  • oven-sh/bun#35437: Removes several of the same environment variables and unused CSS and Rust symbols.
  • oven-sh/bun#35437: Overlaps with this pull request across dead declarations and APIs.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change as removing dead code across the listed Rust components and two C++ bindings. It does not mention every affected component, but it remains concise and accu…
Description check ✅ Passed The description explains the removed items, the dead-code analysis method, intentional exclusions, and verification results. It provides the required purpose and verification information, although it …
Full details: Title check

Explanation

The title clearly identifies the main change as removing dead code across the listed Rust components and two C++ bindings. It does not mention every affected component, but it remains concise and accurate.

Full details: Description check

Explanation

The description explains the removed items, the dead-code analysis method, intentional exclusions, and verification results. It provides the required purpose and verification information, although it uses headings different from the template headings.


Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Status: the diff is complete and verified (full debug build, rust:check-all 12/12, the test suites listed in the description).

On tests: this PR deletes unreachable code only, so no behavior changes and no test can fail before the change and pass after it. The one test shape that would, a source lint that greps for the removed names, is the kind test/internal/source-lints/CLAUDE.md asks us not to write. The last two dead-code PRs (#39795, #39581) merged without one for the same reason, so this PR follows them and adds no test file.

The "possibly related" #35437 from the review summary is closed, not merged. None of the deletions here overlap with an open PR (checked against #39929, #40232, #40294, #40172, #40122 by file and hunk).

The claude-find-issues check failed inside the action itself (is_error: true after 649 ms, before it read the diff). It is not related to this change.

@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 two inline nits, I also grepped for lingering references to the removed C++ functions (keyFromPublicString, formatStackTraceToJSValueWithoutPrepareStackTrace) and the removed env-var declarations (MI_VERBOSE, BUN_NEEDS_PROC_SELF_WORKAROUND, TODIUM) across the whole repo including vendor/ — nothing reads them via getenv or otherwise. The codegen.rs hit for the well_know pattern is an unrelated well_known field.

Extended reasoning...

The two findings are prose-only (a doc comment and three clippy reason strings), so I spot-checked the removals most likely to have non-Rust consumers: the two C++ static functions and the three env-var declarations. None have any remaining reference in src/, vendor/, or elsewhere in the tree. The clippy.toml finding is the one worth a maintainer's call — it's not just stale text; the workspace lint actively forbids str::rsplitn / bstr::rsplit_once_str and redirects to the helper being deleted, so either the reason strings need updating or rsplit_once should stay.

Comment thread src/jsc/bindgen.rs Resolved
Comment thread src/bun_core/string/immutable.rs Resolved
Comment thread src/jsc/generated.rs Resolved
Comment thread src/jsc/generated.rs Resolved
@robobun

robobun commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Review round handled in a0ec661 and bc80bc7:

  • strings::rsplit_once stays. clippy.toml names it as the replacement for the disallowed str::rsplitn and bstr::ByteSlice::rsplit_once_str, so deleting it would have left the lint pointing at a missing helper.
  • The ExternOptional doc comment in src/jsc/generated.rs no longer names the removed BindgenTrivial. It keeps its original three-line length.

All four review threads are resolved. The PR description is updated to the current diff: net -235 lines across 44 files. No test file is added, for the reason in the comment above.

@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 — both prior nits (the BindgenTrivial doc comment and the rsplit_once/clippy.toml pointer) are addressed in a0ec661/bc80bc7.

What was reviewed:

  • Re-grepped every removed identifier (to_slice_fast, ColorCode::Pink, the three env vars, well_know, StmtListWhich::AllStmts, FontFeatureValues, the two selector error variants, keyFromPublicString, formatStackTraceToJSValueWithoutPrepareStackTrace, return_type_annotation, reference_node_ids, BindgenTrivial) — zero remaining references in src/.
  • Confirmed the removed standalone Hole enum is distinct from the still-used ArrayPatternElement::Hole/ArrayElement::Hole/PlaceOrSpreadOrHole::Hole variants.
  • Confirmed PhantomData in bindgen.rs is still used by BindgenOptional/BindgenArray after the BindgenTrivial removal.
Extended reasoning...

Overview

Net -235 lines of dead-code removal across 44 files spanning bun_core (an unused ZigString helper, a ColorCode variant, three unread env-var declarations), bun_jsc (BindgenTrivial adapter + a doc-comment reword), bun_css (an unconstructed AtRulePrelude variant with an unreachable!() arm, two never-constructed selector-error kinds, and 24 commented-out #[cfg(feature = "sourcemap")] stubs from the lightningcss port), react_compiler (a standalone Hole enum, two write-only struct fields), bun_bundler (a StmtListWhich variant with no constructor), bun_http (a write-only DecodeResult field), two static/unreferenced C++ functions, and several blocks of commented-out Zig-era code.

The two nits from my prior run were addressed: strings::rsplit_once was reinstated (clippy.toml names it as the disallowed-methods replacement, so immutable.rs is no longer in the diff), and the ExternOptional doc comment was reworded to drop the removed BindgenTrivial name and shortened back to three lines to satisfy the comment-cop check.

Security risks

None. No inputs are parsed, no auth/crypto/permission logic changes — the JSVerify.cpp deletion is a static free function with no declaration and no caller. Everything removed is either provably unreachable (never-constructed enum variants whose match arms were unreachable!()), commented-out, or a public item whose name appears nowhere else in the tree.

Level of scrutiny

Low-to-medium. Dead-code deletion is compiler-verified: the PR reports bun bd and rust:check-all across all 12 target triples pass, which mechanically proves no removed Rust item is referenced (including from cfg-gated code). I independently re-grepped every removed identifier across src/ and found zero remaining references. The 15 files matching \bHole\b all reference the separate ArrayPatternElement::Hole / ArrayElement::Hole / PlaceOrSpreadOrHole::Hole / ApplyArgConfig::Hole variants, not the removed standalone enum. The SelectorError grep only surfaces the unrelated unexpected_namespace_rule (kept). The C++ removals are file-static (FormatStackTraceForJS.cpp) or undeclared (JSVerify.cpp), so link-time verifies them.

Other factors

  • The PR follows the pattern of #39795 / #39581 (merged dead-code sweeps with no test file, since no behavior can change).
  • The description's methodology (rewrite pub → pub(crate) per crate, --force-warn dead_code, iterate) is sound and the Notes section documents exactly what was intentionally left in place and why (h2 rewrite unit-test-only helpers, MultiArrayList schema fields, owned-buffer fields, clippy-mandated helpers).
  • All four review threads on the PR are resolved and the author's follow-up commits directly address them.
  • The removed DecodeResult::well_know field only drops a write-only copy; the underlying FFI lshpack_header::hpack_index field is untouched, so the C ABI struct layout is unchanged.

@robobun

robobun commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Ready for a maintainer: both review rounds are addressed and all four threads are resolved. Format, clippy, miri, mordant, source lints and comment-cop pass on bc80bc7; the Buildkite build is still running. The only red check is the evidence gate, for the no-test reason explained above.

@robobun

robobun commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:20 PM PT - Aug 24th, 2026

✅ @robobun, your commit b29337112100de705215df549f7cc7f97c905baa passed in Build #105265! 🎉


🧪   To try this PR locally:

bunx bun-pr 40367

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

bun-40367 --bun

@robobun

robobun commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

CI on bc80bc7 (Buildkite build 104974): 181 of 182 jobs pass. The one red job is Windows 2019 x64, where test/js/node/test/sequential/test-cpu-prof-name.js segfaults in --cpu-prof; that failure is also present on main and is reported to main-break triage separately. Every other entry in the build is a retry-passing flake in areas this PR does not touch (install, napi, inspector, webview).

… two C++ bindings

Delete items that nothing references:

- bun_core: `ZigString::to_slice_fast`, `strings::rsplit_once`, the `Pink`
  color code, and the `BUN_NEEDS_PROC_SELF_WORKAROUND`, `MI_VERBOSE` and
  `TODIUM` env var declarations.
- bun_jsc: the `BindgenTrivial` adapter.
- bun_css: the `AtRulePrelude::FontFeatureValues` variant, the
  `ExpectedNamespace` / `UnexpectedIdent` selector error kinds and their
  `SelectorError` counterparts, and the commented-out `cfg(feature =
  "sourcemap")` / `dest.add_mapping` pairs left from the lightningcss port.
- react_compiler: the `Hole` enum, the always-`None`
  `HirFunction::return_type_annotation`, and the always-empty
  `Environment::reference_node_ids`.
- bun_bundler: the `StmtListWhich::AllStmts` variant.
- bun_http: the write-only `DecodeResult::well_know` field.
- C++: `keyFromPublicString` (JSVerify.cpp) and the static
  `formatStackTraceToJSValueWithoutPrepareStackTrace`
  (FormatStackTraceForJS.cpp).
- Commented-out Zig code in url/lib.rs, create_command.rs, shell/subproc.rs,
  PackageManagerEnqueue.rs and CodeCoverage.rs.
…nd drop the BindgenTrivial mention from a doc comment
@robobun
robobun force-pushed the claude/farm/1dd9aae5/dead-code-rust-css-react-compiler branch from bc80bc7 to b293371 Compare August 25, 2026 02:44
@robobun

robobun commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (3e8b2e6) as b293371. One conflict, in src/bun_core/string/mod.rs: #40374 had already removed ZigString::to_slice_fast together with its neighbours, so this PR's hunk there is dropped and the file is no longer in the diff. Everything else applied cleanly. The rebased branch builds (bun bd), rust:check-all is 12 of 12, and the css, css-modules, crypto key-object, coverage and react-compiler fixture suites pass. The description is updated to the new totals: net -222 lines across 43 files.

@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 — both earlier nits are addressed (rsplit_once kept for the clippy.toml disallowed-methods redirect; the ExternOptional doc comment no longer names BindgenTrivial), and every removed identifier now has zero references in src/.

Spot-checked the removed env vars, DecodeResult::well_know, keyFromPublicString, formatStackTraceToJSValueWithoutPrepareStackTrace, the CSS selector-error variants, FontFeatureValues, StmtListWhich::AllStmts, return_type_annotation, reference_node_ids, and ColorCode::Pink — all unreferenced. Confirmed the removed standalone Hole enum is distinct from the ArrayPatternElement::Hole / PlaceOrSpreadOrHole::Hole variants that remain in use.

Extended reasoning...

Overview

Pure dead-code removal: net -222 lines across 43 files spanning bun_core (three unread env-var declarations, ColorCode::Pink), bun_jsc (BindgenTrivial adapter + doc-comment reword), bun_css (never-constructed AtRulePrelude::FontFeatureValues, two unconstructed selector-error kinds and their mapped variants, 24 commented-out #[cfg(feature = "sourcemap")] stubs from the lightningcss port), react_compiler (standalone Hole enum, write-only HirFunction::return_type_annotation and Environment::reference_node_ids), bun_bundler (StmtListWhich::AllStmts), bun_http (write-only DecodeResult::well_know), two uncalled C++ statics, and several blocks of commented-out Zig porting scaffolding. My earlier review flagged two consumers outside the search scope (clippy.toml naming rsplit_once, and a hand-written doc comment naming BindgenTrivial); the author kept rsplit_once and reworded the doc comment, and both threads are resolved.

Security risks

None. The only security-adjacent file is JSVerify.cpp, where a static helper with no declaration and no caller (keyFromPublicString) is deleted; the live verify path is untouched. No auth, permissions, or input-validation surface is affected.

Level of scrutiny

Low-to-medium. Wide file spread but every hunk is a deletion of unreferenced code or commented-out scaffolding — no control-flow, no data-layout, no FFI-signature changes. The build (bun bd), rust:check-all (12/12 targets), and the css / react-compiler / h2 / crypto / coverage suites pass on the rebased head. CI is 181/182 green with the one red job also failing on main. I grepped the repo for every removed identifier and confirmed zero remaining references, and confirmed the removed standalone Hole enum is distinct from the still-used ArrayElement::Hole / ArrayPatternElement::Hole / PlaceOrSpreadOrHole::Hole variants.

Other factors

The workspace already denies dead_code, so these deletions are all pub items reachable from crate roots — the compiler could not flag them. The methodology (temporarily narrow to pub(crate), let rustc report, iterate) is sound and the description's "left in place on purpose" list documents the intentional exclusions (test-only helpers, MultiArrayList schema fields, in-progress-rewrite modules with #[allow(dead_code)], buffers whose only role is owning what a borrowed slice points into). No new tests are expected — nothing here changes behavior, and the repo's source-lint policy explicitly discourages tests that grep for removed names. All prior review threads are resolved and no human reviewer has left outstanding comments.

@robobun

robobun commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

State after the rebase (b293371): mergeable, no open review threads, and Format, clippy, miri, mordant, source lints and comment-cop pass. Buildkite build 105265 is running. The only red check remains the evidence gate, for the no-test reason explained above.

alii pushed a commit that referenced this pull request Aug 25, 2026
…sc JSC bindings (#40413)

### Problem
- Four Rust host exports have no C++ caller:
`Bun__WebSocketClient__writeBlob`, `Bun__WebSocketClientTLS__writeBlob`,
`Bun__WebSocketClientTLS__initWithTunnel`, and
`Bun__internal_drainTimers`. `WebSocket.cpp` converts a Blob to bytes
itself and calls `writeBinaryData`, and the tunnel path only creates the
non-TLS client. The `HOST_EXPORT` marker roots each of them, so neither
rustc nor hawk can see that they are dead.
- A handful of C++ methods are declared and defined but never called:
`HTTPParser::lessThan`, one `JSNodePerformanceHooksHistogram::create`
overload, `JSAbortAlgorithm::callbackData` and `toJS(AbortAlgorithm&)`,
`JSPerformance::toWrapped`, `JSCStackFrame::typeName`,
`root(CryptoKey*)`, the `String` overload of `throwNodeRangeError`, and
16 ncrypto helpers.
- Two `pub` Rust items have no caller in any crate:
`bun_base64::simdutf_encode_url_safe_alloc` and
`CowSliceZ::init_unchecked`.

### Fix
- Delete the items above. `WebSocketClient::write_blob` goes with its
exports. `encode_append_impl` folds into `encode_append`, its only
remaining caller. The ncrypto `Ec` class keeps its one live member,
`GetCurveIdFromName`.
- Every deletion is confirmed two ways: `rg` over `src/`,
`build/debug/codegen/`, `src/codegen/`, `packages/`, and `vendor/WebKit`
finds no reference, and a `bun-debug` relink with `--gc-sections
--print-gc-sections` discards each symbol. `host_fn_this_value` and
`root(MessagePort*)` looked the same way and stay: codegen emits the
first, and #39841 is editing `MessagePort.cpp`, so the second waits for
that fix to land.
- New source lint
`test/internal/source-lints/host-export-callers.test.ts`: every
`c`/`jsc` `HOST_EXPORT` marker must be named by a C or C++ source. It
fails on main with exactly the four exports above and passes here.
- Verified: `bun bd` builds, `bun run rust:check-all` passes on all 12
targets, `clang-format` and `cargo fmt` are clean. Ran
`test/js/web/websocket/` (blob, client, bidir proxy),
`test/js/node/crypto/` (crypto, ecdh, hmac, sign, x509), `node-http`,
`node-http-parser`, `perf_hooks`, and `abort`.

### Background
- `// HOST_EXPORT(Name, c)` marks a Rust fn that
`src/codegen/generate-host-exports.ts` wraps in an `extern "C"` thunk
for C++. The thunk exists whether or not C++ calls it, so an orphaned
export compiles without a warning.
- ncrypto (`src/jsc/bindings/ncrypto.{cpp,h}`) is Bun's copy of Node's
OpenSSL helper layer. Node still uses the removed helpers; Bun's callers
never did.
- The linker check: a debug link with `-Wl,--gc-sections
-Wl,--print-gc-sections` lists every function section nothing
references. A function that is discarded and also absent from the linked
binary has no caller on that platform. Platform-gated code then needs a
source check, which is why the darwin-only `Bun__noOrphans_*` and the
Windows-only `windowsEnv` builtin stay.

<details><summary>Notes</summary>

Removed, by file:

- `src/http_jsc/websocket_client.rs`:
`bun__websocketclient__write_blob`,
`bun__websocketclienttls__write_blob`,
`bun__websocketclienttls__init_with_tunnel`,
`WebSocketClient::write_blob`, and the now unused `JSValue` import.
- `src/runtime/timer/Timer.rs`: `drain_timers_export`
(`Bun__internal_drainTimers`).
- `src/base64/lib.rs`: `simdutf_encode_url_safe_alloc`;
`encode_append_impl` folded into `encode_append`.
- `src/ptr/CowSlice.rs`: `CowSliceZ::init_unchecked`.
- `src/jsc/bindings/node/http/NodeHTTPParser.{cpp,h}`:
`HTTPParser::lessThan`.
- `src/jsc/bindings/JSNodePerformanceHooksHistogram.{cpp,h}`:
`create(VM&, Structure*, JSGlobalObject*, HistogramData&&)`.
- `src/jsc/bindings/webcore/JSAbortAlgorithm.{cpp,h}`: `callbackData()`,
`toJS(AbortAlgorithm&)`, `toJS(AbortAlgorithm*)`.
- `src/jsc/bindings/webcore/JSPerformance.{cpp,h}`:
`JSPerformance::toWrapped`.
- `src/jsc/bindings/ErrorStackTrace.{cpp,h}`: `JSCStackFrame::typeName`,
`retrieveTypeName`, `m_typeName`.
- `src/jsc/bindings/webcrypto/CryptoKey.{cpp,h}`: `root(CryptoKey*)` and
the `WebCoreOpaqueRoot` forward declaration and include it needed.
- `src/jsc/bindings/webcore/JSDOMOperation.{cpp,h}`:
`throwNodeRangeError(JSGlobalObject*, ThrowScope&, const String&)`;
every caller passes an `ASCIILiteral`.
- `src/jsc/bindings/ncrypto.{cpp,h}`: `CryptoErrorList::add`,
`CryptoErrorList::pop_front`, `BignumPointer::encode`,
`BignumPointer::encodeInto`, `X509View::clone`, `BIOPointer::New(const
BIO_METHOD*)`, `BIOPointer::Write`, `EVPKeyPointer::bits`,
`Cipher::EMPTY`, `ECKeyPointer::New(const EC_GROUP*)`,
`EVPKeyCtxPointer::derive`, `HMACCtxPointer::digest`, `Ec::Ec()`,
`Ec::Ec(const EC_KEY*)`, `Ec::getGroup`, and the `Ec` conversion
operators and field.

Scan summary for this run. Areas: Rust in `src/runtime`, `src/http_jsc`,
`src/bun_core`, `src/base64`, `src/ptr`, and the JSC bindings outside
the files that open dead-code PRs (#39929, #40232, #40367, #40294,
#40172, #40122) already touch; the TS builtins in `src/js`.

- hawk over `x86_64-unknown-linux-gnu`, `x86_64-pc-windows-msvc`,
`aarch64-apple-darwin` (release profile, per `hawk.toml`): 847
`dead_public` findings. 668 are fields of FFI mirror structs
(`libuv.rs`, `windows_sys/externs.rs`, `boringssl.rs`). Most of the rest
are in files the open PRs own, are debug-only (`has_resolve_breakpoint`,
`StoredTrace::capture`, `ArrayHashMap::unlock_pointers`), are codegen
targets (`host_fn_this_value`), or are FFI enum mirrors
(`tty::Mode::Io`, `ImplementationVisibility`).
- oxlint with `no-unused-vars`, `no-unused-private-class-members`,
`no-unreachable` over `src/js`: 0 findings. No `src/js` file is
unimported. No `.rs` file is outside a `mod` tree except the three
`[[bench]]` targets.
- `--gc-sections` relink of `bun-debug`: 1005 non-generated discarded
symbols, 283 of them in files no open PR touches. After removing
sqlite3.c, llhttp, vendored shims, platform-gated code, and generated
`ZigGeneratedClasses` helpers, the list above is what remains.

Possibly dead, left alone:

- `bun_core::strings::split_once` / `rsplit_once`: no caller today, but
`clippy.toml` names them as the replacement for the denied
`str::split_once` / `bstr::split_once_str` forms. Kept as API surface.

- `src/jsc/bindings/webcore/streams/JSCrossRealmTransformState.{cpp,h}`
(135 lines): the `CrossRealm` source and sink kinds in
`StreamsForward.h` are never constructed. It reads as scaffolding for
stream transfer in the native streams work, so it stays.
- `ECDSASigPointer`, `ECGroupPointer`, `ECPointPointer`,
`HMACCtxPointer`: default constructor, move constructor, and `release()`
are unreferenced, but they are the smart-pointer idiom the rest of
ncrypto follows.
- `src/threading/Futex.rs` `wasm_impl` and `unsupported_impl`: no
shipped target compiles them.
- `bun_core::Global::StoredTrace::{EMPTY, capture}`,
`has_resolve_breakpoint`, `ArrayHashMap::unlock_pointers`,
`TaskTag::name`: release-dead, used under `debug_assertions`.

</details>
Jarred-Sumner added a commit that referenced this pull request Aug 27, 2026
…her crates (#40610)

### Problem
- The workspace denies `dead_code` and `unreachable_pub`, and earlier
sweeps removed the `pub` items a cross-crate analysis can see. What is
left is code no lint reports: branches behind constant conditions, `pub`
enum variants that nothing constructs, `pub` struct fields that nothing
reads, and commented-out code.
- The largest case is the js lexer: `LexerType` carried seven const
generic parameters for a JSON mode (`IS_JSON`, `ALLOW_COMMENTS`, ...)
that no caller ever set. The only instantiation is the default one, so
every `if IS_JSON` body in `src/js_parser/lexer.rs` was unreachable.
JSON is parsed by `src/parsers/json.rs`.

### Fix
- Delete the items. 83 source files, +221 / -1653. Every candidate was
checked with `rg` over `src/`, `build/debug/codegen/` and
`src/codegen/`, including `#[cfg(windows)]` and macOS paths. The Notes
list each one.
- The lexer becomes a plain `struct Lexer<'a>`: the `JsonOptionsT`
trait, the `NewLexer` alias, the `lexer_impl_header!` macro and the
`generic_const_exprs` feature gate go with the JSON branches. The only
JS-visible change is none: the default instantiation was the only one.
- `bun_runtime::Error` loses 85 unit variants that are never built (the
X509 codes live in `bun_http::CertError`; `InstallFailed` and friends
are only ever nested as `Error::Install(..)`). The `AllocatorVTable`
keeps only `free`, the one slot `StdAllocator` dispatches.
- New source lint
`test/internal/source-lints/literal-bool-condition.test.ts`: a
statement-level `if true {` / `if false {` outside `#[cfg(test)]` code
fails the lint. rustc and clippy accept both, so the dead `if false {
break 'outer; }` in `doStep5.rs` and the always-taken `if true {` block
in `Watcher.rs` (unwrapped here) had no other guard. The lint fails on
`main` with those two lines and passes with this PR.
- Verified: `bun bd`, `bun run rust:check-all` (12 targets), `cargo
clippy --workspace`, `cargo check --workspace --tests`, `cargo fmt
--check`. `bun bd test` on transpiler, bundler edge cases, shell, yaml,
zstd, transpiler cache, `Bun.write`, `Bun.file`, sourcemap, resolver
cache, WebSocket client, `bun add`/`bun remove`, lockfile sync, archive,
`bun:test`, `--watch`, and the source lints (about 2,700 tests, 0
failures attributable to this change; see Notes).

### Background
- `dead_code` does not report a `pub` item, a trait impl, an enum
variant that a `match` arm names, or a field that a compound assignment
(`+=`) touches. Each of those counts as a use to rustc even when nothing
reads the result.
- A `const bool` that is the same in every build (`const ALLOW_TMPFILE:
bool = false`, a trait const no impl overrides, a const generic no
caller sets) makes one side of its `if` unreachable, but rustc still
type-checks and keeps that side. The removed branches are all of this
kind. Flags that vary per build (`IS_WINDOWS`, `IS_DEBUG`,
`ENABLE_ASAN`) and the debug toggles (`TRACING`, `VERBOSE_FS`-style
logging switches that still have a body) were left alone.
- `BunBuiltinNames.h` entries and JS private names can be referenced by
string (`$getByIdDirectPrivate(this, "writer")`), so a name with no
`$name` hit is not dead. Two such candidates were checked and kept.

<details><summary>Notes</summary>

Removed, constant conditions:

- `src/js_parser/lexer.rs`: the 7 const generic parameters of
`LexerType`, the `JsonOptionsT` trait, `DefaultJsonOptions`, the
`NewLexer` alias and the `lexer_impl_header!` macro. 30 `if IS_JSON`
bodies, `assert_not_json` and its 13 calls, the `is_ascii_only` field
(only written in JSON mode), `Error::JSONStringsMustUseDoubleQuotes`,
and the `if !FeatureFlags::ALLOW_JSON_SINGLE_QUOTES` block.
`src/js_parser/lib.rs` drops `#![feature(adt_const_params,
generic_const_exprs)]`, which nothing else in the crate used.
- `src/bun_core/feature_flags.rs`: `ENABLE_ENTRY_CACHE` (always true:
the "cache disabled" tails of `read_directory_error` and
`read_directory_with_iterator` in `src/resolver/lib.rs`), `VERBOSE_FS`
(always false: two `prettyln!` blocks in `src/resolver/fs.rs` and the
`bstr::BStr` import), `HARDCODE_LOCALHOST_TO_127_0_0_1` (always false:
the rewrite in `HTTPContext::connect` and `WebSocketUpgradeClient`),
`ALLOW_JSON_SINGLE_QUOTES` (only read by the lexer JSON mode).
- `src/sys/tmp.rs`: `ALLOW_TMPFILE = false` with the `O_TMPFILE` open
and `linkat` paths and the `using_tmpfile` field.
`RuntimeTranspilerCache.rs` always unlinks the tmp name on failure now,
which is what the `!using_tmpfile` guard already did. The non-Linux
`O::TMPFILE` consts and `linkat_tmpfile` stubs in `src/sys/lib.rs` had
no other caller (`src/install/npm.rs` uses them under `cfg(linux)`).
- `src/libarchive/lib.rs`: `ArchiveAppender::HAS_APPEND_MUTABLE`, no
impl overrides the `false` default. With it: `append_mutable`, the `if
A::HAS_APPEND_MUTABLE` block, `Context::all_files`, `EntryMap`,
`U64Context` and its two impls, and the `all_files` initializer in
`create_command.rs`.
- `src/bundler/linker_context/doStep5.rs`: `if false { break 'outer; }`
and the label. `src/watcher/Watcher.rs`: an `if true {` block around the
"Added to watch list" log, unwrapped.
- `src/io/PipeWriter.rs`: `PosixStreamingWriterParent::HAS_ON_READY`,
set by both impls (the macro and `Terminal.rs`), read by nothing.

Removed, enum variants nothing constructs (each with its `name()` arm
and match arms):

- `bun_runtime::Error` (`src/runtime/error.rs`): `Panic`,
`RequestBodyNotReusable`, `DNSResolveFailed`, `TooManyRedirects`,
`ConnectionRefused`, `RedirectURLInvalid`, the 66 X509 verification
codes from `UNABLE_TO_GET_ISSUER_CERT` to
`UNKNOWN_CERTIFICATE_VERIFICATION_ERROR`, `InstallFailed`,
`InvalidPackageJSON`, `PathAlreadyExists`, `InvalidTarget`,
`OpenFailed`, `UnableToDecode`, `SocketClosed`, `StackOverflow`, `Test`,
`MissingTranspileExtra`, `PluginError`, `Name`, `EscapeCalledTwice`. The
or-patterns in `install_command.rs`, `pm_update_package_json.rs` and
`jsc_hooks.rs` keep their live alternatives.
- `bun_core::strings::BOM::{Utf16Be, Utf32Le, Utf32Be}`: `detect()` only
returns `Utf8` and `Utf16Le`. With them: the three byte-pattern consts,
the `_ =>` arms in the two `remove_and_convert_*` functions, and the
commented-out detection lines.
- `bun_shell_parser`: `Token::{Dollar, Eq}` and `TokenTag::{Dollar, Eq}`
(the lexer never pushes them), with the `TestToken` mirrors and JSON
arms in `src/runtime/shell/shell_body.rs`.
- `ShellErr::Todo` (`shell_body.rs`, `Builtin.rs`),
`bun_crash_handler::Error::InvalidDebugInfo` (patterns in
`crash_handler/lib.rs` and `jsc/btjs.rs`) and the
`bun_jsc::Error::InvalidDebugInfo` mirror,
`FetchFlags::PrintSourceAndClone` (`ModuleLoader.rs`, arm in
`jsc_hooks.rs`), yaml `ParseError::InvalidIndentation` and the
`ParseResultError::InvalidIndentation` it alone produced,
`bun_sourcemap::Error::Unknown`.

Removed, fields nothing reads:

- `AllocatorVTable::{alloc, resize, remap}` (`src/bun_alloc/lib.rs`):
only `free` is ever dispatched. With them:
`NO_ALLOC`/`NO_RESIZE`/`NO_REMAP`, `MimallocAllocator` and its four
functions in `basic.rs`, `default_alloc::{malloc_aligned,
realloc_aligned}` and `Alignment::to_byte_units`.
- `ArgumentsSlice::all` (`src/jsc/CallFrame.rs`),
`ParseTask::tree_shaking` (`src/bundler/ParseTask.rs`, 11 writers in
`bundle_v2.rs`; the parser reads `topts.tree_shaking`),
`JSMeta::entry_point_part_index` (`LinkerGraph.rs`, written in
`scanImportsAndExports.rs`), `NetworkSink::high_water_mark`
(`streams.rs`, `s3/client.rs`, with the `part_size` locals that fed it),
`CopyFile::read_off`, the POSIX `ReadFile::byte_store`,
`file_sink::Options::close`, `ZstdReaderArrayList::total_out`,
`Cloner::trees_count`.

Removed, commented-out code older than six months (blame on the line, or
on the Zig line the port copied):

- C++: `ImportMetaObject.cpp`, `InspectorHTTPServerAgent.cpp`,
`JSDOMExceptionHandling.cpp`, `ncrypto.cpp`, `KeyObject.cpp`,
`EventTarget.cpp`, `JSPerformanceEntryCustom.cpp`, `MessageEvent.h`
(plus a duplicate `#include "MessagePort.h"`), `Performance.cpp`,
`Performance.h`, `PerformanceEntry.cpp`, `PerformanceObserver.cpp`,
`PerformanceResourceTiming.cpp`, `WebSocket.cpp`.
- Rust: `AstBuilder.rs`, `postProcessCSSChunk.rs`,
`postProcessJSChunk.rs`, `crash_handler/lib.rs`, `css/declaration.rs`,
`css/selectors/selector.rs`, `css/values/percentage.rs`,
`WebSocketUpgradeClient.rs`, `lexer.rs`, `parse_fn.rs`, `visit_expr.rs`,
`paths/resolve_path.rs`, `exec_command.rs`, `braces.rs`,
`sha_hmac/sha.rs`, `StaticHashMap.rs`, `ffi_body.rs`.
- `.classes.ts`: disabled entries in `sql.classes.ts`,
`sockets.classes.ts`, `server.classes.ts`, `jest.classes.ts`; a leftover
loop in `generate_uv_posix_stubs.ts`.

Declaration-only C++:
`CryptoKeyOKP::platformExportSpki/platformExportPkcs8`,
`JSX509Certificate::getPublicKey`, `KeyPairJobCtx::deinit`,
`BunShell`/`ShellError` in `BunObject.h`.

Checked and kept: `Terminal::get_slave_fd` (used by
`js_bun_spawn_bindings.rs`), `macro(writer)` and `macro(mockedFunction)`
in `BunBuiltinNames.h` (`$getByIdDirectPrivate(this, "writer")` in
`ConsoleObject.ts`, `BunCommonStrings.h`), css `Segment::Name` and
`CssModuleExport::is_referenced` (lightningcss data model), the
react_compiler variants and fields that mirror the upstream schema,
`Mode::ProductionDynamic` (bake scaffolding), the MySQL protocol fields
that mirror the wire format, the debug toggles `LOG_ALLOCATIONS`,
`DISABLE_COMPRESSION_IN_HTTP_CLIENT`, crash handler `ENABLE`,
`ENABLE_AUTO_CORK`/`ENABLE_ALLOCATOR_POOL`, and the wasm scaffolding
behind `IS_WASM`/`IS_BROWSER`.

Test runs: `test/js/web/fetch/fetch.test.ts` fails the same 26 tests
with the released `bun` in this container (root user, no network).
`Bun.write > copyFileRange is not available > on large files` hits its 5
s timeout under the ASAN debug build while filling a 256 MB buffer in
JS; the copy itself takes 0.6 s and the hash matches.

This PR repeats no deletion of the open dead-code PRs (#39929, #40122,
#40172, #40232, #40294, #40367, #40492, #40525, #40557), checked by
diffing the removed lines. Three files are shared with them in other
regions (`src/install/lockfile/Package.rs`,
`src/runtime/cli/create_command.rs`, `src/runtime/jsc_hooks.rs`).
</details>

<!-- robobun:evidence:begin -->

---

**[review]** gate passed · iteration 2 · 84 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: BUILD FAILED (no junit output)
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/internal/source-lints/literal-bool-condition.test.ts
ninja: Entering directory `/workspace/bun/build/debug'
[1/166] gen generated_host_exports.rs
generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited
[2/166] gen ZigGeneratedClasses.{cpp,h,rs}
Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts
  - ResolveMessage (15 fields)
  - BuildMessage (10 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts
  - Archive (4 fields, 1 class fields)
Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts
  - ResourceUsage (8 fields)
  - Subprocess (20 fields)
Found 1 classes from /workspace/bun/src/runtime/api/cron.classes.ts
  - CronJob (5 fields)
Found 3 classes from /workspace/bun/src/runtime/api/filesystem_router.classes.ts
  - FileSystemRouter (5 fields)
  - FrameworkFileSystemRouter (2 fields)
  - MatchedRoute (8 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Glob.classes.ts
  - Glob (5 fields)
Found 1 classes fro
... (truncated)

release without fix: 1 FAILED
bun test v1.4.1-canary.1 (9e0b058)

test/internal/source-lints/literal-bool-condition.test.ts:
(pass) scans a non-empty set of tracked Rust sources [0.09ms]
(pass) withoutTestItems keeps production code and blanks #[cfg(test)] items [0.09ms]
234 |     "fn after_strings() {}",
235 |   ]);
236 | });
237 | 
238 | test("if true { .. } / if false { .. } outside #[cfg(test)] code", () => {
239 |   expect(offenders).toEqual([]);
                          ^
error: expect(received).toEqual(expected)

- []
+ [
+   "src/bundler/linker_context/doStep5.rs:308: if false {",
+   "src/watcher/Watcher.rs:752: if true {",
+ ]

- Expected  - 1
+ Received  + 4

      at <anonymous> (/workspace/bun/test/internal/source-lints/literal-bool-condition.test.ts:239:21)
(fail) if true { .. } / if false { .. } outside #[cfg(test)] code [0.19ms]

 2 pass
 1 fail
 3 expect() calls
Ran 3 tests across 1 file. [798.00ms]
__F:1:S:0
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/internal/source-lints/literal-bool-condition.test.ts
bun test v1.4.1 (731aa92)

test/internal/source-lints/literal-bool-condition.test.ts:
(pass) scans a non-empty set of tracked Rust sources [2.29ms]
(pass) withoutTestItems keeps production code and blanks #[cfg(test)] items [4.24ms]
(pass) if true { .. } / if false { .. } outside #[cfg(test)] code [1.22ms]

 3 pass
 0 fail
 3 expect() calls
Ran 3 tests across 1 file. [62.41s]
__F:0:S:0

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 631ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/126] gen generated_host_exports.rs
generated_host_exports.rs: 122 exports (host=5, lazy=10, generic=107, rust=0); 243 extern-C blocks audited
[2/126] gen ZigGeneratedClasses.{cpp,h,rs}
Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts
  - ResolveMessage (15 fields)
  - BuildMessage (10 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts
  - Archive (4 fields, 1 class fields)
Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts
  - ResourceUsage (8 fields)
  - Subprocess (20 fields)
Found 1 classes from /workspace/bun/src/runtime/api/cron.classes.ts
  - CronJob (5 fields)
Found 3 classes from /workspace/bun/src/runtime/api/filesystem_router.classes.ts
  - FileSystemRouter (5 fields)
  - FrameworkFileSystemRouter (2 fields)
  - MatchedRoute (8 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Glob.classes.ts
  - Glob (5 fields)
Found 1 classes from /workspace/bun/src/runtime/api/h2.classes.ts
  - H2FrameParser (32 fields)
Found 
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/bun_alloc/basic.rs                             |  73 +--
 src/bun_alloc/lib.rs                               | 105 +---
 src/bun_core/feature_flags.rs                      |  14 -
 src/bun_core/string/immutable/unicode.rs           |  28 -
 src/bundler/AstBuilder.rs                          |   4 -
 src/bundler/LinkerGraph.rs                         |   3 -
 src/bundler/ParseTask.rs                           |   4 -
 src/bundler/bundle_v2.rs                           |   9 -
 src/bundler/linker_context/doStep5.rs              |   5 +-
 src/bundler/linker_context/postProcessCSSChunk.rs  |   9 -
 src/bundler/linker_context/postProcessJSChunk.rs   |   5 -
 .../linker_context/scanImportsAndExports.rs        |   2 -
 src/collections/StaticHashMap.rs                   |   7 -
 src/crash_handler/error.rs                         |   3 -
 src/crash_handler/lib.rs                           |   7 +-
 src/css/declaration.rs                             |   4 -
 src/css/selectors/selector.rs                      |  23 -
 src/css/values/percentage.rs                       |  11 -
 src/http/HTTPContext.rs                            |  16 +-
 .../websocket_client/WebSocketUpgradeClient.rs     |  19 +-
 src/install/lockfile.rs                            |   2 -
 src/install/lockfile/Package.rs                    |   4 +-
 src/io/PipeWriter.rs                               |   2 -
 src/js_parser/lexer.rs                             | 631 ++++-----------------
 src/js_parser/lib.rs                               |   6 -
 src/js_parser/parse/parse_fn.rs                    |   3 -
 src/js_parser/visit/visit_expr.rs                  |   6 -
 src/jsc/CallFrame.rs                               |   9 +-
 src/jsc/ModuleLoader.rs                            |   1 -
 src/jsc/RuntimeTranspilerCache.rs                  |   6 +-
 src/jsc/bindings/BunObject.h                       |   3 -
 src/jsc/bindings/ImportMetaObject.cpp              |   4 -
 src/jsc/bindings/InspectorHTTPSe
... (truncated)
```

</details>

**gate history** · 2 passed · 1 rejected · iteration 2

<details><summary>evidence per changed file</summary>

```
file                                                 reads  edits  tests
src/bun_alloc/basic.rs                                   0      0      0
src/bun_alloc/lib.rs                                     0      0      0
src/bun_core/feature_flags.rs                            1      0      0
src/bun_core/string/immutable/unicode.rs                 0      0      0
src/bundler/AstBuilder.rs                                0      0      0
src/bundler/LinkerGraph.rs                               0      0      0
src/bundler/ParseTask.rs                                 0      0      0
src/bundler/bundle_v2.rs                                 0      0      0
src/bundler/linker_context/doStep5.rs                    0      0      0
src/bundler/linker_context/postProcessCSSChunk.rs        0      0      0
src/bundler/linker_context/postProcessJSChunk.rs         0      0      0
src/bundler/linker_context/scanImportsAndExports.rs      0      0      0
src/collections/StaticHashMap.rs                         0      0      0
src/crash_handler/error.rs                               0      0      0
src/crash_handler/lib.rs                                 0      0      0
src/css/declaration.rs                                   0      0      0
(+ 68 more files)
```

</details>

<!-- robobun:evidence:end -->

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
@robobun

robobun commented Aug 29, 2026

Copy link
Copy Markdown
Collaborator Author

Heads-up on a hunk overlap: #40915 deletes src/jsc/bindgen.rs outright (nothing outside the file names the module) and drops pub mod bindgen from src/jsc/lib.rs. Whichever of the two lands second can drop its bindgen.rs hunk on rebase; the generated.rs comment rewording here is untouched by #40915.

Jarred-Sumner pushed a commit that referenced this pull request Sep 25, 2026
### Problem
- `hasExportStar` in `src/runtime/bake/hmr-module.ts` has no caller. Its
only call site is a block that #18109 commented out on 2025-03-14. The
`availableExportKeys` local above that block is read only by the
commented-out code.
- `firstConnection` in `src/runtime/bake/client/websocket.ts` is
assigned once and never read.
- No lint reports them. Earlier sweeps ran `tsc --noUnusedLocals` over
`src/js` and `scripts` only, not over `src/runtime/bake`.

### Fix
- Delete `hasExportStar`, the commented-out check,
`availableExportKeys`, and `firstConnection`. 2 files, 40 lines removed.
- Correct because the bundler already drops `hasExportStar`. The
generated `bake.client.js`, `bake.server.js` and `bake.error.js` differ
from `main` only by the two removed local declarations.
- Verified: `tsc -p src/runtime/bake/tsconfig.json --noUnusedLocals` no
longer reports either file. `test/bake/dev/esm.test.ts` (17 pass),
`hot.test.ts` (11 pass) and `bundle.test.ts` (23 pass) with the debug
build.

Behaviour change: none

### Background
- `hmr-module.ts` is the module loader that the dev server sends to the
browser and to the SSR realm. `parseEsmDependencies` walks the
dependency list of an ES module. Each entry carries the export names
that the importer uses.
- The removed check compared those names with the exports of the
dependency and threw a `SyntaxError` for a missing one. It has been off
for 18 months. A missing export fails at the use site.
- A deletion has one possible place, so no other design was weighed.

### Downsides
- The commented-out check was the only sketch of export verification in
the HMR runtime. A person who wants to build it starts from the history
of #18109.

<details><summary>Notes</summary>

#### Why this run is small
Every other hit of this run is live, is platform code with a user on
another target, or is a line that one of the 34 open dead-code pull
requests already deletes. Each removed line here was checked against
those diffs. #40492 and #43378 touch `websocket.ts` in other hunks.

#### Scans of this run, all clean or already claimed
- Debug objects linked again with `--gc-sections --print-gc-sections`,
then `llvm-symbolizer` for `file:line`. 20,668 discarded functions in
bun's objects. The Rust ones outside macros and trait impls are Windows
or macOS helpers, or claimed (#40824, #40557, #40232). The C++ ones are
claimed, are template instantiations, or have a Rust caller on another
target (`bsd_socket_export`, `posix_spawnattr_reset_signals`).
- Rust functions that never get a symbol (generic or `#[inline]`, never
instantiated), found by comparing every `fn` line with the DWARF
declaration lines of all emitted functions. 86 hits outside `cfg`, trait
impls and `#[inline(always)]`. All are Windows-only, test-only (the
outbound half of `api/bun/h2/connection.rs`), or claimed.
- `clang -fsyntax-only -Wunused-function -Wunused-macros
-Wunused-template -Wunused-member-function` over 588 translation units
and the 69 unified ones (the build passes `-Wno-unused-function`). 3
functions and 6 macros.
`formatStackTraceToJSValueWithoutPrepareStackTrace`, `hostName`,
`G_TRUE`, `G_FALSE`, `MAX_LABELS` and `us_ioctl` are claimed (#40367,
#43378, #40492, #40294). `us_quic_send_one` is used under the non-Linux
`#if` branch.
- A whole-program C++ reference index (`c-index-test -index-file`, 657
translation units, 32,018 symbols declared in bun's tree). 8,711 have no
recorded reference. After filters for template-dependent uses, `extern
"C"`, virtual methods and names that WebKit headers use, 78 remain. All
are index artifacts (typedef struct tags, primary templates with used
specializations, `requires` clauses) or one-line getters in files that
open pull requests rewrite.
- `tsc --noUnusedLocals` over `src/js`, `scripts`, `src/codegen`,
`src/runtime/bake`, `src/node-fallbacks` and the sources of each
package. The hits outside this change are claimed (#40122, #41169,
#41385, #40492, #43778) or are loop variables.
- Regex scans for struct fields with no read and for `bool` or `Option`
fields that only ever get one constant. Nothing new after #43745.
- Exports of `src/js` modules and builtin functions with no mention in
another file: none.
- Files that nothing includes, imports or names: none outside `.idl`
copies (#41064). `src/symbols.txt`, `symbols.def` and the `package.json`
scripts name nothing that is gone. No `#if 0`.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 1 · the description declares no behaviour
change, so there is no failing test to prove; the existing suite in CI
is the check

<!-- robobun:evidence:end -->
@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-08-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.

1 participant