Skip to content

Remove dead code from the bun_runtime re-export hubs, bun_core, bun_css, bun_install, bun_bundler, the FFI crates, and the error-code table - #39319

Closed
robobun wants to merge 4 commits into
mainfrom
claude/farm/a988bc98/dead-code-runtime-reexports-misc
Closed

Remove dead code from the bun_runtime re-export hubs, bun_core, bun_css, bun_install, bun_bundler, the FFI crates, and the error-code table#39319
robobun wants to merge 4 commits into
mainfrom
claude/farm/a988bc98/dead-code-runtime-reexports-misc

Conversation

@robobun

@robobun robobun commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator

Removes 427 lines that nothing references (44 lines of reflowed import groups, two blank lines that keep rustfmt's module groups where they were, and visibility adjustments added, plus a 201-line source lint pinning the removed symbols), mostly from bun_runtime's re-export hubs, with leftovers in bun_core, bun_css, bun_install, bun_bundler, bun_collections, bun_sql_jsc, bun_jsc, the FFI declaration crates and the node error-code table. No behavior change.

This run is small on purpose: 24 dead-code PRs are already open, and everything they delete was left alone (checked line by line against their diffs; see "Left alone" below). What is here is the residue those PRs do not cover.

Problem

bun_runtime re-export hubs (about 200 lines)

  • src/jsc/generated_classes_list.rs (116 lines), mounted as bun_runtime::GeneratedClassesList, was a flat alias namespace with no reader: generate-classes.ts resolves each .classes.ts class to its Rust type by walking the crate's own pub mod / pub use tree (rustModuleResolver), and the regenerated generated_classes.rs is byte-identical without the file. bun_runtime is also the only crate that can see its own re-export hubs (nothing but bun_bin depends on it, and bun_bin only calls Cli::start), so a hub entry rustc reports unused is unused everywhere.
  • api.rs still mirrored the old bun.api.* Zig namespace: 36 aliases (Image, Shell, Timer, Archive, Glob, HTMLRewriter, NativeZlib, Valkey, MySQL, Postgres, FFIObject, SocketHandlers, x509, the 18 process::* names other than Rusage, the five PTY types under bun::terminal, bun::H2FrameParser, posix_spawn, bun_spawn as spawn, ...) that no code and no generated code names. TCPSocket/TLSSocket stay: rustc reported them unused on linux, but socket/WindowsNamedPipeContext.rs imports them through api.
  • Same shape in bun.js.rs (pub use crate::{api, webcore}), webcore.rs (the five sink re-exports, form_data::{AsyncFormData, FormData}, and the webcore::jsc::codegen forwarding module whose doc comment says it exists for call sites that "still spell" a path nothing spells), webcore/streams.rs (result::StreamResult), webcore/Request.rs (js_gen::from_js*), webcore/FormData.rs (get_boundary), s3/client.rs (multipart::{self}), bake/mod.rs (FrameworkRouter alias, DynamicRouteMap/EncodedPattern/Route/StaticRouteMap, production::{EntryPointMap, TypeAndFlags}), bake/dev_server/mod.rs (Assets, IncrementalGraph, RouteBundle, SourceMapStore), server/mod.rs (BunInfo, PreparedRequestFor, ServerInitContext, ServePluginsState), lib.rs (five cli::*_command crate-root aliases), cli/mod.rs (command::Command self-alias), cli/Arguments.rs (load_config), allocators/mod.rs, shell/interpreter.rs (Builtin), node/zlib/NativeZstd.rs (Context), api/JSBundler.rs (Config, MiniImportRecord), api/BunObject.rs (JSZstd::deallocator, whose own comment says "0 C++ refs, 0 Rust refs"), api/bun/Terminal.rs (from_js, from_js_direct) and api/bun/h2_frame_parser.rs (the CamelCase H2FrameParserConstructor twin of the snake_case alias the js2native thunk actually calls).
  • Seven items in server_body.rs, FrameworkRouter.rs and production.rs were reachable only through the deleted re-exports; they become pub(crate) (rustc's unreachable_pub demands it), and nothing else in them turned out to be dead.

bun_runtime items (about 110 lines)

  • streams::Writable::{TemporaryAndDone, IntoArray, IntoArrayAndDone} are never produced (the StreamResult variants of the same names are; the Writable ones only had to_js arms). WritableFuture::Handler is never armed: the only construction is inside the run() arm that matches an existing Handler, so WritableHandler, WritableHandlerFn and that arm go with it.
  • Never-constructed variants and their match arms: DrainResult::Empty (webcore.rs, two matches! in Body.rs, one arm in ByteStream.rs), ReadableStream::Source::Direct (the C++ Tag::Direct maps to None in from_js; the FFI Tag enum itself is untouched), pretty_format::Tag::ArrayBuffer (JSType::ArrayBuffer maps to Tag::TypedArray; the now-unreachable _ => {} arm of print_as goes too), shell::IoKind::Stdin, node_fs_watcher::Event::Close (EventType::Close, which is used, stays), cron::CalendarError::OutOfMemory, thumbhash::DecodeError::OutOfMemory.
  • Trait items with no caller: ServerLike::{SSL_ENABLED, DEBUG_MODE, vm_mut} (RequestContext uses its own const generics; the inherent NewServer::vm_mut is still used and stays) and ResponseLike::upgrade with both impls (the HMR upgrade goes through the inherent uws methods).

Other crates (about 60 lines)

  • bun_core: strings::rsplit_once (the _char variant is used, this one is not), the CodePointZero re-export in immutable.rs, and the ZERO_VALUE/MAX associated consts of CodePointZero (both impls; from_u32 is what the decoders use).
  • bun_css: css_parser::CustomMedia and IdentFns, the crate-root CustomIdentFns/DashedIdentFns, container::ContainerNameFns, selector::{_PrintErr, _Printer} ("re-export alias parity"), and the path re-export of the css_eql_partialeq! macro (every use is textual).
  • bun_install: PackageManager::{do_patch_commit, prepare_patch, GitResolver}, crate-root FolderResolution and PostinstallOptimizer, patch_install::PatchedDep.
  • bun_bundler: LinkerContext::{OutputFileListBuilder, StaticRouteVisitor, do_step5} module aliases, bundle_v2::{AdditionalFile, IndexStringMap}, options::BakeExtra. bun_collections::ArrayListAlignedIn and bun_sql_jsc::mysql::MySQLRequestQueue crate-level re-exports, bun_jsc::ZigErrorType crate-root re-export (the type is used by path).
  • FFI declarations with no caller on any target: windows_sys::kernel32::SetFileTime (its futimens caller was rewritten) and lsquic_sys::lsquic_conn_n_pending_streams.
  • ErrorCode.ts: 17 codes with no producer ($ERR_X( in src/js, ErrorCode::ERR_X in C++, ErrorCode::X in Rust, none in tests or docs): ERR_BUFFER_CONTEXT_NOT_AVAILABLE, ERR_CRYPTO_INITIALIZATION_FAILED, ERR_CRYPTO_INVALID_COUNTER, ERR_CRYPTO_INVALID_TAG_LENGTH, ERR_CRYPTO_JOB_INIT_FAILED, ERR_CRYPTO_SCRYPT_INVALID_PARAMETER, ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE, ERR_INVALID_ADDRESS, ERR_INVALID_PACKAGE_CONFIG, ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE, ERR_MISSING_PLATFORM_FOR_WORKER, ERR_NON_CONTEXT_AWARE_DISABLED, ERR_REQUIRE_ASYNC_MODULE, ERR_TLS_PSK_SET_IDENTITY_HINT_FAILED, ERR_WASI_NOT_STARTED, ERR_WORKER_INIT_FAILED, ERR_SECRETS_NOT_AVAILABLE. Everything that consumes the table is generated from it, so the renumbering is invisible.

Fix

  • Deletes the items above; the only other edits are the ones the deletions force (match arms, reflowed pub use groups, the seven pub -> pub(crate) changes, and the comments that named the removed items: JSBundler.rs's OutputKind note, api.rs, production.rs, the two SAFETY comments that cited ServerLike::vm_mut, and the ByteStream.rs / FormData.rs comments that named DrainResult::Empty / get_boundary, which were trimmed to a line and removed respectively).
  • How the Rust candidates were found: the workspace builds with dead_code = deny, so the only dead Rust left is pub items, which rustc exempts. For every crate, pub was temporarily demoted to pub(crate) on the items no file outside the crate mentions (and, for bun_runtime, on everything the codegen output and bun_bin do not mention), and cargo check -p <crate> was run for x86_64-unknown-linux-gnu, x86_64-pc-windows-msvc and aarch64-apple-darwin. An item was only deleted when rustc reported it unused on all three; items it reported on one target only (ipc.rs, node_fs.rs, cron.rs's Windows and macOS error variants, the api.rs socket aliases) and items only reached through macros expanded in other crates (bun_alloc's zone methods, bun_clap's const-eval helpers, js_class_module!'s IntoRawMut) were kept. The C++ was checked at link level (nm over every object plus libbun_rust.a); everything unreferenced there is either already in an open PR or a virtual override.
  • Verified by bun bd (regenerates the class, js2native, host-export and error-code codegen and links; the regenerated generated_classes.rs and generated_js2native.rs are byte-identical to before, generated_host_exports.rs differs only in source line-number comments), bun run rust:check-all (12 of 12 targets ok), bun bd test on test/js/web/streams/streams.test.js, test/js/web/fetch/body-stream.test.ts, test/js/node/watch/fs.watch.test.ts, test/js/bun/shell/{bunshell,commands/echo,commands/rm}.test.ts, test/js/node/util/parse_args/parse-args-null-config.test.ts, test/js/node/url/url-fileurltopathbuffer.test.ts and test/js/node/crypto/crypto-oneshot.test.ts (all pass; test/js/bun/test/pretty-format-overflow.test.ts segfaults on a 500-deep object in this debug+ASAN build exactly the same with main's pretty_format.rs swapped back in, and passes at depth 300 and on the release binary, so it is a debug stack-depth limit rather than anything here), and the new source lint test/internal/source-lints/dead-symbols-runtime-reexports-misc.test.ts (all five of its tests fail against main, every check firing, and pass here).

Left alone (for a later run)


[review] gate passed · iteration 0 · 54 files touched

fails on main (without fix)
ASAN without fix: 3 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/internal/source-lints/dead-symbols-runtime-reexports-misc.test.ts
bun test v1.4.0 (8c5296ac4)

test/internal/source-lints/dead-symbols-runtime-reexports-misc.test.ts:
(pass) orphaned files stay deleted [552.05ms]
113 |     ["src/runtime/cli/Arguments.rs", /\{load_config,/],
114 |     ["src/runtime/allocators/mod.rs", /^pub use linux_mem_fd_allocator::LinuxMemFdAllocator;/m],
115 |     ["src/runtime/shell/interpreter.rs", /^pub use crate::shell::builtin::Builtin;/m],
116 |     ["src/runtime/node/zlib/NativeZstd.rs", /^pub use _impl::\{Context, NativeZstd\};/m],
117 |   ];
118 |   expect(resurrected(checks, src)).toEqual([]);
                                         ^
error: expect(received).toEqual(expected)

- []
+ [
+   "src/runtime/lib.rs: \bGeneratedClassesList\b",
+   "src/bun.js.rs: ^pub use crate::(api|webcore);",
+   "src/runtime/api.rs: \bas (Image|Shell|Timer|Archive|SecureContext|Subprocess|Glob|HTMLRewriter|JSTranspiler|MarkdownObject|NativePromiseContext|BlockList|NativeBrotli|NativeZlib|NativeZstd|Valkey|MySQL|Postgre
... (truncated)

release without fix: 3 FAILED
bun test v1.4.0-canary.1 (eabb96de7)

test/internal/source-lints/dead-symbols-runtime-reexports-misc.test.ts:
(pass) orphaned files stay deleted [24.70ms]
113 |     ["src/runtime/cli/Arguments.rs", /\{load_config,/],
114 |     ["src/runtime/allocators/mod.rs", /^pub use linux_mem_fd_allocator::LinuxMemFdAllocator;/m],
115 |     ["src/runtime/shell/interpreter.rs", /^pub use crate::shell::builtin::Builtin;/m],
116 |     ["src/runtime/node/zlib/NativeZstd.rs", /^pub use _impl::\{Context, NativeZstd\};/m],
117 |   ];
118 |   expect(resurrected(checks, src)).toEqual([]);
                                         ^
error: expect(received).toEqual(expected)

- []
+ [
+   "src/runtime/lib.rs: \bGeneratedClassesList\b",
+   "src/bun.js.rs: ^pub use crate::(api|webcore);",
+   "src/runtime/api.rs: \bas (Image|Shell|Timer|Archive|SecureContext|Subprocess|Glob|HTMLRewriter|JSTranspiler|MarkdownObject|NativePromiseContext|BlockList|NativeBrotli|NativeZlib|NativeZstd|Valkey|MySQL|Postgres|SocketHandlers|FFIObject|x509)\b",
+   "src/runtime/api.rs: \bpub use crate::(server::(NodeHTTPResponse|ServerConfig|ServerWebSocket)|socket::udp_socket::UDPSocket|ffi::FFI|napi|node|dns_jsc as 
... (truncated)
passes on PR (with fix)
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/dead-symbols-runtime-reexports-misc.test.ts
bun test v1.4.0 (8c5296ac4)

test/internal/source-lints/dead-symbols-runtime-reexports-misc.test.ts:
(pass) orphaned files stay deleted [542.48ms]
(pass) dead bun_runtime re-exports do not reappear [67.68ms]
(pass) dead bun_runtime items do not reappear [25.74ms]
(pass) dead symbols in the other crates do not reappear [37.73ms]
(pass) dead error codes do not reappear [39.94ms]

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

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     366e4f4074
  features     baseline

22 deps, 120 codegen, 1175 objects in 853ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1236] gen bindgenv2
[2/1236] fetch zlib
[zlib] up to date
[3/1236] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[4/1236] install /workspace/bun
bun install v1.4.0-canary.1 (eabb96de7)

Checked 107 installs across 153 packages (no changes) [38.00ms]
[5/1236] fetch tinycc
[tinycc] up to date
[6/1235] gen .bind.ts → GeneratedBindings.cpp
[7/1235] gen ErrorCode+*.h
[8/1235] gen ProcessBindingConstants.lut.h
Generating /workspace/bun/build/release/codegen/ProcessBindingConstants.lut.h from /workspace/bun/src/jsc/bindings/ProcessBindingConstants.cpp
[9/1235] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (eabb96de7)

Checked 1 install across 2 packages (no changes) [1.00ms]
[10/1235] gen JSBuffer.lut.h
Generating /workspace/bun/build/release/codegen/JSBuffer.lut.h from /workspace/bun/src/jsc/bindings/JSBuffer.cpp
[11/1235] inst
... (truncated)
diff hotspot
src/bun.js.rs                                      |   4 -
 src/bun_core/string/immutable.rs                   |  12 --
 src/bun_core/string/immutable/unicode.rs           |   9 +-
 src/bundler/LinkerContext.rs                       |   3 -
 src/bundler/bundle_v2.rs                           |   2 -
 src/bundler/lib.rs                                 |   1 -
 src/collections/lib.rs                             |   1 -
 src/css/css_parser.rs                              |   3 +-
 src/css/generics.rs                                |   1 -
 src/css/lib.rs                                     |   2 +-
 src/css/rules/container.rs                         |   1 -
 src/css/selectors/selector.rs                      |   3 -
 src/install/PackageManager.rs                      |   4 +-
 src/install/lib.rs                                 |   2 -
 src/install/patch_install.rs                       |   2 -
 src/jsc/bindings/ErrorCode.ts                      |  17 --
 src/jsc/generated_classes_list.rs                  | 116 ------------
 src/jsc/lib.rs                                     |   7 +-
 src/lsquic_sys/lib.rs                              |   1 -
 src/runtime/allocators/mod.rs                      |   2 -
 src/runtime/api.rs                                 |  53 +-----
 src/runtime/api/BunObject.rs                       |   3 -
 src/runtime/api/JSBundler.rs                       |   6 +-
 src/runtime/api/bun/Terminal.rs                    |   4 +-
 src/runtime/api/bun/h2_frame_parser.rs             |   1 -
 src/runtime/api/cron.rs                            |   2 -
 src/runtime/bake/DevServer.rs                      |  18 --
 src/runtime/bake/FrameworkRouter.rs                |  10 +-
 src/runtime/bake/dev_server/mod.rs                 |  29 ---
 src/runtime/bake/mod.rs                            |   8 +-
 src/runtime/bake/production.rs                     |   4 +-
 src/runtime/cli/Arguments.rs                       |   2 +-
 src/runtime/cli/mod.rs          
... (truncated)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                                      reads  edits  tests
src/bun.js.rs                                 1      1      0
src/bun_core/string/immutable.rs              0      0      0
src/bun_core/string/immutable/unicode.rs      0      0      0
src/bundler/LinkerContext.rs                  0      0      0
src/bundler/bundle_v2.rs                      0      0      0
src/bundler/lib.rs                            0      0      0
src/collections/lib.rs                        0      0      0
src/css/css_parser.rs                         0      0      0
src/css/generics.rs                           0      0      0
src/css/lib.rs                                0      0      0
src/css/rules/container.rs                    0      0      0
src/css/selectors/selector.rs                 0      0      0
src/install/PackageManager.rs                 0      0      0
src/install/lib.rs                            0      0      0
src/install/patch_install.rs                  0      0      0
src/jsc/bindings/ErrorCode.ts                 0      0      0
(+ 38 more files)

…ss, bun_install, bun_bundler, the FFI crates, and the error-code table

Deletes src/jsc/generated_classes_list.rs (an alias namespace with no
reader), the unused aliases in bun_runtime's api.rs / webcore.rs / bake /
server / cli re-export hubs, a handful of never-constructed enum variants
(streams::Writable::{TemporaryAndDone, IntoArray, IntoArrayAndDone},
WritableFuture::Handler, DrainResult::Empty, Source::Direct,
pretty_format Tag::ArrayBuffer, shell IoKind::Stdin, fs watcher
Event::Close, CalendarError::OutOfMemory, thumbhash
DecodeError::OutOfMemory), the never-called ServerLike consts / vm_mut and
ResponseLike::upgrade, leftover re-exports and helpers in bun_core,
bun_css, bun_install, bun_bundler, bun_collections, bun_sql_jsc and
bun_jsc, two FFI declarations with no caller (SetFileTime,
lsquic_conn_n_pending_streams), and 17 error codes nothing produces.

Each Rust item was reported unused by rustc with the crate's pub items
demoted to pub(crate), on the linux, windows and darwin targets; verified
with bun bd, rust:check-all, the affected test files, and a source lint
pinning the removed symbols.
@coderabbitai

coderabbitai Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 minutes

Limit details: You’ve used all 5 included reviews currently available under your plan.

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e2c4cfb5-d276-4983-bb9e-129670aa3f6e

📥 Commits

Reviewing files that changed from the base of the PR and between 23d535a and fc4da40.

📒 Files selected for processing (54)
  • src/bun.js.rs
  • src/bun_core/string/immutable.rs
  • src/bun_core/string/immutable/unicode.rs
  • src/bundler/LinkerContext.rs
  • src/bundler/bundle_v2.rs
  • src/bundler/lib.rs
  • src/collections/lib.rs
  • src/css/css_parser.rs
  • src/css/generics.rs
  • src/css/lib.rs
  • src/css/rules/container.rs
  • src/css/selectors/selector.rs
  • src/install/PackageManager.rs
  • src/install/lib.rs
  • src/install/patch_install.rs
  • src/jsc/bindings/ErrorCode.ts
  • src/jsc/generated_classes_list.rs
  • src/jsc/lib.rs
  • src/lsquic_sys/lib.rs
  • src/runtime/allocators/mod.rs
  • src/runtime/api.rs
  • src/runtime/api/BunObject.rs
  • src/runtime/api/JSBundler.rs
  • src/runtime/api/bun/Terminal.rs
  • src/runtime/api/bun/h2_frame_parser.rs
  • src/runtime/api/cron.rs
  • src/runtime/bake/DevServer.rs
  • src/runtime/bake/FrameworkRouter.rs
  • src/runtime/bake/dev_server/mod.rs
  • src/runtime/bake/mod.rs
  • src/runtime/bake/production.rs
  • src/runtime/cli/Arguments.rs
  • src/runtime/cli/mod.rs
  • src/runtime/image/thumbhash.rs
  • src/runtime/lib.rs
  • src/runtime/node/node_fs_watcher.rs
  • src/runtime/node/zlib/NativeZstd.rs
  • src/runtime/server/RequestContext.rs
  • src/runtime/server/mod.rs
  • src/runtime/server/server_body.rs
  • src/runtime/shell/Builtin.rs
  • src/runtime/shell/interpreter.rs
  • src/runtime/test_runner/pretty_format.rs
  • src/runtime/webcore.rs
  • src/runtime/webcore/Body.rs
  • src/runtime/webcore/ByteStream.rs
  • src/runtime/webcore/FormData.rs
  • src/runtime/webcore/ReadableStream.rs
  • src/runtime/webcore/Request.rs
  • src/runtime/webcore/s3/client.rs
  • src/runtime/webcore/streams.rs
  • src/sql_jsc/mysql.rs
  • src/windows_sys/externs.rs
  • test/internal/source-lints/dead-symbols-runtime-reexports-misc.test.ts

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

@robobun

robobun commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator Author
Updated 12:54 AM PT - Aug 16th, 2026

@robobun, your commit fc4da40af6c62d0ca2fe32d8e1ab9c19169252af passed in Build #99277! 🎉


🧪   To try this PR locally:

bunx bun-pr 39319

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

bun-39319 --bun

@robobun

robobun commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator Author

Status: ready for review (review feedback addressed, waiting on CI).

  • Diff is green locally at fc4da40: bun bd builds and links, bun run rust:check-all passes on all 12 targets, the affected test files pass under bun bd test, and bun test test/internal/source-lints/ passes (the new lint fails on every check when run against main).
  • Deletions were checked line by line against the diffs of the 24 open dead-code PRs; nothing here overlaps them (the items they claim are listed under "Left alone" in the description).
  • Review: the two stale-comment nits are fixed (8b2eb56); the ServerInitContext report is a false positive, it is reachable through AnyRoute::from_js and cannot be demoted (details in the thread); the two comment-cop hits were trimmed/removed (fc4da40).

Comment thread src/runtime/server/mod.rs
Comment thread src/runtime/server/mod.rs
Comment thread src/runtime/bake/production.rs
Comment thread src/runtime/webcore/ByteStream.rs Outdated
Comment thread src/runtime/webcore/FormData.rs Outdated
Comment thread src/runtime/webcore/ByteStream.rs Outdated
Comment thread src/runtime/webcore/FormData.rs Outdated
@robobun

robobun commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the review in 8b2eb56 and fc4da40:

  • ServerLike::vm_mut references in the two SAFETY comments now point at NewServer::vm_mut, and the stale "for bake::production::EntryPointMap callers" sentence is gone.
  • The ServerInitContext re-export report is a false positive: the struct stays reachable through AnyRoute::from_js (server_body.rs:759), so unreachable_pub does not fire, and demoting it fails with private_interfaces. cargo check -p bun_runtime, bun bd and bun run rust:check-all pass as pushed. Replied in the thread with the exact error.
  • The two comments the comment lint flagged were pre-existing ones that only changed because they named deleted items; the ByteStream.rs doc is now one line and the FormData.rs comment is removed.

No code changes beyond comments since the first push.

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

Re-reviewed after 8b2eb56 and fc4da40 — no new issues found. I've verified the author's rebuttal on the ServerInitContext finding: AnyRoute is pub in server/mod.rs:148 and its inherent pub fn from_js (server_body.rs:759) takes &mut ServerInitContext, so rustc treats the struct as reachable and unreachable_pub does not fire; that finding was a false positive on my part. The two SAFETY-comment and doc-comment nits are fixed.

Given the breadth (54 files across ~10 crates, match-arm removals for never-constructed variants, 17 error-code table entries, and the generated_classes_list.rs deletion whose correctness rests on the codegen resolver), a human sanity pass is still worthwhile before merge.

Also checked: the new source-lint's /^\s+fn vm_mut\(/m check does not match the surviving inherent pub(crate) fn vm_mut at mod.rs:472, and the css/lib.rscss_parser.rs IdentFns/CustomIdentFns/DashedIdentFns re-shuffle keeps every previously-used path resolvable.

Extended reasoning...

Overview

This PR removes ~427 lines of dead code across 54 files: unused pub use re-exports in bun_runtime's hub modules (api.rs, webcore.rs, bake/mod.rs, etc.), the entire generated_classes_list.rs alias namespace, never-constructed enum variants and their match arms (DrainResult::Empty, ReadableStream::Source::Direct, Writable::{TemporaryAndDone,IntoArray,IntoArrayAndDone}, IoKind::Stdin, Event::Close, Tag::ArrayBuffer, two OutOfMemory error variants), never-called trait items (ServerLike::{SSL_ENABLED,DEBUG_MODE,vm_mut}, ResponseLike::upgrade), 17 unused error codes from ErrorCode.ts, two FFI declarations, and assorted crate-root re-exports in bun_core/bun_css/bun_install/bun_bundler/bun_collections/bun_sql_jsc. Seven items were demoted pubpub(crate) to satisfy unreachable_pub = deny. A 201-line source-lint test pins the deletions.

Follow-up on prior review

My previous run flagged three items. The two 🟡 nits (SAFETY comments citing the removed ServerLike::vm_mut, and a stale EntryPointMap doc sentence) were fixed in 8b2eb56. The 🔴 ServerInitContext/unreachable_pub finding was rebutted by the author, and I have now verified the rebuttal is correct: AnyRoute is a pub enum in the pub server module, and impl AnyRoute { pub fn from_js(..., init_ctx: &mut ServerInitContext, ...) } at server_body.rs:759 makes ServerInitContext reachable through a public interface, so rustc does not emit unreachable_pub. Demoting it would instead trip private_interfaces. The author also confirmed bun bd and rust:check-all pass on all 12 targets. That thread should be considered resolved. The comment-cop hits on ByteStream.rs/FormData.rs were addressed in fc4da40 (comments trimmed/removed).

Security risks

None identified. This is pure deletion of unreferenced Rust items, re-exports, and error-code table entries. No auth, crypto, permission, or input-validation logic is touched. The removed error codes have no producers (verified per PR description via grep across $ERR_X( in src/js, ErrorCode::ERR_X in C++, ErrorCode::X in Rust).

Level of scrutiny

Medium-high. While each individual removal is mechanical, the aggregate is large and the correctness of several removals depends on non-local facts: (a) that generate-classes.ts truly does not read generated_classes_list.rs (author reports regenerated generated_classes.rs is byte-identical), (b) that no macro-expanded or cfg-gated code constructs the removed enum variants (author checked all three target OSes via rustc dead-code analysis after temporarily demoting pubpub(crate)), and (c) that the 17 error codes have no dynamic producers. The methodology is sound and the compile-on-12-targets verification catches (b), but (a) and (c) rest on grep/byte-diff evidence a human should spot-check.

Other factors

  • The PR description is exceptionally thorough, including a per-item rationale and an explicit list of items left alone because open PRs claim them.
  • The source-lint test correctly scopes its regexes (verified /^\s+fn vm_mut\(/m does not match the surviving inherent method).
  • The css/lib.rs change is a re-shuffle rather than pure deletion (moves which module re-exports IdentFns vs CustomIdentFns/DashedIdentFns), but the net public surface is a strict subset of before.
  • CI build #99231 was still in progress at the time of the last status comment.
  • 24 other dead-code PRs are open per the description; a maintainer should confirm this one's non-overlap claim holds against whatever has merged since.

@robobun

robobun commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator Author

For whoever does the sanity pass, the two points above that rest on non-compiler evidence are quick to reproduce:

  • generated_classes_list.rs: bun bd --target codegen on this branch and on main, then diff build/debug/codegen/generated_classes.rs (and generated_js2native.rs); both are byte-identical. The resolver in generate-classes.ts only registers items at module depth 0, and everything in that file sat inside pub mod Classes { ... }.
  • Error codes: for each removed ERR_X, rg -w ERR_X src test docs finds only the table entry (JS producers spell $ERR_X(, C++ ErrorCode::ERR_X, both hit a word search), and rg -w X src (the Rust constants drop the ERR_ prefix) finds nothing.

All review threads are resolved; CI for fc4da40 is at 178/179 jobs passed with nothing failed so far.

Jarred-Sumner pushed a commit that referenced this pull request Aug 18, 2026
… and misc crates (#39574)

### Problem
- `src/jsc/bindings/libuv/` is only on the include path for non-Windows
builds (`scripts/build/flags.ts`, "libuv stubs for unix"). `uv/win.h`
(703 lines) and `uv/tree.h` (512 lines, included only by `win.h`) are
never reached.
- `uv/sunos.h`, `uv/os390.h`, `uv/aix.h` and `uv/posix.h` are selected
by `uv/unix.h` only on Solaris, z/OS, AIX, IBM i, Cygwin, Haiku, QNX and
Hurd. Bun builds for linux, macOS and FreeBSD.
- `packages/bun-error` is embedded in the dev error page
(`src/runtime/server/dev-error-page.html`). The page calls the function
behind `Symbol.for("Bun__renderFallbackError")` and nothing else.
`renderRuntimeError`, the abort state `dismissError` kept for it, and
the two modules only it imported (`sourcemap.ts`,
`stack-trace-parser.ts`) have no callers. #37081 lists this path as a
follow-up.
- `bun_zlib_sys::posix` and `bun_zlib_sys::win32` declare zlib functions
that nothing calls. `bun_zlib` declares its own. The only use of the two
modules was as re-exports of the types in `shared.rs`.
- A set of `pub` items in other crates has no user in any crate. rustc
cannot report them because `pub` items count as used.

### Fix
- Delete the six libuv headers. `uv.h` now includes `uv/unix.h`
directly. `uv/unix.h` keeps the linux, darwin and BSD branches.
`uv-posix-polyfills.c` drops the commented-out copies of the removed
branches.
- Delete `renderRuntimeError`, `sourcemap.ts` and
`stack-trace-parser.ts`. `dismissError` keeps the part that removes the
overlay. `runtime-error.ts` stays (it has a test).
- Delete `bun_zlib_sys/posix.rs` and `win32.rs`. `bun_zlib` imports the
types from `bun_zlib_sys::shared`, which is where the removed modules
took them from.
- Delete the unused Rust items listed below, plus the trait
implementations and imports that only they needed.

Verification:
- Every Rust item was found by making the unexported items crate-private
and compiling the workspace. An item is deleted only if rustc reports it
dead on x86_64 linux (dev, release, and with the `bun_debug` and
`bun_asan` cfgs), aarch64 linux, x86_64 musl, x86_64 Windows and aarch64
macOS.
- Each removed name was also searched in `src/codegen/`, the
`*.classes.ts` files, `src/js/` and the C++ bindings. Items that a
codegen template can emit were kept.
- `bun run rust:check-all`: 12 of 12 targets pass. `cargo check
--workspace --all-targets` passes (benches and unit tests still
compile). `cargo check -p bun_shim_impl --features shim_standalone` for
the Windows target passes.
- `bun bd` builds. The build recompiles `uv-posix-stubs.c` and
`uv-posix-polyfills.c` against the trimmed `uv.h`, and rebuilds the
bun-error bundle, which no longer exports `renderRuntimeError`.
- New test in `test/js/bun/http/serve.test.ts`: it takes the bun-error
bundle out of a real 500 page, evaluates it outside a browser, and
checks that the bundle registers the renderer and that `dismissError` is
a no-op when nothing is rendered. This is the surface the
`packages/bun-error` change touches.
- `bun bd test` passes for `test/js/bun/http/serve.test.ts -t "dev error
page"` (including the new test), `test/js/bun/runtime-error.test.ts`,
`test/js/bun/util/{zstd,arraybuffersink,filesink}.test.ts`,
`test/js/node/zlib/deflate-streaming.test.ts`,
`test/js/web/encoding/text-{encoder,decoder}.test.*`,
`test/js/workerd/html-rewriter.test.js`,
`test/js/bun/css/nth-anplusb-ident.test.ts`,
`test/js/web/fetch/blob.test.ts` and
`test/internal/source-lints/dead-code-escapes.test.ts`.
- `cargo fmt --check`, clang-format on the touched C file and prettier
on the touched TypeScript files pass.

<details>
<summary>Removed Rust items</summary>

- `bun_zlib_sys`: modules `posix` and `win32` (`struct_gz_header_s`,
`gz_header`, `gz_headerp`, `in_func`, `out_func`, and the `deflate*`,
`inflate*`, `compress*`, `uncompress`, `adler32`, `crc32`, `zlibVersion`
declarations), `shared::voidpf`.
- `bun_zlib`: declarations `compress`, `compressBound`, `uncompress`,
and the `internal` module that selected between the two removed modules.
- `bun_zstd`: `decompress` (every caller uses `decompress_append`).
- `bun_libdeflate_sys`: `libdeflate_deflate_decompress` (the `_ex`
variant is the one in use).
- `bun_mimalloc_sys`: `mi_strdup`, `mi_heap_collect`,
`mi_thread_set_in_threadpool`.
- `bun_cares_sys`: `ares_strerror`.
- `bun_windows_sys`: `SetHandleInformation`, `closesocket`.
- `bun_alloc`: `default_alloc::calloc`.
- `bun_core`: `GenericIndexInt::from_usize` and its macro-generated
implementations.
- `bun_css`: the four deprecated `to_css` methods on
`GenericSelectorList`, `GenericSelector`, `GenericComponent` and
`Combinator`. Their bodies were `unreachable!()`; the serializer
functions replaced them.
- `bun_runtime`: `JsSinkType::done` and its six overrides,
`FileCloser::update` and its implementations, `ReadableStream::to_js`,
`node_fs::Null::to_js`.

</details>

<details>
<summary>Overlap with open pull requests</summary>

The deletions here were checked against the open dead-code pull requests
(#35437, #35775, #35880, #36115, #36237, #37012, #37149, #37181, #37208,
#37301, #37454, #37659, #37788, #38005, #38900, #39319, #39561) and
against #38958 and #35075. Nothing deleted here is deleted by any of
them. Candidates they already cover were left out: `src/jsc/bindgen.rs`
(#37149), the dead `pub use` re-exports (#39319), the simdutf big-endian
and UTF-32 wrappers (#38958), and the items named in the skip lists of
the others. Some files here (`bun_alloc/lib.rs`, `bun_core/util.rs`,
`libdeflate.rs`, `mimalloc.rs`, `node_fs.rs`, `Blob.rs`, `FileSink.rs`,
`ReadableStream.rs`, `streams.rs`, `windows_sys/externs.rs`) are also
touched by open pull requests in different hunks. #36437 edits
`packages/bun-error` from a base that predates #37081; it changes one
import line in `stack-trace-parser.ts` and keeps `renderRuntimeError`,
so it does not overlap with this deletion but will need a rebase.

</details>

<details>
<summary>Found but not deleted (judgment calls for a
maintainer)</summary>

- `packages/bun-inspector-protocol/src/protocol/v8/` (about 32,600
lines): not exported by the package index since 2023 and regenerated
only with the opt-in `--v8` flag of `scripts/generate-protocol.ts`.
#39110 kept the flag, so this needs a decision.
- `packages/h3blast` (1,468 lines) and `packages/bun-build-mdx-rs` (558
lines): nothing in the repository references them. They may be kept on
purpose as a load generator and a proof of concept.
- `packages/bun-error/runtime-error.ts` is unused by the page but
covered by `test/js/bun/runtime-error.test.ts`. The four images in
`packages/bun-error/img/` are referenced only by the source glob in
`scripts/glob-sources.ts`.
- `HotReloadTaskView` in `src/jsc/hot_reloader.rs`: both `reload`
implementations ignore the task, and `VirtualMachine::reload` ignores
its `Option<HotReloadTask>` argument. Removing the plumbing is a small
refactor rather than a deletion.
- `react_compiler/compile_result.rs` has constructors and fields with no
users, but the file says the types are waiting to be wired up.
- The streams-era private globals in `BunBuiltinNames.h`
(`makeGetterTypeError`, `makeDOMException`, `addAbortAlgorithmToSignal`,
`removeAbortAlgorithmFromSignal`, `isAbortSignal`,
`createUninitializedArrayBuffer`, about 100 lines of
`ZigGlobalObject.cpp`) have no JS callers. Both files are being edited
by several open dead-code pull requests, so they were left for a later
run.

</details>

### Background
- rustc's `dead_code` lint treats every `pub` item in a library crate as
used, because another crate could import it. In this workspace every
crate is an implementation detail of one binary, so a `pub` item with no
importer in any crate is dead in the same sense as a private one. Making
such items crate-private for one compile lets rustc report the ones with
no users at all. The visibility changes themselves are not part of this
pull request.
- On POSIX, bun does not link libuv. Node-API addons that reference
libuv symbols get `uv-posix-stubs.c` and `uv-posix-polyfills*.c`, which
are compiled against the copied headers in `src/jsc/bindings/libuv/`. On
Windows the real libuv is linked and that directory is not used.
- `JsSinkType` is the Rust trait behind the native sink classes
(`FileSink`, `ArrayBufferSink`, the HTTP response sinks). Its methods
are called from the shared sink glue in `Sink.rs`; `done` was declared
there but the glue never called it.

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

---

**no test proof** · iteration 1 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/bun/http/serve.test.ts

<!-- robobun:evidence:end -->
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Closing as stale: this has merge conflicts with main. If the dead code is still present, please open a fresh PR against current main.

@robobun

robobun commented Aug 18, 2026

Copy link
Copy Markdown
Collaborator Author

Reopened against current main as #39582 (same deletions, rebased; one conflict in windows_sys/externs.rs where another sweep had since removed the neighbouring SetHandleInformation, resolved by only removing SetFileTime). The review threads from here are already folded in, and the lint test is dropped per the new test/internal/source-lints/CLAUDE.md.

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.

2 participants