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

Closed
RO
3mo ago
+244-435

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)

  • Claimed by open dead-code PRs and therefore not touched here: webcore.rs's DOMExceptionCode/web_worker (#37149), install/lib.rs's TextLockfile (#37089 edits the adjacent line), valkey_jsc/js_valkey.rs's close_subscription_ctx pair (#38439, under its pre-refactor name), api/bun/spawn.rs and ffi/mod.rs re-exports (#37089, #37362; two more of them became unused by this PR), zlib_sys::inflateBackInit_ in both backends (#38439 edits the Windows one), the ERR_REDIS_* and ERR_KEY_GENERATION_JOB_FAILED codes (#37062 edits that block), bindgen.rs's three unused marker structs (#37149), react_compiler's 1150-line _exp validation variant (#37272).
  • Deliberately kept although rustc reports them: napi_status variants, SSRKind::Regular, serialized_failure::ErrorKind's JS variants and MessageId::Visualizer (external code tables), bake::Mode::ProductionDynamic (a documented mode placeholder), GenericIndexInt::from_usize (#38703 is editing that impl block), ERR_POSTGRES_INVALID_BYTE_SEQUENCE_FOR_ENCODING (documented in docs/runtime/sql.mdx), and the unused entries of the O::, EPOLL::, IN:: and POLL_* constant tables in bun_sys.

[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)