diff --git a/src/ast/expr.rs b/src/ast/expr.rs index 73b8f92140c..f0980358545 100644 --- a/src/ast/expr.rs +++ b/src/ast/expr.rs @@ -255,10 +255,6 @@ impl Expr { } } - // TODO(port): gated on `EString::string_z` (E.rs:1666 block) which - // needs `bun_core::ZStr` bump-arena constructors. Only caller - // (`get_string_cloned_z`) is likewise gated. - #[inline] pub fn as_string_z<'b>(&self, bump: &'b Bump) -> Result, AllocError> { match &self.data { @@ -283,10 +279,6 @@ impl Expr { } // Expr — property/object/string accessor methods. -// TODO(port): these call into `E::Object::as_property` / `EString` -// methods that need `bun_core::utf16_eql_string`/`to_utf8_alloc` (track-A -// blocked_on) and `Vec::deep_clone`. Types are real; bodies un-gate with -// the parser round once those land. impl Expr { pub fn has_any_property_named(&self, names: &'static [&'static [u8]]) -> bool { @@ -314,7 +306,6 @@ impl Expr { } // toJS alias deleted — `to_js` lives in `bun_js_parser_jsc::expr_jsc` extension trait. - // TODO(port): move to *_jsc /// Only use this for pretty-printing JSON. Do not use in transpiler. /// @@ -2306,10 +2297,6 @@ impl Data { // ─────────────────────────────────────────────────────────────────────────── // Data — heavy transform/analysis methods (clone/deep_clone/fold/etc). -// TODO(port): these reference `Vec::deep_clone`/`E::*::Clone` -// surfaces, `bun_core::write_any_to_hasher`, and parser-state types that land -// with `P.rs`/`Parser.rs`. The *types* (`Data`/`Expr`/`Tag`/`Store`) are real; -// only these method bodies wait. impl Data { /// Shallow clone: re-allocate the boxed payload (so the caller owns a fresh @@ -3101,7 +3088,6 @@ impl Data { } // toJS alias deleted — see `bun_js_parser_jsc::expr_jsc::DataJsc` extension trait. - // TODO(port): move to *_jsc #[inline] pub fn is_string_value(&self) -> bool { diff --git a/src/ast/lib.rs b/src/ast/lib.rs index 2d00a3afdfa..b2104c4a98b 100644 --- a/src/ast/lib.rs +++ b/src/ast/lib.rs @@ -2090,9 +2090,6 @@ impl Log { let Some((tag_name, sys_errno)) = e.get_error_code_tag_name() else { return self.add_error_fmt(None, Loc::EMPTY, args); }; - // TODO(port): Zig does comptime fmt-string concat `"{s}: " ++ fmt` and - // tuple concat `.{x} ++ args`. With `fmt::Arguments` we compose at the - // value level instead. let prefix = bun_sys::coreutils_error_map::get(sys_errno).unwrap_or(tag_name); self.add_error_fmt(None, Loc::EMPTY, format_args!("{}: {}", prefix, args)) } diff --git a/src/ast/nodes.rs b/src/ast/nodes.rs index 5122c8b0c8e..c6f67e8f68b 100644 --- a/src/ast/nodes.rs +++ b/src/ast/nodes.rs @@ -622,7 +622,6 @@ pub struct SlotCounts { impl SlotCounts { pub fn union_max(&mut self, other: SlotCounts) { - // TODO(port): `enum_map::EnumMap` exposes `.values()`; the Zig iterates raw arrays. for (a, b) in self.slots.values_mut().zip(other.slots.values()) { if *a < *b { *a = *b; @@ -1244,7 +1243,6 @@ pub fn printmem(args: fmt::Arguments<'_>) { Output::flush(); } -// TODO(port): `thiserror` not in this crate's deps; hand-roll Display/Error. #[derive(Debug, Copy, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum ToJSError { #[strum(serialize = "Cannot convert argument type to JS")] diff --git a/src/ast/op.rs b/src/ast/op.rs index d8f1cd522ff..62f4f3b4c3e 100644 --- a/src/ast/op.rs +++ b/src/ast/op.rs @@ -277,7 +277,6 @@ impl Op { // Zig: `pub const TableType: std.EnumArray(Op.Code, Op) = undefined;` // This declared an `undefined` value (vestigial / used only for @TypeOf at callsites). // Ported as a type alias since Rust statics cannot be uninitialized. -// TODO(port): verify no callsite reads TableType as a value. pub type TableType = Table; /// `.rodata` `[Op; Code::COUNT]` indexed by [`Code`] discriminant. Exposes the diff --git a/src/ast/stmt.rs b/src/ast/stmt.rs index bb1b4aaae0b..defe492bb31 100644 --- a/src/ast/stmt.rs +++ b/src/ast/stmt.rs @@ -155,7 +155,6 @@ impl Stmt { // Zig `comptime_init` — `@unionInit(Data, tag_name, origData)`. In Rust the // variant constructor IS the union-init; this helper collapses to identity // and is absorbed by `StatementData::wrap_ref`. - // TODO(port): no direct equivalent; callers use the trait. #[inline] pub fn alloc(orig_data: T, loc: crate::Loc) -> Stmt { diff --git a/src/base64/lib.rs b/src/base64/lib.rs index 6259fbc30aa..2775f4b6a5b 100644 --- a/src/base64/lib.rs +++ b/src/base64/lib.rs @@ -109,7 +109,6 @@ pub enum DecodeAllocError { bun_core::named_error_set!(DecodeAllocError); pub fn decode_alloc(input: &[u8]) -> Result, DecodeAllocError> { - // TODO(port): narrow error set let mut dest = vec![0u8; decode_len(input)]; let result = decode(&mut dest, input); if !result.is_successful() { @@ -122,7 +121,6 @@ pub fn decode_alloc(input: &[u8]) -> Result, DecodeAllocError> { pub use bun_core::base64::encode; pub fn encode_alloc(source: &[u8]) -> Vec { - // TODO(port): narrow error set (Zig was `!bun.Vec`; OOM now aborts) let len = encode_len(source); let mut destination = vec![0u8; len]; let encoded_len = encode(&mut destination, source); diff --git a/src/boringssl/lib.rs b/src/boringssl/lib.rs index 60c17a526ce..62af27833c7 100644 --- a/src/boringssl/lib.rs +++ b/src/boringssl/lib.rs @@ -367,7 +367,6 @@ pub fn check_x509_server_identity(x509: &mut boring::X509, hostname: &[u8]) -> b for i in 0..boring::sk_GENERAL_NAME_num(names) { let r#gen = boring::sk_GENERAL_NAME_value(names, i); if let Some(name) = r#gen.as_ref() { - // TODO(port): name_type discriminants — verify GEN_* are c_int consts in bun_boringssl_sys match name.name_type { boring::GEN_URI => { has_identifier_san = true; diff --git a/src/bun_alloc/basic.rs b/src/bun_alloc/basic.rs index c1fe95e397d..17f072e7f93 100644 --- a/src/bun_alloc/basic.rs +++ b/src/bun_alloc/basic.rs @@ -1,8 +1,6 @@ use core::ffi::c_void; use crate::{default_alloc, mimalloc}; -// TODO(port): `Allocator`/`AllocatorVTable`/`Alignment` are the bun_alloc crate's -// equivalents of `std.mem.Allocator`, its `VTable`, and `std.mem.Alignment`. // TODO(refactor): consider reshaping the vtable struct into `trait Allocator` impls. use crate::{Alignment, AllocatorVTable, StdAllocator}; diff --git a/src/bun_alloc/heap_breakdown.rs b/src/bun_alloc/heap_breakdown.rs index 36a0784559c..d04b2709245 100644 --- a/src/bun_alloc/heap_breakdown.rs +++ b/src/bun_alloc/heap_breakdown.rs @@ -2,9 +2,8 @@ use core::ffi::{c_char, c_void}; #[cfg(target_os = "macos")] use core::ffi::{c_int, c_uint}; -// Only referenced from the Darwin `extern "C"` block below; rustc's -// reachability analysis doesn't see uses inside dead `extern fn` signatures. -#[allow(non_camel_case_types, dead_code)] +#[cfg(target_os = "macos")] +#[allow(non_camel_case_types)] type vm_size_t = usize; // Environment.allow_assert and Environment.isMac and !Environment.enable_asan diff --git a/src/bun_alloc/lib.rs b/src/bun_alloc/lib.rs index 492646cd26d..4227c90a4b3 100644 --- a/src/bun_alloc/lib.rs +++ b/src/bun_alloc/lib.rs @@ -2187,8 +2187,6 @@ impl Result { } pub fn is_overflowing(&self) -> bool { - // TODO(port): Zig compares the whole packed struct against a usize here - // (`r.index >= count`); reproduce by comparing the raw u32. self.index.raw() as usize >= COUNT } } @@ -2198,7 +2196,6 @@ impl Result { // ────────────────────────────────────────────────────────────────────────── /// Required interface for the `Block` parameter of `OverflowGroup`/`OverflowList`. -/// TODO(port): Zig used structural duck-typing; this trait names the methods the body calls. pub trait OverflowBlock { /// In-place initialize the `used` counter on possibly-uninitialized storage. /// SAFETY: `this` must point to writable, properly-aligned storage of `Self`. @@ -2766,7 +2763,6 @@ struct EmptyType { } /// Trait modeling Zig's `comptime AppendType` switch in `doAppend`. -/// TODO(port): Zig dispatches on the *type* (EmptyType / single slice / iterable-of-slices). pub trait BSSAppendable { /// Total byte length (excluding sentinel). fn total_len(&self) -> usize; @@ -3214,7 +3210,6 @@ impl let _key = Self::key_hash(denormalized_key); let _guard = self.mutex.lock(); - // TODO(port): narrow error set — IndexMap::get_or_put can only OOM. match self.index.entry(_key) { std::collections::hash_map::Entry::Occupied(e) => { let v = *e.get(); diff --git a/src/bun_bin/lib.rs b/src/bun_bin/lib.rs index 37395b82980..9ec80f18f1d 100644 --- a/src/bun_bin/lib.rs +++ b/src/bun_bin/lib.rs @@ -38,7 +38,7 @@ use core::ffi::{c_char, c_int}; mod phase_c_exports; // Force-link `bun_platform` so its `#[no_mangle]` C exports -// (`sys_epoll_pwait2`, `ioctl_ficlone`, …) reach the linker. +// (`sys_epoll_pwait2`, …) reach the linker. use bun_platform as _; use bun_core::Global; diff --git a/src/bun_core/Global.rs b/src/bun_core/Global.rs index c59bc5f5da0..1352feac513 100644 --- a/src/bun_core/Global.rs +++ b/src/bun_core/Global.rs @@ -660,8 +660,6 @@ pub fn exit(code: u32) -> ! { #[cfg(debug_assertions)] { - // TODO(port): Zig asserts the debug allocator deinit() == .ok and nulls - // the backing. Map to `bun_alloc::debug_allocator_data` once ported. debug_assert!(debug_allocator_data::deinit_ok()); } @@ -789,9 +787,6 @@ pub fn crash() -> ! { pub const user_agent: &str = concatcp!("Bun/", package_json_version); -// TODO(port): `*const c_char` is `!Sync`; wrap this in a `#[repr(transparent)]` -// Sync newtype or export via a `#[used]` static byte array. Kept as-is to -// mirror the Zig `export const`. #[repr(transparent)] pub struct SyncCStr(pub *const c_char); // SAFETY: points into a `'static` string literal; the pointer is never mutated. diff --git a/src/bun_core/env_var.rs b/src/bun_core/env_var.rs index 9ddfaf7b9a4..84129898328 100644 --- a/src/bun_core/env_var.rs +++ b/src/bun_core/env_var.rs @@ -832,7 +832,6 @@ macro_rules! __key_opt { None }; ($lit:literal) => { - // TODO(port): need a `zstr!` const constructor for &'static ZStr from a string literal. Some($crate::zstr!($lit)) }; } diff --git a/src/bun_core/external_shared.rs b/src/bun_core/external_shared.rs index 076cbf637d5..a7650784f2e 100644 --- a/src/bun_core/external_shared.rs +++ b/src/bun_core/external_shared.rs @@ -74,9 +74,6 @@ impl ExternalShared { ptr: Some(this.ptr), } } - - // TODO(port): Zig's `ExternalShared(T).Optional` was an inherent associated type. - // Stable Rust callers spell `ExternalSharedOptional` directly. } impl core::ops::Deref for ExternalShared { diff --git a/src/bun_core/fmt.rs b/src/bun_core/fmt.rs index c7088f5cc8c..930c51973cf 100644 --- a/src/bun_core/fmt.rs +++ b/src/bun_core/fmt.rs @@ -127,9 +127,6 @@ impl TableSymbols { // Table // ─────────────────────────────────────────────────────────────────────────── -// TODO(port): Zig `column_color` was a comptime `[]const u8` param spliced into the -// format string at compile time. Rust const generics don't accept `&'static str`, so -// it is stored as a runtime field and the format string is built at print time. pub struct Table< 'a, const COLUMN_LEFT_PAD: usize, @@ -211,9 +208,6 @@ impl<'a, const L: usize, const R: usize, const C: bool> Table<'a, L, R, C> { for _ in 0..L { crate::pretty!(" "); } - // TODO(port): Zig spliced `column_color` into the comptime format string - // ("<" ++ column_color ++ ">{s}"). Replicate via Output::pretty's - // runtime tag handling. Output::pretty(format_args!( "<{}>{}", self.column_color, @@ -703,9 +697,6 @@ pub fn fmt_os_path(buf: crate::OSPathSlice<'_>, options: PathFormatOptions) -> F } } -// TODO(port): Zig `fmtPath` dispatches on `comptime T: type` returning either FormatUTF8 -// or FormatUTF16. In Rust, callers should call `fmt_path_u8` / `fmt_path_u16` directly, -// or use a small trait. Providing both monomorphizations here. pub fn fmt_path_u8(path: &[u8], options: PathFormatOptions) -> FormatUTF8<'_> { FormatUTF8 { buf: path, @@ -3556,10 +3547,6 @@ fn escape_powershell_impl(str: &[u8], writer: &mut impl fmt::Write) -> fmt::Resu // OutOfRangeFormatter — Equivalent to ERR_OUT_OF_RANGE // ─────────────────────────────────────────────────────────────────────────── -// TODO(port): Zig `NewOutOfRangeFormatter(comptime T: type)` branches on `@typeName(T)` -// and `std.meta.hasFn(T, "format")` for the "Received" tail. The `@typeName(T)` fallback -// path is debug-only (Zig panics if field_name unset in debug). Represent as a trait so -// each `T` controls how it prints "Received ". pub trait OutOfRangeValue { fn write_received(&self, f: &mut Formatter<'_>) -> fmt::Result; fn type_name() -> &'static str; diff --git a/src/bun_core/lib.rs b/src/bun_core/lib.rs index d670f4e1b33..3f554c8f547 100644 --- a/src/bun_core/lib.rs +++ b/src/bun_core/lib.rs @@ -217,8 +217,8 @@ unsafe impl Sync for RawSlice {} /// Port of Zig's `std.os.environ` global (`[][*:0]u8`). On Windows the /// startup path `bun_sys::windows::env::convert_env_to_wtf8` overwrites this -/// with a WTF-8-encoded envp slice; `getenvZ` and `bun_main` then read it via -/// `os_environ_ptr()`. POSIX builds leave it empty and use libc's `environ`. +/// with a WTF-8-encoded envp slice; `getenvZ` then reads it via +/// `os::environ()`. POSIX builds leave it empty and use libc's `environ`. #[cfg(windows)] pub mod os { use core::ffi::c_char; @@ -259,20 +259,6 @@ pub mod os { } } -/// `bun.os_environ_ptr()` — pointer to the first element of `std.os.environ` -/// (or null if empty). Windows-only; POSIX uses libc's `environ` symbol. -#[cfg(windows)] -#[inline] -#[allow(dead_code)] -pub(crate) fn os_environ_ptr() -> *const *mut core::ffi::c_char { - // SAFETY: read of a process-global written once at startup. - let e = unsafe { os::environ() }; - if e.is_empty() { - core::ptr::null() - } else { - e.as_ptr() - } -} pub mod deprecated; pub mod env_var; pub mod feature_flags; diff --git a/src/bun_core/output.rs b/src/bun_core/output.rs index 7b324999675..dbf3b714153 100644 --- a/src/bun_core/output.rs +++ b/src/bun_core/output.rs @@ -7,8 +7,7 @@ //! * thin `macro_rules!` wrappers (`pretty!`, `pretty_errorln!`, `note!`, …) that perform //! the compile-time format-string rewrite via `pretty_fmt!`. //! -//! `pretty_fmt!` itself (the `` → ANSI substitution) is necessarily a proc-macro; -//! a stub is declared here and flagged `TODO(port): proc-macro`. +//! `pretty_fmt!` itself (the `` → ANSI substitution) is necessarily a proc-macro. use core::cell::{Cell, RefCell}; use core::ffi::c_int; diff --git a/src/bun_core/string/HashedString.rs b/src/bun_core/string/HashedString.rs index 47a8f70ec88..bced35f94a1 100644 --- a/src/bun_core/string/HashedString.rs +++ b/src/bun_core/string/HashedString.rs @@ -33,10 +33,6 @@ impl HashedString { } } - // TODO(port): Zig `eql` took `other: anytype` and switched on `@TypeOf(other)`: - // - HashedString / *HashedString / *const HashedString → compare hash/ptr/len - // - else (slice-like with .len and indexing) → rehash bytes and compare - // Rust has no type-switch; split into `eql` (HashedString) and `eql_bytes` (&[u8]). pub fn eql(&self, other: &HashedString) -> bool { ((self.hash.max(other.hash) > 0 && self.hash == other.hash) || (self.ptr == other.ptr)) && self.len == other.len diff --git a/src/bundler/Chunk.rs b/src/bundler/Chunk.rs index b5e92040cbe..cb06d1ec675 100644 --- a/src/bundler/Chunk.rs +++ b/src/bundler/Chunk.rs @@ -54,7 +54,6 @@ pub struct Chunk { pub files_with_parts_in_chunk: ArrayHashMap, /// We must not keep pointers to this type until all chunks have been allocated. - // TODO(port): was `= undefined` in Zig (set before use) pub entry_bits: AutoBitSet, /// PORT NOTE: Zig stored this as an arena-owned `[]const u8` (linker arena); @@ -652,7 +651,6 @@ impl IntermediateOutput { // `LinkerGraph.files` SoA (`items_entry_point_chunk_index`) lands with // the LinkerGraph work. `bun_paths` / `bun_core::fmt::count` / // `bun_alloc::alloc_slice` surfaces are tracked upstream. - // TODO(port): MultiArrayList SoA accessors — assuming `.items(.field)` → method returning slice let additional_files = graph.input_files.items_additional_files(); let unique_key_for_additional_files = graph.input_files.items_unique_key_for_additional_file(); @@ -750,7 +748,6 @@ impl IntermediateOutput { } QueryKind::HtmlImport => { - // TODO(port): std.fmt.count → counting writer; assuming bun_core::fmt::count count += bun_core::fmt::count(format_args!( "{}", HTMLImportManifest::format_escaped_json( @@ -790,7 +787,6 @@ impl IntermediateOutput { let debug_id_len = if ENABLE_SOURCE_MAP_SHIFTS && FeatureFlags::SOURCE_MAP_DEBUG_ID { - // TODO(port): std.fmt.count → counting writer bun_core::fmt::count(format_args!( "\n//# debugId={}\n", source_map::DebugIDFormatter { @@ -914,7 +910,6 @@ impl IntermediateOutput { } QueryKind::HtmlImport => { - // TODO(port): std.io.fixedBufferStream → write into &mut [u8] let mut cursor: &mut [u8] = remain; let before_len = cursor.len(); HTMLImportManifest::write_escaped_json( @@ -1214,7 +1209,6 @@ impl fmt::Display for UniqueKey { pub struct EntryPoint(u64); /// so `EntryPoint` can be a u64 -// TODO(port): Rust has no native u30 — using u32 with mask. Zig: `pub const ID = u30;` pub(crate) type EntryPointId = u32; impl EntryPoint { @@ -1425,13 +1419,11 @@ impl Layers { } impl CssImportOrder { - // TODO(port): hasher: anytype — Zig hasher protocol has .update([]const u8) pub(crate) fn hash(&self, hasher: &mut H) { // TODO: conditions, condition_import_records // Zig: bun.writeAnyToHasher(hasher, std.meta.activeTag(this.kind)) — feeds the small-int // tag bytes. core::mem::Discriminant is opaque/pointer-sized; hash an explicit u8 instead. - // TODO(port): activeTag byte width — Zig's Tag(union) here is u2; u8 keeps hash stable. let tag: u8 = match &self.kind { CssImportOrderKind::Layers(_) => 0, CssImportOrderKind::ExternalPath(_) => 1, diff --git a/src/bundler/Graph.rs b/src/bundler/Graph.rs index 824d7ba2fb4..b2f2c3fd9ce 100644 --- a/src/bundler/Graph.rs +++ b/src/bundler/Graph.rs @@ -18,9 +18,7 @@ use bun_ast::Index; pub(crate) use crate::IndexInt; pub struct Graph<'a> { - // TODO(port): lifetime — no direct LIFETIMES.tsv row for Graph.pool, but row 170 - // (ThreadPool.v2, BACKREF) evidence states "BundleV2.graph.pool owns ThreadPool". - // bundle_v2.zig:992 allocates it from `this.arena()` (the `self.heap` arena) and + // bundle_v2.zig:992 allocates this from `this.arena()` (the `self.heap` arena) and // bundle_v2.zig:2248 calls `pool.deinit()`, so this is arena-owned but self-referential // (sibling field). `BackRef` (not raw `NonNull`) so the read accessor `pool()` is // safe — the BACKREF invariant (pointee outlives holder) holds for the entire diff --git a/src/bundler/HTMLImportManifest.rs b/src/bundler/HTMLImportManifest.rs index 18716fb9a96..21b1df4849b 100644 --- a/src/bundler/HTMLImportManifest.rs +++ b/src/bundler/HTMLImportManifest.rs @@ -51,8 +51,6 @@ use crate::options::{Loader, OutputKind}; use crate::options_impl::LoaderExt as _; use crate::{BundleV2, Chunk, LinkerGraph}; -// TODO(port): lifetime — LIFETIMES.tsv has no rows for this file; classified as -// BORROW_PARAM (transient formatter struct passed by value). #[derive(Clone, Copy)] pub struct HTMLImportManifest<'a> { pub index: u32, diff --git a/src/bundler/HTMLScanner.rs b/src/bundler/HTMLScanner.rs index 9f14e7a16a6..7d8b17e1e54 100644 --- a/src/bundler/HTMLScanner.rs +++ b/src/bundler/HTMLScanner.rs @@ -14,8 +14,6 @@ use bun_sys as sys; bun_core::declare_scope!(HTMLScanner, hidden); -// TODO(port): lifetime — `log`/`source` are borrowed for the scanner's lifetime -// (LIFETIMES.tsv had no row for this file; classified locally as BORROW_PARAM). pub(crate) struct HTMLScanner<'a> { // arena field dropped — global mimalloc (see PORTING.md §Allocators). pub import_records: Vec, // Zig: ImportRecord.List diff --git a/src/bundler/LinkerContext.rs b/src/bundler/LinkerContext.rs index 2083b9665a2..dc5971ab2a5 100644 --- a/src/bundler/LinkerContext.rs +++ b/src/bundler/LinkerContext.rs @@ -153,7 +153,6 @@ pub use crate::linker_context::prepare_css_asts_for_chunk::{ pub use crate::linker_context::rename_symbols_in_chunk::rename_symbols_in_chunk; pub use crate::linker_context::write_output_files_to_disk::write_output_files_to_disk; -// TODO(port): DeferredBatchTask, ParseTask re-exports — Zig re-exports from bundle_v2 pub use crate::DeferredBatchTask::DeferredBatchTask; pub use crate::ParseTask; @@ -440,12 +439,6 @@ use crate::bundled_ast::Flags as AstFlags; use crate::generic_path_with_pretty_initialized; type DeclaredSymbolList = bun_ast::DeclaredSymbolList; -// TODO(port): method bodies depend on `LinkerGraph` SoA accessors -// (`graph.files.items_*()`, `graph.ast.items_*()`, `graph.meta.items_*()`), -// `crate::thread_pool::Worker`, `generic_path_with_pretty_initialized`, and the gated -// `linker_context/` submodules. The struct + LinkerOptions + SourceMapData -// above are real; this impl block un-gates with `LinkerGraph.rs`. - impl<'a> LinkerContext<'a> { pub fn arena(&self) -> &Bump { // TODO(port): bundler is an AST crate; LinkerGraph owns the arena @@ -1778,12 +1771,6 @@ pub(crate) fn crash_guard_for_part_range( bun_crash_handler::scoped_action(bundle_generate_chunk_action(c, chunk, part_range)) } -// TODO(port): scan/tree-shake/link method bodies. These reach into -// `LinkerGraph` SoA fields (`graph.files`, `graph.meta`, `graph.ast`), the -// gated `linker_context/scanImportsAndExports.rs`, `bun_resolve_builtins`, -// and `css::css_modules`. The bodies are real ports of `LinkerContext.zig` -// and un-gate together with `LinkerGraph.rs`. - impl<'a> LinkerContext<'a> { pub fn generate_isolated_hash(&mut self, chunk: &Chunk, arena: &Bump) -> u64 { let _trace = bun::perf::trace("Bundler.generateIsolatedHash"); diff --git a/src/bundler/OutputFile.rs b/src/bundler/OutputFile.rs index 784d7d7a280..c3a1d8fefb0 100644 --- a/src/bundler/OutputFile.rs +++ b/src/bundler/OutputFile.rs @@ -44,9 +44,7 @@ pub struct OutputFile { } impl OutputFile { - // TODO(port): Zig `zero_value` is a const struct literal; Rust can't make this a - // true `const` because `Box`/`fs::Path` aren't const-constructible. Exposed as a - // plain fn so call sites read `OutputFile::zero_value()`. + // Not a `const` because `Box`/`fs::Path` aren't const-constructible. pub fn zero_value() -> OutputFile { OutputFile { loader: Loader::File, @@ -341,7 +339,6 @@ impl OutputFile { } } - // TODO(port): Zig took `std.fs.File`; std::fs is banned. Accepting a raw `Fd`. pub fn init_file(file: Fd, pathname: &'static [u8], size: usize) -> OutputFile { OutputFile { loader: Loader::File, @@ -352,7 +349,6 @@ impl OutputFile { } } - // TODO(port): Zig took `std.fs.Dir`; using `Fd` for the dir handle. pub fn init_file_with_dir( file: Fd, pathname: &'static [u8], @@ -376,7 +372,6 @@ pub enum OptionsData { data: Box<[u8]>, }, File { - // TODO(port): Zig used `std.fs.File` / `std.fs.Dir`; mapped to `Fd`. file: Fd, size: usize, dir: Fd, diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index fd55fd00b8f..8795ba98ed5 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -544,7 +544,6 @@ pub mod parse_worker { // extra match matters (it shouldn't — called once). let parse_task = ParseTask { - // TODO(port): Zig used `undefined` for ctx; using None. ctx: None, path: Fs::Path::init_with_namespace(b"runtime", b"bun:runtime"), side_effects: bun_ast::SideEffects::NoSideEffectsPureData, diff --git a/src/bundler/defines.rs b/src/bundler/defines.rs index 9d06e128995..125ec1ae115 100644 --- a/src/bundler/defines.rs +++ b/src/bundler/defines.rs @@ -64,7 +64,6 @@ fn defines_path() -> FsPath<'static> { } // Zig: `pub const Data = DefineData;` inside `Define` -// TODO(port): inherent associated type aliases are unstable; expose as module-level alias. pub type Data = DefineData; // ══════════════════════════════════════════════════════════════════════════ diff --git a/src/bundler/linker_context/computeCrossChunkDependencies.rs b/src/bundler/linker_context/computeCrossChunkDependencies.rs index 92507d00716..5139e28de46 100644 --- a/src/bundler/linker_context/computeCrossChunkDependencies.rs +++ b/src/bundler/linker_context/computeCrossChunkDependencies.rs @@ -325,8 +325,6 @@ fn compute_cross_chunk_dependencies_with_chunk_metas( chunks: &mut [Chunk], chunk_metas: &mut [ChunkMeta], ) -> Result<(), bun_alloc::AllocError> { - // TODO(port): narrow error set - // Mark imported symbols as exported in the chunk from which they are declared // PORT NOTE: reshaped for borrowck — Zig zips (chunks, chunk_metas, 0..) and also indexes // chunk_metas[other_chunk_index] / chunks[other_chunk_index] inside the loop body. We diff --git a/src/bundler/linker_context/convertStmtsForChunkForDevServer.rs b/src/bundler/linker_context/convertStmtsForChunkForDevServer.rs index 2b1cf2e540c..ae25173e490 100644 --- a/src/bundler/linker_context/convertStmtsForChunkForDevServer.rs +++ b/src/bundler/linker_context/convertStmtsForChunkForDevServer.rs @@ -49,7 +49,6 @@ pub fn convert_stmts_for_chunk_for_dev_server<'bump>( bump: &'bump Bump, ast: &mut JSAst<'_>, ) -> Result<(), AllocError> { - // TODO(port): narrow error set let hmr_api_ref = ast.wrapper_ref; let hmr_api_id = Expr::init_identifier(hmr_api_ref, Loc::EMPTY); let mut esm_decls: bun_alloc::ArenaVec<'bump, ArrayBinding> = bun_alloc::ArenaVec::new_in(bump); diff --git a/src/bundler/linker_context/generateChunksInParallel.rs b/src/bundler/linker_context/generateChunksInParallel.rs index 5d85ceecfdd..6a5954e67de 100644 --- a/src/bundler/linker_context/generateChunksInParallel.rs +++ b/src/bundler/linker_context/generateChunksInParallel.rs @@ -74,7 +74,6 @@ pub fn generate_chunks_in_parallel( c: unsafe { bun_ptr::ParentRef::from_raw_mut(std::ptr::from_mut::(c)) }, chunks: bun_ptr::BackRef::new_mut(chunks), }; - // TODO(port): worker_pool.eachPtr signature — arena param dropped; Rust impl is infallible. // SAFETY: `parse_graph` is the `BundleV2.graph` backref (valid for the // link step); `pool` is the arena-allocated bundler ThreadPool. c.worker_pool() @@ -820,7 +819,6 @@ pub fn generate_chunks_in_parallel( buf.extend_from_slice(b); buf.push(b'\n'); - // TODO(port): Zig frees old code_result.buffer via allocatorForSize; relying on Drop here. code_result.buffer = buf.into_boxed_slice(); } @@ -864,7 +862,6 @@ pub fn generate_chunks_in_parallel( let _ = bun_base64::encode(&mut buf[old_len..], &output_source_map); buf.push(b'\n'); - // TODO(port): Zig frees old code_result.buffer via allocatorForSize; relying on Drop here. code_result.buffer = buf.into_boxed_slice(); drop(output_source_map); } @@ -1079,7 +1076,6 @@ pub fn generate_chunks_in_parallel( output_files.insert_for_chunk(options::OutputFile::init(options::OutputFileInit { data: options::OutputFileData::Buffer { data: code_result.buffer, - // TODO(port): Zig stores Chunk.IntermediateOutput.allocatorForSize(len) for matched dealloc. }, hash: chunk.template.placeholder.hash, loader: chunk.content.loader(), diff --git a/src/bundler/linker_context/generateCodeForFileInChunkJS.rs b/src/bundler/linker_context/generateCodeForFileInChunkJS.rs index c84642f660b..72dcd1714bb 100644 --- a/src/bundler/linker_context/generateCodeForFileInChunkJS.rs +++ b/src/bundler/linker_context/generateCodeForFileInChunkJS.rs @@ -304,7 +304,6 @@ pub fn generate_code_for_file_in_chunk_js<'r, 'src>( flags.wrap, &ast, ) { - // TODO(port): bun.handleErrorReturnTrace — no Rust equivalent return PrintResult::Err(err); } diff --git a/src/bundler/linker_context/generateCompileResultForHtmlChunk.rs b/src/bundler/linker_context/generateCompileResultForHtmlChunk.rs index 0e1b662cc09..e8fb88000af 100644 --- a/src/bundler/linker_context/generateCompileResultForHtmlChunk.rs +++ b/src/bundler/linker_context/generateCompileResultForHtmlChunk.rs @@ -489,14 +489,12 @@ fn generate_compile_result_for_html_chunk_impl<'a>( html_loader.added_body_script = true; } } - // value is ignored. fail loud if hit in debug - // TODO(port): Zig returned `undefined` in debug to fail loud; Rust has no direct equivalent. + // value is ignored break 'brk 0; } }; CompileResult::Html { - // TODO(port): Zig returned `output.items` (slice into the ArrayList). Here we hand over the Vec. code: html_loader.output.into_boxed_slice(), source_index, script_injection_offset, diff --git a/src/bundler/linker_context/generateCompileResultForJSChunk.rs b/src/bundler/linker_context/generateCompileResultForJSChunk.rs index 81d0301ef48..f33d4844344 100644 --- a/src/bundler/linker_context/generateCompileResultForJSChunk.rs +++ b/src/bundler/linker_context/generateCompileResultForJSChunk.rs @@ -52,7 +52,7 @@ pub unsafe fn generate_compile_result_for_js_chunk(task: *mut ThreadPoolLib::Tas [part_range.part_range.source_index.get() as usize] .path; if bun_core::debug_flags::has_print_breakpoint(&path.pretty, &path.text) { - // TODO(port): @breakpoint() — no stable Rust equivalent; left as no-op (see resolver/lib.rs:4573) + // @breakpoint() in Zig — no stable Rust equivalent; left as no-op } } diff --git a/src/bundler/linker_context/writeOutputFilesToDisk.rs b/src/bundler/linker_context/writeOutputFilesToDisk.rs index 7e14e735c53..75aefd5033f 100644 --- a/src/bundler/linker_context/writeOutputFilesToDisk.rs +++ b/src/bundler/linker_context/writeOutputFilesToDisk.rs @@ -20,7 +20,6 @@ use crate::output_file::{ }; use crate::{BundleV2, Chunk, cheap_prefix_normalizer}; -// TODO(port): bun_sys::{write_file_with_path_buffer, WriteFileArgs, ...} arrive from move-in. use bun_sys::{ FdDirExt, PathOrFileDescriptor, WriteFileArgs, WriteFileData, WriteFileEncoding, write_file_with_path_buffer, @@ -38,8 +37,6 @@ pub fn write_output_files_to_disk( ) -> Result<(), Error> { let _trace = bun_core::perf::trace("Bundler.writeOutputFilesToDisk"); - // TODO(port): Zig used `std.fs.cwd().makeOpenPath`. Replace with bun_sys - // directory API once available; using a placeholder wrapper here. let root_dir = match bun_sys::Dir::cwd().make_open_path(root_path, Default::default()) { Ok(dir) => dir, Err(e) => { diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 6490c4c6204..fa53adadea3 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -431,8 +431,6 @@ pub trait LoaderExt: Copy { // cross-crate callers (bun_jsc / bun_runtime) resolve them without a trait // import. - // TODO(port): `obj: anytype` — Zig duck-typed `.get(ext) -> Option`. - // Monomorphized to the only concrete map type callers pass (`LoaderHashTable`). fn for_file_name(filename: &[u8], obj: &LoaderHashTable) -> Option { let ext = bun_paths::extension(filename); if ext.is_empty() || (ext.len() == 1 && ext[0] == b'.') { @@ -2533,7 +2531,6 @@ pub enum PlaceholderField { // Shared body for PathTemplate::needs / PathTemplateConst::needs (D064). #[inline] pub(crate) fn path_template_needs(data: &[u8], field: PlaceholderField) -> bool { - // TODO(port): Zig used comptime @tagName concatenation; here we match explicitly. let needle: &[u8] = match field { PlaceholderField::Dir => b"[dir]", PlaceholderField::Name => b"[name]", @@ -2729,8 +2726,7 @@ pub static PLACEHOLDER_MAP: phf::Map<&'static [u8], PlaceholderField> = phf::phf b"target" => PlaceholderField::Target, }; -// TODO(port): Zig PathTemplate constants used &'static str fields; Rust struct uses Box<[u8]>. -// PathTemplateConst is a const-friendly mirror; convert to PathTemplate at use sites. +// PathTemplateConst is a const-friendly mirror of PathTemplate; convert to PathTemplate at use sites. #[derive(Debug, Clone, Copy)] pub struct PathTemplateConst { pub data: &'static [u8], diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index 4b23d2097f7..219d05f478a 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -1773,7 +1773,6 @@ impl<'a> Transpiler<'a> { source_contents_backing: source_backing, }, js_ast::Result::Cached => ParseResult { - // TODO(port): Zig used `undefined` for ast here. ast: bun_ast::Ast::empty_in(arena), runtime_transpiler_cache: rtc_ptr, source: source.clone(), @@ -1785,7 +1784,6 @@ impl<'a> Transpiler<'a> { source_contents_backing: source_backing, }, js_ast::Result::AlreadyBundled(already_bundled) => ParseResult { - // TODO(port): Zig used `undefined` for ast here. ast: bun_ast::Ast::empty_in(arena), already_bundled: match already_bundled { js_ast::AlreadyBundled::Bun => AlreadyBundled::SourceCode, diff --git a/src/clap/args.rs b/src/clap/args.rs index a99fd46e0df..c35b2147df1 100644 --- a/src/clap/args.rs +++ b/src/clap/args.rs @@ -72,8 +72,6 @@ pub struct OsIterator { } impl OsIterator { - // TODO(port): Zig aliased `process.ArgIterator.InitError`; no std::process here. - pub fn init() -> OsIterator { let mut res = OsIterator { exe_arg: None, diff --git a/src/clap/lib.rs b/src/clap/lib.rs index 6c8875d3b3f..8c4d38d22d4 100644 --- a/src/clap/lib.rs +++ b/src/clap/lib.rs @@ -367,9 +367,6 @@ impl Diagnostic { }; let name = bstr::BStr::new(name); - // TODO(port): bun_core::err! — `from_name` is a tier-0 stub returning a - // sentinel, so these equality checks all collapse. Restore once the interning - // table lands; meanwhile the `else` arm covers all cases. if err == bun_core::err!("DoesntTakeValue") { bun_core::pretty_errorln!( "error: The argument '{}' does not take a value.", @@ -597,8 +594,6 @@ where let max_spacing: usize = 'blk: { let mut res: usize = 0; for param in params { - // TODO(port): std.io.countingWriter(io.null_writer) — using a local - // CountingWriter that discards output and counts bytes. let mut cs = CountingWriter::null(); print_param(&mut cs, param, context, value_text)?; if res < cs.count { @@ -616,7 +611,6 @@ where let ht = help_text(context, param).map_err(Into::into)?; // only print flag if description is defined if !ht.is_empty() { - // TODO(port): std.io.countingWriter(stream) — wrapping `stream` let mut cs = CountingWriter::wrap(stream); write!(cs.inner(), "\t")?; print_param(&mut cs, param, context, value_text)?; @@ -908,7 +902,6 @@ where E: Into, { // TODO(port): narrow error set - // TODO(port): std.io.countingWriter(stream) let mut cos = CountingWriter::wrap(stream); for param in params { let Some(name) = param.names.short else { diff --git a/src/clap/streaming.rs b/src/clap/streaming.rs index 607534d7ce0..320858f1c5e 100644 --- a/src/clap/streaming.rs +++ b/src/clap/streaming.rs @@ -6,7 +6,6 @@ use crate as clap; use crate::args::ArgIter; // Disabled because not all CLI arguments are parsed with Clap. -// TODO(port): Zig `pub var` — using AtomicBool for safe mutable global. pub static WARN_ON_UNRECOGNIZED_FLAG: AtomicBool = AtomicBool::new(false); /// The result returned from StreamingClap.next diff --git a/src/collections/bit_set.rs b/src/collections/bit_set.rs index bc754ba4c18..fb2015c0a2f 100644 --- a/src/collections/bit_set.rs +++ b/src/collections/bit_set.rs @@ -146,14 +146,6 @@ impl IntegerBitSet { /// The number of items in this bit set pub const BIT_LENGTH: usize = SIZE; - /// The integer type used to represent a mask in this bit set - // TODO(port): Zig: `pub const MaskInt = std.meta.Int(.unsigned, size);` - // type MaskInt = usize (inherent assoc → inline usize) - - /// The integer type used to shift a mask in this bit set - // TODO(port): Zig: `pub const ShiftInt = std.math.Log2Int(MaskInt);` - // type ShiftInt = u32 (inherent assoc → inline u32) - const FULL_MASK: usize = if SIZE as u32 >= usize::BITS { // SIZE > usize::BITS is a caller error (use ArrayBitSet); saturating // here avoids a const-eval shift-overflow at monomorphization time so @@ -454,9 +446,6 @@ pub const fn num_masks_for(bit_length: usize) -> usize { /// // TODO(port): Zig is generic over `MaskIntType`; every in-tree caller uses // `usize`. Dropped the type parameter. Phase B can re-generify if needed. -// TODO(port): `[usize; NUM_MASKS]` requires -// `#![feature(generic_const_exprs)]`. Phase B may instead take NUM_MASKS as a -// second const generic and assert `NUM_MASKS == num_masks_for(SIZE)`. #[repr(C)] #[derive(Clone, Copy)] pub struct ArrayBitSet { @@ -1743,9 +1732,6 @@ impl DynamicBitSet { // ───────────────────────────── IteratorOptions ───────────────────────────── /// Options for configuring an iterator over a bit set -// TODO(port): Zig passes a `comptime options: IteratorOptions` struct. Stable -// Rust adt_const_params is unstable; split into two const-generic enum params -// (`KIND`, `DIRECTION`) at every callsite. #[derive(Clone, Copy, Default)] pub struct IteratorOptions { /// determines which bits should be visited diff --git a/src/collections/comptime_string_map.rs b/src/collections/comptime_string_map.rs index 35bd2b40005..59db5df0222 100644 --- a/src/collections/comptime_string_map.rs +++ b/src/collections/comptime_string_map.rs @@ -18,7 +18,6 @@ // prefer `phf::phf_map!` directly when they only need `.get()`/`.has()`. This struct exists // for the call sites that need `get_with_eql` / `get_any_case` / `index_of` / `get_key`. -// TODO(port): `strings` arrives in bun_core via move-in (was bun_core::strings — same-tier cycle). use bun_core::strings; #[derive(Copy, Clone)] diff --git a/src/crash_handler/handle_oom.rs b/src/crash_handler/handle_oom.rs index 406d975831f..4b16c972bdd 100644 --- a/src/crash_handler/handle_oom.rs +++ b/src/crash_handler/handle_oom.rs @@ -9,8 +9,6 @@ use bun_core::Error; // the `HandleOom` trait impls below — the `AllocError` impls ARE the // "OOM-only" arm (Output = T / Output = !), and the `bun_core::Error` impls // ARE the "other errors possible" arm (Output = Result / Output = E). -// -// TODO(port): @typeInfo reflection — no direct Rust equivalent; encoded as trait impls. /// If `error_union_or_set` is `error.OutOfMemory`, calls `bun.outOfMemory`. Otherwise: /// diff --git a/src/crash_handler/lib.rs b/src/crash_handler/lib.rs index 8563ff1b394..03ea0070727 100644 --- a/src/crash_handler/lib.rs +++ b/src/crash_handler/lib.rs @@ -402,7 +402,7 @@ pub mod debug { // ────────────────────────────────────────────────────────────────────────── // Byte-writer trait — D101: deduped to canonical `bun_io::Write`. -// The local stub (TODO(port)) predated `bun_io` compiling; it carried a +// The local stub predated `bun_io` compiling; it carried a // `core::fmt::Write` supertrait so `write!(…)` returned `fmt::Result`. The // canonical trait instead provides its own `write_fmt` returning // `Result<(), bun_core::Error>`, so `write!` on `impl Write` now yields the @@ -1024,7 +1024,6 @@ mod draft { } else { #[cfg(windows)] { - // TODO(port): bun_sys::windows::GetThreadDescription / PWSTR / HRESULT_CODE { let mut name: bun_sys::windows::PWSTR = core::ptr::null_mut(); // SAFETY: GetCurrentThread/GetThreadDescription are valid Win32 calls @@ -1574,7 +1573,6 @@ mod draft { "x64" }; - // TODO(port): std.fmt.comptimePrint — use const_format::formatcp! const METADATA_VERSION_LINE: &str = const_format::formatcp!( "Bun {}v{} {} {}{}\n", if cfg!(debug_assertions) { @@ -2171,7 +2169,6 @@ mod draft { } #[cfg(windows)] { - // TODO(port): std.zig.system.windows.detectRuntimeVersion() write!( writer, "Windows v{}\n", @@ -2212,7 +2209,6 @@ mod draft { } } - // TODO(port): bun_analytics::Features::formatter { write!(writer, "\n{}", bun_analytics::features::formatter()).map_err(fmt_err)?; } @@ -2309,7 +2305,6 @@ mod draft { struct Platform; impl Platform { - // TODO(port): Zig builds this via @tagName(os) ++ "_" ++ @tagName(arch) ++ baseline. // Rust cannot concat ident names at const time without a proc-macro; spell out the cfg matrix. const CURRENT: u8 = { // Android folds into the Linux variants — Zig's `@tagName(Environment.os)` @@ -2785,8 +2780,6 @@ mod draft { } #[cfg(windows)] { - // TODO(port): bun_sys::windows::PROCESS_INFORMATION / STARTUPINFOW / CreateProcessW - // TODO(port): bun_core::w! / strings::convert_utf8_to_utf16_in_buffer use bun_sys::windows; let mut process: windows::PROCESS_INFORMATION = bun_core::ffi::zeroed(); let mut startup_info = windows::STARTUPINFOW { @@ -3338,9 +3331,6 @@ mod draft { // `StoredTrace::capture()` instead — this crate no longer owns the type. pub use bun_core::StoredTrace; - // TODO(port): move to *_jsc — `pub const js_bindings = @import("../runtime/api/crash_handler_jsc.zig").js_bindings;` - // Per PORTING.md this *_jsc alias is deleted; the bindings live as an extension trait in bun_runtime. - /// For large codebases such as bun.bake.DevServer, it may be helpful /// to dump a large amount of state to a file to aid debugging a crash. /// diff --git a/src/css/css_modules.rs b/src/css/css_modules.rs index 64bcf8eb737..1385fa555ea 100644 --- a/src/css/css_modules.rs +++ b/src/css/css_modules.rs @@ -413,7 +413,6 @@ pub enum Segment { } /// A map of exported names to values. -// TODO(port): std.StringArrayHashMapUnmanaged → bun_collections::ArrayHashMap; key is arena &[u8] pub type CssModuleExports<'a> = ArrayHashMap<&'a [u8], CssModuleExport<'a>>; /// A map of placeholders to references. diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index 18b0f031a65..2f1e72e2dd7 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -331,10 +331,6 @@ pub trait DefineShorthand: Sized { pub mod enum_property_util { use super::*; - // TODO(port): `as_str` / `parse` / `to_css` here used Zig - // `bun.ComptimeEnumMap` + `@tagName`. In Rust this is - // `strum::IntoStaticStr` + `strum::EnumString` (case-insensitive). Callers - // should `#[derive(EnumProperty)]` and use the trait below. pub fn as_str + Copy>(this: &T) -> &'static str { (*this).into() } @@ -4559,8 +4555,6 @@ pub struct Tokenizer<'a> { pub source_map_url: Option<&'a [u8]>, pub current_line_start_position: usize, pub current_line_number: u32, - // TODO(port): AST crate — keep arena. Zig threaded `Allocator`; in Rust - // this is `&'a Bump`. pub arena: &'a Bump, var_or_env_functions: SeenStatus, pub current: Token, @@ -5413,8 +5407,6 @@ impl<'a> Tokenizer<'a> { pub fn consume_escape_and_write(&mut self, bytes: &mut CopyOnWriteStr<'a>) { let val = self.consume_escape(); let mut utf8bytes = [0u8; 4]; - // TODO(port): Zig used std.unicode.utf8Encode; route through char's - // UTF-8 encoder (val is guaranteed a valid scalar by consume_escape). let c = char::from_u32(val).unwrap_or('\u{FFFD}'); let len = c.encode_utf8(&mut utf8bytes).len(); bytes.append(self.arena, &utf8bytes[..len]); @@ -5717,9 +5709,6 @@ pub enum TokenKind { impl TokenKind { pub fn to_string(self) -> &'static str { - // TODO(port): Zig switch had stale variant names (close_bracket, hash, - // string) and pattern-matched `delim` payload — which TokenKind has - // none of. Preserved best-effort. match self { TokenKind::AtKeyword => "@-keyword", TokenKind::BadString => "bad string token", diff --git a/src/css/dependencies.rs b/src/css/dependencies.rs index 55690f09a00..5ebca15c04a 100644 --- a/src/css/dependencies.rs +++ b/src/css/dependencies.rs @@ -156,8 +156,6 @@ impl UrlDependency { filename: &[u8], import_records: &[bun_ast::ImportRecord], ) -> UrlDependency { - // TODO(port): `bun_paths::fs::Path::pretty` is currently `&'static str`; - // should become `&[u8]` per PORTING.md §Strings. Until then, `.as_bytes()`. let theurl: &[u8] = import_records[url.import_record_idx as usize].path.pretty; let placeholder = crate::css_modules::hash( bump, diff --git a/src/css/generics.rs b/src/css/generics.rs index 080a7cd4376..74f7a4c2760 100644 --- a/src/css/generics.rs +++ b/src/css/generics.rs @@ -63,9 +63,6 @@ pub use bun_css_derive::DeepClone; #[inline] pub fn implement_deep_clone<'bump, T: DeepClone<'bump>>(this: &T, bump: &'bump Arena) -> T { - // TODO(port): Zig `implementDeepClone` is comptime field/variant reflection. - // In Rust this is the body of `#[derive(DeepClone)]`; the free fn just - // forwards to the trait so existing callers keep working. this.deep_clone(bump) } @@ -202,8 +199,6 @@ pub use bun_css_derive::CssEql; #[inline] pub fn implement_eql(this: &T, other: &T) -> bool { - // TODO(port): Zig `implementEql` is comptime field/variant reflection == - // the body of `#[derive(CssEql)]`. Free fn forwards to trait. this.eql(other) } @@ -893,8 +888,6 @@ pub use bun_css_derive::CssHash; #[inline] pub fn implement_hash(this: &T, hasher: &mut Wyhash) { - // TODO(port): Zig `implementHash` is comptime field/variant reflection == - // the body of `#[derive(CssHash)]`. Free fn forwards to trait. this.hash(hasher) } diff --git a/src/css/properties/align.rs b/src/css/properties/align.rs index b060d038b3f..f812330a582 100644 --- a/src/css/properties/align.rs +++ b/src/css/properties/align.rs @@ -778,9 +778,7 @@ impl PlaceSelf { // ────────────────────────────────────────────────────────────────────────────── /// A [``](https://www.w3.org/TR/css-align-3/#typedef-self-position) value. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -// TODO(port): css.DefineEnumProperty — derive-based eql/hash/parse/toCss/deepClone for plain enums. -#[derive(css::DefineEnumProperty)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, css::DefineEnumProperty)] pub enum SelfPosition { /// Item is centered within the container. #[css(name = "center")] @@ -886,9 +884,7 @@ impl PlaceContent { // ────────────────────────────────────────────────────────────────────────────── /// A [``](https://www.w3.org/TR/css-align-3/#typedef-content-distribution) value. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -// TODO(port): css.DefineEnumProperty -#[derive(css::DefineEnumProperty)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, css::DefineEnumProperty)] pub enum ContentDistribution { /// Items are spaced evenly, with the first and last items against the edge of the container. #[css(name = "space-between")] @@ -905,9 +901,7 @@ pub enum ContentDistribution { } /// An [``](https://www.w3.org/TR/css-align-3/#typedef-overflow-position) value. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -// TODO(port): css.DefineEnumProperty -#[derive(css::DefineEnumProperty)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, css::DefineEnumProperty)] pub enum OverflowPosition { /// If the size of the alignment subject overflows the alignment container, /// the alignment subject is instead aligned as if the alignment mode were start. @@ -920,9 +914,7 @@ pub enum OverflowPosition { } /// A [``](https://www.w3.org/TR/css-align-3/#typedef-content-position) value. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -// TODO(port): css.DefineEnumProperty -#[derive(css::DefineEnumProperty)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, css::DefineEnumProperty)] pub enum ContentPosition { /// Content is centered within the container. #[css(name = "center")] diff --git a/src/css/properties/border.rs b/src/css/properties/border.rs index 2a16afa7951..f6aa3be4fa1 100644 --- a/src/css/properties/border.rs +++ b/src/css/properties/border.rs @@ -186,7 +186,7 @@ where // ────────────────────────────────────────────────────────────────────────── /// A [``](https://drafts.csswg.org/css-backgrounds/#typedef-line-style) value, used in the `border-style` property. -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, css::DefineEnumProperty)] // TODO(port): provides eql/hash/parse/to_css/deep_clone +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, css::DefineEnumProperty)] pub enum LineStyle { /// No border. #[default] diff --git a/src/css/properties/border_image.rs b/src/css/properties/border_image.rs index f6f76f85fbc..d79fef7960f 100644 --- a/src/css/properties/border_image.rs +++ b/src/css/properties/border_image.rs @@ -564,12 +564,7 @@ impl BorderImageHandler { unparsed.deep_clone(arena) }; - // TODO(port): re-enable once `PropertyHandlerContext::add_unparsed_fallbacks` - // un-gates (blocked on `SupportsCondition::eql` in context.rs). - - // blocked_on: PropertyHandlerContext::add_unparsed_fallbacks (gated in context.rs) context.add_unparsed_fallbacks(arena, &mut unparsed_clone); - let _ = &mut unparsed_clone; self.flushed_properties.insert( BorderImageProperty::try_from_property_id(unparsed_clone.property_id.tag()) .unwrap(), diff --git a/src/css/properties/box_shadow.rs b/src/css/properties/box_shadow.rs index f2bdad7ee88..84ba72d9f34 100644 --- a/src/css/properties/box_shadow.rs +++ b/src/css/properties/box_shadow.rs @@ -229,11 +229,7 @@ impl BoxShadowHandler { self.flush(dest, context); let mut unparsed = unp.deep_clone(arena); - // TODO(port): re-enable once `PropertyHandlerContext::add_unparsed_fallbacks` - // un-gates (blocked on `SupportsCondition::eql` in context.rs). - context.add_unparsed_fallbacks(arena, &mut unparsed); - let _ = &mut unparsed; dest.push(Property::Unparsed(unparsed)); self.flushed = true; } else { diff --git a/src/css/properties/flex.rs b/src/css/properties/flex.rs index 3f7a4408a13..2470c4ab847 100644 --- a/src/css/properties/flex.rs +++ b/src/css/properties/flex.rs @@ -14,7 +14,6 @@ use css::prefixes::is_flex_2009; /// A value for the [flex-direction](https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#propdef-flex-direction) property. /// A value for the [flex-direction](https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#propdef-flex-direction) property. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash, css::DefineEnumProperty)] -// TODO(port): css::DefineEnumProperty derive provides parse/to_css/eql/hash/deep_clone over kebab-case variant names pub enum FlexDirection { /// Flex items are laid out in a row. #[default] diff --git a/src/css/properties/font.rs b/src/css/properties/font.rs index 125b7ccead1..e3202c4d6b0 100644 --- a/src/css/properties/font.rs +++ b/src/css/properties/font.rs @@ -340,9 +340,6 @@ pub enum FontFamily { FamilyName(*const [u8]), } -// TODO(port): Zig defined `pub fn HashMap(comptime V: type) type` wrapping std.ArrayHashMapUnmanaged -// with a custom Wyhash hasher over the family-name bytes. Module-level alias (inherent assoc types are nightly-only). -// blocked_on: ArrayHashMap key trait bounds for FontFamily pub(crate) type FontFamilyHashMap = bun_collections::ArrayHashMap; impl FontFamily { @@ -1170,7 +1167,6 @@ fn compatible_font_family( // perform the inserts using the captured index. if let Some(i) = families.slice_const().iter().position(is_system_ui) { for (j, name) in DEFAULT_SYSTEM_FONTS.iter().enumerate() { - // TODO(port): families.insert(arena, idx, val) — Vec::insert with arena families.insert( i + j + 1, FontFamily::FamilyName(std::ptr::from_ref::<[u8]>(*name)), diff --git a/src/css/selectors/parser.rs b/src/css/selectors/parser.rs index 7a52ff92866..49bffbe820d 100644 --- a/src/css/selectors/parser.rs +++ b/src/css/selectors/parser.rs @@ -737,8 +737,6 @@ fn parse_compound_selector( if parse_type_selector::(parser, input, *state, builder).is_ok() { // Note: Zig `.asValue()` here means "if Ok"; the bool result is unused. - // TODO(port): the Zig only sets `empty = false` on Ok(true|false) — but - // `asValue()` returns Some on .result regardless of bool value, so this matches. empty = false; } diff --git a/src/css/selectors/selector.rs b/src/css/selectors/selector.rs index 969e5909a6c..1f5068221a9 100644 --- a/src/css/selectors/selector.rs +++ b/src/css/selectors/selector.rs @@ -25,7 +25,6 @@ pub use parser::SelectorList; /// Zig-shaped namespace (`selector.impl.Selectors.SelectorImpl.*` type /// aliases) kept for diff parity with `selector.zig`. pub use super::impl_; -// TODO(port): `impl` is a Rust keyword; using raw identifier `r#impl` for module name parity. pub mod r#impl { use super::*; @@ -1052,8 +1051,6 @@ pub mod serialize { d.write_str(val) } - // TODO(port): Zig `Helpers.pseudo` used comptime `@field` to look up - // `dest.pseudo_classes.`. Expanded per call site via macro. macro_rules! pseudo { ($d:expr, $field:ident, $s:literal) => {{ let class = if let Some(pseudo_classes) = &$d.pseudo_classes { diff --git a/src/css/values/calc.rs b/src/css/values/calc.rs index 63ae6c475c2..3c15de0172e 100644 --- a/src/css/values/calc.rs +++ b/src/css/values/calc.rs @@ -885,7 +885,6 @@ impl Calc { None } }; - // TODO(port): Zig threaded `&closure` here; Rust captures via fn-pointer wrapper. Calc::::parse_atan2_args(input, ctx, parse_ident_fn) } @@ -926,7 +925,6 @@ impl Calc { None } }; - // TODO(port): Zig threaded `&closure` here; same reshape as parse_trig/parse_atan2. let v: Calc = Calc::::parse_sum(input, ctx, parse_ident_fn)?; let val = match v { Calc::Number(n) => n, diff --git a/src/css/values/percentage.rs b/src/css/values/percentage.rs index 6011f1c2afb..9bcaa8eac5d 100644 --- a/src/css/values/percentage.rs +++ b/src/css/values/percentage.rs @@ -43,7 +43,6 @@ impl Percentage { }; if self.v != 0.0 && self.v.abs() < 0.01 { - // TODO(port): fixed-size stack writer — Zig used std.Io.Writer.fixed over [32]u8. let mut backing = [0u8; 32]; let mut fbs = css::serializer::FixedBufWriter::new_mut(&mut backing); if percent.to_css_generic(&mut fbs).is_err() { @@ -123,10 +122,6 @@ impl Percentage { } } -// TODO(port): `needsDeepclone` was a comptime type-switch (Angle→false, LengthValue→false, -// else @compileError). In Rust, `D: Clone` makes this distinction irrelevant for Copy types -// (clone is memcpy). If a deep-clone protocol is required for non-Copy D, add a trait bound. - pub enum DimensionPercentage { Dimension(D), Percentage(Percentage), @@ -232,7 +227,6 @@ where where D: protocol::Zero, { - // TODO(port): Zig special-cased D == f32 → 0.0. Handle via trait impl on f32. Self::Dimension(D::zero()) } @@ -241,7 +235,6 @@ where D: protocol::Zero, { match self { - // TODO(port): Zig special-cased D == f32 → d == 0.0. Handle via trait impl on f32. Self::Dimension(d) => d.is_zero(), Self::Percentage(p) => p.is_zero(), _ => false, @@ -252,7 +245,6 @@ where where D: protocol::MulF32, { - // TODO(port): Zig special-cased D == f32 → lhs * rhs. Handle via trait impl on f32. lhs.mul_f32(rhs) } diff --git a/src/css/values/time.rs b/src/css/values/time.rs index 329731e2b4d..1ba1b1a4e47 100644 --- a/src/css/values/time.rs +++ b/src/css/values/time.rs @@ -68,7 +68,6 @@ impl Time { let token = input.next()?.clone(); match &token { Token::Dimension(dim) => { - // TODO(port): Zig fn name has a typo (`ASCIII`); verify exact bun_str symbol. if bun_core::strings::eql_case_insensitive_ascii_check_length(b"s", dim.unit) { Ok(Time::Seconds(dim.num.value)) } else if bun_core::strings::eql_case_insensitive_ascii_check_length( diff --git a/src/dns/lib.rs b/src/dns/lib.rs index 07234a6e10f..227e0c6e6a1 100644 --- a/src/dns/lib.rs +++ b/src/dns/lib.rs @@ -43,7 +43,6 @@ mod sock { // duplicate the POSIX/Windows split (see dns_jsc::dns). pub use sock::{addrinfo, freeaddrinfo}; -// TODO(port): move to dns_sys / verify libc crate exposes these on all targets #[cfg(windows)] pub const AI_V4MAPPED: c_int = 2048; #[cfg(not(windows))] @@ -88,9 +87,6 @@ impl GetAddrInfo { pub fn hash(&self) -> u64 { let mut hasher = Wyhash::init(0); - // TODO(port): Zig used asBytes(&port) ++ asBytes(&options) where Options is - // packed struct(u64). Rust Options is not bit-packed; verify hash stability - // is not load-bearing across process boundaries (it isn't — used for in-memory dedupe). hasher.update(&self.port.to_ne_bytes()); hasher.update(&self.options.to_packed_bytes()); hasher.update(&self.name); @@ -304,9 +300,6 @@ impl Default for Backend { } } -// TODO(port): std.net.Address — std::net is banned. `bun_sys::net::Address` -// wraps `libc::sockaddr_storage`; `.in/.in6` views go through the typed -// `as_in4()`/`as_in6()` accessors. `.un` still casts on `as_sockaddr()`. pub type Address = bun_sys::net::Address; pub struct GetAddrInfoResult { diff --git a/src/dotenv/env_loader.rs b/src/dotenv/env_loader.rs index 8adb572802b..c6225c7d15f 100644 --- a/src/dotenv/env_loader.rs +++ b/src/dotenv/env_loader.rs @@ -541,7 +541,6 @@ impl<'a> Loader<'a> { Ok(true) } - // TODO(port): Zig `getAs(comptime T: type)` only implements `bool`; expose as concrete fn. pub fn get_as_bool(&self, key: &[u8]) -> Option { let value = self.get(key)?; if value == b"" { diff --git a/src/errno/windows_errno.rs b/src/errno/windows_errno.rs index 1f02f6ae8c0..6a3f62ac140 100644 --- a/src/errno/windows_errno.rs +++ b/src/errno/windows_errno.rs @@ -336,7 +336,6 @@ impl E { /// bun_errno::posix::*` unconditionally. Windows has no real `mode_t`/kernel /// `errno`, so this is the minimal subset higher tiers reach for. pub mod posix { - use super::SystemErrno; pub type mode_t = i32; /// Zig: `std.posix.E` — alias to the platform errno enum so cross-platform @@ -345,45 +344,6 @@ pub mod posix { /// Zig: `std.posix.S` — file-mode bits. Re-export the canonical module so /// `posix::S::IFDIR` / `posix::S::ISREG(m)` resolve identically to POSIX. pub use super::s as S; - - #[allow(dead_code)] - pub(crate) const ACCES: i32 = SystemErrno::EACCES as i32; - #[allow(dead_code)] - pub(crate) const AGAIN: i32 = SystemErrno::EAGAIN as i32; - #[allow(dead_code)] - pub(crate) const BADF: i32 = SystemErrno::EBADF as i32; - #[allow(dead_code)] - pub(crate) const BUSY: i32 = SystemErrno::EBUSY as i32; - #[allow(dead_code)] - pub(crate) const EXIST: i32 = SystemErrno::EEXIST as i32; - #[allow(dead_code)] - pub(crate) const INTR: i32 = SystemErrno::EINTR as i32; - #[allow(dead_code)] - pub(crate) const INVAL: i32 = SystemErrno::EINVAL as i32; - #[allow(dead_code)] - pub(crate) const ISDIR: i32 = SystemErrno::EISDIR as i32; - #[allow(dead_code)] - pub(crate) const MFILE: i32 = SystemErrno::EMFILE as i32; - #[allow(dead_code)] - pub(crate) const NAMETOOLONG: i32 = SystemErrno::ENAMETOOLONG as i32; - #[allow(dead_code)] - pub(crate) const NOENT: i32 = SystemErrno::ENOENT as i32; - #[allow(dead_code)] - pub(crate) const NOMEM: i32 = SystemErrno::ENOMEM as i32; - #[allow(dead_code)] - pub(crate) const NOSPC: i32 = SystemErrno::ENOSPC as i32; - #[allow(dead_code)] - pub(crate) const NOSYS: i32 = SystemErrno::ENOSYS as i32; - #[allow(dead_code)] - pub(crate) const NOTDIR: i32 = SystemErrno::ENOTDIR as i32; - #[allow(dead_code)] - pub(crate) const NOTSUP: i32 = SystemErrno::ENOTSUP as i32; - #[allow(dead_code)] - pub(crate) const PERM: i32 = SystemErrno::EPERM as i32; - #[allow(dead_code)] - pub(crate) const PIPE: i32 = SystemErrno::EPIPE as i32; - #[allow(dead_code)] - pub(crate) const XDEV: i32 = SystemErrno::EXDEV as i32; } /// Uppercase re-export so `bun_errno::S::IFDIR` compiles cross-platform. @@ -416,18 +376,8 @@ pub use bun_core::S as s; // getErrno // ────────────────────────────────────────────────────────────────────────── -// TODO(port): Zig `getErrno(rc: anytype)` dispatches on `@TypeOf(rc)` at comptime: -// - if NTSTATUS → translateNTStatusToErrno(rc) -// - otherwise → ignore rc, read Win32 GetLastError() then WSAGetLastError() -// Rust has no specialization on stable; callers must pick the right overload. - -/// `getErrno(rc)` for the NTSTATUS case. -#[allow(dead_code)] -pub(crate) fn get_errno_ntstatus(rc: NTSTATUS) -> E { - windows::translate_ntstatus_to_errno(rc) -} - -/// `getErrno(rc)` for every non-NTSTATUS case (rc is ignored, mirrors Zig). +/// `getErrno(rc)` — `rc` is ignored, mirroring Zig's non-NTSTATUS branch; +/// NTSTATUS callers use `windows::translate_ntstatus_to_errno` directly. pub fn get_errno(_rc: T) -> E { if let Some(sys) = Win32Error::get().to_system_errno() { return sys.to_e(); @@ -705,11 +655,6 @@ impl SystemErrno { bun_core::Error::from_errno(self as u16 as i32) } - // TODO(port): Zig `init(code: anytype)` is comptime type-dispatch over u16 / c_int / - // Win32Error / std.os.windows.Win32Error / signed integers. Stable Rust has no - // specialization, so this is split into typed entry points. Callers that passed - // arbitrary integer types should pick `init_c_int`. - /// `init(code: u16)` — Win32/WSA error codes and negated-uv codes encoded as u16. pub fn init_u16(code: u16) -> Option { Self::init_numeric(code) diff --git a/src/event_loop/AnyTask.rs b/src/event_loop/AnyTask.rs index 17f406baaa8..5b88cde42cd 100644 --- a/src/event_loop/AnyTask.rs +++ b/src/event_loop/AnyTask.rs @@ -16,7 +16,6 @@ pub use bun_core::JsError as ErasedJsError; pub type JsResult = core::result::Result; pub struct AnyTask { - // TODO(port): lifetime — type-erased callback context; raw by design. pub ctx: Option>, pub callback: fn(*mut c_void) -> JsResult<()>, } diff --git a/src/event_loop/ConcurrentTask.rs b/src/event_loop/ConcurrentTask.rs index 33409da4758..d51fcc0416f 100644 --- a/src/event_loop/ConcurrentTask.rs +++ b/src/event_loop/ConcurrentTask.rs @@ -9,7 +9,6 @@ //! Otherwise, it's expected that the containing struct will deallocate the task. use crate::ManagedTask; -// TODO(port): confirm crate for UnboundedQueue (bun.UnboundedQueue) — assuming bun_threading use bun_threading::UnboundedQueue; use bun_threading::unbounded_queue::{Link, Linked}; @@ -350,9 +349,6 @@ impl ConcurrentTask { Self::create(Task::from_boxed(task)) } - // TODO(port): `comptime callback: anytype` + `std.meta.Child(@TypeOf(ptr))` is comptime - // reflection. Modeled here as a generic over the pointee type `T` with a plain fn-pointer - // callback. Zig's `ManagedTask.New(T, cb).init(ptr)` collapses to `ManagedTask::new(ptr, cb)`. // PORT NOTE: callback returns `JsResult<()>` to match `ManagedTask::new`'s stored ABI; // Zig accepted both `fn(*T) void` and `fn(*T) JSError!void` via comptime — Rust callers // that have a `fn(*mut T)` should wrap it as `|p| { f(p); Ok(()) }` at the call site. diff --git a/src/event_loop/EventLoopTimer.rs b/src/event_loop/EventLoopTimer.rs index a7f10ea0273..45c3e96b1e5 100644 --- a/src/event_loop/EventLoopTimer.rs +++ b/src/event_loop/EventLoopTimer.rs @@ -206,11 +206,6 @@ pub enum Tag { } impl Tag { - // TODO(port): Zig `pub fn Type(comptime T: Tag) type` returns a type at comptime. - // Rust has no value→type mapping. All call sites (`jsTimerInternalsFlags`, `fire`) - // have been manually expanded above. If a generic mapping is ever needed, - // consider a trait `TagType { type Out; }` with per-variant impls. - pub fn allow_fake_timers(self) -> bool { match self { Tag::WTFTimer // internal diff --git a/src/event_loop/MiniEventLoop.rs b/src/event_loop/MiniEventLoop.rs index 3fdf3f8f66d..d5a31fd9046 100644 --- a/src/event_loop/MiniEventLoop.rs +++ b/src/event_loop/MiniEventLoop.rs @@ -626,8 +626,6 @@ pub enum EventLoopKind { Mini, } -// TODO(port): Zig `Type()` / `refType()` return `type` at comptime. Rust cannot return a type -// from a runtime enum value. Model as a trait with associated types instead: pub trait EventLoopKindT { type Loop; type Ref; diff --git a/src/event_loop/SpawnSyncEventLoop.rs b/src/event_loop/SpawnSyncEventLoop.rs index 49170e16802..23a05c6975a 100644 --- a/src/event_loop/SpawnSyncEventLoop.rs +++ b/src/event_loop/SpawnSyncEventLoop.rs @@ -30,8 +30,7 @@ use bun_uws as uws; // MOVE-IN: EventLoopHandle relocated from bun_jsc — see AnyEventLoop.rs. use crate::EventLoopHandle; -// TODO(port): `@FieldType(jsc.VirtualMachine, "event_loop_handle")` — comptime reflection on a -// foreign struct field. On POSIX this is `?*uws.Loop`, on Windows `?*libuv.Loop`. +// On POSIX this is `?*uws.Loop`, on Windows `?*libuv.Loop`. #[cfg(unix)] pub type VmEventLoopHandle = Option>; #[cfg(windows)] diff --git a/src/glob/GlobWalker.rs b/src/glob/GlobWalker.rs index da220032214..580fe9b099b 100644 --- a/src/glob/GlobWalker.rs +++ b/src/glob/GlobWalker.rs @@ -193,7 +193,6 @@ impl Accessor for SyscallAccessor { } fn close(handle: SyscallHandle) -> Option { - // TODO(port): @returnAddress() — Rust has no stable equivalent; pass None. handle.value.close_allowing_bad_file_descriptor(None) } @@ -771,7 +770,6 @@ impl<'a, A: Accessor, const SENTINEL: bool> Iterator<'a, A, SENTINEL> { // kernel filter could hide entries needed by other indices, // so skip it. The filter is purely an optimization; // matchPatternImpl still runs for correctness. - // TODO(port): @hasDecl(Accessor.DirIter, "setNameFilter") — trait default method covers this let filter: Option<&[u16]> = if active.count() == 1 { self.compute_nt_filter( u32::try_from(active.find_first_set().unwrap()).expect("int cast"), diff --git a/src/http/HTTPContext.rs b/src/http/HTTPContext.rs index f91ce2a42ae..ef19a9a2a26 100644 --- a/src/http/HTTPContext.rs +++ b/src/http/HTTPContext.rs @@ -3,17 +3,15 @@ use core::ffi::{c_int, c_void}; use core::ptr::NonNull; use crate::http_thread::InitOpts as HTTPThreadInitOpts; +use crate::ssl_config::{self, SSLConfig}; use crate::{ self as http, AlpnOffer, HTTPCertError, HTTPClient, InitError, get_cert_error_from_no, h2, }; use bun_boringssl::ssl_ctx_setup; use bun_boringssl_sys::SSL_CTX; use bun_collections::{HiveArray, TaggedPtrUnion}; -use bun_core::{self, Error, FeatureFlags}; -// TODO(port): SSLConfig arrives from move-in -// (MOVE_DOWN bun_runtime::api::server::server_config::SSLConfig → bun_http) -use crate::ssl_config::{self, SSLConfig}; use bun_core::strings; +use bun_core::{self, Error, FeatureFlags}; use bun_uws as uws; bun_core::declare_scope!(HTTPContext, hidden); diff --git a/src/http/HTTPThread.rs b/src/http/HTTPThread.rs index c7084787057..04230f29954 100644 --- a/src/http/HTTPThread.rs +++ b/src/http/HTTPThread.rs @@ -317,7 +317,6 @@ impl LibdeflateState { pub const REQUEST_BODY_SEND_STACK_BUFFER_SIZE: usize = 32 * 1024; -// TODO(port): UnboundedQueue is intrusive over `AsyncHttp.next`; encode the field offset. pub(crate) type Queue = UnboundedQueue>; // Clone: bitwise OK for the `*const c_void` CA-string pointers — they borrow @@ -541,7 +540,6 @@ impl HttpThread { } // Cache miss - create new SSL context - // TODO(port): Zig used allocator.create + manual destroy on error. let custom_context = bun_core::heap::release(Box::new(NewHttpContext:: { ref_count: Cell::new(1), pending_sockets: bun_collections::HiveArray::init(), diff --git a/src/http/InternalState.rs b/src/http/InternalState.rs index c993b8325e7..fe8c5d58809 100644 --- a/src/http/InternalState.rs +++ b/src/http/InternalState.rs @@ -256,10 +256,6 @@ impl<'a> InternalState<'a> { if bun_core::feature_flags::is_libdeflate_enabled() { // Fast-path: use libdeflate - // TODO(port): bun_http::HTTPThread::deflater — `http_thread()` accessor and the - // `LibdeflateState { decompressor, shared_buffer }` it returns live in the gated - // HTTPThread cluster. Re-gated until HTTPThread un-gates (which itself blocks on - // bun_uws::SocketHandler method bodies). 'libdeflate: { use bun_libdeflate_sys::libdeflate as bun_libdeflate; @@ -347,10 +343,6 @@ impl<'a> InternalState<'a> { } } - // TODO(port): bun_zlib::ZlibReaderArrayList / bun_brotli::BrotliReaderArrayList / - // bun_zstd::ZstdReaderArrayList — `Decompressor::update_buffers` is re-gated until - // those reader types are reshaped to not carry an `'a` borrow of the output Vec. - if let Err(err) = self .decompressor .update_buffers(self.encoding, buffer, body_out_str) diff --git a/src/http/h2_client/PendingConnect.rs b/src/http/h2_client/PendingConnect.rs index 0d777c55e09..edc8a884258 100644 --- a/src/http/h2_client/PendingConnect.rs +++ b/src/http/h2_client/PendingConnect.rs @@ -8,8 +8,6 @@ use bun_core::strings; use crate::HTTPClient; use crate::NewHTTPContext; -// TODO(port): SSLConfig arrives from move-in -// (MOVE_DOWN bun_runtime::api::server::server_config::SSLConfig → bun_http) use crate::ssl_config::SSLConfig; #[derive(Default)] diff --git a/src/http/h3_client/Stream.rs b/src/http/h3_client/Stream.rs index 9fe49ff1aad..c14ec66cd19 100644 --- a/src/http/h3_client/Stream.rs +++ b/src/http/h3_client/Stream.rs @@ -12,8 +12,6 @@ use bun_uws::quic; use super::ClientSession; use crate::HttpClient; -// TODO(port): H3Client.zig sits at src/http/H3Client.zig alongside the h3_client/ dir; -// confirm the module path for `live_streams` once the crate layout is wired. use crate::h3_client as h3; pub struct Stream { diff --git a/src/http/lib.rs b/src/http/lib.rs index bce6e59856c..8d0f9f5033a 100644 --- a/src/http/lib.rs +++ b/src/http/lib.rs @@ -1158,8 +1158,6 @@ pub fn print_request( body: &[u8], curl: bool, ) { - // TODO(port): Zig built a clone with `path = url` for the curl formatter. - // picohttp::Request<'_> isn't `Clone`, so format the fields directly. if curl { let request_ = picohttp::Request { method: request.method, @@ -2437,8 +2435,6 @@ impl<'a> HTTPClient<'a> { // (it needs `&mut self`, which would alias every other `self.*` call in the body), // so it is reshaped as an explicit `self.complete_connecting_process()` before each return. - // TODO(port): allocator vtable identity check elided (no allocator param in Rust) - // Aborted before connecting if self.signals.get(signals::Field::Aborted) { self.fail(err!(AbortedBeforeConnecting)); @@ -3315,7 +3311,6 @@ impl<'a> HTTPClient<'a> { && !self.state.flags.did_set_content_encoding { // if it compressed with this header, it is no longer because we will decompress it - // TODO(port): Zig wrapped headers in ArrayListUnmanaged but never mutated; preserved as-is self.state.flags.did_set_content_encoding = true; self.state.content_encoding_i = u8::MAX; // we need to reset the pending response because we removed a header diff --git a/src/http_jsc/websocket_client.rs b/src/http_jsc/websocket_client.rs index cc968f08bf5..d17eb74b970 100644 --- a/src/http_jsc/websocket_client.rs +++ b/src/http_jsc/websocket_client.rs @@ -362,7 +362,6 @@ impl WebSocket { .discard(self.receive_buffer.readable_length()); if free { - // TODO(port): LinearFifo::deinit → Drop semantics; reset to fresh state self.receive_buffer = LinearFifo::>::init(); } @@ -401,8 +400,6 @@ impl WebSocket { // PORT NOTE: reshaped for borrowck — drop deflate borrow before re-borrowing self let items = decompressed.as_slice(); - // TODO(port): borrowck — `decompressed` borrows `deflate.rare_data`; may need to - // copy out or restructure. self.dispatch_data(items, kind); } @@ -2097,10 +2094,6 @@ impl WebSocket { // ────────────────────────────────────────────────────────────────────────── // exportAll() — comptime @export with name concat // ────────────────────────────────────────────────────────────────────────── -// TODO(port): Zig's `@export(&fn, .{.name = "Bun__" ++ name ++ "__fn"})` with -// comptime string concat cannot be expressed generically in Rust (no_mangle -// requires a literal). Emit two monomorphized #[no_mangle] shims per fn via macro. - // PORT NOTE: avoids the `paste` crate by passing the nine fully-qualified // `#[no_mangle]` idents at the call site (declare-site macro). Zig's // comptime `++` concat has no Rust equivalent for `#[no_mangle]` literals. diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index 55d3def55e6..349de5853bb 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -1141,7 +1141,6 @@ impl HTTPClient { // Use ssl_config if available, otherwise use defaults let ssl_options: SSLConfig = match &me.ssl_config { Some(config) => (**config).clone(), - // TODO(port): SSLConfig clone — Zig copies by value (`config.*`). None => { let mut c = SSLConfig::default(); c.reject_unauthorized = 0; // We verify manually @@ -1827,8 +1826,6 @@ impl HTTPClient { unsafe { (*this.as_ptr()).tcp.detach() }; // For the TCP socket. - // TODO(port): defer self.deref() — moved to end of fn. - if this.state == State::Reading { // SAFETY: no `&mut Self` is live across this call. unsafe { Self::terminate(this.as_ptr(), ErrorCode::FailedToConnect) }; diff --git a/src/http_types/Method.rs b/src/http_types/Method.rs index a567e717c86..9f02d2335c0 100644 --- a/src/http_types/Method.rs +++ b/src/http_types/Method.rs @@ -3,7 +3,6 @@ use enumset::EnumSet; #[allow(non_camel_case_types)] #[repr(u8)] #[derive(enumset::EnumSetType, Debug)] -// TODO(port): EnumSetType derive auto-impls Copy/Clone/Eq/PartialEq; verify it coexists with #[repr(u8)] (needed for FFI @intFromEnum) pub enum Method { ACL = 0, BIND = 1, diff --git a/src/ini/lib.rs b/src/ini/lib.rs index 2a30d02211d..078753188a5 100644 --- a/src/ini/lib.rs +++ b/src/ini/lib.rs @@ -215,16 +215,8 @@ pub enum ScopeError { // // `Parser::parse` / `Parser::prepare_str` (unquoted path) / `ConfigIterator` // now compile against the live `bun_js_parser::{Expr, ExprData, E::*}` surface. -// Remaining gates are blocked on schema/API types only: // ────────────────────────────────────────────────────────────────────────── -// TODO(port): bun_api::BunInstall -// TODO(port): bun_api::NpmRegistry -// TODO(port): bun_api::NpmRegistryMap -// TODO(port): bun_api::npm_registry::Parser -// TODO(port): bun_api::Ca -// TODO(port): bun_install_types::NodeLinker::PnpmMatcher::from_expr - pub use draft::{ ConfigIterator, Parser, ScopeItem, ScopeIterator, ToStringFormatter, load_npmrc, load_npmrc_config, diff --git a/src/install/NetworkTask.rs b/src/install/NetworkTask.rs index e037d32f051..26b2faff448 100644 --- a/src/install/NetworkTask.rs +++ b/src/install/NetworkTask.rs @@ -300,8 +300,6 @@ impl NetworkTask { // SAFETY: `real` is set by the HTTP thread before invoking the // completion callback; Zig unwraps with `.?`. - // TODO(port): Zig does a struct-value copy `real.* = async_http.*` — - // requires `AsyncHTTP: Clone` or a bitwise copy helper. unsafe { let real = async_http.real.expect("unreachable").as_ptr(); ptr::write(real, ptr::read(async_http)); diff --git a/src/install/PackageInstall.rs b/src/install/PackageInstall.rs index 0946699b3f6..e03ffc64510 100644 --- a/src/install/PackageInstall.rs +++ b/src/install/PackageInstall.rs @@ -303,7 +303,6 @@ struct InstallDirState { impl Default for InstallDirState { fn default() -> Self { - // TODO(port): Zig used `undefined` for most fields; we need a sentinel. Self { cached_package_dir: Dir::from_fd(Fd::INVALID), walker: None, @@ -493,7 +492,6 @@ impl NewTaskQueue { } } -// TODO(port): helper trait so `NewTaskQueue::push` can reach the intrusive `.task` field generically. pub trait HasWorkPoolTask { fn task(&mut self) -> &mut WorkPoolTask; } diff --git a/src/install/PackageInstaller.rs b/src/install/PackageInstaller.rs index 3a8e6a0ce6d..6db646995ee 100644 --- a/src/install/PackageInstaller.rs +++ b/src/install/PackageInstaller.rs @@ -254,7 +254,6 @@ impl NodeModulesFolder { let out = 'brk: { #[cfg(unix)] { - // TODO(port): std.fs.Dir.makeOpenPath — bun_sys equivalent (mkdir -p + open) break 'brk root.make_open_path( self.path.as_slice(), bun_sys::OpenDirOptions { @@ -1245,7 +1244,6 @@ impl<'a> PackageInstaller<'a> { .workspace_versions .get(&pkg_name_hash) { - // TODO(port): std.fmt.bufPrint — write into &mut [u8], return written slice break 'brk bun_core::fmt::buf_print( &mut resolution_buf, format_args!("{}", workspace_version.fmt(string_buf!())), @@ -1743,7 +1741,6 @@ impl<'a> PackageInstaller<'a> { break 'result package_install::InstallResult::fail( err, package_install::Step::OpeningCacheDir, - // TODO(port): @errorReturnTrace() None, ); } diff --git a/src/install/PackageManager.rs b/src/install/PackageManager.rs index 8f4f7b7bcc1..15cfcdcc836 100644 --- a/src/install/PackageManager.rs +++ b/src/install/PackageManager.rs @@ -353,8 +353,8 @@ bun_output::declare_scope!(PackageManager, hidden); // ────────────────────────────────────────────────────────────────────────── pub struct PackageManager { - pub cache_directory_: Option, // TODO(port): std.fs.Dir → bun_sys::Dir - pub cache_directory_path: ZBox, // TODO(port): lifetime — singleton-leaked + pub cache_directory_: Option, + pub cache_directory_path: ZBox, // owned; process lifetime via the leaked singleton pub root_dir: &'static mut fs::DirEntry, // allocator dropped per §Allocators (was `bun.default_allocator`). For the // handful of sites that allocated AST nodes via `Expr.allocate(manager.allocator, …)` @@ -395,7 +395,7 @@ pub struct PackageManager { /// Only set in `bun pm` pub root_package_json_name_at_time_of_init: Box<[u8]>, - pub root_package_json_file: bun_sys::File, // TODO(port): std.fs.File → bun_sys::File + pub root_package_json_file: bun_sys::File, /// The package id corresponding to the workspace the install is happening in. Could be root, or /// could be any of the workspaces. @@ -447,12 +447,12 @@ pub struct PackageManager { pub preinstall_state: Vec, pub postinstall_optimizer: crate::postinstall_optimizer::List, - pub global_link_dir: Option, // TODO(port): std.fs.Dir - pub global_dir: Option, // TODO(port): std.fs.Dir + pub global_link_dir: Option, + pub global_dir: Option, pub global_link_dir_path: Box<[u8]>, pub on_wake: WakeHandler, - pub ci_mode: LazyBool bool>, // TODO(port): bun.LazyBool(computeIsContinuousIntegration, @This(), "ci_mode") + pub ci_mode: LazyBool bool>, pub peer_dependencies: LinearFifo>, @@ -470,7 +470,7 @@ pub struct PackageManager { // When adding a `file:` dependency in a workspace package, we want to install it // relative to the workspace root, but the path provided is relative to the // workspace package. We keep track of the original here. - pub original_package_json_path: ZBox, // TODO(port): owned [:0]const u8 + pub original_package_json_path: ZBox, // null means root. Used during `cleanWithLogger` to identifier which // workspace is adding/removing packages @@ -852,7 +852,7 @@ mod holder { static CWD_BUF: bun_core::RacyCell = bun_core::RacyCell::new(PathBuffer::ZEROED); static ROOT_PACKAGE_JSON_PATH_BUF: bun_core::RacyCell = bun_core::RacyCell::new(PathBuffer::ZEROED); -pub static ROOT_PACKAGE_JSON_PATH: bun_core::RacyCell<&ZStr> = bun_core::RacyCell::new(ZStr::EMPTY); // TODO(port): [:0]const u8 static slice into ROOT_PACKAGE_JSON_PATH_BUF +pub static ROOT_PACKAGE_JSON_PATH: bun_core::RacyCell<&ZStr> = bun_core::RacyCell::new(ZStr::EMPTY); // ────────────────────────────────────────────────────────────────────────── // impl PackageManager @@ -1128,8 +1128,7 @@ impl PackageManager { // bun.once wrappers // ────────────────────────────────────────────────────────────────────────── -// TODO(port): bun.once returns a struct whose .call() runs the closure exactly once -// and caches the result. `Transpiler` is non-`Copy` and self-referential, so cache +// `Transpiler` is non-`Copy` and self-referential, so cache // a process-static raw pointer (mirrors Zig `var ..: Transpiler = undefined;`). // PORTING.md §Global mutable state: init-once ptr → AtomicPtr. static CONFIGURE_ENV_FOR_SCRIPTS_ONCE: core::sync::atomic::AtomicPtr< @@ -1988,7 +1987,7 @@ pub fn init( )); wr!(cache_directory_, None); - wr!(cache_directory_path, ZBox::from_bytes(b"")); // TODO(port): default "" + wr!(cache_directory_path, ZBox::from_bytes(b"")); wr!(options, options); wr!( active_lifecycle_scripts, @@ -2034,7 +2033,6 @@ pub fn init( original_package_json_path, ZBox::from_vec_with_nul(original_package_json_path_buf) ); - // TODO(port): owned [:0]const u8 conversion wr!(workspace_package_json_cache, workspace_package_json_cache); wr!(workspace_name_hash, workspace_name_hash); wr!(subcommand, subcommand); @@ -2303,7 +2301,6 @@ pub fn init( let timestamp_for_manifest_cache_control: u32 = 'brk: { if cfg!(debug_assertions) { - // TODO(port): bun.Environment.allow_assert if let Some(cache_control) = env.get(b"BUN_CONFIG_MANIFEST_CACHE_CONTROL_TIMESTAMP") { // env-var bytes are not guaranteed UTF-8; parse on bytes directly (Zig: std.fmt.parseInt) if let Ok(int) = bun_core::parse_int::(cache_control, 10) { @@ -2440,7 +2437,7 @@ pub(crate) fn init_with_runtime_once( )); wr!(cache_directory_, None); - wr!(cache_directory_path, ZBox::from_bytes(b"")); // TODO(port): default + wr!(cache_directory_path, ZBox::from_bytes(b"")); wr!( options, Options { diff --git a/src/install/PackageManager/CommandLineArguments.rs b/src/install/PackageManager/CommandLineArguments.rs index 2f1d72f38bb..7bfdaac38c7 100644 --- a/src/install/PackageManager/CommandLineArguments.rs +++ b/src/install/PackageManager/CommandLineArguments.rs @@ -1077,7 +1077,6 @@ Full documentation is available at https://bun.com/docs/cli/pm#scan. } if let Some(network_concurrency) = args.option(b"--network-concurrency") { - // TODO(port): parse u16 from &[u8] — bun_str helper or core::str::from_utf8 + parse cli.network_concurrency = Some(match strings::parse_int::(network_concurrency, 10) { Ok(n) => n, @@ -1096,7 +1095,6 @@ Full documentation is available at https://bun.com/docs/cli/pm#scan. } if let Some(min_age_secs) = args.option(b"--minimum-release-age") { - // TODO(port): parse f64 from &[u8] let secs: f64 = match bun_core::parse_double(min_age_secs) { Ok(s) => s, Err(_) => { diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index 39318cfbf36..4c30e0a030f 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -193,7 +193,6 @@ pub fn enqueue_tarball_for_download( } task_queue.value_ptr.push(task_context); - // TODO(port): narrow error set if task_queue.found_existing { return Ok(()); @@ -375,7 +374,6 @@ pub unsafe fn enqueue_parse_npm_package( ), }, id: task_id, - // TODO(port): `data: undefined` — Task::data left uninitialized in Zig ..Task::uninit() } }; @@ -1686,7 +1684,6 @@ fn init_extract_task( }), }, id: (*network_task).task_id, - // TODO(port): `data: undefined` ..Task::uninit() } }; @@ -1795,7 +1792,6 @@ fn enqueue_git_clone( } else { None }, - // TODO(port): `data: undefined` ..Task::uninit() }; let task = this.preallocated_resolve_tasks.get_init(value).as_ptr(); @@ -1881,7 +1877,6 @@ pub fn enqueue_git_checkout( None }, id: task_id, - // TODO(port): `data: undefined` ..Task::uninit() } }; @@ -1977,7 +1972,6 @@ fn enqueue_local_tarball( }), }, id: task_id, - // TODO(port): `data: undefined` ..Task::uninit() }; let task = this.preallocated_resolve_tasks.get_init(value).as_ptr(); diff --git a/src/install/PackageManager/PackageManagerOptions.rs b/src/install/PackageManager/PackageManagerOptions.rs index 14e4d966948..76b01df8f74 100644 --- a/src/install/PackageManager/PackageManagerOptions.rs +++ b/src/install/PackageManager/PackageManagerOptions.rs @@ -18,7 +18,6 @@ pub struct Options { pub log_level: LogLevel, pub global: bool, - // TODO(port): std.fs.Dir → bun_sys::Fd (directory handle); default was bun.FD.invalid.stdDir() pub global_bin_dir: bun_sys::Fd, pub explicit_global_directory: &'static [u8], /// destination directory to link bins into @@ -102,7 +101,6 @@ impl Default for Options { global: false, global_bin_dir: bun_sys::Fd::INVALID, explicit_global_directory: b"", - // TODO(port): bun.pathLiteral("node_modules/.bin") — platform-specific separator at comptime bin_path: bun_paths::path_literal!("node_modules/.bin"), did_override_default_scope: false, // PORT NOTE: Zig had `= undefined`; always assigned in `load()` before read. diff --git a/src/install/PackageManager/install_with_manager.rs b/src/install/PackageManager/install_with_manager.rs index 44cbd2fd7df..dae6ffbad2a 100644 --- a/src/install/PackageManager/install_with_manager.rs +++ b/src/install/PackageManager/install_with_manager.rs @@ -1080,7 +1080,6 @@ fn print_install_summary( count, if count == 1 { "" } else { "s" }, ); - // TODO(port): Output::pretty multi-arg formatting Output::print_start_end_stdout(ctx.start_time, nano_timestamp()); } printed_timestamp = true; @@ -1095,7 +1094,6 @@ fn print_install_summary( "s" }, ); - // TODO(port): Output::pretty multi-arg formatting Output::print_start_end_stdout(ctx.start_time, nano_timestamp()); printed_timestamp = true; print_blocked_packages_info(install_summary, this.options.global); @@ -1191,7 +1189,6 @@ fn print_summary_installed( pkgs_installed, if pkgs_installed == 1 { "" } else { "s" }, ); - // TODO(port): Output::pretty multi-arg formatting Output::print_start_end_stdout(start_time, nano_timestamp()); print_blocked_packages_info(install_summary, this.options.global); @@ -1218,7 +1215,6 @@ fn print_summary_removed( this.summary.remove, if this.summary.remove == 1 { "" } else { "s" }, ); - // TODO(port): Output::pretty multi-arg formatting Output::print_start_end_stdout(start_time, nano_timestamp()); print_blocked_packages_info(install_summary, this.options.global); } @@ -1231,7 +1227,6 @@ fn print_summary_failed(install_summary: &PackageInstallSummary) { install_summary.fail, if install_summary.fail == 1 { "" } else { "s" }, ); - // TODO(port): Output::pretty multi-arg formatting Output::flush(); } @@ -1265,7 +1260,6 @@ fn print_blocked_packages_info(summary: &PackageInstallSummary, global: bool) { if scripts_count > 1 { "s" } else { "" }, if global { "-g " } else { "" }, ); - // TODO(port): Output::pretty multi-arg formatting } else { bun_core::pretty!("\n"); } @@ -1798,7 +1792,6 @@ fn save_lockfile_only( "s" }, ); - // TODO(port): Output::pretty multi-arg formatting — Zig used positional `{s} {d} {s}` Output::print_start_end_stdout(ctx.start_time, nano_timestamp()); bun_core::pretty!("\n"); } diff --git a/src/install/PackageManager/runTasks.rs b/src/install/PackageManager/runTasks.rs index 6536fdfde7c..b7952a25722 100644 --- a/src/install/PackageManager/runTasks.rs +++ b/src/install/PackageManager/runTasks.rs @@ -104,10 +104,6 @@ pub trait RunTasksCallbacks { unreachable!() } - // TODO(port): two distinct call shapes in Zig: - // PackageInstaller: (ctx, task_id, dependency_id, *ExtractData, log_level) - // Store.Installer: (ctx, task_id) - // Model as two methods; only one is reachable per impl. fn on_extract_package_installer( _ctx: &mut Self::Ctx, _task_id: Task::Id, diff --git a/src/install/PackageManager/security_scanner.rs b/src/install/PackageManager/security_scanner.rs index 442f3b04523..37a4684a6e2 100644 --- a/src/install/PackageManager/security_scanner.rs +++ b/src/install/PackageManager/security_scanner.rs @@ -424,7 +424,6 @@ pub(crate) fn prompt_for_warnings() -> bool { bun_core::pretty!("\nSecurity warnings found. Continue anyway? [y/N] "); Output::flush(); - // TODO(port): Zig used std.fs.File.stdin().readerStreaming(); use bun_core stdin reader. let mut reader = bun_core::output::stdin_reader(); let Ok(first_byte) = reader.take_byte() else { @@ -476,7 +475,6 @@ pub(crate) fn prompt_for_warnings() -> bool { struct PackageCollector<'a> { manager: &'a PackageManager, dedupe: ArrayHashMap, - // TODO(port): Zig uses bun.LinearFifo(QueueItem, .Dynamic); VecDeque is the closest std equivalent. queue: VecDeque, package_paths: ArrayHashMap, } @@ -819,7 +817,6 @@ fn attempt_security_scan_with_retry( BStr::new(original_cwd) ); } - // TODO(port): std.time.milliTimestamp() — use bun_core::time helper or std::time::Instant. let start_time = bun_core::time::milli_timestamp(); let finder = ScannerFinder { diff --git a/src/install/bin.rs b/src/install/bin.rs index a559ef265b6..8013ec5afb1 100644 --- a/src/install/bin.rs +++ b/src/install/bin.rs @@ -446,7 +446,6 @@ impl Bin { } pub fn init() -> Bin { - // TODO(port): bun.serializable() zero-initialized padding for hashing stability Bin { tag: Tag::None, _padding_tag: [0; 3], @@ -517,7 +516,6 @@ pub union Value { impl Value { /// To avoid undefined memory between union values, we must zero initialize the union first. - // TODO(port): bun.serializableInto zeroed the full union before assignment. #[inline] pub fn init_none() -> Value { // SAFETY: all-zero is a valid Value (largest member ExternalStringList is POD) @@ -592,7 +590,6 @@ pub struct NamesIterator<'a> { pub bin: Bin, pub i: usize, pub done: bool, - // TODO(port): std.fs.Dir.Iterator → bun_sys directory iterator type pub dir_iterator: Option, pub package_name: String, /// Borrowed view of the destination `node_modules` directory fd; the @@ -1167,7 +1164,6 @@ impl<'a> Linker<'a> { // Snapshot the length and restore via `set_length` after. let node_modules_path_save = self.node_modules_path.len(); let _ = self.node_modules_path.append(b".bin"); - // TODO(port): bun.makePath(std.fs.cwd(), ...) let _ = sys::Dir::cwd().make_path(self.node_modules_path.slice()); self.node_modules_path.set_length(node_modules_path_save); @@ -1331,7 +1327,6 @@ impl<'a> Linker<'a> { } // delete and try again - // TODO(port): std.fs.deleteTreeAbsolute → bun_sys equivalent let _ = sys::delete_tree_absolute(abs_dest.as_bytes()); if let Err(err) = sys::symlink_running_executable(rel_target, abs_dest) { self.err = Some(err.to_zig_err()); diff --git a/src/install/dependency.rs b/src/install/dependency.rs index 9a462e654b5..aaaf57fca8a 100644 --- a/src/install/dependency.rs +++ b/src/install/dependency.rs @@ -1204,7 +1204,6 @@ impl ValueExt for Value { // Free functions: parse // ────────────────────────────────────────────────────────────────────────── -#[allow(dead_code)] pub fn is_windows_abs_path_with_leading_slashes(dep: &[u8]) -> Option<&[u8]> { let mut i: usize = 0; if dep.len() > 2 && dep[i] == b'/' { diff --git a/src/install/extract_tarball.rs b/src/install/extract_tarball.rs index d21cd4ea272..30d8e7ac138 100644 --- a/src/install/extract_tarball.rs +++ b/src/install/extract_tarball.rs @@ -165,9 +165,6 @@ pub(crate) fn build_url_with_printer( } } -// TODO(port): `bun.ThreadlocalBuffers(struct{...})` returns a type with `.get()` -// yielding a `*Bufs` into TLS. Model as a thread_local RefCell; callers borrow -// for the duration of the function. struct TlBufs { final_path_buf: PathBuffer, folder_name_buf: PathBuffer, diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 24558bd117d..18efbceff8d 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -123,11 +123,6 @@ struct WyhashWriter<'a> { hasher: &'a mut Wyhash, } -impl<'a> WyhashWriter<'a> { - // TODO(port): Zig used std.io.GenericWriter; here we impl std::io::Write - // directly so `write!()` works and never errors. -} - impl<'a> std::io::Write for WyhashWriter<'a> { fn write(&mut self, bytes: &[u8]) -> std::io::Result { self.hasher.update(bytes); @@ -242,7 +237,6 @@ pub(crate) fn install_isolated_packages( let store: Store = 'store: { let mut timer = std::time::Instant::now(); - // TODO(port): std.time.Timer.start() catch unreachable → Instant::now() let pkgs = lockfile.packages.slice(); let pkg_dependency_slices = pkgs.items_dependencies(); let pkg_resolutions = pkgs.items_resolution(); @@ -676,7 +670,6 @@ pub(crate) fn install_isolated_packages( // TODO: make this sort in an order that allows peers to be resolved last // and devDependency handling to match `hoistDependency` - // TODO(port): std.sort.pdq → slice::sort_by with DepSorter { let sorter = lockfile::DepSorter { lockfile }; dep_ids_sort_buf.sort_by(|a, b| { @@ -1246,8 +1239,6 @@ pub(crate) fn install_isolated_packages( // patch or be mutated underneath other projects. if lockfile.patched_dependencies.count() > 0 { let mut name_version_buf = PathBuffer::uninit(); - // TODO(port): std.fmt.bufPrint returned the written - // slice; emulate via cursor write into the PathBuffer. let mut cursor = std::io::Cursor::new(&mut name_version_buf.0[..]); let name_version: &[u8] = match write!( diff --git a/src/install/isolated_install/Installer.rs b/src/install/isolated_install/Installer.rs index 4eed0200d77..6f30c3c8d04 100644 --- a/src/install/isolated_install/Installer.rs +++ b/src/install/isolated_install/Installer.rs @@ -873,7 +873,6 @@ impl Task { let pkg_name_hash = pkg_name_hashes[pkg_id as usize]; let pkg_res = pkg_resolutions[pkg_id as usize]; - // TODO(port): Zig labeled-switch `next_step:` modeled as loop+match let mut step = Step::from_u32(entry_steps[self.entry_id.get() as usize].load(Ordering::Acquire)); 'step: loop { @@ -901,7 +900,6 @@ impl Task { }; let _folder_dir_guard = sys::CloseOnDrop::new(folder_dir); - // TODO(port): Zig labeled-switch `backend:` modeled as loop+match let mut backend = InstallMethod::Hardlink; 'backend: loop { match backend { diff --git a/src/install/lifecycle_script_runner.rs b/src/install/lifecycle_script_runner.rs index 54f0b079898..3d44a4562d0 100644 --- a/src/install/lifecycle_script_runner.rs +++ b/src/install/lifecycle_script_runner.rs @@ -363,7 +363,6 @@ use bun_sys::windows::libuv as uv; pub type OutputReader = BufferedReader; -// TODO(port): `std.time.Timer` — replace with bun_core monotonic timer wrapper. pub(crate) type Timer = bun_core::time::Timer; impl<'a> LifecycleScriptSubprocess<'a> { @@ -708,8 +707,6 @@ impl<'a> LifecycleScriptSubprocess<'a> { ) { Ok(Ok(s)) => s, res => { - // TODO(port): Zig was `try (try spawnProcess(...)).unwrap()` — outer - // `!Maybe(Spawned)`. Modeled here as `Result, _>`. #[cfg(windows)] { // `spawn_process_windows` only `heap::take`s the `Stdio::Buffer` diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index 823d0e2e94f..8bf1175ef33 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -78,7 +78,7 @@ pub use self::bun_lockb as Serializer; pub use self::catalog_map::CatalogMap; pub use self::lockfile_json_stringify_for_debugging::json_stringify; pub use self::override_map::OverrideMap; -pub use self::package::Package; // TODO(port): Zig was `Package(u64)` — generic instantiation +pub use self::package::Package; pub use self::tree::Tree; pub use crate::padding_checker::assert_no_uninitialized_padding; // Bring the derive-generated `items_*` column accessors (`PackageColumns` for @@ -176,7 +176,6 @@ pub struct Lockfile { pub meta_hash: MetaHash, pub packages: PackageList, - // TODO(port): Lockfile.Package.List is a MultiArrayList pub buffers: Buffers, /// name -> PackageID || [*]PackageID @@ -630,7 +629,6 @@ impl Lockfile { log: &mut bun_ast::Log, ) -> LoadResult<'a> { let mut stream = Stream::new(buf); - // TODO(port): Stream{ .buffer = buf, .pos = 0 } self.format = FormatVersion::current(); self.scripts = Scripts::default(); @@ -1433,9 +1431,6 @@ impl Lockfile { } /// Sets `buffers.trees` and `buffers.hoisted_dependencies` - // TODO(port): Zig uses `comptime method` to make several params conditionally `void`. - // Rust const-generic enums need #[derive(ConstParamTy)] on Tree::BuilderMethod and the - // value-level branching can't change param types. Consider two monomorphized fns. pub fn hoist( &mut self, log: &mut bun_ast::Log, diff --git a/src/install/lockfile/Package.rs b/src/install/lockfile/Package.rs index 2e00c93f83b..75a1928c4ec 100644 --- a/src/install/lockfile/Package.rs +++ b/src/install/lockfile/Package.rs @@ -817,7 +817,6 @@ impl Package { total_dependencies_count = 0; // PERF(port): was `inline for` — profile if hot. for group in dependency_groups { - // TODO(port): @field reflection — see note above let map: ExternalStringMap = package_version.dep_group(group.field); let keys = map.name.get(&manifest.external_strings); let version_strings = map.value.get(&manifest.external_strings_for_versions); diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index 4545c71a890..34e45fb3006 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -198,7 +198,6 @@ impl WorkspaceMap { match process_workspace_name(json_cache, abs_package_json_path, log) { Ok(e) => e, Err(err) => { - // TODO(port): bun.handleErrorReturnTrace — no Rust equivalent (Zig error return traces) if err == bun_core::err!("EISNOTDIR") || err == bun_core::err!("EISDIR") || err == bun_core::err!("EACCESS") @@ -432,8 +431,6 @@ impl WorkspaceMap { ) { Ok(e) => e, Err(err) => { - // TODO(port): bun.handleErrorReturnTrace — no Rust equivalent - let entry_base: &[u8] = path::basename(matched_path); if err == bun_core::err!("FileNotFound") || err == bun_core::err!("PermissionDenied") @@ -444,7 +441,6 @@ impl WorkspaceMap { Some(source), bun_ast::Loc::EMPTY, format_args!( - // TODO(port): comptime concat with sep_str — using runtime sep "Missing \"name\" from package.json in {}{}{}", BStr::new(entry_dir), SEP_STR, diff --git a/src/install/lockfile/Tree.rs b/src/install/lockfile/Tree.rs index bd4ab867dd9..d6f2863a166 100644 --- a/src/install/lockfile/Tree.rs +++ b/src/install/lockfile/Tree.rs @@ -490,7 +490,6 @@ impl<'a, const METHOD: BuilderMethod> Builder<'a, METHOD> { } pub(crate) fn maybe_report_error(&mut self, args: core::fmt::Arguments<'_>) { - // TODO(port): bun_ast::Log::add_error_fmt signature — allocator param dropped. let _ = self.log.add_error_fmt(None, bun_ast::Loc::EMPTY, args); } @@ -721,8 +720,6 @@ impl Tree { dependencies: DependencyIDList::default(), })?; - // TODO(port): Zig kept long-lived mutable slices into `builder.list` (trees, dependency_lists) - // alongside &mut builder. Reshaped to re-borrow per use to satisfy borrowck. // PORT NOTE: reshaped for borrowck. let next_id = (builder.list.len() - 1) as Id; diff --git a/src/install/lockfile/lockfile_json_stringify_for_debugging.rs b/src/install/lockfile/lockfile_json_stringify_for_debugging.rs index 4693c1c172e..8b4358ceabe 100644 --- a/src/install/lockfile/lockfile_json_stringify_for_debugging.rs +++ b/src/install/lockfile/lockfile_json_stringify_for_debugging.rs @@ -222,7 +222,6 @@ where package_index::Entry::Id(id) => *id, package_index::Entry::Ids(ids) => ids.as_slice()[0], }; - // TODO(port): MultiArrayList column accessor — `packages.items(.name)` in Zig. let name = this.packages.items_name()[first_id as usize].slice(sb); w.object_field(name)?; match entry { diff --git a/src/install/npm.rs b/src/install/npm.rs index ab474b90f8d..452a088a415 100644 --- a/src/install/npm.rs +++ b/src/install/npm.rs @@ -211,8 +211,6 @@ pub fn whoami(manager: &mut PackageManager) -> Result, WhoamiError> { Ok(username.to_vec()) } -// TODO(port): body gated — picohttp::Response field shape drift - pub fn response_error( req: &AsyncHTTP, res: &picohttp::Response, @@ -889,8 +887,6 @@ impl PackageManifest { self.pkg.name.slice(&self.string_buf) } - // TODO(port): bun_io::DiscardingWriter — counting writer not exposed yet - pub fn byte_length(&self, scope: ®istry::Scope) -> usize { let mut counter = bun_io::DiscardingWriter::new(); match package_manifest::Serializer::write(self, scope, &mut counter) { @@ -1292,7 +1288,7 @@ pub mod package_manifest { // TODO(port): lifetime — `scope` is borrowed across a thread boundary; Zig assumed // the Registry.Scope outlives the threadpool task. Prove or change to owned. let task = bun_core::heap::into_raw(SaveTask::new(SaveTask { - manifest: this.clone(), // TODO(port): Zig copied PackageManifest by value + manifest: this.clone(), scope, tmpdir, cache_dir, @@ -3345,7 +3341,7 @@ impl PackageManifest { match how_many_bytes_to_store_indices { 1 => sort_with_int!(u8), 2 => sort_with_int!(u16), - 3 => sort_with_int!(u32), // TODO(port): Zig used u24; Rust has no u24, use u32 + 3 => sort_with_int!(u32), 4 => sort_with_int!(u32), 5..=8 => sort_with_int!(u64), _ => { diff --git a/src/install/patch_install.rs b/src/install/patch_install.rs index e54d68b07f7..2ba8e53b0ca 100644 --- a/src/install/patch_install.rs +++ b/src/install/patch_install.rs @@ -888,8 +888,6 @@ impl PatchTask { } } -// TODO(port): these enum/type references are placeholders for cross-file types that live in -// `bun_install`. Replace with the real paths once those modules are ported. use crate::PreinstallState; use crate::network_task::Authorization; use crate::package_install::{InstallResult, Method as InstallMethod}; diff --git a/src/install/windows-shim/bun_shim_impl.rs b/src/install/windows-shim/bun_shim_impl.rs index a5696c38d60..86b34592da6 100644 --- a/src/install/windows-shim/bun_shim_impl.rs +++ b/src/install/windows-shim/bun_shim_impl.rs @@ -72,16 +72,11 @@ const DBG: bool = cfg!(debug_assertions); /// In Zig: `@import("root") == @This()` — true when this module IS the binary root /// (the standalone `bun_shim_impl.exe`), false when compiled into bun.exe. -// TODO(port): this should be a cargo feature (`shim_standalone`) set only when building -// the standalone shim binary; the `bun` crate is unavailable in standalone builds. const IS_STANDALONE: bool = cfg!(feature = "shim_standalone"); #[cfg(not(feature = "shim_standalone"))] bun_output::declare_scope!(bun_shim_impl, hidden); -// TODO(port): Zig `callmod_inline` selects `.always_inline` in standalone, `bun.callmod_inline` -// otherwise. Rust has no per-callsite call modifier; rely on `#[inline(always)]` on `w::teb()`. - /// A copy of all ntdll declarations this program uses mod nt { use super::*; @@ -223,7 +218,6 @@ pub enum FailReason { NoDirname, CouldNotOpenShim, CouldNotReadShim, - #[allow(dead_code)] InvalidShimDataSize, ShimNotFound, CreateProcessFailed, @@ -440,11 +434,6 @@ pub(crate) enum LauncherMode { } impl LauncherMode { - // TODO(port): Zig's `RetType`/`FailRetType` returned different types per variant - // (`noreturn`/`void`/`ReadWithoutLaunchResult`). Stable Rust const-generics cannot - // associate a return type with a const value. We unify on `LauncherRet` below; the - // public wrappers (`try_startup_from_bun_js`, `read_without_launch`, `main`) narrow it. - // PERF(port): comptime mode/reason demoted to runtime args — profile if it shows up on a hot path. #[cold] #[inline(never)] @@ -470,9 +459,6 @@ enum LauncherRet { /// Abstraction over `()` (standalone), `FromBunRunContext`, and `FromBunShellContext` /// for the Zig `bun_ctx: anytype` parameter. -// TODO(port): this trait approximates Zig comptime duck-typing; methods that don't apply -// to a given impl call `unreachable!()` (matching the Zig — those code paths are gated by -// `is_standalone`/`mode` checks that prevent the call at runtime). trait BunCtx { fn base_path(&self) -> *mut u16; fn base_path_len(&self) -> usize; @@ -1599,7 +1585,6 @@ impl FromBunRunContext { /// View `base_path[0..base_path_len]` as a slice. Centralises the (ptr, len) /// → slice reconstruction so callers don't open-code `from_raw_parts`. #[inline] - #[allow(dead_code)] pub(crate) fn base_path_slice(&self) -> &[u16] { // SAFETY: caller of `try_startup_from_bun_js` (run_command.rs) sets // `base_path`/`base_path_len` from a live `[u16]` buffer it owns for @@ -1653,7 +1638,6 @@ impl BunCtx for &FromBunRunContext { /// this returns void, to which the caller should still try invoking the exe directly. This /// is to handle version mismatches where bun.exe's decoder is too new than the .bunx file. #[cfg(not(feature = "shim_standalone"))] -#[allow(dead_code)] pub fn try_startup_from_bun_js(context: FromBunRunContext) { debug_assert!(!context.base_path_slice().starts_with(&NT_OBJECT_PREFIX)); const _: () = assert!(!IS_STANDALONE); @@ -1729,9 +1713,7 @@ impl BunCtx for &FromBunShellContext { // negligible here and gives us safe matching. pub enum ReadWithoutLaunchResult { /// enum which has a predefined custom formatter - #[allow(dead_code)] Err(FailReason), - #[allow(dead_code)] CommandLine(*const u16, usize), } diff --git a/src/install/yarn.rs b/src/install/yarn.rs index ab68b4b9138..9e3581c6bff 100644 --- a/src/install/yarn.rs +++ b/src/install/yarn.rs @@ -379,8 +379,6 @@ impl<'a> YarnLock<'a> { if spec_trimmed.is_empty() { continue; } - // TODO(port): Zig dupes here; we borrow from `content` directly since - // spec_trimmed is a subslice of `content` and outlives YarnLock<'a>. current_specs.push(spec_trimmed); } @@ -393,7 +391,6 @@ impl<'a> YarnLock<'a> { for spec in ¤t_specs { if let Some(at_index) = strings::index_of(spec, b"@file:") { let file_path = &spec[at_index + 6..]; - // TODO(port): Zig dupes here; borrow from content instead. new_entry.file = Some(file_path); break; } @@ -2039,7 +2036,6 @@ pub(crate) fn migrate_yarn_lockfile<'a>( this.fetch_necessary_package_metadata_after_yarn_or_pnpm_migration::(manager)?; if cfg!(debug_assertions) { - // TODO(port): Environment.allow_assert maps to debug_assertions this.verify_data()?; } diff --git a/src/install_jsc/dependency_jsc.rs b/src/install_jsc/dependency_jsc.rs index dd67ede640b..3ef276570ab 100644 --- a/src/install_jsc/dependency_jsc.rs +++ b/src/install_jsc/dependency_jsc.rs @@ -105,7 +105,6 @@ pub(crate) fn version_to_js( Ok(object) } -// TODO(port): proc-macro — `#[bun_jsc::host_fn]` ABI wrapper. pub fn tag_infer_from_js(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { use bun_core::String as BunString; use bun_install::dependency::{TagExt, version::Tag}; @@ -134,7 +133,6 @@ pub(crate) fn log_to_js( bun_ast_jsc::log_to_js(log, global, msg) } -// TODO(port): proc-macro — `#[bun_jsc::host_fn]` ABI wrapper. pub fn dependency_from_js(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { use bun_ast::Log; use bun_install::dependency; diff --git a/src/install_jsc/hosted_git_info_jsc.rs b/src/install_jsc/hosted_git_info_jsc.rs index 11327345184..04f719a948b 100644 --- a/src/install_jsc/hosted_git_info_jsc.rs +++ b/src/install_jsc/hosted_git_info_jsc.rs @@ -56,8 +56,6 @@ impl HostedGitInfoJsc for bun_install::hosted_git_info::HostedGitInfo { } } -// TODO(port): proc-macro — `#[bun_jsc::host_fn]` will wrap these into the -// `JSHostFn` ABI for `$newZigFunction`. Bodies are plain `JSHostFnZig`-shaped fns. pub fn js_parse_url(go: &JSGlobalObject, callframe: &CallFrame) -> JsResult { use bun_install::hosted_git_info as hgi; if callframe.arguments_count() != 1 { diff --git a/src/install_jsc/npm_jsc.rs b/src/install_jsc/npm_jsc.rs index 8c2bef10375..018c6753444 100644 --- a/src/install_jsc/npm_jsc.rs +++ b/src/install_jsc/npm_jsc.rs @@ -5,9 +5,6 @@ use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult}; -// TODO(port): proc-macro — `#[bun_jsc::host_fn]` will wrap these into the -// `JSHostFn` ABI for `JSFunction::create`. Until that lands, the bodies are -// plain `JSHostFnZig`-shaped fns (compile-checked, not yet ABI-wrapped). pub fn operating_system_is_match(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { use bun_install::npm; let args = frame.arguments_old::<1>(); diff --git a/src/install_types/resolver_hooks.rs b/src/install_types/resolver_hooks.rs index fa685634c9c..6604abf0f8f 100644 --- a/src/install_types/resolver_hooks.rs +++ b/src/install_types/resolver_hooks.rs @@ -1416,7 +1416,6 @@ impl WakeHandler { // PORT NOTE: Zig casts `t.handler` (the wrong field) to the dep-error fn type — this is // a Zig bug. The port reads `on_dependency_error` instead; preserving the bug would // require an unsound transmute between fn-pointer signatures. - // TODO(port): upstream fix to PackageManager.zig self.on_dependency_error.unwrap() } } diff --git a/src/io/PipeReader.rs b/src/io/PipeReader.rs index b30a1c2d707..37f31e8d0b0 100644 --- a/src/io/PipeReader.rs +++ b/src/io/PipeReader.rs @@ -1093,7 +1093,6 @@ pub struct WindowsBufferedReader { pub flags: WindowsFlags, pub maxbuf: Option>, - #[allow(dead_code)] pub parent: *mut c_void, pub vtable: BufferedReaderVTable, } @@ -1125,12 +1124,10 @@ impl WindowsFlags { #[cfg(windows)] impl WindowsBufferedReader { - #[allow(dead_code)] pub fn memory_cost(&self) -> usize { mem::size_of::() + self._buffer.capacity() } - #[allow(dead_code)] pub fn init() -> WindowsBufferedReader { WindowsBufferedReader { source: None, @@ -1144,7 +1141,6 @@ impl WindowsBufferedReader { } #[inline] - #[allow(dead_code)] pub fn is_done(&self) -> bool { self.flags.intersects( WindowsFlags::IS_DONE @@ -1153,7 +1149,6 @@ impl WindowsBufferedReader { ) } - #[allow(dead_code)] pub fn from(&mut self, other: &mut WindowsBufferedReader, parent: *mut c_void) { debug_assert!(other.source.is_some() && self.source.is_none()); // PORT NOTE: keep self.vtable; move other's state in. @@ -1175,7 +1170,6 @@ impl WindowsBufferedReader { self.set_parent(parent); } - #[allow(dead_code)] pub fn get_fd(&self) -> Fd { let Some(source) = &self.source else { return Fd::INVALID; @@ -1183,7 +1177,6 @@ impl WindowsBufferedReader { source.get_fd() } - #[allow(dead_code)] pub fn watch(&mut self) { // No-op on windows. } @@ -1202,7 +1195,6 @@ impl WindowsBufferedReader { } } - #[allow(dead_code)] pub fn update_ref(&mut self, value: bool) { if let Some(source) = self.source.as_mut() { if value { @@ -1213,17 +1205,10 @@ impl WindowsBufferedReader { } } - #[allow(dead_code)] - pub(crate) fn enable_keeping_process_alive(&mut self, _: C) { - self.update_ref(true); - } - - #[allow(dead_code)] pub fn disable_keeping_process_alive(&mut self, _: C) { self.update_ref(false); } - #[allow(dead_code)] pub fn take_buffer(&mut self) -> Vec { mem::take(&mut self._buffer) } @@ -1232,12 +1217,10 @@ impl WindowsBufferedReader { &mut self._buffer } - #[allow(dead_code)] pub fn final_buffer(&mut self) -> &mut Vec { self.buffer() } - #[allow(dead_code)] pub fn has_pending_activity(&self) -> bool { let Some(source) = &self.source else { return false; @@ -1245,7 +1228,6 @@ impl WindowsBufferedReader { source.is_active() } - #[allow(dead_code)] pub fn has_pending_read(&self) -> bool { if self.flags.contains(WindowsFlags::HAS_INFLIGHT_READ) { return true; @@ -1317,13 +1299,11 @@ impl WindowsBufferedReader { self.vtable.on_reader_done(); } - #[allow(dead_code)] pub fn on_error(&mut self, err: sys::Error) { self.finish(); self.vtable.on_reader_error(err); } - #[allow(dead_code)] pub(crate) fn get_read_buffer_with_stable_memory_address( &mut self, suggested_size: usize, @@ -1334,7 +1314,6 @@ impl WindowsBufferedReader { unsafe { bun_core::vec::spare_bytes_mut(&mut self._buffer) } } - #[allow(dead_code)] pub fn start_with_current_pipe(&mut self) -> sys::Result<()> { debug_assert!(!self.source.as_ref().unwrap().is_closed()); let self_ptr = core::ptr::from_mut(self).cast::(); @@ -1347,14 +1326,12 @@ impl WindowsBufferedReader { /// SAFETY: `pipe` must be a `Box`-allocated pointer; ownership /// transfers to `self.source` (later freed via `close_and_destroy`). #[cfg(windows)] - #[allow(dead_code)] pub unsafe fn start_with_pipe(&mut self, pipe: *mut uv::Pipe) -> sys::Result<()> { // SAFETY: caller contract — Box-allocated, ownership transfers. self.source = Some(Source::Pipe(unsafe { bun_core::heap::take(pipe) })); self.start_with_current_pipe() } - #[allow(dead_code)] pub fn start(&mut self, fd: Fd, _: bool) -> sys::Result<()> { debug_assert!(self.source.is_none()); // Use the event loop from the parent, not the global one @@ -1369,14 +1346,12 @@ impl WindowsBufferedReader { self.start_with_current_pipe() } - #[allow(dead_code)] pub fn start_file_offset(&mut self, fd: Fd, poll: bool, offset: usize) -> sys::Result<()> { self._offset = offset; self.flags.insert(WindowsFlags::USE_PREAD); self.start(fd, poll) } - #[allow(dead_code)] pub fn set_raw_mode(&mut self, value: bool) -> sys::Result<()> { let Some(source) = self.source.as_mut() else { return sys::Result::Err(sys::Error { @@ -1711,7 +1686,6 @@ impl WindowsBufferedReader { #[cfg(not(windows))] pub fn start_reading(&mut self) -> sys::Result<()> { - // TODO(port): Windows-only path; stubbed on non-Windows so the type still compiles. sys::Result::Ok(()) } @@ -1779,9 +1753,7 @@ impl WindowsBufferedReader { self.flags.insert(WindowsFlags::IS_PAUSED); } #[cfg(not(windows))] - _ => { - // TODO(port): Pipe/Tty arms are Windows-only. - } + _ => {} } // self.source already None via take(). if CALL_DONE { @@ -1816,7 +1788,6 @@ impl WindowsBufferedReader { /// Explicit teardown that does **not** fire `on_reader_done` (unlike /// [`close`]). Mirrors Zig `WindowsBufferedReader.deinit`. Safe to call /// before Drop; both paths are idempotent over an already-taken source. - #[allow(dead_code)] pub fn deinit(&mut self) { MaxBuf::remove_from_pipereader(&mut self.maxbuf); self._buffer = Vec::new(); @@ -1915,17 +1886,14 @@ impl WindowsBufferedReader { } } - #[allow(dead_code)] pub fn pause(&mut self) { let _ = self.stop_reading(); } - #[allow(dead_code)] pub fn unpause(&mut self) { let _ = self.start_reading(); } - #[allow(dead_code)] pub fn read(&mut self) { // we cannot sync read pipes on Windows so we just check if we are paused to resume the reading self.unpause(); diff --git a/src/io/PipeWriter.rs b/src/io/PipeWriter.rs index 4ee90d9487f..e9847356024 100644 --- a/src/io/PipeWriter.rs +++ b/src/io/PipeWriter.rs @@ -69,8 +69,6 @@ pub trait PosixPipeWriter { fn get_file_type(&self) -> FileType; fn get_force_sync(&self) -> bool; - // TODO(port): Zig accesses `parent.handle` (PollOrFd) directly for logging - // in on_poll. Expose via accessor instead of requiring a field. fn handle(&self) -> &PollOrFd; /// Only reads `get_file_type()` / `get_fd()` from `self`; takes `&self` so @@ -289,7 +287,6 @@ pub trait PosixBufferedWriterParent { /// # Safety /// `this` must point to a live `Self`. unsafe fn on_writable(_this: *mut Self) {} - // TODO(port): Zig calls `parent.eventLoop()` (returns anytype); pin a concrete type. /// # Safety /// `this` must point to a live `Self`. unsafe fn event_loop(this: *mut Self) -> EventLoopHandle; @@ -1848,7 +1845,6 @@ impl StreamBuffer { } pub fn write_type_as_bytes_assume_capacity(&mut self, data: T) { - // TODO(port): Zig round-trips through bun.Vec here; Rust just writes bytes. // PERF(port): was assume_capacity self.list.extend_from_slice(bun_core::bytes_of(&data)); } @@ -1953,19 +1949,14 @@ pub struct WindowsStreamingWriter { pub parent: *mut Parent, pub is_done: bool, // we use only one write_req, any queued data in outgoing will be flushed after this ends - #[allow(dead_code)] pub write_req: uv::uv_write_t, - #[allow(dead_code)] pub write_buffer: uv::uv_buf_t, // queue any data that we want to write here - #[allow(dead_code)] pub outgoing: StreamBuffer, // libuv requires a stable ptr when doing async so we swap buffers - #[allow(dead_code)] pub current_payload: StreamBuffer, // we preserve the last write result for simplicity - #[allow(dead_code)] pub last_write_result: WriteResult, // some error happed? we will not report onClose only onError pub closed_without_reporting: bool, @@ -2049,7 +2040,6 @@ impl WindowsStreamingWriter { /// would alias the live `&mut self` under Stacked Borrows. All vtable /// dispatch goes through `Parent::method(ptr, ..)` which takes `*mut Self`. #[inline] - #[allow(dead_code)] fn parent(&self) -> *mut Parent { self.parent } @@ -2069,7 +2059,6 @@ impl WindowsStreamingWriter { /// `Parent::on_error(Self::r(this).parent(), err)` dispatch blocks in /// `on_write_complete` / `on_fs_write_complete` / `process_send` into one. #[inline(always)] - #[allow(dead_code)] fn r_on_error(this: *mut Self, err: sys::Error) { let parent = Self::r(this).parent; // SAFETY: type invariant — set-once parent backref outlives writer. @@ -2080,7 +2069,6 @@ impl WindowsStreamingWriter { /// invariant and laundered-receiver rationale. Collapses the two /// `Parent::on_write` arms in `on_write_complete` into one `unsafe`. #[inline(always)] - #[allow(dead_code)] fn r_on_write(this: *mut Self, written: usize, status: WriteStatus) { let parent = Self::r(this).parent; // SAFETY: type invariant — set-once parent backref outlives writer. @@ -2094,7 +2082,6 @@ impl WindowsStreamingWriter { /// read order at each scopeguard site. Collapses the three /// `Parent::deref` blocks into one `unsafe`. #[inline(always)] - #[allow(dead_code)] fn r_deref(this: *mut Self) { let parent = Self::r(this).parent; // SAFETY: type invariant — set-once parent backref; ref taken in @@ -2103,17 +2090,14 @@ impl WindowsStreamingWriter { unsafe { Parent::deref(parent) } } - #[allow(dead_code)] pub fn memory_cost(&self) -> usize { mem::size_of::() + self.current_payload.memory_cost() + self.outgoing.memory_cost() } - #[allow(dead_code)] pub fn has_pending_data(&self) -> bool { self.outgoing.is_not_empty() || self.current_payload.is_not_empty() } - #[allow(dead_code)] fn on_write_complete(&mut self, status: uv::ReturnCode) { // PORT_NOTES_PLAN R-2: `&mut self` carries LLVM `noalias`, but // `Parent::on_write` (e.g. `FileSink::on_write`) re-enters JS via @@ -2405,10 +2389,7 @@ impl WindowsStreamingWriter { } } - #[allow(dead_code)] fn write_internal_u8(&mut self, buffer: &[u8], kind: WriteKind) -> WriteResult { - // TODO(port): Zig used `comptime writeFn: anytype` (fn-ptr identity); - // Rust splits into u8/u16 paths via WriteKind enum. if self.is_done { return WriteResult::Done(0); } @@ -2464,7 +2445,6 @@ impl WindowsStreamingWriter { self.last_write_result.clone() } - #[allow(dead_code)] fn write_internal_u16(&mut self, buffer: &[u16]) -> WriteResult { if self.is_done { return WriteResult::Done(0); @@ -2520,22 +2500,18 @@ impl WindowsStreamingWriter { self.last_write_result.clone() } - #[allow(dead_code)] pub fn write_utf16(&mut self, buf: &[u16]) -> WriteResult { self.write_internal_u16(buf) } - #[allow(dead_code)] pub fn write_latin1(&mut self, buffer: &[u8]) -> WriteResult { self.write_internal_u8(buffer, WriteKind::Latin1) } - #[allow(dead_code)] pub fn write(&mut self, buffer: &[u8]) -> WriteResult { self.write_internal_u8(buffer, WriteKind::Bytes) } - #[allow(dead_code)] pub fn flush(&mut self) -> WriteResult { if self.is_done { return WriteResult::Done(0); @@ -2548,7 +2524,6 @@ impl WindowsStreamingWriter { self.last_write_result.clone() } - #[allow(dead_code)] pub fn end(&mut self) { if self.is_done { return; diff --git a/src/io/lib.rs b/src/io/lib.rs index 29194df41ae..a85d2a3a344 100644 --- a/src/io/lib.rs +++ b/src/io/lib.rs @@ -6,9 +6,7 @@ // ════════════════════════════════════════════════════════════════════════════ // Loop / Poll / Waker / Closer / FilePoll-vtable / heap / pipes / MaxBuf / // openForWriting / PipeReader / PipeWriter compile on POSIX. `source` and the -// Windows*Reader/Writer impls are `#[cfg(windows)]`-gated (libuv-only). See -// TODO(port) notes for remaining shims (`bun_sys::syslog`, `bun_sys::Error::oom`, -// `bun_core::debug_warn`). +// Windows*Reader/Writer impls are `#[cfg(windows)]`-gated (libuv-only). // ════════════════════════════════════════════════════════════════════════════ #![allow(unsafe_op_in_unsafe_fn)] @@ -708,8 +706,6 @@ impl IoRequestLoop { panic!("Failed to create epoll file descriptor"); } loop_.epoll_fd = Fd::from_native(raw); - // TODO(port): Zig used `std.posix.epoll_create1` which already error-checks; here we - // only panic on negative, matching semantics. { // SAFETY: all-zero is a valid epoll_event (POD). @@ -1273,8 +1269,6 @@ macro_rules! intrusive_uv_fs { impl Default for Request { fn default() -> Self { - // TODO(port): Zig had `next: ?*Request = null, scheduled: bool = false` defaults - // but `callback` has no default; callers must overwrite `callback`. Self { next: bun_threading::Link::new(), callback: |_| unreachable!(), @@ -2043,7 +2037,6 @@ pub mod waker { /// Stand-in until `init()` runs (e.g. a `BundleThread` allocated before /// its real waker is created). `Fd::INVALID` is sentinel-only; never /// poll/wake through it. - #[allow(dead_code)] pub const fn placeholder() -> Self { Self { fd: Fd::INVALID } } @@ -2068,7 +2061,6 @@ pub mod waker { Self { fd } } - #[allow(dead_code)] pub fn wait(&self) { // eventfd reads are always exactly 8 bytes (u64 counter). Use a u64 // directly instead of type-punning through usize, which would be UB @@ -2211,12 +2203,10 @@ pub mod waker { /// `wake()`/`wait()`/`uv_loop()`. Mirrors `LinuxWaker::placeholder` / /// `KEventWaker::placeholder` so cross-platform call sites don't fall /// back to `mem::zeroed()` (UB for the niche-optimised `Option`). - #[allow(dead_code)] pub const fn placeholder() -> Self { Self { loop_: None } } - #[allow(dead_code)] pub fn init() -> Result { Ok(Self { loop_: Some(bun_ptr::BackRef::from( @@ -2234,7 +2224,6 @@ pub mod waker { self.loop_.expect("WindowsWaker used before init()") } - #[allow(dead_code)] pub fn wait(&self) { // Do NOT route through `WindowsLoop::wait(&mut self)`: that would // materialize a `&mut WindowsLoop` over the process-global @@ -2267,7 +2256,6 @@ pub mod waker { /// block at the call site. Mirrors Zig's `waker.loop.uv_loop` field /// chain (BundleThread.zig:79). #[inline] - #[allow(dead_code)] pub fn uv_loop(&self) -> *mut bun_sys::windows::libuv::Loop { // `BackRef` deref is safe (process-lifetime singleton); `uv_loop` // is a `Copy` field set once by C `us_create_loop`. diff --git a/src/io/openForWriting.rs b/src/io/openForWriting.rs index d905e590c18..926a7f8a9bb 100644 --- a/src/io/openForWriting.rs +++ b/src/io/openForWriting.rs @@ -189,7 +189,6 @@ where #[cfg(windows)] { - // TODO(port): bun_sys::windows::GetFileType *pollable = (bun_sys::windows::GetFileType(fd.native()) & bun_sys::windows::FILE_TYPE_PIPE) != 0 && !force_sync; diff --git a/src/io/pipes.rs b/src/io/pipes.rs index e07dfe6640d..7cb1e3ffb8e 100644 --- a/src/io/pipes.rs +++ b/src/io/pipes.rs @@ -51,9 +51,6 @@ impl PollOrFd { } } - // TODO(port): Zig's `comptime onCloseFn: anytype` allowed passing `void` for - // "no callback" (checked via `@TypeOf(onCloseFn) != void`). Represented here - // as `Option`; callers that passed `{}` should pass `None::`. pub fn close_impl( &mut self, ctx: Option<*mut c_void>, diff --git a/src/io/posix_event_loop.rs b/src/io/posix_event_loop.rs index c6af4e56b7a..630461f43bf 100644 --- a/src/io/posix_event_loop.rs +++ b/src/io/posix_event_loop.rs @@ -576,8 +576,6 @@ impl FilePoll { #[inline] pub fn can_ref(&self) -> bool { - // TODO(port): Zig checks `.disable` flag, but no such variant exists in Flags enum — - // dead code in Zig? Preserving as no-op false check. !self.flags.contains(Flags::HasIncrementedPollCount) } @@ -1252,7 +1250,6 @@ pub enum Flags { } pub type FlagsSet = enumset::EnumSet; -#[allow(dead_code)] pub type FlagsStruct = FlagsSet; impl Flags { @@ -1422,7 +1419,6 @@ impl Store { self.pending_free_tail = poll; let callback: OpaqueCallback = Self::process_deferred_frees_thunk; - // TODO(port): Zig asserts the callback slot is empty or already this fn. debug_assert!( vm.after_event_loop_callback().is_none() || vm.after_event_loop_callback().map(|f| f as usize) == Some(callback as usize) diff --git a/src/io/source.rs b/src/io/source.rs index c3a83d7b817..38a15e489b5 100644 --- a/src/io/source.rs +++ b/src/io/source.rs @@ -435,7 +435,6 @@ impl Source { errno: bun_sys::E::NOTSUP as _, syscall: bun_sys::Tag::uv_tty_set_mode, fd: self.get_fd(), - // TODO(port): bun_sys::Error remaining fields default ..Default::default() }), } diff --git a/src/js_parser/lexer.rs b/src/js_parser/lexer.rs index 3c08e85c22b..1ba724ae858 100644 --- a/src/js_parser/lexer.rs +++ b/src/js_parser/lexer.rs @@ -2760,7 +2760,6 @@ lexer_impl_header! { // if that invariant is ever broken — strictly safer than the raw cast). let utf16: &[u16] = bytemuck::cast_slice::(self.string_literal_raw_content); Ok(js_ast::E::String::init_utf16(utf16)) - // TODO(port): exact constructor name on js_ast::E::String for utf16 } StringLiteralRawFormat::NeedsDecode => { // string_literal_raw_content contains escapes (ie '\n') that need to be converted to their values (ie 0x0A). @@ -2803,7 +2802,6 @@ lexer_impl_header! { pub fn to_utf8_e_string(&mut self) -> Result { let mut res = self.to_e_string()?; res.to_utf8(self.arena)?; - // TODO(port): arena routing for E.String.toUTF8 Ok(res) } @@ -2849,7 +2847,6 @@ lexer_impl_header! { self.current, format_args!( "Duplicate flag \"{}\" in regular expression", - // TODO(port): {u} formatter — codepoint as char char::from_u32(self.code_point as u32) .unwrap_or('\u{FFFD}') ), @@ -3836,7 +3833,6 @@ lexer_impl_header! { // Filter out underscores; if underscore_count > 0 { let mut i: usize = 0; - // TODO(port): arena routing — Zig uses lexer.arena.alloc let bytes = self .arena .alloc_slice_fill_default::(text.len() - underscore_count); diff --git a/src/js_parser/p.rs b/src/js_parser/p.rs index 1f07f29859c..88d199bf5c2 100644 --- a/src/js_parser/p.rs +++ b/src/js_parser/p.rs @@ -3753,7 +3753,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O // from expression to binding should be written to "invalidLog" instead. That // way we can potentially keep this as an expression if it turns out it's not // needed as a binding after all. - // TODO(port): needs ArrayBinding (B.rs gated trait), Flags::PropertyInit fn convert_expr_to_binding( &mut self, expr: ExprNodeIndex, @@ -3899,7 +3898,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } } - // TODO(port): heavy body, depends on parse_*/visit_*/ImportScanner/full E surface pub fn convert_expr_to_binding_and_initializer( &mut self, _expr: &mut ExprNodeIndex, @@ -6241,8 +6239,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } pub fn jsx_import(&mut self, kind: JSXImport, loc: bun_ast::Loc) -> Expr { - // TODO(port): Zig used `switch (kind) { inline else => |field| ... @tagName(field) }`. - // We replicate via tag_name() helper on the enum. let ref_: Ref = match self.jsx_imports.get_with_tag(kind) { Some(existing) => existing, None => { @@ -8209,8 +8205,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O .write_to_hasher(&mut ctx.hasher, self.symbols.as_mut_slice()); } } else { - // TODO(port): Zig used `inline .e_identifier, .e_import_identifier, .e_commonjs_export_identifier => |id, tag|` - // with @unionInit. We expand the three arms. match &hook_call.target.data { js_ast::ExprData::EIdentifier(id) => { let gop = ctx.user_hooks.get_or_put(id.ref_).expect("oom"); diff --git a/src/js_parser/parse/parse_jsx.rs b/src/js_parser/parse/parse_jsx.rs index 083595de43d..15686b1d835 100644 --- a/src/js_parser/parse/parse_jsx.rs +++ b/src/js_parser/parse/parse_jsx.rs @@ -347,7 +347,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O let end_tag = JSXTag::parse(p)?; if end_tag.name != tag.name { - // TODO(port): arena param dropped from Zig signature. p.log().add_range_error_fmt_with_note( Some(p.source), end_tag.range, diff --git a/src/js_parser/parse/parse_property.rs b/src/js_parser/parse/parse_property.rs index 0362675f141..53b79617d0d 100644 --- a/src/js_parser/parse/parse_property.rs +++ b/src/js_parser/parse/parse_property.rs @@ -144,7 +144,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O PropertyKind::Get => { if args.len() > 0 { let r = js_lexer::range_of_identifier(p.source, args[0].binding.loc); - // TODO(port): Zig used p.keyNameForError(key) inline; borrowck reshape — pre-compute name. let key_name = p.key_name_for_error(key); p.log().add_range_error_fmt( Some(p.source), diff --git a/src/js_parser/parse/parse_stmt.rs b/src/js_parser/parse/parse_stmt.rs index 04df0ee6bc6..f564c83b437 100644 --- a/src/js_parser/parse/parse_stmt.rs +++ b/src/js_parser/parse/parse_stmt.rs @@ -1297,7 +1297,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O bun_core::fmt::fmt_identifier(path_name.non_unique_name_string_base()) ) .expect("unreachable"); - // TODO(port): store_name_in_ref expects arena-owned slice; verify lifetime p.store_name_in_ref(p.arena.alloc_slice_copy(&buf))? }; diff --git a/src/js_parser/parse/parse_typescript.rs b/src/js_parser/parse/parse_typescript.rs index e52f86a4d02..a766177d7c4 100644 --- a/src/js_parser/parse/parse_typescript.rs +++ b/src/js_parser/parse/parse_typescript.rs @@ -231,8 +231,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O is_typescript_declare: opts.is_typescript_declare, ..ParseStatementOptions::default() }; - // TODO(port): Zig `ListManaged.fromOwnedSlice` adopts the slice in-place; - // `parse_stmts_up_to` already returns a BumpVec<'a, Stmt> so just take it. stmts = p.parse_stmts_up_to(T::TCloseBrace, &mut _opts)?; p.lexer.next()?; } @@ -558,8 +556,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O }; // Generate the namespace object - // TODO(port): Zig `var arg_ref: Ref = undefined;` — initialized to NONE here; only read on - // paths where it has been assigned below. let mut arg_ref: Ref = Ref::NONE; let mut ts_namespace: js_ast::StoreRef = p.get_or_create_exported_namespace_members(name_text, opts.is_export, true); @@ -585,8 +581,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O // Parse the body let mut values: BumpVec<'_, EnumValue> = BumpVec::new_in(p.arena); while p.lexer.token != T::TCloseBrace { - // TODO(port): Zig `name = undefined` — placeholder empty slice; always overwritten or - // we return SyntaxError before use. let mut value = EnumValue { loc: p.lexer.loc(), ref_: Ref::NONE, diff --git a/src/js_parser/parser.rs b/src/js_parser/parser.rs index 303bd056bf6..f6b33a185f4 100644 --- a/src/js_parser/parser.rs +++ b/src/js_parser/parser.rs @@ -620,7 +620,6 @@ pub use js_ast::Op::Level; pub use crate::lexer as js_lexer; pub use js_lexer::T; -// TODO(port): defines arrives from move-in (was bun_bundler::defines → js_parser) use crate::defines::Define; // ────────────────────────────────────────────────────────────────────────── @@ -2071,10 +2070,6 @@ impl Default for Jest { // '../../build/macos-x86_64/bun node_modules/react-dom/cjs/react-dom.development.js --resolve=disable' ran // 1.02 ± 0.07 times faster than '../../bun.before-comptime-js-parser node_modules/react-dom/cjs/react-dom.development.js --resolve=disable' // -// TODO(port): `NewParser` is a Zig comptime type-generating fn parametrised by -// a struct of bools (jsx/typescript/scan_only). The Rust port in `ast/P.rs` -// will expose this via const generics or a marker-type strategy; these aliases -// pin the eight monomorphizations. // `NewParser!` Zig comptime-type-fn lowering: named aliases now live in // `ast/Parser.rs` (where the JsxT ZSTs are in scope). Re-export here. pub use crate::parse::parse_entry::{ diff --git a/src/js_parser/scan/scan_symbols.rs b/src/js_parser/scan/scan_symbols.rs index bd529ea77ad..9bc6e55fea2 100644 --- a/src/js_parser/scan/scan_symbols.rs +++ b/src/js_parser/scan/scan_symbols.rs @@ -136,9 +136,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O .module_scope_mut() .get_or_put_member_with_hash(name, hash) .value_ptr = js_ast::scope::Member { ref_: new_ref, loc }; - // TODO(port): the line above conflates key_ptr/value_ptr writes from Zig's - // `gpe.key_ptr.* = name; gpe.value_ptr.* = Scope.Member{...}` — verify - // get_or_put_member_with_hash's Rust API shape. declare_loc = loc; diff --git a/src/js_parser/visit/visit_binary.rs b/src/js_parser/visit/visit_binary.rs index 7eba9ff3e2f..7591c25a41c 100644 --- a/src/js_parser/visit/visit_binary.rs +++ b/src/js_parser/visit/visit_binary.rs @@ -536,7 +536,6 @@ impl BinaryExpressionVisitor { if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data) { return p.new_expr( - // TODO(port): math arrives from move-in (was bun_jsc::math → js_parser) E::Number { value: bun_ast::math::pow(vals[0], vals[1]), }, diff --git a/src/js_parser/visit/visit_expr.rs b/src/js_parser/visit/visit_expr.rs index cc6b005dac9..90de364837d 100644 --- a/src/js_parser/visit/visit_expr.rs +++ b/src/js_parser/visit/visit_expr.rs @@ -540,11 +540,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O e_.children.truncate(last_child as usize); } - // TODO(port): jsxChildrenKeyData in Zig is a mutable `var` of `Expr.Data` - // pointing at `Prefill.String.Children`. ExprData::EString wants a - // `StoreRef` (arena-backed) so a process-static won't compile (see - // P.rs `` ~7552). Allocate via `p.new_expr` from the const - // `prefill::string::CHILDREN` instead — small extra alloc. // PERF(port): was process-static — profile if it shows up on a hot path let children_key = p.new_expr(prefill::string::CHILDREN, expr.loc); diff --git a/src/js_printer/lib.rs b/src/js_printer/lib.rs index 9d3ba4e602e..e1dc61ab68d 100644 --- a/src/js_printer/lib.rs +++ b/src/js_printer/lib.rs @@ -957,9 +957,6 @@ pub fn estimate_length_for_utf8(input: &[u8], ascii_only: bool, quote_char: u8) // The branch above already handled the loop body; falling out of the loop with no // iterations means "no escapes anywhere". } - // TODO(port): the original `while ... else { return remaining.len + 2 }` returns early when - // index_of_needs_escape returns null at the *first* check. The current shape returns `len` - // (which equals 2) plus nothing for `remaining`. Match Zig precisely. len + remaining.len() } @@ -1003,8 +1000,6 @@ pub fn write_pre_quoted_string_inner( where W: Write + ?Sized, { - // TODO(port): for ENCODING == Utf16, Zig reinterprets `text_in` as []const u16 via bytesAsSlice. - // In Rust we keep `text_in: &[u8]` and index by code-unit width below. debug_assert!( !(json && quote_char != b'"'), "for json, quote_char must be '\"'" @@ -1224,9 +1219,6 @@ pub fn write_json_string( // SourceMapHandler / Options — gated on bun_sourcemap::Chunk::Builder and the // real bun_js_parser::{runtime, Ast::*} surface. // ─────────────────────────────────────────────────────────────────────────── -// TODO(port): bun_sourcemap::Chunk::Builder -// TODO(port): bun_ast::runtime::Runtime::Imports -// TODO(port): bun_ast::Ast::CommonJSNamedExports pub struct SourceMapHandler<'a> { pub ctx: NonNull<()>, pub callback: fn(*mut (), SourceMap::Chunk, &bun_ast::Source) -> Result<(), bun_core::Error>, @@ -1294,7 +1286,6 @@ pub struct Options<'a> { pub module_hash: u32, pub source_path: Option>, // allocator dropped — global mimalloc (this is an AST crate but Options.allocator is the global default) - // TODO(port): source_map_allocator was Option; arena-backed in some callers pub source_map_handler: Option>, pub source_map_builder: Option<&'a mut SourceMap::chunk::Builder>, // TODO(port): bun_options_types::schema::api::CssInJsBehavior — local stand-in. @@ -4698,9 +4689,7 @@ pub mod __gated_printer { initializer: item_in.initializer, // PERF(port): Vec not Copy — re-slice instead of move. ts_decorators: bun_alloc::AstAlloc::vec(), - // TODO(port): ts_decorators not used by the printer; Vec is !Copy so omit the copy. ts_metadata: Default::default(), - // TODO(port): ts_metadata not used by the printer; not Copy. }; if !IS_JSON { if item.kind == G::PropertyKind::Spread { @@ -6892,9 +6881,6 @@ pub mod __gated_printer { }; self.print_decls(keyword, decls, ExprFlag::none(), tlm); self.print_semicolon_after_statement(); - // TODO(port): bun_ast::runtime::Imports::__export — the - // full `runtime.rs` is ``-gated upstream; the active - // `parser.rs::Runtime::Imports` stub is a fieldless unit struct. if REWRITE_ESM_TO_CJS && is_export && !decls.is_empty() { // PORT NOTE: Zig stored `?GeneratedSymbol`; the Rust `runtime::Imports` @@ -7706,7 +7692,6 @@ pub struct DirectWriter { impl DirectWriter { pub fn write(&mut self, buf: &[u8]) -> Result { - // TODO(port): Zig used std.posix.write directly. Route via bun_sys::write. bun_sys::write(self.handle, buf) .map_err(|e| bun_core::Error::from_errno(i32::from(e.errno))) } @@ -7976,7 +7961,6 @@ pub fn get_source_map_builder( tree: &Ast, ) -> SourceMap::chunk::Builder { if generate_source_map == GenerateSourceMap::Disable { - // TODO(port): Zig returned `undefined` here. return SourceMap::chunk::Builder::default(); } @@ -8479,7 +8463,6 @@ pub fn print_with_writer_and_platform< if let Err(err) = printer.writer.done() { // In bundle_v2, this is backed by an arena, but incremental uses // `dev.allocator` for this buffer, so it must be freed. - // TODO(port): printer.source_map_builder.source_map.ctx.data.deinit() — Drop handles. return PrintResult::Err(err); } diff --git a/src/js_printer/renamer.rs b/src/js_printer/renamer.rs index 98f6c61e54e..b0a22ac298d 100644 --- a/src/js_printer/renamer.rs +++ b/src/js_printer/renamer.rs @@ -710,7 +710,6 @@ impl NumberRenamer { ) { let mut s: *mut NumberScope = initial_scope; let mut scope = scope_; - // TODO(port): defer cleanup of `s` if s != initial_scope — handled at end loop { let symbol_count = scope.members.count() + scope.generated.len_u32() as usize; diff --git a/src/jsc/AbortSignal.rs b/src/jsc/AbortSignal.rs index 66615cb4273..e4f7d1d25b3 100644 --- a/src/jsc/AbortSignal.rs +++ b/src/jsc/AbortSignal.rs @@ -73,8 +73,6 @@ unsafe extern "C" { /// Trait expressing the Zig `comptime cb: *const fn (*Context, JSValue) void` /// monomorphization for `listen`. Implement on your context type. -// TODO(port): Zig used a comptime fn-pointer param; Rust has no const fn-ptr -// generics, so callers implement this trait instead. pub trait AbortListener { fn on_abort(&mut self, reason: JSValue); } diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index 5f104240164..f43552ed7d7 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -95,11 +95,6 @@ pub struct ConsoleObject { stderr_buffer: [u8; 4096], stdout_buffer: [u8; 4096], - // TODO(port): Zig stores `Adapter` structs for the old→new `std.Io.Writer` - // bridge plus self-referential `*std.Io.Writer` pointers into them. In Rust - // we restructure as direct buffered writer fields and expose them via - // `error_writer()` / `writer()` getters (LIFETIMES.tsv: BORROW_FIELD → - // self-ref; restructure as getter). error_writer_backing: Output::QuietWriterAdapter, writer_backing: Output::QuietWriterAdapter, @@ -1929,10 +1924,6 @@ pub mod formatter { impl core::fmt::Display for ZigFormatter<'_, '_> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - // TODO(port): Zig writes through `*std.Io.Writer`; here we go - // through `core::fmt::Write`. A `bun_io::Write` adapter for - // `core::fmt::Formatter` would keep the byte path. - // // Move the unique `&mut Formatter` out of the cell for the body; // re-seat it (and clear `remaining_values`) on the way out so the // adapter mirrors Zig's `defer` and stays reusable. @@ -1947,7 +1938,6 @@ pub mod formatter { let result = (|| { let tag = Tag::get(self.value, formatter.global_this).map_err(|_| core::fmt::Error)?; - // TODO(port): need a `&mut dyn bun_io::Write` over `f`. let mut sink = bun_io::FmtAdapter::new(f); let global = formatter.global_this; formatter @@ -2540,10 +2530,6 @@ pub mod formatter { } impl<'a> Formatter<'a> { - // TODO(port): Zig parameterizes over `Slice` (`[]const u8` or `[]const u16`) - // via `comptime Slice: type`. Only the `&[u8]` path is handled here; the - // UTF-16 path was unused at the call site (`slice` always comes from - // `toSlice` → UTF-8). fn write_with_formatting( &mut self, writer_: &mut dyn bun_io::Write, diff --git a/src/jsc/DOMFormData.rs b/src/jsc/DOMFormData.rs index 9033a3e080b..ce185f221fe 100644 --- a/src/jsc/DOMFormData.rs +++ b/src/jsc/DOMFormData.rs @@ -158,7 +158,6 @@ impl DOMFormData { ctx_(unsafe { *name_ }, value); } - // TODO(port): jsc.markBinding(@src()) — debug-only binding tracker; no Rust equivalent yet. // C++ invokes the callback synchronously and does not retain `ctx` or the fn // pointer past this call. DOMFormData__forEach( diff --git a/src/jsc/ErrorCode.rs b/src/jsc/ErrorCode.rs index e0a745a8eee..43f0c78ed2a 100644 --- a/src/jsc/ErrorCode.rs +++ b/src/jsc/ErrorCode.rs @@ -1374,9 +1374,6 @@ static CODE_STR: [&str; ErrorCode::COUNT as usize] = [ // Legacy anyerror-wrapper sentinels (src/jsc/ErrorCode.zig). // ────────────────────────────────────────────────────────────────────────── impl ErrorCode { - // TODO(port): bun_core::Error::as_u16 — bun_core::Error is currently the - // wide errno-carrying struct, not the NonZeroU16 anyerror code. Use errno as a - // stand-in until the interning table lands. pub const PARSER_ERROR: ErrorCodeInt = 0xFFFE; pub const JS_ERROR_OBJECT: ErrorCodeInt = 0xFFFD; diff --git a/src/jsc/FetchHeaders.rs b/src/jsc/FetchHeaders.rs index 719549a0249..cec2b5d26d6 100644 --- a/src/jsc/FetchHeaders.rs +++ b/src/jsc/FetchHeaders.rs @@ -146,7 +146,6 @@ impl FetchHeaders { global: &JSGlobalObject, value: JSValue, ) -> JsResult>> { - // TODO(port): bun.jsc.fromJSHostCallGeneric — wraps the FFI call and converts a pending VM exception into JsError host_fn::from_js_host_call_generic(global, || { NonNull::new(WebCore__FetchHeaders__createFromJS(global, value)) }) diff --git a/src/jsc/HTTPServerAgent.rs b/src/jsc/HTTPServerAgent.rs index 7ebc2750f3a..e396aa4fb9b 100644 --- a/src/jsc/HTTPServerAgent.rs +++ b/src/jsc/HTTPServerAgent.rs @@ -6,7 +6,6 @@ use bun_core::String as BunString; pub struct HTTPServerAgent { /// Underlying C++ agent. Set to null when not enabled. - // TODO(port): lifetime — FFI-owned C++ opaque; raw ptr is correct here pub agent: Option>, /// This becomes the "server ID" field. diff --git a/src/jsc/JSFunction.rs b/src/jsc/JSFunction.rs index 8ed471cd4c3..d1ea2c0b41a 100644 --- a/src/jsc/JSFunction.rs +++ b/src/jsc/JSFunction.rs @@ -65,10 +65,6 @@ unsafe extern "C" { } impl JSFunction { - // TODO(port): Zig accepted `implementation` as either `JSHostFnZig` (safe) or - // `JSHostFn` (raw ABI) via comptime `@TypeOf` dispatch, calling `jsc.toJSHostFn` - // for the safe form. In Rust, callers produce a `JSHostFn` via `#[bun_jsc::host_fn]`, - // so we take the raw fn pointer type directly. pub fn create( global: &JSGlobalObject, fn_name: impl Into, diff --git a/src/jsc/JSPromise.rs b/src/jsc/JSPromise.rs index bad936f179d..60276eebdf3 100644 --- a/src/jsc/JSPromise.rs +++ b/src/jsc/JSPromise.rs @@ -91,8 +91,6 @@ impl Default for Weak { impl Weak { pub fn reject(&mut self, global: &JSGlobalObject, val: JSValue) { - // TODO(port): Zig discards the `JSTerminated` from `JSPromise::reject` here - // (return type is `void`). Mirror that by ignoring the Result. let _ = self.swap().reject(global, Ok(val)); } @@ -230,9 +228,6 @@ impl Strong { } // Zig: `pub const rejectOnNextTick = @compileError("...")` - // TODO(port): @compileError poison-decl has no direct Rust equivalent. Relying on - // the method simply not existing; callers will fail to compile. A - // `#[deprecated(note = "...")]` shim could be added if migration error messages are needed. pub fn resolve(&mut self, global: &JSGlobalObject, val: JSValue) -> Result<(), JsTerminated> { self.swap().resolve(global, val) diff --git a/src/jsc/JSRef.rs b/src/jsc/JSRef.rs index 5e6947d230f..29cfdbdacac 100644 --- a/src/jsc/JSRef.rs +++ b/src/jsc/JSRef.rs @@ -108,8 +108,6 @@ pub enum JsRef { // Belt-and-suspenders: JSValue and Strong are already !Send/!Sync, but make it // explicit so a future refactor of those types cannot accidentally make JsRef // sendable. -// TODO(port): if a zero-cost marker is preferred over auto-trait inference, -// wrap in a struct with `PhantomData<*const ()>`. const _: PhantomData<*const ()> = PhantomData; impl JsRef { diff --git a/src/jsc/JSString.rs b/src/jsc/JSString.rs index adaf5cf7edb..7351771d607 100644 --- a/src/jsc/JSString.rs +++ b/src/jsc/JSString.rs @@ -78,8 +78,6 @@ impl JSString { // an owned UTF-8 copy so the result outlives the GC'd JSString. Returning // `to_slice()` here (a borrow that may alias JSC-owned memory) would hand // callers a use-after-free once the cell is collected. - // TODO(port): un-gate once `bun_core::ZigString::to_slice_clone` is - // ported; gated so wrong-semantics fallback cannot be called. pub fn to_slice_clone(&self, global: &JSGlobalObject) -> JsResult { let mut str = ZigString::init(b""); @@ -90,8 +88,6 @@ impl JSString { // Spec (JSString.zig:54-62): `str.toSliceZ(allocator)` guarantees a `[:0]` // sentinel. `to_slice()` is not NUL-terminated; passing it to a C API that // expects one reads past the buffer end. - // TODO(port): un-gate once `bun_core::ZigString::to_slice_z` is - // ported; gated so wrong-semantics fallback cannot be called. pub fn to_slice_z(&self, global: &JSGlobalObject) -> ZigStringSlice { let mut str = ZigString::init(b""); diff --git a/src/jsc/array_buffer.rs b/src/jsc/array_buffer.rs index af27bfc598f..0541d38e7de 100644 --- a/src/jsc/array_buffer.rs +++ b/src/jsc/array_buffer.rs @@ -899,15 +899,10 @@ impl TypedArrayType { #[derive(Default)] pub struct MarkedArrayBuffer { pub buffer: ArrayBuffer, - // TODO(port): Zig stores `?std.mem.Allocator` to track ownership of the byte buffer. - // In Rust the global allocator is implicit; we keep a bool flag so `destroy` knows - // whether to mi_free the backing storage. pub owns_buffer: bool, pub pinned: bool, } -// TODO(port): Zig `ArrayBuffer.Stream = std.io.FixedBufferStream([]u8)`. -// `std::io::Cursor<&mut [u8]>` is the closest in-memory equivalent. // Hoisted to module scope (inherent associated type aliases are unstable). pub(crate) type ArrayBufferStream<'a> = std::io::Cursor<&'a mut [u8]>; diff --git a/src/jsc/config.rs b/src/jsc/config.rs deleted file mode 100644 index 0dcf1b0493e..00000000000 --- a/src/jsc/config.rs +++ /dev/null @@ -1,16 +0,0 @@ -// PORT NOTE: Zig `DefaultBunDefines` is a namespace-only struct with nested -// namespace-only structs. Ported as nested modules; inner consts were NOT `pub` -// in the Zig source, mirrored here. -#[allow(non_snake_case, dead_code)] -pub mod DefaultBunDefines { - #[allow(non_snake_case)] - pub mod Keys { - const WINDOW: &[u8] = b"window"; - } - #[allow(non_snake_case)] - pub mod Values { - const WINDOW: &[u8] = b"undefined"; - } -} - -// ported from: src/jsc/config.zig diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index 304e3448cae..b19b78e8465 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -47,7 +47,6 @@ pub use crate::work_task::{WorkTask, WorkTaskContext}; bun_core::declare_scope!(EventLoop, hidden); -// TODO(port): bun.LinearFifo(Task, .Dynamic) — std.fifo.LinearFifo pub type Queue = bun_collections::LinearFifo>; diff --git a/src/jsc/host_fn.rs b/src/jsc/host_fn.rs index b4514c51781..57d90c6b6ac 100644 --- a/src/jsc/host_fn.rs +++ b/src/jsc/host_fn.rs @@ -104,14 +104,12 @@ pub use { // const fn pointer without a proc-macro (no `const fn` ABI thunks). Callers use // `#[bun_jsc::host_fn]` instead, which emits the shim and calls // `to_js_host_fn_result` for the body. -// TODO(port): proc-macro — `#[bun_jsc::host_fn]` replaces `toJSHostFn`. #[doc(hidden)] pub const fn to_js_host_fn(_function_to_wrap: JsHostFnZig) -> ! { panic!("use #[bun_jsc::host_fn] instead of to_js_host_fn()"); } // Zig: `pub fn toJSHostFnWithContext(comptime ContextType: type, comptime Function: ...) ...` -// TODO(port): proc-macro — `#[bun_jsc::host_fn(method)]` replaces `toJSHostFnWithContext`. #[doc(hidden)] pub const fn to_js_host_fn_with_context(_function: JsHostFnZigWithContext) -> ! { panic!("use #[bun_jsc::host_fn(method)] instead of to_js_host_fn_with_context()"); @@ -860,7 +858,6 @@ pub fn new_function_with_data( jsc::mark_binding(); // Zig: `toJSHostFn(function)` wrapped a `comptime JSHostFnZig` here. In Rust the // caller passes an already-wrapped `JsHostFn` (produced by `#[bun_jsc::host_fn]`). - // TODO(port): proc-macro — callers must apply `#[bun_jsc::host_fn]` themselves. private::Bun__CreateFFIFunctionWithDataValue( global_object, symbol_name, diff --git a/src/jsc/hot_reloader.rs b/src/jsc/hot_reloader.rs index d358dabdc99..69d98e14111 100644 --- a/src/jsc/hot_reloader.rs +++ b/src/jsc/hot_reloader.rs @@ -790,7 +790,6 @@ where if cfg!(feature = "debug_logs") { bun_core::scoped_log!(hot_reloader, "{}", args); } else { - // TODO(port): Output.prettyErrorln with color tags bun_core::pretty_errorln!("watcher: {}", args); } } diff --git a/src/jsc/lib.rs b/src/jsc/lib.rs index 74a036683a7..1f10634d4a5 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -52,7 +52,6 @@ pub use bun_jsc_macros::{JsClass, JsClassDerive, codegen_cached_accessors, host_ /// — `extern "..."` takes a string literal, not an expression. The /// `#[bun_jsc::host_fn]` / `#[bun_jsc::host_call]` attribute macros emit the /// correct ABI per-target instead. See PORTING.md §FFI / §JSC types. -// TODO(port): proc-macro — `conv` is encoded in #[bun_jsc::host_fn] / #[bun_jsc::host_call]. #[cfg(all(windows, target_arch = "x86_64"))] pub const CONV: &str = "sysv64"; #[cfg(not(all(windows, target_arch = "x86_64")))] @@ -98,8 +97,6 @@ pub mod sizes; pub mod source_provider; #[path = "SourceType.rs"] pub mod source_type; -#[path = "static_export.rs"] -pub mod static_export; #[path = "TextCodec.rs"] pub mod text_codec; #[path = "URLSearchParams.rs"] @@ -560,8 +557,6 @@ pub mod codegen_mod; pub mod comptime_string_map_jsc; #[path = "ConcurrentPromiseTask.rs"] pub mod concurrent_promise_task; -#[path = "config.rs"] -pub mod config; #[path = "EventLoopHandle.rs"] pub mod event_loop_handle; #[path = "FFI.rs"] @@ -2124,7 +2119,6 @@ pub fn opaque_wrap() -> OpaqueCallback where F: FnTyped, { - // TODO(port): Zig used `comptime Function: fn(*Context) void` as a value param. extern "C" fn callback>(ctx: *mut c_void) { // SAFETY: caller guarantees ctx is a valid *mut Context. let context: &mut Context = unsafe { bun_ptr::callback_ctx::(ctx) }; @@ -2146,7 +2140,6 @@ pub type Error = ErrorCode; /// Maximum Date in JavaScript is less than Number.MAX_SAFE_INTEGER (u52). pub const INIT_TIMESTAMP: JSTimeType = (1u64 << 52) - 1; -// TODO(port): Zig u52 — Rust has no u52. Using u64. pub type JSTimeType = u64; /// `jsc.zig:245 toJSTime(sec, nsec)`. Zig: `@intCast` (safety-checked sign diff --git a/src/jsc/static_export.rs b/src/jsc/static_export.rs deleted file mode 100644 index 15588160bc8..00000000000 --- a/src/jsc/static_export.rs +++ /dev/null @@ -1,46 +0,0 @@ -use core::marker::PhantomData; - -// PORT NOTE: The Zig source is a file-level struct holding *comptime* metadata -// (two `type` fields + two string literals) used to drive `@export` generation. -// Rust has no `type`-valued fields; the closest shape is a generic struct with -// PhantomData markers. In practice this whole mechanism is superseded in Rust by -// `#[unsafe(no_mangle)] pub extern "C" fn ...` at the definition site. -// TODO(refactor): delete this type outright once callers are migrated. - -pub struct StaticExport { - // Zig: `Type: type` - pub ty: PhantomData, - // PORT NOTE: `&'static str` (not `&'static [u8]`) because these are always - // ASCII identifier literals and feed into const string concatenation below. - pub symbol_name: &'static str, - pub local_name: &'static str, - // Zig: `Parent: type` - pub parent: PhantomData

, -} - -impl StaticExport { - // TODO(port): `std.meta.declarationInfo(Parent, local_name)` is comptime - // reflection (`@typeInfo`) with no Rust equivalent. The consumer of this - // metadata should become a proc-macro / build-script. Stubbed to `()`. - pub const fn decl(&self) { - // TODO(port): proc-macro - } - - // Zig: `comptime "wrap" ++ this.symbol_name` - // PORT NOTE: const string concatenation over a *field* is not expressible - // in stable Rust. Return an owned `String` so the caller controls the - // lifetime — `Box::leak` is forbidden per docs/PORTING.md (it would leak a - // fresh allocation on every call, whereas the Zig original is a single - // comptime-interned constant). Callers holding a literal should prefer - // `const_format::concatcp!("wrap", SYM)` to recover the comptime semantics. - // TODO(refactor): replace this whole mechanism with `#[no_mangle]` + proc-macro. - // PERF(port): was comptime `++` (zero-cost) — profile if it shows up on a hot path. - pub fn wrapped_name(&self) -> String { - let mut s = String::with_capacity(4 + self.symbol_name.len()); - s.push_str("wrap"); - s.push_str(self.symbol_name); - s - } -} - -// ported from: src/jsc/static_export.zig diff --git a/src/libarchive/lib.rs b/src/libarchive/lib.rs index 95bb465b3b4..3028985f47c 100644 --- a/src/libarchive/lib.rs +++ b/src/libarchive/lib.rs @@ -1077,9 +1077,6 @@ pub enum Seek { } pub struct BufferReadStream { - // TODO(port): lifetime — `buf` is borrowed for the stream's lifetime (callers - // construct on stack, init, defer deinit). Stored as raw fat ptr to avoid - // a struct lifetime param. buf: *const [u8], pos: usize, @@ -1505,9 +1502,6 @@ pub mod archiver { pub use archiver::{Context, ExtractOptions, Plucker}; -// TODO(port): Zig used `comptime FilePathAppender: type` + `@hasDecl` duck-typing -// for `onFirstDirectoryName` / `appendMutable` / `append`. Model as a trait with -// default no-op impls; the `void` ContextType becomes `()` which uses the defaults. pub trait ArchiveAppender { /// Mirrors `@hasDecl(Child, "onFirstDirectoryName")`. const HAS_ON_FIRST_DIRECTORY_NAME: bool = false; @@ -1664,10 +1658,6 @@ impl Archiver { let overwrite_entry = ctx.overwrite_list.get_or_put(path_to_use)?; if !overwrite_entry.found_existing { - // TODO(port): key ownership semantics — Zig stored the - // appender-owned slice as the map key. StringArrayHashMap - // already boxed `path_to_use` on insert; overwrite with the - // appender-owned bytes to match Zig lifetime intent. *overwrite_entry.key_ptr = Box::from(appender.append(path_to_use)?); } } @@ -1772,7 +1762,6 @@ impl Archiver { } // strip and normalize the path - // TODO(port): std.mem.tokenizeScalar(OSPathChar, pathname, '/') + .rest() // `pathname_z` is `&ZStr` on POSIX (`as_bytes() → &[u8]`) // and `&WStr` on Windows (`as_slice() → &[u16]`); both // deref to `&[OSPathChar]`. @@ -1829,7 +1818,6 @@ impl Archiver { normalized_buf[normalized_len] = 0; // SAFETY: we just wrote a NUL at normalized_buf[normalized_len] let path: &mut [OSPathChar] = &mut normalized_buf[..normalized_len]; - // TODO(port): Zig had `[:0]OSPathChar` here; the NUL is at path.len() if path.is_empty() || (path.len() == 1 && path[0] == b'.' as OSPathChar) { continue; } @@ -2253,8 +2241,6 @@ impl Archiver { appender: &mut A, options: ExtractOptions, ) -> Result { - // TODO(port): `options` was `comptime` in Zig — not used in a type position, - // so demoted to runtime. // PERF(port): was comptime monomorphization // TODO(port): narrow error set let dir: Fd = 'brk: { let cwd = Fd::cwd(); diff --git a/src/libdeflate_sys/libdeflate.rs b/src/libdeflate_sys/libdeflate.rs index 7dc7f5eea5e..d2641947c37 100644 --- a/src/libdeflate_sys/libdeflate.rs +++ b/src/libdeflate_sys/libdeflate.rs @@ -472,7 +472,6 @@ pub(crate) const LIBDEFLATE_BAD_DATA: c_uint = 1; pub(crate) const LIBDEFLATE_SHORT_OUTPUT: c_uint = 2; pub(crate) const LIBDEFLATE_INSUFFICIENT_SPACE: c_uint = 3; -// TODO(port): Zig uses `enum(c_uint)`; Rust cannot write `#[repr(c_uint)]`. // `u32` matches `c_uint` on all Bun targets. #[repr(u32)] #[derive(Copy, Clone, Eq, PartialEq)] diff --git a/src/lolhtml_sys/lol_html.rs b/src/lolhtml_sys/lol_html.rs index 53ca95f248c..34913fc842d 100644 --- a/src/lolhtml_sys/lol_html.rs +++ b/src/lolhtml_sys/lol_html.rs @@ -24,7 +24,6 @@ pub struct SourceLocationBytes { #[inline(always)] fn auto_disable() { - // TODO(port): bun_core::feature_flags::DISABLE_LOLHTML — comptime flag in Zig if bun_core::feature_flags::DISABLE_LOLHTML { unreachable!(); } @@ -222,8 +221,6 @@ impl HTMLRewriterBuilder { /// /// WARNING: Pointers passed to handlers are valid only during the /// handler execution. So they should never be leaked outside of handlers. - // TODO(port): Zig used comptime fn-value params to monomorphize trampolines per callback. - // Rust cannot take const fn pointers as const generics; modeled via DirectiveCallback trait. // PORT NOTE: handler-data params are `Option>`, not // `Option<&mut H>` — callers routinely pass the SAME allocation for // multiple slots (one `DocumentHandler` services doctype/comment/text/end), @@ -285,7 +282,6 @@ impl HTMLRewriterBuilder { /// /// WARNING: Pointers passed to handlers are valid only during the /// handler execution. So they should never be leaked outside of handlers. - // TODO(port): comptime fn-value params → trait-based trampolines (see add_document_content_handlers) // PORT NOTE: Zig also checked `handler != null` (in addition to `handler_data != null`); the trait // model assumes the handler is always present when data is Some, so (handler=null, data=non-null) // is unrepresentable here. @@ -327,8 +323,6 @@ impl HTMLRewriterBuilder { } } - // TODO(port): Zig took comptime Writer/Done fn-values; modeled via OutputSink trait - // // PORT NOTE: takes `*mut S` (not `&mut S`) so the userdata pointer stored // in the C rewriter retains the caller's raw-pointer provenance (typically // a `heap::alloc` root). If we took `&mut S`, the userdata would carry a diff --git a/src/md/blocks.rs b/src/md/blocks.rs index 26afe4b88f0..f4ced5313ee 100644 --- a/src/md/blocks.rs +++ b/src/md/blocks.rs @@ -984,7 +984,6 @@ impl Parser<'_> { dest: dest_dupe, title: title_dupe, }); - // TODO(port): Zig used `catch return` on push; Vec::push is infallible here } let mut newlines: u32 = 0; @@ -1028,8 +1027,6 @@ impl Parser<'_> { // get_block_header_at / get_block_at moved to parser.rs (shared by containers.rs). } -// TODO(port): `Line.type` field — Zig uses `.type`; Rust uses `r#type`. The variant -// type is assumed to be `types::LineType` re-exported here for brevity. use crate::types::LineType; // ported from: src/md/blocks.zig diff --git a/src/md/html_renderer.rs b/src/md/html_renderer.rs index 09ae2757110..b6076083baa 100644 --- a/src/md/html_renderer.rs +++ b/src/md/html_renderer.rs @@ -7,10 +7,6 @@ use crate::helpers; use crate::types; use crate::types::{BlockType, JsResult, Renderer, RendererImpl, SpanDetail, SpanType, TextType}; -// TODO(port): lifetime — `src_text` and `saved_img_title` borrow the caller's -// source buffer for the renderer's lifetime (never freed in Zig `deinit`). -// The porting guide discourages struct lifetimes, but raw `*const [u8]` is -// worse here; revisit if `'src` causes friction. pub(crate) struct HtmlRenderer<'src> { pub out: OutputBuffer, // allocator dropped — non-AST crate uses global mimalloc @@ -210,7 +206,6 @@ impl<'src> HtmlRenderer<'src> { BlockType::Li => self.write(b"\n"), BlockType::Hr => {} BlockType::H => { - // TODO(port): leave_heading() drops allocator param; returns Option<&[u8]>. if let Some(slug) = self.heading_tracker.leave_heading() { // Write opening tag with id self.out.write(match data { diff --git a/src/md/inlines.rs b/src/md/inlines.rs index c3b48dfb76d..f29d219f913 100644 --- a/src/md/inlines.rs +++ b/src/md/inlines.rs @@ -18,7 +18,6 @@ pub struct EmphDelim { pub open_count: usize, // total chars consumed as opener pub close_count: usize, // total chars consumed as closer // Individual match sizes in order (each is 1 for em, 2 for strong) - // TODO(port): Zig used u2 element type; Rust uses u8 — values are always 0..=2. pub open_sizes: [u8; MAX_EMPH_MATCHES], pub open_num: u8, // number of open matches (Zig: u4) pub close_sizes: [u8; MAX_EMPH_MATCHES], diff --git a/src/md/line_analysis.rs b/src/md/line_analysis.rs index 1daa98cd031..e8091adfc9c 100644 --- a/src/md/line_analysis.rs +++ b/src/md/line_analysis.rs @@ -355,7 +355,6 @@ impl Parser<'_> { return false; } pos += u32::try_from(tag.len()).expect("int cast"); - // TODO(port): if OFF != u32, adjust the cast above. if pos >= self.size { return true; } diff --git a/src/md/root.rs b/src/md/root.rs index 4d9f819c7b7..61b29fee847 100644 --- a/src/md/root.rs +++ b/src/md/root.rs @@ -209,12 +209,10 @@ impl Options { ]; } -// TODO(port): narrow error set — Zig: `parser.Parser.Error` pub fn render_to_html(text: &[u8]) -> Result, parser::ParserError> { render_to_html_with_options(text, Options::default()) } -// TODO(port): narrow error set — Zig: `parser.Parser.Error` pub fn render_to_html_with_options( text: &[u8], options: Options, @@ -223,7 +221,6 @@ pub fn render_to_html_with_options( } /// Parse and render using a custom renderer implementation. -// TODO(port): narrow error set — Zig: `parser.Parser.Error` pub fn render_with_renderer<'a>( text: &'a [u8], options: Options, diff --git a/src/md/types.rs b/src/md/types.rs index 25ffb715755..5d082a6f6c9 100644 --- a/src/md/types.rs +++ b/src/md/types.rs @@ -522,9 +522,6 @@ pub const CODESPAN_MARK_MAXLEN: u32 = 255; pub const TABLE_MAXCOLCOUNT: u32 = 128; /// Reference definition used for link resolution. -// TODO(port): `label_needs_free`/`title_needs_free` indicate sometimes-owned -// data (normalized label vs. source slice). Consider `Cow<'a, [u8]>` and drop -// the bool flags. pub struct RefDef<'a> { pub label: &'a [u8], pub title: Attribute<'a>, diff --git a/src/mimalloc_sys/mimalloc.rs b/src/mimalloc_sys/mimalloc.rs index cab0db3671d..8565dc4ee6b 100644 --- a/src/mimalloc_sys/mimalloc.rs +++ b/src/mimalloc_sys/mimalloc.rs @@ -496,8 +496,6 @@ pub const MI_SMALL_SIZE_MAX: usize = pub const MI_ALIGNMENT_MAX: c_ulong = (16 * 1024) * 1024; pub const MI_MAX_ALIGN_SIZE: usize = 16; -// TODO(port): Zig took `std.mem.Alignment` (log2 newtype). Rust callers pass the -// alignment in bytes directly; revisit if `bun_alloc` grows an `Alignment` type. #[inline] pub fn must_use_aligned_alloc(alignment: usize) -> bool { alignment > MI_MAX_ALIGN_SIZE diff --git a/src/options_types/bundle_enums.rs b/src/options_types/bundle_enums.rs index 97b8384e857..3029592afdd 100644 --- a/src/options_types/bundle_enums.rs +++ b/src/options_types/bundle_enums.rs @@ -76,8 +76,6 @@ impl Format { #[derive(Default)] pub struct WindowsOptions { pub hide_console: bool, - // TODO(port): lifetime — Zig `?[]const u8` fields with no `deinit` in this - // file; conservatively owned as Box<[u8]> here. pub icon: Option>, pub title: Option>, pub publisher: Option>, @@ -281,9 +279,6 @@ pub trait ImportKindExt: sealed::Sealed { impl ImportKindExt for bun_ast::ImportKind { fn to_api(self) -> api::ImportKind { use bun_ast::ImportKind; - // TODO(port): source Zig references `ImportKind.entry_point` which is not a declared variant - // (only entry_point_run / entry_point_build exist). This compiles in Zig only because the - // function is never analyzed. Mapping both entry-point variants to api::ImportKind::entry_point. match self { ImportKind::EntryPointRun | ImportKind::EntryPointBuild => api::ImportKind::entry_point, ImportKind::Stmt => api::ImportKind::stmt, @@ -304,7 +299,6 @@ impl ImportKindExt for bun_ast::ImportKind { /// inline source code. #[derive(Clone, Debug)] pub enum BuiltInModule { - // TODO(port): lifetime — Zig `[]const u8`; arena-owned in bake.UserOptions. Import(Box<[u8]>), Code(Box<[u8]>), } diff --git a/src/options_types/command_tag.rs b/src/options_types/command_tag.rs index 462182fd851..1c42bc83fe1 100644 --- a/src/options_types/command_tag.rs +++ b/src/options_types/command_tag.rs @@ -132,8 +132,6 @@ impl Tag { // unless invoked. Rust has no lazy decl resolution; re-exporting // `bun_runtime::cli::Command::{tag_params, tag_print_help}` here would create a // crate cycle (cli → options_types → cli). - // TODO(port): call sites of `cmd.params()` / `cmd.printHelp()` must call - // `bun_runtime::cli::Command::tag_params(cmd)` / `tag_print_help(cmd)` directly. } /// `.rodata` flag table indexed by [`Tag`] discriminant. These tables cost zero diff --git a/src/options_types/compile_target.rs b/src/options_types/compile_target.rs index 420048d7146..c7869cec074 100644 --- a/src/options_types/compile_target.rs +++ b/src/options_types/compile_target.rs @@ -90,8 +90,6 @@ impl fmt::Display for BaselineFormatter { } } -// TODO(port): impl From for bun_core::Error - #[derive(thiserror::Error, Debug, strum::IntoStaticStr)] pub enum ParseError { #[error("UnsupportedTarget")] @@ -429,9 +427,6 @@ impl CompileTarget { // PERF(port): was comptime monomorphization (inline else over os/arch/libc returning // anonymous struct const). Could generate static tables via macro_rules! or // const_format::concatcp! over OperatingSystem::name_string(). - // TODO(port): this needs a static [&[u8]; 3] per (os, arch, libc) combo — the os - // string is `"\"" ++ os.nameString() ++ "\""` and the version is - // `"\"" ++ Global.package_json_version ++ "\""`, both comptime in Zig. macro_rules! table { ($platform:literal, $arch:literal) => {{ const VALUES: &[&[u8]] = &[ @@ -455,7 +450,6 @@ impl CompileTarget { OperatingSystem::Windows => table!(b"\"win32\"", b"\"x64\""), OperatingSystem::Freebsd => table!(b"\"freebsd\"", b"\"x64\""), OperatingSystem::Wasm => table!(b"\"wasm\"", b"\"x64\""), - // TODO(port): verify os.nameString() values match these literals }, }, Architecture::Arm64 => match self.libc { diff --git a/src/options_types/schema.rs b/src/options_types/schema.rs index 41a07c00e83..8a798fd5150 100644 --- a/src/options_types/schema.rs +++ b/src/options_types/schema.rs @@ -62,8 +62,8 @@ pub mod api { pub use bun_dotenv::DotEnvBehavior; /// schema.zig:711 — `enum(u8)` (open). Kept closed. - /// Variants PascalCased to match the only downstream writers - /// (`jsc/config.rs`, `runtime/cli/Arguments.rs` → `api::ResolveMode::Lazy`). + /// Variants PascalCased to match the only downstream writer + /// (`runtime/cli/Arguments.rs` → `api::ResolveMode::Lazy`). #[repr(u8)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Default)] pub enum ResolveMode { @@ -125,8 +125,7 @@ pub mod api { /// `?[]const u8` → `Option>` /// `[]const []const u8` → `Vec>` /// `?[:0]const u8` → `Option>` (sentinel re-derived - /// at use-site; see Context.rs `// TODO(port): - /// owned ZStr repr` precedent) + /// at use-site) /// /// `Default` ⇔ `std.mem.zeroes(TransformOptions)` — every Option `None`, /// every slice empty, every scalar `0`/`false`. diff --git a/src/parsers/json.rs b/src/parsers/json.rs index 389881a840a..5ff04381b52 100644 --- a/src/parsers/json.rs +++ b/src/parsers/json.rs @@ -55,7 +55,7 @@ mod hash_map_pool { fn new_expr(t: Ty, loc: bun_ast::Loc) -> Expr where - Ty: js_ast::ExprInit, // TODO(port): bound to whatever trait Expr::init accepts + Ty: js_ast::ExprInit, { // Zig had: if @typeInfo(Type) == .pointer => @compileError — Rust's type system // already prevents passing a reference where a value is expected; no runtime check needed. @@ -133,9 +133,6 @@ where // TODO(port): narrow error set Expr::data_store_assert(); Stmt::data_store_assert(); - // TODO(port): Zig calls Expr.Data.Store.assert() / Stmt.Data.Store.assert(); - // map to whatever the typed-arena store assertion becomes in bun_js_parser. - Ok(Self { lexer: js_lexer::Lexer::init(log, source_, bump, opts)?, bump, @@ -428,7 +425,6 @@ pub struct PackageJSONVersionChecker<'a, 'bump> { } // Zig: const opts = if (LEXER_DEBUGGER_WORKAROUND) JSONOptions{} else JSONOptions{ is_json=true, json_warn_duplicate_keys=false, allow_trailing_commas=true, allow_comments=true } -// TODO(port): wire as const-generic params on the lexer type once js_lexer::NewLexer is ported. const PKG_JSON_OPTS: js_lexer::JSONOptions = if LEXER_DEBUGGER_WORKAROUND { js_lexer::JSONOptions::DEFAULT } else { @@ -1235,7 +1231,6 @@ pub fn parse_for_bundling( } // NOTE: Zig passes `source.*` (by value) here, unlike every other call site. - // TODO(port): verify whether JSONParser::init wants by-ref or by-value source. let mut parser = JSONLikeParser::init(JSON_OPTS, bump, source, log)?; let result = parser.parse_expr(false, true)?; Ok(JSONParseResult { @@ -1403,7 +1398,6 @@ mod tests { mangled_props: None, }, )?; - // TODO(port): Zig accessed writer.ctx.buffer.list.items.ptr[0..written+1]. let buf = writer.ctx.buffer.as_slice(); let mut js = &buf[0..written + 1]; diff --git a/src/parsers/toml.rs b/src/parsers/toml.rs index f7498d3101f..549ab1223c0 100644 --- a/src/parsers/toml.rs +++ b/src/parsers/toml.rs @@ -51,7 +51,7 @@ impl<'a> TOML<'a> { // call sites, so this collapses to a single generic forwarding to Expr::init. pub fn e(&self, t: D, loc: bun_ast::Loc) -> Expr where - D: js_ast::ExprInit, // TODO(port): real trait bound for Expr::init payloads + D: js_ast::ExprInit, { Expr::init(t, loc) } diff --git a/src/parsers/toml/lexer.rs b/src/parsers/toml/lexer.rs index d73ce5d2cf9..be445c66a06 100644 --- a/src/parsers/toml/lexer.rs +++ b/src/parsers/toml/lexer.rs @@ -62,8 +62,6 @@ pub struct Lexer<'a> { pub bump: &'a Arena, pub code_point: CodePoint, - // TODO(port): lifetime — borrows from `source.contents` (and arena for decoded strings); - // may be self-referential depending on how bun_ast::Source owns `contents` in Rust. pub identifier: &'a [u8], pub number: f64, pub prev_error_loc: bun_ast::Loc, diff --git a/src/parsers/yaml.rs b/src/parsers/yaml.rs index 1b7c197840f..9e4ccf975ee 100644 --- a/src/parsers/yaml.rs +++ b/src/parsers/yaml.rs @@ -889,9 +889,6 @@ impl YamlString { } pub fn eql(&self, r: &[u8], input: &[Enc::Unit]) -> bool { - // TODO(port): Zig compared []const enc.unit() against []const u8 via - // std.mem.eql(enc.unit(), ...) which only compiles when enc.unit() == u8. - // TODO(port): constrain or transcode. let l_slice = self.slice(input); if l_slice.len() != r.len() { return false; @@ -2422,8 +2419,6 @@ pub struct Parser<'i, Enc: Encoding> { pub explicit_document_start_line: Option, pub anchors: StringHashMap, - // TODO(port): Zig key type was []const enc.unit(); StringHashMap keys are &[u8]. - // For Utf16 this needs a different map type. pub tag_handles: StringHashMap<()>, pub whitespace_buf: Vec>, @@ -2608,7 +2603,6 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { self.try_skip_char(Enc::ch(b'!'))?; self.try_skip_s_white()?; - // TODO(port): StringHashMap key type; for Utf16 needs different keying. self.tag_handles .put(Enc::key_bytes(handle.slice(self.input)), ())?; @@ -3476,7 +3470,6 @@ impl MappingProps { ast::ExprData::EString(key_str) => key_str.eql_comptime(b"<<"), _ => false, }; - // TODO(port): exact ExprData variant names depend on bun_ast. if !is_merge_key { self.list.push(G::Property { @@ -5353,8 +5346,6 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { if self.line_indent.is_less_than(min_indent) { return Ok(ctx.done()?); } - // TODO(port): need Enc::Unit from u32; assuming Enc::Unit: From for ASCII range only. - // For non-ASCII units we need to read self.next() directly. let unit = self.next(); let _ = c; ctx.append(unit)?; @@ -5639,7 +5630,6 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { let ch = char::from_u32(cp).ok_or(ParseError::UnexpectedCharacter)?; let mut buf = [0u8; 4]; let s = ch.encode_utf8(&mut buf); - // TODO(port): need to push &[u8] into Vec; Enc::Unit==u8 here. for b in s.bytes() { text.push(Enc::ch(b)); } @@ -5795,7 +5785,6 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { fn shorthand_to_tag(&self, shorthand: StringRange) -> NodeTag { let s = shorthand.slice(self.input); - // TODO(port): comparing &[Enc::Unit] to ASCII literals; assumes u8-compatible. if eq_ascii::(s, b"bool") { return NodeTag::Bool; } diff --git a/src/patch/lib.rs b/src/patch/lib.rs index 8b76e8b6ff5..22bfb2e9b46 100644 --- a/src/patch/lib.rs +++ b/src/patch/lib.rs @@ -52,9 +52,6 @@ pub struct PatchFile<'a> { #[cfg_attr(unix, allow(dead_code))] struct ApplyState { pathbuf: PathBuffer, - // TODO(port): lifetime — `patch_dir_abs_path` is a self-referential slice - // into `self.pathbuf`. Model as (len) and reconstruct on demand to avoid - // a self-ref borrow. patch_dir_abs_path: Option, } @@ -302,7 +299,6 @@ fn apply_patch(patch: &FilePatch<'_>, patch_dir: Fd, state: &mut ApplyState) -> // to use the arena // PERF(port): was arena vs default_allocator selection — profile if hot. let _use_arena: bool = stat.st_size as usize <= PAGE_SIZE; - // TODO(port): Zig used `patch_dir.stdDir().readFileAlloc(...)` (std.fs). Replace with bun_sys::File::read_from. let filebuf: Vec = match read_file_alloc(patch_dir, &file_path, 1024 * 1024 * 1024 * 4) { Ok(b) => b, Err(_) => { diff --git a/src/patch_jsc/testing.rs b/src/patch_jsc/testing.rs index 8ed6bc83167..d2c6795b6b1 100644 --- a/src/patch_jsc/testing.rs +++ b/src/patch_jsc/testing.rs @@ -63,10 +63,6 @@ impl TestingAPIs { pub fn apply(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { let args = Self::parse_apply_args(global, frame)?; - // TODO(port): lifetime — `PatchFile<'a>` borrows its source bytes, so the Zig - // `ApplyArgs { patchfile, patchfile_txt }` pair is self-referential in Rust. - // PORTING.md forbids Box::leak / lifetime-extend, so we store the owned bytes - // in `ApplyArgs` and reparse here (already validated in `parse_apply_args`). let patchfile: PatchFile<'_> = parse_patch_file(&args.patchfile_txt).expect("validated in parse_apply_args"); @@ -182,9 +178,6 @@ impl TestingAPIs { } pub struct ApplyArgs { - // TODO(port): lifetime — Zig stored both `ZigString.Slice` and `PatchFile` - // (which borrows it). Self-referential in Rust; PORTING.md forbids - // Box::leak/lifetime-extend, so we store owned bytes and reparse on use. patchfile_txt: Vec, dirfd: Fd, } diff --git a/src/paths/Path.rs b/src/paths/Path.rs index 82d11df62d3..0363c6d76cc 100644 --- a/src/paths/Path.rs +++ b/src/paths/Path.rs @@ -375,11 +375,6 @@ impl PathUnit for u16 { } } -/// `Unit::Os` — resolves to `u16` on Windows, `u8` elsewhere. -#[cfg(windows)] -#[allow(dead_code)] -pub(crate) type OsUnit = u16; - // ────────────────────────────────────────────────────────────────────────── // Buf — `opts.Buf()` (only the `.pool` variant is implemented in Zig) // ────────────────────────────────────────────────────────────────────────── @@ -625,7 +620,7 @@ pub type AutoRelPath = Path; /// `Path(comptime opts: Options) type` /// /// `BufType` is omitted as a parameter because only `.pool` is implemented in Zig. -/// `Unit` is encoded as the type parameter `U: PathUnit` (use `u8`, `u16`, or `OsUnit`). +/// `Unit` is encoded as the type parameter `U: PathUnit` (use `u8` or `u16`). pub struct Path< U: PathUnit = u8, const KIND: u8 = { Kind::ANY }, @@ -690,7 +685,6 @@ impl #[cfg(windows)] { - // TODO(port): pick long_path_prefix vs long_path_prefix_u8 based on U. this._buf_append_input(crate::windows::long_path_prefix_for::(), false); } diff --git a/src/paths/lib.rs b/src/paths/lib.rs index 93fd70a4509..ab93d95081e 100644 --- a/src/paths/lib.rs +++ b/src/paths/lib.rs @@ -340,8 +340,6 @@ pub mod path_buffer_pool; // (done). 46× E0106 remain — TLS-buf-returning wrappers need `'static` lifetime // or out-param redesign. The `_buf`-suffixed fns (explicit `&mut [u8]` param) // compile; the convenience wrappers don't yet. Gate the module; expose Platform. -// TODO(port): annotate the 46 TLS-wrapper return lifetimes as `'static` (matches -// Zig "valid until next call" semantics). pub mod resolve_path; pub use resolve_path::{Platform, PlatformT, platform}; pub mod component_iterator; diff --git a/src/paths/resolve_path.rs b/src/paths/resolve_path.rs index 1a7f92b2743..dafa01b318d 100644 --- a/src/paths/resolve_path.rs +++ b/src/paths/resolve_path.rs @@ -154,7 +154,6 @@ pub(crate) fn get_if_exists_longest_common_path_generic<'a, P: PlatformT>( } if index == 0 { - // TODO(port): Zig returned &[_]u8{separator} (static); needs per-platform &'static [u8; 1] return Some(P::P.separator_string().as_bytes()); } @@ -289,7 +288,6 @@ pub(crate) fn longest_common_path_generic<'a, P: PlatformT>(input: &[&'a [u8]]) } if index == 0 { - // TODO(port): Zig returned &[_]u8{separator} (static one-byte slice) return P::P.separator_string().as_bytes(); } @@ -387,7 +385,6 @@ pub(crate) fn relative_to_common_path<'a, const ALWAYS_COPY: bool, P: PlatformT> normalized_to_: &'a [u8], buf: &'a mut [u8], ) -> &'a [u8] { - // TODO(port): return borrows either `buf` or `normalized_to_`; lifetimes need unification. let mut normalized_from = normalized_from_; let mut normalized_to = normalized_to_; let win_root_len: Option = if P::P == Platform::Windows { @@ -613,7 +610,6 @@ pub fn dirname(str: &[u8]) -> &[u8] { } Platform::Windows => { let Some(separator) = last_index_of_separator_windows(str) else { - // TODO(port): std.fs.path.diskDesignatorWindows return crate::disk_designator_windows(str); }; &str[..separator] @@ -905,9 +901,6 @@ pub fn normalize_string_generic< ) } -// TODO(port): `separatorAdapter(T, func)` wrapped a `fn(comptime T, char) bool` -// into `fn(T) bool`. In Rust we pass closures directly; no adapter needed. - pub fn normalize_string_generic_t< 'a, T: PathChar, @@ -1257,9 +1250,6 @@ impl Platform { } } - // TODO(port): get_separator_func_t returned a generic fn-over-T; Rust cannot - // express that as a value. Callers use `is_separator_t::` directly instead. - pub const fn get_last_separator_func(self) -> LastSeparatorFunction { match self { Platform::Loose => last_index_of_separator_loose, @@ -1268,9 +1258,6 @@ impl Platform { } } - // TODO(port): get_last_separator_func_t — same as above; callers dispatch - // via `last_index_of_separator_*_t::` directly. - #[inline(always)] pub fn is_separator(self, char: u8) -> bool { self.is_separator_t::(char) diff --git a/src/paths/string_paths.rs b/src/paths/string_paths.rs index 14497b4662c..6aebccea819 100644 --- a/src/paths/string_paths.rs +++ b/src/paths/string_paths.rs @@ -389,7 +389,6 @@ pub fn path_contains_node_modules_folder(path: &[u8]) -> bool { pub use crate::is_sep_any as char_is_any_slash; #[inline(always)] -#[allow(dead_code)] pub fn starts_with_windows_drive_letter(s: &[u8]) -> bool { starts_with_windows_drive_letter_t(s) } diff --git a/src/perf/hw_timer.rs b/src/perf/hw_timer.rs index 736ff3f756c..6b9372946f3 100644 --- a/src/perf/hw_timer.rs +++ b/src/perf/hw_timer.rs @@ -18,12 +18,6 @@ //! See WebKit r312153 (UnbarrieredMonotonicTime) for the original design and //! drift/monotonicity measurements on Darwin/arm64. -#[cfg(all( - target_arch = "x86_64", - any(target_os = "macos", target_os = "freebsd") -))] -use core::ffi::{c_char, c_int, c_void}; - /// Raw counter read. No barriers. /// - aarch64: `CNTVCT_EL0` (fixed-frequency virtual counter) /// - x86_64: `rdtsc` @@ -61,51 +55,4 @@ pub fn read_counter() -> u64 { compile_error!("hw_timer::read_counter: unsupported architecture"); } -#[cfg(all( - target_arch = "x86_64", - not(any(target_os = "macos", target_os = "freebsd")) -))] -#[allow(dead_code)] -struct CpuidResult { - eax: u32, - ebx: u32, - ecx: u32, - edx: u32, -} - -#[cfg(all( - target_arch = "x86_64", - not(any(target_os = "macos", target_os = "freebsd")) -))] -#[inline] -#[allow(dead_code)] -fn cpuid(leaf: u32, subleaf: u32) -> CpuidResult { - // PORT NOTE: Rust inline asm reserves `rbx` (LLVM PIC base), so we use the - // std intrinsic which handles the xchg dance internally instead of raw asm. - // (`__cpuid_count` is a safe fn on x86_64 — cpuid is baseline.) - let r = core::arch::x86_64::__cpuid_count(leaf, subleaf); - CpuidResult { - eax: r.eax, - ebx: r.ebx, - ecx: r.ecx, - edx: r.edx, - } -} - -// TODO(port): move to perf_sys / bun_sys -#[cfg(all( - target_arch = "x86_64", - any(target_os = "macos", target_os = "freebsd") -))] -unsafe extern "C" { - #[allow(dead_code)] - fn sysctlbyname( - name: *const c_char, - oldp: *mut c_void, - oldlenp: *mut usize, - newp: *const c_void, - newlen: usize, - ) -> c_int; -} - // ported from: src/perf/hw_timer.zig diff --git a/src/perf/lib.rs b/src/perf/lib.rs index 5c8393f5f6b..b78e6053ddb 100644 --- a/src/perf/lib.rs +++ b/src/perf/lib.rs @@ -141,11 +141,10 @@ pub use darwin_impl::Darwin; mod darwin_impl { use super::*; use bun_sys::darwin::OSLog; - use core::sync::atomic::AtomicPtr; - // TODO(port): verify Rust path for `OSLog.Signpost.Interval` and `.PointsOfInterest` category use bun_sys::darwin::os_log::signpost::{ Category as SignpostCategory, Interval as SignpostInterval, }; + use core::sync::atomic::AtomicPtr; pub struct Darwin { interval: SignpostInterval, @@ -169,7 +168,6 @@ mod darwin_impl { } fn get_once() { - // TODO(port): verify `OSLog::init()` signature; Zig returns `?*OSLog` if let Some(log) = OSLog::init() { OS_LOG.store(log.as_ptr(), Ordering::Release); } diff --git a/src/picohttp/lib.rs b/src/picohttp/lib.rs index 9f793ffbca8..71d726aa50d 100644 --- a/src/picohttp/lib.rs +++ b/src/picohttp/lib.rs @@ -183,8 +183,7 @@ impl Header { impl fmt::Display for Header { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // NOTE: pretty_fmt! is the comptime ANSI-tag expander (`` → escape - // codes). bun_core's current impl is a passthrough TODO(port) until the - // proc-macro lands; output will contain literal `` tags until then. + // codes). if enable_ansi_colors_stderr() { if self.is_multiline() { write!(f, pretty_fmt!("{}", true), BStr::new(self.value())) @@ -286,7 +285,6 @@ impl<'a> HeaderList<'a> { // Request // ────────────────────────────────────────────────────────────────────────── -// TODO(port): thiserror not in workspace deps — manual Display/Error impl. #[derive(Debug, strum::IntoStaticStr)] pub enum ParseRequestError { BadRequest, diff --git a/src/platform/lib.rs b/src/platform/lib.rs index df77493f1d2..e56df6b2b54 100644 --- a/src/platform/lib.rs +++ b/src/platform/lib.rs @@ -1,6 +1,6 @@ #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] #![warn(unused_must_use)] -//! Per-OS APIs that don't fit in `bun_sys` (signposts, splice/preadv2 wrappers). +//! Per-OS APIs that don't fit in `bun_sys` (signposts, the `sys_epoll_pwait2` export). // Zig's `Environment.isLinux` is `os.tag == .linux`, which is true on Android // (Zig models Android as `os = linux, abi = android`); Rust splits them, so diff --git a/src/platform/linux.rs b/src/platform/linux.rs index fff75b01a15..b95a2c88c7e 100644 --- a/src/platform/linux.rs +++ b/src/platform/linux.rs @@ -3,10 +3,7 @@ //! If an API can be implemented on multiple platforms, //! it does not belong in this namespace. -use core::ffi::{c_int, c_long}; -use core::sync::atomic::{AtomicU8, Ordering}; - -use bun_core::Fd; +use core::ffi::c_long; // Zig: `pub const MemFdAllocator = bun.allocators.LinuxMemFdAllocator;` // LAYERING: `LinuxMemFdAllocator` lives in `bun_runtime::allocators` (it pulls in @@ -17,9 +14,9 @@ use bun_core::Fd; /// Re-encode a glibc `syscall(2)` wrapper return into the raw-kernel convention used by /// Zig's `std.os.linux.syscallN`: on error the kernel returns `-errno` in the result /// register (i.e. a value in `-4095..=-1`), whereas glibc's wrapper translates that to -/// `-1` and stashes the code in thread-local `errno`. Callers of these functions -/// (`bun.sys.getErrno` for `usize`, and the C `epoll_kqueue.c` loop for `isize`) decode -/// errno *from the return value*, so we must put it back in-band. +/// `-1` and stashes the code in thread-local `errno`. The caller (the C +/// `epoll_kqueue.c` loop) decodes errno *from the return value*, so we must put it +/// back in-band. #[inline(always)] fn encode_raw_errno(rc: c_long) -> isize { if rc == -1 { @@ -29,108 +26,6 @@ fn encode_raw_errno(rc: c_long) -> isize { } } -/// splice() moves data between two file descriptors without copying -/// between kernel address space and user address space. It -/// transfers up to len bytes of data from the file descriptor fd_in -/// to the file descriptor fd_out, where one of the file descriptors -/// must refer to a pipe. -#[allow(dead_code)] -pub(crate) fn splice( - fd_in: c_int, - off_in: Option<&mut i64>, - fd_out: c_int, - off_out: Option<&mut i64>, - len: usize, - flags: u32, -) -> usize { - // SAFETY: direct Linux syscall; arguments mirror the kernel ABI for splice(2). - let rc = unsafe { - libc::syscall( - libc::SYS_splice, - fd_in as isize as usize, - off_in.map_or(0usize, |p| std::ptr::from_mut::(p) as usize), - fd_out as isize as usize, - off_out.map_or(0usize, |p| std::ptr::from_mut::(p) as usize), - len, - flags as usize, - ) - }; - // Callers (e.g. blob copy_file) feed this through `bun.sys.getErrno(usize)` which - // expects the raw `-errno`-in-high-range encoding of `std.os.linux.syscall6`. - encode_raw_errno(rc) as usize -} - -#[repr(u8)] -#[derive(Copy, Clone, Eq, PartialEq)] -#[allow(dead_code)] -pub(crate) enum RWFFlagSupport { - Unknown = 0, - Unsupported = 2, - Supported = 1, -} - -#[allow(dead_code)] -static RWF_BOOL: AtomicU8 = AtomicU8::new(RWFFlagSupport::Unknown as u8); - -#[allow(dead_code)] -impl RWFFlagSupport { - pub(crate) fn is_linux_kernel_version_with_buggy_rwf_nonblock() -> bool { - let v = bun_core::linux_kernel_version(); - v.major == 5 && matches!(v.minor, 9 | 10) - } - - pub(crate) fn disable() { - RWF_BOOL.store(RWFFlagSupport::Unsupported as u8, Ordering::Relaxed); - } - - /// Workaround for https://github.com/google/gvisor/issues/2601 - pub(crate) fn is_maybe_supported() -> bool { - if !cfg!(any(target_os = "linux", target_os = "android")) { - return false; - } - let current: RWFFlagSupport = match RWF_BOOL.load(Ordering::Relaxed) { - 0 => RWFFlagSupport::Unknown, - 1 => RWFFlagSupport::Supported, - _ => RWFFlagSupport::Unsupported, - }; - match current { - RWFFlagSupport::Unknown => { - if Self::is_linux_kernel_version_with_buggy_rwf_nonblock() - || bun_core::env_var::feature_flag::BUN_FEATURE_FLAG_DISABLE_RWF_NONBLOCK::get() - .unwrap_or(false) - { - RWF_BOOL.store(RWFFlagSupport::Unsupported as u8, Ordering::Relaxed); - return false; - } - - RWF_BOOL.store(RWFFlagSupport::Supported as u8, Ordering::Relaxed); - true - } - RWFFlagSupport::Supported => true, - RWFFlagSupport::Unsupported => false, - } - } -} - -/// https://man7.org/linux/man-pages/man2/ioctl_ficlone.2.html -/// -/// Support for FICLONE is dependent on the filesystem driver. -#[allow(dead_code)] -pub(crate) fn ioctl_ficlone(dest_fd: Fd, srcfd: Fd) -> usize { - // SAFETY: direct Linux ioctl syscall; FICLONE takes the source fd as its argument. - let rc = unsafe { - libc::syscall( - libc::SYS_ioctl, - dest_fd.native() as usize, - libc::FICLONE as usize, - // @intCast(srcfd.native()) — valid fds are non-negative - usize::try_from(srcfd.native()).expect("int cast"), - ) - }; - // Callers switch on `getErrno(rc)` for XDEV/NOSYS/OPNOTSUPP — must preserve in-band -errno. - encode_raw_errno(rc) as usize -} - #[unsafe(no_mangle)] pub(crate) extern "C" fn sys_epoll_pwait2( epfd: i32, diff --git a/src/ptr/owned.rs b/src/ptr/owned.rs index 545eda7b9f6..4af47cb371d 100644 --- a/src/ptr/owned.rs +++ b/src/ptr/owned.rs @@ -155,7 +155,6 @@ pub type OwnedIn = Box; // core::ptr::drop_in_place(raw as *mut ManuallyDrop); // no-op // alloc::alloc::dealloc(raw.cast(), Layout::new::()); // } -// // TODO(port): audit callers of deinitShallow; likely all fall under (a) or (b). // ── get ────────────────────────────────────────────────────────────────────────────────────── // Returns the inner pointer or slice. diff --git a/src/ptr/ref_count.rs b/src/ptr/ref_count.rs index 69b083f3a47..2eee27c476d 100644 --- a/src/ptr/ref_count.rs +++ b/src/ptr/ref_count.rs @@ -1088,8 +1088,6 @@ pub struct DebugData { // TODO(port): Zig used `align(@alignOf(u32))` to reduce u128 alignment to // 4. Rust cannot under-align a field; consider `[u32; 4]` if layout matters. magic: u128, - // TODO(port): Zig used `if (thread_safe) std.debug.SafetyLock else bun.Mutex`. - // Debug-only — always `bun_core::Mutex<()>` (poison-free `std::sync`) here for simplicity. lock: bun_core::Mutex<()>, next_id: AtomicU32, map: HashMap, diff --git a/src/resolver/dir_info.rs b/src/resolver/dir_info.rs index cdb1f854290..2db61822cbf 100644 --- a/src/resolver/dir_info.rs +++ b/src/resolver/dir_info.rs @@ -366,9 +366,6 @@ impl Flags { pub use Flags as Flag; impl DirInfo { - // TODO(port): in-place cache invalidation, not Drop — DirInfo lives in BSS-backed - // allocators::BSSMap storage so Drop never fires naturally; callers invoke this - // explicitly when invalidating the cache slot. Zig name was `deinit`. pub fn reset(&mut self) { if let Some(p) = self.package_json.take() { // SAFETY: `p` carries mut-provenance from `intern_package_json` (NonNull diff --git a/src/resolver/fs.rs b/src/resolver/fs.rs index 2394db528e7..1c749fa5dae 100644 --- a/src/resolver/fs.rs +++ b/src/resolver/fs.rs @@ -397,8 +397,6 @@ impl Default for EntryCache { // that external-locking discipline). pub struct Entry { pub cache: core::cell::Cell, - // TODO(port): rule deviation — Zig deinit calls allocator.free(e.dir) so guide says Box<[u8]>, - // but this points into DirnameStore (a &'static BSSList). Keeping &'static. pub dir: &'static [u8], pub base_: strings::StringOrTinyString, @@ -1006,8 +1004,6 @@ impl bun_dotenv::DirEntryProbe for DirEntry { pub use EntryKind as FsEntryKind; pub use dir_entry::Err as DirEntryErr; -// TODO(port): Entry::deinit took allocator and destroyed self; Entry lives in EntryStore (BSSList) so no Drop needed - // pub fn statBatch(fs: *FileSystemEntry, paths: []string) ![]?Stat { // } // pub fn stat(fs: *FileSystemEntry, path: string) !Stat { @@ -1170,7 +1166,6 @@ impl RealFS { } let mut tmp_buf = PathBuffer::uninit(); - // TODO(port): std.posix.getcwd — bun_sys::getcwd let n = bun_sys::getcwd(&mut tmp_buf[..]).expect("Failed to get cwd for platformTempDir"); let cwd = &tmp_buf[..n]; @@ -2551,11 +2546,8 @@ impl core::fmt::Display for PrintHandle { write!(f, "{}", self.0) } } -// TODO(port): FmtHandleFnGenerator used @TypeOf reflection — replaced with per-type Display impls #[path = "fs/stat_hash.rs"] pub mod stat_hash; -// TODO(port): src/resolver/fs/stat_hash.rs depends on bun_hash::XxHash64 + -// bun_http_types::wtf::write_http_date — gated until those land. // ported from: src/resolver/fs.zig diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 78e39812121..d4d9598a3d5 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -2426,10 +2426,6 @@ pub mod cache { } } - // TODO(port): Zig `Fs.deinit` references `c.entries` which is not a field on `Fs` — - // dead code (Zig lazy compilation never instantiated it). No Drop impl needed beyond - // the auto-drop of `shared_buffer` / `macro_shared_buffer`. - /// Port of `Fs.readFileShared` (cache.zig:87) — read `path` into the /// caller's `shared` buffer (HMR / dev-server path). pub fn read_file_shared( diff --git a/src/resolver/package_json.rs b/src/resolver/package_json.rs index d6bbd884e79..9065c0dd368 100644 --- a/src/resolver/package_json.rs +++ b/src/resolver/package_json.rs @@ -325,10 +325,6 @@ impl ::bun_install_types::resolver_hooks::PackageJsonView for PackageJSON { } impl PackageJSON { - // pub const new = bun.TrivialNew(@This()); - // pub const deinit = bun.TrivialDeinit(@This()); - // TODO(port): TrivialNew/TrivialDeinit — use Box::new / Drop - pub fn name_for_import(&self) -> Result, bun_core::Error> { // TODO(port): narrow error set if strings::index_of(self.source.path.text, NODE_MODULES_PATH.as_bytes()).is_some() { @@ -1541,7 +1537,6 @@ impl PackageJSON { } type DependencyGroup = install_stubs::DependencyGroup; - // TODO(port): comptime feature flags + comptime brk block — expanded inline below let dev_deps = INCLUDE_DEPENDENCIES == IncludeDependencies::Main; let dependency_groups: &[DependencyGroup] = if dev_deps { &[ @@ -2399,7 +2394,6 @@ impl<'a> ESModule<'a> { // live `&mut` to resolved_path_buf_percent on this thread. let resolved_path_buf_percent: &mut PathBuffer = unsafe { &mut (*module_bufs()).resolved_path_buf_percent }; - // TODO(port): std.io.fixedBufferStream + PercentEncoding.decode let len = match bun_url::PercentEncoding::decode_into( &mut resolved_path_buf_percent.0, &result.path, diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 4a5b396ef35..ae4cd319328 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -398,8 +398,7 @@ pub struct Bufs { #[cfg(not(windows))] pub win32_normalized_dir_info_cache: (), } -// TODO(port): bun.ThreadlocalBuffers(Bufs) — lazily-allocated threadlocal Box. -// In Rust we model it as a `thread_local! { static BUFS_PTR: BufsSlot }` caching a +// `Bufs` is modeled as a `thread_local! { static BUFS_PTR: BufsSlot }` caching a // leaked `Box` pointer. `BufsSlot`'s `Drop` reclaims that box when a // worker/transpiler-pool thread exits; the main thread's lives process-lifetime // (as in Zig, which never freed it). The `bufs!()` macro hands out `&mut` to a @@ -1155,7 +1154,6 @@ impl<'a> Resolver<'a> { // Only setting 'current_action' in debug mode because module resolution // is done very often, and has a very low crash rate. - // TODO(port): bun.crash_handler.current_action save/restore (Environment.show_crash_trace gated) #[cfg(debug_assertions)] let _crash_guard = ::bun_crash_handler::set_current_action_resolver(source_dir, import_path, kind); @@ -4397,7 +4395,6 @@ impl<'a> Resolver<'a> { #[cfg(unix)] let open_req: core::result::Result = { - // TODO(port): std.fs.openDirAbsoluteZ — using bun_sys equivalent bun_sys::open_dir_absolute_z( sentinel, bun_sys::OpenDirOptions { @@ -6082,7 +6079,6 @@ impl<'a> Resolver<'a> { BIN_FOLDERS_LOADED.store(true, core::sync::atomic::Ordering::Release); } - // TODO(port): std.fs.Dir.openDirZ → bun_sys let Ok(file) = bun_sys::open_dir_z( fd, bun_paths::path_literal!(b"node_modules/.bin"), diff --git a/src/router/lib.rs b/src/router/lib.rs index ced9ab435c8..3f2969d695a 100644 --- a/src/router/lib.rs +++ b/src/router/lib.rs @@ -306,7 +306,6 @@ impl<'a> Router<'a> { debug_assert!(!route.path.is_empty()); - // TODO(port): @hasField(std.meta.Child(Server), "watcher") — modeled via ServerLike trait method if let Some(watcher) = server.watcher_mut() { if watcher.watchloop_handle().is_none() { let _ = watcher.start(); @@ -2256,7 +2255,6 @@ mod tests { fn pattern_match() { type Entry = Param<'static>; - // TODO(port): Zig used anonymous-struct field iteration; ported as explicit array. let regular_list: &[(&[u8], &[u8], &[Entry])] = &[ (b"404", b"404", &[]), ( diff --git a/src/runtime/api/Archive.rs b/src/runtime/api/Archive.rs index 4a8e3d30915..de38a21b15b 100644 --- a/src/runtime/api/Archive.rs +++ b/src/runtime/api/Archive.rs @@ -660,9 +660,6 @@ pub trait TaskContext: Send { /// Dispatch tag for this context's `AsyncTask` variant. const TAG: TaskTag; /// Runs on thread pool. Stores its result on `self`. - // TODO(port): Zig's `AsyncTask.run` used `@typeInfo(@TypeOf(result)) == .error_union` - // to generically catch and store `.err`. Rust has no reflection; each impl handles - // its own error path inside `run` and writes `self.result`. fn run(&mut self); fn run_from_js(&mut self, global: &JSGlobalObject) -> JsResult; } diff --git a/src/runtime/api/BunObject.rs b/src/runtime/api/BunObject.rs index e30b19455a1..acc8abfb390 100644 --- a/src/runtime/api/BunObject.rs +++ b/src/runtime/api/BunObject.rs @@ -1159,8 +1159,6 @@ pub(crate) fn sleep_sync( ))); } - // TODO(port): std.Thread.sleep — bun owns its own sleep; using thread::sleep - // here matches Zig's blocking semantics (this is a sync API). std::thread::sleep(core::time::Duration::from_millis( u64::try_from(milliseconds).expect("int cast"), )); @@ -1558,9 +1556,6 @@ pub(crate) fn index_of_line( } pub use crate::crypto as crypto_mod; -// TODO(port): `pub const Crypto = @import("../crypto/crypto.zig");` re-exports -// the crypto module under this file's namespace; in Rust the canonical path is -// `crate::crypto`. #[bun_jsc::host_fn] pub(crate) fn nanoseconds(global_this: &JSGlobalObject, _: &CallFrame) -> JsResult { @@ -1787,7 +1782,6 @@ pub(crate) fn mmap_file(global_this: &JSGlobalObject, callframe: &CallFrame) -> libc::MAP_PRIVATE }; - // TODO(port): @hasField(std.c.MAP, "SYNC") — gated by target_os in Rust. #[cfg(target_os = "linux")] if opts .get_boolean_loose(global_this, "sync")? diff --git a/src/runtime/api/JSBundler.rs b/src/runtime/api/JSBundler.rs index 0102cd9a133..5c9fa5dd73d 100644 --- a/src/runtime/api/JSBundler.rs +++ b/src/runtime/api/JSBundler.rs @@ -840,7 +840,6 @@ pub mod js_bundler { } if entry_points.len() == 1 { - // TODO(port): std.fs.path.dirname → bun_paths::dirname let d = bun_paths::resolve_path::dirname::( &entry_points[0], ); @@ -861,7 +860,6 @@ pub mod js_bundler { ); }; - // TODO(port): std.fs.cwd().openDir — banned std::fs; use bun_sys let dir = match bun_sys::open_dir_at(bun_sys::Fd::cwd(), path.slice()) { Ok(d) => d, Err(err) => { diff --git a/src/runtime/api/JSTranspiler.rs b/src/runtime/api/JSTranspiler.rs index 9d63dc44811..4e2de009bd7 100644 --- a/src/runtime/api/JSTranspiler.rs +++ b/src/runtime/api/JSTranspiler.rs @@ -33,9 +33,6 @@ use bun_collections::ArrayHashMapExt; use bun_core::{OwnedString, String as BunString, ZigString}; use bun_options_types::schema::api; -// TODO(port): `pub const js = jsc.Codegen.JSTranspiler;` and the toJS/fromJS/fromJSDirect -// aliases are wired by `#[bun_jsc::JsClass]` codegen — see PORTING.md §JSC types. - // Host-fn re-entrancy: every JS-exposed method takes `&self`; per-field // interior mutability via `JsCell` (= `UnsafeCell` projector). `JsCell` is // `#[repr(transparent)]`, so field offsets are unchanged. @@ -788,8 +785,6 @@ impl<'a> TransformTask<'a> { }, ); - // TODO(port): ASTMemoryAllocator scope — typed_arena in AST crates; here we just - // construct one and enter it. Model as RAII guard. let mut ast_memory_allocator = bun_ast::ASTMemoryAllocator::borrowing(&arena); let _ast_scope = ast_memory_allocator.enter(); diff --git a/src/runtime/api/bun/h2_frame_parser.rs b/src/runtime/api/bun/h2_frame_parser.rs index fa0f9ae741c..14ce1890208 100644 --- a/src/runtime/api/bun/h2_frame_parser.rs +++ b/src/runtime/api/bun/h2_frame_parser.rs @@ -37,7 +37,7 @@ bun_output::declare_scope!(H2FrameParser, visible); // (see `${TypeName}__fromJS` etc. in build/*/codegen/ZigGeneratedClasses.cpp); // replace with the macro-derived modules once the .rs codegen backend lands. // ────────────────────────────────────────────────────────────────────────── -#[allow(non_snake_case, non_camel_case_types, dead_code)] +#[allow(non_snake_case, non_camel_case_types)] pub mod JSH2FrameParser { use super::{JSGlobalObject, JSValue}; @@ -390,7 +390,6 @@ impl FrameHeader { pub const BYTE_SIZE: usize = 9; #[inline] fn write(&self, writer: &mut impl WireWriter) -> bool { - // TODO(port): byteSwapAllFields on packed struct(u72) — emit big-endian wire format manually let mut buf = [0u8; Self::BYTE_SIZE]; buf[0] = ((self.length >> 16) & 0xFF) as u8; buf[1] = ((self.length >> 8) & 0xFF) as u8; @@ -562,7 +561,6 @@ impl FullSettingsPayload { pub(crate) fn write(&self, writer: &mut impl WireWriter) -> bool { let mut swap = *self; - // TODO(port): byteSwapAllFields — swap each field manually swap._header_table_size_type = swap._header_table_size_type.swap_bytes(); swap.header_table_size = swap.header_table_size.swap_bytes(); swap._enable_push_type = swap._enable_push_type.swap_bytes(); @@ -1086,7 +1084,6 @@ pub fn js_get_packed_settings( } } - // TODO(port): byteSwapAllFields — done inside .write(); here we need raw swapped bytes let mut buf = [0u8; FullSettingsPayload::BYTE_SIZE]; let mut cursor = FixedBufferStream::new(&mut buf); let _ = settings.write(&mut cursor); @@ -1223,7 +1220,6 @@ impl Handlers { if JSH2FrameParser::Gc::onWrite.get(this_value) == Some(JSValue::ZERO) || JSH2FrameParser::Gc::onWrite.get(this_value).is_none() { - // TODO(port): Zig compares to .zero; codegen may return None — check both return Err(global_object .throw_invalid_arguments(format_args!("Expected at least \"write\" callback"))); } @@ -3775,7 +3771,6 @@ impl H2FrameParser { let global = self.handlers.get().global(); while !payload.is_empty() { - // TODO(port): fixedBufferStream over const slice for reading u16 BE if payload.len() < 2 { bun_output::scoped_log!( H2FrameParser, diff --git a/src/runtime/api/bun/js_bun_spawn_bindings.rs b/src/runtime/api/bun/js_bun_spawn_bindings.rs index e33e32d3ac2..d2b7637997e 100644 --- a/src/runtime/api/bun/js_bun_spawn_bindings.rs +++ b/src/runtime/api/bun/js_bun_spawn_bindings.rs @@ -391,8 +391,6 @@ pub(crate) fn spawn_maybe_sync( let cmd_value: JSValue; let mut detached = false; let mut args = args_; - // TODO(port): Zig used `if (is_sync) void else ?IPC.Mode`; Rust const-generic bool - // can't gate field type. Always Option; IS_SYNC branches never read it. let mut maybe_ipc_mode: Option = None; let mut ipc_callback: JSValue = JSValue::ZERO; let mut extra_fds: Vec = Vec::new(); @@ -410,8 +408,6 @@ pub(crate) fn spawn_maybe_sync( let mut terminal_info: Option = None; let mut existing_terminal: Option> = None; // Existing terminal passed by user let mut terminal_js_value: JSValue = JSValue::ZERO; - // TODO(port): the Zig `defer` block at function end (abort_signal.unref + terminal cleanup) - // is implemented via scopeguard below; disarmed where the Zig set the locals to null. let mut defer_guard = scopeguard::guard( (&mut abort_signal, &mut terminal_info), |(abort_signal, terminal_info): ( @@ -907,8 +903,6 @@ pub(crate) fn spawn_maybe_sync( ); // PORT NOTE: reshaped for borrowck — re-borrow through the guard tuple so the guard // stays armed (runs on every early return) until disarmed by `**should_close_memfd = false` below. - // TODO(port): errdefer — if borrowck rejects the double-&mut reborrow at later use sites, - // may need to move stdio into the guard by value and reborrow via DerefMut. let (should_close_memfd, stdio) = &mut *memfd_guard; // "NODE_CHANNEL_FD=" is 16 bytes long, 15 bytes for the number, and 1 byte for the null terminator should be enough/safe diff --git a/src/runtime/api/bun/subprocess.rs b/src/runtime/api/bun/subprocess.rs index e4b147430bb..ebc32887d8a 100644 --- a/src/runtime/api/bun/subprocess.rs +++ b/src/runtime/api/bun/subprocess.rs @@ -4,11 +4,9 @@ use core::cell::Cell; use core::ffi::c_void; use core::ptr::NonNull; -use std::sync::atomic::AtomicU32; use bun_ptr::{RefCount, RefPtr}; -use bun_io::{FilePoll, KeepAlive}; use bun_jsc::{ self as jsc, CallFrame, JSGlobalObject, JSPromise, JSValue, JsCell, JsRef, JsResult, VirtualMachine, @@ -307,26 +305,6 @@ bitflags::bitflags! { } } -// TODO(port): Poll appears unreferenced (dead code per LIFETIMES.tsv). Porting for parity. -pub enum Poll { - PollRef(Option>), // TODO(port): lifetime - WaitThread(WaitThreadPoll), -} - -pub struct WaitThreadPoll { - pub ref_count: AtomicU32, - pub poll_ref: KeepAlive, -} - -impl Default for WaitThreadPoll { - fn default() -> Self { - Self { - ref_count: AtomicU32::new(0), - poll_ref: KeepAlive::default(), - } - } -} - // `StdioResult` is `Option` (Copy) on unix but a non-Copy enum on windows; // a fn would have to pick by-value (moves on windows) or by-ref // (clippy::trivially_copy_pass_by_ref on unix). diff --git a/src/runtime/api/bun/subprocess/SubprocessPipeReader.rs b/src/runtime/api/bun/subprocess/SubprocessPipeReader.rs index 3d85a9f64a9..a38b2cd5bc0 100644 --- a/src/runtime/api/bun/subprocess/SubprocessPipeReader.rs +++ b/src/runtime/api/bun/subprocess/SubprocessPipeReader.rs @@ -171,7 +171,6 @@ impl PipeReader { // outlives the guard's drop on return. let _keepalive = unsafe { ScopedRef::new(std::ptr::from_mut::(self)) }; - // TODO(port): on POSIX `StdioResult` is `Option`; `.unwrap()` mirrors Zig `.?`. match self.reader.start(self.stdio_result.unwrap(), true) { bun_sys::Result::Err(err) => { return bun_sys::Result::Err(err); @@ -350,7 +349,6 @@ impl PipeReader { } } - // TODO(port): `loop` is a Rust keyword; renamed to `loop_`. Callers (BufferedReader vtable) must match. pub(crate) fn loop_(&self) -> *mut AsyncLoop { // `event_loop.virtual_machine` is set by the time a PipeReader is // created. The VM is the per-thread singleton owning `event_loop`, so diff --git a/src/runtime/api/filesystem_router.rs b/src/runtime/api/filesystem_router.rs index eed6a530d14..49e58f47db2 100644 --- a/src/runtime/api/filesystem_router.rs +++ b/src/runtime/api/filesystem_router.rs @@ -203,7 +203,6 @@ impl FileSystemRouter { continue; } // PERF(port): was appendAssumeCapacity - // TODO(port): `toUTF8Bytes(allocator)[1..]` — slices off leading '.'; arena owns the bytes. let bytes = val.to_slice(global_this)?.into_vec(); // SAFETY: arena is boxed and moved into the returned `FileSystemRouter`, so the // backing allocation outlives this slice. Cast through raw ptr to detach the diff --git a/src/runtime/api/glob.rs b/src/runtime/api/glob.rs index c251fbf8e5f..7daf31452b8 100644 --- a/src/runtime/api/glob.rs +++ b/src/runtime/api/glob.rs @@ -15,7 +15,6 @@ use bun_sys as syscall; // Codegen hooks (JSGlob): toJS / fromJS / fromJSDirect are provided by the // generated C++ wrapper. See PORTING.md §JSC ".classes.ts-backed types". -// TODO(port): #[derive(bun_jsc::JsClass)] once codegen is wired for Rust. #[bun_jsc::JsClass] pub struct Glob { pattern: Box<[u8]>, diff --git a/src/runtime/bake/DevServer.rs b/src/runtime/bake/DevServer.rs index 701a448d2ff..ce1504f82b3 100644 --- a/src/runtime/bake/DevServer.rs +++ b/src/runtime/bake/DevServer.rs @@ -265,7 +265,7 @@ pub struct CurrentBundle { /// Information BundleV2 needs to finalize the bundle pub start_data: bundler::bundle_v2::DevServerInput, /// Started when the bundle was queued - pub timer: Instant, // TODO(port): std.time.Timer → Instant; .read() becomes .elapsed() + pub timer: Instant, /// If any files in this bundle were due to hot-reloading, some extra work /// must be done to inform clients to reload routes. When this is false, /// all entry points do not have bundles yet. @@ -439,7 +439,7 @@ pub struct DevServer { // Debugging #[cfg(feature = "bake_debugging_features")] - pub dump_dir: Option, // TODO(port): std.fs.Dir → bun_sys equivalent + pub dump_dir: Option, #[cfg(not(feature = "bake_debugging_features"))] pub dump_dir: (), /// Reference count to number of active sockets with the incremental_visualizer enabled. @@ -1308,9 +1308,6 @@ impl DevServer { } /// Returns true if a catch-all handler was attached. - // TODO(port): `server: anytype` -- monomorphized over NewServer so - // the SSL flag is a real const-generic (associated consts can't appear in - // const-generic position on stable). pub fn set_routes( &mut self, server: &mut crate::server::NewServer, @@ -1905,7 +1902,7 @@ impl RequestEnsureRouteBundledCtx { // PORT NOTE: reshaped for borrowck — captured args before re-borrowing dev let route_bundle_index = self.route_bundle_index; let kind = self.kind; - let req = ::core::mem::replace(&mut self.req, ReqOrSaved::Aborted); // TODO(port): ReqOrSaved moved into deferRequest + let req = ::core::mem::replace(&mut self.req, ReqOrSaved::Aborted); let resp = self.resp; let dev = self.dev_mut(); let requests_array: *mut deferred_request::List = match bundle_field { @@ -2020,8 +2017,6 @@ enum BundleQueueType { CurrentBundle, } -// TODO(port): `ensureRouteIsBundled` is a comptime-generic over `Ctx` with @field -// duck-typing. In Rust we use a trait. trait EnsureRouteCtx { fn on_defer(&mut self, bundle_field: BundleQueueType) -> JsResult<()>; fn on_loaded(&mut self) -> JsResult<()>; @@ -2146,12 +2141,8 @@ fn ensure_route_is_bundled( dev.route_bundle_ptr(route_bundle_index).server_state = route_bundle::State::Bundling; - dev.start_async_bundle( - entry_points, - false, - Instant::now(), // TODO(port): std.time.Timer.start() - ) - .expect("oom"); + dev.start_async_bundle(entry_points, false, Instant::now()) + .expect("oom"); return Ok(()); } route_bundle::State::DeferredToNextBundle => { @@ -2202,7 +2193,7 @@ fn ensure_route_is_bundled( enum ReqOrSaved { Req(*mut Request), // FFI: uws C request ptr from handler callback Saved(SavedRequest), - Aborted, // TODO(port): added for take()-style move; not in Zig + Aborted, } impl ReqOrSaved { @@ -2379,7 +2370,6 @@ fn check_route_failures( // See comment on this field for information if !dev.assume_perfect_incremental_bundling { // Cache bust EVERYTHING reachable - // TODO(port): inline for over .{ {graph, bits}, ... } — unrolled { let mut it = gts.client_bits.iterator::(); while let Some(file_index) = it.next() { @@ -5116,7 +5106,6 @@ impl DevServer { let _g = self.graph_safety_lock.guard(); - // TODO(port): `switch (graph == .client) { inline else => |is_client| ... }` — unrolled let owner: serialized_failure::OwnerPacked = if graph == bake::Graph::Client { let idx = self.client_graph.insert_stale(abs_path, false)?; serialized_failure::OwnerPacked::new(bake::Side::Client, idx.get()) @@ -5161,7 +5150,6 @@ impl DevServer { let _g = self.graph_safety_lock.guard(); - // TODO(port): switch (side) { inline else => |side_comptime| ... } — unrolled macro_rules! check { ($g:expr) => {{ let g = $g; @@ -5190,7 +5178,6 @@ impl DevServer { entry_points: &mut EntryPointList, optional_id: impl Into, ) -> Result<(), bun_core::Error> { - // TODO(port): Zig used `anytype` and matched on @TypeOf; using From/Into. let file = match optional_id.into() { OpaqueFileIdOrOptional::Optional(o) => match o { Some(f) => f, @@ -5221,7 +5208,6 @@ impl DevServer { } } -// TODO(port): helper enum for `optional_id: anytype` in append_opaque_entry_point pub(super) enum OpaqueFileIdOrOptional { Id(OpaqueFileId), Optional(framework_router::OpaqueFileIdOptional), @@ -5485,8 +5471,6 @@ impl DevServer { ) -> Result<(), bun_core::Error> { let mut buf: Vec = Vec::with_capacity(2048); - // TODO(port): switch (kind) { inline else => |k| std.fmt.comptimePrint(...) } - // → const_format would need const enum-dependent string; using match on runtime kind. let page_title = match kind { ErrorPageKind::Bundler => "Build Failed", ErrorPageKind::Evaluation => "Runtime Error", @@ -5648,7 +5632,6 @@ pub fn dump_bundle( &mut *buf, &[<&'static str>::from(graph).as_bytes(), rel_path], )[1..]; - // TODO(port): std.fs.Dir.makeOpenPath / createFile — use bun_sys let inner_dir = dump_dir.make_open_path( paths::resolve_path::dirname::(name), Default::default(), @@ -5849,7 +5832,6 @@ impl DevServer { payload.push(MessageId::Visualizer.char()); // PERF(port): was assume_capacity - // TODO(port): inline for over [2]bake.Side + .{client_graph, server_graph} — unrolled macro_rules! emit_files { ($side:expr, $g:expr) => {{ let g = $g; @@ -5934,7 +5916,6 @@ impl DevServer { pub(super) use crate::bake::dev_server::{HmrTopic, MessageId}; bitflags::bitflags! { - // TODO(port): Zig generated `Bits` via @Type from HmrTopic enum fields. // bitflags! requires explicit power-of-two values; field names match enum variants. #[derive(Default, Copy, Clone)] pub struct HmrTopicBits: u8 { @@ -6226,7 +6207,6 @@ impl DevServer { } } -// TODO(port): packed struct(u32) with non-bool fields → repr(transparent) + manual accessors #[repr(transparent)] #[derive(Copy, Clone)] struct SafeFileId(u32); @@ -6422,7 +6402,6 @@ fn dump_state_due_to_crash(dev: &mut DevServer) -> Result<(), bun_core::Error> { ); bun_core::slice_to_nul(&filepath_buf) }; - // TODO(port): std.fs.cwd().createFileZ — use bun_sys let file = match sys::File::create(sys::Fd::cwd(), filepath, true) { Ok(f) => f, Err(err) => { @@ -6461,7 +6440,6 @@ fn dump_state_due_to_crash(dev: &mut DevServer) -> Result<(), bun_core::Error> { Ok(()) } -// TODO(port): packed struct(u32) — Route.Index is 31 bits + 1 bool bit #[repr(transparent)] #[derive(Copy, Clone)] pub struct RouteIndexAndRecurseFlag(pub u32); @@ -6481,9 +6459,6 @@ impl RouteIndexAndRecurseFlag { (self.0 >> 31) != 0 } } -// TODO(port): Zig field-init `.{ .route_index = .., .should_recurse_when_visiting = .. }` -// is used throughout; Phase B should add a `new()` and update callsites. - /// Bake needs to specify which graph (client/server/ssr) each entry point is. #[derive(Default)] pub struct EntryPointList { @@ -6633,7 +6608,7 @@ struct UnrefSourceMapRequest { // BACKREF: DevServer outlives the request; raw ptr avoids the `'static` // bound on `BodyReaderHandler` that a borrowed `&mut DevServer` would violate. dev: *mut DevServer, - body: uws::BodyReaderMixin, // TODO(port): BodyReaderMixin(@This(), "body", runWithBody, finalize) + body: uws::BodyReaderMixin, } bun_core::intrusive_field!(UnrefSourceMapRequest, body: uws::BodyReaderMixin); diff --git a/src/runtime/bake/DevServer/HmrSocket.rs b/src/runtime/bake/DevServer/HmrSocket.rs index 38a31b8cfdf..aaeb675746b 100644 --- a/src/runtime/bake/DevServer/HmrSocket.rs +++ b/src/runtime/bake/DevServer/HmrSocket.rs @@ -259,7 +259,6 @@ impl HmrSocket { return; } - // TODO(port): std.time.Timer — `start_async_bundle` takes Instant. let timer = std::time::Instant::now(); dev.start_async_bundle(event.entry_points, true, timer) // bun.handleOom(err) — Rust aborts on OOM by default diff --git a/src/runtime/bake/FrameworkRouter.rs b/src/runtime/bake/FrameworkRouter.rs index 050015eb014..bcc2b704347 100644 --- a/src/runtime/bake/FrameworkRouter.rs +++ b/src/runtime/bake/FrameworkRouter.rs @@ -78,7 +78,6 @@ pub struct FrameworkRouter { } pub type StaticRouteMap = StringArrayHashMap; -// TODO(port): ArrayHashMap with custom context (EffectiveURLContext) — needs custom Hash/Eq adapter pub type DynamicRouteMap = ArrayHashMap; /// A logical route, for which layouts are looked up on after resolving a route. @@ -2060,7 +2059,6 @@ impl JSFrameworkRouter { let mut rendered: Vec = Vec::with_capacity(filepath.slice().len()); for part in parsed.parts { - // TODO(port): writing fmt into Vec — needs adapter (bstr or io::Write) part.to_string_for_internal_use(&mut ByteFmtWriter::new(&mut rendered)) .expect("ByteFmtWriter is infallible"); } diff --git a/src/runtime/bake/bake_body.rs b/src/runtime/bake/bake_body.rs index 018f051e0b7..4cd80cba91c 100644 --- a/src/runtime/bake/bake_body.rs +++ b/src/runtime/bake/bake_body.rs @@ -1557,7 +1557,7 @@ pub struct PatternBuffer { impl PatternBuffer { pub const EMPTY: PatternBuffer = PatternBuffer { - bytes: PathBuffer::ZEROED, // TODO(port): Zig used `undefined`; uninit not const-safe + bytes: PathBuffer::ZEROED, i: core::mem::size_of::() as u32, }; diff --git a/src/runtime/cli/audit_command.rs b/src/runtime/cli/audit_command.rs index 1d762f28e91..233f626c732 100644 --- a/src/runtime/cli/audit_command.rs +++ b/src/runtime/cli/audit_command.rs @@ -847,7 +847,6 @@ fn print_enhanced_audit_report( dependents: paths, }; } - // TODO(port): Zig pushes a copy of the (POD) struct; cloned here. result.value_ptr.vulnerabilities.push(VulnerabilityInfo { severity: vulnerability.severity.clone(), title: vulnerability.title.clone(), @@ -902,7 +901,6 @@ fn print_enhanced_audit_report( } reversed_items.reverse(); - // TODO(port): std.mem.join → manual join into Vec. let mut vuln_pkg_path: Vec = Vec::new(); for (i, item) in reversed_items.iter().enumerate() { if i > 0 { diff --git a/src/runtime/cli/build_command.rs b/src/runtime/cli/build_command.rs index 80faa0d0c7f..fb60095c160 100644 --- a/src/runtime/cli/build_command.rs +++ b/src/runtime/cli/build_command.rs @@ -381,7 +381,6 @@ impl BuildCommand { resolve_path::get_if_exists_longest_common_path(&entries).unwrap_or(b".") }; - // TODO(port): std.posix.toPosixPath — NUL-terminate path into a stack buffer let dir = match bun_sys::open_dir_at(Fd::cwd(), path) { Ok(d) => d, Err(err) => { @@ -473,7 +472,6 @@ impl BuildCommand { MacroOptions::Unspecified => {} } - // TODO(port): client_transpiler is left uninitialized in Zig until needed; using Option here let mut client_transpiler: Option = None; if this_transpiler.options.server_components { let mut ct = transpiler::Transpiler::init(arena, log, ctx.args.clone(), None)?; @@ -811,7 +809,6 @@ impl BuildCommand { outfile = b"index"; } - // TODO(port): outfile may need owned storage when reassigned to allocated buffer below let mut outfile_owned: Vec; if compile_target.os == OperatingSystem::Windows && !strings::has_suffix_comptime(outfile, b".exe") @@ -1135,7 +1132,6 @@ fn print_summary( let bundle_elapsed = if minified { bundle_until_now - i64::try_from((minify_duration as u64) & ((1u64 << 63) - 1)).unwrap() - // TODO(port): @as(u63, @truncate(minify_duration)) — masked to 63 bits above } else { bundle_until_now }; diff --git a/src/runtime/cli/bunx_command.rs b/src/runtime/cli/bunx_command.rs index a10dfce893f..41aeb5854d1 100644 --- a/src/runtime/cli/bunx_command.rs +++ b/src/runtime/cli/bunx_command.rs @@ -483,7 +483,6 @@ impl BunxCommand { if is_stale { let _ = target_package_json.close(); // If delete fails, oh well. Hope installation takes care of it. - // TODO(port): Zig used std.fs.cwd().deleteTree; map to bun_sys recursive rm. let _ = bun_sys::Dir::cwd().delete_tree(tempdir_name); return Err(bun_core::err!("NeedToInstall")); } @@ -900,7 +899,6 @@ impl BunxCommand { path = { let mut v = Vec::new(); let path_is_nonzero = !path.is_empty(); - // TODO(port): bun.pathLiteral() applied platform separator at comptime. write!( &mut v, "{tmp}{sep}bunx-{uid}-{pkg}{sep}node_modules{sep}.bin", @@ -1255,7 +1253,6 @@ impl BunxCommand { Global::exit(1); } - // TODO(port): Zig used std.fs.cwd().makeOpenPath; map to bun_sys recursive mkdir + open. let bunx_install_dir = Fd::cwd().make_open_path(bunx_cache_dir)?; 'create_package_json: { @@ -1353,7 +1350,6 @@ impl BunxCommand { BStr::new(&install_param), err.name(), ); - // TODO(port): @errorName(err) → err.name() Global::exit(1); } Ok(maybe) => match maybe { diff --git a/src/runtime/cli/create_command.rs b/src/runtime/cli/create_command.rs index 39884aabbee..55b52956308 100644 --- a/src/runtime/cli/create_command.rs +++ b/src/runtime/cli/create_command.rs @@ -135,7 +135,6 @@ fn exec_task(task_: &[u8], cwd: &[u8], _path: &[u8], npm_client: Option = const { core::cell::RefCell::new([[0u8; 1024]; 2]) }; static BUF_INDEX: Cell = const { Cell::new(0) }; @@ -447,7 +446,6 @@ impl CreateCommand { let file_buf = vec![0u8; 16384]; - // TODO(port): ArrayListUnmanaged with pre-allocated buffer — using Vec directly let mut tarball_buf_list: Vec = file_buf; let mut gunzip = Zlib::ZlibReaderArrayList::init( tarball_bytes.list.as_slice(), @@ -730,7 +728,6 @@ impl CreateCommand { let path_env = env_loader.map.get(b"PATH").unwrap_or(b""); { - // TODO(port): std.fs.openDirAbsolute — use bun_sys let parent_dir = bun_sys::Dir::open(destination)?; #[cfg(windows)] { @@ -1089,7 +1086,6 @@ impl CreateCommand { } pub(crate) fn npx_react_scripts_build() -> bun_ast::Expr { - // TODO(port): build bun_ast::Expr { .e_string = "npx react-scripts build" } bun_ast::Expr::init( bun_ast::E::EString::init(b"npx react-scripts build"), bun_ast::Loc::EMPTY, @@ -2367,7 +2363,6 @@ impl Example { Global::crash(); } - // TODO(port): Zig returned `mutable.*` (deref-copy of struct). MutableString may need Clone. Ok(mutable.clone()?) } @@ -2542,7 +2537,6 @@ impl Example { refresher.refresh(); - // TODO(port): see note above re: returning MutableString by value Ok(mutable.clone()?) } @@ -2758,7 +2752,6 @@ impl CreateListExamplesCommand { struct GitHandler; -// TODO(port): mutable static atomic + thread handle — single use per process static SUCCESS: AtomicU32 = AtomicU32::new(0); // Zig used `std.Thread`; bun_threading has no top-level Thread wrapper yet, // so use std::thread::JoinHandle directly (CLI-only, no JSC interaction). diff --git a/src/runtime/cli/filter_run.rs b/src/runtime/cli/filter_run.rs index f133eadf58c..930185b387b 100644 --- a/src/runtime/cli/filter_run.rs +++ b/src/runtime/cli/filter_run.rs @@ -92,8 +92,6 @@ impl<'a> ProcessHandle<'a> { handle.config.combined.as_ptr().cast(), core::ptr::null(), ]; - // TODO(port): Zig uses `[_:null]?[*:0]const u8` (null-terminated array of nullable C strings). - handle.start_time = Some(Instant::now()); let spawned: spawn::SpawnProcessResult = 'brk: { // Get the envp with the PATH configured @@ -256,8 +254,6 @@ bun_io::impl_buffered_reader_parent! { } /// `Output.prettyFmt(str, true)` — comptime ANSI-tag expansion in Zig. -// TODO(port): `pretty_fmt` is comptime string processing in Zig; needs a `const fn` or macro -// in `bun_core::Output`. Using a thin wrapper macro for now. macro_rules! fmt { ($s:literal) => { bun_core::Output::pretty_fmt!($s, true) @@ -582,7 +578,6 @@ impl<'a> State<'a> { } fn flush_draw_buf(&self) { - // TODO(port): std::fs::File::stdout() banned — use bun_sys stdout write. let _ = bun_sys::File::stdout().write_all(&self.draw_buf); } @@ -914,9 +909,7 @@ pub(crate) fn run_scripts_with_filter( } }; - let handles: Box<[ProcessHandle]> = - // TODO(port): Box::new_uninit_slice — handles initialized in loop below. - Vec::with_capacity(scripts.len()).into(); + let handles: Box<[ProcessHandle]> = Vec::with_capacity(scripts.len()).into(); // PORT NOTE: reshaped for borrowck — Zig allocates uninit slice then writes each element. // We build into a Vec first, but need stable addresses for `&state` backref and `&mut handles[i]` // pointers stored in `map`. This is self-referential; raw pointers used below. diff --git a/src/runtime/cli/init_command.rs b/src/runtime/cli/init_command.rs index 6eed5643048..b737c836b12 100644 --- a/src/runtime/cli/init_command.rs +++ b/src/runtime/cli/init_command.rs @@ -35,8 +35,6 @@ impl InitCommand { label: &'static str, default: &[u8], ) -> Result, Error> { - // TODO(port): Zig returns `[:0]const u8` (NUL-terminated, length-carrying). - // We return `Vec` here and NUL-terminate at the call sites that need it. #[allow(clippy::disallowed_methods)] // label is a runtime parameter that may contain markup Output::pretty(format_args!("{}", label)); @@ -56,7 +54,6 @@ impl InitCommand { }); let mut input: Vec = Vec::new(); - // TODO(port): bun.Output.buffered_stdin.reader().readUntilDelimiterArrayList(&input, '\n', 1024) Output::buffered_stdin_read_until_delimiter(&mut input, b'\n', 1024)?; if strings::ends_with_char(&input, b'\r') { @@ -376,7 +373,6 @@ impl InitCommand { } if let Some(ifdir) = initialize_in_folder { - // TODO(port): std.fs.cwd().makePath → bun_sys::make_path / bun.makePath if let Err(err) = bun_sys::Dir::cwd().make_path(ifdir) { bun_core::pretty_errorln!( "Failed to create directory {}: {}", @@ -402,12 +398,10 @@ impl InitCommand { let _ = Fs::FileSystem::init(None)?; let pathname = Fs::PathName::init(Fs::FileSystem::get().top_level_dir_without_trailing_slash()); - // TODO(port): std.fs.cwd() → bun_sys::Fd::cwd(); the Zig kept a std.fs.Dir handle let destination_dir = Fd::cwd(); let mut fields = PackageJSONFields::default(); - // TODO(port): destination_dir.openFile("package.json", .{ .mode = .read_write }) catch null let mut package_json_file: Option = bun_sys::File::openat(destination_dir, b"package.json", bun_sys::O::RDWR, 0).ok(); let mut package_json_contents: MutableString = MutableString::init_empty(); @@ -509,7 +503,6 @@ impl InitCommand { .or_else(|| package_json_expr.get(b"main")) { if let Some(str_) = name.as_utf8_string_literal() { - // TODO(port): asStringZ returns NUL-terminated; we store bytes only fields.entry_point = str_.to_vec(); } } @@ -884,7 +877,6 @@ impl InitCommand { } } - // TODO(port): entry_point must be NUL-terminated for createNew let mut ep_z = fields.entry_point.clone(); ep_z.push(0); let ep_zstr = ZStr::from_slice_with_nul(&ep_z[..]); @@ -1133,8 +1125,6 @@ pub struct PackageJSONFields { pub type_: &'static [u8], /// ARENA: allocated from `bun_ast::Expr` Store via `initialize_store()`; no deinit. pub object: Option>, - // TODO(port): Zig type was `[:0]const u8`; we drop the NUL sentinel and - // re-terminate at FFI boundaries. pub entry_point: Vec, pub private: bool, } @@ -1494,7 +1484,6 @@ impl Template { } const AGENT_RULE: &'static [u8] = include_bytes!("./init/rule.md"); - // TODO(port): Zig `[:0]const u8` literal — Rust byte literals are not NUL-terminated. const CURSOR_RULE: TemplateFile = TemplateFile::new( b".cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc", Self::AGENT_RULE, @@ -1540,7 +1529,6 @@ impl Template { } else { template_file.path }; - // TODO(port): asset_path / template_file.path need NUL termination for create_new let asset_path_z = { let mut v = asset_path.to_vec(); v.push(0); @@ -1638,12 +1626,7 @@ impl Template { #[cfg(windows)] { // Zig: `bun.getenvZAnyCase("USER")` walks `std.os.environ` (bun.zig:913). - // `bun_core::getenv_z_any_case` is a TODO stub on Windows that always - // returns None (bun_core/util.rs), so calling it here makes the probe - // dead code. Use `std::env::var`, which on Windows goes through - // `GetEnvironmentVariableW` (inherently case-insensitive) — matching - // the Zig any-case semantics. - if let Ok(user) = std::env::var("USER") { + if let Some(user) = bun_core::getenv_z_any_case(bun_core::zstr!("USER")) { let mut pathbuf = path_buffer_pool::get(); // Zig: `std.fmt.bufPrintZ(..) catch { return false; }` — // fallible on overflow, do not panic. @@ -1651,12 +1634,11 @@ impl Template { use std::io::Write as _; let total = pathbuf.len(); let mut cursor: &mut [u8] = &mut pathbuf[..]; - if cursor - .write_fmt(format_args!( - "C:\\Users\\{}\\AppData\\Local\\Programs\\Cursor\\Cursor.exe", - user - )) - .is_err() + if cursor.write_all(b"C:\\Users\\").is_err() + || cursor.write_all(user).is_err() + || cursor + .write_all(b"\\AppData\\Local\\Programs\\Cursor\\Cursor.exe") + .is_err() { return false; } @@ -1691,9 +1673,6 @@ impl Template { Template::ReactBlank => REACT_BLANK_FILES, Template::ReactTailwind => REACT_TAILWIND_FILES, Template::ReactTailwindShadcn => REACT_SHADCN_FILES, - // TODO(port): Zig `else => &.{.{ &.{}, &.{} }}` constructs a single - // bogus TemplateFile; preserved as an empty slice here since the - // branch is unreachable in practice. _ => &[], } } @@ -1717,7 +1696,6 @@ impl Template { ], ) } else { - // TODO(port): path needs NUL termination for create_new let mut p = path.to_vec(); p.push(0); Assets::create_new( @@ -2003,8 +1981,6 @@ fn is_safe_entry_point_path(path: &[u8]) -> bool { #[inline] fn exists_z(path: &[u8]) -> bool { - // TODO(port): Zig `existsZ` takes `[:0]const u8`; here we accept `&[u8]` and - // let bun_sys handle termination via the non-Z `exists` (copies into a buffer). bun_sys::exists(path) } diff --git a/src/runtime/cli/install_completions_command.rs b/src/runtime/cli/install_completions_command.rs index d730be51cb1..0316374fea4 100644 --- a/src/runtime/cli/install_completions_command.rs +++ b/src/runtime/cli/install_completions_command.rs @@ -124,8 +124,6 @@ impl InstallCompletionsCommand { let mut bunx_path_buf = WPathBuffer::uninit(); - // TODO(port): bun.strings.literal(u16, BUNX_NAME ++ ".cmd") — w!() needs a literal, - // but BUNX_NAME is cfg-dependent. Const-concat or two cfg'd literals. let cmd_suffix: &[u16] = if cfg!(debug_assertions) { w!("bunx-debug.cmd") } else { diff --git a/src/runtime/cli/mod.rs b/src/runtime/cli/mod.rs index 1956fffa88d..0a4a81e3737 100644 --- a/src/runtime/cli/mod.rs +++ b/src/runtime/cli/mod.rs @@ -216,15 +216,14 @@ pub(crate) mod ci_info_generated { pub mod add_completions; #[path = "colon_list_type.rs"] pub mod colon_list_type; -#[path = "shell_completions.rs"] -pub mod shell_completions; -#[path = "which_npm_client.rs"] -pub mod which_npm_client; -// TODO(port): list-of-yarn-commands.rs has duplicate phf_set! keys. #[path = "discord_command.rs"] pub mod discord_command; #[path = "list-of-yarn-commands.rs"] pub mod list_of_yarn_commands; +#[path = "shell_completions.rs"] +pub mod shell_completions; +#[path = "which_npm_client.rs"] +pub mod which_npm_client; // ─── open (minimal open_url; full Editor/EditorContext stays gated) ────────── // TODO(port): full `open.rs` (Editor detection/spawn) needs diff --git a/src/runtime/cli/multi_run.rs b/src/runtime/cli/multi_run.rs index dd47653b406..6a1d516884e 100644 --- a/src/runtime/cli/multi_run.rs +++ b/src/runtime/cli/multi_run.rs @@ -24,10 +24,7 @@ use crate::api::bun::process::{ self as spawn, Process, Rusage, SpawnOptions, SpawnProcessResult, Status, event_loop_handle_to_ctx, }; -// TODO(port): crate path for `bun.DotEnv.Loader` use bun_dotenv::Loader as DotEnvLoader; -// TODO(port): crate path for `bun.io` BufferedReader/ReadState — assumed `bun_io` -// TODO(port): crate path for Output writer type type OutputWriter = bun_core::io::Writer; /// Value type for package.json `scripts` map. Mirrors @@ -41,7 +38,6 @@ type OwnedScriptsMap = StringArrayHashMap>; struct ScriptConfig { label: Box<[u8]>, - // TODO(port): was `[:0]const u8` — NUL-terminated, used directly as argv element command: Box<[u8]>, cwd: Box<[u8]>, /// PATH env var value for this script @@ -1117,8 +1113,6 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result) -> bool { if let Some(paths) = bin_path(editor) { for path in paths { - // TODO(port): replace std.fs.cwd().openFile with bun_sys equivalent - // (bun_sys::File::open / bun_sys::access). Zig used std.fs directly here. match bun_sys::File::open_at(bun_sys::Fd::cwd(), path, bun_sys::O::RDONLY, 0) { bun_sys::Result::Ok(opened) => { let _ = opened.close(); // close error is non-actionable (Zig parity: discarded) @@ -165,7 +163,6 @@ impl Editor { // PORT NOTE: reshaped for borrowck — by_fallback_path_for_editor writes a // 'static slice; we widen `out` to accept it via a temporary. - // TODO(port): lifetime — `out` may need to be `&mut &[u8]` with caller-chosen lifetime. let mut static_out: &'static [u8] = b""; if Self::by_fallback_path_for_editor(editor, Some(&mut static_out)) { *out = static_out; @@ -293,11 +290,6 @@ impl Editor { } spawned.argc = i; - // TODO(port): std.process.Child is banned (PORTING.md: no std::process). - // Zig stored `std.process.Child.init(args_buf[0..i], default_allocator)` here and - // spawned a detached std.Thread to run it. TODO(port): replace with - // crate::process::spawn (async) or a bun_threading worker that owns - // SpawnedEditorContext and calls bun.spawnSync. let spawned_ptr = bun_core::heap::into_raw(spawned); // PORT NOTE: Zig used `std.Thread.spawn(.{}, autoClose, .{spawned})` then `.detach()`. // bun_threading has no detached-spawn helper; std::thread::spawn matches semantics @@ -350,8 +342,6 @@ pub(super) static BIN_NAME: std::sync::LazyLock Option<&'static [&'static ZStr]> { #[cfg(target_os = "macos")] { @@ -402,7 +392,6 @@ pub(super) struct SpawnedEditorContext { pub file_path_buf: [u8; 1024 + MAX_PATH_BYTES], pub buf: [(*const u8, usize); 10], pub argc: usize, - // TODO(port): was `std.process.Child` — replace with a bun spawn handle. } impl Default for SpawnedEditorContext { @@ -431,8 +420,6 @@ fn auto_close(spawned: *mut SpawnedEditorContext) { argv[j] = unsafe { bun_core::ffi::slice(p, l) }; } - // TODO(port): Zig called `child_process.spawn()` then `.wait()` via std.process.Child. - // Mapped to sync::spawn (bun.spawnSync) per src/CLAUDE.md guidance. // FIXME(windows-leak): Zig's autoClose (open.zig:329-335) used std.process.Child // directly (CreateProcessW) and never created a uv loop. The sync::spawn substitution // requires a `WindowsOptions.loop_`; `MiniEventLoop::init_global` heap-allocates a @@ -524,7 +511,6 @@ impl EditorContext { basename = &basename_buf[0..basename.len() + 3]; } - // TODO(port): Zig used std.fs.Dir.writeFile / openFile. Map to bun_sys::File. // `write_file` wants a `&ZStr`; NUL-terminate `basename` into a path buffer. let mut basename_zbuf = PathBuffer::uninit(); let basename_z = bun_paths::resolve_path::z(basename, &mut basename_zbuf); diff --git a/src/runtime/cli/pack_command.rs b/src/runtime/cli/pack_command.rs index 19f168a56dd..3eff3f0fc53 100644 --- a/src/runtime/cli/pack_command.rs +++ b/src/runtime/cli/pack_command.rs @@ -489,8 +489,6 @@ fn new_pack_queue() -> PackQueue { /// (dir, dir_subpath, dir_depth) struct DirInfo(Dir, Box<[u8]>, usize); -// TODO(port): Zig used `string` (borrowed) for the subpath; here owned because -// values are pushed onto a Vec stack and outlive the producing iteration. // ─────────────────────────────────────────────────────────────────────────── // tree iteration (includes / excludes) @@ -2324,7 +2322,6 @@ pub(crate) fn pack( path: ZBox::from_bytes(bin.path.as_bytes()), optional: true, })?; - // TODO(port): Zig pushed a borrowed slice; cloning here } BinType::Dir => { let bin_dir = match dir_open_dir_z( @@ -3024,8 +3021,6 @@ fn run_lifecycle_script( if err == bun_core::err!("OutOfMemory") { return Err(PackError::OutOfMemory); } - // TODO(port): Zig's error set is exactly {MissingShell, OutOfMemory}; - // unreachable here. unreachable!() } } @@ -3214,7 +3209,6 @@ fn archive_package_json( }; entry.set_pathname(bun_core::zstr!("package/package.json")); - // TODO(port): PACKAGE_PREFIX ++ "package.json" comptime concat entry.set_size(i64::try_from(edited_package_json.len()).expect("int cast")); // https://github.com/libarchive/libarchive/blob/898dc8319355b7e985f68a9819f182aaed61b53a/libarchive/archive_entry.h#L185 entry.set_filetype(0o100000); @@ -3360,7 +3354,6 @@ fn edit_root_package_json( if let Some(dependencies_expr) = json.root.get(dependency_group) { if let ExprData::EObject(mut dependencies) = dependencies_expr.data { for dependency in dependencies.properties.slice_mut() { - // TODO(port): Zig iterated `slice()` of `*dependency`; need mutable iter if dependency.key.is_none() { continue; } @@ -3548,7 +3541,6 @@ fn edit_root_package_json( .buffer .list .reserve(json.source.contents.len() + 1); - // TODO(port): ensureTotalCapacity → reserve(n - len) per guide; len==0 here buffer_writer.append_newline = has_trailing_newline; let mut package_json_writer = js_printer::BufferPrinter::init(buffer_writer); @@ -3581,8 +3573,6 @@ fn edit_root_package_json( .ctx .written_without_trailing_zero() .into()) - // TODO(port): return type ownership — Zig returned a borrowed slice into - // package_json_writer's internal buffer; here boxed. } // ─────────────────────────────────────────────────────────────────────────── @@ -3872,8 +3862,6 @@ impl IgnorePatterns { // printArchivedFilesAndPackages // ─────────────────────────────────────────────────────────────────────────── -// TODO(port): Zig used `comptime is_dry_run: bool` to vary the param type -// (`*PackQueue` vs `PackList`). Using a small enum wrapper. enum PackListOrQueue<'a> { Queue(&'a mut PackQueue), List(&'a PackList), diff --git a/src/runtime/cli/patch_command.rs b/src/runtime/cli/patch_command.rs index efb03cd46ec..8756a2f0e5d 100644 --- a/src/runtime/cli/patch_command.rs +++ b/src/runtime/cli/patch_command.rs @@ -9,7 +9,6 @@ pub(crate) struct PatchCommand; impl PatchCommand { pub(crate) fn exec(ctx: command::Context) -> Result<(), bun_core::Error> { - // TODO(port): verify enum path for `.patch` (PackageManager subcommand variant) update_package_json_and_install_catch_error(ctx, bun_install::Subcommand::Patch)?; Ok(()) } diff --git a/src/runtime/cli/pm_pkg_command.rs b/src/runtime/cli/pm_pkg_command.rs index 38a0dda4232..e9a64800765 100644 --- a/src/runtime/cli/pm_pkg_command.rs +++ b/src/runtime/cli/pm_pkg_command.rs @@ -534,7 +534,6 @@ impl PmPkgCommand { } current = arr.items.slice()[index]; - // TODO(port): Expr likely Copy via arena handle; verify. } else { if !matches!(current.data, ExprData::EObject(_)) { return Err(err!("NotFound")); @@ -940,7 +939,6 @@ impl PmPkgCommand { } let content = writer.ctx.written_without_trailing_zero(); - // TODO(port): Zig used std.fs.cwd().writeFile; using bun_sys per porting rules (no std::fs). let path_z = bun_core::ZBox::from_bytes(path); if let Err(e) = bun_sys::File::write_file(bun_sys::Fd::cwd(), path_z.as_zstr(), content) { Output::err_generic( diff --git a/src/runtime/cli/pm_view_command.rs b/src/runtime/cli/pm_view_command.rs index 4f1e5989973..a9ddd56f2bc 100644 --- a/src/runtime/cli/pm_view_command.rs +++ b/src/runtime/cli/pm_view_command.rs @@ -80,7 +80,6 @@ pub(crate) fn view( let scope = manager.scope_for_package_name(name).clone(); let mut url_buf = PathBuffer::uninit(); - // TODO(port): std.fmt.bufPrint — `buf_print` returns the written slice let encoded_name = buf_print( url_buf.0.as_mut_slice(), format_args!("{}", bun_fmt::dependency_url(name)), diff --git a/src/runtime/cli/publish_command.rs b/src/runtime/cli/publish_command.rs index 173879f478e..5146ba531f2 100644 --- a/src/runtime/cli/publish_command.rs +++ b/src/runtime/cli/publish_command.rs @@ -84,8 +84,6 @@ use crate::cli::init_command::InitCommand; use crate::cli::open; use crate::run_command::RunCommand as Run; -// TODO(port): inherent associated type `Digest = [u8; N]` requires nightly -// `inherent_associated_types`; mirror pack_command.rs and spell the array out. type SHA1Digest = [u8; sha::SHA1::DIGEST]; type SHA512Digest = [u8; sha::SHA512::DIGEST]; @@ -137,8 +135,6 @@ pub enum FromTarballError { } bun_core::oom_from_alloc!(FromTarballError); -// TODO(port): Zig defined this as a nested type alias on the Context struct; -// inherent associated types are unstable (rust#8995) so hoist to module scope. pub(crate) type FromWorkspaceError = pack::PackError; impl<'a, const DIRECTORY_PUBLISH: bool> Context<'a, DIRECTORY_PUBLISH> { @@ -1263,7 +1259,6 @@ impl PublishCommand { Output::flush(); // on another thread because pressing enter is not required - // TODO(port): Zig used std.Thread.spawn — bun_threading has no spawn; use std::thread::Builder match std::thread::Builder::new() .spawn(move || Self::press_enter_to_open_in_browser(auth_url_str)) { @@ -1673,7 +1668,6 @@ impl PublishCommand { ..Default::default() }); - // TODO(port): direct mutation of e_object.properties[i] — borrowck reshape may be needed json.data .e_object_mut() .expect("infallible: variant checked") @@ -1759,7 +1753,6 @@ impl PublishCommand { }); } - // TODO(port): direct mutation of e_object.properties[i] — borrowck reshape may be needed json.data .e_object_mut() .expect("infallible: variant checked") @@ -1817,7 +1810,6 @@ impl PublishCommand { } }; - // TODO(port): Zig used std.fs.Dir here for openDirZ — using bun_sys::Fd instead let mut dirs: Vec<(Fd, Box<[u8]>, bool)> = Vec::new(); dirs.push((bin_dir, normalized_bin_dir.as_bytes().into(), false)); @@ -1884,7 +1876,6 @@ impl PublishCommand { }); if entry.kind == bun_sys::EntryKind::Directory { - // TODO(port): Zig used dir.openDirZ — substituting bun_sys::openat let Ok(subdir) = bun_sys::openat(dir, name, bun_sys::O::DIRECTORY, 0) else { continue; diff --git a/src/runtime/cli/repl.rs b/src/runtime/cli/repl.rs index a97937ff9a3..fc4edf35a19 100644 --- a/src/runtime/cli/repl.rs +++ b/src/runtime/cli/repl.rs @@ -411,7 +411,6 @@ impl LineEditor { if self.cursor == self.buffer.len() { self.buffer.extend_from_slice(slice); } else { - // TODO(port): Vec has no insert_slice; splice is equivalent self.buffer .splice(self.cursor..self.cursor, slice.iter().copied()); } @@ -1675,7 +1674,6 @@ impl<'a> Repl<'a> { ..Default::default() }, )?; - // TODO(port): array.writer.flush() — Vec writer needs no flush Ok(Some(array.into_boxed_slice())) } diff --git a/src/runtime/cli/test/ChangedFilesFilter.rs b/src/runtime/cli/test/ChangedFilesFilter.rs index accda5a2768..3226bffc142 100644 --- a/src/runtime/cli/test/ChangedFilesFilter.rs +++ b/src/runtime/cli/test/ChangedFilesFilter.rs @@ -111,7 +111,6 @@ pub(crate) fn filter<'a>( // With a clean working tree and no --watch, nothing can be affected and // there is no watcher to seed, so skip the module-graph scan entirely. if changed_files.count() == 0 && ctx.debug.hot_reload != HotReload::Watch { - // TODO(port): `HotReload::Watch` enum path — confirm crate::cli::Command::HotReload let total = test_files.len(); return Ok(Result { test_files: &mut test_files[0..0], @@ -264,7 +263,6 @@ pub(crate) fn filter<'a>( let mut queue: Vec = Vec::new(); { - // TODO(port): StringSet iteration API — Zig accesses `.map.iterator()` for changed_path in changed_files.keys() { if let Some(&idx) = path_to_index.get(changed_path.as_ref()) { if !affected.is_set(idx as usize) { @@ -350,8 +348,6 @@ pub(crate) fn init_watch_trigger() { let path: ZBox = if let Some(existing) = getenv_z(TRIGGER_FILE_ENV_VAR_Z) { ZBox::from_bytes(existing) } else { - // TODO(port): std.Random.DefaultPrng / std.time.milliTimestamp / std.c.getpid — - // pick Rust equivalents (likely bun_core::time::milli_timestamp() ^ libc::getpid()) // SAFETY: getpid is always safe. let seed: u64 = bun_core::time::milli_timestamp() as u64 ^ unsafe { libc::getpid() } as u64; @@ -700,7 +696,6 @@ fn append_paths(set: &mut StringSet, git_root: &[u8], stdout: &[u8]) { } } -// TODO(port): `HotReload` enum import — placeholder for `ctx.debug.hot_reload != .watch` check use crate::Command::HotReload; // ported from: src/cli/test/ChangedFilesFilter.zig diff --git a/src/runtime/cli/test/parallel/Channel.rs b/src/runtime/cli/test/parallel/Channel.rs index 8d72d880d4e..8101e829c42 100644 --- a/src/runtime/cli/test/parallel/Channel.rs +++ b/src/runtime/cli/test/parallel/Channel.rs @@ -99,7 +99,6 @@ pub type Socket = uws::NewSocketHandler; #[cfg(windows)] pub type Socket = (); -#[allow(dead_code)] pub struct PosixBackend { pub socket: Socket, } @@ -480,8 +479,6 @@ impl Channel { break; } let Ok(kind) = frame::Kind::try_from(self.r#in[head + 4]) else { - // TODO(port): Zig used std.meta.intToEnum; ensure Kind impls - // TryFrom in frame.rs. head += 5usize + len as usize; continue; }; @@ -631,10 +628,6 @@ impl WindowsHandlers { let _ = suggested; &mut self_.backend.read_chunk[..] } - #[allow(dead_code)] - pub(crate) fn on_read(self_: &mut Channel, data: &[u8]) { - self_.ingest(data); - } pub(crate) fn on_error(self_: &mut Channel, _err: bun_sys::E) { // Mirror the POSIX on_close path: detach the transport before // signalling done so the owner can tell EOF apart from a protocol diff --git a/src/runtime/cli/test/parallel/Coordinator.rs b/src/runtime/cli/test/parallel/Coordinator.rs index 1b276dd8364..ea52872f0d4 100644 --- a/src/runtime/cli/test/parallel/Coordinator.rs +++ b/src/runtime/cli/test/parallel/Coordinator.rs @@ -38,7 +38,6 @@ pub struct Coordinator<'a> { pub argv: Box<[bun_spawn::CStrPtr]>, /// One envp per worker slot — same base, with that slot's JEST_WORKER_ID /// and BUN_TEST_WORKER_ID appended. - // TODO(port): []const [:null]?[*:0]const u8 — see argv note. pub envps: Vec, pub workers: &'a mut [Worker], @@ -204,7 +203,6 @@ impl<'a> Coordinator<'a> { if self.bailed || !self.has_undispatched_files() { return; } - // TODO(port): std.time.milliTimestamp() — verify bun_core helper name. let now = bun_core::time::milli_timestamp(); for w in self.workers[..self.spawned_count as usize].iter() { if !w.alive { @@ -502,8 +500,6 @@ impl<'a> Coordinator<'a> { let mut respawned = false; if !self.bailed && self.has_undispatched_files() { - // TODO(port): explicit deinit of ipc/out/err — in Rust these become - // Drop on assignment; verify no double-free with Default::default(). w.ipc = Default::default(); w.out = WorkerPipe::new(PipeRole::Stdout, std::ptr::from_ref::(w)); w.err = WorkerPipe::new(PipeRole::Stderr, std::ptr::from_ref::(w)); @@ -709,7 +705,6 @@ fn is_panic_status(status: &SpawnStatus) -> bool { } fn describe_status<'b>(buf: &'b mut [u8; 32], status: &SpawnStatus) -> &'b [u8] { - // TODO(port): std.fmt.bufPrint — using io::Write on &mut [u8]. match status { SpawnStatus::Exited(e) => { let mut cursor: &mut [u8] = &mut buf[..]; diff --git a/src/runtime/cli/test/parallel/Frame.rs b/src/runtime/cli/test/parallel/Frame.rs index 8c537538506..c9eb7673332 100644 --- a/src/runtime/cli/test/parallel/Frame.rs +++ b/src/runtime/cli/test/parallel/Frame.rs @@ -116,7 +116,6 @@ impl Frame { /// Payload reader; bounds-checked, returns zero/empty on truncation. pub struct Reader<'a> { - // TODO(port): lifetime — borrowed cursor over caller-owned payload slice pub p: &'a [u8], } diff --git a/src/runtime/cli/test/parallel/Worker.rs b/src/runtime/cli/test/parallel/Worker.rs index 42c74d8c558..3a0df6a20ce 100644 --- a/src/runtime/cli/test/parallel/Worker.rs +++ b/src/runtime/cli/test/parallel/Worker.rs @@ -43,9 +43,6 @@ pub struct Worker { /// Commands and results both flow through this channel; backpressure is /// handled by the loop, so a busy worker writing thousands of `test_done` /// frames never truncates and the coordinator never blocks. - // TODO(port): Zig `Channel(Worker, "ipc")` — second comptime arg is the - // field name for `container_of` recovery. Rust side likely uses - // `offset_of!(Worker, ipc)` or an explicit owner-ptr. pub ipc: Channel, pub out: WorkerPipe, pub err: WorkerPipe, @@ -375,7 +372,6 @@ impl Worker { f.str(file); self.ipc.send(f.finish()); self.inflight = Some(file_idx); - // TODO(port): std.time.milliTimestamp() → confirm bun_core helper name. self.dispatched_at = bun_core::time::milli_timestamp(); } @@ -450,9 +446,6 @@ pub enum PipeRole { /// and flushes atomically with the next test result so console output from /// concurrent files never interleaves. pub struct WorkerPipe { - // TODO(port): Zig default `BufferedReader.init(WorkerPipe)` passes the - // owner type for callback vtable wiring. Rust side likely a generic param - // or trait impl. pub reader: bun_io::BufferedReader, pub worker: *const Worker, pub role: PipeRole, diff --git a/src/runtime/cli/test/parallel/aggregate.rs b/src/runtime/cli/test/parallel/aggregate.rs index 7ea910dd76a..403f62ec6e4 100644 --- a/src/runtime/cli/test/parallel/aggregate.rs +++ b/src/runtime/cli/test/parallel/aggregate.rs @@ -31,7 +31,6 @@ fn attr_value(head: &[u8], name: &'static [u8]) -> u32 { return 0; }; let end = start + q as usize; - // TODO(port): narrow error set strings::parse_int::(&head[start..end], 10).unwrap_or(0) } diff --git a/src/runtime/cli/test/parallel/runner.rs b/src/runtime/cli/test/parallel/runner.rs index 940dd42ebb9..8c1beb6a168 100644 --- a/src/runtime/cli/test/parallel/runner.rs +++ b/src/runtime/cli/test/parallel/runner.rs @@ -122,7 +122,6 @@ pub fn run_as_coordinator( unsafe { libc::getpid() as i64 } } }; - // TODO(port): allocPrintSentinel — was arena-backed; sentinel dropped (no C-string consumer on this path) let dir: Box<[u8]> = format_bytes!( "{}/bun-test-worker-{}", bstr::BStr::new(RealFS::get_default_temp_dir()), @@ -173,10 +172,9 @@ pub fn run_as_coordinator( } let mut workers: Vec = Vec::with_capacity(k as usize); - // TODO(port): Zig allocates uninitialized then assigns in-place; Rust pushes - // constructed values. Populate fully BEFORE constructing Coordinator so it - // can hold `&mut [Worker]` without aliasing the push loop. The `coord` - // backref is null here and patched once Coordinator's address is fixed. + // Populate fully BEFORE constructing Coordinator so it can hold + // `&mut [Worker]` without aliasing the push loop. The `coord` backref is + // null here and patched once Coordinator's address is fixed. for i in 0..k { let idx: u32 = i; workers.push(Worker { @@ -525,9 +523,6 @@ fn jsx_runtime_tag_name(r: bun_options_types::schema::api::JsxRuntime) -> &'stat /// `uv.Pipe` over the inherited duplex named-pipe on Windows. pub struct WorkerCommands { pub vm: *mut VirtualMachine, - // TODO(port): Channel(WorkerCommands, "channel") — second comptime arg is - // the field name for intrusive container_of recovery; encode via offset_of - // or a trait impl. pub channel: Channel, /// Coordinator dispatches one `.run` and waits for `.file_done` before /// the next, so a single slot is sufficient. Owned path storage. @@ -760,7 +755,6 @@ fn worker_flush_aggregates( } }; if let Some(junit) = &mut reporter.reporters.junit { - // TODO(port): allocPrintSentinel → ZBox; was bun.default_allocator (leaked) let path = ZBox::from_bytes(format_bytes!("{}/w{}.xml", bstr::BStr::new(dir), id).as_slice()); if !junit.current_file.is_empty() { diff --git a/src/runtime/cli/test_command.rs b/src/runtime/cli/test_command.rs index 8f8283ee972..737f6099709 100644 --- a/src/runtime/cli/test_command.rs +++ b/src/runtime/cli/test_command.rs @@ -1697,7 +1697,6 @@ impl CommandLineReporter { } let mut console_buffer: Vec = Vec::new(); - // TODO(port): std.Io.Writer.Allocating → Vec + adapter let console_writer = &mut console_buffer; let mut avg = Fraction { @@ -1711,9 +1710,6 @@ impl CommandLineReporter { // --- LCOV --- let mut lcov_name_buf = PathBuffer::uninit(); - // TODO(port): the Zig code uses tuple destructuring with comptime branching to make - // lcov_file/lcov_name/lcov_buffered_writer be `void` when !REPORTERS_LCOV. We use - // Option here. let mut lcov_state: Option<(File, &bun_core::ZStr, /*buffered*/ Vec)> = if REPORTERS_LCOV { 'brk: { @@ -1782,7 +1778,6 @@ impl CommandLineReporter { } else { None }; - // TODO(port): errdefer lcov cleanup — using scopeguard with disarm on success let mut lcov_guard = scopeguard::guard( &mut lcov_state, |s: &mut Option<(File, &bun_core::ZStr, Vec)>| { @@ -1894,7 +1889,6 @@ impl CommandLineReporter { console.write_all(&Output::pretty_fmt::(" |\n"))?; } - // TODO(port): console_writer.flush() — Vec has nothing to flush console.write_all(&console_buffer)?; console.write_all(&Output::pretty_fmt::(""))?; // Spec uses `catch return` (NOT `try`) — Zig's `errdefer` does not @@ -1972,7 +1966,6 @@ pub(crate) extern "C" fn BunTest__shouldGenerateCodeCoverage( } let ext = bun_path::extension(slice); - // TODO(port): std.fs.path.extension — using bun_path equivalent // SAFETY: `VirtualMachine::get()` returns the process-lifetime VM pointer; only // called from the JS thread once a VM exists. let loader_by_ext = VirtualMachine::get() diff --git a/src/runtime/cli/update_interactive_command.rs b/src/runtime/cli/update_interactive_command.rs index 032af2e417e..e6ac938fe0b 100644 --- a/src/runtime/cli/update_interactive_command.rs +++ b/src/runtime/cli/update_interactive_command.rs @@ -1432,8 +1432,6 @@ impl UpdateInteractiveCommand { let mut reprint_menu = true; let mut total_lines: usize = 0; let mut last_terminal_width = initial_terminal_size.width; - // TODO(port): errdefer reprint_menu = false; — handled inline below by setting before early return on error. - // TODO(port): defer block that uses state.selected — moved to explicit calls before each return. macro_rules! cleanup_and_reprint { ($reprint:expr) => {{ @@ -2006,7 +2004,6 @@ impl UpdateInteractiveCommand { Output::flush(); // Read input - // TODO(port): std.fs.File.stdin().readerStreaming — use bun_sys stdin byte reader let mut reader = bun_core::output::stdin_reader(); let byte = match reader.take_byte() { Ok(b) => b, diff --git a/src/runtime/cli/which_npm_client.rs b/src/runtime/cli/which_npm_client.rs index a5f50febb78..6e881f4748c 100644 --- a/src/runtime/cli/which_npm_client.rs +++ b/src/runtime/cli/which_npm_client.rs @@ -1,6 +1,5 @@ #[derive(Copy, Clone)] pub(crate) struct NPMClient { - // TODO(port): verify `bin` is always a static literal (no deinit in Zig source) pub bin: &'static [u8], pub tag: Tag, } diff --git a/src/runtime/crypto/EVP.rs b/src/runtime/crypto/EVP.rs index 9a9ad3b38a9..87376790128 100644 --- a/src/runtime/crypto/EVP.rs +++ b/src/runtime/crypto/EVP.rs @@ -64,8 +64,6 @@ impl AlgorithmExt for Algorithm { } } - // TODO(port): Zig built this at comptime via a labeled block iterating - // EnumArray. bun_core::String is not const-constructible; use a lazy static. fn names() -> &'static [BunString] { static NAMES: std::sync::OnceLock<[BunString; ALL.len()]> = std::sync::OnceLock::new(); NAMES diff --git a/src/runtime/crypto/PasswordObject.rs b/src/runtime/crypto/PasswordObject.rs index 45ea5749266..c5985ac1c1f 100644 --- a/src/runtime/crypto/PasswordObject.rs +++ b/src/runtime/crypto/PasswordObject.rs @@ -229,8 +229,6 @@ pub struct Argon2Params { } impl Argon2Params { - // TODO(port): pwhash.argon2.Params.interactive_2id.{m,t} — hard-code Zig stdlib's - // values here once the pwhash shim is settled. pub(crate) const DEFAULT: Argon2Params = Argon2Params { memory_cost: pwhash::argon2::Params::INTERACTIVE_2ID_M, time_cost: pwhash::argon2::Params::INTERACTIVE_2ID_T, diff --git a/src/runtime/crypto/boringssl_jsc.rs b/src/runtime/crypto/boringssl_jsc.rs index cfb63ba2cb9..63501f6356b 100644 --- a/src/runtime/crypto/boringssl_jsc.rs +++ b/src/runtime/crypto/boringssl_jsc.rs @@ -21,7 +21,6 @@ pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { let error_message: &[u8] = bun_core::slice_to_nul(&outbuf[..]); if error_message.len() == PREFIX.len() { - // TODO(port): globalThis.ERR(.BORINGSSL, ...) builder — confirm bun_jsc API shape return global .err( bun_jsc::ErrorCode::BORINGSSL, @@ -30,7 +29,6 @@ pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { .to_js(); } - // TODO(port): globalThis.ERR(.BORINGSSL, ...) builder — confirm bun_jsc API shape global .err( bun_jsc::ErrorCode::BORINGSSL, diff --git a/src/runtime/dispatch.rs b/src/runtime/dispatch.rs index 4e53780fcdb..1ae1c807109 100644 --- a/src/runtime/dispatch.rs +++ b/src/runtime/dispatch.rs @@ -1114,7 +1114,7 @@ pub unsafe fn __bun_fire_timer(t: *mut EventLoopTimer, now: *const ElTimespec, v }; // SAFETY: per fn contract. `bun_test_timeout_callback` takes a // `&bun_core::Timespec`; the low-tier `EventLoopTimer::Timespec` is - // a layout-identical local stub (see EventLoopTimer.rs TODO(port)). + // a layout-identical local stub. let now_core = unsafe { bun_core::Timespec { sec: (*now).sec, diff --git a/src/runtime/dns_jsc/cares_jsc.rs b/src/runtime/dns_jsc/cares_jsc.rs index a41dd347c61..a8ece76e7c4 100644 --- a/src/runtime/dns_jsc/cares_jsc.rs +++ b/src/runtime/dns_jsc/cares_jsc.rs @@ -676,7 +676,6 @@ impl ErrorDeferred { pub(crate) fn reject(mut self, global_this: &JSGlobalObject) -> JsResult<()> { let code = self.errno.code(); - // TODO(port): bun.String.createFormat used Zig {f} spec for bun.String — verify Display impl let message = if let Some(hostname) = &self.hostname { bstr::String::create_format(format_args!( "{} {} {}", diff --git a/src/runtime/dns_jsc/dns.rs b/src/runtime/dns_jsc/dns.rs index 2d39b426bad..0f5f50be1ea 100644 --- a/src/runtime/dns_jsc/dns.rs +++ b/src/runtime/dns_jsc/dns.rs @@ -600,7 +600,6 @@ pub trait CAresRecordType: Sized { pub struct ResolveInfoRequest { // TODO(port): lifetime — TSV says BORROW_PARAM → Option<&'a Resolver> (struct gets <'a>); raw ptr until reconciled with intrusive RC pub resolver_for_caching: Option<*mut Resolver>, - #[allow(dead_code)] pub hash: u64, pub cache: CacheConfig, pub head: CAresLookup, @@ -742,7 +741,6 @@ impl c_ares::ResolveHandler for ResolveInfoRequest { pub struct GetHostByAddrInfoRequest { // TODO(port): lifetime — TSV says BORROW_PARAM → Option<&'a Resolver>; raw ptr for now pub resolver_for_caching: Option<*mut Resolver>, - #[allow(dead_code)] pub hash: u64, pub cache: CacheConfig, pub head: CAresReverse, @@ -995,7 +993,6 @@ impl Drop for CAresNameInfo { pub struct GetNameInfoRequest { // TODO(port): lifetime — TSV says BORROW_PARAM → Option<&'a Resolver>; raw ptr for now pub resolver_for_caching: Option<*mut Resolver>, - #[allow(dead_code)] pub hash: u64, pub cache: CacheConfig, pub head: CAresNameInfo, @@ -1184,7 +1181,6 @@ pub mod get_addr_info_request { /// OWNED hive slot from `FilePoll::init` (returned via `FilePoll::deinit`, /// not `Box`/global-alloc — Zig: `?*bun.Async.FilePoll`). pub file_poll: Option>, - #[allow(dead_code)] pub machport: mach_port, } @@ -1322,7 +1318,6 @@ pub mod get_addr_info_request { } pub enum Backend { CAres, - #[allow(dead_code)] Libinfo(BackendLibInfo), Libc(LibcBackend), } @@ -2273,7 +2268,6 @@ pub mod internal { // this field. #[derive(Default)] - #[allow(dead_code)] pub struct MacAsyncDNS { pub file_poll: Option>, // OWNED hive slot (FilePoll::init) pub machport: mach_port, @@ -2305,11 +2299,6 @@ pub mod internal { } } } - #[cfg(not(target_os = "macos"))] - #[allow(dead_code)] - pub(crate) fn on_machport_change(_this: *mut Request) { - // libinfo machport DNS is macOS-only. - } } pub struct Request { diff --git a/src/runtime/ffi/ffi_body.rs b/src/runtime/ffi/ffi_body.rs index 5c23eb40bae..624ef1017ad 100644 --- a/src/runtime/ffi/ffi_body.rs +++ b/src/runtime/ffi/ffi_body.rs @@ -201,7 +201,7 @@ impl Offsets { // shim materialises from `m_ctx`, which is the systemic R-2 guarantee. #[bun_jsc::JsClass(no_constructor)] pub struct FFI { - pub dylib: JsCell>, // TODO(port): std.DynLib equivalent + pub dylib: JsCell>, pub functions: JsCell>, pub closed: Cell, pub shared_state: Cell>>, @@ -386,7 +386,6 @@ mod stdarg { } pub(super) fn inject(state: &mut TCC::State) { - // TODO(port): TCC::State::add_symbols API — Zig used addSymbolsComptime over a struct literal state .add_symbols(&[ // printf family @@ -2503,7 +2502,6 @@ impl Function { let ptr = context_ptr.map(|p| p as usize).unwrap_or(0); let fmt = bun_fmt::hex_int_upper::<16>(ptr as u64); - // TODO(port): std.fmt.bufPrint → write!-into-slice let written = if !self.arg_types.is_empty() { let mut cursor = std::io::Cursor::new(&mut inner_buf_[1..]); write!( @@ -2568,11 +2566,7 @@ unsafe extern "C" { pub enum Step { Pending, Compiled(Compiled), - #[allow(dead_code)] - Failed { - msg: Box<[u8]>, - allocated: bool, - }, + Failed { msg: Box<[u8]>, allocated: bool }, } pub struct Compiled { @@ -2581,7 +2575,6 @@ pub struct Compiled { pub js_function: JSValue, // Zig: `?*anyopaque` — opaque storage, never dereferenced. NonNull avoids // a &T → *mut T cast at the assignment site in compile_callback(). - #[allow(dead_code)] pub js_context: Option>, pub ffi_callback_function_wrapper: Option>, } @@ -2702,9 +2695,7 @@ impl CompilerRT { } } - // TODO(port): @import("../../jsc/sizes.zig") → bun_jsc::sizes let offsets = Offsets::get(); - // TODO(port): TCC::State::define_symbols_comptime API — Zig used struct literal with int values state.define_symbols(&[ ( "Bun_FFI_PointerOffsetToArgumentsList", @@ -2797,7 +2788,6 @@ struct MyFunctionSStructWorkAround { uint64_to_jsvalue: unsafe extern "C" fn(*mut JSGlobalObject, u64) -> JSValue, } -// TODO(port): JSValue.exposed_to_ffi — these are static fn ptrs from headers static WORKAROUND: MyFunctionSStructWorkAround = MyFunctionSStructWorkAround { jsvalue_to_int64: exposed_to_ffi::JSVALUE_TO_INT64, jsvalue_to_uint64: exposed_to_ffi::JSVALUE_TO_UINT64, diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 49d4e9610c2..eeed5eda3a1 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -329,9 +329,9 @@ unsafe fn init_runtime_state( // validity-invariant UB, so write via `ptr::write` (NOT assignment — the // zeroed bytes are not a valid `Transpiler` to drop). // - // PORT NOTE: `configure_transform_options_for_bun_vm` lives in the - // ``-gated `bun_jsc::config` module; its body (3 field overwrites) is - // inlined below over the caller-supplied `opts.transform_options`. + // PORT NOTE: Zig's `configureTransformOptionsForBunVM` (jsc/config.zig) + // has its body (3 field overwrites) inlined below over the + // caller-supplied `opts.transform_options`. // SAFETY: `vm.log` was set to a fresh leaked `Box` by // `VirtualMachine::init` immediately before this hook fires. let log: *mut bun_ast::Log = unsafe { &*vm } @@ -3002,11 +3002,6 @@ fn transpile_source_code_inner( } // Spec :553-558 — watcher path uses ref-counted source. - // TODO(b2-blocked): `VirtualMachine::ref_counted_resolved_source`. - // Spec RETURNS the ref-counted `ResolvedSource` here (with - // `is_commonjs_module`/`module_info` patched on). Gated so the - // fall-through to the non-watcher tail below is an explicit, - // intentional degradation rather than a silent live divergence. // SAFETY: per fn contract — `jsc_vm` is the live per-thread VM. if unsafe { &*jsc_vm }.is_watcher_enabled() { // SAFETY: `extra.source_code_printer` is non-null per diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index 0e2ea644930..772096e7c2b 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -186,7 +186,6 @@ unsafe impl bun_ptr::ExternalSharedDescriptor for NapiEnv { } } -// TODO(port): bun.ptr.ExternalShared(NapiEnv) — intrusive externally-refcounted handle. pub(super) type NapiEnvRef = bun_ptr::ExternalShared; #[cold] @@ -2572,8 +2571,6 @@ impl ThreadSafeFunction { // TODO: is this boolean necessary? Can we rely just on the closing value? if !self.has_queued_finalizer { self.has_queued_finalizer = true; - // TODO(port): callback.deinit() — Strong handles drop on Drop; here we must - // explicitly clear before enqueuing the finalize task to match Zig ordering. // PORT NOTE: replace callback with a no-op variant to drop Strong now. self.callback = TsfnCallback::Js(StrongOptional::empty()); self.poll_ref.disable(); diff --git a/src/runtime/node.rs b/src/runtime/node.rs index 4fdb840b91e..16b3f5897be 100644 --- a/src/runtime/node.rs +++ b/src/runtime/node.rs @@ -241,9 +241,6 @@ impl MaybeExt for Maybe { // panic message; collapsed to a single panic + type name. panic!("TODO: Maybe({})", core::any::type_name::()); } - // TODO(port): Zig used `@hasDecl(E, "todo")` to optionally call - // `E::todo()` else default-construct. Modeled via `MaybeErrorTodo` - // trait with a default impl returning `E::default()`. Err(E::todo()) } diff --git a/src/runtime/node/StatFS.rs b/src/runtime/node/StatFS.rs index 3afdd6cac7a..f893876771b 100644 --- a/src/runtime/node/StatFS.rs +++ b/src/runtime/node/StatFS.rs @@ -36,8 +36,6 @@ macro_rules! define_statfs_type { fn statfs_to_js(&self, global: &JSGlobalObject) -> JsResult { if $big { - // TODO(port): bun.jsc.fromJSHostCall wraps an extern call with - // JSC exception-scope checking; map to the Rust equivalent. return bun_jsc::from_js_host_call(global, || { Bun__createJSBigIntStatFSObject( global, diff --git a/src/runtime/node/fs_events.rs b/src/runtime/node/fs_events.rs index ccd1c821d75..47d9e4f88bd 100644 --- a/src/runtime/node/fs_events.rs +++ b/src/runtime/node/fs_events.rs @@ -93,12 +93,10 @@ pub(crate) const K_FS_EVENTS_RENAMED: c_int = K_FS_EVENT_STREAM_EVENT_FLAG_ITEM_ | K_FS_EVENT_STREAM_EVENT_FLAG_ITEM_REMOVED | K_FS_EVENT_STREAM_EVENT_FLAG_ITEM_RENAMED; -#[allow(dead_code)] static FSEVENTS_DEFAULT_LOOP_MUTEX: Mutex = Mutex::new(); // PORTING.md §Global mutable state: written under FSEVENTS_DEFAULT_LOOP_MUTEX, // read with double-checked-locking. AtomicPtr gives safe load/store; the mutex // serialises the init/teardown writes (Acquire/Release publishes the pointee). -#[allow(dead_code)] static FSEVENTS_DEFAULT_LOOP: AtomicPtr = AtomicPtr::new(ptr::null_mut()); #[cfg(unix)] @@ -746,7 +744,6 @@ impl FSEventsLoop { } } - #[allow(dead_code)] fn register_watcher(&mut self, watcher: *mut FSEventsWatcher) { { let _guard = self.mutex.lock_guard(); @@ -850,7 +847,6 @@ impl Drop for FSEventsLoop { } // Vec storage freed by its own Drop (or explicit deinit) - // TODO(port): confirm Vec implements Drop or needs explicit deinit() } } @@ -884,7 +880,6 @@ impl FSEventsWatcher { /// global default loop from `FSEventsLoop::init`) for the lifetime of the /// returned watcher; mutable access to its watcher list is serialized by /// `loop_.mutex` inside `register_watcher`. - #[allow(dead_code)] pub(crate) fn init( loop_: NonNull, path: &[u8], @@ -931,7 +926,6 @@ impl Drop for FSEventsWatcher { } } -#[allow(dead_code)] pub fn watch( path: &[u8], recursive: bool, @@ -968,12 +962,10 @@ pub fn watch( } /// `extern "C"` thunk so this fits `bun_core::Global::ExitFn`. -#[allow(dead_code)] extern "C" fn close_and_wait_on_exit() { close_and_wait() } -#[allow(dead_code)] pub(crate) fn close_and_wait() { #[cfg(not(target_os = "macos"))] { diff --git a/src/runtime/node/node_fs_constant.rs b/src/runtime/node/node_fs_constant.rs index 36d1e7cfb2f..36c988f5c30 100644 --- a/src/runtime/node/node_fs_constant.rs +++ b/src/runtime/node/node_fs_constant.rs @@ -58,10 +58,6 @@ pub const O_NOATIME: i32 = O::NOATIME; pub const O_DSYNC: i32 = O::DSYNC; /// Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. pub const O_SYMLINK: i32 = O::SYMLINK; -/// Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. -#[cfg(any(target_os = "linux", target_os = "android"))] -#[allow(dead_code)] -pub(crate) const O_DIRECT: i32 = libc::O_DIRECT; // File Type Constants /// Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. diff --git a/src/runtime/node/node_os.rs b/src/runtime/node/node_os.rs index a7c7d68fc12..e267b4183de 100644 --- a/src/runtime/node/node_os.rs +++ b/src/runtime/node/node_os.rs @@ -35,7 +35,6 @@ pub(crate) fn freemem() -> u64 { // `global.throw_value`) or reaches `bun_sys::posix::sysctlbyname` / // `bun_sys::c::sysinfo` / `crate::gen_::node_os` which are not yet exported. // CPUTimes struct + freemem() + trailing pure helpers hoisted above/below. -// TODO(port): un-gate once bun_jsc + bun_sys::posix syscall surface land. mod _impl { use super::*; @@ -317,7 +316,6 @@ mod _impl { // Read /proc/stat to get number of CPUs and times { - // TODO(port): std.fs.cwd().openFile → bun_sys::File::open (no std::fs) let file = match bun_sys::File::open(bun_core::zstr!("/proc/stat"), bun_sys::O::RDONLY, 0) { Ok(f) => f, @@ -1049,7 +1047,6 @@ mod _impl { // SAFETY: ifa_name is a NUL-terminated C string let interface_name = unsafe { bun_core::ffi::cstr(iface.ifa_name) }.to_bytes(); - // TODO(port): std.net.Address — using bun_sys::net::Address (no std::net) // SAFETY: ifa_addr/ifa_netmask are valid sockaddr* (skip() ensures ifa_addr non-null) let addr = unsafe { bun_sys::net::Address::init_posix(iface.ifa_addr.cast_const()) }; // SAFETY: ifa_netmask is a valid sockaddr* populated by getifaddrs for this entry @@ -1591,7 +1588,6 @@ mod _impl { if bun_sys::posix::sysctl_read(c"kern.boottime", &mut boot_time).is_err() { return Ok(0.0); } - // TODO(port): std.time.timestamp() → bun_sys::time::timestamp() (no std::time wallclock) return Ok((bun_sys::time::timestamp() - boot_time.tv_sec as i64) as f64); } #[cfg(any(target_os = "linux", target_os = "android"))] diff --git a/src/runtime/node/time_like.rs b/src/runtime/node/time_like.rs index e52e57bf103..3ecc8b3424a 100644 --- a/src/runtime/node/time_like.rs +++ b/src/runtime/node/time_like.rs @@ -88,8 +88,6 @@ fn from_milliseconds(milliseconds: f64) -> TimeLike { #[cfg(windows)] fn from_now() -> TimeLike { - // TODO(port): std.time.nanoTimestamp() — confirm bun_core/bun_sys provides a - // nanosecond-since-epoch helper; std::time::SystemTime is a fallback. let nanos = bun_core::time::nano_timestamp(); (nanos as f64) / NS_PER_S } diff --git a/src/runtime/node/types.rs b/src/runtime/node/types.rs index 8724d15b7dd..0623901ff4b 100644 --- a/src/runtime/node/types.rs +++ b/src/runtime/node/types.rs @@ -1599,7 +1599,6 @@ pub fn mode_from_js(ctx: &JSGlobalObject, value: JSValue) -> JsResult(slice, 8) { Ok(v) => v as u32, Err(_) => { @@ -1923,7 +1922,6 @@ pub struct Dirent { pub kind: DirentKind, } -// TODO(port): Zig used `std.fs.File.Kind`. std::fs is banned; map to bun_sys::FileKind. pub type DirentKind = bun_sys::FileKind; // TODO(port): move to runtime_sys diff --git a/src/runtime/node/win_watcher.rs b/src/runtime/node/win_watcher.rs index 4ee2e9d80da..95ac6d11383 100644 --- a/src/runtime/node/win_watcher.rs +++ b/src/runtime/node/win_watcher.rs @@ -190,10 +190,7 @@ impl ChangeEvent { } } -#[allow(dead_code)] pub type Callback = fn(ctx: Option<*mut c_void>, event: Event, is_file: bool); -#[allow(dead_code)] -pub(crate) type UpdateEndCallback = fn(ctx: Option<*mut c_void>); impl PathWatcher { extern "C" fn uv_event_callback( diff --git a/src/runtime/node/zlib/NativeBrotli.rs b/src/runtime/node/zlib/NativeBrotli.rs index ef9761d7663..8b78f137e15 100644 --- a/src/runtime/node/zlib/NativeBrotli.rs +++ b/src/runtime/node/zlib/NativeBrotli.rs @@ -70,7 +70,6 @@ mod _impl { // In Rust the handle type is `bun_ptr::IntrusiveRc`; the // `ref_count` field below is read/written by that wrapper, and `deinit` is the // drop body invoked when the count reaches zero. - // TODO(port): wire `ref`/`deref` via `bun_ptr::IntrusiveRc` impl. // `.classes.ts`-backed: the C++ JSCell wrapper (JSNativeBrotli) is generated; // this struct is the `m_ctx` payload. Codegen provides toJS/fromJS/fromJSDirect. @@ -99,7 +98,6 @@ mod _impl { // write / runFromJSThread / writeSync / reset / close / setOnError / // getOnError / finalize / emitError. In Rust these are generic associated // fns on `CompressionStream::` (see node_zlib_binding.rs). - // TODO(port): expose via inherent-looking methods so .classes.ts codegen can resolve them. impl NativeBrotli { // PORT NOTE: no `#[bun_jsc::host_fn]` — the free-fn shim it emits calls diff --git a/src/runtime/node/zlib/NativeZlib.rs b/src/runtime/node/zlib/NativeZlib.rs index eafe4afc869..7fb529ecdf4 100644 --- a/src/runtime/node/zlib/NativeZlib.rs +++ b/src/runtime/node/zlib/NativeZlib.rs @@ -10,7 +10,6 @@ use crate::node::node_zlib_binding::Error; // `#[bun_jsc::host_fn]`s; field types (`Strong`, `WorkPoolTask`) are not yet // exported with the expected shapes. The pure-FFI `Context` (zlib state // machine) is hoisted below as the non-JSC body. -// TODO(port): un-gate once bun_jsc Strong/JsClass + bun_threading::WorkPoolTask land. mod _impl { use super::*; diff --git a/src/runtime/server/AnyRequestContext.rs b/src/runtime/server/AnyRequestContext.rs index 13382b2daae..3a0ce9d97e3 100644 --- a/src/runtime/server/AnyRequestContext.rs +++ b/src/runtime/server/AnyRequestContext.rs @@ -130,7 +130,6 @@ macro_rules! dispatch { // set_timeout / set_cookies / set_timeout_handler / get_remote_socket_info / // on_abort / ref_ / deref / set_signal_aborted forward to RequestContext // methods that live in `_gated_state_machine`. Un-gate alongside. -// TODO(port): RequestContext state-machine bodies. impl AnyRequestContext { pub fn set_additional_on_abort_callback(self, cb: Option) { diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index d5d8c9e8b19..3ed131ba36a 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -137,9 +137,6 @@ pub struct RequestContext< /// pointee is live for the holder's entire lifetime. `None` once detached. pub server: Option>, pub resp: Option, - /// thread-local default heap allocator - /// this prevents an extra pthread_getspecific() call which shows up in profiling - // TODO(port): allocator field deleted — global mimalloc per PORTING.md §Allocators. pub req: Option<*mut Req>, pub request_weakref: request::WeakRef, // PORT NOTE: Zig `?*AbortSignal`. `Arc` was wrong — @@ -850,8 +847,6 @@ where } /// destroy RequestContext, should be only called by deref or if defer_deinit_until_callback_completes is ref is set to true - // TODO(port): named `deinit` (not Drop) because RequestContext is pool-allocated and - // explicitly returned to a HiveArray; Drop semantics don't apply. pub fn deinit(&mut self) { ctx_log!("deinit"); self.detach_response(); @@ -1022,18 +1017,13 @@ where } } - // TODO(b2-blocked): `Api::FallbackMessageContainer` + `Fallback::render_backend` - // (bun_options_types::schema::api / bun_ast::runtime) — debug-only HTML - // error page. Production hits `render_production_error` instead. - pub fn render_default_error( &mut self, - // TODO(port): arena_allocator param dropped; this is a non-AST crate, allocations use global mimalloc. // PERF(port): was arena bulk-free — profile in Phase B log: &mut bun_ast::Log, err: bun_core::Error, exceptions: &[Api::JsException], - fmt: core::fmt::Arguments<'_>, // TODO(port): Zig `comptime fmt: string, args: anytype` + fmt: core::fmt::Arguments<'_>, ) { if !self.flags.has_written_status() { self.flags.set_has_written_status(true); @@ -1242,7 +1232,6 @@ where } } - // TODO(port): in-place init — `this` is a pre-allocated slot in a HiveArray pool. pub fn create( this: &mut core::mem::MaybeUninit, server: *const ThisServer, @@ -2765,9 +2754,6 @@ where req.render_metadata(); } - // TODO(b2-blocked): DEBUG_MODE dev-server HTML fallback page — gated on - // `Api::FallbackMessageContainer`/`Fallback::render_backend`. - if DEBUG_MODE { if let Some(server) = req.server { if !err.is_empty_or_undefined_or_null() { @@ -3005,7 +2991,6 @@ where } pub fn on_pipe(this: &mut Self, mut stream: WebCore::streams::Result) { - // TODO(port): allocator param dropped — global mimalloc per §Allocators let stream_needs_deinit = matches!( stream, WebCore::streams::Result::Owned(_) | WebCore::streams::Result::OwnedAndDone(_) @@ -3160,10 +3145,6 @@ where // SAFETY: BACKREF let server = &*server; let global_this = server.global_this(); - // TODO(b2-blocked): DEBUG_MODE branch renders the HTML fallback page via - // `Api::JsException` + `render_default_error`; gated until bun_schema/ - // bun_js_parser surfaces are in. Falls through to the production path. - // `ServerLike::vm()` is the process-static VM `BackRef`; `as_mut()` is // the single audited `&mut VirtualMachine` accessor. let vm = server.vm().as_mut(); @@ -3416,7 +3397,6 @@ where // Advertise the QUIC endpoint on H1/H2 responses so browsers can // discover it (RFC 7838). Multiple Alt-Svc fields are valid, so a // user-supplied one composes rather than conflicts. - // TODO(port): `@hasDecl(ThisServer, "h3AltSvc")` — model as optional trait method. if !HTTP3 { // SAFETY: BACKREF if let Some(alt) = self.server().h3_alt_svc() { diff --git a/src/runtime/server/ServerConfig.rs b/src/runtime/server/ServerConfig.rs index f64a3e505b8..da61463bc2c 100644 --- a/src/runtime/server/ServerConfig.rs +++ b/src/runtime/server/ServerConfig.rs @@ -749,7 +749,6 @@ impl ServerConfig { for port_env in PORT_ENV { if let Some(port) = env.get(port_env) { - // TODO(port): std.fmt.parseInt(u16, port, 10) — using helper if let Ok(_port) = bun_core::immutable::parse_int::(port, 10) { break 'brk _port; } diff --git a/src/runtime/server/WebSocketServerContext.rs b/src/runtime/server/WebSocketServerContext.rs index f068c4da405..e793df19576 100644 --- a/src/runtime/server/WebSocketServerContext.rs +++ b/src/runtime/server/WebSocketServerContext.rs @@ -50,10 +50,6 @@ bitflags::bitflags! { } } -// JS callback bodies — gated until bun_jsc method surface (JSValue::call, -// get_truthy, protect, JSGlobalObject::throw_*) is available. -// TODO(port): bun_jsc::{JSValue, JSGlobalObject} methods. - impl Handler { /// Deref the raw `global_object` pointer. /// SAFETY: `global_object` is set by the server before any websocket @@ -267,9 +263,6 @@ fn lookup_zig_string( table.get(key.slice()).copied() } -// TODO(port): bun_jsc::JSValue::{get, get_truthy, to_boolean, is_string, -// get_zig_string, to_int64, is_any_int}. - pub(crate) fn on_create( global_object: &JSGlobalObject, object: JSValue, diff --git a/src/runtime/server/server_body.rs b/src/runtime/server/server_body.rs index b882c9ecfac..5fe2628a107 100644 --- a/src/runtime/server/server_body.rs +++ b/src/runtime/server/server_body.rs @@ -832,7 +832,6 @@ impl AnyRoute { } pub struct ServerInitContext<'a> { - // TODO(port): arena removed in non-AST crate; if needed for bulk-free, reintroduce bumpalo pub dedupe_html_bundle_map: HashMap<*const HTMLBundle, RefPtr>, pub js_string_allocations: bake::StringRefList, pub global: &'a JSGlobalObject, diff --git a/src/runtime/shell/EnvStr.rs b/src/runtime/shell/EnvStr.rs index 43e5ee8e438..d52a0d55801 100644 --- a/src/runtime/shell/EnvStr.rs +++ b/src/runtime/shell/EnvStr.rs @@ -93,7 +93,6 @@ impl EnvStr { // duplicated bytes transfers to RefCountedStr. let str: Box<[u8]> = Box::<[u8]>::from(old_str); let len = str.len(); - // TODO(port): RefCountedStr::init signature — assumed to take ownership and return *mut RefCountedStr Self::pack( to_ptr(RefCountedStr::init(str) as *const c_void), Tag::Refcounted, diff --git a/src/runtime/shell/shell_body.rs b/src/runtime/shell/shell_body.rs index 386f6adf0e2..b8da8871c2f 100644 --- a/src/runtime/shell/shell_body.rs +++ b/src/runtime/shell/shell_body.rs @@ -274,7 +274,6 @@ impl<'a> GlobalJS<'a> { #[inline] pub fn create_null_delimited_env_map( self, - // TODO(port): allocator param dropped (global mimalloc) ) -> Result { // SAFETY: bun_vm() is non-null for a Bun-owned global; `transpiler.env` is a // long-lived `*mut Loader` owned by the VM. @@ -457,7 +456,6 @@ impl<'a> GlobalMini<'a> { pub struct CmdEnvIter<'a> { pub env: &'a mut bun_collections::StringArrayHashMap>, - // TODO(port): Zig `[:0]const u8` value — confirm map value type. pub iter: bun_collections::array_hash_map::Iter<'a, Box<[u8]>, Box>, } diff --git a/src/runtime/shell/subproc.rs b/src/runtime/shell/subproc.rs index eeb98c15cdd..5c18b75af28 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -277,8 +277,6 @@ pub struct ShellSubprocess { pub event_loop: EventLoopHandle, pub closed: EnumSet, - // TODO(port): this_jsvalue was always .zero in Zig (never assigned) — dropped. - // A bare JSValue field on a Box-allocated struct is a UAF per PORTING.md §JSC. pub flags: Flags, } @@ -1869,8 +1867,6 @@ impl CapturedWriter { } pub fn on_error(&mut self, err: &bun_sys::Error) { - // TODO(port): Zig assigns bun.sys.Error to ?jsc.SystemError field — type mismatch - // in original (dead code under lazy compilation). self.err = Some(err.to_system_error()); } diff --git a/src/runtime/shell/util.rs b/src/runtime/shell/util.rs index 1a74a3fec18..577326bac23 100644 --- a/src/runtime/shell/util.rs +++ b/src/runtime/shell/util.rs @@ -11,8 +11,4 @@ pub enum OutKind { // `bun_spawn` *crate* re-exports under the same name. pub use crate::api::bun_spawn::stdio::Stdio; -#[cfg(any(target_os = "linux", target_os = "android"))] -#[allow(dead_code)] -pub(crate) type WatchFd = core::ffi::c_int; // std.posix.fd_t - // ported from: src/shell/util.zig diff --git a/src/runtime/socket/Handlers.rs b/src/runtime/socket/Handlers.rs index 464e7d9ba6c..df148474690 100644 --- a/src/runtime/socket/Handlers.rs +++ b/src/runtime/socket/Handlers.rs @@ -147,7 +147,6 @@ impl Handlers { // corker: Corker = .{}, - // TODO(port): bun.JSTerminated!void — mapping to JsResult<()> (JsError::Terminated covers it) pub fn resolve_promise(&self, value: JSValue) -> JsResult<()> { let vm = self.vm; if vm.is_shutting_down() { @@ -164,7 +163,6 @@ impl Handlers { Ok(()) } - // TODO(port): bun.JSTerminated!bool — mapping to JsResult pub fn reject_promise(&self, value: JSValue) -> JsResult { let vm = self.vm; if vm.is_shutting_down() { @@ -441,7 +439,6 @@ impl Scope { } } -// TODO(port): GeneratedBinaryType is the enum in jsc.generated.SocketConfigHandlers.binary_type use bun_jsc::generated::SocketConfigHandlersBinaryType as GeneratedBinaryType; /// `handlers` is always `protect`ed in this struct. @@ -465,9 +462,8 @@ impl SocketConfig { /// Deinitializes everything except `handlers`. pub fn deinit_excluding_handlers(&mut self) { - // TODO(port): in Zig this writes `undefined` to all non-handlers fields after - // freeing them, then restores `handlers`. In Rust we drop the owned non-handlers - // fields in place; `handlers` is left untouched so pointers into it remain valid. + // Drops the owned non-handlers fields in place; `handlers` is left + // untouched so pointers into it remain valid. self.hostname_or_unix = ZigStringSlice::empty(); self.ssl = None; // other scalar fields need no cleanup @@ -567,7 +563,6 @@ impl SocketConfig { result.port = Some(match generated.port { Some(p) => p, None => match bun_url::URL::parse(slice).get_port() { - // TODO(port): bun.URL.parse — confirm crate path Some(p) => p, None => { return Err( @@ -600,7 +595,6 @@ impl SocketConfig { } } -// TODO(port): GeneratedTls is the union(enum) at jsc.generated.SocketConfig.tls use bun_jsc::generated::SocketConfigTls as GeneratedTls; // ported from: src/runtime/socket/Handlers.zig diff --git a/src/runtime/socket/Listener.rs b/src/runtime/socket/Listener.rs index 205eea54f6e..00514d67519 100644 --- a/src/runtime/socket/Listener.rs +++ b/src/runtime/socket/Listener.rs @@ -190,7 +190,6 @@ impl Listener { // Only deinit handlers if there's an error; otherwise we put them in a `Listener` and // need them to stay alive. - // TODO(port): errdefer handlers.deinit() — scopeguard captures &mut into socket_config; reshaped below. let port = socket_config.port; let ssl_enabled = socket_config.ssl.is_some(); diff --git a/src/runtime/socket/SocketAddress.rs b/src/runtime/socket/SocketAddress.rs index 642fd0da077..e24c8bdb37e 100644 --- a/src/runtime/socket/SocketAddress.rs +++ b/src/runtime/socket/SocketAddress.rs @@ -9,10 +9,9 @@ use core::cell::Cell; use core::ffi::{c_int, c_void}; use core::mem; +use bun_cares_sys::c_ares as ares; use bun_core::{OwnedString, String as BunString, ZStr}; use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsClass, JsError, JsResult, StringJsc, URL}; -// TODO(port): move to _sys — c-ares FFI lives in bun_cares_sys -use bun_cares_sys::c_ares as ares; // `pub const js = jsc.Codegen.JSSocketAddress;` + toJS/fromJS/fromJSDirect // → handled by the JsClass derive; codegen wires toJS/fromJS/fromJSDirect. @@ -781,7 +780,6 @@ fn pton_noerr(af: c_int, addr: &[u8], dst: *mut c_void) -> bool { // FIXME: c-headers-for-zig casts AF_* and PF_* to `c_int` when it should be `comptime_int` #[repr(u16)] -// TODO(port): repr should be inet::sa_family_t but Rust requires concrete int; sa_family_t is u16 on posix+win #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum AF { INET = inet::AF_INET as u16, @@ -1045,15 +1043,9 @@ pub mod inet { #![allow(non_camel_case_types)] use bun_sys::windows::ws2_32 as ws2; // PORT NOTE: `bun_windows_sys::ws2_32` does not currently surface - // `IN4ADDR_LOOPBACK` / `INET6_ADDRSTRLEN` / `ADDRESS_FAMILY` / `USHORT`; - // mirror the `ws2ipdef.h` / `ws2def.h` values locally so the Windows - // build resolves without widening the leaf crate. - /// `ws2ipdef.h`: `#define IN4ADDR_LOOPBACK 0x0100007f` — the raw - /// **network-order** `s_addr` value for 127.0.0.1. Spelled via - /// `from_ne_bytes` so the wire bytes `[127,0,0,1]` are explicit (yields - /// `0x0100_007f` on little-endian Windows, matching the header literal). - #[allow(dead_code)] - pub(crate) const IN4ADDR_LOOPBACK: u32 = u32::from_ne_bytes([127, 0, 0, 1]); + // `INET6_ADDRSTRLEN` / `ADDRESS_FAMILY` / `USHORT`; mirror the + // `ws2ipdef.h` / `ws2def.h` values locally so the Windows build + // resolves without widening the leaf crate. /// `ws2ipdef.h`: `INET6_ADDRSTRLEN == 65` on Windows (vs 46 on POSIX). pub use bun_sys::posix::INET6_ADDRSTRLEN; pub(crate) const IN6ADDR_ANY_INIT: [u8; 16] = [0; 16]; @@ -1066,7 +1058,6 @@ pub mod inet { #[cfg(not(windows))] pub mod inet { #![allow(non_camel_case_types)] - pub const IN4ADDR_LOOPBACK: u32 = u32::from_ne_bytes([127, 0, 0, 1]); pub use bun_sys::posix::INET6_ADDRSTRLEN; // Make sure this is in line with IN6ADDR_ANY_INIT in `netinet/in.h` on all platforms. pub(crate) const IN6ADDR_ANY_INIT: [u8; 16] = [0; 16]; diff --git a/src/runtime/socket/WindowsNamedPipe.rs b/src/runtime/socket/WindowsNamedPipe.rs index 9dab8f4247b..f2d26137295 100644 --- a/src/runtime/socket/WindowsNamedPipe.rs +++ b/src/runtime/socket/WindowsNamedPipe.rs @@ -72,9 +72,6 @@ pub struct WindowsNamedPipe { /// (`bun_io::EventLoopHandle` wraps `*const EventLoopHandle`). pub event_loop_handle: bun_jsc::EventLoopHandle, - // TODO(port): `bun.io.StreamingWriter(WindowsNamedPipe, .{ onClose, onWritable, onError, onWrite })` - // is a comptime type-generator binding callbacks at type level. Encode callbacks as a - // trait impl (`impl StreamingWriterHandler for WindowsNamedPipe`) or const-generic vtable. pub writer: StreamingWriter, pub incoming: Vec, // Maybe we should use IPCBuffer here as well diff --git a/src/runtime/socket/WindowsNamedPipeContext.rs b/src/runtime/socket/WindowsNamedPipeContext.rs index a153676ce10..0a07146c902 100644 --- a/src/runtime/socket/WindowsNamedPipeContext.rs +++ b/src/runtime/socket/WindowsNamedPipeContext.rs @@ -284,9 +284,6 @@ impl WindowsNamedPipeContext { ) -> *mut WindowsNamedPipeContext { let global_this = GlobalRef::from(global_this); let vm: &'static VirtualMachine = global_this.bun_vm(); - // TODO(port): in-place init — `named_pipe`/`task` capture `this` (self-referential), so - // allocate uninit, derive the stable pointer, build the fields, then ptr::write the whole - // struct. Avoids `mem::zeroed()` on non-POD AnyTask/WindowsNamedPipe. let this: *mut WindowsNamedPipeContext = bun_core::heap::into_raw(Box::< core::mem::MaybeUninit, >::new_uninit()) diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 1dda99cdacf..2b19038d2cf 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -214,11 +214,6 @@ impl bun_ptr::RefCounted for NewSocket { } impl NewSocket { - // TODO(port): `pub const js = if (!ssl) jsc.Codegen.JSTCPSocket else jsc.Codegen.JSTLSSocket` - // — codegen module accessor. `#[bun_jsc::JsClass]` derive provides - // `to_js`/`from_js`/`from_js_direct`. `dataSetCached`/`dataGetCached` are - // emitted as `Self::data_set_cached` / `Self::data_get_cached`. - // ─── R-2 interior-mutability helpers ───────────────────────────────────── /// Read-modify-write the packed `Cell` through `&self`. @@ -591,7 +586,6 @@ impl NewSocket { // the handlers must be kept alive for the duration of the function call // that way if we need to call the error handler, we can let scope = Handlers::enter_ref(handlers); - // TODO(port): errdefer — `scope.exit()` returns true when handlers freed let global = handlers.global_object; let this_value = self.get_this_value(&global); let _ = handlers.call_error_handler(this_value, &[this_value, err_value]); @@ -774,11 +768,6 @@ impl NewSocket { this.poll_ref .with_mut(|p| p.unref_on_next_tick(js_loop_ctx())); - // TODO(port): errdefer — `defer markInactive()` + `defer if (needs_deref) deref()` - // moved to a guard so all early-returns run them. The outer - // `_outer_deref` above owns the final `deref()`; LIFO drop order - // (cleanup → _outer_deref) mirrors Zig's three defers exactly. - // // The deferred `mark_inactive()` is gated on the `Handlers` pointer // captured before the user callback runs: `onConnectError` can // synchronously re-enter `connect()` and — via `do_connect()`'s diff --git a/src/runtime/socket/tls_socket_functions.rs b/src/runtime/socket/tls_socket_functions.rs index 6444685bc76..74ed013f7d7 100644 --- a/src/runtime/socket/tls_socket_functions.rs +++ b/src/runtime/socket/tls_socket_functions.rs @@ -13,7 +13,7 @@ use crate::api::bun_x509 as X509; // Declared here per port rules (call the linked C symbol directly); migrate // into `bun_boringssl_sys` once the bindgen pass covers them. // ────────────────────────────────────────────────────────────────────────── -#[allow(non_camel_case_types, non_upper_case_globals, dead_code)] +#[allow(non_camel_case_types, non_upper_case_globals)] pub(super) mod ffi { use super::boringssl::{SSL, SSL_CTX, X509, struct_stack_st_X509}; use core::ffi::{c_char, c_int, c_long, c_uint, c_void}; @@ -31,8 +31,6 @@ pub(super) mod ffi { pub(crate) struct EC_GROUP; } - pub(crate) type ssl_renegotiate_mode_t = c_int; - // ssl.h pub(crate) const TLSEXT_NAMETYPE_host_name: c_int = 0; @@ -192,9 +190,6 @@ pub(super) mod ffi { pub(crate) safe fn SSL_set_ex_data(ssl: &SSL, idx: c_int, data: *mut c_void) -> c_int; // Returns the borrowed parent CTX (always non-null for a live `SSL*`). pub(crate) safe fn SSL_get_SSL_CTX(ssl: &SSL) -> *mut SSL_CTX; - // Atomic refcount bump on a live `SSL_CTX*`; opaque-ZST ref ⇒ no - // caller-side precondition (route via `SSL_CTX::opaque_ref`). - pub(crate) safe fn SSL_CTX_up_ref(ctx: &SSL_CTX) -> c_int; // Stores `cb`/`arg` opaquely on the CTX (BoringSSL never derefs `arg` // outside the callback). Opaque-ZST `&SSL_CTX` + by-value fn-ptr + // opaque `*mut c_void` ⇒ no caller-side precondition. diff --git a/src/runtime/test_runner/Collection.rs b/src/runtime/test_runner/Collection.rs index 6c6c9e5be1c..18222c351e5 100644 --- a/src/runtime/test_runner/Collection.rs +++ b/src/runtime/test_runner/Collection.rs @@ -11,7 +11,6 @@ use crate::test_runner::bun_test::{ RefDataValue, StepResult, }; use crate::test_runner::bun_test::debug::group; -// TODO(port): jsc.Jest.Jest.runner / jsc.ConsoleObject live under bun_jsc::jest / bun_jsc::console_object — verify module paths. use crate::test_runner::jest::Jest; pub struct Collection { diff --git a/src/runtime/test_runner/ScopeFunctions.rs b/src/runtime/test_runner/ScopeFunctions.rs index 4e4c884a986..b5e1c36423a 100644 --- a/src/runtime/test_runner/ScopeFunctions.rs +++ b/src/runtime/test_runner/ScopeFunctions.rs @@ -68,7 +68,6 @@ pub struct ScopeFunctions { pub mod strings { use bun_core::String as BunString; - // TODO(port): `bun.String.static("...")` — assumes a const-capable `BunString::static_str`. #[allow(non_snake_case)] #[inline] pub fn DESCRIBE() -> BunString { BunString::static_str("describe") } #[allow(non_snake_case)] #[inline] pub fn XDESCRIBE() -> BunString { BunString::static_str("xdescribe") } #[allow(non_snake_case)] #[inline] pub fn TEST() -> BunString { BunString::static_str("test") } @@ -357,7 +356,6 @@ impl ScopeFunctions { if debugger.test_reporter_agent.is_enabled() { // Zig: fn-local `struct { var max_test_id_for_debugger: i32 = 0; }` — process-global static. static MAX_TEST_ID_FOR_DEBUGGER: AtomicI32 = AtomicI32::new(0); - // TODO(port): Zig used non-atomic `+= 1` (single JS thread). Relaxed fetch_add preserves semantics. let id = MAX_TEST_ID_FOR_DEBUGGER.fetch_add(1, Ordering::Relaxed) + 1; let mut name = BunString::init(description.unwrap_or(b"(unnamed)")); let parent: &DescribeScope = bun_test.collection.active_scope(); diff --git a/src/runtime/test_runner/diff/diff_match_patch.rs b/src/runtime/test_runner/diff/diff_match_patch.rs index 6ed76de32f6..549204d1851 100644 --- a/src/runtime/test_runner/diff/diff_match_patch.rs +++ b/src/runtime/test_runner/diff/diff_match_patch.rs @@ -95,7 +95,6 @@ impl fmt::Display for Diff { Operation::Insert => "+", Operation::Delete => "-", }; - // TODO(port): Zig used `{s}` on `[]const Unit`; bytes may not be valid UTF-8. write!(f, "({}, \"{}\")", op, bstr::BStr::new(&self.text)) } } @@ -791,7 +790,6 @@ fn diff_lines_to_chars_munge( line_array: &mut Vec<*const [Unit]>, line_hash: &mut StringHashMap, ) -> Result, DiffError> { - // TODO(port): comptime `if (Unit != u8) @panic` → runtime TypeId check. if TypeId::of::() != TypeId::of::() { panic!("Unit must be u8"); } @@ -1296,7 +1294,6 @@ fn diff_cleanup_semantic_score(one: &[Unit], two: &[Unit]) -> us return 6; } - // TODO(port): comptime `if (Unit != u8) return 5;` → runtime TypeId check. if TypeId::of::() != TypeId::of::() { return 5; } @@ -1591,11 +1588,6 @@ mod tests { diffs ); } - - // TODO(port): `checkAllAllocationFailures` / `CheckAllAllocationFailuresTuples` - // are Zig comptime-reflection helpers wrapping `std.testing.checkAllAllocationFailures`. - // Rust's global allocator aborts on OOM; there is no analogous fallible-alloc - // injection harness in this codebase. Dropped. } // ported from: src/test_runner/diff/diff_match_patch.zig diff --git a/src/runtime/test_runner/diff/printDiff.rs b/src/runtime/test_runner/diff/printDiff.rs index ded95b5690b..d5afae65754 100644 --- a/src/runtime/test_runner/diff/printDiff.rs +++ b/src/runtime/test_runner/diff/printDiff.rs @@ -273,9 +273,6 @@ mod base_styles { }; } -// TODO(port): Zig selects this namespace via `switch (mode)` at comptime. Since MODE is const -// Mode::BgDiffOnly, only that arm is materialized here. The .bg_always and .fg_diff arms differ -// only in inserted_equal/removed_equal; .fg omits inserted_diff/removed_diff entirely. mod styles { use super::{Style, base_styles}; pub(super) const INSERTED_LINE: Style = base_styles::RED_FG_INSERTED; diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index 05a297fe637..4412f2728f1 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -54,7 +54,7 @@ pub enum Promise { Rejects = 2, } -#[repr(u8)] // TODO(port): Zig used u5; encoded inside Flags packed repr +#[repr(u8)] #[derive(Clone, Copy, PartialEq, Eq, Default)] pub enum AsymmetricMatcherConstructorType { #[default] diff --git a/src/runtime/test_runner/harness/recover.rs b/src/runtime/test_runner/harness/recover.rs index 34f19756c21..6ff1d625bd2 100644 --- a/src/runtime/test_runner/harness/recover.rs +++ b/src/runtime/test_runner/harness/recover.rs @@ -132,7 +132,6 @@ mod musl { unsafe fn get_context(ctx: *mut Context) { #[cfg(windows)] { - // TODO(port): std.os.windows.ntdll.RtlCaptureContext → bun_sys::windows::ntdll // SAFETY: ctx is a valid, writable, properly-aligned CONTEXT (caller contract). unsafe { bun_sys::windows::ntdll_context::RtlCaptureContext(ctx) }; } diff --git a/src/runtime/test_runner/jest.rs b/src/runtime/test_runner/jest.rs index e941554238a..32cb7692e61 100644 --- a/src/runtime/test_runner/jest.rs +++ b/src/runtime/test_runner/jest.rs @@ -117,7 +117,6 @@ pub struct TestRunner<'a> { pub only: bool, pub run_todo: bool, pub concurrent: bool, - // TODO(port): std.Random has no direct Rust equivalent; using xoshiro256++ handle. pub randomize: Option, /// The --seed value when --randomize is on. Used to derive a per-file /// shuffle PRNG from hash(seed, file_path) so within-file test order is @@ -130,7 +129,6 @@ pub struct TestRunner<'a> { pub max_concurrency: u32, // PORT NOTE: `std.mem.Allocator param` field deleted — global mimalloc. - // TODO(port): `drainer` had `= undefined` default in Zig pub drainer: jsc::AnyTask::AnyTask, pub has_pending_tests: bool, @@ -208,7 +206,6 @@ impl<'a> TestRunner<'a> { return false; } let file_path = self.files.items_source()[file_id as usize].path.text(); - // TODO(port): MultiArrayList column accessor name (`items(.source)` in Zig) // Check if the file path matches any of the glob patterns for pattern in glob_patterns { diff --git a/src/runtime/test_runner/pretty_format.rs b/src/runtime/test_runner/pretty_format.rs index b678b3ea54b..695fab0d872 100644 --- a/src/runtime/test_runner/pretty_format.rs +++ b/src/runtime/test_runner/pretty_format.rs @@ -449,8 +449,6 @@ impl core::fmt::Display for ZigFormatter<'_, '_> { let result = (|| { let tag = Tag::get(self.value, self.global).map_err(|_| core::fmt::Error)?; - // TODO(port): core::fmt::Formatter is a text sink; format() takes bun_io::Write. - // Bridge via bun_io::FmtAdapter so ZigFormatter can write bytes through `f`. let mut adapter = bun_io::FmtAdapter::new(f); formatter .format::<_, false>(tag, &mut adapter, self.value, self.global) @@ -2613,7 +2611,6 @@ impl<'a> Formatter<'a> { JSType::Uint16Array => print_typed_slice!(u16), JSType::Int32Array => print_typed_slice!(i32), JSType::Uint32Array => print_typed_slice!(u32), - // TODO(port): Rust has no native f16; use bun_core::f16 or half crate. JSType::Float16Array => print_typed_slice!(bun_core::f16), JSType::Float32Array => print_typed_slice!(f32), JSType::Float64Array => print_typed_slice!(f64), diff --git a/src/runtime/test_runner/snapshot.rs b/src/runtime/test_runner/snapshot.rs index 7a5ea2bf72d..b1bbfbc7534 100644 --- a/src/runtime/test_runner/snapshot.rs +++ b/src/runtime/test_runner/snapshot.rs @@ -37,7 +37,6 @@ pub struct Snapshots<'a> { pub _current_file: Option, // TODO(port): lifetime — borrows Jest.runner.files[..].source.path; BACKREF (not owned, never freed). pub snapshot_dir_path: Option>, - // TODO(port): LIFETIMES.tsv says `IndexMap>`; PORTING.md prefers `bun_collections::ArrayHashMap`. pub inline_snapshots_to_write: &'a mut IndexMap>, pub last_error_snapshot_name: Option>, } @@ -89,7 +88,6 @@ impl InlineSnapshotToWrite { pub struct File { pub id: FileId, - // TODO(port): Zig used `std.fs.File` (via `fd.stdFile()`); std::fs is banned. Using bun_sys::File. pub file: bun_sys::File, } @@ -164,7 +162,6 @@ impl<'a> Snapshots<'a> { // immutably for the whole fn body (NLL limitation with returned borrows), preventing // the later `insert`. Probe with `contains_key` first; re-lookup on hit. if self.values.contains_key(&name_hash) { - // TODO(port): returning &[u8] borrowing self.values; lifetime tied to &mut self. return Ok(Some(&**self.values.get(&name_hash).unwrap())); } @@ -421,7 +418,6 @@ impl<'a> Snapshots<'a> { let p = Jest::RUNNER.read().expect("Jest runner not set").as_ptr(); &(*p).files.items_source()[file_id as usize] }; - // TODO(port): arena.dupeZ — using owned Vec with trailing NUL. let test_filename: Box<[u8]> = { let mut v = test_file_source.path.text.to_vec(); v.push(0); diff --git a/src/runtime/test_runner/timers/FakeTimers.rs b/src/runtime/test_runner/timers/FakeTimers.rs index 5f23ecfacb1..ff76d52f82c 100644 --- a/src/runtime/test_runner/timers/FakeTimers.rs +++ b/src/runtime/test_runner/timers/FakeTimers.rs @@ -88,16 +88,6 @@ impl CurrentTime { } } -#[derive(Copy, Clone)] -enum AssertMode { - Locked, - // PORT NOTE: `.unlocked` callers (`execute_*`/`fire`) were converted to - // associated fns with no `self` (noalias re-entrancy — see below); the - // Zig `.unlocked` arm was a no-op anyway. - #[allow(dead_code)] - Unlocked, -} - use crate::jsc_hooks::timer_all; /// RAII `lock()`/`unlock()` for the per-thread `timer::All.lock`. Centralises @@ -120,7 +110,7 @@ fn from_el_timespec(t: &ElTimespec) -> Timespec { } impl FakeTimers { - fn assert_valid(&self, mode: AssertMode) { + fn assert_locked(&self) { if !Environment::CI_ASSERT { return; } @@ -128,41 +118,37 @@ impl FakeTimers { let owner: &timer::All = unsafe { &*(bun_core::from_field_ptr!(timer::All, fake_timers, std::ptr::from_ref::(self))) }; - match mode { - AssertMode::Locked => debug_assert!(!owner.lock.try_lock()), - // can't assert unlocked because another thread could be holding the lock - AssertMode::Unlocked => {} - } + debug_assert!(!owner.lock.try_lock()); } pub fn is_active(&self) -> bool { - self.assert_valid(AssertMode::Locked); - // defer self.assert_valid(.locked) — re-checked at fn exit + self.assert_locked(); + // defer assertValid(.locked) — re-checked at fn exit let r = self.active; - self.assert_valid(AssertMode::Locked); + self.assert_locked(); r } fn activate(&mut self, js_now: f64, global: &JSGlobalObject) { - self.assert_valid(AssertMode::Locked); + self.assert_locked(); self.active = true; CURRENT_TIME.set(global, &Timespec::EPOCH, Some(js_now)); - self.assert_valid(AssertMode::Locked); + self.assert_locked(); } fn deactivate( &mut self, global: &JSGlobalObject, ) -> Vec> { - self.assert_valid(AssertMode::Locked); + self.assert_locked(); let pinned = self.clear(); CURRENT_TIME.clear(global); self.active = false; - self.assert_valid(AssertMode::Locked); + self.assert_locked(); pinned } @@ -179,7 +165,7 @@ impl FakeTimers { /// same gap. #[must_use] fn clear(&mut self) -> Vec> { - self.assert_valid(AssertMode::Locked); + self.assert_locked(); let mut pinned = Vec::new(); while let Some(timer) = self.timers.delete_min() { @@ -199,7 +185,7 @@ impl FakeTimers { } } - self.assert_valid(AssertMode::Locked); + self.assert_locked(); pinned } diff --git a/src/runtime/timer/mod.rs b/src/runtime/timer/mod.rs index 2c25886e4e0..adc157bd754 100644 --- a/src/runtime/timer/mod.rs +++ b/src/runtime/timer/mod.rs @@ -1263,10 +1263,6 @@ impl All { // `JSValue::to_number()`, `bun_core::String::transfer_to_js()`, etc. // Kept gated until `bun_jsc.workspace = true` is re-enabled. -// TODO(port): JS-facing surface (`set_timeout`/`set_interval`/...) lives in -// `Timer.rs` and is wired via `#[cfg(feature = "jsc")]` once `bun_jsc` is -// re-enabled. The placeholder `include!` was non-compilable; removed. - // ─── enums / value types ───────────────────────────────────────────────────── #[derive(Copy, Clone, PartialEq, Eq, strum::IntoStaticStr)] diff --git a/src/runtime/valkey_jsc/ValkeyCommand.rs b/src/runtime/valkey_jsc/ValkeyCommand.rs index be16ac055ad..d63faaec251 100644 --- a/src/runtime/valkey_jsc/ValkeyCommand.rs +++ b/src/runtime/valkey_jsc/ValkeyCommand.rs @@ -200,7 +200,7 @@ impl Meta { /// Promise for a Valkey command pub struct Promise { pub meta: Meta, - pub promise: jsc::JSPromiseStrong, // TODO(port): exact path for jsc.JSPromise.Strong + pub promise: jsc::JSPromiseStrong, } impl Promise { @@ -214,7 +214,6 @@ impl Promise { global_object: &JSGlobalObject, value: &mut protocol::RESPValue, ) -> Result<(), jsc::JsTerminated> { - // TODO(port): bun.JSTerminated! mapping let options = ToJSOptions { return_as_buffer: self.meta.contains(Meta::RETURN_AS_BUFFER), }; @@ -235,7 +234,6 @@ impl Promise { global_object: &JSGlobalObject, jsvalue: JsResult, ) -> Result<(), jsc::JsTerminated> { - // TODO(port): bun.JSTerminated! mapping self.promise.reject(global_object, jsvalue)?; Ok(()) } @@ -261,7 +259,6 @@ impl PromisePair { global_object: &JSGlobalObject, jsvalue: JSValue, ) -> Result<(), jsc::JsTerminated> { - // TODO(port): bun.JSTerminated! mapping self.promise.reject(global_object, Ok(jsvalue))?; Ok(()) } diff --git a/src/runtime/valkey_jsc/js_valkey_functions.rs b/src/runtime/valkey_jsc/js_valkey_functions.rs index 659e994633b..f05657ab9bd 100644 --- a/src/runtime/valkey_jsc/js_valkey_functions.rs +++ b/src/runtime/valkey_jsc/js_valkey_functions.rs @@ -1048,7 +1048,6 @@ impl JSValkeyClient { )); }; - // TODO(port): JSPropertyIterator comptime config struct → options arg let mut object_iter = JSPropertyIterator::init( global, obj, @@ -1872,7 +1871,6 @@ impl JSValkeyClient { )); } Err(_) => { - // TODO(port): {f} format spec on ZigString return Err(global.throw(format_args!( "Failed to remove handler for channel {}", // `JSString` is an `opaque_ffi!` ZST — safe deref. diff --git a/src/runtime/valkey_jsc/valkey.rs b/src/runtime/valkey_jsc/valkey.rs index abf358529eb..214b8a18b79 100644 --- a/src/runtime/valkey_jsc/valkey.rs +++ b/src/runtime/valkey_jsc/valkey.rs @@ -271,8 +271,6 @@ pub struct ValkeyClient { pub reply_scanner: protocol::ReplyScanner, /// In-flight commands, after the data has been written to the network socket - // TODO(port): `Queue` is `std.fifo.LinearFifo(PromisePair, .Dynamic)` in Zig — assume - // valkey_command.rs exposes a matching type (readable_slice/read_item/write_item/etc.). pub in_flight: command::promise_pair::Queue, /// Commands that are waiting to be sent to the server. When pipelining is implemented, this usually will be empty. diff --git a/src/runtime/webcore.rs b/src/runtime/webcore.rs index f8fdc6e96e5..ca2dce61732 100644 --- a/src/runtime/webcore.rs +++ b/src/runtime/webcore.rs @@ -330,7 +330,6 @@ bun_collections::object_pool!(pub ByteListPool: Vec, threadsafe, 8); // Re-export the crate-local jsc shim's opaque type until `bun_jsc::fetch_headers` // is green; the shim's `#[repr(transparent)] struct FetchHeaders(usize)` matches the // opaque-handle ABI used by the `WebCore__FetchHeaders__*` extern fns. -// TODO(port): bun_jsc::fetch_headers — swap to `pub use bun_jsc::fetch_headers::FetchHeaders;`. pub use crate::jsc::FetchHeaders; #[path = "webcore/EncodingLabel.rs"] diff --git a/src/runtime/webcore/Blob.rs b/src/runtime/webcore/Blob.rs index 182e2e58251..fcb3c42cbdf 100644 --- a/src/runtime/webcore/Blob.rs +++ b/src/runtime/webcore/Blob.rs @@ -416,8 +416,6 @@ pub unsafe extern "C" fn Bun__Blob__sharedView(this: *const Blob, len: *mut usiz #[allow(non_snake_case, clippy::too_many_arguments)] impl BlobExt for Blob { - // TODO(port): bun_core::FormData (gated module) - fn get_form_data_encoding(&self) -> Option> { let content_type_slice = self.get_content_type()?; let encoding = bun_core::form_data::Encoding::get(content_type_slice.slice())?; @@ -796,7 +794,6 @@ impl BlobExt for Blob { ctx, impl_: write_bytes, }; - // TODO(port): wrap StructuredCloneWriter in a bun_io::Write adapter. let _ = self._on_structured_clone_serialize(&mut writer); } @@ -4283,7 +4280,6 @@ fn _on_structured_clone_deserialize>( match pathlike_tag { PathOrFileDescriptorSerializeTag::Fd => { - // TODO(port): readStruct(bun.FD) — read raw FD bytes. let fd: Fd = reader.read_struct()?; let mut path_or_fd = PathOrFileDescriptor::Fd(fd); break 'file Blob::new(Blob::find_or_create_file_from_path( @@ -6578,9 +6574,6 @@ impl Any { } // ─── Any: JSC-integration (to_js/from_js paths) ────────────────────────────── -// TODO(port): bun_jsc::* — Any::{to_action_value,to_promise,wrap, -// to_json,to_string,to_array_buffer*,to_blob,to_uint8_array*} call into -// JSValue/ZigString JSC methods and Blob JSC impls gated above. impl Any { fn to_internal_blob_if_possible(&mut self) { @@ -6929,14 +6922,11 @@ impl Internal { self.bytes.capacity() } - // TODO(port): bun_jsc::* — ZigString::to_external_u16/to_js_object. - pub fn to_string_owned(&mut self, global_this: &JSGlobalObject) -> JsResult { let bytes_without_bom = strings::without_utf8_bom(&self.bytes); if let Some(out) = strings::to_utf16_alloc(bytes_without_bom, false, false).unwrap_or(Some(Vec::new())) { - // TODO(port): Zig used `catch &[_]u16{}` to swallow alloc errors into empty. let out_len = out.len(); // Ownership transfers to JSC's external-string finalizer. let out_ptr = bun_core::heap::into_raw(out.into_boxed_slice()) @@ -6969,8 +6959,6 @@ impl Internal { } } - // TODO(port): bun_jsc::* — ZigString::to_json_object. - pub fn to_json(&mut self, global_this: &JSGlobalObject) -> JSValue { let str_bytes = ZigString::init(strings::without_utf8_bom(&self.bytes)).with_encoding(); let json = str_bytes.to_json_object(global_this); @@ -7068,8 +7056,6 @@ impl Inline { Self::internal_init(data, true) } - // TODO(port): bun_jsc::* — ZigString::to_js. - pub fn to_string_owned(&mut self, global_this: &JSGlobalObject) -> JSValue { if self.len == 0 { return ZigString::EMPTY.to_js(global_this); diff --git a/src/runtime/webcore/Body.rs b/src/runtime/webcore/Body.rs index 7f52dd8e491..73e8cbb0a46 100644 --- a/src/runtime/webcore/Body.rs +++ b/src/runtime/webcore/Body.rs @@ -179,9 +179,6 @@ impl Body { } } -// TODO(port): bun_jsc::ConsoleFormatter — write_format depends on the -// ConsoleObject formatter trait (`print_as`/`print_comma`/`write_indent`). - impl Body { pub fn write_format( &self, @@ -189,7 +186,7 @@ impl Body { writer: &mut W, ) -> core::fmt::Result where - F: bun_jsc::ConsoleFormatter, // TODO(port): exact trait for ConsoleObject.Formatter + F: bun_jsc::ConsoleFormatter, { formatter.write_indent(writer)?; write!( @@ -346,9 +343,6 @@ impl PendingValue { self.size_hint } - // TODO(port): ReadableStream::to_any_blob (gated on ByteBlobLoader/ - // ByteStream un-stubbing in ReadableStream.rs). - pub(crate) fn to_any_blob(&mut self) -> Option { if self.promise.is_some() { return None; @@ -391,8 +385,6 @@ impl PendingValue { false } - // TODO(port): ReadableStream::to_any_blob (see above). - pub(crate) fn to_any_blob_allow_promise(&mut self) -> Option { let global = self.global(); let mut stream = self.readable.get(global)?; @@ -405,9 +397,6 @@ impl PendingValue { None } - // TODO(port): JSGlobalObject::readable_stream_to_{json,array_buffer, - // bytes,text,blob,form_data} + bun_core::FormDataEncoding (gated payload). - pub(crate) fn set_promise( &mut self, global_this: &JSGlobalObject, @@ -638,11 +627,6 @@ impl ValueError { } } -// TODO(port): BunString::{to_error_instance,to_type_error_instance} not -// yet exported from `bun_string`; SystemError lacks Clone. The bodies are -// otherwise wired to bun_jsc (CommonAbortReason::to_js, strong::Optional, -// JSValue::attach_async_stack_from_promise all exist). - impl ValueError { pub fn to_stream_error( &mut self, @@ -756,10 +740,6 @@ impl Value { } } - // TODO(port): ZigStringSlice::slice() accessor + AnyBlob payload - // matching depend on the wtf string slice port. `to_any_blob` itself is - // un-gated above; only the WTFStringImpl→InternalBlob conversion blocks. - pub fn to_blob_if_possible(&mut self) { if let Value::WTFStringImpl(str) = *self { if let Some(bytes) = wtf_impl(&str).to_utf8_if_needed() { @@ -856,10 +836,6 @@ impl Value { // pub const empty = Value::Empty; - // TODO(port): ByteStream::Source — webcore::byte_stream is still a unit - // stub (`pub struct ByteStream;`); `Source::new` / `.context.setup()` / - // `.to_readable_stream()` need the real ByteStream port to land. - pub fn to_readable_stream(&mut self, global_this: &JSGlobalObject) -> JsResult { jsc::mark_binding(); @@ -1001,10 +977,6 @@ impl Value { } } - // TODO(port): `bun_jsc::JsClass` is not yet implemented for the opaque - // `DOMFormData`/`URLSearchParams` stubs (orphan rule prevents impl here). - // The `as_dom_form_data`/`as_url_search_params` shims below return None - // until upstream wires `from_js`. if let Some(form_data) = as_dom_form_data(value) { // SAFETY: shim returns a live JSC heap cell. return Ok(Value::Blob(Blob::from_dom_form_data(global_this, unsafe { @@ -1113,10 +1085,6 @@ impl Value { }) } - // TODO(port): AnyBlob::to_string_transfer / to_json_share / - // to_array_buffer_transfer / to_uint8_array_transfer + Blob::new/to_js + - // AnyPromise::wrap — all in gated Blob/jsc impls. - pub fn resolve( &mut self, new: &mut Value, @@ -1317,10 +1285,6 @@ impl Value { } } - // TODO(port): Blob::init_empty signature takes `&JSGlobalObject`, - // but the Zig path passed `undefined`; needs a nullable - // overload (or `Blob::default()`) before this type-checks. - pub fn try_use_as_any_blob(&mut self) -> Option { let any_blob: AnyBlob = match self { Value::Blob(b) => AnyBlob::Blob(core::mem::take(b)), @@ -1346,8 +1310,6 @@ impl Value { Some(any_blob) } - // TODO(port): see `try_use_as_any_blob`. - pub fn use_as_any_blob(&mut self) -> AnyBlob { let was_null = matches!(self, Value::Null); // PORT NOTE: `Value` has `Drop`, so we cannot `mem::replace` then @@ -1387,8 +1349,6 @@ impl Value { any_blob } - // TODO(port): see `try_use_as_any_blob`. - pub fn use_as_any_blob_allow_non_utf8_string(&mut self) -> AnyBlob { let was_null = matches!(self, Value::Null); // PORT NOTE: see `use_as_any_blob` — match by `&mut` to avoid E0509. @@ -1412,8 +1372,6 @@ impl Value { any_blob } - // TODO(port): webcore::readable_stream::Source::Bytes + ByteStream::on_data. - pub fn to_error_instance( &mut self, err: ValueError, @@ -1475,8 +1433,6 @@ impl Value { Ok(()) } - // TODO(port): forwards to `to_error_instance` (gated above). - pub fn to_error(&mut self, err: bun_core::Error, global: &JSGlobalObject) -> JsTerminated<()> { self.to_error_instance( ValueError::Message(BunString::create_format(format_args!( @@ -1538,10 +1494,6 @@ impl Drop for Value { } impl Value { - // TODO(port): ByteStream::Source — see `to_readable_stream`. The - // tail half of `tee()` constructs a `ByteStream::Source` to back a fresh - // ReadableStream; un-gate once the real ByteStream port lands. - pub fn tee( &mut self, global_this: &JSGlobalObject, @@ -1653,9 +1605,6 @@ impl Value { })) } - // TODO(port): forwards to `to_blob_if_possible`/`tee`/`Blob::init`, - // all of which are still gated (see notes above each). - pub fn clone(&mut self, global_this: &JSGlobalObject) -> JsResult { self.clone_with_readable_stream(global_this, None) } diff --git a/src/runtime/webcore/ByteStream.rs b/src/runtime/webcore/ByteStream.rs index 0f294de4b81..c6b2a8f9b02 100644 --- a/src/runtime/webcore/ByteStream.rs +++ b/src/runtime/webcore/ByteStream.rs @@ -59,9 +59,6 @@ impl Default for ByteStream { } /// `webcore.ReadableStream.NewSource(@This(), "Bytes", onStart, onPull, onCancel, deinit, null, drain, memoryCost, toBufferedValue)` -// TODO(port): `NewSource` is a Zig comptime type-generator that wires callbacks into a -// `.classes.ts` wrapper. In Rust this becomes `ReadableStream::Source` where -// `ByteStream: ReadableStreamSourceContext` (trait with `on_start`/`on_pull`/... methods). pub type Source = readable_stream::NewSource; impl readable_stream::SourceContext for ByteStream { @@ -162,7 +159,6 @@ impl ByteStream { } pub(crate) fn on_data(&self, stream: streams::Result) -> Result<(), bun_jsc::JsTerminated> { - // TODO(port): narrow error set — Zig `bun.JSTerminated!void` bun_jsc::mark_binding!(); if self.done.get() { // PORT NOTE: Zig frees `stream.owned.slice()` / `stream.owned_and_done.slice()` here @@ -188,7 +184,6 @@ impl ByteStream { (p.ctx, p.on_pipe) }; if let Some(ctx) = pipe_ctx { - // TODO(port): `Pipe.onPipe` signature — Zig passes `(ctx, stream, allocator)`. (pipe_fn.unwrap())(ctx, stream); return Ok(()); } diff --git a/src/runtime/webcore/FileReader.rs b/src/runtime/webcore/FileReader.rs index fd16e364a4a..56b9d2896fd 100644 --- a/src/runtime/webcore/FileReader.rs +++ b/src/runtime/webcore/FileReader.rs @@ -1084,10 +1084,6 @@ impl FileReader { } } -// TODO(port): `ReadableStream.NewSource(@This(), "File", onStart, onPull, onCancel, deinit, -// setRefOrUnref, drain, memoryCost, null)` is a comptime type-generator that builds a -// vtable-backed Source struct embedding `context: FileReader`. In Rust this becomes a -// generic `NewSource` + a `SourceContext` trait impl. pub type Source = readable_stream::NewSource; // Intrusive backref: `self` is always the `context` field of a heap-allocated diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index 8dd6c601f6d..fa323d5816a 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -8,11 +8,10 @@ use bun_io::{self, WriteResult, WriteStatus}; use bun_jsc::JsCell; use bun_sys::{self as sys, Fd, FdExt as _}; +use crate::api::bun::process::Status as SpawnStatus; use crate::webcore::jsc::{CallFrame, EventLoopHandle, JSGlobalObject, JSValue, JsResult}; use crate::webcore::readable_stream::{self, ReadableStream}; use crate::webcore::{self, AutoFlusher, PathOrFileDescriptor, streams}; -// TODO(port): verify module path for `bun.spawn.Status` -use crate::api::bun::process::Status as SpawnStatus; #[cfg(windows)] use bun_sys::windows::libuv as uv; #[cfg(windows)] diff --git a/src/runtime/webcore/ReadableStream.rs b/src/runtime/webcore/ReadableStream.rs index 3bd8e17c7db..6ed7c561201 100644 --- a/src/runtime/webcore/ReadableStream.rs +++ b/src/runtime/webcore/ReadableStream.rs @@ -440,8 +440,6 @@ impl ReadableStream { _parent: P, buffered_reader: &mut bun_io::BufferedReader, ) -> JsResult { - // TODO(port): Zig's `buffered_reader: anytype` — only ever instantiated with the - // platform `PipeReader`/`PosixBufferedReader`. let source = NewSource::::new_mut(NewSource { global_this: Some(bun_ptr::BackRef::new(global_this)), context: FileReader { @@ -463,7 +461,6 @@ impl ReadableStream { } pub fn empty(global_this: &JSGlobalObject) -> JsResult { - // TODO(port): bun.cpp.ReadableStream__empty wraps the extern with exception check bun_jsc::from_js_host_call(global_this, || { // SAFETY: FFI call into JSC bindings; global_this is a valid &JSGlobalObject. ReadableStream__empty(global_this) @@ -471,7 +468,6 @@ impl ReadableStream { } pub fn used(global_this: &JSGlobalObject) -> JsResult { - // TODO(port): bun.cpp.ReadableStream__used wraps the extern with exception check bun_jsc::from_js_host_call(global_this, || { // SAFETY: FFI call into JSC bindings; global_this is a valid &JSGlobalObject. ReadableStream__used(global_this) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index cfae88827ca..21454047a29 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -35,8 +35,6 @@ use bun_ptr::weak_ptr::WeakPtrData; use bun_uws as uws; use core::mem::ManuallyDrop; -// TODO(port): WeakRef = bun.ptr.WeakPtr(Request, "weak_ptr_data") — intrusive weak-ptr; -// keep raw *mut Request + embedded WeakPtrData. See PORTING.md §Pointers. impl bun_ptr::weak_ptr::HasWeakPtrData for Request { unsafe fn weak_ptr_data(this: *mut Self) -> *mut WeakPtrData { // SAFETY: caller guarantees `this` points to a live (possibly-finalized) allocation. @@ -1550,7 +1548,6 @@ impl Request { let this_value = callframe.this(); let cloned = self.clone(global_this)?; - // TODO(port): cloned is Box; to_js consumes via heap::alloc inside codegen. let cloned_ptr = bun_core::heap::into_raw(cloned); // SAFETY: cloned_ptr was just created via heap::alloc above; toJS adopts ownership. let js_wrapper = unsafe { (*cloned_ptr).to_js(global_this) }; diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index 0cb95315d70..9391d20acba 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -217,8 +217,6 @@ impl Default for Response { } } -// TODO(port): WeakPtr is intrusive (embedded WeakPtrData field). Keep raw-pointer -// semantics; do NOT map to std::rc::Weak (owner is intrusive-refcounted). impl bun_ptr::weak_ptr::HasWeakPtrData for Response { unsafe fn weak_ptr_data(this: *mut Self) -> *mut WeakPtrData { // SAFETY: caller guarantees `this` points to a live (possibly-finalized) allocation. @@ -406,10 +404,6 @@ impl Response { } } -// TODO(port): bun_jsc::* + bun_core::form_data — to_js, JsRef::try_get/ -// init_weak, js::gc::stream, ReadableStream::from_js, BodyValue::estimated_size, -// JSValue methods. Everything below until `Init` is JSC integration. - impl Response { #[inline] pub fn get_body_len(&self) -> usize { @@ -488,8 +482,6 @@ impl Response { } } -// TODO(port): bun_jsc::* — host_fn, callframe.arguments_old, JSValue::as_. - mod _jsc_host_fns { use super::*; @@ -683,10 +675,6 @@ impl Response { } } -// TODO(port): bun_jsc::* — write_format ConsoleFormatter, do_clone/ -// constructor/from_js paths (need codegen js::gc::stream slots, JsClass downcast, -// Body::extract). - impl Response { pub fn write_format( &self, @@ -1022,8 +1010,6 @@ impl Response { .get() .value .set(BodyValue::InternalBlob(InternalBlob { - // TODO(port): Zig used Managed(u8).fromOwnedSlice; bytes.slice() ownership - // transfers here as Vec. bytes: bytes.into_vec(), was_string: true, })); @@ -1492,8 +1478,6 @@ pub fn status_200(global_this: &JSGlobalObject) -> *mut Response { #[inline] fn empty_with_status(_global: &JSGlobalObject, status: u16) -> *mut Response { - // TODO(port): Zig signature says `Response` but body calls bun.new(Response, ...) — - // it actually returns *Response. Preserving the heap-alloc behavior. bun_core::heap::into_raw(Box::new(Response { body: JsCell::new(Body::new(BodyValue::Null)), init: JsCell::new(Init { diff --git a/src/runtime/webcore/S3File.rs b/src/runtime/webcore/S3File.rs index 1d0c3017b81..35cb9596ac4 100644 --- a/src/runtime/webcore/S3File.rs +++ b/src/runtime/webcore/S3File.rs @@ -643,7 +643,6 @@ impl S3BlobStatTask { s3::stat( credentials, path, - // TODO(port): @ptrCast fn pointer — verify s3::stat callback signature matches S3BlobStatTask::on_s3_exists_resolved, this.cast::(), env.get_http_proxy(true, None, None).map(|proxy| proxy.href), diff --git a/src/runtime/webcore/Sink.rs b/src/runtime/webcore/Sink.rs index cb909128288..0db7f68045d 100644 --- a/src/runtime/webcore/Sink.rs +++ b/src/runtime/webcore/Sink.rs @@ -191,10 +191,6 @@ pub struct UTF8Fallback; // should reference `crate::webcore::sink::UTF8Fallback` directly. // TODO(port): inherent associated type — `impl Sink { pub type UTF8Fallback = UTF8Fallback; }`. -// TODO(port): `bun_core::strings::{is_all_ascii, replace_latin1_with_utf8, -// copy_utf16_into_utf8_impl, to_utf8_alloc}` + `Vec::::from_*` constructors -// are not yet exported with these exact names. Body gated; signatures kept. - impl UTF8Fallback { const STACK_SIZE: usize = 1024; @@ -1196,8 +1192,6 @@ pub fn destructor_ptr_subprocess(ptr: *const c_void) -> usize { ((ptr as usize as u64 & ADDR_MASK) | (SUBPROCESS_TAG << ADDR_BITS)) as usize } -// TODO(port): `Subprocess::on_stdin_destroyed` + `Output::debug_warn`. - #[unsafe(no_mangle)] pub extern "C" fn Bun__onSinkDestroyed(ptr_value: *mut c_void, sink_ptr: *mut c_void) { let _ = sink_ptr; // autofix diff --git a/src/runtime/webcore/blob/read_file.rs b/src/runtime/webcore/blob/read_file.rs index 6e76f067c71..3a848c5f879 100644 --- a/src/runtime/webcore/blob/read_file.rs +++ b/src/runtime/webcore/blob/read_file.rs @@ -366,7 +366,6 @@ impl ReadFile { read_eof: false, size: 0, buffer: Vec::new(), - // TODO(port): was `undefined` — overwritten before first schedule. task: WorkPoolTask { node: Default::default(), callback: Self::do_read_loop_task, diff --git a/src/runtime/webcore/encoding.rs b/src/runtime/webcore/encoding.rs index d6c425efbbc..1f19c4d3cb3 100644 --- a/src/runtime/webcore/encoding.rs +++ b/src/runtime/webcore/encoding.rs @@ -52,18 +52,12 @@ const fn encoding_from_u8(n: u8) -> Encoding { /// `Encoding` discriminants as `u8` consts for use in `const ENCODING: u8` /// generic args (stable-Rust workaround for `adt_const_params`). -#[allow(non_snake_case, dead_code)] +#[allow(non_snake_case)] mod enc { use super::Encoding; pub(super) const UTF8: u8 = Encoding::Utf8 as u8; - pub(super) const UCS2: u8 = Encoding::Ucs2 as u8; pub(super) const UTF16LE: u8 = Encoding::Utf16le as u8; - pub(super) const LATIN1: u8 = Encoding::Latin1 as u8; pub(super) const ASCII: u8 = Encoding::Ascii as u8; - pub(super) const BASE64: u8 = Encoding::Base64 as u8; - pub(super) const BASE64URL: u8 = Encoding::Base64url as u8; - pub(super) const HEX: u8 = Encoding::Hex as u8; - pub(super) const BUFFER: u8 = Encoding::Buffer as u8; } // ──────────────────────────────────────────────────────────────────────────── diff --git a/src/runtime/webcore/fetch/FetchTasklet.rs b/src/runtime/webcore/fetch/FetchTasklet.rs index 2af0b7bba9f..80d9490a2c2 100644 --- a/src/runtime/webcore/fetch/FetchTasklet.rs +++ b/src/runtime/webcore/fetch/FetchTasklet.rs @@ -458,7 +458,7 @@ impl FetchTasklet { } if let Some(certificate) = self.result.certificate_info.take() { - drop(certificate); // TODO(port): CertificateInfo::deinit(allocator) -> Drop + drop(certificate); } // PORT NOTE: Zig `entries.deinit()` + `buf.deinit()`; Rust drop on @@ -470,7 +470,7 @@ impl FetchTasklet { } if let Some(metadata) = self.metadata.take() { - drop(metadata); // TODO(port): HTTPResponseMetadata::deinit(allocator) -> Drop + drop(metadata); } self.response_buffer = MutableString::default(); @@ -1721,7 +1721,7 @@ impl FetchTasklet { metadata: None, javascript_vm: jsc_vm, global_this: GlobalRef::from(global_this), - request_body: fetch_options.body, // TODO(port): move semantics; FetchOptions consumed + request_body: fetch_options.body, request_body_streaming_buffer: None, response_buffer: MutableString::default(), scheduled_response_buffer: MutableString::default(), diff --git a/src/runtime/webcore/s3/client.rs b/src/runtime/webcore/s3/client.rs index a6219ff65e2..1f48ec8e142 100644 --- a/src/runtime/webcore/s3/client.rs +++ b/src/runtime/webcore/s3/client.rs @@ -61,7 +61,6 @@ use bun_io::StreamBuffer; bun_core::declare_scope!(S3UploadStream, visible); -// TODO(port): `bun.JSTerminated!T` is not in the type map; assuming a thin alias in bun_jsc. type JsTerminatedResult = Result; pub(crate) fn stat( diff --git a/src/runtime/webcore/s3/multipart.rs b/src/runtime/webcore/s3/multipart.rs index 0e9d14a160d..81c1348be02 100644 --- a/src/runtime/webcore/s3/multipart.rs +++ b/src/runtime/webcore/s3/multipart.rs @@ -118,7 +118,6 @@ use crate::webcore::s3::simple_request::{ execute_simple_s3_request, }; -// TODO(port): verify exact path/type for `bun.JSTerminated!T` — assumed `Result` type JsTerminatedResult = Result; declare_scope!(S3MultiPartUpload, hidden); diff --git a/src/runtime/webcore/s3/simple_request.rs b/src/runtime/webcore/s3/simple_request.rs index 6e88d75f3c6..3a17eb4985e 100644 --- a/src/runtime/webcore/s3/simple_request.rs +++ b/src/runtime/webcore/s3/simple_request.rs @@ -501,7 +501,6 @@ impl Drop for S3HttpSimpleTask { // - http.clearData() // Owned-field frees from the Zig deinit (response_buffer, headers, sign_result, range, // proxy_url, result.certificate_info, result.metadata) are handled by their own Drop impls. - // TODO(port): verify HTTPClientResult's Drop frees certificate_info/metadata. // PORT NOTE: KeepAlive::unref takes an aio EventLoopCtx; the JS-loop ctx is fetched via // the global hook (registered by crate::init) — same pattern as // `event_loop_handle_to_ctx` in process.rs. diff --git a/src/runtime/webcore/streams.rs b/src/runtime/webcore/streams.rs index 35adafa31f6..77c158342b6 100644 --- a/src/runtime/webcore/streams.rs +++ b/src/runtime/webcore/streams.rs @@ -480,7 +480,6 @@ pub struct WritableHandler { pub type WritableHandlerFn = fn(ctx: *mut c_void, result: Writable); /// Trait replacing Zig's `comptime handler_fn` — implementors provide the callback. -// TODO(port): Zig used comptime fn param to generate wrapper; trait-based dispatch instead pub trait WritablePendingCallback { fn on_handle(&mut self, result: Writable); } @@ -527,7 +526,6 @@ impl WritablePending { strong.swap(), &global, ); - // TODO(port): Zig moved p out then reassigned future = .none; mem::replace mirrors this } WritableFuture::Handler(h) => { self.future = WritableFuture::Handler(WritableHandler { @@ -642,7 +640,6 @@ impl Default for Pending { } /// Trait replacing Zig's `comptime handler_fn` for Result.Pending. -// TODO(port): Zig used comptime fn param to generate wrapper; trait-based dispatch instead pub trait PendingCallback { fn on_handle(&mut self, result: StreamResult); } @@ -1152,7 +1149,6 @@ impl HTTPServerWritable { self.buffer.capacity() as usize } - // TODO(port): const-generic string selection — Rust cannot branch on const bool to produce &'static str at type level pub const NAME: &'static str = if HTTP3 { "H3ResponseSink" } else if SSL { @@ -1161,8 +1157,6 @@ impl HTTPServerWritable { "HTTPResponseSink" }; // PORT NOTE: associated const with const-generic if — requires `#![feature(generic_const_exprs)]` or a trait-based dispatch. - - // TODO(port): `pub const JSSink = Sink.JSSink(@This(), name)` — type generator; needs macro/codegen } /// Per-monomorphization JSSink wrapper alias. Mirrors @@ -1228,12 +1222,6 @@ impl crate::webcore::sink::JsSinkAbi } } -// TODO(port): full impl depends on `bun_uws::Response` -// const-generic dispatch (the body casts `res` to `*mut uws::Response` without -// the SSL/H3 parameter), `bun_event_loop::AutoFlusher` free-fns (the local -// `crate::webcore::AutoFlusher` is a fieldless stub), and `ByteListPool::Node` -// data access. Un-gate once the UwsResponse type-dispatch trait lands. - impl HTTPServerWritable { /// Const-generic → runtime dispatch for the type-erased `res` field. /// Mirrors Zig's `const UWSResponse = if (http3) uws.H3.Response else uws.NewApp(ssl).Response`. @@ -2153,7 +2141,6 @@ impl NetworkSink { pub fn new(init: NetworkSink) -> Box { Box::new(init) } - // TODO(port): bun.TrivialDeinit → relies on Drop; explicit deinit is no-op here pub fn path(&self) -> Option<&[u8]> { if let Some(task) = self.task_ref() { @@ -2188,7 +2175,6 @@ impl NetworkSink { pub fn to_sink(&mut self) -> *mut NetworkSinkJSSink { // SAFETY: JSSink wraps Self at offset 0 (repr guarantee from codegen) std::ptr::from_mut::(self).cast::() - // TODO(port): @ptrCast(this) to JSSink — depends on codegen layout } pub fn finalize(&mut self) { @@ -2372,7 +2358,6 @@ impl NetworkSink { pub fn to_js(&mut self, global_this: &JSGlobalObject) -> JSValue { NetworkSinkJSSink::create_object(global_this, self, 0) - // TODO(port): JSSink.createObject — codegen-provided } pub fn memory_cost(&self) -> usize { @@ -2475,17 +2460,12 @@ impl BufferAction { self.tag } - // TODO(port): `AnyBlob::wrap` takes `(jsc::AnyPromise, &JSGlobalObject, - // BufferActionTag)`; `swap()` here yields `*mut JSPromise`. Un-gate once an - // `AnyPromise::from(*mut JSPromise)` adapter exists. - pub fn fulfill( &mut self, global: &JSGlobalObject, blob: &mut AnyBlob, ) -> core::result::Result<(), jsc::JsTerminated> { blob.wrap(jsc::AnyPromise::Normal(self.swap()), global, self.tag()) - // TODO(port): Zig passed `this.*` (full enum) as 3rd arg; using tag() } pub fn reject( diff --git a/src/runtime/webview/ChromeProcess.rs b/src/runtime/webview/ChromeProcess.rs index d489f9c1ad2..e50cc260a1c 100644 --- a/src/runtime/webview/ChromeProcess.rs +++ b/src/runtime/webview/ChromeProcess.rs @@ -25,9 +25,9 @@ use std::io::Write as _; #[cfg(any(target_os = "linux", target_os = "android"))] use bun_core::ZStr; -use bun_core::{self, strings}; +use bun_core::{self, getenv_z, strings, zstr}; #[cfg(not(windows))] -use bun_core::{ZBox, env_var, getenv_z, zstr}; +use bun_core::{ZBox, env_var}; use bun_jsc::JSGlobalObject; #[cfg(not(windows))] use bun_jsc::virtual_machine::VirtualMachine; @@ -613,15 +613,8 @@ fn read_dev_tools_active_port(out_buf: &mut Vec) -> Option<()> { // Windows roots under %LOCALAPPDATA%; POSIX under $HOME. The subdir // names come from each browser's installer — hardcoded, not // discoverable. Edge uses the same CDP + file format as Chrome. - // NB: do NOT route Windows through bun_core::getenv_z — it is stubbed to - // None on cfg(windows) (TODO(port) in bun_core/util.rs), which made - // this whole function dead on Windows. Zig's bun.getenvZ walks the env - // block case-insensitively and returns a real value; std::env::var is the - // working equivalent here (LOCALAPPDATA is always valid Unicode). #[cfg(windows)] - let root_owned = std::env::var("LOCALAPPDATA").ok()?; - #[cfg(windows)] - let root: &[u8] = root_owned.as_bytes(); + let root = getenv_z(zstr!("LOCALAPPDATA"))?; #[cfg(not(windows))] let root = getenv_z(zstr!("HOME"))?; diff --git a/src/s3_signing/credentials.rs b/src/s3_signing/credentials.rs index 7ca2f212043..a3de8b5fe2a 100644 --- a/src/s3_signing/credentials.rs +++ b/src/s3_signing/credentials.rs @@ -31,8 +31,6 @@ fn pico_header_empty() -> PicoHeader { PicoHeader::ZERO } -// TODO(port): bun_picohttp::Header::new — fields are private; constructing via -// repr(C) layout-pun until a public ctor lands. Layout is asserted in bun_picohttp. #[inline] fn pico_header_new(name: &[u8], value: &[u8]) -> PicoHeader { PicoHeader::new(name, value) @@ -560,7 +558,6 @@ impl S3Credentials { // `tmp_buffer` which has since been overwritten by the `AWS4{secret}` bufPrint, // so Zig passes corrupted bytes to `cache.set` (latent bug → cache never hits). // We recompute the correct `{region}{service}{secret}` key here. - // TODO(port): fix the overwritten-key bug in credentials.zig as well. let key = buf_print( &mut tmp_buffer, format_args!( diff --git a/src/safety/CriticalSection.rs b/src/safety/CriticalSection.rs index e9dcd960d23..1467b182bc5 100644 --- a/src/safety/CriticalSection.rs +++ b/src/safety/CriticalSection.rs @@ -34,9 +34,6 @@ use core::sync::atomic::{AtomicU32, Ordering}; #[cfg(debug_assertions)] use bun_core::StoredTrace; -// TODO(port): `ThreadId` / `INVALID_THREAD_ID` / `current_thread_id()` come from the sibling -// `src/safety/thread_id.zig` port + Zig's `std.Thread`. TODO(port): confirm the concrete integer -// width and atomic type (Zig's `std.Thread.Id` is platform-dependent). #[cfg(debug_assertions)] use super::thread_id::{ AtomicThreadId, INVALID as INVALID_THREAD_ID, ThreadId, current as current_thread_id, diff --git a/src/semver/SemverQuery.rs b/src/semver/SemverQuery.rs index b584f47374e..06b7f51d908 100644 --- a/src/semver/SemverQuery.rs +++ b/src/semver/SemverQuery.rs @@ -442,7 +442,6 @@ impl Group { } pub fn json_stringify(&self, writer: &mut impl core::fmt::Write) -> fmt::Result { - // TODO(port): Zig called `this.fmt()` with no buf arg (looks like a latent bug upstream). // TODO(port): std.json.encodeJsonString — needs a JSON string encoder in bun_core/serde. let temp = { use std::io::Write as _; diff --git a/src/semver/SemverRange.rs b/src/semver/SemverRange.rs index 3aff84214ec..a23698b527c 100644 --- a/src/semver/SemverRange.rs +++ b/src/semver/SemverRange.rs @@ -2,7 +2,6 @@ use core::cmp::Ordering; use core::fmt; use crate::Version; -// TODO(port): verify exact module path for Query::Token::Wildcard in bun_semver use crate::query::token::Wildcard; #[repr(u8)] diff --git a/src/semver/Version.rs b/src/semver/Version.rs index 21773f50fbf..35fdd2ab395 100644 --- a/src/semver/Version.rs +++ b/src/semver/Version.rs @@ -777,8 +777,6 @@ impl<'a, T: VersionInt> fmt::Display for DiffFormatter<'a, T> { ) .unwrap_or(ChangedVersion::None); - // TODO(port): Output.prettyFmt is a comptime ANSI-tag expander. `pretty_fmt!` - // currently passes the literal through; the proc-macro substitution lands later. match diff { ChangedVersion::Major => write!( writer, @@ -989,9 +987,6 @@ pub struct Tag { impl Tag { pub fn order_pre(self, rhs: Tag, lhs_buf: &[u8], rhs_buf: &[u8]) -> Ordering { - // TODO(port): Zig parameterized this on IntType (u32 vs u64). Only the - // u64 instantiation is used at runtime (OldV2Version is migration-only), - // so we hardcode u64 here. let lhs_str = self.pre.slice(lhs_buf); let rhs_str = rhs.pre.slice(rhs_buf); diff --git a/src/semver/lib.rs b/src/semver/lib.rs index fb7faa76f9e..d9e22be18bf 100644 --- a/src/semver/lib.rs +++ b/src/semver/lib.rs @@ -84,10 +84,6 @@ pub mod sliced_string { use super::external_string::ExternalString; use super::semver_string::String; - // TODO(port): lifetime — PORTING.md says "no lifetime param on struct for []const u8 fields", - // but SlicedString is purely a borrowed (ptr+len) view used for offset arithmetic into a - // backing buffer; Box/&'static/raw are all wrong here. Confirm `'a` threading or - // swap to raw `*const [u8]` if borrowck fights at call sites. #[derive(Copy, Clone)] pub struct SlicedString<'a> { pub buf: &'a [u8], @@ -751,8 +747,6 @@ pub mod semver_string { b'#' => b'+', _ => c, }; - // TODO(port): writing raw byte through fmt::Write requires char conversion; - // bytes here are path-safe ASCII so `as char` is fine. use core::fmt::Write; f.write_char(n as char)?; } diff --git a/src/sha_hmac/sha.rs b/src/sha_hmac/sha.rs index 2185c1cbdff..df0049d39cb 100644 --- a/src/sha_hmac/sha.rs +++ b/src/sha_hmac/sha.rs @@ -353,9 +353,4 @@ pub mod hashers { ); } -// TODO(port): `boring`, `zig`, `evp` below were Zig `[_]type{...}` comptime type -// lists (with `void` sentinels) used for ad-hoc benchmarking against Zig's -// `std.crypto.hash`. Rust has no type-list value equivalent and no `std.crypto` -// counterpart; they are private and unreferenced in the Zig source. - // ported from: src/sha_hmac/sha.zig diff --git a/src/shell_parser/braces.rs b/src/shell_parser/braces.rs index 7cc5428e6a9..aa9402810f8 100644 --- a/src/shell_parser/braces.rs +++ b/src/shell_parser/braces.rs @@ -446,7 +446,6 @@ impl Token { match self { Token::Open(_) => SmolStr::from_char(b'{'), Token::Comma => SmolStr::from_char(b','), - // TODO(port): bun_core::SmolStr — see Clone for Token above. Token::Text(txt) => SmolStr::from_slice(txt.slice()).expect("OOM cloning SmolStr"), Token::Close => SmolStr::from_char(b'}'), Token::Eof => SmolStr::empty(), diff --git a/src/shell_parser/parse.rs b/src/shell_parser/parse.rs index 074c7e5311a..7117e01a14a 100644 --- a/src/shell_parser/parse.rs +++ b/src/shell_parser/parse.rs @@ -184,7 +184,7 @@ pub mod ast { } #[derive(Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] - #[strum(serialize_all = "kebab-case")] // TODO(port): tag names must match Zig exactly ("-a", "==", etc.) + #[strum(serialize_all = "kebab-case")] pub enum CondExprOp { /// -a file: True if file exists. #[strum(serialize = "-a")] @@ -320,7 +320,6 @@ pub mod ast { } /// Single-arg ops: name starts with '-' and len == 2. - // TODO(port): Zig built this via @typeInfo reflection over enum fields. Hand-rolled here. pub const SINGLE_ARG_OPS: &'static [(&'static str, CondExprOp)] = &[ ("-a", CondExprOp::DashA), ("-b", CondExprOp::DashB), @@ -3559,7 +3558,6 @@ impl<'bump, const ENCODING: StringEncoding> Lexer<'bump, ENCODING> { // Set the cursor to decode the codepoint at new_idx. // Use width=0 so that nextCursor (which computes pos = width + i) // starts reading from exactly new_idx. - // TODO(port): direct field access on SrcUnicode cursor — encapsulate in helper. self.chars.src.set_unicode_cursor(new_idx); if let Some(pc) = prev_ascii_char { self.chars.prev = Some(InputChar { @@ -3599,7 +3597,6 @@ impl<'bump, const ENCODING: StringEncoding> Lexer<'bump, ENCODING> { match bytes[i] { b'0'..=b'9' => { if digit_buf_count as usize >= digit_buf.len() { - // TODO(port): Zig comptime concat for error string. Build at runtime. let mut error_buf = Vec::new(); write!( &mut error_buf, @@ -3927,8 +3924,6 @@ pub enum CharState { Double, } -// TODO(port): Zig `Src = switch (encoding) { .ascii => SrcAscii, .wtf8/.utf16 => SrcUnicode }` -// — Rust const-generic-on-enum can't pick a struct type. Use a tagged union and branch on ENCODING. #[derive(Clone, Copy)] pub enum Src<'a> { Ascii(SrcAscii<'a>), @@ -4498,8 +4493,6 @@ impl SmolListInlined { // equivalent of the previous `assume_init_read` + `ptr::copy` shift. self.slice_mut()[idx..].rotate_left(1); self.pop() - // TODO(port): Zig fn returns T but body falls off end without returning the removed item - // (likely a Zig bug). Here we return it. } pub(crate) fn swap_remove(&mut self, idx: usize) -> T { @@ -4511,7 +4504,6 @@ impl SmolListInlined { let last = self.len as usize - 1; self.slice_mut().swap(idx, last); self.pop() - // TODO(port): same Zig oddity — pop() decremented len already; restore by writing back. } pub(crate) fn pop(&mut self) -> T { @@ -4567,7 +4559,6 @@ impl SmolList { let mut cost = size_of::(); match self { SmolList::Inlined(inlined) => { - // TODO(port): Zig branches on `@hasDecl(T, "memoryCost")` — express via trait/specialization. for item in inlined.slice() { cost += item.memory_cost(); } @@ -4655,8 +4646,6 @@ impl SmolList { // arena-backed and `!Drop`). inlined.slice_mut().rotate_left(starting_idx); inlined.len = u32::try_from(new_len).expect("int cast"); - // TODO(port): Zig version copies into [0..starting_idx] which is a bug if - // new_len > starting_idx; mirroring intended semantics (shift-down) here. } SmolList::Heap(heap) => { // `Vec::drain` shifts the tail down and drops the prefix. diff --git a/src/simdutf_sys/simdutf.rs b/src/simdutf_sys/simdutf.rs index 87a49c6c556..974133b67c5 100644 --- a/src/simdutf_sys/simdutf.rs +++ b/src/simdutf_sys/simdutf.rs @@ -628,8 +628,6 @@ pub mod length { pub mod from { use super::*; pub fn utf8(input: &[u8]) -> usize { - // TODO(port): Zig had `if (@inComptime())` branch using std.unicode.utf8CountCodepoints - // for compile-time evaluation; Rust has no equivalent — runtime path only. // SAFETY: input is a valid slice; FFI reads exactly len bytes. unsafe { simdutf__utf16_length_from_utf8(input.as_ptr(), input.len()) } } diff --git a/src/sourcemap/InternalSourceMap.rs b/src/sourcemap/InternalSourceMap.rs index f76cde96936..71187b392f8 100644 --- a/src/sourcemap/InternalSourceMap.rs +++ b/src/sourcemap/InternalSourceMap.rs @@ -87,7 +87,7 @@ use core::mem::size_of; use core::ptr; -use crate::Ordinal; // TODO(port): bun_core::Ordinal — local shim +use crate::Ordinal; use bun_collections::VecExt as _; use bun_core::MutableString; @@ -298,7 +298,6 @@ impl State { source_index: self.source_index, name_index: -1, } - // TODO(port): verify Mapping field shape (`generated`/`original` struct name) in bun_sourcemap. } } diff --git a/src/sourcemap/Mapping.rs b/src/sourcemap/Mapping.rs index 439c0de0fcb..77fdb83c60d 100644 --- a/src/sourcemap/Mapping.rs +++ b/src/sourcemap/Mapping.rs @@ -268,9 +268,6 @@ impl List { pub fn name_index(&self) -> &[i32] { match &self.r#impl { - // TODO(port): Zig `inline else` calls `.items(.name_index)` on both arms, but - // `MappingWithoutName` has no `name_index` field — relies on Zig lazy analysis. - // Return an empty slice for the without-names case. ListValue::WithoutNames(_list) => &[], ListValue::WithNames(list) => list.items_name_index(), } diff --git a/src/sourcemap/ParsedSourceMap.rs b/src/sourcemap/ParsedSourceMap.rs index 6a8225200bd..5ae7c9b6b29 100644 --- a/src/sourcemap/ParsedSourceMap.rs +++ b/src/sourcemap/ParsedSourceMap.rs @@ -2,7 +2,7 @@ use core::ffi::c_void; use core::fmt; use core::sync::atomic::AtomicU32; -use crate::Ordinal; // TODO(port): bun_core::Ordinal — local shim +use crate::Ordinal; use crate::mapping; use crate::vlq::VLQ; diff --git a/src/sourcemap/lib.rs b/src/sourcemap/lib.rs index 1ea5adedf13..0523119adfc 100644 --- a/src/sourcemap/lib.rs +++ b/src/sourcemap/lib.rs @@ -217,7 +217,7 @@ impl Default for ParseResultFail { fn default() -> Self { Self { loc: bun_ast::Loc::default(), - err: bun_core::err!("Unknown"), // TODO(port): Zig has no default for `err` + err: bun_core::err!("Unknown"), value: 0, msg: b"", } @@ -1148,7 +1148,6 @@ pub fn parse_json( let Some(s) = item.data.as_e_string() else { return Err(bun_core::err!("InvalidSourceMap")); }; - // TODO(port): e_string.string(alloc) — exact API TBD let s = s.string(arena)?; v.push(Box::<[u8]>::from(s)); } @@ -1336,9 +1335,6 @@ pub fn append_source_map_chunk<'a>( } /// Always returns UTF-8. -// TODO(port): Zig was generic over `comptime T: type` (u8/u16). Rust cannot -// express `[]const T` literals generically without a helper trait; split into -// two functions and dispatch at the (only) callsite. fn find_source_mapping_url_u8(source: &[u8]) -> Option { const NEEDLE: &[u8] = b"\n//# sourceMappingURL="; let found = bun_core::strings::last_index_of(source, NEEDLE)?; diff --git a/src/sourcemap_jsc/CodeCoverage.rs b/src/sourcemap_jsc/CodeCoverage.rs index 9ad59a1d978..ee18a3292c0 100644 --- a/src/sourcemap_jsc/CodeCoverage.rs +++ b/src/sourcemap_jsc/CodeCoverage.rs @@ -833,7 +833,6 @@ impl ByteRangeMapping { source_url: ZigStringSlice, ) -> ByteRangeMapping { ByteRangeMapping { - // TODO(port): VirtualMachine::get().allocator dropped — LineOffsetTable::generate uses global mimalloc line_offset_table: LineOffsetTable::generate(source_contents, 0) .unwrap_or_else(|_| bun_alloc::out_of_memory()), source_id, @@ -858,7 +857,6 @@ pub(crate) extern "C" fn ByteRangeMapping__generate( let slice = str_.to_utf8(); let hash = bun_wyhash::hash(slice.slice()); - // TODO(port): getOrPut → entry API; verify ByteRangeMapping is properly dropped on overwrite let source_contents = source_contents_str.to_utf8(); let new_value = ByteRangeMapping::compute(source_contents.slice(), source_id, slice); diff --git a/src/sourcemap_jsc/JSSourceMap.rs b/src/sourcemap_jsc/JSSourceMap.rs index 9b45b688158..fb97b8d5d01 100644 --- a/src/sourcemap_jsc/JSSourceMap.rs +++ b/src/sourcemap_jsc/JSSourceMap.rs @@ -59,7 +59,6 @@ pub(crate) fn find_source_map(global: &JSGlobalObject, frame: &CallFrame) -> JsR let path = bun_jsc::URL::path_from_file_url(source_url_string.dupe_ref()); if path.is_dead() { - // TODO(port): verify ERR builder API shape (`global.ERR(.INVALID_URL, fmt, args).throw()`) return Err(global.throw_value(global.err_invalid_url(format_args!( "Invalid URL: {}", BStr::new(source_url_slice.slice()) diff --git a/src/spawn_sys/spawn_process.rs b/src/spawn_sys/spawn_process.rs index fc9dd2f8a9e..1f26dd5de98 100644 --- a/src/spawn_sys/spawn_process.rs +++ b/src/spawn_sys/spawn_process.rs @@ -671,7 +671,6 @@ pub unsafe fn spawn_process_posix( } if options.detached { - // TODO(port): @hasDecl check — assume present on platforms that define it. #[cfg(any(target_os = "linux", target_os = "android"))] { // glibc/musl/bionic all define POSIX_SPAWN_SETSID as 0x80; diff --git a/src/sql/mysql/protocol/Auth.rs b/src/sql/mysql/protocol/Auth.rs index b1d59a7f8b4..497764b1646 100644 --- a/src/sql/mysql/protocol/Auth.rs +++ b/src/sql/mysql/protocol/Auth.rs @@ -326,7 +326,6 @@ pub mod caching_sha2_password { Ok(()) } - // TODO(port): `pub const decode = decoderWrap(PublicKeyResponse, decodeInternal).decode;` pub fn decode( &mut self, reader: NewReader, diff --git a/src/sql/mysql/protocol/NewWriter.rs b/src/sql/mysql/protocol/NewWriter.rs index 01fafeb3966..fe2dd9a4d09 100644 --- a/src/sql/mysql/protocol/NewWriter.rs +++ b/src/sql/mysql/protocol/NewWriter.rs @@ -159,9 +159,6 @@ pub type NewWriter = NewWriterWrap; /// that auto-wraps a raw context into `NewWriterWrap` before forwarding to /// `writeFn`. In Rust this is a free helper that the per-packet `write` impls /// call directly. -// TODO(port): Zig used @hasDecl to detect already-wrapped contexts at the call -// site. Rust callers should pass `impl WriterContext` and let this helper wrap -// unconditionally; already-wrapped values go straight to `write_fn`. #[inline] pub fn write_wrap( this: &mut Container, diff --git a/src/sql/mysql/protocol/OKPacket.rs b/src/sql/mysql/protocol/OKPacket.rs index fee91d306f4..aad11923f86 100644 --- a/src/sql/mysql/protocol/OKPacket.rs +++ b/src/sql/mysql/protocol/OKPacket.rs @@ -11,7 +11,6 @@ pub struct OKPacket { pub warnings: u16, pub info: Data, pub session_state_changes: Data, - // TODO(port): Zig u24 — using u32, callers must ensure value fits in 24 bits pub packet_size: u32, } diff --git a/src/sql/mysql/protocol/PacketHeader.rs b/src/sql/mysql/protocol/PacketHeader.rs index dd1b2e65896..760ec63188b 100644 --- a/src/sql/mysql/protocol/PacketHeader.rs +++ b/src/sql/mysql/protocol/PacketHeader.rs @@ -1,6 +1,5 @@ #[derive(Copy, Clone)] pub struct PacketHeader { - // TODO(port): Zig used u24; Rust has no u24, using u32 (value is always < 2^24) pub length: u32, pub sequence_id: u8, } diff --git a/src/sql/mysql/protocol/PreparedStatement.rs b/src/sql/mysql/protocol/PreparedStatement.rs index c2ab3c04281..17f5812d6b1 100644 --- a/src/sql/mysql/protocol/PreparedStatement.rs +++ b/src/sql/mysql/protocol/PreparedStatement.rs @@ -45,8 +45,6 @@ impl PrepareOK { } } -// TODO(port): lifetime — Execute is a transient builder borrowing params/param_types -// from the caller for one write() call (BORROW_PARAM, matches Query::Execute<'a>). pub struct Execute<'a> { /// ID of the prepared statement to execute, returned from COM_STMT_PREPARE pub statement_id: u32, diff --git a/src/sql/mysql/protocol/SSLRequest.rs b/src/sql/mysql/protocol/SSLRequest.rs index 653863d1048..0386baaa698 100644 --- a/src/sql/mysql/protocol/SSLRequest.rs +++ b/src/sql/mysql/protocol/SSLRequest.rs @@ -18,7 +18,6 @@ pub struct SSLRequest { impl Default for SSLRequest { fn default() -> Self { Self { - // TODO(port): capability_flags has no Zig default; caller must set it capability_flags: Capabilities::default(), max_packet_size: 0xFFFFFF, // 16MB default character_set: CharacterSet::default(), diff --git a/src/sql/mysql/protocol/StackReader.rs b/src/sql/mysql/protocol/StackReader.rs index 8c88244fefe..3b1e2b5d85d 100644 --- a/src/sql/mysql/protocol/StackReader.rs +++ b/src/sql/mysql/protocol/StackReader.rs @@ -6,10 +6,6 @@ use super::any_mysql_error::Error as AnyMySQLError; use super::new_reader::{NewReader, ReaderContext}; use crate::shared::data::Data; -// TODO(port): lifetime — `offset`/`message_start` are caller-owned `usize` on the -// stack (LIFETIMES.tsv has no entry; classified BORROW_PARAM). Zig passes `@This()` -// by value (Copy) and mutates through `*usize`; modeled here as `&'a Cell` -// to keep `Copy` + interior mutability without `unsafe`. #[derive(Clone, Copy)] pub struct StackReader<'a> { pub buffer: &'a [u8], @@ -38,7 +34,6 @@ impl<'a> StackReader<'a> { offset: &'a Cell, message_start: &'a Cell, ) -> NewReader> { - // TODO(port): NewReader field name assumed `wrapped` per Zig struct literal NewReader { wrapped: StackReader { buffer, diff --git a/src/sql/mysql/protocol/StmtPrepareOKPacket.rs b/src/sql/mysql/protocol/StmtPrepareOKPacket.rs index b4cf54bc865..7d02fedc3b8 100644 --- a/src/sql/mysql/protocol/StmtPrepareOKPacket.rs +++ b/src/sql/mysql/protocol/StmtPrepareOKPacket.rs @@ -7,7 +7,6 @@ pub struct StmtPrepareOKPacket { pub num_columns: u16, pub num_params: u16, pub warning_count: u16, - // TODO(port): Zig type is u24; Rust has no native u24. Value is bounded to 24 bits. pub packet_length: u32, } diff --git a/src/sql/postgres/CommandTag.rs b/src/sql/postgres/CommandTag.rs index 49d43498503..df1680df76a 100644 --- a/src/sql/postgres/CommandTag.rs +++ b/src/sql/postgres/CommandTag.rs @@ -2,7 +2,6 @@ use bun_core::strings; bun_core::declare_scope!(Postgres, visible); -// TODO(port): lifetime — `Other` borrows from the input `tag` slice passed to `init`. pub enum CommandTag<'a> { // For an INSERT command, the tag is INSERT oid rows, where rows is the // number of rows inserted. oid used to be the object ID of the inserted diff --git a/src/sql/postgres/protocol/ArrayList.rs b/src/sql/postgres/protocol/ArrayList.rs index 094a4deb060..105162b347b 100644 --- a/src/sql/postgres/protocol/ArrayList.rs +++ b/src/sql/postgres/protocol/ArrayList.rs @@ -2,7 +2,6 @@ use super::new_writer::{NewWriter, WriterContext}; use crate::postgres::AnyPostgresError; pub struct ArrayList<'a> { - // TODO(port): lifetime — Zig `*std.array_list.Managed(u8)`; classified as BORROW_PARAM (mutable borrow of caller's buffer) pub array: &'a mut Vec, } diff --git a/src/sql/postgres/protocol/Execute.rs b/src/sql/postgres/protocol/Execute.rs index a954787716f..e6ca46f948f 100644 --- a/src/sql/postgres/protocol/Execute.rs +++ b/src/sql/postgres/protocol/Execute.rs @@ -11,7 +11,6 @@ impl<'a> Default for Execute<'a> { fn default() -> Self { Self { max_rows: 0, - // TODO(port): PortalOrPreparedStatement has no Zig default; callers must set `p`. p: PortalOrPreparedStatement::Portal(b""), } } diff --git a/src/sql/postgres/protocol/FieldMessage.rs b/src/sql/postgres/protocol/FieldMessage.rs index f3df6888046..a785defc4c1 100644 --- a/src/sql/postgres/protocol/FieldMessage.rs +++ b/src/sql/postgres/protocol/FieldMessage.rs @@ -68,9 +68,6 @@ impl FieldMessage { if field_int == 0 { break; } - // TODO(port): Zig `FieldType` is a non-exhaustive `enum(u8)` (the - // `init` switch has an `else` arm). `from_raw` must accept any u8 - // without UB — do NOT `transmute` here. let field: FieldType = FieldType::from(field_int); let message = reader.read_z()?; diff --git a/src/sql/postgres/protocol/NegotiateProtocolVersion.rs b/src/sql/postgres/protocol/NegotiateProtocolVersion.rs index 03f041eea42..51126352739 100644 --- a/src/sql/postgres/protocol/NegotiateProtocolVersion.rs +++ b/src/sql/postgres/protocol/NegotiateProtocolVersion.rs @@ -36,8 +36,6 @@ impl NegotiateProtocolVersion { break; } // `defer option.deinit()` — deleted; `option` drops at end of iteration. - // TODO(port): Zig used `borrowUTF8` then dropped `option`; that would dangle. - // Clone instead — `option` is Temporary into the connection buffer either way. this.unrecognized_options .push(String::clone_utf8(option.slice())); // PERF(port): was appendAssumeCapacity — profile if it shows up on a hot path. diff --git a/src/sql/postgres/protocol/NewReader.rs b/src/sql/postgres/protocol/NewReader.rs index 1c4b5f4c6a0..cb7b1362fae 100644 --- a/src/sql/postgres/protocol/NewReader.rs +++ b/src/sql/postgres/protocol/NewReader.rs @@ -7,7 +7,6 @@ use bun_core::String as BunString; /// Zig passed these as `comptime fn(ctx: Context) ...` arguments and `NewReader` /// filled them in from `Context.markMessageStart`, `Context.peek`, etc. — i.e. /// structural duck-typing. In Rust the trait bound IS that check. -// TODO(port): narrow error set pub trait ReaderContext { fn mark_message_start(&mut self); fn peek(&self) -> &[u8]; diff --git a/src/sql/postgres/protocol/NewWriter.rs b/src/sql/postgres/protocol/NewWriter.rs index d83c587ea9f..f08a36b5256 100644 --- a/src/sql/postgres/protocol/NewWriter.rs +++ b/src/sql/postgres/protocol/NewWriter.rs @@ -5,9 +5,6 @@ use crate::postgres::types::int_types::{PostgresInt32, PostgresInt64, int32}; /// took as comptime fn-pointer params (`offsetFn_`, `writeFunction_`, /// `pwriteFunction_`). In Zig those were passed explicitly; in Rust the /// trait bound IS that binding. -// TODO(port): `NewWriterWrap`'s explicit fn-pointer params collapse into this -// trait. If a caller needs to wrap a context with *different* fns than its -// inherent impl (none do today), add a newtype that impls this trait. pub trait WriterContext: Copy { fn offset(self) -> usize; fn write(self, bytes: &[u8]) -> Result<(), AnyPostgresError>; diff --git a/src/sql/postgres/protocol/StackReader.rs b/src/sql/postgres/protocol/StackReader.rs index 8e403442a57..d82331b31e4 100644 --- a/src/sql/postgres/protocol/StackReader.rs +++ b/src/sql/postgres/protocol/StackReader.rs @@ -3,9 +3,6 @@ use crate::postgres::protocol::new_reader::{NewReader, ReaderContext}; use crate::shared::data::Data; use bun_core::strings; -// TODO(port): lifetime — `offset`/`message_start` are `*usize` fields not present in -// LIFETIMES.tsv; classified here as BORROW_PARAM by inspection (struct is named -// "StackReader" and is only ever constructed on the caller's stack via `init`). pub struct StackReader<'a> { pub buffer: &'a [u8], pub offset: &'a mut usize, diff --git a/src/sql/shared/ColumnIdentifier.rs b/src/sql/shared/ColumnIdentifier.rs index 4a6894b1012..11510a155a8 100644 --- a/src/sql/shared/ColumnIdentifier.rs +++ b/src/sql/shared/ColumnIdentifier.rs @@ -8,7 +8,6 @@ pub enum ColumnIdentifier { impl ColumnIdentifier { pub fn init(name: Data) -> Result { - // TODO(port): narrow error set — only `try` site is name.to_owned() const U32_MAX_DIGITS: usize = "4294967295".len(); let might_be_int = match name.slice().len() { 1..=U32_MAX_DIGITS => true, diff --git a/src/sql_jsc/lib.rs b/src/sql_jsc/lib.rs index a552dec38be..973229ea957 100644 --- a/src/sql_jsc/lib.rs +++ b/src/sql_jsc/lib.rs @@ -3,10 +3,7 @@ // ────────────────────────────────────────────────────────────────────────── // Module tree wired with explicit `#[path]` attrs (files use PascalCase -// basenames, mirroring the Zig sources). Heavy leaf modules remain -// individually gated with `// TODO(port):` markers naming the -// lower-tier symbol they need. Un-gate one-by-one as `bun_jsc` / -// `bun_string` / `bun_runtime` grow real method surfaces. +// basenames, mirroring the Zig sources). // ────────────────────────────────────────────────────────────────────────── // Local signature-compatible stubs for the JSC surface this crate names. diff --git a/src/sql_jsc/mysql.rs b/src/sql_jsc/mysql.rs index 2c915e971eb..6d6dc597c15 100644 --- a/src/sql_jsc/mysql.rs +++ b/src/sql_jsc/mysql.rs @@ -28,8 +28,7 @@ pub fn create_binding(global_object: &JSGlobalObject) -> JSValue { // ────────────────────────────────────────────────────────────────────────── // Submodule tree (files use PascalCase basenames, mirroring the Zig sources; -// wired via `#[path]`). Heavy modules remain ``-gated until their lower- -// tier deps land — see per-module `TODO(port)` markers. +// wired via `#[path]`). // ────────────────────────────────────────────────────────────────────────── #[path = "mysql/MySQLContext.rs"] @@ -41,24 +40,15 @@ pub mod my_sql_statement; #[path = "mysql/MySQLRequestQueue.rs"] pub mod my_sql_request_queue; -// TODO(port): bun_jsc::JsRef + JSValue method surface (.call, .ensure_still_alive) -// TODO(port): bun_jsc::host_fn proc-macro - #[path = "mysql/MySQLQuery.rs"] pub mod my_sql_query; -// TODO(port): bun_jsc::host_fn proc-macro + JSValue/CallFrame method surface - #[path = "mysql/JSMySQLQuery.rs"] pub mod js_my_sql_query; #[path = "mysql/MySQLValue.rs"] pub mod my_sql_value; -// TODO(port): bun_jsc::host_fn proc-macro -// TODO(port): bun_uws::Socket method surface -// TODO(port): bun_jsc::VirtualMachine::get / RareData - #[path = "mysql/JSMySQLConnection.rs"] pub mod js_my_sql_connection; @@ -90,13 +80,9 @@ pub mod protocol { #[path = "any_mysql_error_jsc.rs"] pub mod any_mysql_error_jsc; - // TODO(port): bun_jsc::JSValue method surface (date/number/buffer constructors) - #[path = "DecodeBinaryValue.rs"] pub mod decode_binary_value; - // TODO(port): bun_jsc::JSValue / bun_jsc::JSObject method surface - #[path = "ResultSet.rs"] pub mod result_set; } diff --git a/src/sql_jsc/mysql/MySQLStatement.rs b/src/sql_jsc/mysql/MySQLStatement.rs index 469ea00fe89..eee302ae2b6 100644 --- a/src/sql_jsc/mysql/MySQLStatement.rs +++ b/src/sql_jsc/mysql/MySQLStatement.rs @@ -123,9 +123,6 @@ impl MySQLStatement { .remove(ExecutionFlags::NEEDS_DUPLICATE_CHECK); let mut seen_numbers: Vec = Vec::new(); - // TODO(port): StringHashMap key lifetime — Zig stores borrowed `name.slice()` pointers - // that outlive the map (columns outlive this function). The Rust StringHashMap clones - // into owned `Box<[u8]>` keys; fine for a transient dedup set. let mut seen_fields: StringHashMap<()> = StringHashMap::default(); seen_fields.reserve(self.columns.len()); diff --git a/src/sql_jsc/mysql/protocol/ResultSet.rs b/src/sql_jsc/mysql/protocol/ResultSet.rs index f0a37bfe6f5..6fcb599ceae 100644 --- a/src/sql_jsc/mysql/protocol/ResultSet.rs +++ b/src/sql_jsc/mysql/protocol/ResultSet.rs @@ -137,7 +137,6 @@ impl<'a> Row<'a> { } MYSQL_TYPE_INT24 => { if column.flags.contains(ColumnFlags::UNSIGNED) { - // TODO(port): Zig used u24; Rust has no u24 — u32 parse then mask not needed (text protocol bounds) let val: u32 = parse_int::(value.slice(), 10).unwrap_or(0); *cell = SQLDataCell { tag: Tag::Uint4, diff --git a/src/sql_jsc/postgres.rs b/src/sql_jsc/postgres.rs index e3e566e954f..6b8dcdc4d09 100644 --- a/src/sql_jsc/postgres.rs +++ b/src/sql_jsc/postgres.rs @@ -20,8 +20,7 @@ pub fn create_binding(global_object: &JSGlobalObject) -> JSValue { // ────────────────────────────────────────────────────────────────────────── // Submodule tree (files use PascalCase basenames, mirroring the Zig sources; -// wired via `#[path]`). Heavy modules remain ``-gated until their lower- -// tier deps land — see per-module `TODO(port)` markers. +// wired via `#[path]`). // ────────────────────────────────────────────────────────────────────────── #[path = "postgres/SASL.rs"] @@ -50,29 +49,17 @@ pub mod error_jsc; pub mod postgres_sql_statement; pub use postgres_sql_statement::PostgresSQLStatement; -// TODO(port): bun_jsc::host_fn proc-macro + JSValue/CallFrame method surface -// TODO(port): bun_uws::Socket method surface -// TODO(port): bun_jsc::VirtualMachine::get / RareData - #[path = "postgres/PostgresSQLConnection.rs"] pub mod postgres_sql_connection; pub use postgres_sql_connection::PostgresSQLConnection; -// TODO(port): bun_jsc::host_fn proc-macro + JSValue/CallFrame method surface - #[path = "postgres/PostgresSQLQuery.rs"] pub mod postgres_sql_query; pub use postgres_sql_query::PostgresSQLQuery; -// TODO(port): bun_jsc::JSValue / bun_jsc::JSObject method surface - #[path = "postgres/PostgresRequest.rs"] pub mod postgres_request; -// TODO(port): bun_jsc::js_object::ExternColumnIdentifier -// TODO(port): bun_jsc::JSType (real enum) -// TODO(port): bun_core::wtf::{RefPtr,StringImpl} - #[path = "postgres/DataCell.rs"] pub mod data_cell; diff --git a/src/sql_jsc/postgres/DataCell.rs b/src/sql_jsc/postgres/DataCell.rs index 3fa54915b78..71ab83e6706 100644 --- a/src/sql_jsc/postgres/DataCell.rs +++ b/src/sql_jsc/postgres/DataCell.rs @@ -254,7 +254,6 @@ fn parse_array( value: Value { json: if !unescaped.is_empty() { BunString::clone_utf8(unescaped).leak_wtf_impl() - // TODO(port): .value.WTFStringImpl accessor name } else { core::ptr::null_mut() }, @@ -1481,7 +1480,6 @@ impl<'a> Putter<'a> { result_mode: PostgresSQLQueryResultMode, cached_structure: Option<&PostgresCachedStructure>, ) -> Result { - // TODO(port): jsc.JSObject.ExternColumnIdentifier path — confirm bun_jsc export name let mut names: *mut crate::jsc::ExternColumnIdentifier = core::ptr::null_mut(); let mut names_count: u32 = 0; if let Some(c) = cached_structure { diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 6d10f4b0062..87cab2555b1 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -94,8 +94,6 @@ use crate::jsc::verify_error_to_js; #[derive(bun_ptr::CellRefCounted)] #[ref_count(destroy = Self::deinit)] pub struct PostgresSQLConnection { - // TODO(port): bun.ptr.RefCount(@This(), "ref_count", deinit, .{}) — intrusive refcount; - // ref()/deref() forward to this. When it hits 0, `deinit` runs and frees the Box. pub socket: JsCell, pub status: Cell, // Private — intrusive refcount invariant; reach via `ref_()`/`deref()` @@ -1224,7 +1222,6 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR if !entry.is_empty() && entry.contains(&0) { drop(options_buf); // tls_config / secure released by the errdefer above. - // TODO(port): Zig used `entry[1] ++ " must not contain null bytes"` (comptime concat). return global_object.throw_invalid_arguments_fmt(format_args!( "{} must not contain null bytes", bstr::BStr::new(name) @@ -1406,7 +1403,6 @@ impl SocketHandler { } // pub const onHandshake = if (ssl) onHandshake_ else null; - // TODO(port): conditional associated const fn — in Rust, expose `Option`. pub const ON_HANDSHAKE: Option< fn(&PostgresSQLConnection, SocketType, i32, uws::us_bun_verify_error_t), > = if SSL { Some(Self::on_handshake_) } else { None }; @@ -1481,11 +1477,6 @@ impl PostgresSQLConnection { }); } - // TODO(port): `deinit` is the intrusive-refcount destructor (called when ref_count hits 0). - // Not `impl Drop` because it frees `self`'s own Box and is also called directly on the - // connect-fail path before any JS wrapper exists. Non-pub: callers are `deref()` and the - // connect-fail path in `call()`, both in this file. - // // Raw-pointer receiver: this function ends in `heap::take(this)`. A `&mut self` // argument would carry a Stacked Borrows protector for the whole frame, and freeing // the allocation while that protector is live is UB ("deallocating while item is @@ -2444,7 +2435,6 @@ impl PostgresSQLConnection { bigint: request_flags.bigint, global_object: self.global(), count: 0, - // TODO(port): other Putter default fields }; let mut stack_buf = [DataCell::SQLDataCell::default(); 70]; @@ -3081,7 +3071,6 @@ impl PostgresSQLConnection { pub fn update_ref(&self) { self.update_has_pending_activity(); - // TODO(port): Zig reads `pending_activity_count.raw` (non-atomic). Using Relaxed load. if self.pending_activity_count.load(Ordering::Relaxed) > 0 { self.poll_ref.with_mut(|r| { r.r#ref(bun_io::posix_event_loop::get_vm_ctx( diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 8ff4c8c39cd..eadefe3c368 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -25,10 +25,6 @@ use bun_sql::shared::SQLQueryResultMode as PostgresSQLQueryResultMode; bun_core::declare_scope!(Postgres, visible); -// TODO(port): codegen module — generated by `.classes.ts` (JSPostgresSQLQuery). -// Provides targetGetCached/targetSetCached/bindingGetCached/bindingSetCached/ -// pendingValueGetCached/pendingValueSetCached/columnsGetCached/columnsSetCached/ -// queriesGetCached/fromJS/fromJSDirect/toJS. pub use crate::jsc::codegen::JSPostgresSQLQuery as js; pub use js::to_js; diff --git a/src/standalone_graph/StandaloneModuleGraph.rs b/src/standalone_graph/StandaloneModuleGraph.rs index 50cb098aaa3..b3efb8826b4 100644 --- a/src/standalone_graph/StandaloneModuleGraph.rs +++ b/src/standalone_graph/StandaloneModuleGraph.rs @@ -376,11 +376,9 @@ pub struct File { pub loader: Loader, pub contents: &'static ZStr, pub sourcemap: LazySourceMap, - // TODO(port): lifetime — assigned in runtime/api/ (out of crate) pub cached_blob: Option>, pub encoding: Encoding, pub wtf_string: BunString, - // TODO(port): Zig type is []u8 (mutable) obtained via @constCast on section bytes. // BACKREF into the embedded section; JSC mutates the bytecode buffer in place. pub bytecode: *mut [u8], pub module_info: *mut [u8], @@ -464,9 +462,6 @@ impl LazySourceMap { let mut stored = SourceMap::ParsedSourceMap::from_internal(ism); let source_files_count = serialized.source_files_count(); - // TODO(port): Zig allocated a single `[]?[]u8` of len*2 and reinterpreted - // the first half as `[][]const u8` for file_names. Rust splits into two - // separate Vecs to avoid the punning. // PERF(port): `external_source_names` is `Vec>` so we // copy the section bytes; Zig held a borrowed slice. Could switch // the field to `Vec<&'static [u8]>` for the standalone path. @@ -1689,7 +1684,7 @@ pub(crate) fn download_to_path( pub fn to_executable( target: &CompileTarget, output_files: &[OutputFile], - root_dir: Fd, // TODO(port): was std.fs.Dir + root_dir: Fd, module_prefix: &[u8], outfile: &[u8], env: &mut bun_dotenv::Loader, @@ -1739,7 +1734,6 @@ pub fn to_executable( } } else { let mut exe_path_buf = PathBuffer::uninit(); - // TODO(port): std.fmt.allocPrintSentinel — build NUL-terminated owned string. let mut version_str: Vec = Vec::new(); let _ = write!(&mut version_str, "{}", target); version_str.push(0); @@ -1940,8 +1934,6 @@ pub fn to_executable( ))); } }; - // TODO(port): std.posix.toPosixPath — copy into NUL-terminated fixed buffer. - // `resolve_path::z` does the same (copy + NUL) and yields `&ZStr`. let mut temp_posix_buf = PathBuffer::uninit(); let temp_posix = path::resolve_path::z(&temp_location, &mut temp_posix_buf); let outfile_basename = bun_paths::basename(outfile); diff --git a/src/sys/PosixStat.rs b/src/sys/PosixStat.rs index f8d8e5377d6..a8c583c8119 100644 --- a/src/sys/PosixStat.rs +++ b/src/sys/PosixStat.rs @@ -32,9 +32,6 @@ unsafe impl bun_core::ffi::Zeroable for PosixStat {} /// C's implicit integer → `uint64_t` conversion, i.e. what libuv does /// when copying platform `struct stat` fields into `uv_stat_t`. -// -// TODO(port): Zig used `@typeInfo(@TypeOf(value)).int.signedness` reflection. -// Rust has no equivalent; expressed here as a trait impl'd per primitive int. #[cfg(not(windows))] mod to_u64_impl { pub(super) trait ToU64: Copy { diff --git a/src/sys/copy_file.rs b/src/sys/copy_file.rs index 27a36f9e93e..60ec803c55f 100644 --- a/src/sys/copy_file.rs +++ b/src/sys/copy_file.rs @@ -342,7 +342,6 @@ pub fn copy_file_range( && !copy_file_state.contains(LinuxCopyFileState::HAS_COPY_FILE_RANGE_FAILED) { loop { - // TODO(port): raw syscall binding `std.os.linux.copy_file_range` // SAFETY: raw syscall; fds valid, offset ptrs null let rc = unsafe { crate::linux::copy_file_range( @@ -385,7 +384,6 @@ pub fn copy_file_range( } while !copy_file_state.contains(LinuxCopyFileState::HAS_SENDFILE_FAILED) { - // TODO(port): raw syscall binding `std.os.linux.sendfile` // SAFETY: raw syscall; fds valid, offset ptr null let rc = unsafe { crate::linux::sendfile(out, in_, core::ptr::null_mut(), len) }; crate::syslog!("sendfile({}, {}, {}) = {}", in_, out, len, rc); diff --git a/src/sys/lib.rs b/src/sys/lib.rs index 5af21f2f141..ff71add6da8 100644 --- a/src/sys/lib.rs +++ b/src/sys/lib.rs @@ -1469,7 +1469,6 @@ impl Tag { pub const SetEndOfFile: Tag = Tag(100); // ── PORT NOTE: tags below this line are Rust-port-only (no Zig ordinal). // They sit above the Zig range so a Zig-produced `Tag` never collides. - // TODO(port): upstream these into sys.zig's `Tag` enum, then realign. pub const dup2: Tag = Tag(101); pub const fchdir: Tag = Tag(102); pub const fchownat: Tag = Tag(103); diff --git a/src/sys/sys_uv.rs b/src/sys/sys_uv.rs index 28690ab4191..047309ff73d 100644 --- a/src/sys/sys_uv.rs +++ b/src/sys/sys_uv.rs @@ -50,7 +50,6 @@ pub use crate::unlinkat_with_flags; // part of the public 2-arg signature, so we cannot `pub use mkdir_w as ...` — // that would drop the second arg and break Zig-ported callers that pass a mode. #[inline] -#[allow(dead_code)] pub fn mkdir_os_path(file_path: &bun_core::WStr, flags: Mode) -> Result<()> { let _ = flags; crate::mkdir_w(file_path) @@ -214,7 +213,6 @@ pub fn fchmod(fd: Fd, flags: Mode) -> Result<()> { } } -#[allow(dead_code)] pub fn statfs(file_path: &ZStr) -> Result { // Zig: `defer req.deinit();` — `uv_fs_statfs` heap-allocates the // `uv_statfs_t` result into `req.ptr` (plus the WCHAR path copy); only @@ -553,7 +551,6 @@ pub fn close(fd: Fd) -> Option { fd.close_allowing_bad_file_descriptor(None) } -#[allow(dead_code)] pub fn close_allowing_stdout_and_stderr(fd: Fd) -> Option { // TODO(port): @returnAddress() — Rust has no stable equivalent; pass None for now. fd.close_allowing_standard_io(None) @@ -578,7 +575,6 @@ fn sum_bufs_len(bufs: &[PlatformIOVec]) -> usize { pub fn preadv(fd: Fd, bufs: &[PlatformIOVec], position: i64) -> Result { let uv_fd = fd.uv(); - // TODO(port): comptime bun.assert(bun.PlatformIOVec == uv.uv_buf_t) — static type-eq assert const _: () = assert!( core::mem::size_of::() == core::mem::size_of::() && core::mem::align_of::() == core::mem::align_of::() @@ -652,7 +648,6 @@ pub fn preadv(fd: Fd, bufs: &[PlatformIOVec], position: i64) -> Result { pub fn pwritev(fd: Fd, bufs: &[PlatformIOVecConst], position: i64) -> Result { let uv_fd = fd.uv(); - // TODO(port): comptime bun.assert(bun.PlatformIOVec == uv.uv_buf_t) — static type-eq assert const _: () = assert!( core::mem::size_of::() == core::mem::size_of::() && core::mem::align_of::() == core::mem::align_of::() diff --git a/src/sys/walker_skippable.rs b/src/sys/walker_skippable.rs index 48eb1c36cf0..8dd09b78faa 100644 --- a/src/sys/walker_skippable.rs +++ b/src/sys/walker_skippable.rs @@ -11,8 +11,6 @@ fn hash_with_seed(seed: u64, bytes: &[u8]) -> u64 { Wyhash11::hash(seed, bytes) } -// TODO(port): `DirIterator.NewWrappedIterator(if (Environment.isWindows) .u16 else .u8)` — -// `dir_iterator::WrappedIterator` is parameterized on the native OS path char in Zig. type WrappedIterator = dir_iterator::WrappedIterator; type NameBufferList = Vec; @@ -70,7 +68,6 @@ impl Walker { && self.resolve_unknown_entry_types { let dir_fd = self.stack[top_idx].iter.dir(); - // TODO(port): `base.name.sliceAssumeZ()` — assumed `.as_zstr()` match sys::lstatat(dir_fd, base.name.as_zstr()) { Ok(stat_buf) => sys::kind_from_mode(stat_buf.st_mode as sys::Mode), Err(_) => continue, // skip entries we can't stat @@ -153,8 +150,6 @@ impl Walker { )?; { self.stack.push(StackItem { - // TODO(port): Zig passed encoding `if windows .u16 else .u8`; - // assumed native-encoding overload. iter: dir_iterator::iterate(new_dir), dirname_len: cur_len, }); @@ -231,7 +226,6 @@ pub fn walk( } stack.push(StackItem { - // TODO(port): Zig passed encoding `if windows .u16 else .u8`; assumed native-encoding overload. iter: dir_iterator::iterate(self_), dirname_len: 0, }); diff --git a/src/sys/windows/env.rs b/src/sys/windows/env.rs index 6c294572922..a6adc07f2f2 100644 --- a/src/sys/windows/env.rs +++ b/src/sys/windows/env.rs @@ -34,7 +34,6 @@ pub fn convert_env_to_wtf8() -> Result<(), AllocError> { let mut num_vars: usize = 0; let wtf8_buf: Vec = 'blk: { - // TODO(port): Zig's wrapper returns OOM on null; verify `crate::windows::GetEnvironmentStringsW` signature. let wtf16_buf: *mut u16 = crate::windows::GetEnvironmentStringsW()?; let _free = scopeguard::guard(wtf16_buf, |p| { crate::windows::FreeEnvironmentStringsW(p); @@ -85,7 +84,6 @@ pub fn convert_env_to_wtf8() -> Result<(), AllocError> { // SAFETY: single-threaded startup; statics are written exactly once here. unsafe { WTF8_ENV_BUF.write(Some(wtf8_buf)); - // TODO(port): need Rust equivalent of Zig `std.os.environ` (process-global envp slice). ORIG_ENVIRON.write(Some(bun_core::os::take_environ())); bun_core::os::set_environ(envp_slice.as_mut_ptr(), envp_nonnull_len); } diff --git a/src/sys/windows/mod.rs b/src/sys/windows/mod.rs index 9bc9670224b..3b52c8d0484 100644 --- a/src/sys/windows/mod.rs +++ b/src/sys/windows/mod.rs @@ -41,14 +41,12 @@ pub mod kernel32 { // ── IOCP / async directory watching ── // safe: all args are by-value opaques (`HANDLE`/`ULONG_PTR`/`DWORD`); // a bad handle yields NULL + GetLastError, no UB. - #[allow(dead_code)] pub safe fn CreateIoCompletionPort( FileHandle: HANDLE, ExistingCompletionPort: HANDLE, CompletionKey: ULONG_PTR, NumberOfConcurrentThreads: DWORD, ) -> HANDLE; - #[allow(dead_code)] pub fn GetQueuedCompletionStatus( CompletionPort: HANDLE, lpNumberOfBytesTransferred: *mut DWORD, @@ -56,7 +54,6 @@ pub mod kernel32 { lpOverlapped: *mut *mut OVERLAPPED, dwMilliseconds: DWORD, ) -> BOOL; - #[allow(dead_code)] pub fn ReadDirectoryChangesW( hDirectory: HANDLE, lpBuffer: *mut c_void, @@ -73,7 +70,6 @@ pub mod kernel32 { pub safe fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; // ── file moves ── - #[allow(dead_code)] pub fn MoveFileExW( lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, @@ -81,22 +77,17 @@ pub mod kernel32 { ) -> BOOL; // ── SRW locks / condition variables (`bun_threading` windows arm) ── - #[allow(dead_code)] pub fn AcquireSRWLockExclusive(SRWLock: *mut SRWLOCK); pub fn ReleaseSRWLockExclusive(SRWLock: *mut SRWLOCK); // Returns BOOLEAN (u8), not BOOL — compare against 0, not FALSE. - #[allow(dead_code)] pub fn TryAcquireSRWLockExclusive(SRWLock: *mut SRWLOCK) -> u8; - #[allow(dead_code)] pub fn SleepConditionVariableSRW( ConditionVariable: *mut CONDITION_VARIABLE, SRWLock: *mut SRWLOCK, dwMilliseconds: DWORD, Flags: ULONG, ) -> BOOL; - #[allow(dead_code)] pub fn WakeConditionVariable(ConditionVariable: *mut CONDITION_VARIABLE); - #[allow(dead_code)] pub fn WakeAllConditionVariable(ConditionVariable: *mut CONDITION_VARIABLE); /// No preconditions; reads the calling thread's ID. @@ -114,7 +105,6 @@ pub use bun_windows_sys::PATH_MAX_WIDE; pub use bun_windows_sys::WORD; /// `PVOID` (winnt.h) — alias of `LPVOID`. Zig's `std.os.windows` exposes both; /// keep the alias so ported callers (`bun_shim_impl`) don't need rewriting. -#[allow(dead_code)] pub type PVOID = LPVOID; pub use bun_windows_sys::COORD; pub use bun_windows_sys::FALSE; @@ -142,13 +132,9 @@ pub use bun_windows_sys::WCHAR; /// `STARTF_USESTDHANDLES` (winbase.h). pub use bun_windows_sys::externs::STARTF_USESTDHANDLES; /// `ENABLE_VIRTUAL_TERMINAL_PROCESSING` (consoleapi.h). -#[allow(dead_code)] pub const ENABLE_VIRTUAL_TERMINAL_PROCESSING: DWORD = 0x0004; -#[allow(dead_code)] pub const MOVEFILE_COPY_ALLOWED: DWORD = 0x2; -#[allow(dead_code)] pub const MOVEFILE_REPLACE_EXISTING: DWORD = 0x1; -#[allow(dead_code)] pub const MOVEFILE_WRITE_THROUGH: DWORD = 0x8; pub use bun_windows_sys::FILETIME; @@ -213,7 +199,6 @@ pub use bun_core::windows_sys::{ /// `-11_644_473_600` seconds (1601→1970 shift). The shift is required: /// `nano_timestamp()` uses `SystemTime::UNIX_EPOCH`, not raw FILETIME. #[inline] -#[allow(dead_code)] pub const fn from_sys_time(nt_time: i64) -> i128 { /// `std.time.epoch.windows * (std.time.ns_per_s / 100)` — the /// 1601-01-01 → 1970-01-01 offset expressed in 100-ns ticks. @@ -223,9 +208,7 @@ pub const fn from_sys_time(nt_time: i64) -> i128 { pub const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; -#[allow(dead_code)] pub const NT_OBJECT_PREFIX: [u16; 4] = [b'\\' as u16, b'?' as u16, b'?' as u16, b'\\' as u16]; -#[allow(dead_code)] pub const NT_UNC_OBJECT_PREFIX: [u16; 8] = [ b'\\' as u16, b'?' as u16, @@ -238,9 +221,7 @@ pub const NT_UNC_OBJECT_PREFIX: [u16; 8] = [ ]; pub const LONG_PATH_PREFIX: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; -#[allow(dead_code)] pub const NT_OBJECT_PREFIX_U8: [u8; 4] = *b"\\??\\"; -#[allow(dead_code)] pub const NT_UNC_OBJECT_PREFIX_U8: [u8; 8] = *b"\\??\\UNC\\"; pub const LONG_PATH_PREFIX_U8: [u8; 4] = *b"\\\\?\\"; @@ -261,7 +242,6 @@ pub use bun_windows_sys::ULONG_PTR; /// `HRESULT` — 32-bit signed result code. pub type HRESULT = i32; /// `WaitForSingleObject` infinite timeout sentinel. -#[allow(dead_code)] pub const INFINITE: DWORD = 0xFFFF_FFFF; // ── SRWLOCK / CONDITION_VARIABLE (`bun_threading` windows arm) ──────────── @@ -283,11 +263,9 @@ impl Default for SRWLOCK { #[repr(transparent)] #[derive(Copy, Clone)] -#[allow(dead_code)] pub struct CONDITION_VARIABLE { pub ptr: *mut c_void, } -#[allow(dead_code)] pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = CONDITION_VARIABLE { ptr: ptr::null_mut(), }; @@ -309,20 +287,14 @@ pub const fn HRESULT_CODE(hr: HRESULT) -> HRESULT { } // `NtCreateFile` access masks / create-options not yet in `bun_windows_sys`. -#[allow(dead_code)] pub const FILE_LIST_DIRECTORY: ULONG = 0x0001; pub const FILE_OPEN_FOR_BACKUP_INTENT: ULONG = 0x0000_4000; // `ReadDirectoryChangesW` action codes (`winnt.h`). -#[allow(dead_code)] pub const FILE_ACTION_ADDED: DWORD = 0x0000_0001; -#[allow(dead_code)] pub const FILE_ACTION_REMOVED: DWORD = 0x0000_0002; -#[allow(dead_code)] pub const FILE_ACTION_MODIFIED: DWORD = 0x0000_0003; -#[allow(dead_code)] pub const FILE_ACTION_RENAMED_OLD_NAME: DWORD = 0x0000_0004; -#[allow(dead_code)] pub const FILE_ACTION_RENAMED_NEW_NAME: DWORD = 0x0000_0005; bitflags::bitflags! { @@ -352,7 +324,6 @@ bitflags::bitflags! { /// by `ReadDirectoryChangesW`. `FileName` is a flexible array; declared as /// `[WCHAR; 1]` to match the C layout (read past it via `FileNameLength`). #[repr(C)] -#[allow(dead_code)] pub struct FILE_NOTIFY_INFORMATION { pub NextEntryOffset: DWORD, pub Action: DWORD, @@ -361,9 +332,7 @@ pub struct FILE_NOTIFY_INFORMATION { } pub use bun_windows_sys::OVERLAPPED; -#[allow(dead_code)] pub type LPOVERLAPPED = *mut OVERLAPPED; -#[allow(dead_code)] pub type LPOVERLAPPED_COMPLETION_ROUTINE = Option; @@ -373,7 +342,6 @@ pub use bun_windows_sys::{PROCESS_INFORMATION, STARTUPINFOEXW, STARTUPINFOW}; /// `std.os.windows.CreateIoCompletionPort` — wraps the kernel32 call and /// returns `Err` on `NULL` (matching Zig's `error.Unexpected`). -#[allow(dead_code)] pub fn CreateIoCompletionPort( file_handle: HANDLE, existing_completion_port: HANDLE, @@ -454,7 +422,6 @@ pub use bun_errno::Win32ErrorExt; /// `Win32Error::unwrap()` from windows.zig — extension trait because /// `Win32Error` is a foreign type and `bun_core::Error` is unavailable in /// `bun_errno` (orphan rule + layering). -#[allow(dead_code)] pub trait Win32ErrorUnwrap: Copy { fn unwrap(self) -> Result<(), bun_core::Error>; } @@ -3362,7 +3329,6 @@ pub fn get_last_win32_error() -> Win32Error { /// Zig: `@tagName(bun.windows.getLastError())` — for `Output.debug` only. #[inline] -#[allow(dead_code)] pub fn get_last_error_tag() -> impl core::fmt::Display { // `Win32Error` derives `Debug`; route through that for a printable token. struct D(Win32Error); @@ -3471,9 +3437,7 @@ pub use bun_windows_sys::externs::SetInformationJobObject; // Output: // 4 // 7 -#[allow(dead_code)] pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: DWORD = 4; -#[allow(dead_code)] pub const JOB_OBJECT_MSG_EXIT_PROCESS: DWORD = 7; pub use bun_windows_sys::externs::OpenProcess; @@ -3500,8 +3464,6 @@ pub use bun_windows_sys::{ // Bun__UVSignalHandle__{init,close}: see src/runtime/node/uv_signal_handle_windows.zig -// TODO(port): @export(&windows_process_dlopen, .{ .name = "Bun__LoadLibraryBunString" }) — see #[unsafe(no_mangle)] fn below - /// Is not the actual UID of the user, but just a hash of username. pub fn user_unique_id() -> u32 { // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsch/165836c1-89d7-4abb-840d-80cf2510aa3e @@ -3527,12 +3489,10 @@ pub fn user_unique_id() -> u32 { bun_wyhash::hash32(bytemuck::cast_slice::(name)) } -#[allow(dead_code)] pub fn win_sock_error_to_zig_error( err: win32::ws2_32::WinsockError, ) -> Result<(), bun_core::Error> { use win32::ws2_32::WinsockError as W; - // TODO(port): Zig used `inline else` proposal; manual mapping below. let tag = match err { W::WSA_INVALID_HANDLE => "WSA_INVALID_HANDLE", W::WSA_NOT_ENOUGH_MEMORY => "WSA_NOT_ENOUGH_MEMORY", @@ -3767,9 +3727,7 @@ pub const ENABLE_ECHO_INPUT: DWORD = 0x004; pub const ENABLE_LINE_INPUT: DWORD = 0x002; pub const ENABLE_PROCESSED_INPUT: DWORD = 0x001; pub const ENABLE_VIRTUAL_TERMINAL_INPUT: DWORD = 0x200; -#[allow(dead_code)] pub const ENABLE_WRAP_AT_EOL_OUTPUT: DWORD = 0x0002; -#[allow(dead_code)] pub const ENABLE_PROCESSED_OUTPUT: DWORD = 0x0001; pub use bun_windows_sys::externs::GetConsoleCP; @@ -4031,19 +3989,15 @@ pub const JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION: DWORD = 0x400; pub const JOB_OBJECT_LIMIT_BREAKAWAY_OK: DWORD = 0x800; pub const JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK: DWORD = 0x00001000; -#[allow(dead_code)] const PE_HEADER_OFFSET_LOCATION: i64 = 0x3C; -#[allow(dead_code)] const SUBSYSTEM_OFFSET: i64 = 0x5C; #[repr(u16)] #[derive(Copy, Clone, PartialEq, Eq)] -#[allow(dead_code)] pub enum Subsystem { WindowsGui = 2, } -#[allow(dead_code)] pub fn edit_win32_binary_subsystem( fd: &bun_sys::File, subsystem: Subsystem, @@ -4091,9 +4045,7 @@ pub mod rescle { // TODO(port): move to windows_sys unsafe extern "C" { - #[allow(dead_code)] fn rescle__setIcon(exe_path: *const u16, icon_path: *const u16) -> c_int; - #[allow(dead_code)] fn rescle__setWindowsMetadata( exe_path: *const u16, // exe_path icon_path: *const u16, // icon_path (nullable) @@ -4110,7 +4062,6 @@ pub mod rescle { #[derive(thiserror::Error, strum::IntoStaticStr, Debug)] pub enum RescleError { #[error("IconEditError")] - #[allow(dead_code)] IconEditError, #[error("InvalidVersionFormat")] InvalidVersionFormat, @@ -4140,7 +4091,6 @@ pub mod rescle { WindowsMetadataEditError, } - #[allow(dead_code)] pub fn set_icon(exe_path: *const u16, icon: *const u16) -> Result<(), RescleError> { const _: () = assert!(cfg!(windows)); // SAFETY: paths are NUL-terminated @@ -4151,7 +4101,6 @@ pub mod rescle { } } - #[allow(dead_code)] pub fn set_windows_metadata( exe_path: *const u16, icon: Option<&[u8]>, @@ -4203,7 +4152,6 @@ pub mod rescle { None }; - // TODO(port): bun.strings.toUTF16AllocForReal returns owned [:0]u16; using Box<[u16]> here. let title_w = title .map(|t| bun_core::strings::to_utf16_alloc_for_real(t, false, true)) .transpose()?; @@ -4363,9 +4311,6 @@ const WATCHER_CHILD_ENV_Z: &[u16] = bun_core::w!("_BUN_WATCHER_CHILD\0"); // this was randomly generated - we need to avoid using a common exit code that might be used by the script itself pub const WATCHER_RELOAD_EXIT: DWORD = 3224497970; -// TODO(port): re-export of bun_runtime::api::bun::spawn::PosixSpawn removed (T1→T6 upward). -// Callers should import `bun_runtime::api::bun::spawn::PosixSpawn` directly. - pub fn is_watcher_child() -> bool { let mut buf: [u16; 1] = [0]; // SAFETY: buf valid for 1 element @@ -4569,7 +4514,6 @@ pub fn spawn_watcher_child( wShowWindow: 0, cbReserved2: 0, lpReserved2: ptr::null_mut(), - // TODO(port): std.fs.File.stdin/stdout/stderr().handle — use bun_sys stdio handles hStdInput: bun_sys::Fd::stdin().native(), hStdOutput: bun_sys::Fd::stdout().native(), hStdError: bun_sys::Fd::stderr().native(), @@ -4653,7 +4597,6 @@ pub use bun_windows_sys::externs::windows_enable_stdio_inheritance; /// Extracted from standard library except this takes an open file descriptor /// /// NOTE: THE FILE MUST BE OPENED WITH ACCESS_MASK "DELETE" OR THIS WILL FAIL -#[allow(dead_code)] pub fn delete_opened_file(fd: Fd) -> bun_sys::Result<()> { // TODO(port): comptime bun.assert(builtin.target.os.version_range.windows.min.isAtLeast(.win10_rs5)); let mut info = win32::FILE_DISPOSITION_INFORMATION_EX { @@ -4808,7 +4751,6 @@ pub fn move_opened_file_at( /// Same as moveOpenedFileAt but allows new_path to be a path relative to new_dir_fd. /// /// Aka: moveOpenedFileAtLoose(fd, dir, ".\\a\\relative\\not-normalized-path.txt", false); -#[allow(dead_code)] pub fn move_opened_file_at_loose( src_fd: Fd, new_dir_fd: Fd, @@ -4942,7 +4884,6 @@ mod kernel32_2 { // `Option<&mut i64>` (FFI-safe via the null-pointer niche → // ABI-identical to a nullable `PLARGE_INTEGER`). Bad handle → BOOL 0 // + GetLastError, never UB. - #[allow(dead_code)] pub(super) safe fn SetFilePointerEx( hFile: HANDLE, liDistanceToMove: i64, @@ -4975,13 +4916,11 @@ pub fn FreeEnvironmentStringsW(penv: *mut u16) { #[derive(thiserror::Error, strum::IntoStaticStr, Debug)] pub enum GetEnvironmentVariableError { #[error("EnvironmentVariableNotFound")] - #[allow(dead_code)] EnvironmentVariableNotFound, #[error("Unexpected")] Unexpected, } -#[allow(dead_code)] pub fn GetEnvironmentVariableW( lpName: LPWSTR, lpBuffer: *mut u16, diff --git a/src/tcc_sys/tcc.rs b/src/tcc_sys/tcc.rs index 66257f510d1..52769da1d25 100644 --- a/src/tcc_sys/tcc.rs +++ b/src/tcc_sys/tcc.rs @@ -32,7 +32,6 @@ pub type ErrorFunc = unsafe extern "C" fn(ctx: *mut Ctx, msg: *const c_char macro_rules! tcc_externs { ($($(#[$attr:meta])* fn $name:ident($($arg:ident: $ty:ty),* $(,)?) $(-> $ret:ty)?;)*) => { #[cfg(not(any(target_os = "android", target_os = "freebsd", all(windows, target_arch = "aarch64"))))] - // TODO(port): move to tcc_sys (already in *_sys crate — verify crate layout) unsafe extern "C" { $($(#[$attr])* fn $name($($arg: $ty),*) $(-> $ret)?;)* } diff --git a/src/threading/Condition.rs b/src/threading/Condition.rs index 5ef387f0776..751c1165b78 100644 --- a/src/threading/Condition.rs +++ b/src/threading/Condition.rs @@ -282,7 +282,6 @@ mod windows_impl { #[cfg(debug_assertions)] { // The internal state of the DebugMutex needs to be handled here as well. - // TODO(port): std.Thread.getCurrentId() equivalent in bun_threading. mutex .impl_ .locking_thread diff --git a/src/threading/Futex.rs b/src/threading/Futex.rs index d95a684646c..556381d24c6 100644 --- a/src/threading/Futex.rs +++ b/src/threading/Futex.rs @@ -205,9 +205,7 @@ mod darwin_impl { // // ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout // ulock_wait2() uses 64-bit nano-second timeouts (with the same convention) - // TODO(port): builtin.target.os.version_range.semver.min.major >= 11 — Rust has no - // direct compile-time min-OS-version query. Bun's deployment target is macOS 13+, so - // assume true; revisit if a runtime check is needed. + // Bun's deployment target is macOS 13+, so ulock_wait2 is always available. let supports_ulock_wait2: bool = true; let mut timeout_ns: u64 = 0; diff --git a/src/threading/Mutex.rs b/src/threading/Mutex.rs index 52b14a3c4ab..47eaf25f89f 100644 --- a/src/threading/Mutex.rs +++ b/src/threading/Mutex.rs @@ -132,7 +132,6 @@ impl Drop for MutexGuard { // Zig: `pub const deinit = void;` — no-op; Drop is implicit and there is nothing to free. -// TODO(port): Zig also gates on `!builtin.single_threaded`; Rust has no direct equivalent. #[cfg(debug_assertions)] type Impl = DebugImpl; #[cfg(not(debug_assertions))] @@ -145,13 +144,6 @@ pub type ReleaseImpl = DarwinImpl; #[cfg(not(any(windows, target_vendor = "apple")))] pub type ReleaseImpl = FutexImpl; -#[cfg(windows)] -#[allow(dead_code)] -pub(crate) type ExternImpl = bun_sys::windows::SRWLOCK; -#[cfg(not(any(windows, target_vendor = "apple")))] -#[allow(dead_code)] -pub(crate) type ExternImpl = u32; - #[cfg(debug_assertions)] type ThreadId = u64; #[cfg(debug_assertions)] @@ -408,10 +400,6 @@ impl FutexImpl { } } -// PORT NOTE: Zig had `pub const Type` inside each impl as an associated alias. -// Inherent associated types are unstable in Rust; the per-platform alias is -// already exposed as the module-level `ExternImpl` type above. - // These have to be a size known to C. #[unsafe(no_mangle)] pub(crate) unsafe extern "C" fn Bun__lock(ptr: *mut ReleaseImpl) { diff --git a/src/url/lib.rs b/src/url/lib.rs index b885f91552b..b9b1e46b537 100644 --- a/src/url/lib.rs +++ b/src/url/lib.rs @@ -1418,8 +1418,6 @@ impl PercentEncoding { let mut buf: Vec = Vec::with_capacity(input.len()); // errdefer allocator.free(buf) — Vec drops automatically on error - // TODO(port): Zig used fixedBufferStream into a pre-sized [u8; input.len]; - // here we just write into a Vec and truncate. let len = Self::decode(&mut buf, input)?; buf.truncate(len as usize); diff --git a/src/uws/lib.rs b/src/uws/lib.rs index 57bdaeefce1..1b9fb6ee9f2 100644 --- a/src/uws/lib.rs +++ b/src/uws/lib.rs @@ -143,7 +143,6 @@ pub(crate) unsafe extern "C" fn BUN__warn__extra_ca_load_failed( pub use bun_uws_sys::LIBUS_SOCKET_DESCRIPTOR; mod c { - // TODO(port): move to uws_sys unsafe extern "C" { // safe: no args; returns a process-static NUL-terminated cipher list. pub(crate) safe fn us_get_default_ciphers() -> *const core::ffi::c_char; diff --git a/src/uws_sys/App.rs b/src/uws_sys/App.rs index 35b99ed9ef0..d7fe145cd20 100644 --- a/src/uws_sys/App.rs +++ b/src/uws_sys/App.rs @@ -460,9 +460,6 @@ impl App { } /// Opaque listen socket handle, parameterized by SSL to match `App`. -/// -/// TODO(port): in Zig this was a nested `App::ListenSocket` opaque. Rust cannot -/// nest type definitions inside an `impl`; defined at module level instead. #[repr(C)] pub struct ListenSocket { _p: core::cell::UnsafeCell<[u8; 0]>, diff --git a/src/uws_sys/Loop.rs b/src/uws_sys/Loop.rs index 36399493824..b3ec2028e66 100644 --- a/src/uws_sys/Loop.rs +++ b/src/uws_sys/Loop.rs @@ -54,8 +54,6 @@ pub type EventType = libc::kevent; // TODO: #[cfg(windows)] pub type EventType = *mut c_void; -// TODO(port): Zig had `.wasm => @compileError("Unsupported OS")` — no Rust equivalent needed; -// the missing cfg arm will fail to compile on wasm. /// Trait replacing Zig's `comptime Handler: anytype` with `@hasDecl` checks for /// optional `pre`/`post`. Implementors override `PRE`/`POST` if they have them. diff --git a/src/uws_sys/Request.rs b/src/uws_sys/Request.rs index 0064617064b..cc5d5d6a5c5 100644 --- a/src/uws_sys/Request.rs +++ b/src/uws_sys/Request.rs @@ -1,6 +1,5 @@ use core::ffi::c_ushort; -// TODO(port): verify module path for H3 request opaque (h3.zig:19 — H3.Request = opaque{}) use crate::h3::Request as H3Request; // PORT NOTE: `dateForHeader` (Request.zig:62) is NOT ported here. Parsing an diff --git a/src/uws_sys/Response.rs b/src/uws_sys/Response.rs index 0d6e1dae5b5..ad7900e1ca9 100644 --- a/src/uws_sys/Response.rs +++ b/src/uws_sys/Response.rs @@ -825,7 +825,6 @@ impl AnyResponse { pub fn force_close(self) { match self { AnyResponse::SSL(ptr) => { - // TODO(port): crate::us_socket_t::close signature / CloseCode::Failure // S008: `us_socket_t` is an `opaque_ffi!` ZST — safe deref. us_socket_t::opaque_mut(TLSResponse::as_handle(ptr).downcast_socket()) .close(crate::us_socket::CloseCode::failure); diff --git a/src/uws_sys/WebSocket.rs b/src/uws_sys/WebSocket.rs index 1dc464ac3da..e73c1f24975 100644 --- a/src/uws_sys/WebSocket.rs +++ b/src/uws_sys/WebSocket.rs @@ -545,7 +545,6 @@ pub trait WebSocketHandler: Sized + 'static { /// Server type that handles the HTTP→WS upgrade. Replaces Zig's /// `comptime ServerType` parameter to `WebSocketBehavior.Wrap`. pub trait WebSocketUpgradeServer: Sized + 'static { - // TODO(port): `*NewApp(is_ssl).Response` — exact Rust type pending App.rs port. /// # Safety /// `this` is the raw user-data pointer passed to `uws_ws()` at registration /// time, cast to `*mut Self`. **Its actual pointee type is discriminated by diff --git a/src/uws_sys/us_socket_t.rs b/src/uws_sys/us_socket_t.rs index b248e911e73..e508e7bd86b 100644 --- a/src/uws_sys/us_socket_t.rs +++ b/src/uws_sys/us_socket_t.rs @@ -117,7 +117,6 @@ impl us_socket_t { if length < 0 { let errno = bun_errno::get_errno(length); debug_assert!(errno != bun_errno::E::SUCCESS); - // TODO(port): bun.errnoToZigErr — map errno to bun_core::Error return Err(bun_core::errno_to_zig_err(errno as i32)); } debug_assert!(buf.len() >= length as usize); @@ -135,7 +134,6 @@ impl us_socket_t { if length < 0 { let errno = bun_errno::get_errno(length); debug_assert!(errno != bun_errno::E::SUCCESS); - // TODO(port): bun.errnoToZigErr — map errno to bun_core::Error return Err(bun_core::errno_to_zig_err(errno as i32)); } debug_assert!(buf.len() >= length as usize); @@ -190,7 +188,6 @@ impl us_socket_t { /// Type-erased ext storage — `LIBUS_EXT_ALIGNMENT`-aligned bytes /// immediately after the C struct. Prefer `ext()`. pub fn ext_ptr(&mut self) -> *mut u8 { - // TODO(port): Rust pointer types do not carry alignment; LIBUS_EXT_ALIGNMENT == 16 c::us_socket_ext(self).cast::() } @@ -525,7 +522,6 @@ pub struct StreamBuffer { } impl us_socket_stream_buffer_t { - // TODO(port): ownership — Zig does not free the previous list_ptr here; matches that. pub fn update(&mut self, stream_buffer: StreamBuffer) { // Decompose the Vec backing `stream_buffer.list` into raw parts so // the C side can read ptr/len/cap directly. diff --git a/src/uws_sys/vtable.rs b/src/uws_sys/vtable.rs index 89a10db14b8..7173928d446 100644 --- a/src/uws_sys/vtable.rs +++ b/src/uws_sys/vtable.rs @@ -32,11 +32,9 @@ use crate::socket_group::VTable; use crate::thunk; use crate::{ConnectingSocket, us_bun_verify_error_t, us_socket_t}; -// TODO(port): Zig uses `@hasDecl(H, "onX")` structural reflection to decide -// which vtable slots are populated. Rust has no equivalent, so handlers -// implement this trait and set the `HAS_ON_*` associated consts for each -// method they actually provide. Default impls are `unreachable!()` and the -// corresponding vtable slot is left `None` when the const is `false`. +// Handlers implement this trait and set the `HAS_ON_*` associated consts for +// each method they actually provide. Default impls are `unreachable!()` and +// the corresponding vtable slot is left `None` when the const is `false`. pub trait Handler: 'static { /// What `us_socket_ext` holds. Ignored when `HAS_EXT == false`. type Ext; @@ -100,10 +98,9 @@ pub trait Handler: 'static { unreachable!() } - // TODO(port): Zig's `HAS_EXT == false` path drops the `ext` arg entirely - // (handlers take `(s, …)`). Rust can't change a trait method's arity by a - // const, so the no-ext variants are separate methods. Only called when - // `HAS_EXT == false`. + // When `HAS_EXT == false`, handlers take `(s, …)`. Rust can't change a + // trait method's arity by a const, so the no-ext variants are separate + // methods. Only called when `HAS_EXT == false`. fn on_open_no_ext(_s: *mut us_socket_t, _is_client: bool, _ip: &[u8]) { unreachable!() } @@ -212,11 +209,6 @@ impl Trampolines { // Zig: `inline fn call(s, comptime f, extra)` — conditionally prepends // `s.ext(@typeInfo(E).pointer.child)` to the arg tuple. Rust can't splat // tuples into a call, so each trampoline inlines the HAS_EXT branch. - // - // TODO(port): Zig's `s.ext(@typeInfo(E).pointer.child)` unwraps the - // pointer-child of `H.Ext` (e.g. `*MySocket` → `MySocket`) before calling - // `us_socket_ext`. Here `H::Ext` is the *pointee* type directly and - // `us_socket_t::ext::()` returns `&mut T`. #[inline(always)] fn ext(s: *mut us_socket_t) -> &'static mut H::Ext { // S008: `us_socket_t` is an `opaque_ffi!` ZST — `opaque_mut` is the diff --git a/src/watcher/INotifyWatcher.rs b/src/watcher/INotifyWatcher.rs index 25d0855fc67..a3fa274cf23 100644 --- a/src/watcher/INotifyWatcher.rs +++ b/src/watcher/INotifyWatcher.rs @@ -43,7 +43,6 @@ pub struct INotifyWatcher { pub loaded: bool, // Avoid statically allocating because it increases the binary size. - // TODO(port): lifetime — owned heap allocation; Box matches `default_allocator.alignedAlloc` in init() pub eventlist_bytes: Box, /// pointers into the next chunk of events // BACKREF: raw pointers into `eventlist_bytes`; self-referential, never freed individually. @@ -185,13 +184,6 @@ impl INotifyWatcher { result } - #[allow(dead_code)] - pub(crate) fn unwatch(&mut self, wd: EventListIndex) { - debug_assert!(self.loaded); - let _ = self.watch_count.fetch_sub(1, Ordering::Release); - let _ = bun_sys::linux::inotify_rm_watch(self.fd.native(), wd); - } - // PORT NOTE: kept as in-place &mut self init (not `-> Result`) because // INotifyWatcher is embedded as `Watcher.platform` with field defaults already set. pub(crate) fn init(&mut self, _root: &[u8]) -> Result<(), bun_core::Error> { diff --git a/src/watcher/WindowsWatcher.rs b/src/watcher/WindowsWatcher.rs index bed10c829d0..b006fe0f0b6 100644 --- a/src/watcher/WindowsWatcher.rs +++ b/src/watcher/WindowsWatcher.rs @@ -17,11 +17,7 @@ bun_core::declare_scope!(watcher, visible); pub(crate) type Platform = WindowsWatcher; -#[allow(dead_code)] -pub(crate) type EventListIndex = core::ffi::c_int; - pub struct WindowsWatcher { - #[allow(dead_code)] pub mutex: Mutex, pub iocp: HANDLE, pub watcher: DirWatcher, @@ -224,8 +220,8 @@ impl EventIterator { } impl WindowsWatcher { - // TODO(port): in-place init — `self` is the pre-allocated `platform` slot inside - // crate::Watcher (64KB+ buffers; avoid moving). Zig sig: `fn init(this, root) !void`. + // `self` is the pre-allocated `platform` slot inside crate::Watcher + // (64KB+ buffers; avoid moving). pub(crate) fn init(&mut self, root: &[u8]) -> Result<(), bun_core::Error> { use bun_paths::string_paths as paths; let mut pathbuf = WPathBuffer::uninit(); @@ -401,8 +397,6 @@ impl WindowsWatcher { #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum Timeout { Infinite = w::INFINITE, - #[allow(dead_code)] - Minimal = 1, None = 0, } diff --git a/src/watcher/lib.rs b/src/watcher/lib.rs index bb9bc611973..866a0ed8977 100644 --- a/src/watcher/lib.rs +++ b/src/watcher/lib.rs @@ -9,12 +9,8 @@ // ─── platform impls ─────────────────────────────────────────────────────── // -// Each platform watcher is compiled only for its target. All three backends -// are now un-gated against their respective `bun_sys` platform surfaces. The -// Windows backend's `init()` body alone remains re-gated on lower-tier -// symbols that have not landed (`bun_windows_sys::ntdll::NtCreateFile`, -// `bun_windows_sys::FILE_OPEN`); see the `TODO(port)` marker in -// `WindowsWatcher.rs`. A host build never compiles the non-native backends. +// Each platform watcher is compiled only for its target. A host build never +// compiles the non-native backends. // Android: same kernel inotify ABI as glibc/musl Linux. #[cfg(any(target_os = "linux", target_os = "android"))] diff --git a/src/zlib/lib.rs b/src/zlib/lib.rs index 43dba9a4345..5674d4855b7 100644 --- a/src/zlib/lib.rs +++ b/src/zlib/lib.rs @@ -329,7 +329,6 @@ impl<'a, W, const BUFFER_SIZE: usize> Drop for ZlibReader<'a, W, BUFFER_SIZE> { } } -// TODO(port): thiserror not in workspace deps; manual Display impl below. #[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum ZlibError { OutOfMemory, diff --git a/test/internal/dead-code-escape-limits.json b/test/internal/dead-code-escape-limits.json new file mode 100644 index 00000000000..d4fe128742c --- /dev/null +++ b/test/internal/dead-code-escape-limits.json @@ -0,0 +1,29 @@ +{ + "src/ast/runtime.rs": 1, + "src/bun_core/lib.rs": 1, + "src/bun_core/output.rs": 1, + "src/bundler/Chunk.rs": 2, + "src/collections/multi_array_list.rs": 8, + "src/crash_handler/lib.rs": 1, + "src/css_derive/lib.rs": 3, + "src/install/PackageInstaller.rs": 3, + "src/install/isolated_install/FileCloner.rs": 3, + "src/install/lockfile/Package.rs": 1, + "src/io/lib.rs": 2, + "src/io/posix_event_loop.rs": 8, + "src/jsc/PosixSignalHandle.rs": 6, + "src/jsc_macros/lib.rs": 2, + "src/opaque/lib.rs": 5, + "src/patch/lib.rs": 2, + "src/runtime/api/bun/Terminal.rs": 2, + "src/runtime/cli/test/ChangedFilesFilter.rs": 1, + "src/runtime/dns_jsc/dns.rs": 5, + "src/runtime/image/backend_coregraphics.rs": 14, + "src/runtime/image/codecs.rs": 1, + "src/runtime/node/path_watcher.rs": 2, + "src/runtime/server/NodeHTTPResponse.rs": 1, + "src/runtime/shell/IOWriter.rs": 1, + "src/runtime/test_runner/expect.rs": 1, + "src/runtime/webcore/ReadableStream.rs": 1, + "src/spawn_sys/posix_spawn.rs": 4 +} diff --git a/test/internal/dead-code-escapes.test.ts b/test/internal/dead-code-escapes.test.ts new file mode 100644 index 00000000000..e36dbf7e9c1 --- /dev/null +++ b/test/internal/dead-code-escapes.test.ts @@ -0,0 +1,102 @@ +// Inventory of item-level `#[allow(dead_code)]` escapes in the Rust sources. +// +// The workspace compiles with `dead_code = "deny"`, so every `#[allow(dead_code)]` +// is a deliberate escape hatch. Each one was audited by stripping the attribute +// and running `cargo check --workspace` for every CI target triple in both dev +// and release profiles: attributes whose items were dead on every target were +// deleted along with the item; attributes whose items are genuinely used (on a +// platform subset, only under `debug_assertions`, only from tests, or from +// macro expansions) were kept and are pinned here per file. +// +// If this test fails because a count went UP: prefer deleting the dead item +// instead of suppressing the lint. If the item is live on another target or +// profile (verify with `cargo check --workspace --target ` and +// `--release`), keep the attribute and update the limits by running +// `bun ./test/internal/dead-code-escapes.test.ts`. +// +// If it fails because a count went DOWN: you deleted dead code — update the +// limits the same way so the inventory stays accurate. + +import { file } from "bun"; +import { realpathSync } from "fs"; +import path from "path"; +import { globAllSources } from "../../scripts/glob-sources.ts"; + +// Item-level escapes only: `#[allow(dead_code)]`, combined lists like +// `#[allow(dead_code, non_snake_case)]`, and `#[cfg_attr(, allow(dead_code))]` +// — including predicates that themselves contain commas, e.g. +// `#[cfg_attr(any(unix, test), allow(dead_code))]` (lazy `[^\]]+?,` backtracks to +// the first comma whose suffix parses as `allow(...)`), attributes that rustfmt +// wrapped across multiple lines (newlines aren't `]`), and trailing meta items +// after the allow, e.g. `#[cfg_attr(test, allow(dead_code), derive(Debug))]` +// (`[^\]]*\]` tail). Neither `[^\]]` class can cross a `]`, so a match is always +// fenced inside a single attribute and cannot span from one `#[...]` to the next. +// Module-level `#![allow(...)]` blocks (codegen surfaces such as +// `runtime/generated_classes.rs` and `jsc/cpp.rs`) are intentionally not counted. +const ESCAPE = /#\[\s*(?:cfg_attr\([^\]]+?,\s*)?allow\([^)]*\bdead_code\b[^)]*\)[^\]]*\]/g; + +const limits: Record = await Bun.file(import.meta.dir + "/dead-code-escape-limits.json").json(); + +const root = path.resolve(import.meta.dir, "..", ".."); +const rustSources = globAllSources().rust.filter(p => p.endsWith(".rs")); + +// Only count files tracked in HEAD: editors and `git stash` round-trips can +// leave stray `.rs` files in the working tree (e.g. files a branch deletes +// being temporarily restored), and those must not fail the ratchet. CI runs +// against the committed tree, so every real file is covered. +const tracked: Set | null = (() => { + const r = Bun.spawnSync({ + cmd: ["git", "-C", root, "ls-tree", "-r", "--name-only", "-z", "HEAD"], + stdout: "pipe", + stderr: "ignore", + }); + if (!r.success) return null; + return new Set(r.stdout.toString().split("\0").filter(Boolean)); +})(); + +const counts: Record = {}; +for (const abs of rustSources) { + const source = path.relative(root, abs).replaceAll(path.sep, "/"); + // `src/cli` is a symlink into `src/runtime/cli`; count each file once + // under its canonical path. + if (path.relative(root, realpathSync(abs)).replaceAll(path.sep, "/") !== source) continue; + if (tracked !== null && !tracked.has(source)) continue; + const content = await file(abs).text(); + // Whole-file scan so rustfmt-wrapped attributes are counted too; strip + // full-line `//` comments first so commented-out escapes stay ignored. + const stripped = content.replace(/^\s*\/\/.*$/gm, ""); + const n = [...stripped.matchAll(ESCAPE)].length; + if (n > 0) counts[source] = n; +} + +if (typeof describe === "undefined") { + // Standalone mode (`bun ./test/internal/dead-code-escapes.test.ts`): + // regenerate the limits file from the current tree. + const sorted = Object.fromEntries(Object.entries(counts).sort(([a], [b]) => (a < b ? -1 : 1))); + await Bun.write(import.meta.dir + "/dead-code-escape-limits.json", JSON.stringify(sorted, null, 2) + "\n"); + console.log(`Wrote ${Object.keys(sorted).length} files to dead-code-escape-limits.json`); + process.exit(0); +} + +describe("#[allow(dead_code)] escapes", () => { + const files = new Set([...Object.keys(limits), ...Object.keys(counts)]); + for (const source of [...files].sort()) { + const limit = limits[source] ?? 0; + const count = counts[source] ?? 0; + test(`${source} (${limit})`, () => { + if (count > limit) { + throw new Error( + `${source} has ${count} item-level #[allow(dead_code)] escapes, up from ${limit}.\n` + + `Every escape must hide code that is live on SOME target/profile; dead code must be deleted instead.\n` + + `Verify with \`cargo check --workspace --target \` (all CI triples) in dev AND release profiles.\n` + + `If the new escape is justified, update the inventory with \`bun ./test/internal/dead-code-escapes.test.ts\`.`, + ); + } else if (count < limit) { + throw new Error( + `${source} has ${count} item-level #[allow(dead_code)] escapes, down from ${limit}.\n` + + `Update the inventory with \`bun ./test/internal/dead-code-escapes.test.ts\`.`, + ); + } + }); + } +});