From 67ab8eaa5c12602a754f26867d7246c364cfda98 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 03:31:24 +0000 Subject: [PATCH 1/7] collections: make allocation-only APIs infallible ArrayHashMap, StringArrayHashMap, StringHashMap, StringSet, StringMap, HashMap, MultiArrayList, the bit sets, ByteVecExt, OffsetByteList and PriorityQueue returned Result<_, AllocError> from methods whose bodies grow a Vec or hashbrown table, which abort on allocation failure and never return Err. The raw-allocation containers (MultiArrayList, the dynamic bit sets) now call handle_alloc_error like Vec does. The crash handler installs an alloc error hook so every failed infallible allocation is reported as out-of-memory instead of as an abort() crash. Types whose clone() returned Result now implement Clone. Leaf callers updated; LinearFifo is left fallible because a full StaticBuffer is reported through the same error. --- src/ast/nodes.rs | 61 +++---- src/ast/server_component_boundary.rs | 16 +- src/collections/array_hash_map.rs | 234 +++++++++++---------------- src/collections/array_list.rs | 10 +- src/collections/bit_set.rs | 112 +++++++------ src/collections/lib.rs | 3 +- src/collections/multi_array_list.rs | 58 ++++--- src/collections/string_map.rs | 11 +- src/collections/vec_ext.rs | 37 +++-- src/collections/zig_hash_map.rs | 34 ++-- src/crash_handler/lib.rs | 11 ++ src/dotenv/env_loader.rs | 139 +++++++--------- src/dotenv/error.rs | 3 - src/glob/GlobWalker.rs | 7 +- src/http_types/ETag.rs | 17 +- src/http_types/MimeType.rs | 6 +- src/io/PipeWriter.rs | 2 +- src/libarchive/lib.rs | 5 +- src/md/helpers.rs | 4 +- src/parsers/yaml.rs | 25 ++- src/react_compiler/collections.rs | 4 +- src/s3_signing/credentials.rs | 2 +- src/semver/lib.rs | 22 +-- src/watcher/Watcher.rs | 11 +- 24 files changed, 355 insertions(+), 479 deletions(-) diff --git a/src/ast/nodes.rs b/src/ast/nodes.rs index cac0f62a22c6..dc045851d386 100644 --- a/src/ast/nodes.rs +++ b/src/ast/nodes.rs @@ -910,33 +910,19 @@ impl DeclaredSymbolList { core::mem::take(self) } - pub fn clone(&self) -> core::result::Result { - Ok(DeclaredSymbolList { - entries: self.entries.clone()?, - }) - } - #[inline] pub fn len(&self) -> usize { self.entries.len() } - pub fn append( - &mut self, - entry: DeclaredSymbol, - ) -> core::result::Result<(), bun_alloc::AllocError> { - self.ensure_unused_capacity(1)?; + pub fn append(&mut self, entry: DeclaredSymbol) { + self.ensure_unused_capacity(1); self.append_assume_capacity(entry); - Ok(()) } - pub fn append_list( - &mut self, - other: &DeclaredSymbolList, - ) -> core::result::Result<(), bun_alloc::AllocError> { - self.ensure_unused_capacity(other.len())?; + pub fn append_list(&mut self, other: &DeclaredSymbolList) { + self.ensure_unused_capacity(other.len()); self.append_list_assume_capacity(other); - Ok(()) } pub(crate) fn append_list_assume_capacity(&mut self, other: &DeclaredSymbolList) { @@ -947,18 +933,12 @@ impl DeclaredSymbolList { self.entries.append_assume_capacity(entry); } - pub fn ensure_total_capacity( - &mut self, - count: usize, - ) -> core::result::Result<(), bun_alloc::AllocError> { - self.entries.ensure_total_capacity(count) + pub fn ensure_total_capacity(&mut self, count: usize) { + self.entries.ensure_total_capacity(count); } - pub fn ensure_unused_capacity( - &mut self, - count: usize, - ) -> core::result::Result<(), bun_alloc::AllocError> { - self.entries.ensure_unused_capacity(count) + pub fn ensure_unused_capacity(&mut self, count: usize) { + self.entries.ensure_unused_capacity(count); } pub fn clear_retaining_capacity(&mut self) { @@ -967,23 +947,26 @@ impl DeclaredSymbolList { // `deinit` → Drop on MultiArrayList; no explicit body needed. - pub fn init_capacity( - capacity: usize, - ) -> core::result::Result { + pub fn init_capacity(capacity: usize) -> DeclaredSymbolList { let mut entries = MultiArrayList::new_in(bun_alloc::AstAlloc); - entries.ensure_unused_capacity(capacity)?; - Ok(DeclaredSymbolList { entries }) + entries.ensure_unused_capacity(capacity); + DeclaredSymbolList { entries } } - pub fn from_slice( - entries: &[DeclaredSymbol], - ) -> core::result::Result { - let mut this = Self::init_capacity(entries.len())?; - // errdefer this.deinit() → Drop handles it + pub fn from_slice(entries: &[DeclaredSymbol]) -> DeclaredSymbolList { + let mut this = Self::init_capacity(entries.len()); for entry in entries { this.append_assume_capacity(*entry); } - Ok(this) + this + } +} + +impl Clone for DeclaredSymbolList { + fn clone(&self) -> Self { + DeclaredSymbolList { + entries: self.entries.clone(), + } } } diff --git a/src/ast/server_component_boundary.rs b/src/ast/server_component_boundary.rs index 598f457e4b68..ef641e9deedc 100644 --- a/src/ast/server_component_boundary.rs +++ b/src/ast/server_component_boundary.rs @@ -68,13 +68,13 @@ impl List { use_directive: UseDirective, reference_source_index: IndexInt, ssr_source_index: IndexInt, - ) -> Result<(), bun_alloc::AllocError> { + ) { self.list.append(ServerComponentBoundary { source_index, use_directive, reference_source_index, ssr_source_index, - })?; + }); // For borrowck we hand the adapter just the `source_index` column // it needs. let gop = self.map.get_or_put_adapted( @@ -82,9 +82,8 @@ impl List { &Adapter { source_indices: self.list.items::<"source_index", IndexInt>(), }, - )?; + ); debug_assert!(!gop.found_existing); - Ok(()) } /// Use this to improve speed of accessing fields at the cost of @@ -122,15 +121,12 @@ impl<'a> Slice<'a> { Some(self.list.items::<"reference_source_index", IndexInt>()[i]) } - pub fn bit_set( - &self, - input_file_count: usize, - ) -> Result { - let mut scb_bitset = DynamicBitSetUnmanaged::init_empty(input_file_count)?; + pub fn bit_set(&self, input_file_count: usize) -> DynamicBitSetUnmanaged { + let mut scb_bitset = DynamicBitSetUnmanaged::init_empty(input_file_count); for &source_index in self.list.items::<"source_index", IndexInt>() { scb_bitset.set(source_index as usize); } - Ok(scb_bitset) + scb_bitset } } diff --git a/src/collections/array_hash_map.rs b/src/collections/array_hash_map.rs index 9a638abec709..efa8da074a3f 100644 --- a/src/collections/array_hash_map.rs +++ b/src/collections/array_hash_map.rs @@ -28,8 +28,6 @@ use bun_alloc::{DefaultAlloc, HashbrownAllocator}; use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; -use bun_alloc::AllocError; - // ────────────────────────────────────────────────────────────────────────── // Free functions // ────────────────────────────────────────────────────────────────────────── @@ -416,10 +414,9 @@ impl Default for ArrayHashMap { } } -impl ArrayHashMap { - /// Fallible (OOM) clone; kept as `Result` for API stability. - pub fn clone(&self) -> Result { - Ok(Self { +impl Clone for ArrayHashMap { + fn clone(&self) -> Self { + Self { keys: self.keys.clone(), values: self.values.clone(), hashes: self.hashes.clone(), @@ -427,7 +424,7 @@ impl ArrayHashMap { ctx: C::default(), #[cfg(debug_assertions)] pointer_stability: core::sync::atomic::AtomicBool::new(false), - }) + } } } @@ -530,13 +527,8 @@ impl ArrayHashMap { self.index = None; } - pub fn ensure_total_capacity(&mut self, n: usize) -> Result<(), AllocError> { - let need = n.saturating_sub(self.keys.len()); - self.keys.reserve(need); - self.values.reserve(need); - self.hashes.reserve(need); - self.reserve_index_to_capacity(); - Ok(()) + pub fn ensure_total_capacity(&mut self, n: usize) { + self.reserve(n.saturating_sub(self.keys.len())); } /// Bulk-resize the backing columns so callers can @@ -586,15 +578,12 @@ impl ArrayHashMap { self.push_entry(key, value, h); } - pub fn ensure_unused_capacity(&mut self, additional: usize) -> Result<(), AllocError> { - self.keys.reserve(additional); - self.values.reserve(additional); - self.hashes.reserve(additional); - self.reserve_index_to_capacity(); - Ok(()) + #[inline] + pub fn ensure_unused_capacity(&mut self, additional: usize) { + self.reserve(additional); } - /// std-HashMap-compat alias for `ensure_unused_capacity` (infallible). + /// std-HashMap-compat alias for `ensure_unused_capacity`. #[inline] pub fn reserve(&mut self, additional: usize) { self.keys.reserve(additional); @@ -990,7 +979,7 @@ impl, A: MapAllocator> ArrayHashMap { /// Recompute every stored hash from the current keys. Call after mutating /// keys via `keys_mut()`. - pub fn re_index(&mut self) -> Result<(), AllocError> { + pub fn re_index(&mut self) { for (i, k) in self.keys.iter().enumerate() { self.hashes[i] = self.ctx.hash(k); } @@ -998,10 +987,9 @@ impl, A: MapAllocator> ArrayHashMap { if self.keys.len() > INDEX_THRESHOLD { self.rebuild_index(); } - Ok(()) } - pub fn put(&mut self, key: K, value: V) -> Result<(), AllocError> { + pub fn put(&mut self, key: K, value: V) { let h = self.ctx.hash(&key); if let Some(i) = self.find_hash(h, |k, idx| self.ctx.eql(&key, k, idx)) { // Only the value is assigned on hit; the original key is preserved. @@ -1009,10 +997,9 @@ impl, A: MapAllocator> ArrayHashMap { } else { self.push_entry(key, value, h); } - Ok(()) } - pub fn put_no_clobber(&mut self, key: K, value: V) -> Result<(), AllocError> { + pub fn put_no_clobber(&mut self, key: K, value: V) { let h = self.ctx.hash(&key); debug_assert!( self.find_hash(h, |k, idx| self.ctx.eql(&key, k, idx)) @@ -1020,13 +1007,12 @@ impl, A: MapAllocator> ArrayHashMap { "put_no_clobber: key already present", ); self.push_entry(key, value, h); - Ok(()) } /// PERF: skips the grow check, but `Vec::push` will still reallocate if /// the caller lied about capacity. pub fn put_assume_capacity(&mut self, key: K, value: V) { - let _ = self.put(key, value); + self.put(key, value); } /// std-HashMap-compat alias for `put`, returning the displaced value. @@ -1180,45 +1166,35 @@ impl<'a, K, V, C, A: MapAllocator> MapEntry<'a, K, V, C, A> { impl, A: MapAllocator> ArrayHashMap { /// Look up `key`; if absent, append it with a defaulted /// value slot and return `found_existing = false`. - pub fn get_or_put(&mut self, key: K) -> Result, AllocError> { + pub fn get_or_put(&mut self, key: K) -> GetOrPutResult<'_, K, V> { let h = self.ctx.hash(&key); if let Some(i) = self.find_hash(h, |k, idx| self.ctx.eql(&key, k, idx)) { - return Ok(self.gop_at(i, true)); + return self.gop_at(i, true); } + // PERF: `push_within_capacity` is unstable; `push` is a no-grow when + // a prior `ensure_unused_capacity` reserved the slot. let i = self.push_entry(key, V::default(), h); - Ok(self.gop_at(i, false)) + self.gop_at(i, false) } - /// Like [`get_or_put`] but skips the grow - /// check. Caller must have called `ensure_unused_capacity` first. + /// Alias for [`get_or_put`]; `Vec::push` still grows if the caller lied + /// about capacity. + #[inline] pub fn get_or_put_assume_capacity(&mut self, key: K) -> GetOrPutResult<'_, K, V> { - let h = self.ctx.hash(&key); - if let Some(i) = self.find_hash(h, |k, idx| self.ctx.eql(&key, k, idx)) { - return self.gop_at(i, true); - } - // PERF: `push_within_capacity` is unstable; `push` is a no-grow - // when the prior `ensure_unused_capacity` reserved the slot. - let i = self.push_entry(key, V::default(), h); - self.gop_at(i, false) + self.get_or_put(key) } /// Like `get_or_put` but writes `value` when absent. - pub fn get_or_put_value( - &mut self, - key: K, - value: V, - ) -> Result, AllocError> { - let gop = self.get_or_put(key)?; + pub fn get_or_put_value(&mut self, key: K, value: V) -> GetOrPutResult<'_, K, V> { + let gop = self.get_or_put(key); if !gop.found_existing { - // SAFETY: re-borrow at same index — `gop` borrows `self` so go - // through the slot it already points at. *gop.value_ptr = value; } // Can't return `gop` while it borrows in the branch above without // NLL gymnastics; recompute via index. let i = gop.index; let found = gop.found_existing; - Ok(self.gop_at(i, found)) + self.gop_at(i, found) } } @@ -1230,16 +1206,16 @@ impl ArrayHashMap { &mut self, key: &Q, adapter: &Ad, - ) -> Result, AllocError> + ) -> GetOrPutResult<'_, K, V> where Ad: ArrayHashAdapter, { let h = adapter.hash(key); if let Some(i) = self.find_hash(h, |k, idx| adapter.eql(key, k, idx)) { - return Ok(self.gop_at(i, true)); + return self.gop_at(i, true); } let i = self.push_entry(K::default(), V::default(), h); - Ok(self.gop_at(i, false)) + self.gop_at(i, false) } } @@ -1284,13 +1260,12 @@ impl Default for StringArrayHashMap { } } -impl StringArrayHashMap { - /// Fallible (OOM) clone; kept as `Result` for API stability. - pub fn clone(&self) -> Result { - Ok(Self { - inner: self.inner.clone()?, +impl Clone for StringArrayHashMap { + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), ctx: C::default(), - }) + } } } @@ -1364,18 +1339,17 @@ impl + Default, A: MapAllocator> StringArrayHashMap } } - pub fn put(&mut self, key: &[u8], value: V) -> Result<(), AllocError> { + pub fn put(&mut self, key: &[u8], value: V) { let h = self.ctx.hash(key); if let Some(i) = self.inner.find_hash(h, |k, idx| self.ctx.eql(key, k, idx)) { self.inner.values[i] = value; } else { self.inner.push_entry(box_key::(key), value, h); } - Ok(()) } pub fn put_assume_capacity(&mut self, key: &[u8], value: V) { - let _ = self.put(key, value); + self.put(key, value); } pub fn swap_remove(&mut self, key: &[u8]) -> bool { @@ -1399,29 +1373,26 @@ impl + Default, A: MapAllocator> StringArr /// See `ArrayHashMap::get_or_put`. The key is boxed on insert; callers that /// then write `*gop.key_ptr = Box::from(key)` are doing a redundant alloc — /// harmless. - pub fn get_or_put( - &mut self, - key: &[u8], - ) -> Result, V>, AllocError> { + pub fn get_or_put(&mut self, key: &[u8]) -> GetOrPutResult<'_, Box<[u8], A>, V> { let h = self.ctx.hash(key); if let Some(i) = self.inner.find_hash(h, |k, idx| self.ctx.eql(key, k, idx)) { - return Ok(self.inner.gop_at(i, true)); + return self.inner.gop_at(i, true); } let i = self.inner.push_entry(box_key::(key), V::default(), h); - Ok(self.inner.gop_at(i, false)) + self.inner.gop_at(i, false) } pub fn get_or_put_value( &mut self, key: &[u8], value: V, - ) -> Result, V>, AllocError> { + ) -> GetOrPutResult<'_, Box<[u8], A>, V> { let h = self.ctx.hash(key); if let Some(i) = self.inner.find_hash(h, |k, idx| self.ctx.eql(key, k, idx)) { - return Ok(self.inner.gop_at(i, true)); + return self.inner.gop_at(i, true); } let i = self.inner.push_entry(box_key::(key), value, h); - Ok(self.inner.gop_at(i, false)) + self.inner.gop_at(i, false) } } @@ -1749,13 +1720,11 @@ impl StringHashMap self.inner.values_mut() } - pub fn ensure_total_capacity(&mut self, n: usize) -> Result<(), AllocError> { - let need = n.saturating_sub(self.inner.len()); - self.inner.reserve(need); - Ok(()) + pub fn ensure_total_capacity(&mut self, n: usize) { + self.inner.reserve(n.saturating_sub(self.inner.len())); } - pub fn put(&mut self, key: &[u8], value: V) -> Result<(), AllocError> { + pub fn put(&mut self, key: &[u8], value: V) { use hashbrown::hash_map::RawEntryMut; let hash = self.hash_key(key); match self @@ -1770,7 +1739,6 @@ impl StringHashMap e.insert_hashed_nocheck(hash, owned_key::(key), value); } } - Ok(()) } /// Insert `value` under `key` **without copying the key bytes**. This is @@ -1780,9 +1748,8 @@ impl StringHashMap /// `EntryStore`, AST heap) where the `'static` was minted via an explicit /// `unsafe` lifetime widen at the call site. #[inline] - pub fn put_static_key(&mut self, key: &'static [u8], value: V) -> Result<(), AllocError> { + pub fn put_static_key(&mut self, key: &'static [u8], value: V) { self.inner.insert(StringHashMapKey::borrowed(key), value); - Ok(()) } /// The hash this map's `BuildHasher` assigns `key` — exactly what @@ -1814,12 +1781,7 @@ impl StringHashMap /// recomputing. Same zero-copy / `'static`-key contract as [`put_static_key`]: /// overwrites the value if the key is already present. #[inline] - pub fn put_static_key_hashed( - &mut self, - hash: u64, - key: &'static [u8], - value: V, - ) -> Result<(), AllocError> { + pub fn put_static_key_hashed(&mut self, hash: u64, key: &'static [u8], value: V) { use hashbrown::hash_map::RawEntryMut; match self .inner @@ -1833,7 +1795,6 @@ impl StringHashMap e.insert_hashed_nocheck(hash, StringHashMapKey::borrowed(key), value); } } - Ok(()) } /// Insert `value` under `key` **without copying the key bytes** — the @@ -1851,20 +1812,18 @@ impl StringHashMap /// point into source text or the lexer string-table, both of which outlive /// the `AstAlloc` arena that owns the `Scope` holding this map. #[inline] - pub unsafe fn put_borrowed(&mut self, key: &[u8], value: V) -> Result<(), AllocError> { + pub unsafe fn put_borrowed(&mut self, key: &[u8], value: V) { // SAFETY: caller contract above. Erase the borrow's lifetime so it can // be stored as `Static` without a heap copy; the map never inspects the // lifetime, only the (ptr, len) pair. let key: &'static [u8] = unsafe { &*std::ptr::from_ref::<[u8]>(key) }; self.inner.insert(StringHashMapKey::borrowed(key), value); - Ok(()) } - /// PERF: std::HashMap cannot skip the grow check, so this is - /// just `put` without the `Result`. + /// PERF: std::HashMap cannot skip the grow check, so this is just `put`. #[inline] pub fn put_assume_capacity(&mut self, key: &[u8], value: V) { - let _ = self.put(key, value); + self.put(key, value); } } @@ -1879,44 +1838,38 @@ impl StringHash /// allocated on miss. Callers whose key bytes already outlive the map /// should prefer [`get_or_put_borrowed`] which also skips the miss-path /// box. - pub fn get_or_put(&mut self, key: &[u8]) -> Result, AllocError> { + pub fn get_or_put(&mut self, key: &[u8]) -> StringHashMapGetOrPut<'_, V> { use hashbrown::hash_map::RawEntryMut; let hash = self.hash_key(key); - Ok( - match self - .inner - .raw_entry_mut() - .from_key_hashed_nocheck(hash, key) - { - RawEntryMut::Occupied(o) => StringHashMapGetOrPut { - found_existing: true, - value_ptr: o.into_mut(), - }, - RawEntryMut::Vacant(v) => StringHashMapGetOrPut { - found_existing: false, - value_ptr: v - .insert_hashed_nocheck(hash, owned_key::(key), V::default()) - .1, - }, + match self + .inner + .raw_entry_mut() + .from_key_hashed_nocheck(hash, key) + { + RawEntryMut::Occupied(o) => StringHashMapGetOrPut { + found_existing: true, + value_ptr: o.into_mut(), }, - ) + RawEntryMut::Vacant(v) => StringHashMapGetOrPut { + found_existing: false, + value_ptr: v + .insert_hashed_nocheck(hash, owned_key::(key), V::default()) + .1, + }, + } } - pub fn get_or_put_value(&mut self, key: &[u8], value: V) -> Result<&mut V, AllocError> { + pub fn get_or_put_value(&mut self, key: &[u8], value: V) -> &mut V { use hashbrown::hash_map::RawEntryMut; let hash = self.hash_key(key); - Ok( - match self - .inner - .raw_entry_mut() - .from_key_hashed_nocheck(hash, key) - { - RawEntryMut::Occupied(e) => e.into_mut(), - RawEntryMut::Vacant(e) => { - e.insert_hashed_nocheck(hash, owned_key::(key), value).1 - } - }, - ) + match self + .inner + .raw_entry_mut() + .from_key_hashed_nocheck(hash, key) + { + RawEntryMut::Occupied(e) => e.into_mut(), + RawEntryMut::Vacant(e) => e.insert_hashed_nocheck(hash, owned_key::(key), value).1, + } } /// Zero-allocation `getOrPut` — the arena-lifetime twin of @@ -1992,7 +1945,7 @@ pub mod string_hash_map { // ────────────────────────────────────────────────────────────────────────── /// `bun.StringSet` — insertion-ordered set of owned byte-string keys. -#[derive(Default)] +#[derive(Default, Clone)] pub struct StringSet { pub map: StringArrayHashMap<()>, } @@ -2009,12 +1962,6 @@ impl StringSet { Self::default() } - pub fn clone(&self) -> Result { - Ok(Self { - map: self.map.clone()?, - }) - } - #[inline] pub fn is_empty(&self) -> bool { self.map.count() == 0 @@ -2030,12 +1977,11 @@ impl StringSet { self.map.keys() } - /// Insert `key`, duping it on miss. Returns `Ok(())` whether or not the key - /// was already present. - pub fn insert(&mut self, key: &[u8]) -> Result<(), AllocError> { + /// Insert `key`, duping it on miss. Returns whether the key was newly + /// inserted (`std::HashSet::insert` semantics). + pub fn insert(&mut self, key: &[u8]) -> bool { // get_or_put already boxes `key` on miss. - let _ = self.map.get_or_put(key)?; - Ok(()) + !self.map.get_or_put(key).found_existing } #[inline] @@ -2091,7 +2037,7 @@ mod index_tests { let mut m: ArrayHashMap = ArrayHashMap::new(); // Cross the threshold so the index is exercised. for i in 0..1000u64 { - assert!(m.put(i.wrapping_mul(2654435761), i).is_ok()); + m.put(i.wrapping_mul(2654435761), i); } for i in 0..1000u64 { let k = i.wrapping_mul(2654435761); @@ -2106,7 +2052,7 @@ mod index_tests { assert_eq!(m.get(&k), Some(&i)); } // get_or_put on an existing key after the index was dropped+rebuilt. - let gop = m.get_or_put(2654435761).unwrap(); + let gop = m.get_or_put(2654435761); assert!(gop.found_existing); assert_eq!(*gop.value_ptr, 1); } @@ -2138,7 +2084,7 @@ mod index_tests { let mut m: StringArrayHashMap = StringArrayHashMap::new(); let keys: Vec = (0..200).map(|i| format!("key{i}")).collect(); for (i, k) in keys.iter().enumerate() { - m.put(k.as_bytes(), i).unwrap(); + m.put(k.as_bytes(), i); } for (i, k) in keys.iter().enumerate() { assert_eq!(m.get(k.as_bytes()), Some(&i)); @@ -2186,24 +2132,24 @@ mod index_tests { fn string_hash_map_no_alloc_on_hit() { let mut m: StringHashMap = StringHashMap::new(); // Pre-size so the table itself does not reallocate during the test. - m.ensure_total_capacity(4).unwrap(); + m.ensure_total_capacity(4); let base = COUNTING_ALLOCS.load(Ordering::Relaxed); - m.put(b"aa", 1).unwrap(); - m.put(b"bb", 2).unwrap(); + m.put(b"aa", 1); + m.put(b"bb", 2); let after_miss = COUNTING_ALLOCS.load(Ordering::Relaxed); assert_eq!(after_miss - base, 2, "one key Box per distinct key on miss"); // Hits via every safe owning entry point must not box the key again. - m.put(b"aa", 10).unwrap(); + m.put(b"aa", 10); m.put_assume_capacity(b"bb", 20); - assert!(m.get_or_put(b"aa").unwrap().found_existing); - assert_eq!(*m.get_or_put_value(b"bb", 0).unwrap(), 20); + assert!(m.get_or_put(b"aa").found_existing); + assert_eq!(*m.get_or_put_value(b"bb", 0), 20); let after_hit = COUNTING_ALLOCS.load(Ordering::Relaxed); assert_eq!(after_hit, after_miss, "hits must not allocate a key Box"); // A fresh key via get_or_put boxes exactly once. - let g = m.get_or_put(b"cc").unwrap(); + let g = m.get_or_put(b"cc"); assert!(!g.found_existing); *g.value_ptr = 30; assert_eq!(COUNTING_ALLOCS.load(Ordering::Relaxed), after_hit + 1); diff --git a/src/collections/array_list.rs b/src/collections/array_list.rs index 7f4bde27b7d4..a1e5d6a17dc4 100644 --- a/src/collections/array_list.rs +++ b/src/collections/array_list.rs @@ -1,8 +1,6 @@ #![forbid(unsafe_code)] //! Managed `ArrayList` wrappers. -use bun_alloc::AllocError; - /// Managed `ArrayList` using the default allocator. No overhead compared to an unmanaged /// `ArrayList`. pub type ArrayListDefault = ArrayListAlignedIn; @@ -24,12 +22,10 @@ impl ArrayListAlignedIn { } } - pub fn init_capacity(num: usize) -> Result { - // Vec::with_capacity aborts on OOM rather than returning Err. Could swap to - // `Vec::try_with_capacity` (nightly) or a fallible wrapper if OOM recovery matters. - Ok(Self { + pub fn init_capacity(num: usize) -> Self { + Self { unmanaged: Vec::with_capacity(num), - }) + } } /// The contents of `unmanaged` must have been allocated by the global allocator. diff --git a/src/collections/bit_set.rs b/src/collections/bit_set.rs index 8e68e97f19ec..b80bd5526f67 100644 --- a/src/collections/bit_set.rs +++ b/src/collections/bit_set.rs @@ -30,8 +30,6 @@ use core::mem; use core::ptr; use core::slice; -use bun_alloc::AllocError; - // ───────────────────────────── helpers ───────────────────────────── /// Returns `usize::MAX` if `value`, else `0`. @@ -465,6 +463,17 @@ impl Drop for DynamicBitSetUnmanaged { } } +impl Clone for DynamicBitSetUnmanaged { + /// Deep copy into a fresh allocation (also valid on a `DynamicBitSetList` + /// view; the copy owns its own storage). + fn clone(&self) -> Self { + let mut copy = Self::default(); + copy.resize(self.bit_length, false); + copy.masks_slice_mut().copy_from_slice(self.masks_slice()); + copy + } +} + impl DynamicBitSetUnmanaged { // There is no `const` empty value (the empty sentinel pointer is computed at // runtime); use `Self::default()`. @@ -516,16 +525,16 @@ impl DynamicBitSetUnmanaged { /// Creates a bit set with no elements present. /// If bit_length is not zero, deinit must eventually be called. - pub fn init_empty(bit_length: usize) -> Result { + pub fn init_empty(bit_length: usize) -> Self { let mut this = Self::default(); - this.resize(bit_length, false)?; - Ok(this) + this.resize(bit_length, false); + this } /// Resizes to a new bit_length. If the new length is larger /// than the old length, fills any added bits with `fill`. /// If new_len is not zero, deinit must eventually be called. - pub fn resize(&mut self, new_len: usize, fill: bool) -> Result<(), AllocError> { + pub fn resize(&mut self, new_len: usize, fill: bool) { let old_len = self.bit_length; let old_masks = Self::num_masks(old_len); @@ -547,7 +556,7 @@ impl DynamicBitSetUnmanaged { unsafe { dyn_free(alloc_base, old_alloc_len) }; self.masks = empty_masks_ptr(); self.bit_length = 0; - return Ok(()); + return; } 'realloc: { @@ -563,9 +572,9 @@ impl DynamicBitSetUnmanaged { // SAFETY: alloc_base/old_alloc_len describe the current allocation. let new_alloc = match unsafe { dyn_realloc(alloc_base, old_alloc_len, new_masks + 1) } { Ok(p) => p, - Err(err) => { + Err(layout) => { if new_masks + 1 > old_alloc_len { - return Err(err); + std::alloc::handle_alloc_error(layout); } break 'realloc; } @@ -611,22 +620,13 @@ impl DynamicBitSetUnmanaged { // And finally, save the new length. self.bit_length = new_len; - Ok(()) } /// deinitializes the array and releases its memory. /// The passed allocator must be the same one used for /// init* or resize in the past. Idempotent. pub fn deinit(&mut self) { - self.resize(0, false).expect("unreachable"); - } - - /// Creates a duplicate of this bit set, using the new allocator. - pub fn clone(&self) -> Result { - let mut copy = Self::default(); - copy.resize(self.bit_length, false)?; - copy.masks_slice_mut().copy_from_slice(self.masks_slice()); - Ok(copy) + self.resize(0, false); } /// Returns the number of bits in this bit set @@ -852,24 +852,26 @@ pub struct DynamicBitSetList { } impl DynamicBitSetList { - pub fn init_empty(n: usize, bit_length: usize) -> Result { + pub fn init_empty(n: usize, bit_length: usize) -> Self { let masks = DynamicBitSetUnmanaged::num_masks(bit_length); let single_bitset_buf_size = masks + 1; let buf_len = single_bitset_buf_size * n; if buf_len == 0 { - return Ok(Self { + return Self { buf: ptr::NonNull::dangling(), buf_len: 0, n, bit_length, - }); + }; } - let layout = core::alloc::Layout::array::(buf_len).map_err(|_| AllocError)?; + let layout = core::alloc::Layout::array::(buf_len).expect("capacity overflow"); // SAFETY: `buf_len > 0` so layout has nonzero size. let raw = unsafe { std::alloc::alloc_zeroed(layout) }; - let buf = ptr::NonNull::new(raw).ok_or(AllocError)?.cast::(); + let buf = ptr::NonNull::new(raw) + .unwrap_or_else(|| std::alloc::handle_alloc_error(layout)) + .cast::(); for i in 0..n { // SAFETY: `i * single_bitset_buf_size < buf_len`; allocation is @@ -877,12 +879,12 @@ impl DynamicBitSetList { unsafe { *buf.as_ptr().add(i * single_bitset_buf_size) = single_bitset_buf_size }; } - Ok(Self { + Self { buf, buf_len, n, bit_length, - }) + } } /// Borrow the `i`th bitset as a non-owning `DynamicBitSetUnmanaged` view. @@ -954,18 +956,21 @@ unsafe fn dyn_free(base: *mut usize, len: usize) { unsafe { std::alloc::dealloc(base.cast(), layout) }; } +/// On failure returns the `Layout` that could not be allocated; `resize` hands +/// it to `handle_alloc_error` when growing and keeps the old buffer when +/// shrinking. unsafe fn dyn_realloc( base: *mut usize, old_len: usize, new_len: usize, -) -> Result<*mut usize, AllocError> { - let new_layout = core::alloc::Layout::array::(new_len).map_err(|_| AllocError)?; +) -> Result<*mut usize, core::alloc::Layout> { + let new_layout = core::alloc::Layout::array::(new_len).expect("capacity overflow"); if old_len == 0 { // SAFETY: new_layout is nonzero size (caller never passes new_len==0 // through this path). let p = unsafe { std::alloc::alloc(new_layout) }; if p.is_null() { - return Err(AllocError); + return Err(new_layout); } return Ok(p.cast()); } @@ -973,7 +978,7 @@ unsafe fn dyn_realloc( // SAFETY: caller guarantees `base` was allocated with `old_layout`. let p = unsafe { std::alloc::realloc(base.cast(), old_layout, new_layout.size()) }; if p.is_null() { - return Err(AllocError); + return Err(new_layout); } Ok(p.cast()) } @@ -994,7 +999,7 @@ pub enum AutoBitSet { // ─── two-arm forward helper ──────────────────────────────────────────── // This macro forwards a call to whichever arm is active and is applied to // every method whose Static/Dynamic arms are textually identical. -// Asymmetric arms (clone, raw_bytes, has_intersection, Drop) +// Asymmetric arms (Clone, raw_bytes, has_intersection, Drop) // stay open-coded — they genuinely differ. macro_rules! auto_forward { ($self:expr, |$b:ident| $body:expr) => { @@ -1011,13 +1016,11 @@ impl AutoBitSet { bit_length > AutoBitSetStatic::BIT_LENGTH } - pub fn init_empty(bit_length: usize) -> Result { + pub fn init_empty(bit_length: usize) -> AutoBitSet { if bit_length <= AutoBitSetStatic::BIT_LENGTH { - Ok(AutoBitSet::Static(AutoBitSetStatic::init_empty())) + AutoBitSet::Static(AutoBitSetStatic::init_empty()) } else { - Ok(AutoBitSet::Dynamic(DynamicBitSetUnmanaged::init_empty( - bit_length, - )?)) + AutoBitSet::Dynamic(DynamicBitSetUnmanaged::init_empty(bit_length)) } } @@ -1034,13 +1037,6 @@ impl AutoBitSet { } } - pub fn clone(&self) -> Result { - match self { - AutoBitSet::Static(s) => Ok(AutoBitSet::Static(*s)), - AutoBitSet::Dynamic(d) => Ok(AutoBitSet::Dynamic(d.clone()?)), - } - } - pub fn set(&mut self, index: usize) { auto_forward!(self, |b| b.set(index)) } @@ -1102,12 +1098,21 @@ impl Drop for AutoBitSet { } } +impl Clone for AutoBitSet { + fn clone(&self) -> Self { + match self { + AutoBitSet::Static(s) => AutoBitSet::Static(*s), + AutoBitSet::Dynamic(d) => AutoBitSet::Dynamic(d.clone()), + } + } +} + // ───────────────────────────── DynamicBitSet ───────────────────────────── /// A bit set with runtime-known size, backed by an allocated slice /// of usize. Thin wrapper around DynamicBitSetUnmanaged which keeps /// track of the allocator instance. -#[derive(Default)] +#[derive(Default, Clone)] pub struct DynamicBitSet { /// The number of valid items in this bit set pub unmanaged: DynamicBitSetUnmanaged, @@ -1121,23 +1126,16 @@ impl DynamicBitSet { // type ShiftInt = u32 (inherent assoc → inline u32) /// Creates a bit set with no elements present. - pub fn init_empty(bit_length: usize) -> Result { - Ok(Self { - unmanaged: DynamicBitSetUnmanaged::init_empty(bit_length)?, - }) + pub fn init_empty(bit_length: usize) -> Self { + Self { + unmanaged: DynamicBitSetUnmanaged::init_empty(bit_length), + } } /// Resizes to a new length. If the new length is larger /// than the old length, fills any added bits with `fill`. - pub fn resize(&mut self, new_len: usize, fill: bool) -> Result<(), AllocError> { - self.unmanaged.resize(new_len, fill) - } - - /// Creates a duplicate of this bit set, using the new allocator. - pub fn clone(&self) -> Result { - Ok(Self { - unmanaged: self.unmanaged.clone()?, - }) + pub fn resize(&mut self, new_len: usize, fill: bool) { + self.unmanaged.resize(new_len, fill); } /// Returns the number of bits in this bit set diff --git a/src/collections/lib.rs b/src/collections/lib.rs index 82774f7bccf6..94b65ca9be35 100644 --- a/src/collections/lib.rs +++ b/src/collections/lib.rs @@ -82,7 +82,7 @@ impl PriorityQueue { } impl> PriorityQueue { /// Push and sift-up. - pub fn add(&mut self, elem: T) -> Result<(), bun_alloc::AllocError> { + pub fn add(&mut self, elem: T) { self.items.push(elem); let mut child = self.items.len() - 1; while child > 0 { @@ -98,7 +98,6 @@ impl> PriorityQueue { break; } } - Ok(()) } /// Pop min, sift-down; `None` when empty. pub fn remove_or_null(&mut self) -> Option { diff --git a/src/collections/multi_array_list.rs b/src/collections/multi_array_list.rs index 4476c01129eb..d6f002f4f3c1 100644 --- a/src/collections/multi_array_list.rs +++ b/src/collections/multi_array_list.rs @@ -53,8 +53,6 @@ use core::mem::{ManuallyDrop, MaybeUninit}; use core::ptr::{self, NonNull}; use std::alloc::{Allocator, Global}; -use bun_alloc::AllocError; - /// Declares typed column-accessor extension traits for a `MultiArrayList<$T>` /// element struct. /// @@ -948,16 +946,15 @@ impl MultiArrayList { } /// Extend the list by 1 element. Allocates more memory as necessary. - pub(crate) fn push(&mut self, elem: T) -> Result<(), AllocError> { - self.ensure_unused_capacity(1)?; + pub(crate) fn push(&mut self, elem: T) { + self.ensure_unused_capacity(1); self.append_assume_capacity(elem); - Ok(()) } /// Alias for [`push`]. #[inline] - pub fn append(&mut self, elem: T) -> Result<(), AllocError> { - self.push(elem) + pub fn append(&mut self, elem: T) { + self.push(elem); } /// Extend the list by 1 element, asserting `self.capacity` is sufficient @@ -1073,23 +1070,24 @@ impl MultiArrayList { } /// Modify the array so that it can hold at least `new_capacity` items. - pub fn ensure_total_capacity(&mut self, new_capacity: usize) -> Result<(), AllocError> { + pub fn ensure_total_capacity(&mut self, new_capacity: usize) { if self.capacity >= new_capacity { - return Ok(()); + return; } - self.set_capacity(grow_capacity::(self.capacity, new_capacity)) + self.set_capacity(grow_capacity::(self.capacity, new_capacity)); } /// Modify the array so that it can hold at least `additional_count` **more** items. - pub fn ensure_unused_capacity(&mut self, additional_count: usize) -> Result<(), AllocError> { - self.ensure_total_capacity(self.len + additional_count) + pub fn ensure_unused_capacity(&mut self, additional_count: usize) { + self.ensure_total_capacity(self.len + additional_count); } /// Modify the array so that it can hold exactly `new_capacity` items. /// `new_capacity` must be greater or equal to `len`. - pub fn set_capacity(&mut self, new_capacity: usize) -> Result<(), AllocError> { + pub fn set_capacity(&mut self, new_capacity: usize) { debug_assert!(new_capacity >= self.len); - let new_bytes = aligned_alloc::(&self.alloc, layout_for::(new_capacity))?; + let new_bytes = aligned_alloc::(&self.alloc, layout_for::(new_capacity)) + .unwrap_or_else(|layout| std::alloc::handle_alloc_error(layout)); if self.len != 0 { let mut dst = Slice::::from_raw(new_bytes, self.len, new_capacity); dst.copy_rows_from(0, &self.slice(), self.len); @@ -1097,20 +1095,21 @@ impl MultiArrayList { self.free_allocated_bytes(); self.bytes = new_bytes; self.capacity = new_capacity; - Ok(()) } - /// Create a copy of this list with a new backing store. - pub fn clone(&self) -> Result + /// Create a copy of this list with a new backing store. This is a bitwise + /// copy of the columns, not `Clone::clone` (see the `Drop` impl), which is + /// why it is an inherent method. + pub fn clone(&self) -> Self where A: Clone, { let mut result = Self::new_in(self.alloc.clone()); - result.ensure_total_capacity(self.len)?; + result.ensure_total_capacity(self.len); result.len = self.len; let mut dst = result.slice(); dst.copy_rows_from(0, &self.slice(), self.len); - Ok(result) + result } fn sort_internal(&mut self, a: usize, b: usize, ctx: &C) { @@ -1238,17 +1237,20 @@ fn layout_for(capacity: usize) -> Option { Some(Layout::from_size_align(n, Reflected::::ALIGN).expect("MultiArrayList layout overflow")) } +/// On failure returns the `Layout` that could not be allocated: `set_capacity` +/// hands it to `handle_alloc_error` (the same path `Vec` takes, which the crash +/// handler reports as out-of-memory), `shrink_and_free` keeps the old buffer. fn aligned_alloc( alloc: &A, layout: Option, -) -> Result, AllocError> { +) -> Result, Layout> { let Some(layout) = layout else { return Ok(Reflected::::DANGLING); }; alloc .allocate(layout) .map(|p| p.cast::()) - .map_err(|_| AllocError) + .map_err(|_| layout) } // Index-based context sorts — port of `mem.sortContext` / `mem.sortUnstableContext`. @@ -1358,8 +1360,7 @@ mod tests { a: i, b: i as u8, c: i as u64 * 100, - }) - .unwrap(); + }); } let s = list.slice(); assert_eq!(s.items::<"c", u64>()[7], 700); @@ -1375,8 +1376,7 @@ mod tests { a: i, b: i as u8, c: i as u64 * 10, - }) - .unwrap(); + }); } assert_eq!(list.items::<"c", u64>(), &[0u64, 10, 20, 30]); list.items_mut::<"a", u32>()[2] = 99; @@ -1397,7 +1397,7 @@ mod tests { #[test] fn generic_lifetime() { let mut list = MultiArrayList::>::default(); - list.push(Borrowed { name: b"hi", n: 7 }).unwrap(); + list.push(Borrowed { name: b"hi", n: 7 }); assert_eq!(list.items::<"name", &[u8]>()[0], b"hi"); assert_eq!(list.items::<"n", u32>()[0], 7); } @@ -1418,8 +1418,7 @@ mod tests { a: i, b: i as u8, c: i as u64, - }) - .unwrap(); + }); } assert_eq!(list.items::<"a", u32>(), &[0, 1, 2, 3, 4, 5]); list.ordered_remove(2); @@ -1436,8 +1435,7 @@ mod tests { a: i, b: i as u8, c: i as u64 * 10, - }) - .unwrap(); + }); } let raw = list.items_raw::<"a", u32>(); let len = list.len(); diff --git a/src/collections/string_map.rs b/src/collections/string_map.rs index 64ec506190ba..1fd35e51506b 100644 --- a/src/collections/string_map.rs +++ b/src/collections/string_map.rs @@ -1,8 +1,6 @@ //! A `StringArrayHashMap>` plus a `dupe_keys` flag controlling //! whether `insert` clones the key bytes. Values are always cloned. -use bun_alloc::AllocError; - use crate::array_hash_map::StringArrayHashMap; pub struct StringMap { @@ -41,19 +39,18 @@ impl StringMap { /// Dupe `value`; `key` is duped on miss regardless (`Box<[u8]>` forces a /// copy), so the `dupe_keys` flag is kept for API parity only. - pub fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), AllocError> { - let entry = self.map.get_or_put(key)?; + pub fn insert(&mut self, key: &[u8], value: &[u8]) { + let entry = self.map.get_or_put(key); // get_or_put already boxed `key` on miss; duping again here would be // the same allocation, so skip it. let _ = self.dupe_keys; *entry.value_ptr = Box::from(value); - Ok(()) } /// Alias for [`insert`](Self::insert). #[inline] - pub fn put(&mut self, key: &[u8], value: &[u8]) -> Result<(), AllocError> { - self.insert(key, value) + pub fn put(&mut self, key: &[u8], value: &[u8]) { + self.insert(key, value); } // `deinit` → Drop on the inner Vecs. diff --git a/src/collections/vec_ext.rs b/src/collections/vec_ext.rs index 33c729a132b8..c75e557f3c21 100644 --- a/src/collections/vec_ext.rs +++ b/src/collections/vec_ext.rs @@ -497,10 +497,15 @@ impl VecExt for Vec { /// `Vec`-only helpers. pub trait ByteVecExt { - fn append_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), AllocError>; - fn write(&mut self, str: &[u8]) -> Result; - fn write_latin1(&mut self, str: &[u8]) -> Result; - fn write_utf16(&mut self, str: &[u16]) -> Result; + fn append_fmt(&mut self, args: fmt::Arguments<'_>); + /// Appends `str`; returns the number of bytes appended. + fn write(&mut self, str: &[u8]) -> u32; + /// Appends `str` transcoded from Latin-1 to UTF-8; returns the number of + /// bytes appended. + fn write_latin1(&mut self, str: &[u8]) -> u32; + /// Appends `str` transcoded from UTF-16 to UTF-8; returns the number of + /// bytes appended. + fn write_utf16(&mut self, str: &[u16]) -> u32; /// libuv `uv_alloc_cb`-style: ensure **at least** `suggested` bytes of /// spare capacity past `len()`, typed `&mut [u8]` so the result can be @@ -522,23 +527,24 @@ pub trait ByteVecExt { } impl ByteVecExt for Vec { - fn append_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), AllocError> { - use std::io::Write; - write!(self, "{}", args).map_err(|_| AllocError) + fn append_fmt(&mut self, args: fmt::Arguments<'_>) { + // Writing into a `Vec` cannot fail, so like `format!` the only + // possible error is a `Display` impl returning `Err`. + std::io::Write::write_fmt(self, args) + .expect("a Display implementation returned an error unexpectedly"); } - fn write(&mut self, str: &[u8]) -> Result { - let initial = self.len(); + fn write(&mut self, str: &[u8]) -> u32 { self.extend_from_slice(str); - Ok((self.len() - initial) as u32) + str.len() as u32 } - fn write_latin1(&mut self, str: &[u8]) -> Result { + fn write_latin1(&mut self, str: &[u8]) -> u32 { let initial = self.len(); let old = core::mem::take(self); let old_len = old.len(); *self = strings::allocate_latin1_into_utf8_with_list(old, old_len, str); - Ok((self.len() - initial) as u32) + (self.len() - initial) as u32 } - fn write_utf16(&mut self, str: &[u16]) -> Result { + fn write_utf16(&mut self, str: &[u16]) -> u32 { let initial = self.len(); let estimate = if (self.capacity() - self.len()) <= (str.len() * 3 + 2) { bun_simdutf_sys::simdutf::length::utf8::from::utf16::le(str) @@ -547,7 +553,7 @@ impl ByteVecExt for Vec { }; self.reserve(estimate); strings::convert_utf16_to_utf8_append(self, str); - Ok((self.len() - initial) as u32) + (self.len() - initial) as u32 } #[inline] unsafe fn uv_alloc_spare_u8(&mut self, suggested: usize) -> &mut [u8] { @@ -578,9 +584,8 @@ pub struct OffsetByteList { } impl OffsetByteList { - pub fn write(&mut self, bytes: &[u8]) -> Result<(), AllocError> { + pub fn write(&mut self, bytes: &[u8]) { self.byte_list.extend_from_slice(bytes); - Ok(()) } pub fn remaining(&self) -> &[u8] { diff --git a/src/collections/zig_hash_map.rs b/src/collections/zig_hash_map.rs index f1e5fcc0cc7c..daee505165eb 100644 --- a/src/collections/zig_hash_map.rs +++ b/src/collections/zig_hash_map.rs @@ -201,33 +201,28 @@ impl> HashMap { pub fn with_capacity(capacity: usize) -> Self { let mut m = Self::default(); if capacity > 0 { - let _ = m.ensure_total_capacity(capacity); + m.ensure_total_capacity(capacity); } m } - /// Grow so `new_size` elements fit without further allocation. `Result` - /// kept for call-site `?` symmetry. - pub fn ensure_total_capacity(&mut self, new_size: usize) -> Result<(), bun_alloc::AllocError> { + /// Grow so `new_size` elements fit without further allocation. + pub fn ensure_total_capacity(&mut self, new_size: usize) { let new_size = new_size as u32; if new_size > self.size { self.grow_if_needed(new_size - self.size); } - Ok(()) } - pub fn ensure_unused_capacity( - &mut self, - additional: usize, - ) -> Result<(), bun_alloc::AllocError> { - self.ensure_total_capacity(self.size as usize + additional) + pub fn ensure_unused_capacity(&mut self, additional: usize) { + self.ensure_total_capacity(self.size as usize + additional); } /// std `reserve` — alias of [`ensure_unused_capacity`] for callers ported /// from the old `std::collections::HashMap` Deref. #[inline] pub fn reserve(&mut self, additional: usize) { - let _ = self.ensure_unused_capacity(additional); + self.ensure_unused_capacity(additional); } fn load(&self) -> u32 { @@ -415,10 +410,7 @@ impl> HashMap { /// Single-probe insert-or-lookup. Uninit values cannot be exposed through /// a `&mut V`, so `V: Default` and on miss the slot is default-initialised /// — callers overwrite `*value_ptr` when `!found_existing`. - pub fn get_or_put( - &mut self, - key: K, - ) -> Result, bun_alloc::AllocError> + pub fn get_or_put(&mut self, key: K) -> crate::hash_map::GetOrPutResult<'_, V> where V: Default, { @@ -427,10 +419,10 @@ impl> HashMap { self.slots[idx] = Some((key, V::default())); } let value_ptr = &mut self.slots[idx].as_mut().unwrap().1; - Ok(crate::hash_map::GetOrPutResult { + crate::hash_map::GetOrPutResult { found_existing, value_ptr, - }) + } } /// Alias of [`get_or_put`](Self::get_or_put) kept for call-site parity; @@ -440,7 +432,7 @@ impl> HashMap { &mut self, key: K, _ctx: Ctx, - ) -> Result, bun_alloc::AllocError> + ) -> crate::hash_map::GetOrPutResult<'_, V> where V: Default, { @@ -461,16 +453,14 @@ impl> HashMap { /// Insert or overwrite. #[inline] - pub fn put(&mut self, key: K, value: V) -> Result<(), bun_alloc::AllocError> { + pub fn put(&mut self, key: K, value: V) { self.insert(key, value); - Ok(()) } /// Insert asserting the key is new. - pub fn put_no_clobber(&mut self, key: K, value: V) -> Result<(), bun_alloc::AllocError> { + pub fn put_no_clobber(&mut self, key: K, value: V) { let prev = self.insert(key, value); debug_assert!(prev.is_none(), "putNoClobber: key already present"); - Ok(()) } fn remove_by_index(&mut self, idx: usize) -> Option<(K, V)> { diff --git a/src/crash_handler/lib.rs b/src/crash_handler/lib.rs index a5cb8c8966ea..51c8d8684769 100644 --- a/src/crash_handler/lib.rs +++ b/src/crash_handler/lib.rs @@ -20,6 +20,7 @@ // builds only. Declaring the feature where neither is compiled (Windows // release) trips `unused_features`. #![cfg_attr(any(not(windows), debug_assertions), feature(core_intrinsics))] +#![feature(alloc_error_hook)] #![allow(internal_features)] #![allow(nonstandard_style, static_mut_refs, unexpected_cfgs)] #![warn(unused_must_use)] @@ -1731,6 +1732,16 @@ mod draft { // this hook, a bare `panic!` would print the std // default hook + unwind with no trace string and no upload. std::panic::set_hook(Box::new(rust_panic_hook)); + // A failed infallible allocation (`Vec::push`, `Box::new`, hashbrown + // growth, anything reaching `handle_alloc_error`) is an out-of-memory + // condition, not a bug. Without this hook std prints "memory allocation + // of N bytes failed" and calls `abort()`, which the SIGABRT handler + // above then reports as an ordinary crash. + std::alloc::set_alloc_error_hook(rust_alloc_error_hook); + } + + fn rust_alloc_error_hook(_layout: core::alloc::Layout) { + super::out_of_memory() } /// `std::panic` hook: emit the same trace-string + auto-report as the fatal diff --git a/src/dotenv/env_loader.rs b/src/dotenv/env_loader.rs index 57b4464602a8..e23dfcff6906 100644 --- a/src/dotenv/env_loader.rs +++ b/src/dotenv/env_loader.rs @@ -3,7 +3,6 @@ use core::ffi::c_char; use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; -use bun_alloc::AllocError; use bun_collections::{ArrayHashMapExt, GetOrPutResult, StringSet}; use bun_core::{self, Output}; use bun_core::{ZStr, strings}; @@ -450,16 +449,12 @@ impl Loader { return; } DID_LOAD_CCACHE_PATH.store(true, Ordering::Relaxed); - let _ = self.load_ccache_path_impl(fs); - } - fn load_ccache_path_impl(&mut self, fs: &bun_paths::fs::FileSystem) -> Result<(), AllocError> { // if they have ccache installed, put it in env variable `CMAKE_CXX_COMPILER_LAUNCHER` so // cmake can use it to hopefully speed things up let mut buf = PathBuffer::uninit(); - let path = match self.get(b"PATH") { - Some(p) => p, - None => return Ok(()), + let Some(path) = self.get(b"PATH") else { + return; }; // borrowck — `path` borrows `self.map`; `which` writes into `buf` and // returns a borrow of `buf`. Copy the result before mutating `self.map`. @@ -470,7 +465,7 @@ impl Loader { if !ccache_path.is_empty() { let cxx_gop = self .map - .get_or_put_without_value(b"CMAKE_CXX_COMPILER_LAUNCHER")?; + .get_or_put_without_value(b"CMAKE_CXX_COMPILER_LAUNCHER"); if !cxx_gop.found_existing { *cxx_gop.key_ptr = Box::<[u8]>::from(&**cxx_gop.key_ptr); *cxx_gop.value_ptr = HashTableValue { @@ -479,13 +474,12 @@ impl Loader { } let c_gop = self .map - .get_or_put_without_value(b"CMAKE_C_COMPILER_LAUNCHER")?; + .get_or_put_without_value(b"CMAKE_C_COMPILER_LAUNCHER"); if !c_gop.found_existing { *c_gop.key_ptr = Box::<[u8]>::from(&**c_gop.key_ptr); *c_gop.value_ptr = HashTableValue { value: ccache_path }; } } - Ok(()) } /// Populates `NODE` / @@ -495,7 +489,7 @@ impl Loader { &mut self, fs: &bun_paths::fs::FileSystem, override_node: &[u8], - ) -> crate::Result { + ) -> bool { let mut buf = PathBuffer::uninit(); let node_path_to_use: Box<[u8]> = if !override_node.is_empty() { @@ -510,7 +504,7 @@ impl Loader { c } else { let Some(node) = self.get_node_path(fs, &mut buf) else { - return Ok(false); + return false; }; Box::from(node.as_bytes()) } @@ -518,9 +512,9 @@ impl Loader { // Cache to `NODE_PATH_TO_USE_SET_ONCE` first, then `map.put` (which // dupes the bytes). *NODE_PATH_TO_USE_SET_ONCE.write() = Some(node_path_to_use.clone()); - self.map.put(b"NODE", &node_path_to_use)?; - self.map.put(b"npm_node_execpath", &node_path_to_use)?; - Ok(true) + self.map.put(b"NODE", &node_path_to_use); + self.map.put(b"npm_node_execpath", &node_path_to_use); + true } pub(crate) fn get_as_bool(&self, key: &[u8]) -> Option { @@ -595,13 +589,13 @@ impl Loader { } } - pub fn load_process(&mut self) -> Result<(), AllocError> { + pub fn load_process(&mut self) { if self.did_load_process { - return Ok(()); + return; } let environ: &[*const c_char] = bun_sys::environ(); - self.map.map.ensure_total_capacity(environ.len())?; + self.map.map.ensure_total_capacity(environ.len()); for &_env in environ { // SAFETY: environ entries are NUL-terminated C strings from the OS let env = unsafe { bun_core::ffi::cstr(_env) }.to_bytes(); @@ -609,25 +603,21 @@ impl Loader { let key = &env[..i as usize]; let value = &env[i as usize + 1..]; if !key.is_empty() { - self.map.put(key, value)?; + self.map.put(key, value); } } else { if !env.is_empty() { - self.map.put(env, b"")?; + self.map.put(env, b""); } } } self.did_load_process = true; - Ok(()) } // mostly for tests - pub fn load_from_string( - &mut self, - str: &[u8], - ) -> Result<(), AllocError> { + pub fn load_from_string(&mut self, str: &[u8]) { let mut value_buffer: Vec = Vec::new(); - Parser::parse_bytes::(str, &mut self.map, &mut value_buffer) + Parser::parse_bytes::(str, &mut self.map, &mut value_buffer); } pub fn load( @@ -838,7 +828,7 @@ impl Loader { } } ReadEnvFile::Bytes(buf) => { - Parser::parse_bytes::(&buf, &mut self.map, value_buffer)?; + Parser::parse_bytes::(&buf, &mut self.map, value_buffer); } } @@ -859,7 +849,7 @@ impl Loader { Ok(f) => f, Err(_) => { // prevent retrying - self.custom_files_loaded.insert(file_path)?; + self.custom_files_loaded.insert(file_path); return Ok(()); } }; @@ -876,11 +866,11 @@ impl Loader { } } ReadEnvFile::Bytes(buf) => { - Parser::parse_bytes::(&buf, &mut self.map, value_buffer)?; + Parser::parse_bytes::(&buf, &mut self.map, value_buffer); } } - self.custom_files_loaded.insert(file_path)?; + self.custom_files_loaded.insert(file_path); Ok(()) } } @@ -992,7 +982,7 @@ impl<'a> Parser<'a> { None } - fn parse_quoted(&mut self) -> Result, AllocError> { + fn parse_quoted(&mut self) -> Option<&[u8]> { debug_assert!(self.src[self.pos] == QUOTE); let start = self.pos; self.value_buffer.clear(); // Reset the buffer @@ -1044,38 +1034,38 @@ impl<'a> Parser<'a> { } } } - return Ok(Some(self.value_buffer.as_slice())); + return Some(self.value_buffer.as_slice()); } _ => {} } end += 1; } - Ok(None) + None } - fn parse_value(&mut self) -> Result<&[u8], AllocError> { + fn parse_value(&mut self) -> &[u8] { let start = self.pos; self.skip_whitespaces(); let mut end = self.pos; if end >= self.src.len() { - return Ok(&self.src[self.src.len()..]); + return &self.src[self.src.len()..]; } // reshaped for borrowck — `parse_quoted` returns a borrow of // `self.value_buffer`; capture only its length, then re-borrow the buffer // after the match so the unquoted fallthrough can re-borrow `self`. let quoted_len: Option = match self.src[end] { - b'`' => self.parse_quoted::()?.map(|v| v.len()), - b'"' => self.parse_quoted::()?.map(|v| v.len()), - b'\'' => self.parse_quoted::()?.map(|v| v.len()), + b'`' => self.parse_quoted::().map(|v| v.len()), + b'"' => self.parse_quoted::().map(|v| v.len()), + b'\'' => self.parse_quoted::().map(|v| v.len()), _ => None, }; if let Some(len) = quoted_len { let value = &self.value_buffer[..len]; - return Ok(if IS_PROCESS { + return if IS_PROCESS { value } else { &value[1..value.len() - 1] - }); + }; } end = start; while end < self.src.len() { @@ -1086,18 +1076,18 @@ impl<'a> Parser<'a> { end += 1; } self.pos = end; - Ok(strings::trim(&self.src[start..end], WHITESPACE_CHARS)) + strings::trim(&self.src[start..end], WHITESPACE_CHARS) } - fn expand_value(&mut self, map: &Map, value: &[u8]) -> Result, AllocError> { + fn expand_value(&mut self, map: &Map, value: &[u8]) -> Option<&[u8]> { if value.len() < 2 { - return Ok(None); + return None; } self.value_buffer.clear(); if !Self::expand_into(map, value, self.value_buffer, 0) { - return Ok(None); + return None; } - Ok(Some(self.value_buffer.as_slice())) + Some(self.value_buffer.as_slice()) } /// Left-to-right expansion of `$NAME` / `${NAME}` / `${NAME:-default}`. @@ -1205,17 +1195,17 @@ impl<'a> Parser<'a> { fn parse( &mut self, map: &mut Map, - ) -> Result<(), AllocError> { + ) { let mut count = map.map.count(); while self.pos < self.src.len() { let Some(key) = self.parse_key::() else { self.skip_line(); continue; }; - let value = self.parse_value::()?; + let value = self.parse_value::(); // reshaped for borrowck — value borrows self.value_buffer; copy before map mut. let value_owned: Box<[u8]> = Box::from(value); - let entry = map.map.get_or_put(key)?; + let entry = map.map.get_or_put(key); if entry.found_existing { if entry.index < count { // Allow keys defined later in the same file to override keys defined earlier @@ -1237,7 +1227,7 @@ impl<'a> Parser<'a> { let mut idx = count; while idx < total { let current: Box<[u8]> = Box::from(&*map.map.values()[idx].value); - if let Some(expanded) = self.expand_value(map, ¤t)? { + if let Some(expanded) = self.expand_value(map, ¤t) { map.map.values_mut()[idx] = HashTableValue { value: Box::from(expanded), }; @@ -1247,7 +1237,6 @@ impl<'a> Parser<'a> { count = 0; } let _ = count; - Ok(()) } /// Builds a [`Parser`] over `src` (minus any UTF-8 BOM) and runs [`Parser::parse`] into `map`. @@ -1255,7 +1244,7 @@ impl<'a> Parser<'a> { src: &[u8], map: &mut Map, value_buffer: &mut Vec, - ) -> Result<(), AllocError> { + ) { // Clear the buffer before each parse to ensure no leftover data value_buffer.clear(); let mut parser = Parser { @@ -1265,7 +1254,7 @@ impl<'a> Parser<'a> { src: strings::without_utf8_bom(src), value_buffer, }; - parser.parse::(map) + parser.parse::(map); } } @@ -1285,6 +1274,7 @@ pub type HashTable = bun_collections::StringArrayHashMap; #[cfg(windows)] pub type HashTable = bun_collections::CaseInsensitiveAsciiStringArrayHashMap; +#[derive(Clone)] pub struct Map { pub map: HashTable, } @@ -1298,7 +1288,7 @@ impl Default for Map { impl Map { /// Builds a NULL-terminated `K=V\0` envp array. Returns an owning struct so /// dropping it frees the joined buffers (PORTING.md §Forbidden: no Box::leak). - pub fn create_null_delimited_env_map(&mut self) -> Result { + pub fn create_null_delimited_env_map(&mut self) -> NullDelimitedEnvMap { let envp_count = self.map.count(); let mut storage: Vec> = Vec::with_capacity(envp_count); let mut envp_buf: Vec<*const c_char> = Vec::with_capacity(envp_count + 1); @@ -1318,10 +1308,10 @@ impl Map { debug_assert!(envp_buf.len() == envp_count); } envp_buf.push(core::ptr::null()); // sentinel - Ok(NullDelimitedEnvMap { + NullDelimitedEnvMap { _storage: storage, envp: envp_buf.into_boxed_slice(), - }) + } } /// Returns a wrapper around the env map that does not duplicate the memory of @@ -1329,7 +1319,7 @@ impl Map { // `bun_sys::EnvMap` is `HashMap`, which copies and is // UTF-8-lossy; the lossy round-trip is accepted here. #[allow(clippy::disallowed_methods)] // lossy round-trip documented above - pub fn std_env_map(&mut self) -> Result { + pub fn std_env_map(&mut self) -> StdEnvMapWrapper { let mut env_map = bun_sys::EnvMap::default(); let mut it = self.map.iterator(); while let Some(entry) = it.next() { @@ -1338,9 +1328,9 @@ impl Map { String::from_utf8_lossy(&entry.value_ptr.value).into_owned(), ); } - Ok(StdEnvMapWrapper { + StdEnvMapWrapper { unsafe_map: env_map, - }) + } } /// Build a heap-allocated Windows environment block suitable for @@ -1395,7 +1385,7 @@ impl Map { } #[inline] - pub fn put(&mut self, key: &[u8], value: &[u8]) -> Result<(), AllocError> { + pub fn put(&mut self, key: &[u8], value: &[u8]) { #[cfg(all(windows, debug_assertions))] { debug_assert!(strings::index_of_char(key, b'\x00').is_none()); @@ -1405,11 +1395,11 @@ impl Map { HashTableValue { value: Box::from(value), }, - ) + ); } - pub fn ensure_unused_capacity(&mut self, additional_count: usize) -> Result<(), AllocError> { - self.map.ensure_unused_capacity(additional_count) + pub fn ensure_unused_capacity(&mut self, additional_count: usize) { + self.map.ensure_unused_capacity(additional_count); } pub fn put_assume_capacity(&mut self, key: &[u8], value: &[u8]) { @@ -1426,30 +1416,29 @@ impl Map { } #[inline] - pub fn put_alloc_key_and_value(&mut self, key: &[u8], value: &[u8]) -> Result<(), AllocError> { - let gop = self.map.get_or_put(key)?; + pub fn put_alloc_key_and_value(&mut self, key: &[u8], value: &[u8]) { + let gop = self.map.get_or_put(key); *gop.value_ptr = HashTableValue { value: Box::from(value), }; if !gop.found_existing { *gop.key_ptr = Box::from(key); } - Ok(()) } #[inline] - pub fn put_alloc_value(&mut self, key: &[u8], value: &[u8]) -> Result<(), AllocError> { + pub fn put_alloc_value(&mut self, key: &[u8], value: &[u8]) { // `HashTableValue { value: Box<[u8]> }` storage forces a copy, so this is // equivalent to `put`. Kept as a thin wrapper to preserve call-site alloc intent // should storage ever change to `Cow`/borrowed. - self.put(key, value) + self.put(key, value); } #[inline] pub fn get_or_put_without_value( &mut self, key: &[u8], - ) -> Result, HashTableValue>, AllocError> { + ) -> GetOrPutResult<'_, Box<[u8]>, HashTableValue> { self.map.get_or_put(key) } @@ -1459,26 +1448,18 @@ impl Map { } #[inline] - pub fn put_default(&mut self, key: &[u8], value: &[u8]) -> Result<(), AllocError> { - let _ = self.map.get_or_put_value( + pub fn put_default(&mut self, key: &[u8], value: &[u8]) { + self.map.get_or_put_value( key, HashTableValue { value: Box::from(value), }, - )?; - Ok(()) + ); } pub fn remove(&mut self, key: &[u8]) { let _ = self.map.swap_remove(key); } - - pub fn clone_with_allocator(&self) -> Result { - // allocator param dropped — global mimalloc - Ok(Map { - map: self.map.clone()?, - }) - } } /// Owns the `K=V\0` strings backing a NULL-terminated envp array. diff --git a/src/dotenv/error.rs b/src/dotenv/error.rs index f9f9020050e5..6c38c923dc8c 100644 --- a/src/dotenv/error.rs +++ b/src/dotenv/error.rs @@ -2,8 +2,6 @@ pub enum Error { #[error(transparent)] Sys(#[from] bun_errno::SystemErrno), - #[error(transparent)] - Alloc(#[from] bun_alloc::AllocError), } impl From for Error { @@ -17,7 +15,6 @@ impl Error { pub fn name(&self) -> &'static str { match self { Self::Sys(e) => <&'static str>::from(e), - Self::Alloc(_) => "OutOfMemory", } } } diff --git a/src/glob/GlobWalker.rs b/src/glob/GlobWalker.rs index ef28a0d13532..1da3c5f41a62 100644 --- a/src/glob/GlobWalker.rs +++ b/src/glob/GlobWalker.rs @@ -1025,7 +1025,7 @@ impl<'a, A: Accessor, const SENTINEL: bool> Iterator<'a, A, SENTINEL> { bstr::BStr::new(entry.name_slice()) ); - let active = dir.active.clone().expect("OOM: ComponentSet::clone"); + let active = dir.active.clone(); let entry_name = entry.name_slice(); let dir_dir_path = dir.dir_path().as_bytes(); let dir_fd = dir.fd; @@ -1079,7 +1079,7 @@ impl<'a, A: Accessor, const SENTINEL: bool> Iterator<'a, A, SENTINEL> { { self.walker .eval_impl(&active, entry_name) - .then(|| active.clone().expect("OOM")) + .then(|| active.clone()) } else { let subset = self.walker.eval_literal_subset(&active, entry_name); (subset.count() != 0).then_some(subset) @@ -1169,7 +1169,7 @@ impl<'a, A: Accessor, const SENTINEL: bool> Iterator<'a, A, SENTINEL> { bun_sys::FileKind::SymLink => { let follow_active: Option = if self.walker.follow_symlinks { - Some(active.clone().expect("OOM")) + Some(active.clone()) } else { let subset = self .walker @@ -1791,7 +1791,6 @@ impl GlobWalker { /// Create an empty ComponentSet sized for this pattern. fn make_set(&self) -> ComponentSet { ComponentSet::init_empty(self.pattern_components.len()) - .expect("OOM: ComponentSet::init_empty") } fn single_set(&self, idx: u32) -> ComponentSet { diff --git a/src/http_types/ETag.rs b/src/http_types/ETag.rs index 0206898525c0..68fdd3c74684 100644 --- a/src/http_types/ETag.rs +++ b/src/http_types/ETag.rs @@ -224,13 +224,9 @@ pub struct Headers { } impl Clone for Headers { - // The only fallible calls are allocations — abort on OOM. fn clone(&self) -> Headers { Headers { - entries: self - .entries - .clone() - .unwrap_or_else(|_| bun_alloc::out_of_memory()), + entries: self.entries.clone(), buf: self.buf.clone(), } } @@ -253,7 +249,6 @@ impl Headers { None } - // The only fallible calls are allocations — abort on OOM. pub fn append(&mut self, name: &[u8], value: &[u8]) { let mut offset: u32 = u32::try_from(self.buf.len()).unwrap(); self.buf.reserve(name.len() + value.len()); @@ -269,12 +264,10 @@ impl Headers { offset, length: u32::try_from(value.len()).unwrap(), }; - self.entries - .append(HeaderEntry { - name: name_ptr, - value: value_ptr, - }) - .unwrap_or_else(|_| bun_alloc::out_of_memory()); + self.entries.append(HeaderEntry { + name: name_ptr, + value: value_ptr, + }); } pub fn get_content_disposition(&self) -> Option<&[u8]> { diff --git a/src/http_types/MimeType.rs b/src/http_types/MimeType.rs index 58deff475551..ac2865dc46ad 100644 --- a/src/http_types/MimeType.rs +++ b/src/http_types/MimeType.rs @@ -95,7 +95,7 @@ impl Compact { } #[cold] -pub fn create_hash_table() -> Result { +pub fn create_hash_table() -> Map { let mut map = Map::default(); map.reserve(Table::ALL.len() as u32 as usize); // `StringHashMap` boxes the key. @@ -106,10 +106,10 @@ pub fn create_hash_table() -> Result { bstr::BStr::new(entry.slice()), <&'static str>::from(*entry), ); - map.put(entry.slice(), *entry)?; + map.put(entry.slice(), *entry); } - Ok(map) + map } #[derive(Clone, Copy, PartialEq, Eq, Debug, strum::IntoStaticStr)] diff --git a/src/io/PipeWriter.rs b/src/io/PipeWriter.rs index 074c67937994..9902eb2a5d6d 100644 --- a/src/io/PipeWriter.rs +++ b/src/io/PipeWriter.rs @@ -1862,7 +1862,7 @@ impl StreamBuffer { // calling // `convert_utf16_to_utf8_append` directly (its old shortcut) handed // simdutf a `Vec::new()` dangling pointer (`0x1`) and segfaulted. - ByteVecExt::write_utf16(&mut self.list, buffer)?; + ByteVecExt::write_utf16(&mut self.list, buffer); Ok(()) } diff --git a/src/libarchive/lib.rs b/src/libarchive/lib.rs index 3965e9b415fb..0bde11fe9d50 100644 --- a/src/libarchive/lib.rs +++ b/src/libarchive/lib.rs @@ -1417,7 +1417,7 @@ impl Archiver { &temp_buf[..path_to_use_.len()] }; - let overwrite_entry = ctx.overwrite_list.get_or_put(path_to_use)?; + let overwrite_entry = ctx.overwrite_list.get_or_put(path_to_use); if !overwrite_entry.found_existing { *overwrite_entry.key_ptr = Box::from(appender.append(path_to_use)?); } @@ -1831,8 +1831,7 @@ impl Archiver { if A::HAS_APPEND_MUTABLE { let result = ctx_ .all_files - .get_or_put_adapted(&h, &archiver::U64Context) - .expect("unreachable"); + .get_or_put_adapted(&h, &archiver::U64Context); if !result.found_existing { *result.value_ptr = appender .append_mutable(path_slice)? diff --git a/src/md/helpers.rs b/src/md/helpers.rs index 83cf0e3f932d..46c33c30f6c0 100644 --- a/src/md/helpers.rs +++ b/src/md/helpers.rs @@ -458,9 +458,7 @@ pub(crate) fn generate_slug<'a>( // Deduplicate via slug_counts. `StringHashMap::get_or_put` probes // once (the map owns its keys, value starts at 0 on miss). - let Ok(gop) = slug_counts.get_or_put(&text_buf[..out_len]) else { - return &text_buf[..out_len]; - }; + let gop = slug_counts.get_or_put(&text_buf[..out_len]); if !gop.found_existing { // First occurrence — value initialised to 0 by `get_or_put`. return &text_buf[..out_len]; diff --git a/src/parsers/yaml.rs b/src/parsers/yaml.rs index 2ca5929dbbcd..600f4b55cf70 100644 --- a/src/parsers/yaml.rs +++ b/src/parsers/yaml.rs @@ -2318,7 +2318,7 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { self.try_skip_s_white()?; self.tag_handles - .put(Enc::key_bytes(handle.slice(self.input)), ())?; + .put(Enc::key_bytes(handle.slice(self.input)), ()); self.parse_directive_tag_prefix()?; self.try_skip_to_new_line()?; @@ -3132,10 +3132,7 @@ impl MappingProps { let idx = self.merge_indexed; let key = self.list[idx].key.as_ref().unwrap(); let hash = yaml_merge_key_expr_hash(key); - self.merge_index - .get_or_put(hash)? - .value_ptr - .push(idx as u32); + self.merge_index.get_or_put(hash).value_ptr.push(idx as u32); self.merge_indexed += 1; } @@ -3161,7 +3158,7 @@ impl MappingProps { ..Default::default() }); self.merge_index - .get_or_put(merge_hash)? + .get_or_put(merge_hash) .value_ptr .push((self.list.len() - 1) as u32); self.merge_indexed = self.list.len(); @@ -3312,9 +3309,9 @@ impl CollectionData for E::Object { impl<'i, Enc: Encoding> Parser<'i, Enc> { // By value so binding consumes the `#[must_use]` anchor token. #[allow(clippy::needless_pass_by_value)] - fn bind_anchor(&mut self, anchor: PendingAnchor, node: Expr) -> Result<(), AllocError> { + fn bind_anchor(&mut self, anchor: PendingAnchor, node: Expr) { self.anchors - .put(Enc::key_bytes(anchor.name.slice(self.input)), node) + .put(Enc::key_bytes(anchor.name.slice(self.input)), node); } /// Parses a collection node: it is allocated (empty) before `body` parses @@ -3347,7 +3344,7 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { debug_assert!(closed.is_some_and(|c| collection_id(&c.node) == collection_id(&node))); *slot = result?; - self.bind_anchor(anchor, node)?; + self.bind_anchor(anchor, node); Ok(node) } @@ -3773,7 +3770,7 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { }; let e_node = resolved_tag.resolve_null(loc); if let Some(anchor) = anchor { - self.bind_anchor(anchor, e_node)?; + self.bind_anchor(anchor, e_node); } Ok(e_node) } @@ -3811,7 +3808,7 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { if on_path.contains(&id) { continue; } - on_path.put(id, ())?; + on_path.put(id, ()); stack.push(Visit::Exit(id)); } match &node.data { @@ -4178,7 +4175,7 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { let anchors = node_props.take_implicit_key_anchors(colon_line)?; if let Some(key_anchor) = anchors.key_anchor { - self.bind_anchor(key_anchor, first_key)?; + self.bind_anchor(key_anchor, first_key); } let mapping = self.parse_block_mapping( @@ -4286,7 +4283,7 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { let anchors = node_props.take_implicit_key_anchors(scalar_line)?; if let Some(key_anchor) = anchors.key_anchor { - self.bind_anchor(key_anchor, implicit_key)?; + self.bind_anchor(key_anchor, implicit_key); } let mapping = self.parse_block_mapping( @@ -4335,7 +4332,7 @@ impl<'i, Enc: Encoding> Parser<'i, Enc> { }; if let Some(anchor) = has_anchor { - self.bind_anchor(anchor, resolved)?; + self.bind_anchor(anchor, resolved); } Ok(resolved) diff --git a/src/react_compiler/collections.rs b/src/react_compiler/collections.rs index 54a3a32fa318..b78acad2116d 100644 --- a/src/react_compiler/collections.rs +++ b/src/react_compiler/collections.rs @@ -135,7 +135,7 @@ impl Default for IndexMap { impl Clone for IndexMap { fn clone(&self) -> Self { - Self(self.0.clone().expect("OOM")) + Self(self.0.clone()) } } @@ -281,7 +281,7 @@ impl Default for IndexSet { impl Clone for IndexSet { fn clone(&self) -> Self { - Self(self.0.clone().expect("OOM")) + Self(self.0.clone()) } } diff --git a/src/s3_signing/credentials.rs b/src/s3_signing/credentials.rs index 3996162fe2b4..2538e07b26eb 100644 --- a/src/s3_signing/credentials.rs +++ b/src/s3_signing/credentials.rs @@ -128,7 +128,7 @@ impl AWSSignatureCache { inner.cache.clear(); } inner.date = numeric_day; - bun_core::handle_oom(inner.cache.put(key, value)); + inner.cache.put(key, value); } } diff --git a/src/semver/lib.rs b/src/semver/lib.rs index aadba242a72f..4c97fa16f7f9 100644 --- a/src/semver/lib.rs +++ b/src/semver/lib.rs @@ -590,7 +590,7 @@ pub mod semver_string { } let hash = Builder::string_hash(str); - let entry = self.pool.get_or_put(hash)?; + let entry = self.pool.get_or_put(hash); if entry.found_existing { return Ok(*entry.value_ptr); } @@ -606,7 +606,7 @@ pub mod semver_string { return Ok(String::init_inline(str)); } - let entry = self.pool.get_or_put(hash)?; + let entry = self.pool.get_or_put(hash); if entry.found_existing { return Ok(*entry.value_ptr); } @@ -627,7 +627,7 @@ pub mod semver_string { }); } - let entry = self.pool.get_or_put(hash)?; + let entry = self.pool.get_or_put(hash); if entry.found_existing { return Ok(ExternalString { value: *entry.value_ptr, @@ -652,7 +652,7 @@ pub mod semver_string { }); } - let entry = self.pool.get_or_put(hash)?; + let entry = self.pool.get_or_put(hash); if entry.found_existing { return Ok(ExternalString { value: *entry.value_ptr, @@ -848,12 +848,12 @@ pub mod semver_string { pub value_ptr: &'a mut String, } impl StringPool { - pub fn get_or_put(&mut self, hash: u64) -> Result, AllocError> { - let gpe = self.map.get_or_put(hash)?; - Ok(StringPoolEntry { + pub fn get_or_put(&mut self, hash: u64) -> StringPoolEntry<'_> { + let gpe = self.map.get_or_put(hash); + StringPoolEntry { found_existing: gpe.found_existing, value_ptr: gpe.value_ptr, - }) + } } #[inline] pub fn contains(&self, hash: u64) -> bool { @@ -867,8 +867,8 @@ pub mod semver_string { /// Pre-reserve so `n` entries /// fit without rehash. #[inline] - pub fn ensure_total_capacity(&mut self, n: usize) -> Result<(), AllocError> { - self.map.ensure_total_capacity(n) + pub fn ensure_total_capacity(&mut self, n: usize) { + self.map.ensure_total_capacity(n); } } @@ -1004,7 +1004,7 @@ pub mod semver_string { // &mut self.ptr; capture scalars first, then re-borrow. let start = self.len; let cap = self.cap; - let string_entry = self.string_pool.get_or_put(hash).expect("unreachable"); + let string_entry = self.string_pool.get_or_put(hash); if string_entry.found_existing { let allocated = &self.ptr.as_ref().unwrap()[0..cap]; if !strings::eql(string_entry.value_ptr.slice(allocated), slice_) { diff --git a/src/watcher/Watcher.rs b/src/watcher/Watcher.rs index 796f0b07b17b..e93b1fb87822 100644 --- a/src/watcher/Watcher.rs +++ b/src/watcher/Watcher.rs @@ -712,13 +712,8 @@ impl Watcher { } } } - // Abort on OOM: - // `MultiArrayList::ensure_unused_capacity` returns `Err(AllocError)` on - // allocation failure (does NOT abort), so discarding it would let the - // following `append_assume_capacity` write past capacity. self.watchlist - .ensure_unused_capacity(1 + usize::from(parent_watch_item.is_none())) - .unwrap_or_else(|_| bun_core::out_of_memory()); + .ensure_unused_capacity(1 + usize::from(parent_watch_item.is_none())); if autowatch_parent_dir { parent_watch_item = Some(match parent_watch_item { @@ -796,9 +791,7 @@ impl Watcher { if let Some(idx) = self.index_of(hash) { return Ok(idx as WatchItemIndex); } - self.watchlist - .ensure_unused_capacity(1) - .unwrap_or_else(|_| bun_core::out_of_memory()); + self.watchlist.ensure_unused_capacity(1); self.append_directory_assume_capacity::(fd, file_path, hash) } From 9be346a96bf617a700796d21ab03c41b264f55c0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 05:35:57 +0000 Subject: [PATCH 2/7] crash handler: test that a failed std allocation is reported as out of memory Adds a crash_handler.allocError() test hook that calls handle_alloc_error, the path every infallible std allocation takes when the allocator returns null. Without the alloc error hook std prints "memory allocation of N bytes failed" and aborts, which is reported as an ordinary crash (or, on ASAN builds, not reported at all). --- src/js/internal-for-testing.ts | 1 + src/runtime/api/crash_handler_jsc.rs | 10 ++++++++++ test/cli/run/fixture-crash.js | 2 +- test/cli/run/run-crash-handler.test.ts | 15 +++++++++++---- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index 9b1fed3e91d9..90e2dc50241f 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -122,6 +122,7 @@ export const crash_handler = $rust("crash_handler.rs", "js_bindings.generate") a panic: () => void; rootError: () => void; outOfMemory: () => void; + allocError: () => void; abort: () => void; fastfail: () => void; trap: () => void; diff --git a/src/runtime/api/crash_handler_jsc.rs b/src/runtime/api/crash_handler_jsc.rs index d573f171b4af..9033eddec2b1 100644 --- a/src/runtime/api/crash_handler_jsc.rs +++ b/src/runtime/api/crash_handler_jsc.rs @@ -26,6 +26,7 @@ pub(crate) mod js_bindings { ("panic", __jsc_host_js_panic), ("rootError", __jsc_host_js_root_error), ("outOfMemory", __jsc_host_js_out_of_memory), + ("allocError", __jsc_host_js_alloc_error), ("abort", __jsc_host_js_abort), ("fastfail", __jsc_host_js_fastfail), ("trap", __jsc_host_js_trap), @@ -208,6 +209,15 @@ pub(crate) mod js_bindings { bun_core::out_of_memory(); } + /// Fails the way an infallible std allocation (`Vec::push`, `Box::new`, + /// ...) fails when the allocator returns null, so tests can check that + /// path is reported as out-of-memory rather than as an `abort()` crash. + #[bun_jsc::host_fn] + fn js_alloc_error(_global: &JSGlobalObject, _frame: &CallFrame) -> JsResult { + crash_handler::suppress_core_dumps_if_necessary(); + std::alloc::handle_alloc_error(core::alloc::Layout::new::<[u8; 4096]>()); + } + #[bun_jsc::host_fn] fn js_raise_ignoring_panic_handler( _global: &JSGlobalObject, diff --git a/test/cli/run/fixture-crash.js b/test/cli/run/fixture-crash.js index d44ba5bbc61d..332663c8c092 100644 --- a/test/cli/run/fixture-crash.js +++ b/test/cli/run/fixture-crash.js @@ -12,6 +12,6 @@ if (approach in crash_handler) { crash_handler[approach](); } else { console.error( - "usage: bun fixture-crash.js ", + "usage: bun fixture-crash.js ", ); } diff --git a/test/cli/run/run-crash-handler.test.ts b/test/cli/run/run-crash-handler.test.ts index 4d436bbedc7b..a8c571bfbd78 100644 --- a/test/cli/run/run-crash-handler.test.ts +++ b/test/cli/run/run-crash-handler.test.ts @@ -98,6 +98,7 @@ describe.if(isPosix)("terminal signal reflects the crash cause", () => { test.each([ ["panic", "SIGABRT"], ["outOfMemory", "SIGABRT"], + ["allocError", "SIGABRT"], ["segfault", "SIGSEGV"], ["abort", "SIGABRT"], ["trap", "SIGTRAP"], @@ -122,6 +123,11 @@ describe.if(isPosix)("terminal signal reflects the crash cause", () => { expect(stderr).toContain("abort() called"); } else if (approach === "trap") { expect(stderr).toContain("Trap instruction"); + } else if (approach === "allocError") { + // A failed infallible allocation goes through the alloc error hook and + // is reported as running out of memory, not as std's abort(). + expect(stderr.toLowerCase()).toContain("out of memory"); + expect(stderr).not.toContain("abort() called"); } expect(proc.signalCode).toBe(expectedSignal); expect(exitCode).not.toBe(0); @@ -501,7 +507,7 @@ describe.if(isPosix)("SIGABRT/SIGTRAP are caught by the crash handler", () => { }); describe("automatic crash reporter", () => { - for (const approach of ["panic", "segfault", "outOfMemory"]) { + for (const approach of ["panic", "segfault", "outOfMemory", "allocError"]) { test(`${approach} should report`, async () => { let sent = false; const resolve_handler = Promise.withResolvers(); @@ -538,11 +544,12 @@ describe("automatic crash reporter", () => { expect(exitCode).not.toBe(0); expect(stderr).toContain(server.url.toString()); - if (approach !== "outOfMemory") { - expect(stderr).toContain("oh no: Bun has crashed. This indicates a bug in Bun, not your code"); - } else { + if (approach === "outOfMemory" || approach === "allocError") { expect(stderr.toLowerCase()).toContain("out of memory"); expect(stderr.toLowerCase()).not.toContain("panic"); + expect(stderr).not.toContain("This indicates a bug in Bun"); + } else { + expect(stderr).toContain("oh no: Bun has crashed. This indicates a bug in Bun, not your code"); } expect(sent).toBe(true); }); From cc55b518e61b320f4071d44d7bcfbbce3dc3ffee Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 05:35:58 +0000 Subject: [PATCH 3/7] Enforce clippy::let_unit_value and lint for bun.handleOom comments let_unit_value was allowed because the port left many `let _ = call();` bindings around calls that return (); those are all removed in the next commit. The generated check_slow wrappers for void C++ functions bound their result too, so cppbind now emits a plain call for those. dotenv and http_types no longer use bun_alloc. --- Cargo.lock | 2 -- Cargo.toml | 1 - src/codegen/cppbind.ts | 14 +++++++++++--- src/dotenv/Cargo.toml | 1 - src/http_types/Cargo.toml | 1 - .../internal/source-lints/port-era-markers.test.ts | 5 +++++ 6 files changed, 16 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d6de440ec9d4..c97519c9f7fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -659,7 +659,6 @@ version = "0.0.0" dependencies = [ "bitflags", "bstr", - "bun_alloc", "bun_collections", "bun_core", "bun_dispatch", @@ -856,7 +855,6 @@ version = "0.0.0" dependencies = [ "bitflags", "bstr", - "bun_alloc", "bun_collections", "bun_core", "bun_url", diff --git a/Cargo.toml b/Cargo.toml index c7dcfe86bbb9..0c51c8719b49 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -306,7 +306,6 @@ len_without_is_empty = "allow" needless_return = "allow" module_inception = "allow" missing_safety_doc = "allow" -let_unit_value = "allow" needless_update = "allow" explicit_auto_deref = "allow" doc_lazy_continuation = "allow" diff --git a/src/codegen/cppbind.ts b/src/codegen/cppbind.ts index dedf0324512b..9ba8d19ed238 100644 --- a/src/codegen/cppbind.ts +++ b/src/codegen/cppbind.ts @@ -701,9 +701,17 @@ function generateRustFn(fn: CppFn, rustRaw: string[], rustWrap: string[]): void ` crate::top_scope!(__scope, ${gname});`, ` // SAFETY: \`[[ZIG_EXPORT(check_slow)]]\` extern; ref args are opaque-ZST handles valid for the call;`, ` // any raw-pointer args are forwarded under the wrapper's own \`unsafe fn\` contract.`, - ` let __r = unsafe { raw::${fn.name}(${callArgsStr}) };`, - ` __scope.return_if_exception()?;`, - ` Ok(__r)`, + ...(ret === "()" + ? [ + ` unsafe { raw::${fn.name}(${callArgsStr}) };`, + ` __scope.return_if_exception()?;`, + ` Ok(())`, + ] + : [ + ` let __r = unsafe { raw::${fn.name}(${callArgsStr}) };`, + ` __scope.return_if_exception()?;`, + ` Ok(__r)`, + ]), `}`, ); return; diff --git a/src/dotenv/Cargo.toml b/src/dotenv/Cargo.toml index bab6a7d6b9fd..3caf463a7a1b 100644 --- a/src/dotenv/Cargo.toml +++ b/src/dotenv/Cargo.toml @@ -19,7 +19,6 @@ enum-map.workspace = true enumset.workspace = true libc.workspace = true bitflags.workspace = true -bun_alloc.workspace = true bun_core.workspace = true bun_errno.workspace = true bun_dispatch.workspace = true diff --git a/src/http_types/Cargo.toml b/src/http_types/Cargo.toml index 5384ce8c0183..9a382e5fd88f 100644 --- a/src/http_types/Cargo.toml +++ b/src/http_types/Cargo.toml @@ -19,7 +19,6 @@ enum-map.workspace = true enumset.workspace = true libc.workspace = true bitflags.workspace = true -bun_alloc.workspace = true bun_core.workspace = true bun_collections.workspace = true bun_url.workspace = true diff --git a/test/internal/source-lints/port-era-markers.test.ts b/test/internal/source-lints/port-era-markers.test.ts index 97b42cc0b489..7703cd609596 100644 --- a/test/internal/source-lints/port-era-markers.test.ts +++ b/test/internal/source-lints/port-era-markers.test.ts @@ -45,6 +45,11 @@ const banned: { pattern: RegExp; reason: string }[] = [ pattern: /\bun-gated\b/i, reason: "'un-gated' is port-era progress narrative, not useful documentation", }, + { + pattern: /\bhandleOom\b/, + reason: + "'bun.handleOom' is the Zig idiom; in Rust an allocation-only call is written bare (Vec/Box abort on OOM and the crash handler reports it), so the comment only describes wrapping that should not exist", + }, ]; const rustSources = globAllSources().rust.filter(p => p.endsWith(".rs")); From b8030719cf403af6308c029cd5d6e6b7397b7a50 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 05:35:59 +0000 Subject: [PATCH 4/7] Drop OOM handling around calls that cannot fail Callers of the collection APIs made infallible in the previous commits no longer wrap them in handle_oom, unwrap_or_oom, expect, ?, map_err or let _ =. Thin wrappers whose only error source was one of those calls (bun_dotenv::Map and Loader::load_process, DeclaredSymbolList, StringPool, PathToSourceIndexMap, SavedSourceMap::put_value, ...) return their value directly, and types that used to expose a fallible inherent clone() now implement Clone, which removes the hand-written deep-clone helpers that worked around that. Several of the removed branches looked like graceful handling (Worker env clone, Bun.spawn env block, ArrayBufferSink/HTTP stream writes, SQL buffer writes, markdown slug dedupe, package.json scripts map) but were unreachable: the callee never returned Err. The one real one, source map parsing reserving rows from an untrusted segment count, keeps its error path through MultiArrayList::try_ensure_total_capacity. Also removes the let _ = bindings on unit-returning calls that let_unit_value now flags, and the remaining bun.handleOom comments. --- src/bun_bin/lib.rs | 4 +- src/bun_core/string/StringJoiner.rs | 1 - src/bundler/AstBuilder.rs | 22 +- src/bundler/BundleThread.rs | 2 +- src/bundler/Chunk.rs | 2 +- src/bundler/HTMLImportManifest.rs | 4 +- src/bundler/HTMLScanner.rs | 3 +- src/bundler/LinkerContext.rs | 83 ++++---- src/bundler/LinkerGraph.rs | 24 +-- src/bundler/ParseTask.rs | 32 +-- src/bundler/PathToSourceIndexMap.rs | 13 +- src/bundler/barrel_imports.rs | 52 ++--- src/bundler/bundle_v2.rs | 195 +++++++----------- src/bundler/cache.rs | 10 +- src/bundler/defines.rs | 2 +- src/bundler/lib.rs | 2 +- src/bundler/linker.rs | 4 +- src/bundler/linker_context/MetafileBuilder.rs | 6 +- src/bundler/linker_context/computeChunks.rs | 30 ++- .../computeCrossChunkDependencies.rs | 14 +- src/bundler/linker_context/doStep5.rs | 18 +- .../findAllImportedPartsInJSOrder.rs | 2 +- .../findImportedCSSFilesInJSOrder.rs | 2 +- .../findImportedFilesInCSSOrder.rs | 5 +- .../generateChunksInParallel.rs | 14 +- .../generateCodeForLazyExport.rs | 2 +- .../linker_context/postProcessCSSChunk.rs | 28 ++- .../linker_context/postProcessJSChunk.rs | 24 +-- .../linker_context/scanImportsAndExports.rs | 37 ++-- src/bundler/options.rs | 62 +++--- src/bundler/transpiler.rs | 49 ++--- src/collections/multi_array_list.rs | 47 ++++- src/crash_handler/handle_oom.rs | 9 +- src/css/css_modules.rs | 2 +- src/css/css_parser.rs | 2 +- src/css/declaration.rs | 5 - src/css/rules/supports.rs | 4 +- src/css/values/ident.rs | 1 - src/event_loop/AnyEventLoop.rs | 4 +- src/event_loop/lib.rs | 2 +- src/http/AsyncHTTP.rs | 2 +- src/http/HTTPThread.rs | 2 +- src/http/HeaderBuilder.rs | 2 +- src/http/Headers.rs | 5 +- src/http/h2_client/ClientSession.rs | 4 +- src/http/h3_client/AltSvc.rs | 2 +- src/http/lib.rs | 6 +- src/http_jsc/headers_jsc.rs | 8 +- src/ini/lib.rs | 4 +- src/install/NetworkTask.rs | 2 +- src/install/PackageInstaller.rs | 19 +- src/install/PackageManager.rs | 24 +-- .../PackageManager/PackageJSONEditor.rs | 6 +- .../PackageManager/PackageManagerEnqueue.rs | 41 ++-- .../PackageManager/PackageManagerLifecycle.rs | 12 +- .../PackageManager/PackageManagerOptions.rs | 2 +- .../WorkspacePackageJSONCache.rs | 2 +- .../PackageManager/add_remove_with_filter.rs | 2 +- .../PackageManager/install_with_manager.rs | 20 +- .../PackageManager/package_json_write_back.rs | 2 +- src/install/PackageManager/runTasks.rs | 5 +- .../PackageManager/security_scanner.rs | 14 +- .../PackageManager/workspace_selection.rs | 4 +- src/install/audit_fix.rs | 6 +- src/install/dedupe.rs | 22 +- src/install/hoisted_install.rs | 14 +- src/install/isolated_install.rs | 34 +-- src/install/isolated_install/Store.rs | 8 +- src/install/lib.rs | 6 +- src/install/lockfile.rs | 38 ++-- src/install/lockfile/Buffers.rs | 2 +- src/install/lockfile/CatalogMap.rs | 12 +- src/install/lockfile/OverrideMap.rs | 10 +- src/install/lockfile/Package.rs | 70 +++---- src/install/lockfile/Package/WorkspaceMap.rs | 20 +- src/install/lockfile/Tree.rs | 10 +- src/install/lockfile/bun.lock.rs | 21 +- src/install/lockfile/bun.lockb.rs | 26 +-- src/install/lockfile/printer/tree_printer.rs | 6 +- src/install/lockfile/reachable.rs | 3 +- src/install/migration/npm_lock.rs | 14 +- src/install/npm.rs | 18 +- src/install/patch_install.rs | 10 +- src/install/pnpm.rs | 62 +++--- src/install/postinstall_optimizer.rs | 2 +- src/install/prune.rs | 14 +- src/install/repository.rs | 14 +- src/install/update_scope.rs | 7 +- src/install/update_transitive.rs | 18 +- src/install/yarn.rs | 22 +- src/install_jsc/ini_jsc.rs | 4 +- src/js_parser/fold.rs | 51 ++--- src/js_parser/lower/lower_esm_exports_hmr.rs | 20 +- src/js_parser/p.rs | 114 +++++----- src/js_parser/parse/parse_entry.rs | 21 +- src/js_parser/parse/parse_skip_typescript.rs | 4 +- src/js_parser/parse/parse_typescript.rs | 12 +- src/js_parser/parser.rs | 6 +- src/js_parser/scan/scan_imports.rs | 31 ++- src/js_parser/visit/mod.rs | 37 ++-- src/js_parser/visit/visit_stmt.rs | 10 +- src/js_parser_jsc/Macro.rs | 6 +- src/js_printer/renamer.rs | 18 +- src/jsc/ConsoleObject.rs | 6 +- src/jsc/NodeModuleModule.rs | 2 +- src/jsc/ProcessAutoKiller.rs | 6 +- src/jsc/RuntimeTranspilerStore.rs | 4 +- src/jsc/SavedSourceMap.rs | 37 +--- src/jsc/VirtualMachine.rs | 13 +- src/jsc/bindgen.rs | 2 +- src/jsc/hot_reloader.rs | 4 +- src/jsc/lib.rs | 2 - src/jsc/rare_data.rs | 6 +- src/jsc/web_worker.rs | 8 +- src/resolver/fs.rs | 2 +- src/resolver/options.rs | 4 +- src/resolver/package_json.rs | 22 +- src/resolver/resolver.rs | 12 +- src/resolver/tsconfig_json.rs | 20 +- src/runtime/api/Archive.rs | 2 +- src/runtime/api/BunObject.rs | 14 +- src/runtime/api/JSBundler.rs | 20 +- src/runtime/api/JSON5Object.rs | 6 +- src/runtime/api/JSTranspiler.rs | 35 ++-- src/runtime/api/MarkdownObject.rs | 2 +- src/runtime/api/TOMLObject.rs | 6 +- src/runtime/api/XMLObject.rs | 6 +- src/runtime/api/YAMLObject.rs | 10 +- src/runtime/api/bun/SSLContextCache.rs | 2 +- src/runtime/api/bun/js_bun_spawn_bindings.rs | 8 +- src/runtime/api/cron.rs | 28 +-- src/runtime/api/js_bundle_completion_task.rs | 3 +- src/runtime/bake/DevServer.rs | 65 +++--- src/runtime/bake/FrameworkRouter.rs | 6 +- src/runtime/bake/bake_body.rs | 12 +- src/runtime/bake/dev_server/assets.rs | 4 +- .../bake/dev_server/error_report_request.rs | 4 +- src/runtime/bake/dev_server/hmr_socket.rs | 1 - .../bake/dev_server/incremental_graph.rs | 27 ++- src/runtime/bake/dev_server/mod.rs | 35 ++-- .../bake/dev_server/source_map_store.rs | 3 +- src/runtime/bake/mod.rs | 4 +- src/runtime/bake/production.rs | 10 +- src/runtime/cli/audit_command.rs | 12 +- src/runtime/cli/build_command.rs | 6 +- src/runtime/cli/bunx_command.rs | 22 +- .../cli/create/SourceFileProjectGenerator.rs | 20 +- src/runtime/cli/create_command.rs | 8 +- src/runtime/cli/filter_run.rs | 8 +- src/runtime/cli/multi_run.rs | 12 +- src/runtime/cli/pack_command.rs | 16 +- src/runtime/cli/package_manager_command.rs | 4 +- src/runtime/cli/pm_licenses_command.rs | 2 +- src/runtime/cli/pm_pkg_command.rs | 4 +- src/runtime/cli/pm_trusted_command.rs | 12 +- src/runtime/cli/publish_command.rs | 13 +- src/runtime/cli/run_command.rs | 136 +++++------- src/runtime/cli/test/ChangedFilesFilter.rs | 2 +- src/runtime/cli/test/Timings.rs | 6 +- src/runtime/cli/test/parallel/aggregate.rs | 4 +- src/runtime/cli/test/parallel/runner.rs | 14 +- src/runtime/cli/test_command.rs | 2 +- src/runtime/cli/update_interactive_command.rs | 12 +- src/runtime/cli/upgrade_command.rs | 63 +++--- src/runtime/crypto/CryptoHasher.rs | 6 +- src/runtime/crypto/PasswordObject.rs | 2 +- src/runtime/dns_jsc/dns.rs | 4 +- src/runtime/ipc.rs | 4 +- src/runtime/jsc_hooks.rs | 10 +- src/runtime/node/node_cluster_binding.rs | 3 +- src/runtime/node/node_crypto_binding.rs | 2 +- src/runtime/node/node_fs_stat_watcher.rs | 4 +- src/runtime/node/node_fs_watcher.rs | 4 +- src/runtime/node/node_process.rs | 6 +- src/runtime/node/node_util_binding.rs | 2 +- src/runtime/node/path_watcher.rs | 20 +- src/runtime/server/HTMLBundle.rs | 16 +- src/runtime/server/ServerConfig.rs | 2 +- src/runtime/shell/EnvMap.rs | 6 +- src/runtime/shell/IOWriter.rs | 2 +- src/runtime/shell/RefCountedStr.rs | 1 - src/runtime/shell/builtin/cp.rs | 4 +- src/runtime/shell/subproc.rs | 4 +- src/runtime/socket/Listener.rs | 8 +- src/runtime/socket/socket_body.rs | 11 +- src/runtime/test_runner/bun_test.rs | 2 +- src/runtime/test_runner/jest.rs | 5 +- src/runtime/test_runner/pretty_format.rs | 2 +- src/runtime/test_runner/snapshot.rs | 3 +- src/runtime/timer/timer_object_internals.rs | 2 +- src/runtime/valkey_jsc/valkey.rs | 27 +-- src/runtime/webcore/ArrayBufferSink.rs | 15 +- src/runtime/webcore/fetch.rs | 5 +- src/runtime/webcore/fetch/FetchTasklet.rs | 4 +- src/runtime/webcore/s3/client.rs | 33 ++- src/runtime/webcore/s3/simple_request.rs | 2 +- src/runtime/webcore/streams.rs | 30 +-- src/runtime/webview/ChromeProcess.rs | 2 +- src/runtime/webview/HostProcess.rs | 2 +- src/sourcemap/Chunk.rs | 2 +- src/sourcemap/LineOffsetTable.rs | 13 +- src/sourcemap/Mapping.rs | 52 +++-- src/sourcemap_jsc/CodeCoverage.rs | 26 +-- src/sourcemap_jsc/JSSourceMap.rs | 1 - src/sql_jsc/mysql/JSMySQLConnection.rs | 3 +- src/sql_jsc/mysql/MySQLConnection.rs | 12 +- src/sql_jsc/mysql/MySQLQuery.rs | 11 +- src/sql_jsc/postgres/PostgresSQLConnection.rs | 25 +-- src/sql_jsc/postgres/PostgresSQLQuery.rs | 17 +- src/sql_jsc/shared/SQLDataCell.rs | 6 +- src/standalone_graph/StandaloneModuleGraph.rs | 10 +- 211 files changed, 1317 insertions(+), 1794 deletions(-) diff --git a/src/bun_bin/lib.rs b/src/bun_bin/lib.rs index ba124904593d..31177b0c31f4 100644 --- a/src/bun_bin/lib.rs +++ b/src/bun_bin/lib.rs @@ -185,8 +185,8 @@ pub(crate) unsafe extern "C" fn main(argc: c_int, argv: *const *const c_char) -> Some(bun_alloc::mimalloc::mi_free), ); } - // `bun.handleOom(convertEnvToWTF8())` — converts the OS UTF-16 env - // block to WTF-8 and publishes it via `bun_core::os::set_environ()`. + // Converts the OS UTF-16 env block to WTF-8 and publishes it via + // `bun_core::os::set_environ()`. // Without this, `Bun.env`/`process.env` see only `.env`-file vars. bun_core::handle_oom(bun_sys::windows::env::convert_env_to_wtf8()); } diff --git a/src/bun_core/string/StringJoiner.rs b/src/bun_core/string/StringJoiner.rs index 3e0f1d96a77d..5076c0272586 100644 --- a/src/bun_core/string/StringJoiner.rs +++ b/src/bun_core/string/StringJoiner.rs @@ -72,7 +72,6 @@ impl<'a> StringJoiner<'a> { if data.is_empty() { return; } - // bun.handleOom(this.allocator.dupe(u8, data)) → Box<[u8]> (aborts on OOM) self.push_owned(Box::from(data)); } diff --git a/src/bundler/AstBuilder.rs b/src/bundler/AstBuilder.rs index 72b55ea7b72a..df779d705f9b 100644 --- a/src/bundler/AstBuilder.rs +++ b/src/bundler/AstBuilder.rs @@ -125,7 +125,7 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { ref_, is_top_level: self.scopes.is_empty() || core::ptr::eq(self.current_scope, self.scopes[0]), - })?; + }); Ok(ref_) } @@ -267,7 +267,7 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { // pretend that every symbol was used symbol_uses: 'uses: { let mut map = PartSymbolUseMap::default(); - map.ensure_total_capacity(self.symbols.len())?; + map.ensure_total_capacity(self.symbols.len()); for i in 0..self.symbols.len() { map.put_assume_capacity( Ref::new( @@ -287,7 +287,7 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { // SAFETY: module_scope is a live arena allocation (set in init, scopes stack is empty) let module_scope_ref = unsafe { &*module_scope }; let generated_len = module_scope_ref.generated.len(); - top_level_symbols_to_parts.ensure_total_capacity(generated_len)?; + top_level_symbols_to_parts.ensure_total_capacity(generated_len); // `ArrayHashMap` keeps keys/values in private `Vec`s and rebuilds // hashes on every `put_assume_capacity`, so a plain pre-reserved // insert loop suffices (and `re_index` is a no-op here). `Vec` is @@ -296,7 +296,7 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { top_level_symbols_to_parts .put_assume_capacity(ref_, bun_alloc::AstAlloc::vec_from_slice(&[1])); } - top_level_symbols_to_parts.re_index()?; + top_level_symbols_to_parts.re_index(); // For more details on this section, look at js_parser.toAST // This is mimicking how it calls ImportScanner @@ -347,7 +347,7 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { is_exported: false, local_parts_with_uses: bun_alloc::AstAlloc::vec(), }, - )?; + ); } // convertStmt: `deduplicatedImport` is a no-op for // AstBuilder (each generated file emits at most one @@ -396,10 +396,10 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { parts[1].declared_symbols.append(DeclaredSymbol { ref_: temp_id, is_top_level: true, - })?; + }); parts[1] .symbol_uses - .put(temp_id, symbol::Use { count_estimate: 1 })?; + .put(temp_id, symbol::Use { count_estimate: 1 }); VecExt::append(&mut self.current_scope_mut().generated, temp_id); export_props.push(G::Property { key: Some(Expr::init(E::String::init(b"default"), stmt.loc)), @@ -456,11 +456,11 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { // mark a dependency on module_ref so it is renamed parts[1] .symbol_uses - .put(self.module_ref, symbol::Use { count_estimate: 1 })?; + .put(self.module_ref, symbol::Use { count_estimate: 1 }); parts[1].declared_symbols.append(DeclaredSymbol { ref_: self.module_ref, is_top_level: true, - })?; + }); } // Head-part bookkeeping (only `parts[0]`, which is the empty // namespace-export part): mark dead and depend on `parts[1]`. @@ -500,7 +500,7 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { is_exported: false, local_parts_with_uses: bun_alloc::AstAlloc::vec(), }, - )?; + ); } } bun_ast::StmtData::SLocal(st) if st.is_export => { @@ -590,7 +590,7 @@ impl<'a, 'bump> AstBuilder<'a, 'bump> { alias_loc: Loc::EMPTY, ref_, }, - )?; + ); } Ok(()) } diff --git a/src/bundler/BundleThread.rs b/src/bundler/BundleThread.rs index cef2a0487354..a32874b3a93c 100644 --- a/src/bundler/BundleThread.rs +++ b/src/bundler/BundleThread.rs @@ -303,7 +303,7 @@ impl BundleThread { // SAFETY: `transpiler.log` is the arena-allocated `*mut Log` set up by // `configure_bundler`; valid for the lifetime of `heap`. Raw deref so the // `&'a mut Transpiler` consumed by `init_and_run` above is not reborrowed. - let _ = unsafe { (*(*transpiler_ptr).log).append_to_with_recycled(&mut out_log, true) }; // logger OOM-only + unsafe { (*(*transpiler_ptr).log).append_to_with_recycled(&mut out_log, true) }; completion.set_log(out_log); if run.is_ok() { diff --git a/src/bundler/Chunk.rs b/src/bundler/Chunk.rs index 63e6420e24bb..b68d737e0141 100644 --- a/src/bundler/Chunk.rs +++ b/src/bundler/Chunk.rs @@ -200,7 +200,7 @@ impl Default for Chunk { Chunk { unique_key: b"", files_with_parts_in_chunk: ArrayHashMap::new(), - entry_bits: AutoBitSet::init_empty(0).expect("static AutoBitSet"), + entry_bits: AutoBitSet::init_empty(0), final_rel_path: Box::default(), template: PathTemplate::default(), cross_chunk_imports: Vec::new(), diff --git a/src/bundler/HTMLImportManifest.rs b/src/bundler/HTMLImportManifest.rs index 3b8e54eed82d..522fbb4b6c1e 100644 --- a/src/bundler/HTMLImportManifest.rs +++ b/src/bundler/HTMLImportManifest.rs @@ -182,7 +182,7 @@ pub(crate) fn write( &*bun_core::from_field_ptr!(BundleV2<'static>, graph, std::ptr::from_ref::(graph)) }; let options = &bv2.transpiler().options; - let mut entry_point_bits = AutoBitSet::init_empty(graph.entry_points.len())?; + let mut entry_point_bits = AutoBitSet::init_empty(graph.entry_points.len()); let root_dir: &[u8] = if !options.root_dir.is_empty() { &options.root_dir[..] @@ -233,7 +233,7 @@ pub(crate) fn write( let additional_output_files = graph.additional_output_files.as_slice(); let file_entry_bits: &[AutoBitSet] = linker_graph.files.items_entry_bits(); - let mut already_visited_output_file = AutoBitSet::init_empty(additional_output_files.len())?; + let mut already_visited_output_file = AutoBitSet::init_empty(additional_output_files.len()); // Write all chunks that have files associated with this entry point. // Also include browser chunks from server builds (lazy-loaded chunks from dynamic imports). diff --git a/src/bundler/HTMLScanner.rs b/src/bundler/HTMLScanner.rs index 88cdf4323b10..7793e46be4f5 100644 --- a/src/bundler/HTMLScanner.rs +++ b/src/bundler/HTMLScanner.rs @@ -92,8 +92,7 @@ impl<'a> HTMLScanner<'a> { fn on_html_parse_error(&mut self, message: &[u8]) { // Vec/Box allocations abort on OOM; just call. `IntoText for // Vec` → `Cow::Owned`, so the Log owns and drops the copy. - let _ = self - .log + self.log .add_error(Some(self.source), Loc::EMPTY, message.to_vec()); } diff --git a/src/bundler/LinkerContext.rs b/src/bundler/LinkerContext.rs index bc47073ee17d..760c87ea5871 100644 --- a/src/bundler/LinkerContext.rs +++ b/src/bundler/LinkerContext.rs @@ -826,7 +826,7 @@ impl<'a> LinkerContext<'a> { let mut parts_live: Vec = Vec::with_capacity(parts_col.len()); for (i, parts) in parts_col.iter().enumerate() { - let mut bits = bun_collections::AutoBitSet::init_empty(parts.len())?; + let mut bits = bun_collections::AutoBitSet::init_empty(parts.len()); // The HTML loader's `ParseTask` builds its synthetic part 1 already // live (so the JS-chunk visitor follows every embedded import record). // `mark_file_live_for_tree_shaking` short-circuits for HTML and never @@ -914,7 +914,7 @@ impl<'a> LinkerContext<'a> { // AutoBitSet needs to be initialized if it is dynamic if AutoBitSet::needs_dynamic(entry_points_len) { for bits in file_entry_bits.iter_mut() { - *bits = AutoBitSet::init_empty(entry_points_len)?; + *bits = AutoBitSet::init_empty(entry_points_len); } } else if !file_entry_bits.is_empty() { // assert that the tag is correct @@ -1063,7 +1063,7 @@ impl<'a> LinkerContext<'a> { { let index = source_indices[0]; let path = &sources[index as usize].path; - source_id_map.put_no_clobber(index, 0)?; + source_id_map.put_no_clobber(index, 0); // Note: the relative path lives in a local owned buffer // (drops at scope exit). @@ -1084,7 +1084,7 @@ impl<'a> LinkerContext<'a> { let mut next_mapping_source_index: i32 = 1; for &index in &source_indices[1..] { - let gop = source_id_map.get_or_put(index)?; + let gop = source_id_map.get_or_put(index); if gop.found_existing { continue; } @@ -1497,8 +1497,7 @@ impl SourceMapData { &source.contents, // We don't support sourcemaps for source files with more than 2^31 lines (approximate_line_count as u32 & 0x7FFF_FFFF) as i32, - ) - .expect("OOM"); + ); } } @@ -2368,7 +2367,7 @@ impl<'a> LinkerContext<'a> { break 'follow r#ref; }; - let entry = local_css_names.get_or_put(r#ref).expect("OOM"); + let entry = local_css_names.get_or_put(r#ref); if entry.found_existing { continue; } @@ -2398,8 +2397,7 @@ impl<'a> LinkerContext<'a> { .expect("infallible: in-memory write"); // The map owns its boxed values (freed with `mangled_props`). self.mangled_props - .put(r#ref, final_generated_name.into_boxed_slice()) - .expect("OOM"); + .put(r#ref, final_generated_name.into_boxed_slice()); } } } @@ -3111,9 +3109,7 @@ impl<'a> LinkerContext<'a> { DependencyList::new_in(bun_alloc::AstAlloc) }; let mut symbol_uses = PartSymbolUseMap::default(); - symbol_uses - .put(wrapper_ref, SymbolUse { count_estimate: 1 }) - .expect("OOM"); + symbol_uses.put(wrapper_ref, SymbolUse { count_estimate: 1 }); let exports_ref = self.graph.ast.items_exports_ref()[source_index as usize]; let module_ref = self.graph.ast.items_module_ref()[source_index as usize]; let wrap_ref = self.graph.ast.items_wrapper_ref()[source_index as usize]; @@ -3136,8 +3132,7 @@ impl<'a> LinkerContext<'a> { ref_: wrap_ref, is_top_level: true, }, - ]) - .expect("unreachable"), + ]), dependencies, ..Default::default() }, @@ -3229,9 +3224,7 @@ impl<'a> LinkerContext<'a> { } let mut symbol_uses = PartSymbolUseMap::default(); - symbol_uses - .put(wrapper_ref, SymbolUse { count_estimate: 1 }) - .expect("OOM"); + symbol_uses.put(wrapper_ref, SymbolUse { count_estimate: 1 }); let part_index = self .graph .add_part_to_file( @@ -3241,8 +3234,7 @@ impl<'a> LinkerContext<'a> { declared_symbols: DeclaredSymbolList::from_slice(&[DeclaredSymbol { ref_: wrapper_ref, is_top_level: true, - }]) - .expect("unreachable"), + }]), dependencies, ..Default::default() }, @@ -3864,19 +3856,17 @@ impl<'a> LinkerContext<'a> { match result.kind { MatchImportKind::Normal => { - imports_to_bind - .put( - import_ref, - crate::ImportData { - re_exports, - data: ImportTracker { - source_index: crate::Index::init(result.source_index), - import_ref: result.r#ref, - ..Default::default() - }, + imports_to_bind.put( + import_ref, + crate::ImportData { + re_exports, + data: ImportTracker { + source_index: crate::Index::init(result.source_index), + import_ref: result.r#ref, + ..Default::default() }, - ) - .expect("unreachable"); + }, + ); } MatchImportKind::Namespace => { // SAFETY: the mutated symbol slot is disjoint from `named_import` @@ -3889,19 +3879,17 @@ impl<'a> LinkerContext<'a> { })); } MatchImportKind::NormalAndNamespace => { - imports_to_bind - .put( - import_ref, - crate::ImportData { - re_exports, - data: ImportTracker { - source_index: crate::Index::init(result.source_index), - import_ref: result.r#ref, - ..Default::default() - }, + imports_to_bind.put( + import_ref, + crate::ImportData { + re_exports, + data: ImportTracker { + source_index: crate::Index::init(result.source_index), + import_ref: result.r#ref, + ..Default::default() }, - ) - .expect("unreachable"); + }, + ); // SAFETY: one-shot field store after `imports_to_bind.put` (disjoint // map) has fully returned; no other live borrow aliases this symbol slot. @@ -3933,8 +3921,7 @@ impl<'a> LinkerContext<'a> { } MatchImportKind::ProbablyTypescriptType => { self.graph.meta.items_probably_typescript_type_mut()[source_index as usize] - .put(import_ref, ()) - .expect("unreachable"); + .put(import_ref, ()); } MatchImportKind::Ambiguous => { let source = self.get_source(source_index); @@ -4009,7 +3996,7 @@ impl<'a> LinkerContext<'a> { declared_symbols: DeclaredSymbolList::from_slice(&[DeclaredSymbol { ref_: r#ref, is_top_level: true, - }])?, + }]), can_be_removed_if_unused: true, ..Default::default() }, @@ -4026,7 +4013,7 @@ impl<'a> LinkerContext<'a> { .graph .meta .items_top_level_symbol_to_parts_overlay_mut()[source_index as usize]; - top_level.put(r#ref, bun_alloc::AstAlloc::vec_from_slice(&[part_index]))?; + top_level.put(r#ref, bun_alloc::AstAlloc::vec_from_slice(&[part_index])); let resolved_exports = &mut self.graph.meta.items_resolved_exports_mut()[source_index as usize]; @@ -4040,7 +4027,7 @@ impl<'a> LinkerContext<'a> { }, ..Default::default() }, - )?; + ); Ok((r#ref, part_index)) } diff --git a/src/bundler/LinkerGraph.rs b/src/bundler/LinkerGraph.rs index bfb5fd0871f3..cf089c29c39b 100644 --- a/src/bundler/LinkerGraph.rs +++ b/src/bundler/LinkerGraph.rs @@ -415,7 +415,7 @@ pub(crate) fn generate_symbol_import_and_use( // Mark this symbol as used by this part { let part: &mut Part = &mut parts[source_index as usize].as_mut_slice()[part_index as usize]; - let uses_entry = part.symbol_uses.get_or_put(ref_)?; + let uses_entry = part.symbol_uses.get_or_put(ref_); if !uses_entry.found_existing { *uses_entry.value_ptr = symbol::Use { count_estimate: use_count, @@ -448,7 +448,7 @@ pub(crate) fn generate_symbol_import_and_use( }, ..Default::default() }, - )?; + ); } // Pull in all parts that declare this symbol @@ -622,9 +622,9 @@ impl<'a> LinkerGraph<'a> { entry_point_original_names: &IndexStringMap, ) -> Result<(), crate::Error> { let scb = server_component_boundaries.slice(); - self.files.set_capacity(sources.len())?; + self.files.set_capacity(sources.len()); self.files.zero(); - self.files_live = BitSet::init_empty(sources.len())?; + self.files_live = BitSet::init_empty(sources.len()); // SAFETY: capacity reserved above; columns zeroed by `zero()`. unsafe { self.files.set_len(sources.len()) }; @@ -643,7 +643,7 @@ impl<'a> LinkerGraph<'a> { entry_points.len() + server_component_boundaries.list.len() + dynamic_import_entry_points.len(), - )?; + ); // SAFETY: capacity reserved; columns initialized below. unsafe { self.entry_points.set_len(entry_points.len()) }; @@ -697,7 +697,7 @@ impl<'a> LinkerGraph<'a> { } let import_records_len = self.ast.items_import_records().len(); - self.meta.set_capacity(import_records_len)?; + self.meta.set_capacity(import_records_len); // Fill each slot with `Default`. let ast_len = self.ast.len(); debug_assert!(ast_len <= import_records_len); @@ -706,7 +706,7 @@ impl<'a> LinkerGraph<'a> { } if scb.list.len() > 0 { - self.is_scb_bitset = BitSet::init_empty(self.files.len()).expect("unreachable"); + self.is_scb_bitset = BitSet::init_empty(self.files.len()); // Index all SCBs into the bitset. This is needed so chunking // can track the chunks that SCBs belong to. @@ -815,7 +815,7 @@ impl<'a> LinkerGraph<'a> { count += ts_enums.count(); } if count > 0 { - self.ts_enums.ensure_total_capacity(count)?; + self.ts_enums.ensure_total_capacity(count); for ts_enums in self.ast.items_ts_enums().iter() { debug_assert_eq!(ts_enums.keys().len(), ts_enums.values().len()); for (key, value) in ts_enums.keys().iter().zip(ts_enums.values().iter()) { @@ -836,9 +836,7 @@ impl<'a> LinkerGraph<'a> { .enumerate() { let mut resolved = ResolvedExports::default(); - resolved - .ensure_total_capacity(src.count()) - .expect("unreachable"); + resolved.ensure_total_capacity(src.count()); debug_assert_eq!(src.keys().len(), src.values().len()); for (key, value) in src.keys().iter().zip(src.values().iter()) { resolved.put_assume_capacity( @@ -894,7 +892,7 @@ impl<'a> LinkerGraph<'a> { let import_records = self.ast.items_import_records(); let flags = self.meta.items_flags_mut(); let len = import_records.len(); - let mut visited = AutoBitSet::init_empty(self.ast.len())?; + let mut visited = AutoBitSet::init_empty(self.ast.len()); let mut stack: Vec = Vec::new(); for root in 0..len { @@ -997,7 +995,7 @@ impl Default for File { fn default() -> Self { Self { // Note: empty static-arm bitset; load() overwrites before any read. - entry_bits: AutoBitSet::init_empty(0).expect("static AutoBitSet"), + entry_bits: AutoBitSet::init_empty(0), input_file: Index::source(0u32), distance_from_entry_point: u32::MAX, entry_point_kind: EntryPoint::Kind::None, diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index a4b7cc2acbaf..17d7d655bd0c 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -801,7 +801,7 @@ pub mod parse_worker { .ok_or(AnyError::ParserError)?, )) })(); - let _ = temp_log.clone_to_with_recycled(log, true); + temp_log.clone_to_with_recycled(log, true); return result; } Loader::Yaml => { @@ -827,7 +827,7 @@ pub mod parse_worker { .ok_or(AnyError::ParserError)?, )) })(); - let _ = temp_log.clone_to_with_recycled(log, true); + temp_log.clone_to_with_recycled(log, true); return result; } Loader::Json5 => { @@ -849,7 +849,7 @@ pub mod parse_worker { .ok_or(AnyError::ParserError)?, )) })(); - let _ = temp_log.clone_to_with_recycled(log, true); + temp_log.clone_to_with_recycled(log, true); return result; } Loader::Xml => { @@ -880,7 +880,7 @@ pub mod parse_worker { .ok_or(AnyError::ParserError)?, )) })(); - let _ = temp_log.clone_to_with_recycled(log, true); + temp_log.clone_to_with_recycled(log, true); return result; } Loader::Text => { @@ -916,11 +916,11 @@ pub mod parse_worker { let html = match bun_md::root::render_to_html(&source.contents) { Ok(h) => h, Err(_) => { - let _ = log.add_error( + log.add_error( Some(source), Loc::EMPTY, b"Failed to render markdown to HTML", - ); // logger OOM-only + ); return Err(crate::Error::ParserError); } }; @@ -957,7 +957,7 @@ pub mod parse_worker { Loader::SqliteEmbedded | Loader::Sqlite => { if !topts.target.is_bun() { // logger OOM-only - let _ = log.add_error( + log.add_error( Some(source), Loc::EMPTY, b"To use the \"sqlite\" loader, set target to \"bun\"", @@ -1078,7 +1078,7 @@ pub mod parse_worker { // (dap-eval-cb "source.contents.ptr") if topts.target == options::Target::Browser { // logger OOM-only - let _ = log.add_error( + log.add_error( Some(source), Loc::EMPTY, b"Loading .node files won't work in the browser. Make sure to set target to \"bun\" or \"node\"", @@ -1244,7 +1244,7 @@ pub mod parse_worker { Err(e) => { // Surface the actual CSS parse diagnostic. let _ = e.add_to_logger(&mut temp_log, source); - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); return Err(crate::Error::SyntaxError); } }; @@ -1265,7 +1265,7 @@ pub mod parse_worker { ) { // Surface the actual minify diagnostic. let _ = e.add_to_logger(&mut temp_log, source); - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); return Err(crate::Error::MinifyError); } if css_ast.local_scope.count() > 0 { @@ -1291,7 +1291,7 @@ pub mod parse_worker { b"", symbols, ); - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); let mut ast = JSAst::init(lazy?.ok_or(AnyError::ParserError)?); let css_ast_heap = crate::bundled_ast::CssAstRef::from_bump(bump.alloc(css_ast)); ast.css = Some(css_ast_heap); @@ -1504,7 +1504,7 @@ pub mod parse_worker { file_path.text, ); if e == bun_resolver::Error::Sys(bun_errno::SystemErrno::ENOENT) { - let _ = log.add_error_fmt( + log.add_error_fmt( Some(&source), Loc::EMPTY, format_args!( @@ -1514,7 +1514,7 @@ pub mod parse_worker { ); return Err(crate::Error::Sys(bun_errno::SystemErrno::ENOENT)); } else { - let _ = log.add_error_fmt( + log.add_error_fmt( Some(&source), Loc::EMPTY, format_args!( @@ -1810,7 +1810,7 @@ pub mod parse_worker { } else if msg.kind == bun_ast::Kind::Warn { log.warnings += 1; } - let _ = log.add_msg(msg); + log.add_msg(msg); } /// # Safety @@ -2130,7 +2130,7 @@ pub mod parse_worker { // a second `&mut` via `&mut *args.context` while `&mut self` // is live would be aliased-`&mut` UB. self.log.errors += 1; - let _ = self.log.add_msg(msg); // logger OOM-only + self.log.add_msg(msg); return Err(crate::Error::InvalidNativePlugin); } @@ -2504,7 +2504,7 @@ pub mod parse_worker { opts.features.bundler_feature_flags = topts .bundler_feature_flags .as_deref() - .map(|s| Box::new(bun_core::handle_oom(s.clone()))); + .map(|s| Box::new(s.clone())); // JavaScriptCore implements `using` / `await using` natively, so when // targeting Bun there is no need to lower them. opts.features.lower_using = !target.is_bun(); diff --git a/src/bundler/PathToSourceIndexMap.rs b/src/bundler/PathToSourceIndexMap.rs index f0e42df43810..6ea7b88ed848 100644 --- a/src/bundler/PathToSourceIndexMap.rs +++ b/src/bundler/PathToSourceIndexMap.rs @@ -43,20 +43,13 @@ impl PathToSourceIndexMap { // Takes `&[u8]` (not `impl AsRef<[u8]>`) // to avoid E0283 inference ambiguity at `.into()` call sites in bundle_v2. - pub(crate) fn put( - &mut self, - text: &[u8], - value: IndexInt, - ) -> Result<(), bun_alloc::AllocError> { + pub(crate) fn put(&mut self, text: &[u8], value: IndexInt) { // PERF: bun_collections::StringHashMap is keyed by `Box<[u8]>`, so we dupe here. // Revisit once StringHashMap gains a borrowed-key variant. - self.map.put(text, value) + self.map.put(text, value); } - pub(crate) fn get_or_put( - &mut self, - text: impl AsRef<[u8]>, - ) -> Result, bun_alloc::AllocError> { + pub(crate) fn get_or_put(&mut self, text: impl AsRef<[u8]>) -> GetOrPutResult<'_> { // PERF: see note in `put` re: key duplication. self.map.get_or_put(text.as_ref()) } diff --git a/src/bundler/barrel_imports.rs b/src/bundler/barrel_imports.rs index 86cc210a5783..3e499f70e659 100644 --- a/src/bundler/barrel_imports.rs +++ b/src/bundler/barrel_imports.rs @@ -96,17 +96,8 @@ pub(crate) fn apply_barrel_optimization( this: &mut BundleV2, parse_result: &mut parse_task::Result, ) { - // bun.handleOom: Rust aborts on OOM via the global arena; unwrap is for - // bun_collections ops that still surface AllocError. - apply_barrel_optimization_impl(this, parse_result).expect("OOM"); -} - -fn apply_barrel_optimization_impl( - this: &mut BundleV2, - parse_result: &mut parse_task::Result, -) -> Result<(), AllocError> { let parse_task::ResultValue::Success(result) = &mut parse_result.value else { - return Ok(()); + return; }; let source_index = result.source.index.0; @@ -118,20 +109,20 @@ fn apply_barrel_optimization_impl( let is_side_effects_false = result.side_effects == bun_ast::SideEffects::NoSideEffectsPackageJson; if !is_explicit && !is_side_effects_false { - return Ok(()); + return; } let ast = &mut result.ast; if ast.import_records.len() == 0 { - return Ok(()); + return; } if ast.named_exports.count() == 0 && ast.export_star_import_records.len() == 0 { - return Ok(()); + return; } // Verify pure barrel: all named exports must be re-exports for entry in ast.named_exports.values() { if ast.named_imports.get(&entry.ref_).is_none() { - return Ok(()); + return; } } @@ -139,7 +130,7 @@ fn apply_barrel_optimization_impl( if this.graph.input_files.items_flags()[source_index as usize] .contains(InputFileFlags::IS_EXPORT_STAR_TARGET) { - return Ok(()); + return; } // Check requested_exports to see which exports were already requested by @@ -147,7 +138,7 @@ fn apply_barrel_optimization_impl( // requests eagerly as each file is processed, so we don't need to scan // the graph. let requested = match RequestedExports::lookup(&this.requested_exports, source_index) { - Some(RequestedExports::All) => return Ok(()), // import * already seen — load everything + Some(RequestedExports::All) => return, // import * already seen — load everything Some(RequestedExports::Partial(partial)) => Some(partial), None => None, }; @@ -157,7 +148,7 @@ fn apply_barrel_optimization_impl( let mut needed_records: ArrayHashMap = ArrayHashMap::default(); for record_idx in ast.export_star_import_records.iter() { - needed_records.put(*record_idx, ())?; + needed_records.put(*record_idx, ()); } if let Some(partial) = requested { @@ -165,7 +156,7 @@ fn apply_barrel_optimization_impl( if let Some(resolution) = resolve_barrel_export(key, &ast.named_exports, &ast.named_imports) { - needed_records.put(resolution.import_record_index, ())?; + needed_records.put(resolution.import_record_index, ()); } } } @@ -186,7 +177,7 @@ fn apply_barrel_optimization_impl( if let Some(resolution) = resolve_barrel_export(alias, &ast.named_exports, &ast.named_imports) { - needed_records.put(resolution.import_record_index, ())?; + needed_records.put(resolution.import_record_index, ()); } } } @@ -208,7 +199,7 @@ fn apply_barrel_optimization_impl( needed_paths.put( ast.import_records.as_slice()[*rec_idx as usize].path.text, (), - )?; + ); } } @@ -221,7 +212,7 @@ fn apply_barrel_optimization_impl( .path .text, ) { - needed_records.put(imp.import_record_index, ())?; + needed_records.put(imp.import_record_index, ()); } } } @@ -271,12 +262,9 @@ fn apply_barrel_optimization_impl( // ensuring it gets re-parsed on every incremental build. This is needed // because the set of needed exports can change when importing files change. if let Some(dev) = dev_handle { - dev.register_barrel_with_deferrals(result.source.path.text) - .map_err(|_| AllocError)?; + dev.register_barrel_with_deferrals(result.source.path.text); } } - - Ok(()) } /// Clear is_unused on a deferred barrel record. Returns true if the record was un-deferred. @@ -428,7 +416,7 @@ pub(crate) fn schedule_barrel_deferred_imports( // Build a set of import_record_indices that have named_imports entries, // so we can detect bare imports (those with no specific export bindings). - let mut named_ir_indices = AutoBitSet::init_empty(file_import_records.len())?; + let mut named_ir_indices = AutoBitSet::init_empty(file_import_records.len()); // In HMR, ConvertESMExportsForHmr deduplicates import records by path: // two `import { X } from 'mod'` statements become one, and the second @@ -453,7 +441,7 @@ pub(crate) fn schedule_barrel_deferred_imports( if ir_probe.original_path == ir_probe.path.text { continue; } - dedup_fallback.put(ir_probe.original_path, ir_probe.path.text)?; + dedup_fallback.put(ir_probe.original_path, ir_probe.path.text); } } @@ -499,7 +487,7 @@ pub(crate) fn schedule_barrel_deferred_imports( match value { RequestedExports::All => {} RequestedExports::Partial(p) => { - p.put(alias, ())?; + p.put(alias, ()); } } // Persist the export request on DevServer so it survives across builds. @@ -711,7 +699,7 @@ pub(crate) fn schedule_barrel_deferred_imports( } } RequestedExports::Partial(p) => { - let alias_gop = p.get_or_put(item_alias)?; + let alias_gop = p.get_or_put(item_alias); if found && alias_gop.found_existing { qi += 1; continue; @@ -741,7 +729,7 @@ pub(crate) fn schedule_barrel_deferred_imports( && !flags.contains(import_record::Flags::IS_INTERNAL) { if un_defer_record(barrel_ir, idx) { - barrels_to_resolve.put(barrel_idx, ())?; + barrels_to_resolve.put(barrel_idx, ()); un_deferred_any = true; } } @@ -846,7 +834,7 @@ pub(crate) fn schedule_barrel_deferred_imports( continue; } if un_defer_record(barrel_ir, star_idx as usize) { - barrels_to_resolve.put(barrel_idx, ())?; + barrels_to_resolve.put(barrel_idx, ()); } let mut star_rec_si = barrel_ir.as_slice()[star_idx as usize].source_index; if !star_rec_si.is_valid() { @@ -872,7 +860,7 @@ pub(crate) fn schedule_barrel_deferred_imports( let barrel_ir = &mut this.graph.ast.items_import_records_mut()[barrel_idx as usize]; if un_defer_record(barrel_ir, resolution.import_record_index as usize) { - barrels_to_resolve.put(barrel_idx, ())?; + barrels_to_resolve.put(barrel_idx, ()); } // `original_alias` is an arena-backed `StoreStr` valid for the diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index 24999fd82b68..3df387f28124 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -671,7 +671,7 @@ pub mod bv2_impl { let index = self.files.count(); // Value is the post-bundle output index; left as a placeholder until // the bundle is indexed. - self.files.put_no_clobber(key, OutputFileIndex::init(0))?; + self.files.put_no_clobber(key, OutputFileIndex::init(0)); Ok(OpaqueFileId::init(index as u32)) } } @@ -1735,9 +1735,7 @@ pub mod bv2_impl { // Each file must come after its dependencies self.reachable.push(source_index); if CHECK_DYNAMIC_IMPORTS && was_dynamic_import { - self.dynamic_import_entry_points - .put(source_index.get(), ()) - .expect("unreachable"); + self.dynamic_import_entry_points.put(source_index.get(), ()); } continue; } @@ -1753,9 +1751,7 @@ pub mod bv2_impl { if self.visited.is_set(source_index.get() as usize) { if CHECK_DYNAMIC_IMPORTS && was_dynamic_import { - self.dynamic_import_entry_points - .put(source_index.get(), ()) - .expect("unreachable"); + self.dynamic_import_entry_points.put(source_index.get(), ()); } continue; } @@ -1916,16 +1912,16 @@ pub mod bv2_impl { self.graph .server_component_boundaries .slice() - .bit_set(self.graph.input_files.len())?, + .bit_set(self.graph.input_files.len()), ) } else { None }; let mut additional_files_imported_by_js_and_inlined_in_css = - DynamicBitSetUnmanaged::init_empty(self.graph.input_files.len())?; + DynamicBitSetUnmanaged::init_empty(self.graph.input_files.len()); let mut additional_files_imported_by_css_and_inlined = - DynamicBitSetUnmanaged::init_empty(self.graph.input_files.len())?; + DynamicBitSetUnmanaged::init_empty(self.graph.input_files.len()); self.dynamic_import_entry_points = ArrayHashMap::new(); @@ -1949,7 +1945,7 @@ pub mod bv2_impl { let mut visitor = ReachableFileVisitor { reachable: Vec::with_capacity(self.graph.entry_points.len() + 1), - visited: DynamicBitSet::init_empty(self.graph.input_files.len())?, + visited: DynamicBitSet::init_empty(self.graph.input_files.len()), redirects: self.graph.ast.items_redirect_import_record_index(), all_import_records, all_loaders: self.graph.input_files.items_loader(), @@ -2262,8 +2258,7 @@ pub mod bv2_impl { let (found_existing, value_ptr): (bool, *mut u32) = { let entry = self .path_to_source_index_map(target) - .get_or_put(path_primary.text) - .expect("oom"); + .get_or_put(path_primary.text); ( entry.found_existing, std::ptr::from_mut::(entry.value_ptr), @@ -2544,9 +2539,7 @@ pub mod bv2_impl { import_record.original_target, ) .expect("oom"); - self.path_to_source_index_map(target) - .put(path.text, idx) - .expect("oom"); + self.path_to_source_index_map(target).put(path.text, idx); out_source_index = Some(Index::init(idx)); if let Some(secondary) = &resolve_result.path_pair.secondary { @@ -2580,13 +2573,9 @@ pub mod bv2_impl { Target::ServerComponentsSsr => (main_target, Target::Browser), _ => (Target::Browser, Target::ServerComponentsSsr), }; - self.path_to_source_index_map(ta) - .put(&key_text, idx) - .expect("oom"); + self.path_to_source_index_map(ta).put(&key_text, idx); if separate_ssr { - self.path_to_source_index_map(tb) - .put(&key_text, idx) - .expect("oom"); + self.path_to_source_index_map(tb).put(&key_text, idx); } } } @@ -2635,9 +2624,8 @@ pub mod bv2_impl { // `pretty`. result.path_pair.primary = path; self.path_to_source_index_map(target) - .put(path_slice, source_index.get()) - .expect("oom"); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // OOM/capacity: fire-and-forget + .put(path_slice, source_index.get()); + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); self.graph.input_files.append(crate::Graph::InputFile { source: bun_ast::Source { @@ -2649,7 +2637,7 @@ pub mod bv2_impl { loader, side_effects: result.primary_side_effects_data, ..Default::default() - })?; + }); // Arena-owned; freed on heap reset. let task_val = ParseTask::init(&result, source_index, self); // SAFETY: arena outlives the bundle pass; reborrow `*mut` as `&mut`. @@ -2739,9 +2727,8 @@ pub mod bv2_impl { *p = path; } self.path_to_source_index_map(target) - .put(path.text, source_index.get()) - .expect("oom"); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // OOM/capacity: fire-and-forget + .put(path.text, source_index.get()); + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); let side_effects = result.primary_side_effects_data; self.graph.input_files.append(crate::Graph::InputFile { @@ -2754,7 +2741,7 @@ pub mod bv2_impl { loader, side_effects, ..Default::default() - })?; + }); // Arena-owned; freed on heap reset. let task_val = ParseTask::init(result, source_index, self); // SAFETY: arena outlives the bundle pass; reborrow `*mut` as `&mut`. @@ -3043,7 +3030,7 @@ pub mod bv2_impl { self.graph.entry_points.reserve(num_entry_points); self.graph .input_files - .ensure_unused_capacity(num_entry_points)?; + .ensure_unused_capacity(num_entry_points); for entry_point in data { let entry_point: &[u8] = entry_point.as_ref(); @@ -3104,7 +3091,7 @@ pub mod bv2_impl { self.graph.entry_points.reserve(num_entry_points); self.graph .input_files - .ensure_unused_capacity(num_entry_points)?; + .ensure_unused_capacity(num_entry_points); debug_assert_eq!(files.set.keys().len(), files.set.values().len()); for (abs_path, flags) in files.set.keys().iter().zip(files.set.values().iter()) { @@ -3193,7 +3180,7 @@ pub mod bv2_impl { CssEntryPointMeta { imported_on_server: false, }, - )?; + ); } } } @@ -3223,7 +3210,7 @@ pub mod bv2_impl { self.graph.entry_points.reserve(num_entry_points); self.graph .input_files - .ensure_unused_capacity(num_entry_points)?; + .ensure_unused_capacity(num_entry_points); for key in data.files.keys() { let abs_path = key.abs_path(); @@ -3259,13 +3246,12 @@ pub mod bv2_impl { loader: Loader::Js, side_effects: bun_ast::SideEffects::NoSideEffectsPureData, ..Default::default() - })?; + }); // try this.graph.entry_points.append(arena, Index.runtime); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // OOM/capacity: fire-and-forget + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); self.path_to_source_index_map(self.transpiler.options.target) - .put(&b"bun:wrap"[..], Index::RUNTIME.get()) - .expect("oom"); + .put(&b"bun:wrap"[..], Index::RUNTIME.get()); // SAFETY: arena (`self.graph.heap`) outlives the bundle pass; coerce the // `&mut ParseTask` to `*mut` immediately so the `&self` borrow from // `arena()` ends before we take `&mut self` below. @@ -3287,7 +3273,7 @@ pub mod bv2_impl { fn clone_ast(&mut self) -> Result<(), Error> { let _trace = crate::perf::trace("Bundler.cloneAST"); - self.linker.graph.ast = self.graph.ast.clone()?; + self.linker.graph.ast = self.graph.ast.clone(); for module_scope in self.linker.graph.ast.items_module_scope_mut() { // `children` are arena-allocated `StoreRef`s; we re-point @@ -3576,14 +3562,14 @@ pub mod bv2_impl { known_target: options::Target, ) -> Result { let source_index = Index::init(u32::try_from(self.graph.ast.len()).expect("int cast")); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // OOM/capacity: fire-and-forget + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); self.graph.input_files.append(crate::Graph::InputFile { source: core::mem::take(source), loader, side_effects: loader.side_effects(), ..Default::default() - })?; + }); // `ParseTask::init` takes `bun_ast::Index`; both Index newtypes // are `repr(transparent)` u32 so reconstruct via `.get()`. // Arena-owned; freed on heap reset. @@ -3629,14 +3615,14 @@ pub mod bv2_impl { known_target: options::Target, ) -> Result { let source_index = Index::init(u32::try_from(self.graph.ast.len()).expect("int cast")); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // OOM/capacity: fire-and-forget + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); self.graph.input_files.append(crate::Graph::InputFile { source: core::mem::take(source), loader, side_effects: loader.side_effects(), ..Default::default() - })?; + }); // `core::mem::take` moved the real `Source` into `graph.input_files`, // leaving `*source` as `Default`. Read path/contents back from the // graph's stored copy (where the data now lives for the rest of the @@ -3743,8 +3729,8 @@ pub mod bv2_impl { loader: Loader::Js, side_effects: bun_ast::SideEffects::HasSideEffects, ..Default::default() - })?; - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // OOM/capacity: fire-and-forget + }); + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // `bun.new(ServerComponentParseTask, …)` — heap-owned by the // worker pool; freed via `bun.destroy` in `on_complete` after the @@ -3855,7 +3841,7 @@ pub mod bv2_impl { && path != b"bun" { if strings::is_npm_package_name_ignore_length(path) { - external_deps.insert(path)?; + external_deps.insert(path); } } } @@ -4455,7 +4441,7 @@ pub mod bv2_impl { // When it's not a file, this is a build error and we should report it. // we have no way of loading non-files. - let _ = log.add_error_fmt( + log.add_error_fmt( Some(source), bun_ast::Loc::EMPTY, format_args!( @@ -4477,7 +4463,7 @@ pub mod bv2_impl { let additional_files: &mut bun_alloc::AstVec = &mut this.graph.input_files.items_additional_files_mut() [source_index.get() as usize]; - let _ = additional_files + additional_files .push(crate::AdditionalFile::SourceIndex(source_index.get())); this.graph.input_files.items_side_effects_mut() [source_index.get() as usize] = @@ -4691,7 +4677,7 @@ pub mod bv2_impl { // // We have no way of loading non-files. if resolve.import_record.kind == ImportKind::EntryPointBuild { - let _ = log.add_error_fmt( + log.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -4703,7 +4689,7 @@ pub mod bv2_impl { } else { let source = &this.graph.input_files.items_source() [resolve.import_record.importer_source_index as usize]; - let _ = log.add_range_error_fmt( + log.add_range_error_fmt( Some(source), resolve.import_record.range, format_args!( @@ -4745,8 +4731,7 @@ pub mod bv2_impl { let (value_ptr, found_existing) = { let existing = this .path_to_source_index_map(resolve.import_record.original_target) - .get_or_put(path.text) - .expect("oom"); + .get_or_put(path.text); ( std::ptr::from_mut(existing.value_ptr), existing.found_existing, @@ -4773,26 +4758,23 @@ pub mod bv2_impl { // SAFETY: map slot from `get_or_put` above; map not mutated since. unsafe { *value_ptr = source_index.get() }; out_source_index = Some(source_index); - let _ = this.graph.ast.append(JSAst::empty_in(this.graph.heap)); // OOM/capacity: fire-and-forget + this.graph.ast.append(JSAst::empty_in(this.graph.heap)); let loader = path .loader(&this.transpiler.options.loaders) .unwrap_or(Loader::File); - this.graph - .input_files - .append(crate::Graph::InputFile { - source: bun_ast::Source { - // Shim to the field-identical `bun_paths::fs::Path<'static>`. - path: path_as_static(&path), - contents: std::borrow::Cow::Borrowed(&b""[..]), - index: bun_ast::Index(source_index.get()), - ..Default::default() - }, - loader, - side_effects: bun_ast::SideEffects::HasSideEffects, + this.graph.input_files.append(crate::Graph::InputFile { + source: bun_ast::Source { + // Shim to the field-identical `bun_paths::fs::Path<'static>`. + path: path_as_static(&path), + contents: std::borrow::Cow::Borrowed(&b""[..]), + index: bun_ast::Index(source_index.get()), ..Default::default() - }) - .expect("unreachable"); + }, + loader, + side_effects: bun_ast::SideEffects::HasSideEffects, + ..Default::default() + }); let task_val = ParseTask { // SAFETY: `from_mut(this)` is the live bundle (write provenance); // outlives the task. @@ -4877,12 +4859,11 @@ pub mod bv2_impl { { let entry = this .resolve_tasks_waiting_for_import_source_index - .get_or_put(resolve.import_record.importer_source_index) - .expect("oom"); + .get_or_put(resolve.import_record.importer_source_index); if !entry.found_existing { *entry.value_ptr = Vec::new(); } - let _ = entry.value_ptr.push(PendingImport { + entry.value_ptr.push(PendingImport { to_source_index: source_index, import_record_index: resolve.import_record.import_record_index, }); @@ -5352,10 +5333,8 @@ pub mod bv2_impl { // to routes in DevServer. They have a JS chunk too, // derived off of the import record list. if loaders[index] == Loader::Html { - html_files.put( - Index::init(u32::try_from(index).expect("int cast")), - (), - )?; + html_files + .put(Index::init(u32::try_from(index).expect("int cast")), ()); } else { js_files.push(Index::init(u32::try_from(index).expect("int cast"))); @@ -5382,10 +5361,7 @@ pub mod bv2_impl { continue; } - let gop = start - .css_entry_points - .get_or_put(record.source_index) - .expect("oom"); + let gop = start.css_entry_points.get_or_put(record.source_index); if target != Target::Browser { *gop.value_ptr = CssEntryPointMeta { imported_on_server: true, @@ -5416,7 +5392,7 @@ pub mod bv2_impl { CssEntryPointMeta { imported_on_server: false, }, - )?; + ); } } @@ -5468,7 +5444,7 @@ pub mod bv2_impl { let mut parts_live: Vec = Vec::with_capacity(parts_col.len()); for parts in parts_col { - parts_live.push(bun_collections::AutoBitSet::init_empty(parts.len())?); + parts_live.push(bun_collections::AutoBitSet::init_empty(parts.len())); } for &idx in js_reachable_files { parts_live[idx.get() as usize].set_all(true); @@ -5779,8 +5755,8 @@ pub mod bv2_impl { debug_assert!(self.graph.input_files.len() == 1); debug_assert!(self.graph.ast.len() == 1); - self.graph.ast.ensure_unused_capacity(2)?; - self.graph.input_files.ensure_unused_capacity(2)?; + self.graph.ast.ensure_unused_capacity(2); + self.graph.input_files.ensure_unused_capacity(2); // The statics are `LazyLock` and `Source` is not `Clone`, so // rebuild an owned `Source` from the static's clonable fields @@ -5796,15 +5772,13 @@ pub mod bv2_impl { ..Default::default() }; - // OOM/capacity: fire-and-forget - let _ = self.graph.input_files.append(crate::Graph::InputFile { + self.graph.input_files.append(crate::Graph::InputFile { source: server_source, loader: Loader::Js, side_effects: bun_ast::SideEffects::NoSideEffectsPureData, ..Default::default() }); - // OOM/capacity: fire-and-forget - let _ = self.graph.input_files.append(crate::Graph::InputFile { + self.graph.input_files.append(crate::Graph::InputFile { source: client_source, loader: Loader::Js, side_effects: bun_ast::SideEffects::NoSideEffectsPureData, @@ -5824,8 +5798,8 @@ pub mod bv2_impl { == Index::BAKE_CLIENT_DATA.get() ); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); Ok(()) } @@ -6171,8 +6145,7 @@ pub mod bv2_impl { continue; } - let resolve_entry = - resolve_queue.get_or_put(path_primary.text).expect("oom"); + let resolve_entry = resolve_queue.get_or_put(path_primary.text); if resolve_entry.found_existing { // SAFETY: arena-allocated `ParseTask` stored in the queue; arena outlives the pass. import_record.path = @@ -6545,7 +6518,7 @@ pub mod bv2_impl { import_record.kind = ImportKind::HtmlManifest; } - let resolve_entry = resolve_queue.get_or_put(path.text).expect("oom"); + let resolve_entry = resolve_queue.get_or_put(path.text); if resolve_entry.found_existing { // SAFETY: arena-allocated `ParseTask` stored in the queue; arena outlives the pass. import_record.path = @@ -6641,7 +6614,7 @@ pub mod bv2_impl { } else { self.graph.path_to_source_index_map(target) }; - let existing = map.get_or_put(key).expect("oom"); + let existing = map.get_or_put(key); ( existing.found_existing, std::ptr::from_mut::(existing.value_ptr), @@ -6681,11 +6654,8 @@ pub mod bv2_impl { diff += 1; - self.graph - .input_files - .append(new_input_file) - .expect("unreachable"); - let _ = self.graph.ast.append(JSAst::empty_in(self.graph.heap)); // OOM/capacity: fire-and-forget + self.graph.input_files.append(new_input_file); + self.graph.ast.append(JSAst::empty_in(self.graph.heap)); if is_html_entrypoint { self.ensure_client_transpiler(); @@ -6811,7 +6781,7 @@ pub mod bv2_impl { if let Some(compare) = get_redirect_id(ctx.redirect_import_record_index) { if compare == i as u32 { - let _ = path_to_source_index_map.put(ctx.source_path, source_index); // OOM-only Result + path_to_source_index_map.put(ctx.source_path, source_index); } } } @@ -6899,13 +6869,12 @@ pub mod bv2_impl { }; let fake_source_index = fake_input_file.source.index; - self.graph.input_files.append(fake_input_file)?; - let _ = self.graph.ast.append(ast_for_html_entrypoint); // OOM/capacity: fire-and-forget + self.graph.input_files.append(fake_input_file); + self.graph.ast.append(ast_for_html_entrypoint); import_record.source_index = Index::init(fake_source_index.0); - let _ = self - .path_to_source_index_map(target) - .put(path_text, fake_source_index.0); // OOM-only Result + self.path_to_source_index_map(target) + .put(path_text, fake_source_index.0); self.graph .html_imports .server_source_indices @@ -7167,7 +7136,7 @@ pub mod bv2_impl { is_client != is_browser } } { - Some(result.ast.named_exports.clone().expect("oom")) + Some(result.ast.named_exports.clone()) } else { None }; @@ -7278,18 +7247,14 @@ pub mod bv2_impl { this.graph .path_to_source_index_map(result_ast_target) - .put(source_path_text, reference_source_index) - .expect("oom"); + .put(source_path_text, reference_source_index); - this.graph - .server_component_boundaries - .put( - result_source_index as IndexInt, - result.use_directive, - reference_source_index, - ssr_index, - ) - .expect("oom"); + this.graph.server_component_boundaries.put( + result_source_index as IndexInt, + result.use_directive, + reference_source_index, + ssr_index, + ); } } parse_task::ResultValue::Err(err) => { diff --git a/src/bundler/cache.rs b/src/bundler/cache.rs index e500a858c7aa..c0d5f54fadd5 100644 --- a/src/bundler/cache.rs +++ b/src/bundler/cache.rs @@ -81,7 +81,7 @@ impl JavaScript { let parser = match js_parser::Parser::init(opts, &mut temp_log, source, defines, bump) { Ok(p) => p, Err(_) => { - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); return Ok(None); } }; @@ -99,12 +99,12 @@ impl JavaScript { if temp_log.errors == 0 { log.add_range_error(Some(source), bun_ast::Range::None, err.name().as_bytes()); } - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); return Ok(None); } }; - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); Ok(Some(result)) } @@ -128,14 +128,14 @@ impl JavaScript { let mut parser = match js_parser::Parser::init(opts, &mut temp_log, source, defines, bump) { Ok(p) => p, Err(_) => { - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); return Ok(()); } }; let res = parser.scan_imports(scan_pass_result); drop(parser); - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); res.map_err(Into::into) } } diff --git a/src/bundler/defines.rs b/src/bundler/defines.rs index 8897c2649eb2..9ae2f3cce90d 100644 --- a/src/bundler/defines.rs +++ b/src/bundler/defines.rs @@ -66,7 +66,7 @@ fn env_string_store_put( call_can_be_unwrapped_if_unused: bun_ast::E::CallUnwrap::IfUnused, ..Default::default() }); - store.get_or_put_value(key, data)?; + store.get_or_put_value(key, data); Ok(()) } diff --git a/src/bundler/lib.rs b/src/bundler/lib.rs index 20338efed2b8..7703a22b3eec 100644 --- a/src/bundler/lib.rs +++ b/src/bundler/lib.rs @@ -330,7 +330,7 @@ bun_dispatch::link_interface! { fn is_file_cached(abs_path: &[u8], side: bake_types::Graph) -> Option; fn asset_hash(abs_path: &[u8]) -> Option; fn current_bundle_start_data() -> *mut (); - fn register_barrel_with_deferrals(path: &[u8]) -> Result<(), crate::Error>; + fn register_barrel_with_deferrals(path: &[u8]); fn register_barrel_export(barrel_path: &[u8], alias: &[u8]); } } diff --git a/src/bundler/linker.rs b/src/bundler/linker.rs index ae95b8012f96..e31b01b1141f 100644 --- a/src/bundler/linker.rs +++ b/src/bundler/linker.rs @@ -333,9 +333,7 @@ impl Linker { // the `hashed_filenames` cache never dedups — every call interns a // fresh copy for the life of the process. Accepted: the `'static` // return contract forces a copy anyway, and the alternative (the old - // threadlocal slice return) was unsound. `dupe` also aborts on OOM - // where the old path propagated `?` — consistent with the - // `bun.handleOom` idiom for interner allocations. + // threadlocal slice return) was unsound. // Spec passes `file_path.text` even though the param is named // `basename`; preserved verbatim. let mut hash_name_buf = [0u8; 1024]; diff --git a/src/bundler/linker_context/MetafileBuilder.rs b/src/bundler/linker_context/MetafileBuilder.rs index 436ffeb60f29..1557b35ecf3c 100644 --- a/src/bundler/linker_context/MetafileBuilder.rs +++ b/src/bundler/linker_context/MetafileBuilder.rs @@ -217,7 +217,7 @@ pub(crate) fn generate(c: &mut LinkerContext, chunks: &mut [Chunk]) -> crate::Re let import_records_list = parse_graph.ast.items_import_records(); // Iterate through all files in chunks to collect unique source indices - let mut seen_sources = DynamicBitSet::init_empty(sources.len())?; + let mut seen_sources = DynamicBitSet::init_empty(sources.len()); // defer seen_sources.deinit() — handled by Drop // Mark all files that appear in chunks @@ -828,7 +828,7 @@ pub fn generate_markdown(metafile_json: &[u8]) -> crate::Result> { if let Some(bio) = mi_obj.get(b"bytesInOutput") { if let JsonValue::Integer(bio_int) = bio { let bytes_val: u64 = u64::try_from(*bio_int).expect("int cast"); - let gop = bytes_in_output.get_or_put(module_path)?; + let gop = bytes_in_output.get_or_put(module_path); if gop.found_existing { *gop.value_ptr += bytes_val; } else { @@ -944,7 +944,7 @@ pub fn generate_markdown(metafile_json: &[u8]) -> crate::Result> { } if let Some(key) = matched_key { - let gop = imported_by.get_or_put(key)?; + let gop = imported_by.get_or_put(key); if !gop.found_existing { *gop.value_ptr = Vec::new(); } diff --git a/src/bundler/linker_context/computeChunks.rs b/src/bundler/linker_context/computeChunks.rs index 362414a8cb4b..7205b7434c4f 100644 --- a/src/bundler/linker_context/computeChunks.rs +++ b/src/bundler/linker_context/computeChunks.rs @@ -94,7 +94,7 @@ pub(crate) fn compute_chunks( let entry_bits: AutoBitSet = { let eb = &mut this.graph.files.items_entry_bits_mut()[source_index as usize]; eb.set(entry_bit as usize); - eb.clone()? + eb.clone() }; let has_html_chunk = loaders[source_index as usize] == Loader::Html; @@ -104,7 +104,7 @@ pub(crate) fn compute_chunks( // reachable from other entry points (e.g., via re-exports), its content goes into // a shared chunk rather than staying in the entry point's chunk. // https://github.com/evanw/esbuild/blob/cd832972927f1f67b6d2cc895c06a8759c1cf309/internal/linker/linker.go#L3882 - let mut entry_point_chunk_bits = AutoBitSet::init_empty(this.graph.entry_points.len())?; + let mut entry_point_chunk_bits = AutoBitSet::init_empty(this.graph.entry_points.len()); entry_point_chunk_bits.set(entry_bit as usize); let js_chunk_key: &[u8] = 'brk: { @@ -124,11 +124,11 @@ pub(crate) fn compute_chunks( // Put this early on in this loop so that CSS-only entry points work. if has_html_chunk { - let html_chunk_entry = html_chunks.get_or_put(js_chunk_key)?; + let html_chunk_entry = html_chunks.get_or_put(js_chunk_key); if !html_chunk_entry.found_existing { *html_chunk_entry.value_ptr = Chunk { entry_point: chunk::EntryPoint::entry_point(source_index, entry_bit), - entry_bits: entry_point_chunk_bits.clone()?, + entry_bits: entry_point_chunk_bits.clone(), content: chunk::Content::Html, output_source_map: SourceMapPieces::init(), flags: make_flags( @@ -163,7 +163,7 @@ pub(crate) fn compute_chunks( } hasher.final_() }; - let css_chunk_entry = css_chunks.get_or_put(hash_to_use)?; + let css_chunk_entry = css_chunks.get_or_put(hash_to_use); if !css_chunk_entry.found_existing { // const css_chunk_entry = try js_chunks.getOrPut(); let order_len = order.len() as usize; @@ -192,7 +192,7 @@ pub(crate) fn compute_chunks( // Create a chunk for the entry point here to ensure that the chunk is // always generated even if the resulting file is empty - let js_chunk_entry = js_chunks.get_or_put(js_chunk_key)?; + let js_chunk_entry = js_chunks.get_or_put(js_chunk_key); entry_point_to_js_chunk_idx[entry_id_] = u32::try_from(js_chunk_entry.index).expect("int cast"); *js_chunk_entry.value_ptr = Chunk { @@ -238,7 +238,7 @@ pub(crate) fn compute_chunks( hasher.final_() }; - let css_chunk_entry = css_chunks.get_or_put(hash_to_use)?; + let css_chunk_entry = css_chunks.get_or_put(hash_to_use); if let chunk::Content::Javascript(js) = &mut js_chunk_entry.value_ptr.content { js.css_chunks = Box::<[u32]>::from( @@ -253,14 +253,12 @@ pub(crate) fn compute_chunks( ArrayHashMap::new(); for entry in order.slice() { if let chunk::CssImportOrderKind::SourceIndex(si) = &entry.kind { - css_files_with_parts_in_chunk - .put(si.get(), AtomicUsize::new(0)) - .expect("oom"); + css_files_with_parts_in_chunk.put(si.get(), AtomicUsize::new(0)); } } *css_chunk_entry.value_ptr = Chunk { entry_point: chunk::EntryPoint::entry_point(source_index, entry_bit), - entry_bits: entry_bits.clone()?, + entry_bits: entry_bits.clone(), content: chunk::Content::Css(chunk::CssChunk { imports_in_chunk_in_order: order, asts: (0..order_len) @@ -299,14 +297,14 @@ pub(crate) fn compute_chunks( if this.graph.code_splitting { let js_chunk_key = temp.alloc_slice_copy(entry_bits.bytes(this.graph.entry_points.len())); - let js_chunk_entry = js_chunks.get_or_put(js_chunk_key)?; + let js_chunk_entry = js_chunks.get_or_put(js_chunk_key); if !js_chunk_entry.found_existing { let is_browser_chunk_from_server_build = could_be_browser_target_from_server_build && ast_targets[source_index.get() as usize] == Target::Browser; *js_chunk_entry.value_ptr = Chunk { - entry_bits: entry_bits.clone()?, + entry_bits: entry_bits.clone(), entry_point: chunk::EntryPoint::non_entry_point( source_index.get(), 0, @@ -339,8 +337,7 @@ pub(crate) fn compute_chunks( let entry = js_chunk_entry .value_ptr .files_with_parts_in_chunk - .get_or_put(source_index.get() as u32) - .expect("unreachable"); + .get_or_put(source_index.get() as u32); if !entry.found_existing { *entry.value_ptr = AtomicUsize::new(0); // Initialize byte count to 0 } @@ -361,8 +358,7 @@ pub(crate) fn compute_chunks( let entry = c.chunks[chunk_idx as usize] .files_with_parts_in_chunk - .get_or_put(c.source_id as u32) - .expect("unreachable"); + .get_or_put(c.source_id as u32); if !entry.found_existing { *entry.value_ptr = AtomicUsize::new(0); // Initialize byte count to 0 } diff --git a/src/bundler/linker_context/computeCrossChunkDependencies.rs b/src/bundler/linker_context/computeCrossChunkDependencies.rs index dda39f997d37..c12c4613755f 100644 --- a/src/bundler/linker_context/computeCrossChunkDependencies.rs +++ b/src/bundler/linker_context/computeCrossChunkDependencies.rs @@ -181,7 +181,7 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { // include its hash when we're calculating the hashes of all // dependencies of this chunk. if other_chunk_index as usize != chunk_index { - let _ = chunk_meta.dynamic_imports.put(other_chunk_index, ()); // OOM-only Result + chunk_meta.dynamic_imports.put(other_chunk_index, ()); } } } @@ -249,7 +249,7 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { // be moved to a separate chunk than the use of a symbol even if // the definition and use of that symbol are originally from the // same source file. - let _ = chunk_meta.imports.put(ref_to_use, ()); // OOM-only Result + chunk_meta.imports.put(ref_to_use, ()); } } } @@ -292,7 +292,7 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { debug!("Cross-chunk export: {}", bstr::BStr::new(name),); } - let _ = chunk_meta.imports.put(target_ref, ()); // OOM-only Result + chunk_meta.imports.put(target_ref, ()); } } @@ -300,7 +300,7 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { // https://github.com/evanw/esbuild/blob/v0.27.2/internal/linker/linker.go#L1049-L1051 if flags.force_include_exports_for_entry_point { // result intentionally discarded - let _ = chunk_meta.imports.put( + chunk_meta.imports.put( deps.exports_refs[chunk.entry_point.source_index() as usize], (), ); @@ -310,7 +310,7 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { // https://github.com/evanw/esbuild/blob/v0.27.2/internal/linker/linker.go#L1053-L1056 if flags.wrap != WrapKind::None { // result intentionally discarded - let _ = chunk_meta.imports.put( + chunk_meta.imports.put( deps.wrapper_refs[chunk.entry_point.source_index() as usize], (), ); @@ -365,7 +365,7 @@ fn compute_cross_chunk_dependencies_with_chunk_metas( let entry = js.imports_from_other_chunks.get_or_put_value( other_chunk_index, CrossChunkImportItemList::default(), - )?; + ); entry.value_ptr.push(CrossChunkImportItem { r#ref: import_ref, ..Default::default() @@ -505,7 +505,7 @@ fn compute_cross_chunk_dependencies_with_chunk_metas( // `alias` points into the link-pass arena (see note above), // which outlives `exports_to_other_chunks`; `.slice()` re-borrows // under the StoreStr arena contract. - let _ = repr.exports_to_other_chunks.put(ref_, alias.slice()); // OOM-only Result + repr.exports_to_other_chunks.put(ref_, alias.slice()); } if clause_items.len() > 0 { diff --git a/src/bundler/linker_context/doStep5.rs b/src/bundler/linker_context/doStep5.rs index 6b84d757e84b..26032379d3a7 100644 --- a/src/bundler/linker_context/doStep5.rs +++ b/src/bundler/linker_context/doStep5.rs @@ -337,9 +337,7 @@ impl LinkerContext<'_> { }; for &other_part_index in other_parts { - let local = local_dependencies - .get_or_put(other_part_index) - .expect("unreachable"); + let local = local_dependencies.get_or_put(other_part_index); if !local.found_existing || *local.value_ptr != part_index_u32 { *local.value_ptr = part_index_u32; // note: if we crash on append, it is due to threadlocal heaps in mimalloc @@ -400,9 +398,7 @@ impl LinkerContext<'_> { bun_alloc::ArenaVec::::with_capacity_in(export_aliases.len(), arena); let mut ns_export_symbol_uses = PartSymbolUseMap::default(); - ns_export_symbol_uses - .ensure_total_capacity(export_aliases.len()) - .expect("OOM"); + ns_export_symbol_uses.ensure_total_capacity(export_aliases.len()); let initial_flags = *meta_flags; let needs_exports_variable = initial_flags.needs_exports_variable; @@ -557,12 +553,10 @@ impl LinkerContext<'_> { }, loc, )); - declared_symbols - .append(DeclaredSymbol { - ref_: exports_ref, - is_top_level: true, - }) - .expect("unreachable"); + declared_symbols.append(DeclaredSymbol { + ref_: exports_ref, + is_top_level: true, + }); } // "__export(exports, { foo: () => foo })" diff --git a/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs b/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs index 6b0315614506..121ec318b44c 100644 --- a/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs +++ b/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs @@ -264,7 +264,7 @@ impl<'a, 'ctx> FindImportedPartsVisitor<'a, 'ctx> { if source_index == Index::INVALID.value() { continue; } - let visited_entry = bun_core::handle_oom(self.visited.get_or_put(source_index)); + let visited_entry = self.visited.get_or_put(source_index); if visited_entry.found_existing { continue; } diff --git a/src/bundler/linker_context/findImportedCSSFilesInJSOrder.rs b/src/bundler/linker_context/findImportedCSSFilesInJSOrder.rs index e4b25a83c5b8..a4c43bafa3b2 100644 --- a/src/bundler/linker_context/findImportedCSSFilesInJSOrder.rs +++ b/src/bundler/linker_context/findImportedCSSFilesInJSOrder.rs @@ -30,7 +30,7 @@ pub(crate) fn find_imported_css_files_in_js_order( _temp: &Arena, entry_point: Index, ) -> Vec { - let mut visited = BitSet::init_empty(this.graph.files.len()).expect("oom"); + let mut visited = BitSet::init_empty(this.graph.files.len()); let mut order: Vec = Vec::new(); let all_import_records = this.graph.ast.items_import_records(); diff --git a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs index d301de5b5710..0f7a5041d8b0 100644 --- a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs +++ b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs @@ -4,7 +4,6 @@ use bstr::BStr; use bun_alloc::Arena; use bun_ast::{ImportKind, ImportRecord, ImportRecordFlags}; use bun_collections::{ArrayHashMap, StringArrayHashMap, VecExt}; -use bun_core::handle_oom; use crate::Graph::Graph; use crate::bun_css::css_parser::BundlerCssRule; @@ -396,7 +395,7 @@ pub(crate) fn find_imported_files_in_css_order<'a>( match &entry.kind { CssImportOrderKind::SourceIndex(idx) => { let idx = *idx; - let gop = handle_oom(source_index_duplicates.get_or_put(idx.get())); + let gop = source_index_duplicates.get_or_put(idx.get()); if !gop.found_existing { *gop.value_ptr = Vec::::default(); } @@ -424,7 +423,7 @@ pub(crate) fn find_imported_files_in_css_order<'a>( gop.value_ptr.push(i); } CssImportOrderKind::ExternalPath(p) => { - let gop = handle_oom(external_path_duplicates.get_or_put(p.text)); + let gop = external_path_duplicates.get_or_put(p.text); if !gop.found_existing { *gop.value_ptr = Vec::::default(); } diff --git a/src/bundler/linker_context/generateChunksInParallel.rs b/src/bundler/linker_context/generateChunksInParallel.rs index 536354800a08..411b8faca7aa 100644 --- a/src/bundler/linker_context/generateChunksInParallel.rs +++ b/src/bundler/linker_context/generateChunksInParallel.rs @@ -269,7 +269,7 @@ pub(crate) fn generate_chunks_in_parallel( let mut had_print_error = false; // Without code splitting a failing file is printed once per chunk // that includes it; report each file once. - let mut reported_sources = AutoBitSet::init_empty(c.parse_graph().input_files.len())?; + let mut reported_sources = AutoBitSet::init_empty(c.parse_graph().input_files.len()); for chunk in chunks.iter() { for compile_result in chunk.compile_results_for_chunk.iter() { let message: Cow<'static, [u8]> = match compile_result { @@ -362,7 +362,7 @@ pub(crate) fn generate_chunks_in_parallel( } let mut duplicates_map: StringArrayHashMap = StringArrayHashMap::default(); - let mut chunk_visit_map = AutoBitSet::init_empty(chunks.len())?; + let mut chunk_visit_map = AutoBitSet::init_empty(chunks.len()); // Compute the final hashes of each chunk, then use those to create the final // paths of each chunk. This can technically be done in parallel but it @@ -394,9 +394,9 @@ pub(crate) fn generate_chunks_in_parallel( .expect("write to Vec"); path::resolve_path::platform_to_posix_in_place::(&mut rel_path); - if path_names_map.get_or_put(&rel_path)?.found_existing { + if path_names_map.get_or_put(&rel_path).found_existing { // collect all duplicates in a list - let dup = duplicates_map.get_or_put(&rel_path)?; + let dup = duplicates_map.get_or_put(&rel_path); if !dup.found_existing { *dup.value_ptr = DuplicateEntry::default(); } @@ -520,7 +520,7 @@ pub(crate) fn generate_chunks_in_parallel( let mut resolved: Vec = Vec::new(); resolved.extend_from_slice(normalizer[0]); resolved.extend_from_slice(normalizer[1]); - let _ = unique_key_to_path.put(ch.unique_key, resolved.into_boxed_slice()); // OOM-only Result + unique_key_to_path.put(ch.unique_key, resolved.into_boxed_slice()); } } @@ -622,7 +622,7 @@ pub(crate) fn generate_chunks_in_parallel( // the chunk loop below. `c` outlives `static_route_visitor`. c: unsafe { bun_ptr::detach_lifetime_ref::(c) }, cache: bun_collections::ArrayHashMap::default(), - visited: AutoBitSet::init_empty(c.graph.files.len()).expect("oom"), + visited: AutoBitSet::init_empty(c.graph.files.len()), }; // defer static_route_visitor.deinit() — handled by Drop @@ -1125,7 +1125,7 @@ pub(crate) fn generate_chunks_in_parallel( // detached `&LinkerContext`; `log_disjoint` returns the // disjoint `Transpiler.log` backref so no `&mut c` is // materialized. - let _ = c.log_disjoint().add_error_fmt( + c.log_disjoint().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( diff --git a/src/bundler/linker_context/generateCodeForLazyExport.rs b/src/bundler/linker_context/generateCodeForLazyExport.rs index ff212dadb1ad..5c62085a4a17 100644 --- a/src/bundler/linker_context/generateCodeForLazyExport.rs +++ b/src/bundler/linker_context/generateCodeForLazyExport.rs @@ -90,7 +90,7 @@ pub(crate) fn generate_code_for_lazy_export( break 'size size + 1; }; - let mut inner_visited = BitSet::init_empty(size as usize)?; + let mut inner_visited = BitSet::init_empty(size as usize); // `defer inner_visited.deinit(...)` — handled by Drop. let mut composes_visited: ArrayHashMap = ArrayHashMap::new(); // `defer composes_visited.deinit()` — handled by Drop. diff --git a/src/bundler/linker_context/postProcessCSSChunk.rs b/src/bundler/linker_context/postProcessCSSChunk.rs index 0cd4822a0cf7..61c76d8e81ac 100644 --- a/src/bundler/linker_context/postProcessCSSChunk.rs +++ b/src/bundler/linker_context/postProcessCSSChunk.rs @@ -51,7 +51,7 @@ pub(crate) fn post_process_css_chunk( let mut compile_results_for_source_map: MultiArrayList = MultiArrayList::default(); - bun_core::handle_oom(compile_results_for_source_map.set_capacity(compile_results.len())); + compile_results_for_source_map.set_capacity(compile_results.len()); let sources: &[bun_ast::Source] = c.parse_graph().input_files.items_source(); for compile_result in compile_results.iter() { @@ -103,21 +103,19 @@ pub(crate) fn post_process_css_chunk( if let Some(source_map_chunk) = compile_result.source_map_chunk() { if c.options.source_maps != options::SourceMapOption::None { - bun_core::handle_oom(compile_results_for_source_map.append( - CompileResultForSourceMap { - // SAFETY: bitwise alias of `chunk.compile_results_for_chunk` - // (read-only and outlives this fn); see `postProcessJSChunk.rs`. - source_map_chunk: unsafe { source_map_chunk.alias() }, - // Guaranteed `Value` here - // because `source_maps != None` implies `line_offset` was - // initialised to `Value(_)` above. - generated_offset: match line_offset { - LineColumnOffsetOptional::Value(v) => v, - LineColumnOffsetOptional::Null => unreachable!(), - }, - source_index: compile_result.source_index(), + compile_results_for_source_map.append(CompileResultForSourceMap { + // SAFETY: bitwise alias of `chunk.compile_results_for_chunk` + // (read-only and outlives this fn); see `postProcessJSChunk.rs`. + source_map_chunk: unsafe { source_map_chunk.alias() }, + // Guaranteed `Value` here + // because `source_maps != None` implies `line_offset` was + // initialised to `Value(_)` above. + generated_offset: match line_offset { + LineColumnOffsetOptional::Value(v) => v, + LineColumnOffsetOptional::Null => unreachable!(), }, - )); + source_index: compile_result.source_index(), + }); } line_offset.reset(); diff --git a/src/bundler/linker_context/postProcessJSChunk.rs b/src/bundler/linker_context/postProcessJSChunk.rs index f503f3254274..ce85e2beb834 100644 --- a/src/bundler/linker_context/postProcessJSChunk.rs +++ b/src/bundler/linker_context/postProcessJSChunk.rs @@ -446,7 +446,7 @@ pub(crate) fn post_process_js_chunk( let mut compile_results_for_source_map: MultiArrayList = MultiArrayList::default(); - bun_core::handle_oom(compile_results_for_source_map.set_capacity(compile_results.len())); + compile_results_for_source_map.set_capacity(compile_results.len()); let show_comments = c.options.mode == LinkerOptionsMode::Bundle && !c.options.minify_whitespace; @@ -554,19 +554,17 @@ pub(crate) fn post_process_js_chunk( if let Some(source_map_chunk) = compile_result.source_map_chunk() { if c.options.source_maps != options::SourceMapOption::None { - bun_core::handle_oom(compile_results_for_source_map.append( - CompileResultForSourceMap { - // SAFETY: bitwise alias of `chunk.compile_results_for_chunk` - // (read-only and outlives this fn); slab-only MAL drop means - // the alias is never freed — original keeps the single owner. - source_map_chunk: unsafe { source_map_chunk.alias() }, - generated_offset: match line_offset { - SourceMap::LineColumnOffsetOptional::Value(v) => v, - SourceMap::LineColumnOffsetOptional::Null => Default::default(), - }, - source_index: compile_result.source_index(), + compile_results_for_source_map.append(CompileResultForSourceMap { + // SAFETY: bitwise alias of `chunk.compile_results_for_chunk` + // (read-only and outlives this fn); slab-only MAL drop means + // the alias is never freed — original keeps the single owner. + source_map_chunk: unsafe { source_map_chunk.alias() }, + generated_offset: match line_offset { + SourceMap::LineColumnOffsetOptional::Value(v) => v, + SourceMap::LineColumnOffsetOptional::Null => Default::default(), }, - )); + source_index: compile_result.source_index(), + }); } line_offset.reset(); diff --git a/src/bundler/linker_context/scanImportsAndExports.rs b/src/bundler/linker_context/scanImportsAndExports.rs index 5aabde2e113b..2e7ed4570926 100644 --- a/src/bundler/linker_context/scanImportsAndExports.rs +++ b/src/bundler/linker_context/scanImportsAndExports.rs @@ -1162,10 +1162,7 @@ impl DependencyWrapper<'_> { } // Avoid infinite loops due to cycles in the export star graph - let has_visited = self - .export_star_map - .get_or_put(source_index) - .expect("unreachable"); + let has_visited = self.export_star_map.get_or_put(source_index); if has_visited.found_existing { return false; } @@ -1308,9 +1305,7 @@ impl<'a> ExportStarContext<'a> { } } - let gop = col!(resolved_exports)[target_id] - .get_or_put(alias_slice) - .expect("oom"); + let gop = col!(resolved_exports)[target_id].get_or_put(alias_slice); if !gop.found_existing { // Initialize the re-export *gop.value_ptr = ExportData { @@ -1324,19 +1319,17 @@ impl<'a> ExportStarContext<'a> { // Make sure the symbol is marked as imported so that code splitting // imports it correctly if it ends up being shared with another chunk - col!(self.imports_to_bind)[source_index as usize] - .put( - name.ref_, - ImportData { - data: ImportTracker { - import_ref: name.ref_, - source_index: Index::source(other_source_index), - ..Default::default() - }, + col!(self.imports_to_bind)[source_index as usize].put( + name.ref_, + ImportData { + data: ImportTracker { + import_ref: name.ref_, + source_index: Index::source(other_source_index), ..Default::default() }, - ) - .expect("oom"); + ..Default::default() + }, + ); } else if gop.value_ptr.data.source_index.get() != other_source_index { // Two different re-exports colliding makes it potentially ambiguous gop.value_ptr @@ -1411,7 +1404,7 @@ mod __css_validation { let name_v = name.v(); if !other_css_ast.local_scope.contains(name_v) { // Split-borrow — see `LinkerContext::log_disjoint`. - let _ = this.log_disjoint().add_error_fmt( + this.log_disjoint().add_error_fmt( &col_ref!(input_files)[record.source_index.get() as usize], compose.loc, format_args!( @@ -1488,7 +1481,7 @@ mod __css_validation { source_index: IndexInt, range: bun_ast::Range, ) { - let entry = self.properties.get_or_put(property_name).expect("oom"); + let entry = self.properties.get_or_put(property_name); if !entry.found_existing { *entry.value_ptr = PropertyInFile { @@ -1511,7 +1504,7 @@ mod __css_validation { .original_name .slice(); - let _ = self.log.add_msg(bun_ast::Msg { + self.log.add_msg(bun_ast::Msg { kind: bun_ast::Kind::Err, data: bun_ast::range_data( Some(&col_ref!(self.all_sources)[source_index as usize]), @@ -1571,7 +1564,7 @@ mod __css_validation { if self.visited.contains(&r#ref) { return; } - self.visited.put(r#ref, ()).expect("unreachable"); + self.visited.put(r#ref, ()); // This local name was in a style rule that if let Some(composes) = ast.composes.get(&r#ref) { diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 52f350c1bb71..1d1e1e9396db 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -127,12 +127,12 @@ pub(crate) fn init_external_modules( match target { Target::Node => { // TODO: fix this stupid copy - let _ = result + result .node_modules .map .ensure_total_capacity(NODE_BUILTIN_PATTERNS.len()); for pattern in NODE_BUILTIN_PATTERNS { - result.node_modules.insert(pattern).expect("unreachable"); + result.node_modules.insert(pattern); } } Target::Bun => {} @@ -167,12 +167,12 @@ pub(crate) fn init_external_modules( suffix: Box::from(&external[i + 1..]), }); } else if bun_paths::is_package_path(external) { - result.node_modules.insert(external).expect("unreachable"); + result.node_modules.insert(external); } else { let normalized = validate_path(log, fs, cwd, external, b"external path"); if !normalized.is_empty() { - result.abs_paths.insert(&normalized).expect("unreachable"); + result.abs_paths.insert(&normalized); } } } @@ -305,19 +305,17 @@ impl TargetExt for Target { ]; if self == Target::Node { - exts.ensure_total_capacity(OUT_EXTENSIONS_LIST.len() * 2) - .expect("OOM"); + exts.ensure_total_capacity(OUT_EXTENSIONS_LIST.len() * 2); for &ext in OUT_EXTENSIONS_LIST { - exts.put_static_key(ext, b".mjs").expect("OOM"); + exts.put_static_key(ext, b".mjs"); } } else { - exts.ensure_total_capacity(OUT_EXTENSIONS_LIST.len() + 1) - .expect("OOM"); - exts.put_static_key(b".mjs", b".js").expect("OOM"); + exts.ensure_total_capacity(OUT_EXTENSIONS_LIST.len() + 1); + exts.put_static_key(b".mjs", b".js"); } for &ext in OUT_EXTENSIONS_LIST { - exts.put_static_key(ext, b".js").expect("OOM"); + exts.put_static_key(ext, b".js"); } exts @@ -778,10 +776,10 @@ impl ESMConditions { } pub fn clone(&self) -> Result { - let default = self.default.clone()?; - let import = self.import.clone()?; - let require = self.require.clone()?; - let style = self.style.clone()?; + let default = self.default.clone(); + let import = self.import.clone(); + let require = self.require.clone(); + let style = self.style.clone(); Ok(ESMConditions { default, @@ -915,8 +913,8 @@ pub(crate) fn defines_from_transform_options( Box::from(b"\"development\"".as_slice()) }; - user_defines.get_or_put_value(b"process.env.NODE_ENV", quoted_node_env.clone())?; - user_defines.get_or_put_value(b"process.env.BUN_ENV", quoted_node_env)?; + user_defines.get_or_put_value(b"process.env.NODE_ENV", quoted_node_env.clone()); + user_defines.get_or_put_value(b"process.env.BUN_ENV", quoted_node_env); // Automatically set `process.browser` to `true` for browsers and false for node+js // This enables some extra dead code elimination @@ -924,7 +922,7 @@ pub(crate) fn defines_from_transform_options( user_defines.get_or_put_value( default_user_defines::process_browser_define::KEY, Box::from(value.as_bytes()), - )?; + ); } } @@ -938,7 +936,7 @@ pub(crate) fn defines_from_transform_options( value: defines::DefineValue::EUndefined(Default::default()), ..Default::default() }), - )?; + ); } } @@ -1337,18 +1335,6 @@ pub struct BundleOptions<'a> { // bundle_v2.rs / transpiler.rs are unchanged. pub use bun_options_types::ForceNodeEnv; -/// Manual deep clone for `MacroRemap` (= `StringArrayHashMap>>`). -/// The inner map's `clone()` is an inherent fallible method (not `impl Clone`), -/// so the outer `StringArrayHashMap::::clone()` bound is unmet — -/// rebuild entrywise instead. -fn clone_macro_remap(src: &MacroRemap) -> MacroRemap { - let mut out = MacroRemap::default(); - for (k, v) in src.iter() { - bun_core::handle_oom(out.put(k, bun_core::handle_oom(v.clone()))); - } - out -} - impl<'a> BundleOptions<'a> { pub(crate) fn is_test(&self) -> bool { self.rewrite_jest_for_tests @@ -1395,8 +1381,8 @@ impl<'a> BundleOptions<'a> { bundler_feature_flags: self .bundler_feature_flags .as_deref() - .map(|s| Box::new(bun_core::handle_oom(s.clone()))), - loaders: bun_core::handle_oom(self.loaders.clone()), + .map(|s| Box::new(s.clone())), + loaders: self.loaders.clone(), jsx: self.jsx.clone(), emit_decorator_metadata: self.emit_decorator_metadata, experimental_decorators: self.experimental_decorators, @@ -1446,13 +1432,13 @@ impl<'a> BundleOptions<'a> { load_tsconfig_json: self.load_tsconfig_json, load_package_json: self.load_package_json, rewrite_jest_for_tests: self.rewrite_jest_for_tests, - macro_remap: clone_macro_remap(&self.macro_remap), + macro_remap: self.macro_remap.clone(), no_macros: self.no_macros, conditions: ESMConditions { - default: bun_core::handle_oom(self.conditions.default.clone()), - import: bun_core::handle_oom(self.conditions.import.clone()), - require: bun_core::handle_oom(self.conditions.require.clone()), - style: bun_core::handle_oom(self.conditions.style.clone()), + default: self.conditions.default.clone(), + import: self.conditions.import.clone(), + require: self.conditions.require.clone(), + style: self.conditions.style.clone(), }, tree_shaking: self.tree_shaking, tree_shaking_override: self.tree_shaking_override, diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index b34de7f8e6c2..71b7bab3cea1 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -739,7 +739,7 @@ impl<'a> Transpiler<'a> { // that inherited environment variables are always available // even when a parent directory is not readable. let was_production = self.options.production; - env.load_process()?; + env.load_process(); let has_production_env = env.is_production(); if !was_production && has_production_env { self.options.set_production(true); @@ -799,7 +799,7 @@ impl<'a> Transpiler<'a> { env.load(&dir, &env_files, suffix, skip_default_env)?; } DotEnvBehavior::disable => { - env.load_process()?; + env.load_process(); if env.is_production() { self.options.set_production(true); // See note in the `.prefix` arm. @@ -1087,9 +1087,9 @@ fn resolver_bundle_options_subset( css: ropts::owned_string_list(ropts::bundle_options::defaults::CSS_EXTENSION_ORDER), }, conditions: ropts::Conditions { - import: src.conditions.import.clone().expect("oom"), - require: src.conditions.require.clone().expect("oom"), - style: src.conditions.style.clone().expect("oom"), + import: src.conditions.import.clone(), + require: src.conditions.require.clone(), + style: src.conditions.style.clone(), }, external: src.external.clone(), extra_cjs_extensions: src.extra_cjs_extensions.clone(), @@ -1110,7 +1110,7 @@ fn resolver_bundle_options_subset( B::Import(p) => R::Import(p.clone()), B::Code(c) => R::Code(c.clone()), }; - m.put(k, rv).expect("oom"); + m.put(k, rv); } ropts::Framework { built_in_modules: m, @@ -1398,7 +1398,7 @@ impl<'a> Transpiler<'a> { let data_url = match DataURL::parse_without_check(path.text) { Ok(u) => u, Err(err) => { - let _ = log.add_error_fmt( + log.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -1413,7 +1413,7 @@ impl<'a> Transpiler<'a> { let body = match data_url.decode_data() { Ok(b) => b, Err(err) => { - let _ = log.add_error_fmt( + log.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -1451,7 +1451,7 @@ impl<'a> Transpiler<'a> { ) { Ok(e) => e, Err(err) => { - let _ = log.add_error_fmt( + log.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -1622,7 +1622,7 @@ impl<'a> Transpiler<'a> { .options .bundler_feature_flags .as_deref() - .and_then(|s| s.clone().ok().map(Box::new)); + .map(|s| Box::new(s.clone())); opts.features.repl_mode = self.options.repl_mode; // we'll just always enable top-level await @@ -1969,10 +1969,7 @@ fn parse_data_loader<'a>( continue; } - let visited = match duplicate_key_checker.get_or_put(name) { - Ok(v) => v, - Err(_) => continue, - }; + let visited = duplicate_key_checker.get_or_put(name); if visited.found_existing { decls[*visited.value_ptr as usize].value = Some(prop.value.expect("infallible: prop has value")); @@ -2150,7 +2147,7 @@ fn parse_md_loader<'a>( // `'bump` to `'static` for `E::String.data`). Ok(h) => unsafe { bun_ptr::detach_lifetime(arena.alloc_slice_copy(&h)) }, Err(_) => { - let _ = log.add_error_fmt( + log.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!("Failed to render markdown to HTML"), @@ -2200,7 +2197,7 @@ fn parse_wasm_loader<'a>( ) -> Option> { if target.is_bun() { if !source.is_web_assembly() { - let _ = log.add_error_fmt( + log.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -2857,21 +2854,7 @@ impl<'a> Transpiler<'a> { let experimental_decorators = resolve_result.flags.experimental_decorators(); let use_define_for_class_fields = resolve_result.flags.use_define_for_class_fields(); - // `MacroRemap` (StringArrayHashMap of StringArrayHashMap) has - // no nested `Clone` impl (the inner clone is fallible). - // Rebuild the outer map, deep-cloning - // each inner map (fallible), matching the build-command - // conversion. - let macro_remappings = { - let mut m = MacroRemap::default(); - for (k, v) in self.options.macro_remap.iter() { - let inner = v - .clone() - .map_err(|_| crate::Error::Alloc(bun_alloc::AllocError))?; - m.insert(k, inner); - } - m - }; + let macro_remappings = self.options.macro_remap.clone(); let parse_opts = ParseOptions { arena: self.arena, @@ -2999,7 +2982,7 @@ impl<'a> Transpiler<'a> { ) { Ok(e) => e, Err(err) => { - let _ = self.log_mut().add_error_fmt( + self.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -3045,7 +3028,7 @@ impl<'a> Transpiler<'a> { ) { Ok(v) => v, Err(e) => { - let _ = self.log_mut().add_error_fmt( + self.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!("{} parsing", e), diff --git a/src/collections/multi_array_list.rs b/src/collections/multi_array_list.rs index d6f002f4f3c1..e066d8cc9b00 100644 --- a/src/collections/multi_array_list.rs +++ b/src/collections/multi_array_list.rs @@ -53,6 +53,8 @@ use core::mem::{ManuallyDrop, MaybeUninit}; use core::ptr::{self, NonNull}; use std::alloc::{Allocator, Global}; +use bun_alloc::AllocError; + /// Declares typed column-accessor extension traits for a `MultiArrayList<$T>` /// element struct. /// @@ -1071,10 +1073,9 @@ impl MultiArrayList { /// Modify the array so that it can hold at least `new_capacity` items. pub fn ensure_total_capacity(&mut self, new_capacity: usize) { - if self.capacity >= new_capacity { - return; + if let Err(layout) = self.grow_to(new_capacity) { + std::alloc::handle_alloc_error(layout); } - self.set_capacity(grow_capacity::(self.capacity, new_capacity)); } /// Modify the array so that it can hold at least `additional_count` **more** items. @@ -1082,12 +1083,40 @@ impl MultiArrayList { self.ensure_total_capacity(self.len + additional_count); } + /// `Vec::try_reserve` analog of [`ensure_total_capacity`]: reports an + /// allocation failure instead of aborting. For reservations sized from + /// untrusted input (a source map's segment count, a lexer's line estimate) + /// where the caller turns the failure into an error for the user. + pub fn try_ensure_total_capacity(&mut self, new_capacity: usize) -> Result<(), AllocError> { + self.grow_to(new_capacity).map_err(|_| AllocError) + } + + /// [`try_ensure_total_capacity`] for `additional_count` **more** items. + pub fn try_ensure_unused_capacity( + &mut self, + additional_count: usize, + ) -> Result<(), AllocError> { + self.try_ensure_total_capacity(self.len + additional_count) + } + + fn grow_to(&mut self, new_capacity: usize) -> Result<(), Layout> { + if self.capacity >= new_capacity { + return Ok(()); + } + self.try_set_capacity(grow_capacity::(self.capacity, new_capacity)) + } + /// Modify the array so that it can hold exactly `new_capacity` items. /// `new_capacity` must be greater or equal to `len`. pub fn set_capacity(&mut self, new_capacity: usize) { + if let Err(layout) = self.try_set_capacity(new_capacity) { + std::alloc::handle_alloc_error(layout); + } + } + + fn try_set_capacity(&mut self, new_capacity: usize) -> Result<(), Layout> { debug_assert!(new_capacity >= self.len); - let new_bytes = aligned_alloc::(&self.alloc, layout_for::(new_capacity)) - .unwrap_or_else(|layout| std::alloc::handle_alloc_error(layout)); + let new_bytes = aligned_alloc::(&self.alloc, layout_for::(new_capacity))?; if self.len != 0 { let mut dst = Slice::::from_raw(new_bytes, self.len, new_capacity); dst.copy_rows_from(0, &self.slice(), self.len); @@ -1095,6 +1124,7 @@ impl MultiArrayList { self.free_allocated_bytes(); self.bytes = new_bytes; self.capacity = new_capacity; + Ok(()) } /// Create a copy of this list with a new backing store. This is a bitwise @@ -1237,9 +1267,10 @@ fn layout_for(capacity: usize) -> Option { Some(Layout::from_size_align(n, Reflected::::ALIGN).expect("MultiArrayList layout overflow")) } -/// On failure returns the `Layout` that could not be allocated: `set_capacity` -/// hands it to `handle_alloc_error` (the same path `Vec` takes, which the crash -/// handler reports as out-of-memory), `shrink_and_free` keeps the old buffer. +/// On failure returns the `Layout` that could not be allocated: the infallible +/// growers hand it to `handle_alloc_error` (the same path `Vec` takes, which +/// the crash handler reports as out-of-memory), the `try_` growers report it, +/// and `shrink_and_free` keeps the old buffer. fn aligned_alloc( alloc: &A, layout: Option, diff --git a/src/crash_handler/handle_oom.rs b/src/crash_handler/handle_oom.rs index 6cac4575f436..13b5b28cf543 100644 --- a/src/crash_handler/handle_oom.rs +++ b/src/crash_handler/handle_oom.rs @@ -25,11 +25,10 @@ use bun_alloc::AllocError; /// let thing = match allocate_thing() { Ok(v) => v, Err(err) => bun::handle_oom(err) }; /// ``` /// -/// In Rust, `Vec`/`Box` allocation already aborts on OOM via the -/// global allocator's `handle_alloc_error`. Per PORTING.md §Allocators, -/// callsites of `bun.handleOom(expr)` translate to bare `expr`. This function -/// remains for the residual cases where a `Result` is threaded -/// explicitly. +/// In Rust, `Vec`/`Box` allocation already aborts on OOM via the global +/// allocator's `handle_alloc_error`, so most call sites should be a bare +/// `expr`. This function remains for the residual cases where a +/// `Result` is still threaded explicitly. pub fn handle_oom(error_union_or_set: A) -> A::Output { error_union_or_set.handle_oom() } diff --git a/src/css/css_modules.rs b/src/css/css_modules.rs index c342a548d35e..a53e8bff1527 100644 --- a/src/css/css_modules.rs +++ b/src/css/css_modules.rs @@ -166,7 +166,7 @@ impl<'a> CssModule<'a> { let mut k = BumpVec::with_capacity_in(2 + the_hash.len(), bump); k.extend_from_slice(b"--"); k.extend_from_slice(the_hash); - let _ = self.references.put(k.into_bump_slice(), reference); + self.references.put(k.into_bump_slice(), reference); Some(the_hash) } diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index 71d84c513cf2..559e7e1d716d 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -3069,7 +3069,7 @@ impl<'a> Parser<'a> { // Borrowed probe so a repeated class/id name doesn't box a fresh key // per selector; `StringArrayHashMap::get_or_put` boxes on miss only. - let gop = local_scope.get_or_put(name).expect("unreachable"); + let gop = local_scope.get_or_put(name); let entry = gop.value_ptr; if gop.found_existing { let prev_tag = entry.ref_.tag(); diff --git a/src/css/declaration.rs b/src/css/declaration.rs index 9ced7a46cd18..50cfcb5911cc 100644 --- a/src/css/declaration.rs +++ b/src/css/declaration.rs @@ -412,11 +412,6 @@ impl<'bump> DeclarationHandler<'bump> { if let Some(direction) = self.direction.take() { self.decls.push(css::Property::Direction(direction)); } - // if (this.unicode_bidi) |unicode_bidi| { - // this.unicode_bidi = null; - // this.decls.append(context.arena, css.Property{ .unicode_bidi = unicode_bidi }) catch |err| bun.handleOom(err); - // } - self.background.finalize(&mut self.decls, context); self.border.finalize(&mut self.decls, context); self.flex.finalize(&mut self.decls, context); diff --git a/src/css/rules/supports.rs b/src/css/rules/supports.rs index e4e658649cc2..c9da81ada6cc 100644 --- a/src/css/rules/supports.rs +++ b/src/css/rules/supports.rs @@ -282,7 +282,7 @@ impl SupportsCondition { if let SupportsCondition::Declaration(decl) = &in_parens { let property_id = &decl.property_id; let value = decl.value; - let _ = seen_declarations.put( + seen_declarations.put( SeenDeclKey( property_id.with_prefix(css::VendorPrefix::NONE), value, @@ -305,7 +305,7 @@ impl SupportsCondition { d.property_id.add_prefix(property_id.prefix()); } } else { - let _ = seen_declarations.put(key, conditions.len()); + seen_declarations.put(key, conditions.len()); conditions.push(SupportsCondition::Declaration(Declaration { property_id, value, diff --git a/src/css/values/ident.rs b/src/css/values/ident.rs index 3cd4b213261b..782192d9920f 100644 --- a/src/css/values/ident.rs +++ b/src/css/values/ident.rs @@ -305,7 +305,6 @@ impl IdentOrRef { #[cfg(debug_assertions)] let this = { let (slice, bump) = debug_ident; - // bun.handleOom(arena.create(...)) → arena alloc; OOM aborts let heap_ptr: &mut *const [u8] = bump.alloc(std::ptr::from_ref::<[u8]>(slice)); let addr = std::ptr::from_mut::<*const [u8]>(heap_ptr) as usize as u64; debug_assert!(addr & (1u64 << 63) == 0); diff --git a/src/event_loop/AnyEventLoop.rs b/src/event_loop/AnyEventLoop.rs index d237e2f42331..dfcd7c11e18e 100644 --- a/src/event_loop/AnyEventLoop.rs +++ b/src/event_loop/AnyEventLoop.rs @@ -505,9 +505,7 @@ impl EventLoopHandle { } } - pub fn create_null_delimited_env_map( - self, - ) -> Result { + pub fn create_null_delimited_env_map(self) -> bun_dotenv::NullDelimitedEnvMap { match self { EventLoopHandle::Js { owner } => owner.create_null_delimited_env_map(), EventLoopHandle::Mini(mini) => { diff --git a/src/event_loop/lib.rs b/src/event_loop/lib.rs index afa323575731..2088ec680732 100644 --- a/src/event_loop/lib.rs +++ b/src/event_loop/lib.rs @@ -65,7 +65,7 @@ bun_dispatch::link_interface! { fn js_poster() -> any_event_loop::JsPoster; fn env() -> *mut bun_dotenv::Loader; fn top_level_dir() -> *const [u8]; - fn create_null_delimited_env_map() -> Result; + fn create_null_delimited_env_map() -> bun_dotenv::NullDelimitedEnvMap; } } diff --git a/src/http/AsyncHTTP.rs b/src/http/AsyncHTTP.rs index 970c61bbe591..c58170dff04f 100644 --- a/src/http/AsyncHTTP.rs +++ b/src/http/AsyncHTTP.rs @@ -425,7 +425,7 @@ impl<'a> AsyncHTTP<'a> { url.clone(), // Note: the same `headers` value goes in both `AsyncHTTP.request_headers` // and `client.header_entries`; `MultiArrayList` owns its allocation, so clone here. - headers.clone().expect("OOM"), + headers.clone(), headers_buf, options.hostname, signals, diff --git a/src/http/HTTPThread.rs b/src/http/HTTPThread.rs index 09e3273ccbf4..a58011d0f60a 100644 --- a/src/http/HTTPThread.rs +++ b/src/http/HTTPThread.rs @@ -558,7 +558,7 @@ impl HttpThread { let now = self.timer_read(); let ctx_nn = NonNull::from(&mut *custom_context); - let _ = custom_ssl_context_map().put( + custom_ssl_context_map().put( requested_config, SslContextCacheEntry { ctx: ctx_nn, diff --git a/src/http/HeaderBuilder.rs b/src/http/HeaderBuilder.rs index 1de5b666a697..d41d7bfc21e3 100644 --- a/src/http/HeaderBuilder.rs +++ b/src/http/HeaderBuilder.rs @@ -20,7 +20,7 @@ impl HeaderBuilder { pub fn allocate(&mut self) -> Result<(), AllocError> { self.content.allocate()?; self.entries - .ensure_total_capacity(self.header_count as usize)?; + .ensure_total_capacity(self.header_count as usize); Ok(()) } diff --git a/src/http/Headers.rs b/src/http/Headers.rs index aed96bbed638..675bd7115f9a 100644 --- a/src/http/Headers.rs +++ b/src/http/Headers.rs @@ -37,10 +37,7 @@ impl HeadersExt for Headers { for header in headers { buf_len += header.name().len() + header.value().len(); } - result - .entries - .ensure_total_capacity(header_count) - .expect("OOM"); + result.entries.ensure_total_capacity(header_count); result.buf.reserve_exact(buf_len); for header in headers { let name = header.name(); diff --git a/src/http/h2_client/ClientSession.rs b/src/http/h2_client/ClientSession.rs index 580af0a9510c..98a62c912fc4 100644 --- a/src/http/h2_client/ClientSession.rs +++ b/src/http/h2_client/ClientSession.rs @@ -531,9 +531,9 @@ impl ClientSession { super::live_streams.fetch_add(1, Ordering::Relaxed); self.next_stream_id = self.next_stream_id.saturating_add(2); let stream_ref = stream_mut(stream); - let _ = self.streams.put(stream_ref.id, stream); + self.streams.put(stream_ref.id, stream); if let Some(id) = async_http_id { - let _ = self.by_http_id.put(id, stream); + self.by_http_id.put(id, stream); } client.h2 = NonNull::new(stream); client.flags.protocol = Protocol::Http2; diff --git a/src/http/h3_client/AltSvc.rs b/src/http/h3_client/AltSvc.rs index 208498c59e30..7c8c1bfed16c 100644 --- a/src/http/h3_client/AltSvc.rs +++ b/src/http/h3_client/AltSvc.rs @@ -201,7 +201,7 @@ pub(crate) fn record(origin_host: &[u8], origin_port: u16, field_value: &[u8]) { } } // `StringHashMap::put` dupes the key on insert. - let _ = cache().put( + cache().put( k, Record { h3_port: entry.port, diff --git a/src/http/lib.rs b/src/http/lib.rs index 57bfb2fccb51..99c572cda70b 100644 --- a/src/http/lib.rs +++ b/src/http/lib.rs @@ -1770,7 +1770,7 @@ impl<'a> HTTPClient<'a> { uws::AnySocket::SocketTcp(uws::SocketTCP::from_any(socket.socket)) }; // SAFETY: HTTP-thread only; per-statement reborrow. - let _ = abort_tracker().put(self.async_http_id, any); + abort_tracker().put(self.async_http_id, any); } } @@ -5203,7 +5203,7 @@ impl<'a> HTTPClient<'a> { .get_ascii_case_insensitive(name) .is_some() { - let _ = self.header_entries.ordered_remove(i); + self.header_entries.ordered_remove(i); } else { i += 1; } @@ -5231,7 +5231,7 @@ impl<'a> HTTPClient<'a> { .get_ascii_case_insensitive(name) .is_some() { - let _ = self.header_entries.ordered_remove(i); + self.header_entries.ordered_remove(i); } else { i += 1; } diff --git a/src/http_jsc/headers_jsc.rs b/src/http_jsc/headers_jsc.rs index f23dd12bdcb8..d80533bca5ad 100644 --- a/src/http_jsc/headers_jsc.rs +++ b/src/http_jsc/headers_jsc.rs @@ -49,13 +49,7 @@ pub fn from_fetch_headers( } false }; - if headers - .entries - .ensure_total_capacity(header_count as usize) - .is_err() - { - bun_alloc::out_of_memory(); - } + headers.entries.ensure_total_capacity(header_count as usize); // SAFETY: capacity reserved above; columns are `StringPointer` (POD) and fully // overwritten by `copy_to` / the explicit writes below before any read. unsafe { headers.entries.set_len(header_count as usize) }; diff --git a/src/ini/lib.rs b/src/ini/lib.rs index c8b8f1e57c36..45aff3eca909 100644 --- a/src/ini/lib.rs +++ b/src/ini/lib.rs @@ -1563,7 +1563,7 @@ mod draft { // The single `install.scoped = registry_map` write-back happens at // the bottom of `load_npmrc` after the registry-configuration // block has finished mutating `registry_map`. - registry_map.scopes.ensure_unused_capacity(scope_count)?; + registry_map.scopes.ensure_unused_capacity(scope_count); iter.prop_idx = 0; iter.count = false; @@ -1571,7 +1571,7 @@ mod draft { while let Some(val) = iter.next()? { if let Some(result) = val.get() { let registry = result.registry.clone(); - registry_map.scopes.put(&*result.scope, registry)?; + registry_map.scopes.put(&*result.scope, registry); } } } diff --git a/src/install/NetworkTask.rs b/src/install/NetworkTask.rs index 615177ac1646..d323bc7c9f0c 100644 --- a/src/install/NetworkTask.rs +++ b/src/install/NetworkTask.rs @@ -632,7 +632,7 @@ impl NetworkTask { offset: "Accept".len() as u32, length: (header_buf.len() - "Accept".len()) as u32, }, - })?; + }); header_builder.header_count = 1; self.header_buf = Box::default(); header_buf.as_bytes() diff --git a/src/install/PackageInstaller.rs b/src/install/PackageInstaller.rs index 6c96867f593b..422790ebb64c 100644 --- a/src/install/PackageInstaller.rs +++ b/src/install/PackageInstaller.rs @@ -768,7 +768,7 @@ impl<'a> PackageInstaller<'a> { } for dep_id in deferred { - tree.binaries.add(dep_id).unwrap_or_oom(); + tree.binaries.add(dep_id); } } @@ -1087,7 +1087,7 @@ impl<'a> PackageInstaller<'a> { // fixes an assertion failure where a transitive dependency is a git dependency newly added to the lockfile after the list of dependencies has been resized // this assertion failure would also only happen after the lockfile has been written to disk and the summary is being printed. if self.successfully_installed.bit_length() < self.lockfile().packages.len() { - let new = Bitset::init_empty(self.lockfile().packages.len()).unwrap_or_oom(); + let new = Bitset::init_empty(self.lockfile().packages.len()); let old = core::mem::replace(&mut self.successfully_installed, new); old.copy_into(&mut self.successfully_installed); // `defer old.deinit(bun.default_allocator)` — Bitset impls Drop. @@ -1925,8 +1925,7 @@ impl<'a> PackageInstaller<'a> { if self.bins[package_id as usize].tag != bin::Tag::None { self.trees[self.current_tree_id as usize] .binaries - .add(dependency_id) - .unwrap_or_oom(); + .add(dependency_id); } let dep = @@ -2022,8 +2021,7 @@ impl<'a> PackageInstaller<'a> { .put( trusted_name_hash, Box::<[u8]>::from(trusted_name.slice(string_buf!())), - ) - .unwrap_or_oom(); + ); } } } @@ -2063,8 +2061,7 @@ impl<'a> PackageInstaller<'a> { let entry = self .summary .packages_with_blocked_scripts - .get_or_put(truncated_dep_name_hash) - .unwrap_or_oom(); + .get_or_put(truncated_dep_name_hash); if !entry.found_existing { *entry.value_ptr = 0; } @@ -2244,8 +2241,7 @@ impl<'a> PackageInstaller<'a> { if self.bins[package_id as usize].tag != bin::Tag::None { self.trees[self.current_tree_id as usize] .binaries - .add(dependency_id) - .unwrap_or_oom(); + .add(dependency_id); } // reshaped for borrowck — `LazyPackageDestinationDir` borrows @@ -2363,8 +2359,7 @@ impl<'a> PackageInstaller<'a> { .put( trusted_name_hash, Box::<[u8]>::from(trusted_name.slice(string_buf!())), - ) - .unwrap_or_oom(); + ); } } } diff --git a/src/install/PackageManager.rs b/src/install/PackageManager.rs index e1524675ffb9..789ca8d2a032 100644 --- a/src/install/PackageManager.rs +++ b/src/install/PackageManager.rs @@ -1082,7 +1082,7 @@ fn configure_env_for_scripts_run( // `Ok` — same contract as the runtime impl (run_command.rs:628). let this_transpiler = unsafe { this_transpiler_slot.assume_init() }; - let init_cwd_entry = this.env_mut().map.get_or_put_without_value(b"INIT_CWD")?; + let init_cwd_entry = this.env_mut().map.get_or_put_without_value(b"INIT_CWD"); if !init_cwd_entry.found_existing { *init_cwd_entry.value_ptr = dot_env::HashTableValue { value: Box::<[u8]>::from(strings::without_trailing_slash( @@ -1105,10 +1105,7 @@ fn configure_env_for_scripts_run( if !t_env.has(b"JOBS") { let mut int_buf = bun_core::fmt::ItoaBuf::new(); let jobs_str = bun_core::fmt::itoa(&mut int_buf, thread_count); - t_env - .map - .put_alloc_value(b"JOBS", jobs_str) - .expect("unreachable"); + t_env.map.put_alloc_value(b"JOBS", jobs_str); } } } @@ -1116,9 +1113,8 @@ fn configure_env_for_scripts_run( { let mut node_path = PathBuffer::uninit(); if let Some(node_path_z) = this.env_mut().get_node_path(paths_fs, &mut node_path) { - let _ = this - .env_mut() - .load_node_js_config(paths_fs, node_path_z.as_ref())?; + this.env_mut() + .load_node_js_config(paths_fs, node_path_z.as_ref()); } else { 'brk: { let current_path = this.env().get(b"PATH").unwrap_or(b""); @@ -1130,8 +1126,8 @@ fn configure_env_for_scripts_run( { break 'brk; } - this.env_mut().map.put(b"PATH", &path_var)?; - let _ = this.env_mut().load_node_js_config(paths_fs, bun_path)?; + this.env_mut().map.put(b"PATH", &path_var); + this.env_mut().load_node_js_config(paths_fs, bun_path); } } } @@ -1243,7 +1239,7 @@ fn ensure_temp_node_gyp_script_run(manager: &mut PackageManager) -> Result<(), E path_var.extend_from_slice(strings::without_trailing_slash(tempdir.name)); path_var.push(SEP); path_var.extend_from_slice(&manager.node_gyp_tempdir_name); - manager.env_mut().map.put(b"PATH", &path_var)?; + manager.env_mut().map.put(b"PATH", &path_var); let path_buf_len = path_buf.len(); let mut cursor = &mut path_buf[..]; @@ -1265,7 +1261,7 @@ fn ensure_temp_node_gyp_script_run(manager: &mut PackageManager) -> Result<(), E manager .env_mut() .map - .put_alloc_key_and_value(b"BUN_WHICH_IGNORE_CWD", node_gyp_abs_dir)?; + .put_alloc_key_and_value(b"BUN_WHICH_IGNORE_CWD", node_gyp_abs_dir); Ok(()) } @@ -1876,7 +1872,7 @@ pub fn init( &mut *loader_ptr }; - env.load_process()?; + env.load_process(); // Copy the listing's basenames out under `entries_mutex`; `.data` must // only be probed while the lock is held. let env_probe_keys = { @@ -2169,7 +2165,7 @@ pub fn init( abs_path: Box::<[u8]>::from(&*normalized), resolution: FolderResolution::PackageId(0), }, - )?; + ); // normalized.deinit() → Drop (stack buffer) } diff --git a/src/install/PackageManager/PackageJSONEditor.rs b/src/install/PackageManager/PackageJSONEditor.rs index 88773115f6a9..354f31b0ad77 100644 --- a/src/install/PackageManager/PackageJSONEditor.rs +++ b/src/install/PackageManager/PackageJSONEditor.rs @@ -500,7 +500,7 @@ fn edit_update_entries( // Capture the literal as an owned // copy before borrowing `updating_packages` mutably. let version_literal_owned = Box::<[u8]>::from(version_literal); - let entry = updating_packages.get_or_put(key_str)?; + let entry = updating_packages.get_or_put(key_str); // If a dependency is present in more than one dependency group, only one of it's versions // will be updated. The group is determined by the order of `dependency_groups`, the same @@ -833,7 +833,7 @@ impl CatalogInfoIndex { fn init(infos: &[CatalogUpdateInfo]) -> Result { let mut map = StringArrayHashMap::>::with_capacity(infos.len()); for (i, info) in infos.iter().enumerate() { - map.get_or_put(&info.dep_name)?.value_ptr.push(i); + map.get_or_put(&info.dep_name).value_ptr.push(i); } Ok(CatalogInfoIndex(map)) } @@ -1036,7 +1036,7 @@ pub(crate) fn edit( let version_literal_owned = Box::<[u8]>::from(version_literal); let entry = - manager.updating_packages.get_or_put(name)?; + manager.updating_packages.get_or_put(name); // first come, first serve if entry.found_existing { diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index 27a884a4a4ee..151e8e905ade 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -96,8 +96,7 @@ pub fn enqueue_dependency_list( dependencies_list: Lockfile::DependencySlice, ) { this.task_queue - .ensure_unused_capacity(dependencies_list.len as usize) - .expect("unreachable"); + .ensure_unused_capacity(dependencies_list.len as usize); // Step 1. Go through main dependencies let end = dependencies_list.off.saturating_add(dependencies_list.len); @@ -158,7 +157,7 @@ pub fn enqueue_tarball_for_download( if this.network_task_has_failed(task_id) { return Err(EnqueueTarballForDownloadError::AlreadyFailed); } - let task_queue = this.task_queue.get_or_put(task_id)?; + let task_queue = this.task_queue.get_or_put(task_id); if !task_queue.found_existing { *task_queue.value_ptr = TaskCallbackList::default(); } @@ -214,7 +213,7 @@ pub fn enqueue_tarball_for_reading( // filename store before any append. let path = this.lockfile.str_detached(resolution.local_tarball()); let task_id = Task::Id::for_tarball(path); - let task_queue = this.task_queue.get_or_put(task_id).expect("unreachable"); + let task_queue = this.task_queue.get_or_put(task_id); if !task_queue.found_existing { *task_queue.value_ptr = TaskCallbackList::default(); } @@ -261,10 +260,7 @@ pub fn enqueue_git_for_checkout( let clone_id = Task::Id::for_git_clone(url); let resolved = this.lockfile.str_detached(&repository.resolved); let checkout_id = Task::Id::for_git_checkout(url, resolved); - let checkout_queue = this - .task_queue - .get_or_put(checkout_id) - .expect("unreachable"); + let checkout_queue = this.task_queue.get_or_put(checkout_id); if !checkout_queue.found_existing { *checkout_queue.value_ptr = TaskCallbackList::default(); } @@ -288,7 +284,7 @@ pub fn enqueue_git_for_checkout( ); this.task_batch.push(ThreadPool::Batch::from(task)); } else { - let clone_queue = this.task_queue.get_or_put(clone_id).expect("unreachable"); + let clone_queue = this.task_queue.get_or_put(clone_id); if !clone_queue.found_existing { *clone_queue.value_ptr = TaskCallbackList::default(); } @@ -357,7 +353,7 @@ pub fn enqueue_package_for_download( if this.network_task_has_failed(task_id) { return Err(EnqueuePackageForDownloadError::AlreadyFailed); } - let task_queue = this.task_queue.get_or_put(task_id)?; + let task_queue = this.task_queue.get_or_put(task_id); if !task_queue.found_existing { *task_queue.value_ptr = TaskCallbackList::default(); } @@ -1076,7 +1072,7 @@ pub fn enqueue_dependency_with_main_and_success_fn( { let package_name = this.lockfile.str(&name); let min_age_seconds = min_age_ms / MS_PER_S; - let _ = this.log_mut().add_error_fmt( + this.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -1171,8 +1167,7 @@ pub fn enqueue_dependency_with_main_and_success_fn( return Ok(()); } - let manifest_entry_parse = - this.task_queue.get_or_put_context(task_id, ())?; + let manifest_entry_parse = this.task_queue.get_or_put_context(task_id, ()); if !manifest_entry_parse.found_existing { *manifest_entry_parse.value_ptr = TaskCallbackList::default(); } @@ -1262,10 +1257,7 @@ pub fn enqueue_dependency_with_main_and_success_fn( } } - let entry = this - .task_queue - .get_or_put_context(checkout_id, ()) - .expect("unreachable"); + let entry = this.task_queue.get_or_put_context(checkout_id, ()); if !entry.found_existing { *entry.value_ptr = TaskCallbackList::default(); } @@ -1296,10 +1288,7 @@ pub fn enqueue_dependency_with_main_and_success_fn( ); this.task_batch.push(ThreadPool::Batch::from(task)); } else { - let entry = this - .task_queue - .get_or_put_context(clone_id, ()) - .expect("unreachable"); + let entry = this.task_queue.get_or_put_context(clone_id, ()); if !entry.found_existing { *entry.value_ptr = TaskCallbackList::default(); } @@ -1363,10 +1352,7 @@ pub fn enqueue_dependency_with_main_and_success_fn( // `this.task_queue`; scope it tightly so the calls below can // reborrow `*this`. { - let entry = this - .task_queue - .get_or_put_context(task_id, ()) - .expect("unreachable"); + let entry = this.task_queue.get_or_put_context(task_id, ()); if !entry.found_existing { *entry.value_ptr = TaskCallbackList::default(); } @@ -1567,10 +1553,7 @@ pub fn enqueue_dependency_with_main_and_success_fn( }; // reshaped for borrowck — scope `entry` tightly. { - let entry = this - .task_queue - .get_or_put_context(task_id, ()) - .expect("unreachable"); + let entry = this.task_queue.get_or_put_context(task_id, ()); if !entry.found_existing { *entry.value_ptr = TaskCallbackList::default(); } diff --git a/src/install/PackageManager/PackageManagerLifecycle.rs b/src/install/PackageManager/PackageManagerLifecycle.rs index 63730f9876a4..f8c2ae16650d 100644 --- a/src/install/PackageManager/PackageManagerLifecycle.rs +++ b/src/install/PackageManager/PackageManagerLifecycle.rs @@ -6,7 +6,7 @@ use bstr::BStr; use bun_collections::ArrayHashMap; use bun_core::fmt::PathSep; -use bun_core::{Output, ZBox, fmt as bun_fmt, handle_oom}; +use bun_core::{Output, ZBox, fmt as bun_fmt}; use bun_core::{ZStr, strings}; use bun_paths::resolve_path::{join_abs_string_z, platform}; use bun_paths::{AutoAbsPath, EnvPath}; @@ -365,7 +365,7 @@ impl PackageManager { let this_transpiler = self.configure_env_for_scripts(ctx, log_level)?; let env_loader = this_transpiler.env_mut(); - let mut script_env = env_loader.map.clone_with_allocator()?; + let mut script_env = env_loader.map.clone(); // `defer script_env.map.deinit()` — handled by Drop // `script_env.put` below needs `&mut`; copy PATH out so the @@ -390,13 +390,13 @@ impl PackageManager { } path.append(original_path.as_slice())?; - script_env.put(b"PATH", path.slice())?; + script_env.put(b"PATH", path.slice()); // Ownership transfers to `LifecycleScriptSubprocess`, which // re-uses it across every `spawn_next_script` in the chain. Move the // owning `NullDelimitedEnvMap` by value so its `K=V\0` buffers outlive // this stack frame (freed by the subprocess's `Drop`). - let envp = script_env.create_null_delimited_env_map()?; + let envp = script_env.create_null_delimited_env_map(); let shell_bin: Option<&ZStr> = 'shell_bin: { #[cfg(windows)] @@ -473,7 +473,7 @@ fn add_package_to_set( lockfile: &Lockfile, package_id: PackageID, ) { - if handle_oom(set.get_or_put(package_id)).found_existing { + if set.get_or_put(package_id).found_existing { return; } let mut stack: Vec = vec![package_id]; @@ -485,7 +485,7 @@ fn add_package_to_set( while dep_id < end { let dep_package_id = lockfile.buffers.resolutions[dep_id as usize]; if dep_package_id != invalid_package_id - && !handle_oom(set.get_or_put(dep_package_id)).found_existing + && !set.get_or_put(dep_package_id).found_existing { stack.push(dep_package_id); } diff --git a/src/install/PackageManager/PackageManagerOptions.rs b/src/install/PackageManager/PackageManagerOptions.rs index da7ddb805c55..6621eb43808d 100644 --- a/src/install/PackageManager/PackageManagerOptions.rs +++ b/src/install/PackageManager/PackageManagerOptions.rs @@ -446,7 +446,7 @@ impl Options { self.registries.put( Npm::registry::Scope::hash(name), Npm::registry::Scope::from_api(name, registry, env)?, - )?; + ); } } diff --git a/src/install/PackageManager/WorkspacePackageJSONCache.rs b/src/install/PackageManager/WorkspacePackageJSONCache.rs index 3ef125dddb95..b5587392650f 100644 --- a/src/install/PackageManager/WorkspacePackageJSONCache.rs +++ b/src/install/PackageManager/WorkspacePackageJSONCache.rs @@ -207,7 +207,7 @@ impl WorkspacePackageJSONCache { stale_contents: Vec::new(), }; - let entry = bun_core::handle_oom(self.map.get_or_put(path)); + let entry = self.map.get_or_put(path); debug_assert!(!entry.found_existing); *entry.value_ptr = value; diff --git a/src/install/PackageManager/add_remove_with_filter.rs b/src/install/PackageManager/add_remove_with_filter.rs index 1ae652f46c3e..c9cd02748cf5 100644 --- a/src/install/PackageManager/add_remove_with_filter.rs +++ b/src/install/PackageManager/add_remove_with_filter.rs @@ -659,7 +659,7 @@ pub(super) fn update_filtered_workspaces_and_install( let mine = core::mem::replace(&mut manager.updating_packages, outer); result?; for (name, info) in mine.iter() { - let entry = manager.updating_packages.get_or_put(name)?; + let entry = manager.updating_packages.get_or_put(name); if !entry.found_existing { *entry.value_ptr = PackageUpdateInfo { original_version_literal: info.original_version_literal.clone(), diff --git a/src/install/PackageManager/install_with_manager.rs b/src/install/PackageManager/install_with_manager.rs index 11ed45e6278e..3dfc5bd0ca42 100644 --- a/src/install/PackageManager/install_with_manager.rs +++ b/src/install/PackageManager/install_with_manager.rs @@ -1,7 +1,6 @@ use core::sync::atomic::Ordering; use bun_collections::DynamicBitSet; -use bun_core::UnwrapOrOom as _; use bun_core::time::nano_timestamp; use bun_core::{Global, Output}; @@ -370,13 +369,8 @@ pub fn install_with_manager( builder, )?; - // `ArrayHashMap::clone()` is an inherent fallible method, - // not the `Clone` trait, so - // `Option::clone` won't see it — map by hand. - *lf.trusted_dependencies = match &lockfile.trusted_dependencies { - Some(td) => Some(td.clone()?), - None => None, - }; + lf.trusted_dependencies + .clone_from(&lockfile.trusted_dependencies); lf.dependencies.reserve(len as usize); lf.resolutions.reserve(len as usize); @@ -1582,8 +1576,8 @@ fn enqueue_named_updates( let plannable_peers = plannable_peer_rows(&manager.lockfile, direct); let collect_latest_rows = manager.options.do_.update_to_latest(); let requests = manager.update_requests.len(); - let mut matched = DynamicBitSet::init_empty(requests).unwrap_or_oom(); - let mut matched_elsewhere = DynamicBitSet::init_empty(requests).unwrap_or_oom(); + let mut matched = DynamicBitSet::init_empty(requests); + let mut matched_elsewhere = DynamicBitSet::init_empty(requests); let mut named = NamedUpdates::default(); let mut peer_rows: Vec = Vec::new(); let dependencies_len = manager.lockfile.buffers.dependencies.len(); @@ -1727,7 +1721,7 @@ fn workspaces_reaching_request<'a>( let dep_lists = packages.items_dependencies(); let res_lists = packages.items_resolutions(); - let mut owners = DynamicBitSet::init_empty(packages.len()).unwrap_or_oom(); + let mut owners = DynamicBitSet::init_empty(packages.len()); let all_deps = lockfile.buffers.dependencies.as_slice(); let all_resolutions = lockfile.buffers.resolutions.as_slice(); for (pkg_id, (dep_list, res_list)) in dep_lists.iter().zip(res_lists).enumerate() { @@ -1788,7 +1782,7 @@ fn record_updating_package_versions(manager: &mut PackageManager) { .options .do_ .contains(crate::package_manager::options::Do::UPDATE_TO_LATEST); - let mut workspaces = DynamicBitSet::init_empty(packages.len()).unwrap_or_oom(); + let mut workspaces = DynamicBitSet::init_empty(packages.len()); match manager.update_target_workspaces.as_deref() { None => workspaces.set( manager @@ -1833,7 +1827,7 @@ fn record_updating_package_versions(manager: &mut PackageManager) { if dep.version.tag == DependencyVersionTag::DistTag && !update_to_latest { continue; } - let entry = updating_packages.get_or_put(name).unwrap_or_oom(); + let entry = updating_packages.get_or_put(name); if !entry.found_existing { entry.value_ptr.original_version_literal = Box::from(dep.version.literal.slice(&lockfile.buffers.string_bytes)); diff --git a/src/install/PackageManager/package_json_write_back.rs b/src/install/PackageManager/package_json_write_back.rs index becf4d246f84..465877322877 100644 --- a/src/install/PackageManager/package_json_write_back.rs +++ b/src/install/PackageManager/package_json_write_back.rs @@ -311,7 +311,7 @@ fn sync_lockfile(manager: &mut PackageManager, edited: &[EditedPackageJson]) -> si } else { if claimed.bit_length() == 0 && !row_deps.is_empty() { - claimed = DynamicBitSet::init_empty(row_deps.len())?; + claimed = DynamicBitSet::init_empty(row_deps.len()); claimed.set_range_value( BitRange { start: 0, diff --git a/src/install/PackageManager/runTasks.rs b/src/install/PackageManager/runTasks.rs index 05c3c87d1002..0e7f37a1b1f2 100644 --- a/src/install/PackageManager/runTasks.rs +++ b/src/install/PackageManager/runTasks.rs @@ -1729,10 +1729,7 @@ pub fn has_created_network_task( task_id: Task::Id, is_required: bool, ) -> bool { - let gpe = this - .network_dedupe_map - .get_or_put(task_id) - .expect("unreachable"); + let gpe = this.network_dedupe_map.get_or_put(task_id); // if there's an existing network task that is optional, we want to make it non-optional if this one would be required gpe.value_ptr.is_required = if !gpe.found_existing { diff --git a/src/install/PackageManager/security_scanner.rs b/src/install/PackageManager/security_scanner.rs index 4ee71f3c53ef..2338b142b8e0 100644 --- a/src/install/PackageManager/security_scanner.rs +++ b/src/install/PackageManager/security_scanner.rs @@ -486,7 +486,7 @@ impl<'a> PackageCollector<'a> { continue; } - if self.dedupe.get_or_put(dep_pkg_id)?.found_existing { + if self.dedupe.get_or_put(dep_pkg_id).found_existing { continue; } @@ -518,7 +518,7 @@ impl<'a> PackageCollector<'a> { continue; } - if self.dedupe.get_or_put(dep_pkg_id)?.found_existing { + if self.dedupe.get_or_put(dep_pkg_id).found_existing { continue; } @@ -584,7 +584,7 @@ impl<'a> PackageCollector<'a> { if update_dep_id == invalid_dependency_id { continue; } - if self.dedupe.get_or_put(update_pkg_id)?.found_existing { + if self.dedupe.get_or_put(update_pkg_id).found_existing { continue; } @@ -617,7 +617,7 @@ impl<'a> PackageCollector<'a> { let pkg_dependencies = pkgs.items_dependencies(); let resolutions = self.manager.lockfile.buffers.resolutions.as_slice(); - let mut wanted = bun_collections::DynamicBitSet::init_empty(pkgs.len())?; + let mut wanted = bun_collections::DynamicBitSet::init_empty(pkgs.len()); for &seed in seeds { if (seed as usize) < pkgs.len() { wanted.set(seed as usize); @@ -632,7 +632,7 @@ impl<'a> PackageCollector<'a> { if target == invalid_package_id || !wanted.is_set(target as usize) { continue; } - if self.dedupe.get_or_put(target)?.found_existing { + if self.dedupe.get_or_put(target).found_existing { continue; } @@ -669,7 +669,7 @@ impl<'a> PackageCollector<'a> { pkg_path: pkg_path_copy, dep_path: dep_path_copy, }, - )?; + ); } let pkg_deps = pkg_dependencies[pkg_id as usize]; @@ -682,7 +682,7 @@ impl<'a> PackageCollector<'a> { continue; } - if self.dedupe.get_or_put(next_pkg_id)?.found_existing { + if self.dedupe.get_or_put(next_pkg_id).found_existing { continue; } diff --git a/src/install/PackageManager/workspace_selection.rs b/src/install/PackageManager/workspace_selection.rs index 531b1b411411..55b89efaa436 100644 --- a/src/install/PackageManager/workspace_selection.rs +++ b/src/install/PackageManager/workspace_selection.rs @@ -2,7 +2,7 @@ use std::collections::VecDeque; use bstr::BStr; use bun_collections::{DynamicBitSet, HashMap, index_sort}; -use bun_core::{Global, Output, UnwrapOrOom as _, strings}; +use bun_core::{Global, Output, strings}; use bun_paths::path_buffer_pool; use bun_paths::resolve_path::{join_abs_string_buf, platform}; @@ -158,7 +158,7 @@ fn base_matches(base: &Base, c: &Candidate<'_>, explicit_root_only: bool) -> boo } fn bitset(n: usize) -> DynamicBitSet { - DynamicBitSet::init_empty(n).unwrap_or_oom() + DynamicBitSet::init_empty(n) } /// `unreachable` is the root under `RootSelection::ExplicitOnly`: edges never select it, but it still seeds the walk when named. diff --git a/src/install/audit_fix.rs b/src/install/audit_fix.rs index 0e72077642b7..5238c7d01236 100644 --- a/src/install/audit_fix.rs +++ b/src/install/audit_fix.rs @@ -151,7 +151,7 @@ impl AdvisoryIndex { spans, groups, by_name, - matched_before_install: DynamicBitSet::init_empty(advisories.len())?, + matched_before_install: DynamicBitSet::init_empty(advisories.len()), }) } @@ -637,7 +637,7 @@ pub fn plan_fixes(manager: &mut PackageManager, advisories: &[Advisory]) -> crat let mut unfixable: Vec = Vec::new(); let mut manifest_unavailable: Vec = Vec::new(); let mut expected_gone: Vec<(PackageNameHash, Box<[u8]>)> = Vec::new(); - let mut advisory_still_present = index.matched_before_install.clone()?; + let mut advisory_still_present = index.matched_before_install.clone(); advisory_still_present.toggle_all(); for inst in instances { @@ -1122,7 +1122,7 @@ impl FixPlan { let planned = &self.advisories; let installed = AdvisoryIndex::build(installed_advisories).unwrap_or_oom(); - let mut plan_remaining = planned.matched_before_install.clone().unwrap_or_oom(); + let mut plan_remaining = planned.matched_before_install.clone(); plan_remaining.toggle_all(); let staying: Vec<(PackageNameHash, &[u8])> = self .blocked diff --git a/src/install/dedupe.rs b/src/install/dedupe.rs index 32ed09e28e02..c5f12a1dd541 100644 --- a/src/install/dedupe.rs +++ b/src/install/dedupe.rs @@ -4,7 +4,7 @@ use std::io::Write as _; use bstr::BStr; use bun_collections::bit_set::Range; use bun_collections::{DynamicBitSet, index_sort}; -use bun_core::{Global, Output, UnwrapOrOom as _, strings}; +use bun_core::{Global, Output, strings}; use crate::lockfile::package::PackageColumns as _; use crate::lockfile::{LoadResult, Lockfile, Package, PackageIndexEntry}; @@ -54,15 +54,15 @@ impl<'a> Pass<'a> { edges: vec![Vec::new(); groups.len()], candidates: Vec::with_capacity(max_candidates), edge_count: 0, - sat: DynamicBitSet::init_empty(max_edges * max_candidates).unwrap_or_oom(), - movable: DynamicBitSet::init_empty(max_edges).unwrap_or_oom(), + sat: DynamicBitSet::init_empty(max_edges * max_candidates), + movable: DynamicBitSet::init_empty(max_edges), cur_c: Vec::with_capacity(max_edges), - required: DynamicBitSet::init_empty(max_candidates).unwrap_or_oom(), - chosen: DynamicBitSet::init_empty(max_candidates).unwrap_or_oom(), - survivors: DynamicBitSet::init_empty(max_candidates).unwrap_or_oom(), - covered: DynamicBitSet::init_empty(max_edges).unwrap_or_oom(), - voters: DynamicBitSet::init_empty(package_count).unwrap_or_oom(), - voted: DynamicBitSet::init_empty(package_count).unwrap_or_oom(), + required: DynamicBitSet::init_empty(max_candidates), + chosen: DynamicBitSet::init_empty(max_candidates), + survivors: DynamicBitSet::init_empty(max_candidates), + covered: DynamicBitSet::init_empty(max_edges), + voters: DynamicBitSet::init_empty(package_count), + voted: DynamicBitSet::init_empty(package_count), count: Vec::with_capacity(max_candidates), protected: Vec::new(), } @@ -347,7 +347,7 @@ fn dedupe_lockfile(lockfile: &mut Lockfile) -> Report { let mut groups: Vec> = Vec::new(); let mut group_of: Vec = vec![u32::MAX; pkg_res.len()]; - let mut pinned = DynamicBitSet::init_empty(pkg_res.len()).unwrap_or_oom(); + let mut pinned = DynamicBitSet::init_empty(pkg_res.len()); let mut max_candidates = 0; if has_patches { @@ -415,7 +415,7 @@ fn dedupe_lockfile(lockfile: &mut Lockfile) -> Report { // Walked over the original resolutions: pinning every removed version that led to the orphan keeps those paths intact on the re-run. let (cur, live) = loop { - let mut live = initial.clone().unwrap_or_oom(); + let mut live = initial.clone(); let mut cur: Vec = lockfile.buffers.resolutions.clone(); { let mut pass = Pass::new( diff --git a/src/install/hoisted_install.rs b/src/install/hoisted_install.rs index 81dc1dc5ee53..8fa4032563eb 100644 --- a/src/install/hoisted_install.rs +++ b/src/install/hoisted_install.rs @@ -281,14 +281,14 @@ pub(crate) fn install_hoisted_packages( let mut installer: PackageInstaller = 'brk: { let (completed_trees, tree_ids_to_trees_the_id_depends_on) = 'trees: { let trees = this.lockfile.buffers.trees.as_slice(); - let completed_trees = Bitset::init_empty(trees.len())?; + let completed_trees = Bitset::init_empty(trees.len()); let tree_ids_to_trees_the_id_depends_on = - DynamicBitSetList::init_empty(trees.len(), trees.len())?; + DynamicBitSetList::init_empty(trees.len(), trees.len()); { // For each tree id, traverse through it's parents and mark all visited tree // ids as dependents for the current tree parent - let mut deps = Bitset::init_empty(trees.len())?; + let mut deps = Bitset::init_empty(trees.len()); for _curr in trees { let mut curr = *_curr; tree_ids_to_trees_the_id_depends_on.set(curr.id as usize, curr.id as usize); @@ -393,7 +393,7 @@ pub(crate) fn install_hoisted_packages( skip_delete, summary: &mut summary, force_install, - successfully_installed: Bitset::init_empty(pkg_len)?, + successfully_installed: Bitset::init_empty(pkg_len), command_ctx: ctx, tree_ids_to_trees_the_id_depends_on, completed_trees, @@ -587,10 +587,8 @@ pub(crate) fn install_hoisted_packages( // below. Route through `installer.summary` because `summary` itself is // exclusively borrowed by `installer` for this scope. { - let taken = core::mem::replace( - &mut installer.successfully_installed, - Bitset::init_empty(0)?, - ); + let taken = + core::mem::replace(&mut installer.successfully_installed, Bitset::init_empty(0)); installer.summary.successfully_installed = Some(taken); } diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index d89105ac2ead..6d8d9d1d4436 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -260,13 +260,13 @@ pub(crate) fn build_store( let mut peer_name_idx: ArrayHashMap = ArrayHashMap::default(); for dep in dependencies { if dep.behavior.is_peer() { - peer_name_idx.put(dep.name_hash, ())?; + peer_name_idx.put(dep.name_hash, ()); } } let peer_name_count: u32 = u32::try_from(peer_name_idx.count()).expect("int cast"); let leaking_peers: DynamicBitSetList = - DynamicBitSetList::init_empty(lockfile.packages.len(), peer_name_count as usize)?; + DynamicBitSetList::init_empty(lockfile.packages.len(), peer_name_count as usize); if peer_name_count != 0 { // The runtime child of a peer edge is whichever package an ancestor's @@ -291,9 +291,9 @@ pub(crate) fn build_store( // dependency names that will appear in `node_dependencies` (i.e., not // filtered out by bundled/disabled/unresolved). let own_peers: DynamicBitSetList = - DynamicBitSetList::init_empty(lockfile.packages.len(), peer_name_count as usize)?; + DynamicBitSetList::init_empty(lockfile.packages.len(), peer_name_count as usize); let provides: DynamicBitSetList = - DynamicBitSetList::init_empty(lockfile.packages.len(), peer_name_count as usize)?; + DynamicBitSetList::init_empty(lockfile.packages.len(), peer_name_count as usize); for pkg_idx in 0..lockfile.packages.len() { let pkg_id: PackageID = u32::try_from(pkg_idx).expect("int cast"); let deps = pkg_dependency_slices[pkg_id as usize]; @@ -319,7 +319,7 @@ pub(crate) fn build_store( } } - let mut scratch = DynamicBitSetUnmanaged::init_empty(peer_name_count as usize)?; + let mut scratch = DynamicBitSetUnmanaged::init_empty(peer_name_count as usize); let mut changed = true; while changed { @@ -362,7 +362,7 @@ pub(crate) fn build_store( // ctx_hash is 0 when the package has no leaking peers (or is a workspace). let mut early_dedupe: HashMap = HashMap::default(); - let mut root_declares_workspace = DynamicBitSet::init_empty(lockfile.packages.len())?; + let mut root_declares_workspace = DynamicBitSet::init_empty(lockfile.packages.len()); for _dep_idx in pkg_dependency_slices[0].begin()..pkg_dependency_slices[0].end() { let dep_idx: DependencyID = _dep_idx; if !dependencies[dep_idx as usize].behavior.is_workspace() { @@ -536,7 +536,7 @@ pub(crate) fn build_store( let dedupe_entry = early_dedupe.get_or_put(EarlyDedupeKey { pkg_id: entry.pkg_id, ctx_hash, - })?; + }); if dedupe_entry.found_existing { let dedupe_node_id = *dedupe_entry.value_ptr; @@ -613,7 +613,7 @@ pub(crate) fn build_store( Vec::with_capacity(pkg_deps.len as usize) }, ..Default::default() - })?; + }); let mut nodes_slice = nodes.slice(); // disjoint-column views via `split_mut`. @@ -898,7 +898,7 @@ pub(crate) fn build_store( 'next_entry: while let Some(entry) = entry_queue.read_item() { let pkg_id = node_pkg_ids[entry.node_id.get() as usize]; - let dedupe_entry = dedupe.get_or_put(pkg_id)?; + let dedupe_entry = dedupe.get_or_put(pkg_id); if !dedupe_entry.found_existing { *dedupe_entry.value_ptr = Vec::new(); } else { @@ -1021,12 +1021,12 @@ pub(crate) fn build_store( .slice(string_buf); let Some(hoist_pattern) = &manager.options.hoist_pattern else { - let hoist_entry = hidden_hoisted.get_or_put(dep_name)?; + let hoist_entry = hidden_hoisted.get_or_put(dep_name); break 'hoisted !hoist_entry.found_existing; }; if hoist_pattern.is_match(dep_name) { - let hoist_entry = hidden_hoisted.get_or_put(dep_name)?; + let hoist_entry = hidden_hoisted.get_or_put(dep_name); break 'hoisted !hoist_entry.found_existing; } @@ -1046,7 +1046,7 @@ pub(crate) fn build_store( let new_entry_id: store::entry::Id = store::entry::Id::from(u32::try_from(store_entries.len()).expect("int cast")); - store_entries.append(new_entry)?; + store_entries.append(new_entry); if let Some(entry_parent_id) = entry.entry_parent_id.try_get() { 'skip_adding_dependency: { @@ -1079,7 +1079,7 @@ pub(crate) fn build_store( let dep_name = dependencies[new_entry_dep_id as usize] .name .slice(string_buf); - public_hoisted.put(dep_name, ())?; + public_hoisted.put(dep_name, ()); } else { // transitive dependencies (also direct dependencies of workspaces!) let dep_name = dependencies[new_entry_dep_id as usize] @@ -1087,7 +1087,7 @@ pub(crate) fn build_store( .slice(string_buf); if let Some(public_hoist_pattern) = &manager.options.public_hoist_pattern { if public_hoist_pattern.is_match(dep_name) { - let hoist_entry = public_hoisted.get_or_put(dep_name)?; + let hoist_entry = public_hoisted.get_or_put(dep_name); if !hoist_entry.found_existing { entry_dependencies[0].insert( store::entry::DependenciesItem { @@ -1586,7 +1586,7 @@ pub(crate) fn install_isolated_packages( &dependencies[dep.dep_id as usize].name_hash, )); ext.update(bun_core::bytes_of(&entry_hashes[di])); - scc_ext.put(ext.final_(), ())?; + scc_ext.put(ext.final_(), ()); } } member_sub.sort_unstable(); @@ -2023,7 +2023,7 @@ pub(crate) fn install_isolated_packages( }; let show_progress = manager.options.log_level.show_progress(); - let installed = DynamicBitSet::init_empty(lockfile.packages.len())?; + let installed = DynamicBitSet::init_empty(lockfile.packages.len()); let trusted_dependencies_from_update_requests = manager.find_trusted_dependencies_from_update_requests(); // `Installer.manager` is a BACKREF raw pointer; copying `manager_ptr` @@ -2159,7 +2159,7 @@ pub(crate) fn install_isolated_packages( // thread. // if injected=true this might be false - if !seen_workspace_ids.get_or_put(pkg_id)?.found_existing { + if !seen_workspace_ids.get_or_put(pkg_id).found_existing { entry_steps[entry_id.get() as usize].store( installer::Step::SymlinkDependencies as u32, Ordering::Relaxed, diff --git a/src/install/isolated_install/Store.rs b/src/install/isolated_install/Store.rs index 25be802357ff..2d9fbc28ac4b 100644 --- a/src/install/isolated_install/Store.rs +++ b/src/install/isolated_install/Store.rs @@ -128,7 +128,7 @@ impl Store { if parent_id == maybe_parent_id { return true; } - let _ = parent_dedupe.put(parent_id, ()); // OOM-only Result + parent_dedupe.put(parent_id, ()); } len = parent_dedupe.len(); @@ -142,7 +142,7 @@ impl Store { if parent_id == maybe_parent_id { return true; } - let _ = parent_dedupe.put(parent_id, ()); // OOM-only Result + parent_dedupe.put(parent_id, ()); len = parent_dedupe.len(); } i += 1; @@ -497,7 +497,7 @@ pub mod entry { if parent_id == Id::INVALID { continue; } - let _ = parents.put(parent_id, ()); // OOM-only Result + parents.put(parent_id, ()); } len = parents.len(); @@ -508,7 +508,7 @@ pub mod entry { if parent_id == Id::INVALID { continue; } - let _ = parents.put(parent_id, ()); // OOM-only Result + parents.put(parent_id, ()); len = parents.len(); } i += 1; diff --git a/src/install/lib.rs b/src/install/lib.rs index aaa1d4ba102f..b1cea55ae228 100644 --- a/src/install/lib.rs +++ b/src/install/lib.rs @@ -824,13 +824,13 @@ impl RunCommand { // loader snapshots `environ` before flag parsing runs, so the // `setenv()` in `enable()` isn't reflected here. if bun_io::parent_death_watchdog::is_enabled() { - let _ = env_loader.map.put(b"BUN_FEATURE_FLAG_NO_ORPHANS", b"1"); + env_loader.map.put(b"BUN_FEATURE_FLAG_NO_ORPHANS", b"1"); } // we have no way of knowing what version they're expecting without // running the node executable; running the node executable is too // slow, so we will just hardcode it to LTS - let _ = env_loader.map.put_default( + env_loader.map.put_default( b"npm_config_user_agent", // the use of npm/? is copying yarn // e.g. @@ -851,7 +851,7 @@ impl RunCommand { if env_loader.get(b"npm_execpath").is_none() { // we don't care if this fails if let Ok(self_exe) = bun_core::self_exe_path() { - let _ = env_loader + env_loader .map .put_default(b"npm_execpath", self_exe.as_bytes()); } diff --git a/src/install/lockfile.rs b/src/install/lockfile.rs index 3e8f79c3aa6a..64e3de04d85f 100644 --- a/src/install/lockfile.rs +++ b/src/install/lockfile.rs @@ -936,13 +936,13 @@ impl Lockfile { // it (never `Box::leak` to satisfy a lifetime). let mut new: Box = Box::default(); new.string_pool - .ensure_total_capacity(old.string_pool.capacity())?; + .ensure_total_capacity(old.string_pool.capacity()); new.package_index - .ensure_total_capacity(old.package_index.capacity())?; - new.packages.ensure_total_capacity(old.packages.len())?; + .ensure_total_capacity(old.package_index.capacity()); + new.packages.ensure_total_capacity(old.packages.len()); new.buffers.preallocate(&old.buffers)?; new.patched_dependencies - .ensure_total_capacity(old.patched_dependencies.count())?; + .ensure_total_capacity(old.patched_dependencies.count()); // Reset the FIFO read cursor without discarding capacity. // `LinearFifo::head` is private; the queue is always drained to empty @@ -998,9 +998,9 @@ impl Lockfile { // Clone workspace_paths and workspace_versions at the end. if old.workspace_paths.count() > 0 || old.workspace_versions.count() > 0 { new.workspace_paths - .ensure_total_capacity(old.workspace_paths.count())?; + .ensure_total_capacity(old.workspace_paths.count()); new.workspace_versions - .ensure_total_capacity(old.workspace_versions.count())?; + .ensure_total_capacity(old.workspace_versions.count()); // Field-level split borrow of `new` (string_bytes + string_pool). let mut workspace_paths_builder = string_builder!(new); @@ -1055,7 +1055,7 @@ impl Lockfile { .copy_from_slice(old.workspace_paths.keys()); new.workspace_versions - .ensure_total_capacity(old.workspace_versions.count())?; + .ensure_total_capacity(old.workspace_versions.count()); // SAFETY: capacity reserved immediately above; every slot is filled by // the zip loop below before `re_index()`. unsafe { @@ -1075,8 +1075,8 @@ impl Lockfile { workspace_paths_builder.clamp(); - new.workspace_versions.re_index()?; - new.workspace_paths.re_index()?; + new.workspace_versions.re_index(); + new.workspace_paths.re_index(); } } @@ -1159,7 +1159,7 @@ fn clean_migrate_patched_dependencies_cold( let mut patchdep = *v; patchdep.path = builder .append::(patchdep.path.slice(old.buffers.string_bytes.as_slice())); - new.patched_dependencies.put(*k, patchdep)?; + new.patched_dependencies.put(*k, patchdep); } Ok(()) } @@ -1683,7 +1683,7 @@ impl<'a> Printer<'a> { let mut env_loader = DotEnv::Loader::init(); env_loader.quiet = true; - env_loader.load_process()?; + env_loader.load_process(); env_loader.load( &entries, &[] as &[&[u8]], @@ -2000,7 +2000,7 @@ impl Lockfile { pub(crate) fn mark_exact_pin(&mut self, id: PackageID) { let i = id as usize; if self.exact_pinned.bit_length() <= i { - bun_core::handle_oom(self.exact_pinned.resize(i + 1, false)); + self.exact_pinned.resize(i + 1, false); } self.exact_pinned.set(i); } @@ -2121,12 +2121,12 @@ impl Lockfile { &mut self, pkg: &mut Package, ) -> Result { - let entry = self.package_index.get_or_put(pkg.name_hash)?; + let entry = self.package_index.get_or_put(pkg.name_hash); if !entry.found_existing { let new_id: PackageID = PackageID::try_from(self.packages.len()).expect("int cast"); pkg.meta.id = new_id; - self.packages.append(*pkg)?; + self.packages.append(*pkg); *entry.value_ptr = PackageIndexEntry::Id(new_id); return Ok(new_id); } @@ -2147,7 +2147,7 @@ impl Lockfile { let new_id: PackageID = PackageID::try_from(self.packages.len()).expect("int cast"); pkg.meta.id = new_id; - self.packages.append(*pkg)?; + self.packages.append(*pkg); resolutions = self.packages.items_resolution(); @@ -2180,7 +2180,7 @@ impl Lockfile { let new_id: PackageID = PackageID::try_from(self.packages.len()).expect("int cast"); pkg.meta.id = new_id; - self.packages.append(*pkg)?; + self.packages.append(*pkg); resolutions = self.packages.items_resolution(); @@ -2208,7 +2208,7 @@ impl Lockfile { id: PackageID, name_hash: PackageNameHash, ) -> Result<(), AllocError> { - let gpe = self.package_index.get_or_put(name_hash)?; + let gpe = self.package_index.get_or_put(name_hash); if gpe.found_existing { let index: &mut PackageIndexEntry = gpe.value_ptr; @@ -2277,7 +2277,7 @@ impl Lockfile { let mut package = *package_; package.meta.id = id; - self.packages.append(package)?; + self.packages.append(package); self.get_or_put_id(id, name_hash)?; debug_assert!(self.get_package_id(name_hash, None, &resolution).is_some()); @@ -2505,7 +2505,7 @@ impl<'a> StringBuilder<'a> { debug_assert!(self.len <= self.cap); // didn't count everything debug_assert!(self.ptr.is_some()); // must call allocate first - let string_entry = self.string_pool.get_or_put(hash).expect("unreachable"); + let string_entry = self.string_pool.get_or_put(hash); if !string_entry.found_existing { // See `append_without_pool` — safe indexing into the region // `allocate()` already resized. diff --git a/src/install/lockfile/Buffers.rs b/src/install/lockfile/Buffers.rs index 7a2d2db3e158..72446283307f 100644 --- a/src/install/lockfile/Buffers.rs +++ b/src/install/lockfile/Buffers.rs @@ -474,7 +474,7 @@ pub(crate) fn load( // Legacy tree structure stores package IDs instead of dependency IDs if !this.trees.is_empty() && this.trees[0].dependency_id != tree::ROOT_DEP_ID { - let mut visited = Bitset::init_empty(this.dependencies.len())?; + let mut visited = Bitset::init_empty(this.dependencies.len()); // Iterate by index so // `legacy_package_to_dependency_id` can borrow `&self` while we hold // `&mut this.trees[i]`. diff --git a/src/install/lockfile/CatalogMap.rs b/src/install/lockfile/CatalogMap.rs index d54a7b0d728f..c96bf53a2e24 100644 --- a/src/install/lockfile/CatalogMap.rs +++ b/src/install/lockfile/CatalogMap.rs @@ -207,7 +207,7 @@ impl CatalogMap { return Ok(&mut self.default); } - let entry = self.groups.get_or_put_adapted(&catalog_name, &ctx(buf))?; + let entry = self.groups.get_or_put_adapted(&catalog_name, &ctx(buf)); if !entry.found_existing { *entry.key_ptr = catalog_name; *entry.value_ptr = Map::default(); @@ -338,7 +338,7 @@ impl CatalogMap { }; let buf = builder.string_bytes.as_slice(); - let entry = group.get_or_put_adapted(&dep_name, &ctx(buf))?; + let entry = group.get_or_put_adapted(&dep_name, &ctx(buf)); if entry.found_existing { log.add_error(Some(source), key_loc, b"Duplicate catalog"); @@ -459,7 +459,7 @@ impl CatalogMap { new_catalog .default - .ensure_total_capacity(self.default.count())?; + .ensure_total_capacity(self.default.count()); // Per insert, finish the `&mut builder` appends FIRST, then snapshot // the buffer for the hash/eql closures. Snapshotting once up-front would freeze @@ -478,11 +478,11 @@ impl CatalogMap { new_catalog .groups - .ensure_total_capacity(self.groups.count())?; + .ensure_total_capacity(self.groups.count()); for (catalog_name, deps) in self.groups.keys().iter().zip(self.groups.values()) { let mut new_group = Map::default(); - new_group.ensure_total_capacity(deps.count())?; + new_group.ensure_total_capacity(deps.count()); for (dep_name, dep) in deps.keys().iter().zip(deps.values()) { let new_key = builder.append::(dep_name.slice(old_buf)); @@ -564,7 +564,7 @@ fn put_entries_from_pnpm_lockfile( }; let buf = string_buf.bytes.as_slice(); - let entry = catalog_map.get_or_put_adapted(&dep_name, &ctx(buf))?; + let entry = catalog_map.get_or_put_adapted(&dep_name, &ctx(buf)); if entry.found_existing { return Err(FromPnpmLockfileError::InvalidPnpmLockfile); diff --git a/src/install/lockfile/OverrideMap.rs b/src/install/lockfile/OverrideMap.rs index 4ac9fffab6a3..dd28ab17349e 100644 --- a/src/install/lockfile/OverrideMap.rs +++ b/src/install/lockfile/OverrideMap.rs @@ -446,7 +446,7 @@ impl OverrideMap { new_builder: &mut StringBuilder, ) -> Result { let mut new = OverrideMap::default(); - new.map.ensure_total_capacity(self.map.count())?; + new.map.ensure_total_capacity(self.map.count()); for (k, v) in self.map.keys().iter().zip(self.map.values()) { new.map @@ -456,7 +456,7 @@ impl OverrideMap { if !self.scoped.is_empty() { new.scoped = Vec::with_capacity(self.scoped.len()); new.scoped_names - .ensure_total_capacity(self.scoped_names.count())?; + .ensure_total_capacity(self.scoped_names.count()); for rule in &self.scoped { let parent = match &rule.parent { None => None, @@ -564,7 +564,7 @@ impl OverrideMap { }; if is_flat { - self.map.put(name_hash, dep)?; + self.map.put(name_hash, dep); } else { self.push_scoped( ScopedOverride { @@ -705,7 +705,7 @@ impl OverrideMap { return Ok(()); } - self.map.ensure_unused_capacity(expr.property_count())?; + self.map.ensure_unused_capacity(expr.property_count()); expr.try_for_each_property(|k, key_loc, value_expr| { if k.is_empty() { @@ -824,7 +824,7 @@ impl OverrideMap { ); return Ok(()); } - self.map.ensure_unused_capacity(expr.property_count())?; + self.map.ensure_unused_capacity(expr.property_count()); expr.try_for_each_property(|k, key_loc, value_expr| { if k.is_empty() { ctx.log.add_warning_fmt( diff --git a/src/install/lockfile/Package.rs b/src/install/lockfile/Package.rs index fcd5b545bd4d..3054532e5fe0 100644 --- a/src/install/lockfile/Package.rs +++ b/src/install/lockfile/Package.rs @@ -117,7 +117,7 @@ fn invalid_trusted_dependencies( source: &bun_ast::Source, loc: bun_ast::Loc, ) -> crate::Error { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, source, loc, @@ -1232,7 +1232,7 @@ impl Diff { add_to_lockfile: true, name: to_name.clone(), }, - )?; + ); } } @@ -1249,7 +1249,7 @@ impl Diff { if !still_trusted { summary .removed_trusted_dependencies - .put(from_trusted, from_name.clone())?; + .put(from_trusted, from_name.clone()); } } @@ -1274,7 +1274,7 @@ impl Diff { add_to_lockfile: false, name: Box::from(entry.key), }, - )?; + ); } } @@ -1283,7 +1283,7 @@ impl Diff { if !default_trusted_dependencies::has_with_hash(u64::from(from_trusted)) { summary .removed_trusted_dependencies - .put(from_trusted, from_name.clone())?; + .put(from_trusted, from_name.clone()); } } @@ -1304,7 +1304,7 @@ impl Diff { add_to_lockfile: true, name: to_name.clone(), }, - )?; + ); } { @@ -2014,11 +2014,11 @@ impl Package { debug_assert!(!bun_paths::is_absolute(path.slice(buf))); dependency_version.value.workspace = path; - let workspace_entry = workspace_paths.get_or_put(name_hash)?; + let workspace_entry = workspace_paths.get_or_put(name_hash); let found_matching_workspace = workspace_entry.found_existing; if let Some(ver) = workspace_version { - workspace_versions.put(name_hash, ver)?; + workspace_versions.put(name_hash, ver); for package_dep in &mut package_dependencies[0..dependencies_count as usize] { if match package_dep.version.tag { @@ -2088,7 +2088,7 @@ impl Package { && !group.behavior.is_peer() && !group.behavior.is_workspace() { - let entry = duplicate_checker_map.get_or_put(external_alias.hash)?; + let entry = duplicate_checker_map.get_or_put(external_alias.hash); if entry.found_existing { // duplicate dependencies are allowed in optionalDependencies if group.behavior.is_optional() { @@ -2306,7 +2306,7 @@ impl Package { if FEATURES.peer_dependencies { if let Some(peer_dependencies_meta) = json.as_property(b"peerDependenciesMeta") { optional_peer_dependencies - .ensure_unused_capacity(peer_dependencies_meta.expr.property_count())?; + .ensure_unused_capacity(peer_dependencies_meta.expr.property_count()); peer_dependencies_meta .expr .for_each_property(|key, _key_loc, meta| { @@ -2341,7 +2341,7 @@ impl Package { 'brk: { if dependencies_q.expr.is_array() { if !group.behavior.is_workspace() { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, source, dependencies_q.loc, @@ -2388,7 +2388,7 @@ impl Package { value_loc_of(source, packages_query.loc) }; if !packages_expr.is_array() { - let _ = log.add_error_fmt( + log.add_error_fmt( source, packages_loc, format_args!( @@ -2418,7 +2418,7 @@ impl Package { let count = rows.len() as u32; for (key, value, key_loc) in rows { let Some(value) = value else { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, source, value_loc_of(source, key_loc), @@ -2445,14 +2445,14 @@ impl Package { } if group.behavior.is_workspace() { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, source, dependencies_q.loc, "\"workspaces\" expects an array of strings, e.g.\n \"workspaces\": [\n \"path/to/package\"\n ]" ); } else { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, source, dependencies_q.loc, @@ -2476,7 +2476,7 @@ impl Package { lockfile.trusted_dependencies = Some(Default::default()); } let trusted = lockfile.trusted_dependencies.as_mut().unwrap(); - trusted.ensure_unused_capacity(count)?; + trusted.ensure_unused_capacity(count); if let Some(mut items) = q.expr.as_array() { while let Some(item) = items.next() { let Some(name) = item.as_string(&bump) else { @@ -2582,24 +2582,20 @@ impl Package { if let Some(rows) = JsonObjectStringRows::new(&patched_deps.expr, &bump) { lockfile .patched_dependencies - .ensure_total_capacity(rows.len()) - .expect("unreachable"); + .ensure_total_capacity(rows.len()); for (key, value, _) in rows { let Some(value) = value else { continue; }; let keyhash = semver::string::Builder::string_hash(key); let patch_path = string_builder.append::(value); - lockfile - .patched_dependencies - .put( - keyhash, - PatchedDep { - path: patch_path, - ..Default::default() - }, - ) - .expect("unreachable"); + lockfile.patched_dependencies.put( + keyhash, + PatchedDep { + path: patch_path, + ..Default::default() + }, + ); } } } @@ -2728,7 +2724,7 @@ impl Package { let Some(s) = item.as_string(&bump) else { continue; }; - bundled_deps.insert(s)?; + bundled_deps.insert(s); } } } @@ -2754,7 +2750,7 @@ impl Package { // workspace names from their package jsons. duplicates not allowed let gop = seen_workspace_names .get_or_put(semver::string::Builder::string_hash(&entry.name) - as TruncatedPackageNameHash)?; + as TruncatedPackageNameHash); if gop.found_existing { // this path does alot of extra work to format the error message // but this is ok because the install is going to fail anyways, so this @@ -2839,7 +2835,7 @@ impl Package { Err(_) => bun_ast::Source::init_empty_file(abs_path.as_bytes()), }; - let _ = log.add_range_error_fmt_with_notes( + log.add_range_error_fmt_with_notes( Some(&src), src.range_of_string(entry.name_loc), notes.into(), @@ -2901,11 +2897,9 @@ impl Package { package_dependencies.push(dep); total_dependencies_count += 1; - lockfile.workspace_paths.put(external_name.hash, ws_path)?; + lockfile.workspace_paths.put(external_name.hash, ws_path); if let Some(version) = workspace_version { - lockfile - .workspace_versions - .put(external_name.hash, version)?; + lockfile.workspace_versions.put(external_name.hash, version); } } } @@ -3221,7 +3215,7 @@ pub mod serializer { return Err(crate::Error::LockfileValidationFailedInvalidPackageListRange); } stream.pos = begin_at; - list.ensure_total_capacity(list_len as usize)?; + list.ensure_total_capacity(list_len as usize); let mut needs_update = false; if migrate_from_v2 { @@ -3229,7 +3223,7 @@ pub mod serializer { let mut list_for_migrating_from_v2 = >::default(); // defer list_for_migrating_from_v2.deinit(allocator); — Drop handles it - list_for_migrating_from_v2.ensure_total_capacity(list_len as usize)?; + list_for_migrating_from_v2.ensure_total_capacity(list_len as usize); // SAFETY: capacity reserved above; `load_fields` writes every column. unsafe { list_for_migrating_from_v2.set_len(list_len as usize) }; @@ -3288,7 +3282,7 @@ pub mod serializer { }, }; - list.append(new)?; + list.append(new); } } else { // SAFETY: capacity reserved above; `load_fields` writes every column. diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index 2f2d415ccd4d..c82a406541c3 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -58,7 +58,7 @@ impl WorkspaceMap { // cwd — false positive whenever the two differ (e.g. `bun unlink` from a // workspace package). Existence is already verified by the caller via // `process_workspace_name`, so the check is dropped. - let entry = self.map.get_or_put(key)?; + let entry = self.map.get_or_put(key); if !entry.found_existing { *entry.key_ptr = Box::<[u8]>::from(key); } @@ -226,7 +226,7 @@ impl WorkspaceMap { for i in 0..item_count { let Some(input_path) = arr.item_str(i, &scratch) else { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, Some(source), arr.item_loc(source, i), @@ -297,13 +297,13 @@ impl WorkspaceMap { || err == crate::Error::Sys(bun_errno::SystemErrno::EPERM) || err == crate::Error::Sys(bun_errno::SystemErrno::ENOENT) { - let _ = log.add_error_fmt( + log.add_error_fmt( Some(source), arr.item_loc(source, i), format_args!("Workspace not found \"{}\"", BStr::new(input_path)), ); } else if err == crate::Error::MissingPackageName { - let _ = log.add_error_fmt( + log.add_error_fmt( Some(source), loc, format_args!( @@ -314,7 +314,7 @@ impl WorkspaceMap { } else { let mut cwd_buf = vec![0u8; MAX_PATH_BYTES]; let cwd_len = bun_sys::getcwd(&mut cwd_buf).expect("unreachable"); - let _ = log.add_error_fmt( + log.add_error_fmt( Some(source), arr.item_loc(source, i), format_args!( @@ -396,7 +396,7 @@ impl WorkspaceMap { )? { Ok(w) => w, Err(e) => { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, Some(source), loc, @@ -412,7 +412,7 @@ impl WorkspaceMap { let mut iter = glob::walk::Iterator::new(&mut walker); if let Err(e) = iter.init()? { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, Some(source), loc, @@ -428,7 +428,7 @@ impl WorkspaceMap { Ok(Some(r)) => r, Ok(None) => break, Err(e) => { - let _ = bun_ast::add_error_pretty!( + bun_ast::add_error_pretty!( log, Some(source), loc, @@ -496,7 +496,7 @@ impl WorkspaceMap { if err == crate::Error::Sys(bun_errno::SystemErrno::ENOENT) { continue; } else if err == crate::Error::MissingPackageName { - let _ = log.add_error_fmt( + log.add_error_fmt( Some(source), bun_ast::Loc::EMPTY, format_args!( @@ -507,7 +507,7 @@ impl WorkspaceMap { ), ); } else { - let _ = log.add_error_fmt( + log.add_error_fmt( Some(source), bun_ast::Loc::EMPTY, format_args!( diff --git a/src/install/lockfile/Tree.rs b/src/install/lockfile/Tree.rs index 66d3f9597a28..957dc6e5bb0f 100644 --- a/src/install/lockfile/Tree.rs +++ b/src/install/lockfile/Tree.rs @@ -488,7 +488,7 @@ impl<'a, const METHOD: BuilderMethod> Builder<'a, METHOD> { } fn maybe_report_error(&mut self, args: core::fmt::Arguments<'_>) { - let _ = self.log.add_error_fmt(None, bun_ast::Loc::EMPTY, args); + self.log.add_error_fmt(None, bun_ast::Loc::EMPTY, args); } fn buf(&self) -> &[u8] { @@ -657,7 +657,7 @@ impl Tree { dependencies: DependencyIDSlice::default(), }, dependencies: DependencyIDList::default(), - })?; + }); // reshaped for borrowck. let next_id = (builder.list.len() - 1) as Id; @@ -892,12 +892,12 @@ impl Tree { // later if it's possible to resolve it. let entry = builder .pending_optional_peers - .get_or_put(dependency.name_hash)?; + .get_or_put(dependency.name_hash); if !entry.found_existing { *entry.value_ptr = ArrayHashMap::default(); } - entry.value_ptr.put(dep_id, ())?; + entry.value_ptr.put(dep_id, ()); } HoistDependencyResult::Placement(dest) => { { @@ -1066,7 +1066,7 @@ impl Tree { let buf = lockfile.buffers.string_bytes.as_slice(); let names = lockfile.packages.items_name(); let resolutions = lockfile.packages.items_resolution(); - let _ = builder.log.add_error_fmt( + builder.log.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( diff --git a/src/install/lockfile/bun.lock.rs b/src/install/lockfile/bun.lock.rs index 0bced1e83d5d..b87f2d2ba262 100644 --- a/src/install/lockfile/bun.lock.rs +++ b/src/install/lockfile/bun.lock.rs @@ -1686,10 +1686,7 @@ impl PkgMap { // deinit → Drop (StringHashMap drops itself) - fn get_or_put( - &mut self, - name: &[u8], - ) -> Result, bun_alloc::AllocError> + fn get_or_put(&mut self, name: &[u8]) -> bun_collections::string_hash_map::GetOrPutResult<'_, T> where T: Default, { @@ -2144,7 +2141,7 @@ pub(crate) fn parse_into_binary_lockfile( let entry = lockfile.catalogs.default.get_or_put_adapted( &dep_name, &string_array_hash_context(lockfile.buffers.string_bytes.as_slice()), - )?; + ); if entry.found_existing { log.add_error(Some(source), row.key_loc, b"Duplicate catalog entry"); @@ -2242,7 +2239,7 @@ pub(crate) fn parse_into_binary_lockfile( let entry = group.get_or_put_adapted( &dep_name, &string_array_hash_context(lockfile.buffers.string_bytes.as_slice()), - )?; + ); if entry.found_existing { log.add_error(Some(source), row.key_loc, b"Duplicate catalog entry"); @@ -2405,7 +2402,7 @@ pub(crate) fn parse_into_binary_lockfile( root_pkg.meta.id = 0; let root_name_hash = root_pkg.name_hash; - lockfile.packages.append(root_pkg)?; + lockfile.packages.append(root_pkg); lockfile.get_or_put_id(0, root_name_hash)?; } @@ -2478,7 +2475,7 @@ pub(crate) fn parse_into_binary_lockfile( // there should be no duplicates let pkg_id = lockfile.append_package_dedupe(&mut pkg)?; - let entry = pkg_map.get_or_put(name)?; + let entry = pkg_map.get_or_put(name); if entry.found_existing { log.add_error_fmt( source, @@ -2696,7 +2693,7 @@ pub(crate) fn parse_into_binary_lockfile( if lockfile_version != Version::V0 { if res.tag == ResolutionTag::Workspace { - let entry = pkg_map.get_or_put(pkg_path)?; + let entry = pkg_map.get_or_put(pkg_path); if entry.found_existing { // this workspace package is already in the package map, because // it was added as a workspaceOnly package earlier @@ -3023,7 +3020,7 @@ pub(crate) fn parse_into_binary_lockfile( let pkg_id = lockfile.append_package_dedupe(&mut pkg)?; - let entry = pkg_map.get_or_put(pkg_path)?; + let entry = pkg_map.get_or_put(pkg_path); if entry.found_existing { log.add_error(Some(source), key_loc, b"Duplicate package path"); return Err(ParseError::InvalidPackageKey); @@ -3109,7 +3106,7 @@ pub(crate) fn parse_into_binary_lockfile( if !dep.behavior.is_workspace() && seen_deps - .get_or_put(dep.name.slice(string_buf))? + .get_or_put(dep.name.slice(string_buf)) .found_existing { resolutions[dep_id as usize] = res_id; @@ -3192,7 +3189,7 @@ pub(crate) fn parse_into_binary_lockfile( return Err(ParseError::InvalidPackageInfo); }; - if seen_deps.get_or_put(dep_name)?.found_existing { + if seen_deps.get_or_put(dep_name).found_existing { resolutions[dep_id as usize] = res_id; continue; } diff --git a/src/install/lockfile/bun.lockb.rs b/src/install/lockfile/bun.lockb.rs index 28d719ae958a..751d92bf0837 100644 --- a/src/install/lockfile/bun.lockb.rs +++ b/src/install/lockfile/bun.lockb.rs @@ -500,7 +500,7 @@ pub(crate) fn load( lockfile .workspace_versions - .ensure_total_capacity(workspace_versions_list.len())?; + .ensure_total_capacity(workspace_versions_list.len()); // SAFETY: capacity reserved above; both columns are fully // overwritten by `copy_from_slice` before `re_index` reads them. unsafe { @@ -516,7 +516,7 @@ pub(crate) fn load( .workspace_versions .values_mut() .copy_from_slice(&workspace_versions_list); - lockfile.workspace_versions.re_index()?; + lockfile.workspace_versions.re_index(); } { @@ -529,7 +529,7 @@ pub(crate) fn load( lockfile .workspace_paths - .ensure_total_capacity(workspace_paths_strings.len())?; + .ensure_total_capacity(workspace_paths_strings.len()); // SAFETY: capacity reserved above; both columns are fully // overwritten by `copy_from_slice` before `re_index` reads them. @@ -546,7 +546,7 @@ pub(crate) fn load( .workspace_paths .values_mut() .copy_from_slice(&workspace_paths_strings); - lockfile.workspace_paths.re_index()?; + lockfile.workspace_paths.re_index(); } } else { stream.pos -= 8; @@ -565,7 +565,7 @@ pub(crate) fn load( lockfile.trusted_dependencies = Some(Default::default()); let td = lockfile.trusted_dependencies.as_mut().unwrap(); - td.ensure_total_capacity(trusted_dependencies_hashes.len())?; + td.ensure_total_capacity(trusted_dependencies_hashes.len()); // The binary lockfile only stores the truncated hashes, not the // names they were computed from. The empty value is the // "name unknown, hash-only match" sentinel. @@ -592,7 +592,7 @@ pub(crate) fn load( lockfile .overrides .map - .ensure_total_capacity(overrides_name_hashes.len())?; + .ensure_total_capacity(overrides_name_hashes.len()); let override_versions_external: Vec = buffers::read_array(stream)?; // reshaped for borrowck — `Context.buffer` borrows @@ -638,7 +638,7 @@ pub(crate) fn load( let map = &mut lockfile.patched_dependencies; - map.ensure_total_capacity(patched_dependencies_name_and_version_hashes.len())?; + map.ensure_total_capacity(patched_dependencies_name_and_version_hashes.len()); let patched_dependencies_paths: Vec = buffers::read_array(stream)?; @@ -681,7 +681,7 @@ pub(crate) fn load( } = &mut *lockfile; let string_bytes: &[u8] = buffers.string_bytes.as_slice(); - catalogs.default.ensure_total_capacity(default_deps.len())?; + catalogs.default.ensure_total_capacity(default_deps.len()); // Both arg and existing keys resolve against the lockfile's // string buffer. @@ -708,7 +708,7 @@ pub(crate) fn load( let catalog_names: Vec = buffers::read_array(stream)?; - catalogs.groups.ensure_total_capacity(catalog_names.len())?; + catalogs.groups.ensure_total_capacity(catalog_names.len()); for catalog_name in &catalog_names { let catalog_dep_names: Vec = buffers::read_array(stream)?; @@ -724,7 +724,7 @@ pub(crate) fn load( } else { let entry = catalogs .groups - .get_or_put_adapted(catalog_name, &StringCtxAdapter(&str_ctx))?; + .get_or_put_adapted(catalog_name, &StringCtxAdapter(&str_ctx)); if !entry.found_existing { *entry.key_ptr = *catalog_name; *entry.value_ptr = super::catalog_map::Map::default(); @@ -732,7 +732,7 @@ pub(crate) fn load( entry.value_ptr }; - group.ensure_total_capacity(catalog_deps.len())?; + group.ensure_total_capacity(catalog_deps.len()); debug_assert_eq!(catalog_dep_names.len(), catalog_deps.len()); for (dep_name, dep) in catalog_dep_names.iter().zip(catalog_deps.iter()) { @@ -813,7 +813,7 @@ pub(crate) fn load( lockfile.string_pool = StringPool::default(); lockfile .package_index - .ensure_total_capacity(lockfile.packages.len())?; + .ensure_total_capacity(lockfile.packages.len()); // `get_or_put_id` only mutates `package_index` (and reads `packages` / // `buffers.string_bytes`), and `workspace_paths.put` only mutates @@ -848,7 +848,7 @@ pub(crate) fn load( // SAFETY: tag == Workspace discriminates the active union field. lockfile .workspace_paths - .put(name_hash, *resolution.workspace())?; + .put(name_hash, *resolution.workspace()); } _ => {} } diff --git a/src/install/lockfile/printer/tree_printer.rs b/src/install/lockfile/printer/tree_printer.rs index 4c7385b7748c..3b15cba5f9f8 100644 --- a/src/install/lockfile/printer/tree_printer.rs +++ b/src/install/lockfile/printer/tree_printer.rs @@ -80,7 +80,7 @@ where | ShouldPrintPackageInstallResult::Return => {} ShouldPrintPackageInstallResult::Update(update_info) => { if update_dedupe - .get_or_put(dependencies[dep_id as usize].name_hash)? + .get_or_put(dependencies[dep_id as usize].name_hash) .found_existing { continue; @@ -155,7 +155,7 @@ where let dep = &dependencies[dep_id as usize]; let package_id = resolutions[dep_id as usize]; - if dep_dedupe.get_or_put(dep.name_hash)?.found_existing { + if dep_dedupe.get_or_put(dep.name_hash).found_existing { continue; } @@ -400,7 +400,7 @@ where let names = packages_slice.items_name(); let name_hashes = packages_slice.items_name_hash(); let pkg_resolutions = packages_slice.items_resolution(); - let mut workspace_targets = Bitset::init_empty(pkg_resolutions.len())?; + let mut workspace_targets = Bitset::init_empty(pkg_resolutions.len()); for &owner in update_owners { for &package_id in packages_slice.items_resolutions()[owner as usize] .get(lockfile.buffers.resolutions.as_slice()) diff --git a/src/install/lockfile/reachable.rs b/src/install/lockfile/reachable.rs index c4e86629b8e1..3ee3ac285efd 100644 --- a/src/install/lockfile/reachable.rs +++ b/src/install/lockfile/reachable.rs @@ -5,7 +5,6 @@ use crate::lockfile_real::Lockfile; use crate::npm::{Architecture, OperatingSystem}; use crate::{PackageID, PackageManager}; use bun_collections::DynamicBitSet; -use bun_core::UnwrapOrOom; #[derive(Clone, Copy)] pub struct Options { @@ -158,7 +157,7 @@ impl<'a> Walk<'a> { } fn empty_seen(&self) -> DynamicBitSet { - DynamicBitSet::init_empty(self.dep_slices.len()).unwrap_or_oom() + DynamicBitSet::init_empty(self.dep_slices.len()) } fn follows(&self, behavior: Behavior) -> bool { diff --git a/src/install/migration/npm_lock.rs b/src/install/migration/npm_lock.rs index 263077dfa258..123ad8642000 100644 --- a/src/install/migration/npm_lock.rs +++ b/src/install/migration/npm_lock.rs @@ -126,7 +126,7 @@ pub(super) fn migrate_packages( debug_assert!(!packages_properties.is_empty() && packages_properties[0].key.slice().is_empty()); let entry_count = packages_properties.len(); - this.packages.ensure_total_capacity(entry_count)?; + this.packages.ensure_total_capacity(entry_count); this.package_index.reserve(entry_count); let mut index = StringHashMap::::default(); @@ -139,9 +139,9 @@ pub(super) fn migrate_packages( entries: packages_properties, workspace_map, index, - link_entries: DynamicBitSet::init_empty(entry_count)?, - shadowed: DynamicBitSet::init_empty(entry_count)?, - skipped_external: DynamicBitSet::init_empty(entry_count)?, + link_entries: DynamicBitSet::init_empty(entry_count), + shadowed: DynamicBitSet::init_empty(entry_count), + skipped_external: DynamicBitSet::init_empty(entry_count), entry_package_ids: vec![INVALID_PACKAGE_ID; entry_count], queue: Vec::new(), probe: Vec::new(), @@ -205,14 +205,14 @@ impl<'a> Migrator<'a> { if let Some(link) = pkg.get(b"link") { self.link_entries.set(j); - self.index.put(key, j as u32)?; + self.index.put(key, j as u32); self.register_renamed_workspace_link(key, pkg, link)?; continue; } if pkg_flag_is_true(pkg, b"extraneous") { continue; } - self.index.put(key, j as u32)?; + self.index.put(key, j as u32); } if self.link_entries.is_set(0) || self.index.get(&b""[..]).copied() != Some(0) { @@ -441,7 +441,7 @@ impl<'a> Migrator<'a> { meta, bin: bin_value, scripts: Default::default(), - })?; + }); self.this.get_or_put_id(id, name_hash)?; self.entry_package_ids[j as usize] = id; self.queue.push((j, id)); diff --git a/src/install/npm.rs b/src/install/npm.rs index 3cc06b469ab1..11ed8dfe470a 100644 --- a/src/install/npm.rs +++ b/src/install/npm.rs @@ -1956,7 +1956,7 @@ impl PackageManifest { fn collect_bundled_deps( version_obj: Option<&JSON::E::ObjectJSON>, set: &mut StringSet, -) -> Result { +) -> bool { set.map.clear_retaining_capacity(); let mut bundle_all_deps = false; if let Some(bundled_deps_value) = version_obj @@ -1972,13 +1972,13 @@ fn collect_bundled_deps( let Some(s) = bundled_dep.as_str() else { continue; }; - set.insert(s)?; + set.insert(s); } } _ => {} } } - Ok(bundle_all_deps) + bundle_all_deps } // Keys are pre-hashed string hashes, so don't re-hash them. @@ -2180,7 +2180,7 @@ impl PackageManifest { } } - bundle_all_deps = collect_bundled_deps(version_obj, &mut bundled_deps_set)?; + bundle_all_deps = collect_bundled_deps(version_obj, &mut bundled_deps_set); for pair in &DEPENDENCY_GROUPS { if let Some(obj) = version_obj @@ -2352,9 +2352,9 @@ impl PackageManifest { .unwrap_or(&[]); let mut time_index: HashMap> = HashMap::default(); if !time_props.is_empty() { - time_index.ensure_total_capacity(time_props.len())?; + time_index.ensure_total_capacity(time_props.len()); for (i, p) in time_props.iter().enumerate() { - let gop = time_index.get_or_put(Wyhash11::hash(0, p.key.slice()))?; + let gop = time_index.get_or_put(Wyhash11::hash(0, p.key.slice())); if !gop.found_existing { *gop.value_ptr = i as u32; } @@ -2384,7 +2384,7 @@ impl PackageManifest { let version_obj = prop.value.as_object(); - bundle_all_deps = collect_bundled_deps(version_obj, &mut bundled_deps_set)?; + bundle_all_deps = collect_bundled_deps(version_obj, &mut bundled_deps_set); let mut package_version: PackageVersion = empty_version; @@ -2830,7 +2830,7 @@ impl PackageManifest { let version_map_hash = version_hasher.final_(); let name_entry = - all_extern_strings_dedupe_map.get_or_put(name_map_hash)?; + all_extern_strings_dedupe_map.get_or_put(name_map_hash); if name_entry.found_existing { name_list = *name_entry.value_ptr; // this_names = name_list.mut(all_extern_strings) — only used in debug asserts below @@ -2840,7 +2840,7 @@ impl PackageManifest { } let version_entry = - version_extern_strings_dedupe_map.get_or_put(version_map_hash)?; + version_extern_strings_dedupe_map.get_or_put(version_map_hash); if version_entry.found_existing { version_list = *version_entry.value_ptr; } else { diff --git a/src/install/patch_install.rs b/src/install/patch_install.rs index c5162af3567d..47ef976ebaae 100644 --- a/src/install/patch_install.rs +++ b/src/install/patch_install.rs @@ -259,12 +259,10 @@ impl PatchTask { Global::crash(); }; - let gop = bun_core::handle_oom( - manager - .lockfile - .patched_dependencies - .get_or_put(calc_hash.name_and_version_hash), - ); + let gop = manager + .lockfile + .patched_dependencies + .get_or_put(calc_hash.name_and_version_hash); if gop.found_existing { gop.value_ptr.set_patchfile_hash(Some(hash)); } else { diff --git a/src/install/pnpm.rs b/src/install/pnpm.rs index abf7916c98f8..771cd2694eb3 100644 --- a/src/install/pnpm.rs +++ b/src/install/pnpm.rs @@ -169,7 +169,7 @@ fn collect_patch_paths( let key = prop.key.as_ref().expect("infallible: prop has key"); let value = prop.value.as_ref().expect("infallible: prop has value"); if let (Some(key_str), Some(path_str)) = (as_string(key), as_string(value)) { - out.put(key_str, Box::from(path_str))?; + out.put(key_str, Box::from(path_str)); } } Ok(()) @@ -242,7 +242,7 @@ fn read_named_registries( let key = prop.key.as_ref().expect("infallible: prop has key"); let value = prop.value.as_ref().expect("infallible: prop has value"); if let (Some(name_str), Some(url_str)) = (as_string(key), as_string(value)) { - registries.put(name_str, Box::from(url_str))?; + registries.put(name_str, Box::from(url_str)); } } } @@ -251,7 +251,7 @@ fn read_named_registries( for (name, url) in BUILTIN_NAMED_REGISTRIES { if !registries.contains(name) { - registries.put(name, Box::from(url))?; + registries.put(name, Box::from(url)); } } @@ -709,7 +709,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( }; let path = sbuf!(lockfile).append(path_str)?; - patches.get_or_put(hash_str)?.value_ptr.push(Patch { + patches.get_or_put(hash_str).value_ptr.push(Patch { path, config_key: Box::from(config_key), }); @@ -778,7 +778,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( let name_hash = semver::string::Builder::string_hash(name); let path_str = sbuf!(lockfile).append(importer_path)?; - lockfile.workspace_paths.put(name_hash, path_str)?; + lockfile.workspace_paths.put(name_hash, path_str); if let Some(version_expr) = value.get(b"version") { let Some(version_raw) = as_string(&version_expr) else { @@ -793,7 +793,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( lockfile .workspace_versions - .put(name_hash, parsed.version.min())?; + .put(name_hash, parsed.version.min()); } } @@ -832,7 +832,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( root_pkg.name_hash = name_hash; } - let importer_versions = importer_dep_res_versions.get_or_put(b".")?; + let importer_versions = importer_dep_res_versions.get_or_put(b"."); *importer_versions.value_ptr = StringArrayHashMap::new(); let (off, len) = parse_append_importer_dependencies( @@ -854,13 +854,13 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( root_pkg.meta.id = 0; root_pkg.resolution = Resolution::init_root(); let root_name_hash = root_pkg.name_hash; - lockfile.packages.append(root_pkg)?; + lockfile.packages.append(root_pkg); lockfile.get_or_put_id(0, root_name_hash)?; } let mut pkg_map: StringArrayHashMap = StringArrayHashMap::new(); - pkg_map.put(crate::bun_fs::FileSystem::instance().top_level_dir(), 0)?; + pkg_map.put(crate::bun_fs::FileSystem::instance().top_level_dir(), 0); let workspace_pkgs_off = lockfile.packages.len(); @@ -908,7 +908,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( pkg.name = sbuf!(lockfile).append_with_hash(name, name_hash)?; pkg.name_hash = name_hash; - let importer_versions = importer_dep_res_versions.get_or_put(path)?; + let importer_versions = importer_dep_res_versions.get_or_put(path); if importer_versions.found_existing { return Err(invalid_pnpm_lockfile()); } @@ -945,7 +945,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( let pkg_id = lockfile.append_package_dedupe(&mut pkg)?; - let entry = pkg_map.get_or_put(&abs_path)?; + let entry = pkg_map.get_or_put(&abs_path); if entry.found_existing { return Err(invalid_pnpm_lockfile()); } @@ -1048,7 +1048,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( let mut abs_link_path = bun_paths::AutoAbsPath::init_top_level_dir(); let _ = abs_link_path.join(&[workspace_path, link_path]); // path-buffer overflow unreachable for bounded inputs - let pkg_entry = pkg_map.get_or_put(abs_link_path.slice())?; + let pkg_entry = pkg_map.get_or_put(abs_link_path.slice()); if pkg_entry.found_existing { // they point to the same package continue; @@ -1114,7 +1114,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( } // Pruned lockfiles (`turbo prune`) can leave peer-suffixed keys in `packages:`. - let entry = packages_by_key.get_or_put(remove_suffix(key_str))?; + let entry = packages_by_key.get_or_put(remove_suffix(key_str)); if entry.found_existing { continue; } @@ -1250,7 +1250,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( .copied() .filter(|id| (*id as usize) < workspace_pkgs_end) { - pkg_map.put(key_str, workspace_pkg_id)?; + pkg_map.put(key_str, workspace_pkg_id); continue; } } @@ -1273,7 +1273,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( lockfile.patched_dependencies.put( semver::string::Builder::string_hash(&patch_join_buf), crate::lockfile_real::PatchedDep::with_path(patch.path), - )?; + ); if Dependency::split_name_and_maybe_version(&patch.config_key) .1 .is_none() @@ -1281,7 +1281,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( found_patches.put( &patch.config_key, Box::from(&patch_join_buf[name_str.len() + 1..]), - )?; + ); } } } @@ -1308,7 +1308,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( url, )) => { - if !warned_registries.get_or_put(registry_name)?.found_existing + if !warned_registries.get_or_put(registry_name).found_existing && !silent { bun_core::warn!( @@ -1321,7 +1321,7 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( } Some(_) => scope_registry, None => { - if !warned_registries.get_or_put(registry_name)?.found_existing + if !warned_registries.get_or_put(registry_name).found_existing && !silent { bun_core::warn!( @@ -1394,10 +1394,10 @@ pub(crate) fn migrate_pnpm_lockfile<'a>( let pkg_id = lockfile.append_package_dedupe(&mut pkg)?; if has_unbound_peers { - packages_with_unbound_peers.put(pkg_id, ())?; + packages_with_unbound_peers.put(pkg_id, ()); } - pkg_map.put(key_str, pkg_id)?; + pkg_map.put(key_str, pkg_id); } } @@ -1692,14 +1692,14 @@ fn append_snapshot_dependency_version( let registry_qualified = split_registry_qualified_version(version_str); if registry_qualified.is_none() && !version_str.first().is_some_and(u8::is_ascii_digit) { - references_by_name.put(dep_name, Box::from(reference))?; + references_by_name.put(dep_name, Box::from(reference)); return Ok((sbuf!(lockfile).append(version_str)?, None)); } let alias = sbuf!(lockfile).append_external(alias_str)?; version_buf.clear(); let version_str = match registry_qualified { Some((_, version)) => { - references_by_name.put(dep_name, Box::from(reference))?; + references_by_name.put(dep_name, Box::from(reference)); version } None => version_str, @@ -1715,7 +1715,7 @@ fn append_snapshot_dependency_version( return Ok((version, Some(alias))); } } else if let Some((_, version_str)) = split_registry_qualified_version(reference) { - references_by_name.put(dep_name, Box::from(reference))?; + references_by_name.put(dep_name, Box::from(reference)); return Ok((sbuf!(lockfile).append(version_str)?, None)); } Ok((sbuf!(lockfile).append(reference)?, None)) @@ -1749,7 +1749,7 @@ fn declared_package_peers( optional: false, seen: false, }, - )?; + ); } } @@ -1776,7 +1776,7 @@ fn declared_package_peers( optional: true, seen: false, }, - )?, + ), } } } @@ -1839,7 +1839,7 @@ fn parse_append_package_dependencies( behavior.set_optional(decl.optional); let range = sbuf!(lockfile).append(decl.range)?; let range_sliced = range.sliced(string_bytes!(lockfile)); - references_by_name.put(name_str, Box::from(reference))?; + references_by_name.put(name_str, Box::from(reference)); if let Some(version) = Dependency::parse( name.value, name.hash, @@ -1930,7 +1930,7 @@ fn parse_append_package_dependencies( for (i, dep) in lockfile.buffers.dependencies[off..end].iter().enumerate() { if let Some(reference) = references_by_name.get(dep.name.slice(bytes)) { let dep_id = u32::try_from(off + i).expect("int cast"); - snapshot_dep_paths.put(dep_id, reference.clone())?; + snapshot_dep_paths.put(dep_id, reference.clone()); } } } @@ -1969,7 +1969,7 @@ fn bind_peers_from_variant( .map(remove_suffix) .filter(|reference| !strings::has_prefix_comptime(reference, b"link:")); match reference { - Some(reference) => snapshot_dep_paths.put(dep_id, Box::from(reference))?, + Some(reference) => snapshot_dep_paths.put(dep_id, Box::from(reference)), None => all_bound = false, } } @@ -2067,7 +2067,7 @@ fn collect_manifest_peers( let key = prop.key.as_ref().expect("infallible: prop has key"); let value = prop.value.as_ref().expect("infallible: prop has value"); if let (Some(name_str), Some(range)) = (as_string(key), as_string(value)) { - peers.put(name_str, (range, false))?; + peers.put(name_str, (range, false)); } } } @@ -2084,7 +2084,7 @@ fn collect_manifest_peers( } match peers.get_mut(name_str) { Some(entry) => entry.1 = true, - None => peers.put(name_str, (b"*", true))?, + None => peers.put(name_str, (b"*", true)), } } } @@ -2174,7 +2174,7 @@ fn parse_append_importer_dependencies( continue; } - let entry = importer_versions.get_or_put(name_str)?; + let entry = importer_versions.get_or_put(name_str); if entry.found_existing { continue; } diff --git a/src/install/postinstall_optimizer.rs b/src/install/postinstall_optimizer.rs index 5a7f06e89d28..2fcd7c0ef9cf 100644 --- a/src/install/postinstall_optimizer.rs +++ b/src/install/postinstall_optimizer.rs @@ -62,7 +62,7 @@ impl PostinstallOptimizer { continue; } list.dynamic - .put(semver::string::Builder::string_hash(str), value)?; + .put(semver::string::Builder::string_hash(str), value); } Ok(true) diff --git a/src/install/prune.rs b/src/install/prune.rs index 01aa08b4607c..628a0ced2752 100644 --- a/src/install/prune.rs +++ b/src/install/prune.rs @@ -563,14 +563,14 @@ fn select_importers(manager: &PackageManager, original_cwd: &[u8]) -> Option> = Vec::new(); let mut worklist: Vec = Vec::new(); for importer in 0..pkg_res.len() { @@ -697,9 +697,9 @@ impl<'a> HoistedTree<'a> { }; } - let checked = handle_oom(DynamicBitSet::init_empty(expected.len())); - let matched = handle_oom(DynamicBitSet::init_empty(expected.len())); - let missing = handle_oom(DynamicBitSet::init_empty(expected.len())); + let checked = DynamicBitSet::init_empty(expected.len()); + let matched = DynamicBitSet::init_empty(expected.len()); + let missing = DynamicBitSet::init_empty(expected.len()); HoistedTree { lockfile, trees, @@ -923,7 +923,7 @@ fn plan_hoisted( None => Vec::new(), }; - let mut visited = handle_oom(DynamicBitSet::init_empty(pkg_res.len())); + let mut visited = DynamicBitSet::init_empty(pkg_res.len()); for tree_idx in 0..hoisted.folders.len() { let folder_path = hoisted.path(tree_idx); if folder_path.is_empty() { @@ -1681,7 +1681,7 @@ fn remove_link(dir: &Dir, name: &[u8]) -> sys::Maybe<()> { fn execute(plan: &Plan, quiet: bool) -> usize { let mut failed = 0usize; - let mut removed_from = handle_oom(DynamicBitSet::init_empty(plan.folders.len())); + let mut removed_from = DynamicBitSet::init_empty(plan.folders.len()); for removal in &plan.removals { let dir = plan.dir(removal.folder); diff --git a/src/install/repository.rs b/src/install/repository.rs index 7d86db59cd51..5ba145a82f8a 100644 --- a/src/install/repository.rs +++ b/src/install/repository.rs @@ -254,22 +254,22 @@ impl SharedEnv { // A value can still be entered, but we need to find a workaround // so the user can see what is being prompted. By default the settings // below will cause no prompt and throw instead. - let mut cloned = bun_core::handle_oom(other.map.clone_with_allocator()); + let mut cloned = other.map.clone(); if cloned.get(b"GIT_ASKPASS").is_none() { let config = SloppyGlobalGitConfig::get(); if !config.has_askpass { - bun_core::handle_oom(cloned.put(b"GIT_ASKPASS", b"echo")); + cloned.put(b"GIT_ASKPASS", b"echo"); } } if cloned.get(b"GIT_SSH_COMMAND").is_none() { let config = SloppyGlobalGitConfig::get(); if !config.has_ssh_command { - bun_core::handle_oom(cloned.put( + cloned.put( b"GIT_SSH_COMMAND", b"ssh -oStrictHostKeyChecking=accept-new", - )); + ); } } @@ -363,10 +363,8 @@ pub trait RepositoryExt: Sized { /// A module-level free fn because trait methods cannot be private; called only /// from this file's `download`/`find_commit`/`checkout`. fn exec(env: &bun_dotenv::Map, argv: &[&[u8]]) -> Result, Error> { - // `Map` is move-only; clone via `clone_with_allocator` so callers can - // hand us a shared `&Map` (matches `PackageManagerTask` call sites). - let mut env = bun_core::handle_oom(env.clone_with_allocator()); - let std_map = env.std_env_map()?; + let mut env = env.clone(); + let std_map = env.std_env_map(); // `bun_spawn::run` does POSIX argv/envp marshalling // + `process::sync::spawn`. On Windows it supplies the thread's diff --git a/src/install/update_scope.rs b/src/install/update_scope.rs index 52a986ec0e9a..0759fa5493c5 100644 --- a/src/install/update_scope.rs +++ b/src/install/update_scope.rs @@ -5,7 +5,7 @@ use bstr::BStr; use bun_collections::bit_set::Range; use bun_collections::{DynamicBitSet, HashMap, index_sort}; use bun_core::time::nano_timestamp; -use bun_core::{Global, Output, UnwrapOrOom as _, pretty, strings}; +use bun_core::{Global, Output, pretty, strings}; use bun_semver::string::Builder as StringBuilder; use crate::dependency::Behavior; @@ -86,7 +86,7 @@ impl UpdateScope<'_> { fn walk(&self, lockfile: &Lockfile) -> DynamicBitSet { let pkg_res = lockfile.packages.items_resolution(); if self.whole_workspace { - let mut all = DynamicBitSet::init_empty(pkg_res.len()).unwrap_or_oom(); + let mut all = DynamicBitSet::init_empty(pkg_res.len()); all.unmanaged.set_all(true); return all; } @@ -160,8 +160,7 @@ impl UpdateScope<'_> { /// One bit per dependency row; rows covered by no package's slice (orphans left by the differ) stay unset. pub fn walkable_rows(&self, lockfile: &Lockfile) -> DynamicBitSet { - let mut walk = - DynamicBitSet::init_empty(lockfile.buffers.dependencies.len()).unwrap_or_oom(); + let mut walk = DynamicBitSet::init_empty(lockfile.buffers.dependencies.len()); for (id, slice) in lockfile.packages.items_dependencies().iter().enumerate() { if slice.len == 0 { continue; diff --git a/src/install/update_transitive.rs b/src/install/update_transitive.rs index d53d2adbd821..f51d17e34c0a 100644 --- a/src/install/update_transitive.rs +++ b/src/install/update_transitive.rs @@ -4,7 +4,7 @@ use std::io::Write as _; use bstr::BStr; use bun_collections::bit_set::Range as BitRange; use bun_collections::{DynamicBitSet, index_sort}; -use bun_core::{Output, UnwrapOrOom as _, pretty, prettyln, strings}; +use bun_core::{Output, pretty, prettyln, strings}; use bun_semver as Semver; use crate::audit_fix; @@ -101,7 +101,7 @@ impl DirectDependencies { } else { // Every row before the first miss was a same-index hit. let taken = claimed.get_or_insert_with(|| { - let mut taken = DynamicBitSet::init_empty(rows.len()).unwrap_or_oom(); + let mut taken = DynamicBitSet::init_empty(rows.len()); taken.set_range_value( BitRange { start: 0, @@ -277,7 +277,7 @@ impl TransitiveUpdate { let lockfile = &*manager.lockfile; let scope = UpdateScope::of(&*manager); let owners = (!scope.is_whole_workspace()).then(|| scope.reachable(lockfile)); - let mut edges = DynamicBitSet::init_empty(lockfile.buffers.dependencies.len())?; + let mut edges = DynamicBitSet::init_empty(lockfile.buffers.dependencies.len()); for owner in 0..lockfile.packages.len() { if owners.is_none_or(|reachable| reachable.is_set_allow_out_of_bound(owner, false)) { @@ -302,7 +302,7 @@ impl TransitiveUpdate { /// Like `enqueue`, also returning the rows it pinned so later invalidation passes leave them alone. pub fn enqueue_tracked(&self, manager: &mut PackageManager) -> crate::Result { - let mut pinned = DynamicBitSet::init_empty(manager.lockfile.buffers.resolutions.len())?; + let mut pinned = DynamicBitSet::init_empty(manager.lockfile.buffers.resolutions.len()); self.enqueue_inner(manager, Some(&mut pinned))?; Ok(pinned) } @@ -409,7 +409,7 @@ pub(crate) fn refresh_children_of( } let edges = { let lockfile = &*manager.lockfile; - let mut edges = DynamicBitSet::init_empty(lockfile.buffers.dependencies.len())?; + let mut edges = DynamicBitSet::init_empty(lockfile.buffers.dependencies.len()); for &owner in package_ids { if (owner as usize) < lockfile.packages.len() { set_rows_of(&mut edges, lockfile, owner as usize); @@ -562,7 +562,7 @@ pub(crate) fn register_moved( continue; } let current = res[pkg_id as usize].npm().version; - let entry = updating.get_or_put(names[pkg_id as usize].slice(buf))?; + let entry = updating.get_or_put(names[pkg_id as usize].slice(buf)); if entry.found_existing { let info = &*entry.value_ptr; let keep = !info.original_version_literal.is_empty() @@ -864,7 +864,7 @@ fn warn_unchecked( } let log = manager.log_mut(); let silent = manager.options.log_level == LogLevel::Silent; - let mut used = DynamicBitSet::init_empty(log.msgs.len()).unwrap_or_oom(); + let mut used = DynamicBitSet::init_empty(log.msgs.len()); for (name, version) in unchecked { let reason = log .msgs @@ -976,7 +976,7 @@ pub(crate) fn plannable_peer_rows( let deps = lockfile.buffers.dependencies.as_slice(); let resolutions = lockfile.buffers.resolutions.as_slice(); - let mut providers = DynamicBitSet::init_empty(packages_len).unwrap_or_oom(); + let mut providers = DynamicBitSet::init_empty(packages_len); for &(_, behavior, resolved) in &direct.rows { if !behavior.is_peer() && (resolved as usize) < packages_len { providers.set(resolved as usize); @@ -994,7 +994,7 @@ pub(crate) fn plannable_peer_rows( } } - let mut rows = DynamicBitSet::init_empty(deps.len()).unwrap_or_oom(); + let mut rows = DynamicBitSet::init_empty(deps.len()); for owner in 0..packages_len { if matches!( pkg_res[owner].tag, diff --git a/src/install/yarn.rs b/src/install/yarn.rs index cbcc3613b691..9848ec5bdc6a 100644 --- a/src/install/yarn.rs +++ b/src/install/yarn.rs @@ -368,7 +368,7 @@ impl<'a> YarnLock<'a> { DependencyType::Peer => current_peer_deps.as_mut().unwrap(), DependencyType::Development => current_dev_deps.as_mut().unwrap(), }; - map.put(key, value)?; + map.put(key, value); } continue; } @@ -758,9 +758,9 @@ pub(crate) fn migrate_yarn_lockfile<'a>( this.buffers .resolutions .reserve((num_deps as usize).saturating_sub(this.buffers.resolutions.len())); - this.packages.ensure_total_capacity(num_packages as usize)?; + this.packages.ensure_total_capacity(num_packages as usize); this.package_index - .ensure_total_capacity(num_packages as usize)?; + .ensure_total_capacity(num_packages as usize); let root_name = if let Some(name) = &package_name { sbuf!().append_with_hash(name, package_name_hash)? @@ -786,7 +786,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( }, bin: Bin::init(), scripts: Default::default(), - })?; + }); } // SAFETY: capacity reserved above to num_deps; we write past `len` through @@ -879,7 +879,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( } } - scoped_packages.put(name, list)?; + scoped_packages.put(name, list); } else { yarn_entry_to_package_id[yarn_idx] = existing.package_id; } @@ -894,7 +894,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( package_id, yarn_idx, }, - )?; + ); } } @@ -1112,7 +1112,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( }, bin: Bin::init(), scripts: Default::default(), - })?; + }); } // The derive's `&mut self` accessors can't alias, so we re-borrow per write @@ -1459,7 +1459,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( for (dep_name_key, _) in deps.iter() { if dep_name_key.as_ref() == base_name { let count = usage_count.get(base_name).copied().unwrap_or(0); - usage_count.put(base_name, count + 1)?; + usage_count.put(base_name, count + 1); } } } @@ -1474,7 +1474,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( let base_name = package_names[package_id as usize]; if root_packages.get(base_name).is_none() { - root_packages.put(base_name, package_id)?; + root_packages.put(base_name, package_id); let name_hash = string_hash(base_name); this.get_or_put_id(package_id, name_hash)?; } @@ -1572,7 +1572,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( if let Some(final_scoped_name) = scoped_name { let name_hash = string_hash(&final_scoped_name); this.get_or_put_id(package_id, name_hash)?; - scoped_names.put(package_id, final_scoped_name)?; + scoped_names.put(package_id, final_scoped_name); scoped_count += 1; } } @@ -1609,7 +1609,7 @@ pub(crate) fn migrate_yarn_lockfile<'a>( } for spec in entry.specs.iter() { - spec_to_package_id.put(*spec, package_id)?; + spec_to_package_id.put(*spec, package_id); } } diff --git a/src/install_jsc/ini_jsc.rs b/src/install_jsc/ini_jsc.rs index bc31d3f18821..c82aa1e2a035 100644 --- a/src/install_jsc/ini_jsc.rs +++ b/src/install_jsc/ini_jsc.rs @@ -58,7 +58,7 @@ impl IniTestingAPIs { ), )?; - envmap.ensure_total_capacity(object_iter.len)?; + envmap.ensure_total_capacity(object_iter.len); while let Some(key) = object_iter.next()? { let keyslice = key.to_owned_slice(); @@ -75,7 +75,7 @@ impl IniTestingAPIs { dotenv::map::Entry { value: slice.into_boxed_slice(), }, - )?; + ); } env_storage.insert(dotenv::Loader::init_with_map(dotenv::Map { map: envmap })) diff --git a/src/js_parser/fold.rs b/src/js_parser/fold.rs index 911e1e76de30..9016e9aee292 100644 --- a/src/js_parser/fold.rs +++ b/src/js_parser/fold.rs @@ -159,8 +159,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O p.import_items_for_namespace .get_mut(&id.ref_) .unwrap() - .put(name, new_item) - .expect("unreachable"); + .put(name, new_item); p.is_import_item.insert(new_ref, ()); let symbol = &mut p.symbols[new_ref.inner_index() as usize]; @@ -395,18 +394,16 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O p.new_symbol(js_ast::symbol::Kind::Other, sym_name); // SAFETY: module_scope is arena-owned and valid for 'a. VecExt::append(&mut p.module_scope_mut().generated, new_ref); - p.commonjs_named_exports - .put( - name, - CommonJSNamedExport { - loc_ref: LocRef { - loc: name_loc, - ref_: new_ref, - }, - needs_decl: true, + p.commonjs_named_exports.put( + name, + CommonJSNamedExport { + loc_ref: LocRef { + loc: name_loc, + ref_: new_ref, }, - ) - .expect("unreachable"); + needs_decl: true, + }, + ); if p.commonjs_named_exports_needs_conversion == u32::MAX { p.commonjs_named_exports_needs_conversion = (p.commonjs_named_exports.count() - 1) as u32; @@ -570,12 +567,8 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O // Add a special symbol use instead let gop = p .import_symbol_property_uses - .get_or_put_value(id.ref_, Default::default()) - .expect("unreachable"); - let inner_use = gop - .value_ptr - .get_or_put_value(name, Default::default()) - .expect("unreachable"); + .get_or_put_value(id.ref_, Default::default()); + let inner_use = gop.value_ptr.get_or_put_value(name, Default::default()); inner_use.count_estimate += 1; } } @@ -627,18 +620,16 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O &mut p.module_scope_mut().generated, new_ref, ); - p.commonjs_named_exports - .put( - name, - CommonJSNamedExport { - loc_ref: LocRef { - loc: name_loc, - ref_: new_ref, - }, - needs_decl: true, + p.commonjs_named_exports.put( + name, + CommonJSNamedExport { + loc_ref: LocRef { + loc: name_loc, + ref_: new_ref, }, - ) - .expect("unreachable"); + needs_decl: true, + }, + ); if p.commonjs_named_exports_needs_conversion == u32::MAX { p.commonjs_named_exports_needs_conversion = (p.commonjs_named_exports.count() - 1) as u32; diff --git a/src/js_parser/lower/lower_esm_exports_hmr.rs b/src/js_parser/lower/lower_esm_exports_hmr.rs index 1299e8b030ba..c50b535e50b3 100644 --- a/src/js_parser/lower/lower_esm_exports_hmr.rs +++ b/src/js_parser/lower/lower_esm_exports_hmr.rs @@ -192,10 +192,10 @@ impl<'a> ConvertESMExportsForHmr<'a> { .append(js_ast::DeclaredSymbol { ref_: temp_id, is_top_level: true, - })?; + }); self.last_part .symbol_uses - .put_no_clobber(temp_id, js_ast::symbol::Use { count_estimate: 1 })?; + .put_no_clobber(temp_id, js_ast::symbol::Use { count_estimate: 1 }); // SAFETY: `current_scope` is a live arena ptr for the parser lifetime. VecExt::append(&mut p.current_scope_mut().generated, temp_id); @@ -406,7 +406,7 @@ impl<'a> ConvertESMExportsForHmr<'a> { let path_text = p.import_records.items()[import_record_index as usize] .path .text; - let gop = self.imports_seen.get_or_put(path_text)?; + let gop = self.imports_seen.get_or_put(path_text); if gop.found_existing { let stmt_index = gop.value_ptr.stmt_index; // Disable this one since an older record is getting used. It isn't @@ -590,10 +590,10 @@ impl<'a> ConvertESMExportsForHmr<'a> { .append(js_ast::DeclaredSymbol { ref_: arg1, is_top_level: true, - })?; + }); self.last_part .symbol_uses - .put_no_clobber(arg1, js_ast::symbol::Use { count_estimate: 1 })?; + .put_no_clobber(arg1, js_ast::symbol::Use { count_estimate: 1 }); // SAFETY: `current_scope` is a live arena ptr for the parser lifetime. VecExt::append(&mut p.current_scope_mut().generated, arg1); @@ -684,13 +684,13 @@ impl<'a> ConvertESMExportsForHmr<'a> { // mark a dependency on module_ref so it is renamed self.last_part .symbol_uses - .put(p.module_ref, js_ast::symbol::Use { count_estimate: 1 })?; + .put(p.module_ref, js_ast::symbol::Use { count_estimate: 1 }); self.last_part .declared_symbols .append(js_ast::DeclaredSymbol { ref_: p.module_ref, is_top_level: true, - })?; + }); } if p.options.features.react_fast_refresh && p.react_refresh.register_used { @@ -726,7 +726,7 @@ impl<'a> ConvertESMExportsForHmr<'a> { for part in head_parts.iter_mut() { self.last_part .declared_symbols - .append_list(&core::mem::take(&mut part.declared_symbols))?; + .append_list(&core::mem::take(&mut part.declared_symbols)); self.last_part .import_record_indices .append_slice(part.import_record_indices.slice()); @@ -735,7 +735,7 @@ impl<'a> ConvertESMExportsForHmr<'a> { for i in 0..part.symbol_uses.count() { let k = part.symbol_uses.keys()[i]; let v = part.symbol_uses.values()[i]; - let gop = self.last_part.symbol_uses.get_or_put(k)?; + let gop = self.last_part.symbol_uses.get_or_put(k); if !gop.found_existing { *gop.value_ptr = v; } else { @@ -757,7 +757,7 @@ impl<'a> ConvertESMExportsForHmr<'a> { .append_slice(p.import_records_for_current_part.as_slice()); self.last_part .declared_symbols - .append_list(&p.declared_symbols)?; + .append_list(&p.declared_symbols); // Note: `Stmt` is `Copy`; // copy into the parser arena so the `StoreSlice` outlives this struct. diff --git a/src/js_parser/p.rs b/src/js_parser/p.rs index e14684e6a2f2..cab7eabca0c5 100644 --- a/src/js_parser/p.rs +++ b/src/js_parser/p.rs @@ -1426,7 +1426,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O alias_loc: loc, ref_: r#ref, }, - )?; + ); } Ok(()) } @@ -1446,11 +1446,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O debug_assert!(self.symbols.len() > ref_.inner_index() as usize); self.symbols[ref_.inner_index() as usize].use_count_estimate += 1; // `get_or_put` zero-initializes the slot on insert (`Use::default()`). - self.symbol_uses - .get_or_put(ref_) - .expect("unreachable") - .value_ptr - .count_estimate += 1; + self.symbol_uses.get_or_put(ref_).value_ptr.count_estimate += 1; } // The correctness of TypeScript-to-JavaScript conversion relies on accurate @@ -1699,7 +1695,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O self.add_import_record_by_range(ImportKind::Stmt, bun_ast::Range::NONE, import_path); let mut declared_symbols = bun_ast::DeclaredSymbolList::default(); - declared_symbols.ensure_total_capacity(2)?; + declared_symbols.ensure_total_capacity(2); declared_symbols.append_assume_capacity(DeclaredSymbol { ref_: self.bun_app_namespace_ref, @@ -1745,7 +1741,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O alias_is_star: false, is_exported: false, }, - )?; + ); let import_stmt = self.s( S::Import { @@ -1830,7 +1826,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } }); let mut declared_symbols = bun_ast::DeclaredSymbolList::default(); - declared_symbols.ensure_total_capacity(imports.len() + 1)?; + declared_symbols.ensure_total_capacity(imports.len() + 1); let namespace_ref = self.new_symbol(js_ast::symbol::Kind::Other, namespace_identifier); declared_symbols.append_assume_capacity(DeclaredSymbol { @@ -1881,7 +1877,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O alias_is_star: false, is_exported: false, }, - )?; + ); } let import_stmt = self.s( @@ -1974,7 +1970,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O ); let mut declared_symbols = bun_ast::DeclaredSymbolList::default(); - declared_symbols.ensure_total_capacity(len)?; + declared_symbols.ensure_total_capacity(len); let namespace_ref = self.new_symbol(js_ast::symbol::Kind::Other, b"RefreshRuntime"); declared_symbols.append_assume_capacity(DeclaredSymbol { @@ -2022,7 +2018,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O alias_is_star: false, is_exported: false, }, - )?; + ); } } @@ -3228,12 +3224,12 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O let order_scope = order.scope_ref(); if (cfg!(debug_assertions) && order.loc.start != loc.start) || order_scope.kind != kind { self.log().level = bun_ast::Level::Verbose; - let _ = self.log().add_debug_fmt( + self.log().add_debug_fmt( Some(self.source), loc, format_args!("Expected this scope (.{})", <&'static str>::from(kind)), ); - let _ = self.log().add_debug_fmt( + self.log().add_debug_fmt( Some(self.source), order.loc, format_args!( @@ -3308,12 +3304,12 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O if let Some(prev_loc) = self.scopes_in_order[last_i].as_ref().map(|s| s.loc) { if prev_loc.start >= loc.start { self.log().level = bun_ast::Level::Verbose; - let _ = self.log().add_debug_fmt( + self.log().add_debug_fmt( Some(self.source), prev_loc, format_args!("Previous Scope"), ); - let _ = self.log().add_debug_fmt( + self.log().add_debug_fmt( Some(self.source), loc, format_args!("Next Scope"), @@ -3346,7 +3342,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O // lexer string-table (see `get_or_put_member_with_hash`), // both of which outlive every arena-backed `Scope`. Avoids // a per-argument `mi_heap_malloc` on every function body. - unsafe { scope.members.put_borrowed(key, value)? }; + unsafe { scope.members.put_borrowed(key, value) }; } } } @@ -3633,7 +3629,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O import_record_id: id, name: Some(b"default"), }, - )?; + ); } if let Some(star) = stmt.star_name_loc.to_nullable() { @@ -3646,7 +3642,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O import_record_id: id, name: None, }, - )?; + ); } // arena-owned `StoreSlice` valid for parser 'a. @@ -3662,7 +3658,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O import_record_id: id, name: Some(item.alias.slice()), }, - )?; + ); } return Ok(self.s(S::Empty {}, loc)); @@ -3757,8 +3753,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O used: false, import_record_index: stmt.import_record_index, }, - ) - .expect("unreachable"); + ); } } @@ -3781,7 +3776,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O let count_excluding_namespace = u16::try_from(stmt.items.len()).expect("int cast") + u16::from(stmt.default_name.is_some()); - item_refs.ensure_unused_capacity(count_excluding_namespace as usize)?; + item_refs.ensure_unused_capacity(count_excluding_namespace as usize); // Even though we allocate ahead of time here // we cannot use putAssumeCapacity because a symbol can have existing links // those may write to this hash table, so this estimate may be innaccurate @@ -3820,7 +3815,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O import_record_id: new_import_id, name: Some(b"default"), }, - )?; + ); self.import_records.items_mut()[new_import_id as usize] .path @@ -3850,8 +3845,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O used: false, import_record_index: stmt.import_record_index, }, - ) - .expect("unreachable"); + ); } } @@ -3901,7 +3895,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O import_record_id: new_import_id, name: Some(alias), }, - )?; + ); self.import_records.items_mut()[new_import_id as usize] .path @@ -3930,8 +3924,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O used: false, import_record_index: stmt.import_record_index, }, - ) - .expect("unreachable"); + ); } } @@ -4150,7 +4143,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O loc: binding.loc, data: js_ast::ts::Data::Property, }, - )?; + ); self.ref_to_ts_namespace_member .insert(id.r#ref, js_ast::ts::Data::Property); } @@ -4481,7 +4474,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O ref_, loc: bun_ast::Loc::EMPTY, }, - )?; + ); return Ok(ref_); } @@ -4869,7 +4862,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O // would make this location absolutely useless. let location = loc.unwrap_or_else(|| self.lexer.loc()); if (location.start as usize) < self.lexer.source.contents.len() && !location.is_empty() { - let _ = self.log().add_range_error_fmt( + self.log().add_range_error_fmt( Some(self.source), bun_ast::Range { loc: location, @@ -4993,7 +4986,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O let Some(ref_) = local.ref_.to_nullable() else { continue; }; - let declaration_entry = already_declared.get_or_put(ref_)?; + let declaration_entry = already_declared.get_or_put(ref_); if !declaration_entry.found_existing { let mut decls = bun_alloc::AstAlloc::vec(); VecExt::append( @@ -5013,7 +5006,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O self.declared_symbols.append(DeclaredSymbol { ref_, is_top_level: true, - })?; + }); } } self.relocated_top_level_vars.clear(); @@ -5069,8 +5062,8 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } else if self.declared_symbols.len() > 0 || self.symbol_uses.count() > 0 { // if the part is dead, invalidate all the usage counts self.clear_symbol_usages_from_dead_part(&js_ast::Part { - declared_symbols: self.declared_symbols.clone()?, - symbol_uses: self.symbol_uses.clone()?, + declared_symbols: self.declared_symbols.clone(), + symbol_uses: self.symbol_uses.clone(), ..Default::default() }); self.declared_symbols.clear_retaining_capacity(); @@ -6119,9 +6112,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O || symbol_kind == js_ast::symbol::Kind::TsEnum) && !self.emitted_namespace_vars.contains_key(&name_ref) { - self.emitted_namespace_vars - .put_no_clobber(name_ref, ()) - .expect("oom"); + self.emitted_namespace_vars.put_no_clobber(name_ref, ()); let decls = js_ast::g::DeclList::from_slice(&[G::Decl { binding: self.b(B::Identifier { r#ref: name_ref }, name_loc), @@ -7516,7 +7507,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O js_ast::ExprData::EArray(mut arr) => { for item in arr.items.slice_mut() { let js_ast::ExprData::EString(mut s) = item.data else { - let _ = self.log().add_error( + self.log().add_error( Some(self.source), item.loc, Self::IMPORT_META_HOT_ACCEPT_ERR, @@ -7550,8 +7541,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O break 'found i; } } - let _ = self - .log() + self.log() .add_error(Some(self.source), loc, Self::IMPORT_META_HOT_ACCEPT_ERR); return None; }; @@ -7706,12 +7696,10 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O // TODO: fix the renamer bug. this bug theoretically affects all // usages of temp refs, but i cannot find another example of it // breaking (like with `using`) - self.declared_symbols - .append(DeclaredSymbol { - is_top_level: true, - ref_: signature_cb, - }) - .expect("oom"); + self.declared_symbols.append(DeclaredSymbol { + is_top_level: true, + ref_: signature_cb, + }); } let ctx: &mut crate::HookContext = ctx_storage.as_mut().unwrap(); @@ -7736,7 +7724,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } else { match &hook_call.target.data { js_ast::ExprData::EIdentifier(id) => { - let gop = ctx.user_hooks.get_or_put(id.ref_).expect("oom"); + let gop = ctx.user_hooks.get_or_put(id.ref_); if !gop.found_existing { *gop.value_ptr = Expr { data: js_ast::ExprData::EIdentifier(*id), @@ -7745,7 +7733,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } } js_ast::ExprData::EImportIdentifier(id) => { - let gop = ctx.user_hooks.get_or_put(id.ref_).expect("oom"); + let gop = ctx.user_hooks.get_or_put(id.ref_); if !gop.found_existing { *gop.value_ptr = Expr { data: js_ast::ExprData::EImportIdentifier(*id), @@ -7754,7 +7742,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } } js_ast::ExprData::ECommonjsExportIdentifier(id) => { - let gop = ctx.user_hooks.get_or_put(id.ref_).expect("oom"); + let gop = ctx.user_hooks.get_or_put(id.ref_); if !gop.found_existing { *gop.value_ptr = Expr { data: js_ast::ExprData::ECommonjsExportIdentifier(*id), @@ -8047,13 +8035,11 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O unsafe { core::ptr::write( &raw mut part.declared_symbols, - self.declared_symbols.clone().expect("unreachable"), + self.declared_symbols.clone(), ); } } else { - part.declared_symbols - .append_list(&self.declared_symbols) - .expect("unreachable"); + part.declared_symbols.append_list(&self.declared_symbols); } if part.import_record_indices.is_empty() { @@ -8496,7 +8482,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O use bun_ast::{InlinedEnumValue, InlinedEnumValueDecoded}; let mut map = bun_ast::ast_result::TsEnumsMap::default(); - map.ensure_total_capacity(self.top_level_enums.len())?; + map.ensure_total_capacity(self.top_level_enums.len()); for r#ref in self.top_level_enums.iter() { let Some(js_ast::ts::Data::Namespace(namespace)) = self.ref_to_ts_namespace_member.get(r#ref) @@ -8506,7 +8492,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O }; let ns: &js_ast::TSNamespaceMemberMap = namespace; let mut inner_map = StringHashMap::::default(); - inner_map.ensure_total_capacity(ns.count())?; + inner_map.ensure_total_capacity(ns.count()); for i in 0..ns.count() { let key = &ns.keys()[i]; let val = &ns.values()[i]; @@ -8644,7 +8630,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O parent: None, ..Default::default() }); - let _ = scope_obj + scope_obj .members .ensure_total_capacity(estimated_symbol_count); let scope = js_ast::StoreRef::from_bump(scope_obj); @@ -8708,7 +8694,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } let mut symbol_uses = SymbolUseMap::default(); - let _ = symbol_uses.ensure_total_capacity(estimated_symbol_count); + symbol_uses.ensure_total_capacity(estimated_symbol_count); // JSX transform mode — was the `` const-generic parameter, // now a runtime field (matches `Parser::parse`'s own `if jsx.parse` @@ -9057,12 +9043,10 @@ impl LowerUsingDeclarationsContext { scope .generated .append_slice(&[self.stack_ref, caught_ref, err_ref, has_err_ref]); - p.declared_symbols - .ensure_unused_capacity( - // 5 to include the _promise decl later on: - if self.has_await_using { 5 } else { 4 }, - ) - .expect("oom"); + p.declared_symbols.ensure_unused_capacity( + // 5 to include the _promise decl later on: + if self.has_await_using { 5 } else { 4 }, + ); p.declared_symbols.append_assume_capacity(DeclaredSymbol { is_top_level, ref_: self.stack_ref, diff --git a/src/js_parser/parse/parse_entry.rs b/src/js_parser/parse/parse_entry.rs index 1d4a4d40bcf9..5e93c0a648bf 100644 --- a/src/js_parser/parse/parse_entry.rs +++ b/src/js_parser/parse/parse_entry.rs @@ -417,7 +417,7 @@ impl<'a> Parser<'a> { // re-hash it one identifier reference at a time (≈ one tracked // symbol per 16 source bytes). `ensure_total_capacity` is a no-op // when the map already retains enough capacity from a prior file. - let _ = scan_pass + scan_pass .used_symbols .ensure_total_capacity(self.source.contents.len() / 16); p.parse_pass_symbol_uses = Some(&mut scan_pass.used_symbols); @@ -1137,8 +1137,7 @@ impl<'a> Parser<'a> { if p.options.bundle || !p.options.features.commonjs_at_runtime { if uses_dirname || uses_filename { let count = (uses_dirname as usize) + (uses_filename as usize); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); + let mut declared_symbols = bun_ast::DeclaredSymbolList::init_capacity(count); let decls = p .arena .alloc_slice_fill_with::(count, |_| G::Decl::default()); @@ -1258,8 +1257,7 @@ impl<'a> Parser<'a> { }, ns_loc, ); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(1).expect("unreachable"); + let mut declared_symbols = bun_ast::DeclaredSymbolList::init_capacity(1); declared_symbols.append_assume_capacity(DeclaredSymbol { ref_: ns_ref, is_top_level: true, @@ -1744,8 +1742,7 @@ impl<'a> Parser<'a> { if exports_kind == js_ast::ExportsKind::Esm && (uses_dirname || uses_filename) { debug_assert!(!p.options.bundle); let count = (uses_dirname as usize) + (uses_filename as usize); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); + let mut declared_symbols = bun_ast::DeclaredSymbolList::init_capacity(count); let decls = p .arena .alloc_slice_fill_with::(count, |_| G::Decl::default()); @@ -1873,7 +1870,7 @@ impl<'a> Parser<'a> { } let mut declared_symbols = bun_ast::DeclaredSymbolList::default(); - declared_symbols.ensure_total_capacity(items_count)?; + declared_symbols.ensure_total_capacity(items_count); // For CommonJS modules, use require instead of import if exports_kind == js_ast::ExportsKind::Cjs { @@ -2144,12 +2141,12 @@ impl<'a> Parser<'a> { declared_symbols.append(DeclaredSymbol { ref_: import.namespace_ref, is_top_level: true, - })?; + }); for item in import.items.iter() { declared_symbols.append(DeclaredSymbol { ref_: item.name.ref_, is_top_level: true, - })?; + }); p.is_import_item.insert(item.name.ref_, ()); p.named_imports.put( item.name.ref_, @@ -2162,7 +2159,7 @@ impl<'a> Parser<'a> { alias_is_star: false, is_exported: false, }, - )?; + ); } } js_ast::StmtData::SFunction(func) => { @@ -2170,7 +2167,7 @@ impl<'a> Parser<'a> { declared_symbols.append(DeclaredSymbol { ref_, is_top_level: true, - })?; + }); } } _ => {} diff --git a/src/js_parser/parse/parse_skip_typescript.rs b/src/js_parser/parse/parse_skip_typescript.rs index 1e40e3b5597a..64591db0a140 100644 --- a/src/js_parser/parse/parse_skip_typescript.rs +++ b/src/js_parser/parse/parse_skip_typescript.rs @@ -1333,7 +1333,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O self.lexer.expect(T::TIdentifier)?; if opts.scope.is_module() { - self.local_type_names.put(name, true)?; + self.local_type_names.put(name, true); } let _ = self.skip_type_script_type_parameters( @@ -1355,7 +1355,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O self.lexer.expect(T::TIdentifier)?; if opts.scope.is_module() { - self.local_type_names.put(name, true)?; + self.local_type_names.put(name, true); } let _ = self.skip_type_script_type_parameters( diff --git a/src/js_parser/parse/parse_typescript.rs b/src/js_parser/parse/parse_typescript.rs index 62bc1c41df2d..4051b79c287f 100644 --- a/src/js_parser/parse/parse_typescript.rs +++ b/src/js_parser/parse/parse_typescript.rs @@ -293,7 +293,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O loc: locref.loc, data: TSNamespaceMemberData::Property, }, - )?; + ); p.ref_to_ts_namespace_member .insert(ref_, TSNamespaceMemberData::Property); } @@ -311,7 +311,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O loc: locref.loc, data: TSNamespaceMemberData::Property, }, - )?; + ); p.ref_to_ts_namespace_member .insert(ref_, TSNamespaceMemberData::Property); } @@ -330,7 +330,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O data: clone_ts_member_data(&member_data), loc: ns.name.loc, }, - )?; + ); p.ref_to_ts_namespace_member.insert(ref_, member_data); } } @@ -349,7 +349,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O data: clone_ts_member_data(&member_data), loc: ns.name.loc, }, - )?; + ); p.ref_to_ts_namespace_member.insert(ref_, member_data); } } @@ -399,7 +399,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O { p.pop_and_discard_scope(scope_index); if opts.scope.is_module() { - p.local_type_names.put(name_text, true)?; + p.local_type_names.put(name_text, true); } return Ok(p.s(S::TypeScript {}, loc)); } @@ -666,7 +666,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O loc: value_loc, data: TSNamespaceMemberData::EnumProperty, }, - )?; + ); if p.lexer.token != T::TComma && p.lexer.token != T::TSemicolon { break; diff --git a/src/js_parser/parser.rs b/src/js_parser/parser.rs index cf8248bf4b40..c5e28651f3b0 100644 --- a/src/js_parser/parser.rs +++ b/src/js_parser/parser.rs @@ -1125,7 +1125,7 @@ impl StringVoidMap { pub(crate) fn get_or_put_contains(&mut self, key: &[u8]) -> bool { // StringHashMap copies keys into owned heap allocations on insert, // so the pooled map outliving any one source is fine. - let entry = self.map.get_or_put(key).expect("unreachable"); + let entry = self.map.get_or_put(key); entry.found_existing } @@ -1738,13 +1738,13 @@ pub fn new_lazy_export_ast_impl<'bump>( if temp_log.errors == 0 { log_to_copy_into.add_range_error(Some(source), range, err.name().as_bytes()); } - let _ = temp_log.append_to_maybe_recycled(log_to_copy_into, source); + temp_log.append_to_maybe_recycled(log_to_copy_into, source); return Ok(None); } }; drop(parser); - let _ = temp_log.append_to_maybe_recycled(log_to_copy_into, source); + temp_log.append_to_maybe_recycled(log_to_copy_into, source); match result { crate::Result::Ast(mut ast) => { ast.has_lazy_export = true; diff --git a/src/js_parser/scan/scan_imports.rs b/src/js_parser/scan/scan_imports.rs index b34a49c67754..12469f00eed4 100644 --- a/src/js_parser/scan/scan_imports.rs +++ b/src/js_parser/scan/scan_imports.rs @@ -7,7 +7,6 @@ use bun_ast::{self as js_ast, Expr, G, LocRef, S, Stmt, Symbol}; use bun_ast::{ImportRecord, import_record}; use bun_collections::VecExt; use bun_core::strings; -use bun_crash_handler::handle_oom::handle_oom; // `stmts` is a sub-slice of the input `stmts` argument (in-place compacted), // so it borrows from the caller. @@ -382,7 +381,7 @@ impl<'a> ImportScanner<'a> { sorted.push(arena.alloc_slice_copy(alias)); } strings::sort_desc(&mut sorted); - handle_oom(p.named_imports.ensure_unused_capacity(sorted.len())); + p.named_imports.ensure_unused_capacity(sorted.len()); // Create named imports for these property accesses. This will // cause missing imports to generate useful warnings. @@ -392,7 +391,7 @@ impl<'a> ImportScanner<'a> { // bare identifiers even if the namespace is still needed. for alias in &sorted { let item: LocRef = *existing.get(alias).unwrap(); - handle_oom(p.named_imports.put( + p.named_imports.put( item.ref_, js_ast::NamedImport { alias: Some(js_ast::StoreStr::new(*alias)), @@ -403,7 +402,7 @@ impl<'a> ImportScanner<'a> { alias_is_star: false, is_exported: false, }, - )); + ); let name: LocRef = item; let name_ref = name.ref_; @@ -426,20 +425,18 @@ impl<'a> ImportScanner<'a> { })); // Also record these automatically-generated top-level namespace alias symbols - p.declared_symbols - .append(js_ast::DeclaredSymbol { - ref_: name_ref, - is_top_level: true, - }) - .expect("unreachable"); + p.declared_symbols.append(js_ast::DeclaredSymbol { + ref_: name_ref, + is_top_level: true, + }); } } - handle_oom(p.named_imports.ensure_unused_capacity( + p.named_imports.ensure_unused_capacity( st_items.len() + usize::from(st.default_name.is_some()) + usize::from(!st.star_name_loc.is_empty()), - )); + ); if let Some(loc) = st.star_name_loc.to_nullable() { record!() @@ -523,7 +520,7 @@ impl<'a> ImportScanner<'a> { alias_is_star: false, is_exported: false, }, - )?; + ); // Make sure the printer prints this as a property access let symbol: &mut Symbol = @@ -735,7 +732,7 @@ impl<'a> ImportScanner<'a> { is_exported: true, local_parts_with_uses: bun_alloc::AstAlloc::vec(), }, - )?; + ); let original: &'p [u8] = alias.original_name.slice(); p.record_export(alias.loc, original, st.namespace_ref)?; p.import_records.items_mut()[st.import_record_index as usize] @@ -751,9 +748,7 @@ impl<'a> ImportScanner<'a> { .push(st.import_record_index); // SAFETY: arena-owned slice valid for 'p. let items = st.items.slice(); - p.named_imports - .ensure_unused_capacity(items.len()) - .expect("unreachable"); + p.named_imports.ensure_unused_capacity(items.len()); for item in items.iter() { let ref_ = item.name.ref_; // Note that the imported alias is not item.Alias, which is the @@ -770,7 +765,7 @@ impl<'a> ImportScanner<'a> { is_exported: true, local_parts_with_uses: bun_alloc::AstAlloc::vec(), }, - )?; + ); // SAFETY: arena-owned alias slice valid for 'p. let alias: &'p [u8] = item.alias.slice(); p.record_export(item.name.loc, alias, ref_)?; diff --git a/src/js_parser/visit/mod.rs b/src/js_parser/visit/mod.rs index dd62b2fc2ed2..8d8807730877 100644 --- a/src/js_parser/visit/mod.rs +++ b/src/js_parser/visit/mod.rs @@ -63,12 +63,10 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O pub(crate) fn record_declared_symbol(&mut self, r#ref: Ref) { debug_assert!(r#ref.is_symbol()); - self.declared_symbols - .append(bun_ast::DeclaredSymbol { - ref_: r#ref, - is_top_level: self.current_scope == self.module_scope, - }) - .expect("oom"); + self.declared_symbols.append(bun_ast::DeclaredSymbol { + ref_: r#ref, + is_top_level: self.current_scope == self.module_scope, + }); } pub(crate) fn visit_func(&mut self, mut func: G::Fn, open_parens_loc: bun_ast::Loc) -> G::Fn { @@ -465,9 +463,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O if self.options.features.inlining { if let BData::BIdentifier(id) = property.value.data { - self.const_values - .put(id.r#ref, query.expr) - .expect("oom"); + self.const_values.put(id.r#ref, query.expr); } } } @@ -507,7 +503,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O } BData::BIdentifier(id) => { if self.options.features.inlining { - self.const_values.put(id.r#ref, expr).expect("oom"); + self.const_values.put(id.r#ref, expr); } } BData::BMissing(_) => {} @@ -528,7 +524,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O if could_be_const_value || (Self::ALLOW_MACROS && could_be_macro) { if let Some(val) = decl.value { if val.can_be_const_value() { - self.const_values.put(id_ref, val).expect("oom"); + self.const_values.put(id_ref, val); } } } else { @@ -814,16 +810,13 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O let original_name: &'a [u8] = self.symbols[name_ref.inner_index() as usize] .original_name .slice(); - self.vis_scope() - .members - .put( - original_name, - ScopeMember { - ref_: name.ref_, - loc: name.loc, - }, - ) - .expect("oom"); + self.vis_scope().members.put( + original_name, + ScopeMember { + ref_: name.ref_, + loc: name.loc, + }, + ); } else { let name_str: &'a [u8] = if default_name_ref.is_empty() { b"_this" @@ -1424,7 +1417,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O continue; } - let gpe = fn_stmts.get_or_put(name_ref).expect("oom"); + let gpe = fn_stmts.get_or_put(name_ref); let mut index = *gpe.value_ptr; if !gpe.found_existing { index = u32::try_from(let_decls.len()).expect("int cast"); diff --git a/src/js_parser/visit/visit_stmt.rs b/src/js_parser/visit/visit_stmt.rs index dfce8bec1923..128e50d30ebc 100644 --- a/src/js_parser/visit/visit_stmt.rs +++ b/src/js_parser/visit/visit_stmt.rs @@ -1448,12 +1448,10 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O }, ); // we have to ensure these are known to be top-level - p.declared_symbols - .append(js_ast::DeclaredSymbol { - ref_, - is_top_level: true, - }) - .expect("oom"); + p.declared_symbols.append(js_ast::DeclaredSymbol { + ref_, + is_top_level: true, + }); p.esm_export_keyword.loc = stmt.loc; p.esm_export_keyword.len = 5; p.had_commonjs_named_exports_this_visit = true; diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index 279cb1d6ccab..c9056e766724 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -177,7 +177,7 @@ impl MacroContext { &mut specifier_buf_len, ); - let macro_entry = self.macros.get_or_put(hash).expect("unreachable"); + let macro_entry = self.macros.get_or_put(hash); if !macro_entry.found_existing { *macro_entry.value_ptr = match Macro::init( input_specifier, @@ -692,7 +692,7 @@ impl<'a> Run<'a> { T::Array => { self.is_top_level = false; - let _entry = self.visited.get_or_put(value).expect("unreachable"); + let _entry = self.visited.get_or_put(value); if _entry.found_existing { return Ok(*_entry.value_ptr); } @@ -733,7 +733,7 @@ impl<'a> Run<'a> { // TODO: optimize this T::Object => { self.is_top_level = false; - let _entry = self.visited.get_or_put(value).expect("unreachable"); + let _entry = self.visited.get_or_put(value); if _entry.found_existing { return Ok(*_entry.value_ptr); } diff --git a/src/js_printer/renamer.rs b/src/js_printer/renamer.rs index aebe444e72b9..a7ae8f3248f3 100644 --- a/src/js_printer/renamer.rs +++ b/src/js_printer/renamer.rs @@ -287,7 +287,7 @@ impl MinifyRenamer { } // #14586: here, not in `compute_initial_reserved_names`, so `NumberRenamer` keeps user `$` verbatim. - reserved_names.put(b"$", 1).expect("unreachable"); + reserved_names.put(b"$", 1); Ok(Box::new(MinifyRenamer { symbols: ManuallyDrop::new(symbols), @@ -393,7 +393,7 @@ impl MinifyRenamer { let must_start_with_capital = symbol.must_start_with_capital_letter_for_jsx(); let slots = &mut self.slots[ns]; - let gpe = self.top_level_symbol_to_slot.get_or_put(stable.ref_)?; + let gpe = self.top_level_symbol_to_slot.get_or_put(stable.ref_); if gpe.found_existing { let slot = &mut slots[*gpe.value_ptr]; slot.count += stable.count; @@ -1006,7 +1006,7 @@ impl ExportRenamer { } pub fn next_renamed_name(&mut self, input: &[u8]) -> &[u8] { - let entry = self.used.get_or_put(input).expect("unreachable"); + let entry = self.used.get_or_put(input); if !entry.found_existing { *entry.value_ptr = 1; // `StringHashMap` does not expose a key pointer; allocate a copy in @@ -1033,7 +1033,7 @@ impl ExportRenamer { } // `StringHashMap::put` boxes the key itself; the arena copy below is // only for the caller's returned slice (`string_buffer` is reused). - self.used.put(attempt, 1).expect("unreachable"); + self.used.put(attempt, 1); *self.used.get_mut(input).expect("unreachable") = tries; return self.arena.alloc_slice_copy(attempt); } @@ -1069,7 +1069,7 @@ pub fn compute_initial_reserved_names( names.ensure_total_capacity( cjs_names_len as usize + (Keywords.len() + StrictModeReservedWords.len() + 1 + EXTRAS.len()), - )?; + ); for keyword in Keywords.keys() { names.put_assume_capacity(keyword, 1); @@ -1108,9 +1108,7 @@ pub fn compute_reserved_names_for_scope( let symbol: &Symbol = symbols.get_const(member.ref_).unwrap(); if symbol.kind == symbol::Kind::Unbound || symbol.must_not_be_renamed() { // SAFETY: `original_name` is an AST-arena slice. - names - .put(symbol.original_name.slice(), 1) - .expect("unreachable"); + names.put(symbol.original_name.slice(), 1); } } @@ -1118,9 +1116,7 @@ pub fn compute_reserved_names_for_scope( let symbol: &Symbol = symbols.get_const(*ref_).unwrap(); if symbol.kind == symbol::Kind::Unbound || symbol.must_not_be_renamed() { // SAFETY: `original_name` is an AST-arena slice. - names - .put(symbol.original_name.slice(), 1) - .expect("unreachable"); + names.put(symbol.original_name.slice(), 1); } } diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index a9270cf88662..146402c5ab59 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -3310,7 +3310,7 @@ pub mod formatter { self.map_node = Some(node); } - let entry = self.map.get_or_put(value).expect("unreachable"); + let entry = self.map.get_or_put(value); if entry.found_existing { if writer_ .write_all(pfmt!("[Circular]", C).as_bytes()) @@ -5788,7 +5788,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__count( let slice = unsafe { bun_core::ffi::slice(ptr, len) }; let hash = bun_wyhash::hash(slice); // we don't want to store these strings, it will take too much memory - let counter = this.counts.get_or_put(hash).expect("unreachable"); + let counter = this.counts.get_or_put(hash); let current: u32 = if counter.found_existing { *counter.value_ptr } else { @@ -5856,7 +5856,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__time( } PENDING_TIME_LOGS.with_borrow_mut(|map| { - let result = map.get_or_put(id).expect("unreachable"); + let result = map.get_or_put(id); if !result.found_existing || result.value_ptr.is_none() { *result.value_ptr = Some(bun_core::time::Timer::start()); } diff --git a/src/jsc/NodeModuleModule.rs b/src/jsc/NodeModuleModule.rs index 47cc4e5c7d35..94f0b2cf141c 100644 --- a/src/jsc/NodeModuleModule.rs +++ b/src/jsc/NodeModuleModule.rs @@ -166,7 +166,7 @@ fn on_require_extension_modify( let vm = global.bun_vm().as_mut(); let is_built_in = DEFAULT_LOADERS.get(str).is_some(); - let gop = vm.commonjs_custom_extensions.get_or_put(str)?; + let gop = vm.commonjs_custom_extensions.get_or_put(str); if !gop.found_existing { // `gop.key_ptr` already owns a duped `Box<[u8]>` (StringArrayHashMap // boxes the key on insert). diff --git a/src/jsc/ProcessAutoKiller.rs b/src/jsc/ProcessAutoKiller.rs index 78ac9b977b1f..9bcb234d9157 100644 --- a/src/jsc/ProcessAutoKiller.rs +++ b/src/jsc/ProcessAutoKiller.rs @@ -67,11 +67,7 @@ impl ProcessAutoKiller { /// identity semantics for the map key without a const→mut provenance cast. pub(crate) fn on_subprocess_spawn(&mut self, process: NonNull) { if self.enabled { - // Alloc failure means we never took - // a ref, so just bail. `put` here is fallible only on OOM. - if self.processes.put(process.as_ptr(), ()).is_err() { - return; - } + self.processes.put(process.as_ptr(), ()); // SAFETY: caller passes a live Process; we take a ref to extend its // lifetime for as long as it sits in `processes`. unsafe { (*process.as_ptr()).ref_() }; diff --git a/src/jsc/RuntimeTranspilerStore.rs b/src/jsc/RuntimeTranspilerStore.rs index 640ad4635a6c..2796effb4d82 100644 --- a/src/jsc/RuntimeTranspilerStore.rs +++ b/src/jsc/RuntimeTranspilerStore.rs @@ -803,7 +803,7 @@ impl TranspilerJob { // inner `clone()` must abort — never silently drop a remapping. let mut m = MacroRemap::default(); for (k, v) in transpiler.options.macro_remap.iter() { - m.insert(k, bun_core::handle_oom(v.clone())); + m.insert(k, v.clone()); } m }; @@ -994,7 +994,7 @@ impl TranspilerJob { // SAFETY: leaf-field `&mut` borrow on `*vm.source_mappings`; // `SavedSourceMap` takes its own internal mutex. - let _ = unsafe { &mut (*vm).source_mappings }.put_mappings( + unsafe { &mut (*vm).source_mappings }.put_mappings( &parse_result.source, MutableString { list: core::mem::take(&mut entry.sourcemap).into_vec(), diff --git a/src/jsc/SavedSourceMap.rs b/src/jsc/SavedSourceMap.rs index 7edf2e3ad7d0..e704f0a2df0e 100644 --- a/src/jsc/SavedSourceMap.rs +++ b/src/jsc/SavedSourceMap.rs @@ -105,11 +105,7 @@ impl SavedSourceMap { /// by [`Self::release_value`] on replace / remove / drop. pub fn put_source_provider(&mut self, provider: AnySourceProvider, path: &[u8]) { let boxed = bun_core::heap::into_raw(Box::new(provider)); - // bun.handleOom → drop wrapper; Rust HashMap insert aborts on OOM. - if self.put_value(path, Value::init(boxed)).is_err() { - // SAFETY: the failed insert did not consume `boxed`. - unsafe { bun_core::heap::destroy(boxed) }; - } + self.put_value(path, Value::init(boxed)); } /// Drops the entry for `path` if it still refers to @@ -160,7 +156,8 @@ impl bun_js_printer::OnSourceMapChunk for SavedSourceMap { chunk: SourceMap::Chunk, source: &bun_ast::Source, ) -> bun_js_printer::Result<()> { - self.put_mappings(source, chunk.buffer) + self.put_mappings(source, chunk.buffer); + Ok(()) } } @@ -178,11 +175,7 @@ impl Drop for SavedSourceMap { } impl SavedSourceMap { - pub fn put_mappings( - &mut self, - source: &bun_ast::Source, - mut mappings: MutableString, - ) -> bun_js_printer::Result<()> { + pub fn put_mappings(&mut self, source: &bun_ast::Source, mut mappings: MutableString) { // --hot can re-read a file mid-rewrite (truncate + write) and transpile // a comment-only prefix into a 0-mapping map. Overwriting a real map // with that would make any still-unreported error from the previous @@ -198,7 +191,7 @@ impl SavedSourceMap { let contains = self.map.contains_key(&hash(source.path.text)); self.unlock(); if contains { - return Ok(()); + return; } // Note: reshaped for borrowck — the lock is // released before returning since no further table access follows. @@ -211,24 +204,16 @@ impl SavedSourceMap { // re-alloc+memcpy (1.38 MB for `_tsc.js`'s cached map). `heap::alloc` // is NOT a leak: ownership transfers to the table via `put_value`, and // is reclaimed by `InternalSourceMap::free_owned` (see `put_value` / - // `Drop`). On the error path the Box is reconstituted and dropped. + // `Drop`). let blob: Box<[u8]> = core::mem::take(&mut mappings.list).into_boxed_slice(); let blob_ptr: *mut [u8] = bun_core::heap::into_raw(blob); - // errdefer: on error, reconstitute and drop the Box. - match self.put_value( + self.put_value( source.path.text, Value::init(blob_ptr.cast::().cast::()), - ) { - Ok(()) => Ok(()), - Err(e) => { - // SAFETY: `blob_ptr` came from `heap::alloc` just above and was not consumed. - drop(unsafe { Box::<[u8]>::from_raw(blob_ptr) }); - Err(e) - } - } + ); } - pub(crate) fn put_value(&mut self, path: &[u8], value: Value) -> bun_js_printer::Result<()> { + pub(crate) fn put_value(&mut self, path: &[u8], value: Value) { use bun_collections::zig_hash_map::MapEntry as Entry; self.lock(); @@ -249,7 +234,6 @@ impl SavedSourceMap { } } self.unlock(); - Ok(()) } /// You must call `sourcemap.map.deref()` or you will leak memory @@ -318,8 +302,7 @@ impl SavedSourceMap { // The mutex is not locked. We have to check the hash table again. // Leak one strong ref into the table; `put_value` releases // the replaced provider box. - let _ = - self.put_value(path, Value::init(Arc::into_raw(Arc::clone(parsed_map)))); + self.put_value(path, Value::init(Arc::into_raw(Arc::clone(parsed_map)))); return parse; } diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index f7c0c80fb127..5bc564a9008d 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -3087,8 +3087,7 @@ impl<'a> bun_js_printer::OnSourceMapChunk for SourceMapHandlerGetter<'a> { SOURCE_MAP_URL_PREFIX_START.len() + SOURCE_MAPPING_URL.len() + source_url_len; self.vm_source_mappings_mut() - .put_mappings(source, chunk.buffer) - .map_err(|_| bun_js_printer::Error::WriteFailed)?; + .put_mappings(source, chunk.buffer); // SAFETY: `printer` is the raw `*mut BufferPrinter` passed in by the // caller (jsc_hooks.rs), with the SAME provenance as the `writer` arg @@ -5285,7 +5284,7 @@ impl VirtualMachine { // `log_mut()` is the centralized set-once `Option` // accessor — single audited deref lives there. if let Some(log) = self.log_mut() { - let _ = log.add_msg(build_error.msg.clone()); + log.add_msg(build_error.msg.clone()); } } bun_core::Output::flush(); @@ -5304,7 +5303,7 @@ impl VirtualMachine { // `log_mut()` is the centralized set-once `Option` // accessor — single audited deref lives there. if let Some(log) = self.log_mut() { - let _ = log.add_msg(resolve_error.msg.clone()); + log.add_msg(resolve_error.msg.clone()); } } bun_core::Output::flush(); @@ -6459,7 +6458,7 @@ impl VirtualMachine { formatter.map_node = Some(node); } - let entry = formatter.map.get_or_put(err).expect("unreachable"); + let entry = formatter.map.get_or_put(err); if entry.found_existing { writer.write_all(b"\n")?; pretty_write!(writer, "[Circular]")?; @@ -6724,12 +6723,12 @@ impl VirtualMachine { // The `Arc::clone` is the ref-bump; `into_raw` transfers that strong // ref into the table (reclaimed by `put_value`'s replace path / // `SavedSourceMap` teardown). - bun_core::handle_oom(self.source_mappings.put_value( + self.source_mappings.put_value( path, crate::saved_source_map::Value::init(std::sync::Arc::into_raw(std::sync::Arc::clone( &map, ))), - )); + ); let mapping = map.find_mapping(line, column)?; diff --git a/src/jsc/bindgen.rs b/src/jsc/bindgen.rs index 83cb229da2b0..ca9d5d2501c8 100644 --- a/src/jsc/bindgen.rs +++ b/src/jsc/bindgen.rs @@ -328,7 +328,7 @@ impl Bindgen for BindgenArray { // Fallback: allocate fresh, convert, free old. `data` was `mi_malloc`'d // by the C++ side regardless of the Rust global allocator, so free it // with `mi_free` directly instead of `Vec::drop`. - let mut result = bun_core::handle_oom(Self::ZigType::init_capacity(length)); + let mut result = Self::ZigType::init_capacity(length); let mut unmanaged = ManuallyDrop::new(unmanaged); for item in unmanaged.iter_mut() { // SAFETY: each slot holds a C++-initialized `ExternType`; `ManuallyDrop` ensures it isn't read twice. diff --git a/src/jsc/hot_reloader.rs b/src/jsc/hot_reloader.rs index b94eb1050993..1cad20c4d373 100644 --- a/src/jsc/hot_reloader.rs +++ b/src/jsc/hot_reloader.rs @@ -346,7 +346,7 @@ fn record_changed_path(path: &[u8]) { if path.is_empty() { return; } - bun_core::handle_oom(set.get_mut().insert(path)); + set.get_mut().insert(path); } /// Write the recorded changed paths to the trigger file so the next @@ -793,7 +793,7 @@ where #[cfg(not(windows))] fn put_tombstone(&mut self, key: &[u8], value: *mut Fs::EntriesOption) { - self.tombstones.put(key, value).expect("unreachable"); + self.tombstones.put(key, value); } #[cfg(not(windows))] diff --git a/src/jsc/lib.rs b/src/jsc/lib.rs index 605f0c9e9e16..4c640a7663d7 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -584,8 +584,6 @@ pub fn js_error_to_write_error(e: JsError) -> core::fmt::Error { match e { // TODO: this might lose a JSError, causing exception check problems JsError::Thrown => core::fmt::Error, - // `bun.handleOom(error.OutOfMemory)` — panic-on-OOM wrapper fed a literal OOM, - // i.e. unconditionally abort. JsError::OutOfMemory => bun_alloc::out_of_memory(), } } diff --git a/src/jsc/rare_data.rs b/src/jsc/rare_data.rs index 8476ef60cb1b..6ca88d53eb59 100644 --- a/src/jsc/rare_data.rs +++ b/src/jsc/rare_data.rs @@ -87,7 +87,7 @@ impl HotMap { /// Untyped insert — typed `insert` lives in `bun_runtime` where the /// `TaggedPointerUnion` payload list is named. pub fn insert_raw(&mut self, key: &[u8], entry: HotMapEntry) { - let gop = bun_core::handle_oom(self._map.get_or_put(key)); + let gop = self._map.get_or_put(key); if gop.found_existing { panic!("HotMap already contains key"); } @@ -520,7 +520,7 @@ impl ProxyEnvSlots { macro_rules! sync_one { ($name:literal, $field:ident) => { if let Some(val) = &self.$field { - bun_core::handle_oom(map.put($name, &val.bytes)); + map.put($name, &val.bytes); } }; } @@ -750,7 +750,7 @@ impl RareData { pub(crate) fn mime_type_from_string(&mut self, str_: &[u8]) -> Option { let table = self .mime_types - .get_or_insert_with(|| bun_core::handle_oom(mime_type::create_hash_table())); + .get_or_insert_with(mime_type::create_hash_table); table .get(str_) .map(|entry| mime_type::Compact::from(*entry).to_mime_type()) diff --git a/src/jsc/web_worker.rs b/src/jsc/web_worker.rs index 114ad0091bff..03fea16d7b7e 100644 --- a/src/jsc/web_worker.rs +++ b/src/jsc/web_worker.rs @@ -370,13 +370,7 @@ impl WebWorker { let mut env_map = { let parent_slots = parent_ref.proxy_env_storage.lock(); proxy_env_slots.clone_from(&parent_slots); - match parent_ref.env_loader().map.clone_with_allocator() { - Ok(m) => m, - Err(_) => { - *error_message = BunString::static_(b"Out of memory"); - return core::ptr::null_mut(); - } - } + parent_ref.env_loader().map.clone() }; proxy_env_slots.sync_into(&mut env_map); let init = WorkerVmInit { diff --git a/src/resolver/fs.rs b/src/resolver/fs.rs index d1edb9f43517..41e6fe1f100b 100644 --- a/src/resolver/fs.rs +++ b/src/resolver/fs.rs @@ -580,7 +580,7 @@ impl DirEntry { // `(*stored).base_lowercase()` equals `name_lc` byte-for-byte (a fresh // entry interned `name_lc`; a recycled one matched it exactly above), so // `name_hash` is its hash too — insert without re-hashing. - self.data.put_static_key_hashed(name_hash, key, stored)?; + self.data.put_static_key_hashed(name_hash, key, stored); if !I::IS_VOID { iterator.next(stored_ref, self.fd); diff --git a/src/resolver/options.rs b/src/resolver/options.rs index 6000dfd81eb7..9252f7f4f235 100644 --- a/src/resolver/options.rs +++ b/src/resolver/options.rs @@ -31,8 +31,8 @@ impl Clone for ExternalModules { // `Result<_, AllocError>`), so this can't be `#[derive(Clone)]`. Self { patterns: self.patterns.clone(), - abs_paths: self.abs_paths.clone().expect("oom"), - node_modules: self.node_modules.clone().expect("oom"), + abs_paths: self.abs_paths.clone(), + node_modules: self.node_modules.clone(), } } } diff --git a/src/resolver/package_json.rs b/src/resolver/package_json.rs index 12dd6aa32601..202edffd5155 100644 --- a/src/resolver/package_json.rs +++ b/src/resolver/package_json.rs @@ -58,7 +58,7 @@ impl Clone for DependencyMap { /// POD over `source_buf`. fn clone(&self) -> Self { Self { - map: self.map.clone().expect("OOM"), + map: self.map.clone(), source_buf: self.source_buf, } } @@ -579,10 +579,7 @@ impl PackageJSON { if let Some(str) = expr.as_utf8_string_literal() { if !str.is_empty() { - package_json - .main_fields - .put(main, Box::from(str)) - .expect("unreachable"); + package_json.main_fields.put(main, Box::from(str)); } } } @@ -628,17 +625,11 @@ impl PackageJSON { match &prop.value { js_ast::E::JsonValue::String(str) => { // If this is a string, it's a replacement package - package_json - .browser_map - .put(key, Box::from(str.slice())) - .expect("unreachable"); + package_json.browser_map.put(key, Box::from(str.slice())); } js_ast::E::JsonValue::Boolean(boolean) => { if !*boolean { - package_json - .browser_map - .put(key, Box::default()) - .expect("unreachable"); + package_json.browser_map.put(key, Box::default()); } } _ => { @@ -881,8 +872,7 @@ impl PackageJSON { package_json .dependencies .map - .ensure_total_capacity(total_dependency_count) - .expect("unreachable"); + .ensure_total_capacity(total_dependency_count); for group in dependency_groups { if let Some(group_json) = json.get(group.prop) { @@ -961,7 +951,7 @@ impl PackageJSON { }; let obj = obj.get(); let mut map = StringArrayHashMap::<&'static [u8]>::default(); - map.ensure_total_capacity(obj.properties().len()).ok()?; + map.ensure_total_capacity(obj.properties().len()); for p in obj.properties() { let key = p.key.slice(); let Some(value) = p.value.as_str() else { diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 1e45ac9687a1..ef23459853e5 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -3363,7 +3363,7 @@ impl<'a> Resolver<'a> { Ok(d) => d, Err(err) => { // TODO: handle this error better - let _ = self.log_mut().add_error_fmt( + self.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!("Unable to open directory: {}", bstr::BStr::new(err.name())), @@ -4550,7 +4550,7 @@ impl<'a> Resolver<'a> { if err != crate::Error::Sys(bun_errno::SystemErrno::ENOENT) { if enable_logging { let pretty = queue_top_unsafe_path; - let _ = self.log_mut().add_error_fmt( + self.log_mut().add_error_fmt( None, bun_ast::Loc::default(), format_args!( @@ -5823,7 +5823,7 @@ impl<'a> Resolver<'a> { crate::Error::Sys(bun_errno::SystemErrno::ENOENT) | crate::Error::Sys(bun_errno::SystemErrno::ENOTDIR) => {} _ => { - let _ = self.log_mut().add_error_fmt( + self.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -6498,7 +6498,7 @@ impl<'a> Resolver<'a> { Err(err) => { let pretty = tsconfigpath; if err == crate::Error::Sys(bun_errno::SystemErrno::ENOENT) { - let _ = self.log_mut().add_error_fmt( + self.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -6509,7 +6509,7 @@ impl<'a> Resolver<'a> { } else if err != crate::Error::ParseErrorAlreadyLogged && err != crate::Error::Sys(bun_errno::SystemErrno::EISDIR) { - let _ = self.log_mut().add_error_fmt( + self.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -6553,7 +6553,7 @@ impl<'a> Resolver<'a> { match self.parse_tsconfig(abs_path, FD::INVALID) { Ok(v) => v.map(bun_core::heap::into_raw), Err(err) => { - let _ = self.log_mut().add_debug_fmt( + self.log_mut().add_debug_fmt( None, bun_ast::Loc::EMPTY, format_args!( diff --git a/src/resolver/tsconfig_json.rs b/src/resolver/tsconfig_json.rs index 402ee82c0505..9c5c6170fdcb 100644 --- a/src/resolver/tsconfig_json.rs +++ b/src/resolver/tsconfig_json.rs @@ -51,7 +51,7 @@ impl JsonCache { let mut temp_log = bun_ast::Log::init(); let bump = self.bump.get_or_insert_with(bun_alloc::Arena::new); let result = func(source, &mut temp_log, bump).ok(); - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); Ok(result) } @@ -67,7 +67,7 @@ impl JsonCache { ) -> Result, crate::Error> { let mut temp_log = bun_ast::Log::init(); let result = func(source, &mut temp_log).ok(); - let _ = temp_log.append_to_maybe_recycled(log, source); + temp_log.append_to_maybe_recycled(log, source); Ok(result) } @@ -517,7 +517,7 @@ impl TSConfigJSON { } ImportsNotUsedAsValue::Remove => {} _ => { - let _ = log.add_range_warning_fmt( + log.add_range_warning_fmt( Some(source), source.range_of_string(loc), format_args!( @@ -541,7 +541,7 @@ impl TSConfigJSON { if !str.is_empty() { // Only warn when there is actually content // Sometimes, people do "moduleSuffixes": [""] - let _ = log.add_warning( + log.add_warning( Some(source), loc, b"moduleSuffixes is not supported yet", @@ -641,13 +641,13 @@ impl TSConfigJSON { // (the extends-merge in the resolver) pass the stored slice // to the allocator, which requires the original length. values.shrink_to_fit(); - let _ = result.paths.put(Box::from(key), values); + result.paths.put(Box::from(key), values); } // else: Every entry was invalid; nothing to store. `values` drops here. } } _ => { - let _ = log.add_range_warning_fmt( + log.add_range_warning_fmt( Some(source), source.range_of_string(key_loc), format_args!( @@ -680,7 +680,7 @@ impl TSConfigJSON { if c == b'*' { if found_asterisk { let r = source.range_of_string(loc); - let _ = log.add_range_warning_fmt( + log.add_range_warning_fmt( Some(source), r, format_args!( @@ -718,7 +718,7 @@ impl TSConfigJSON { if parts_count == 1 { if !js_lexer::is_identifier(text) { let warn = source.range_of_string(loc); - let _ = log.add_range_warning_fmt( + log.add_range_warning_fmt( Some(source), warn, format_args!( @@ -738,7 +738,7 @@ impl TSConfigJSON { for part in iter { if !js_lexer::is_identifier(part) { let warn = source.range_of_string(loc); - let _ = log.add_range_warning_fmt( + log.add_range_warning_fmt( Some(source), warn, format_args!( @@ -805,7 +805,7 @@ impl TSConfigJSON { } let r = source.range_of_string(loc); - let _ = log.add_range_warning_fmt( + log.add_range_warning_fmt( Some(source), r, format_args!( diff --git a/src/runtime/api/Archive.rs b/src/runtime/api/Archive.rs index f62b51994e5f..b9a66eb6bf4b 100644 --- a/src/runtime/api/Archive.rs +++ b/src/runtime/api/Archive.rs @@ -1486,7 +1486,7 @@ fn extract_to_disk_filtered( remaining -= bytes_read; } } - let _ = file_fd.close(); + file_fd.close(); if write_success { count += 1; diff --git a/src/runtime/api/BunObject.rs b/src/runtime/api/BunObject.rs index 199d2448adc8..35d3c6ac7309 100644 --- a/src/runtime/api/BunObject.rs +++ b/src/runtime/api/BunObject.rs @@ -794,11 +794,7 @@ fn register_macro(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsRe } // SAFETY: VirtualMachine::get() returns the live per-thread singleton. - let get_or_put_result = VirtualMachine::get() - .as_mut() - .macros - .get_or_put(id) - .expect("unreachable"); + let get_or_put_result = VirtualMachine::get().as_mut().macros.get_or_put(id); if get_or_put_result.found_existing { get_or_put_result.value_ptr.unprotect(); } @@ -1585,10 +1581,10 @@ fn serve(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsResult Option { diff --git a/src/runtime/api/JSBundler.rs b/src/runtime/api/JSBundler.rs index 53326b259f43..2a6bcf849d5e 100644 --- a/src/runtime/api/JSBundler.rs +++ b/src/runtime/api/JSBundler.rs @@ -816,7 +816,7 @@ pub mod js_bundler { let mut iter = entry_points.array_iterator(global_this)?; while let Some(entry_point) = iter.next()? { let slice = entry_point.to_slice_or_null(global_this)?; - this.entry_points.insert(slice.slice())?; + this.entry_points.insert(slice.slice()); drop(slice); } } else { @@ -845,13 +845,13 @@ pub mod js_bundler { if let Some(conditions_value) = config.get_truthy(global_this, "conditions")? { if conditions_value.is_string() { let slice = conditions_value.to_slice_or_null(global_this)?; - this.conditions.insert(slice.slice())?; + this.conditions.insert(slice.slice()); drop(slice); } else if conditions_value.js_type().is_array() { let mut iter = conditions_value.array_iterator(global_this)?; while let Some(entry_point) = iter.next()? { let slice = entry_point.to_slice_or_null(global_this)?; - this.conditions.insert(slice.slice())?; + this.conditions.insert(slice.slice()); drop(slice); } } else { @@ -935,7 +935,7 @@ pub mod js_bundler { let mut iter = externals.array_iterator(global_this)?; while let Some(entry_point) = iter.next()? { let slice = entry_point.to_slice_or_null(global_this)?; - this.external.insert(slice.slice())?; + this.external.insert(slice.slice()); drop(slice); } } @@ -959,7 +959,7 @@ pub mod js_bundler { this.allow_unresolved .as_mut() .unwrap() - .insert(slice.slice())?; + .insert(slice.slice()); drop(slice); } } @@ -970,7 +970,7 @@ pub mod js_bundler { let mut iter = drops.array_iterator(global_this)?; while let Some(entry) = iter.next()? { let slice = entry.to_slice_or_null(global_this)?; - this.drop.insert(slice.slice())?; + this.drop.insert(slice.slice()); drop(slice); } } @@ -979,7 +979,7 @@ pub mod js_bundler { let mut iter = features.array_iterator(global_this)?; while let Some(entry) = iter.next()? { let slice = entry.to_slice_or_null(global_this)?; - this.features.insert(slice.slice())?; + this.features.insert(slice.slice()); drop(slice); } } @@ -988,7 +988,7 @@ pub mod js_bundler { let mut iter = optimize_imports.array_iterator(global_this)?; while let Some(entry) = iter.next()? { let slice = entry.to_slice_or_null(global_this)?; - this.optimize_imports.insert(slice.slice())?; + this.optimize_imports.insert(slice.slice()); drop(slice); } } @@ -1087,7 +1087,7 @@ pub mod js_bundler { let value = val.to_slice(); // .insert clones the value, but not the key - this.define.insert(&key, value.slice())?; + this.define.insert(&key, value.slice()); drop(value); } } @@ -1206,7 +1206,7 @@ pub mod js_bundler { let define_values = compile.compile_target.define_values(); debug_assert_eq!(define_keys.len(), define_values.len()); for (key, value) in define_keys.iter().zip(define_values) { - this.define.insert(key, value)?; + this.define.insert(key, value); } let base_public_path = StandaloneModuleGraph::target_base_public_path( diff --git a/src/runtime/api/JSON5Object.rs b/src/runtime/api/JSON5Object.rs index 233918df8c25..b2b8b40e96cc 100644 --- a/src/runtime/api/JSON5Object.rs +++ b/src/runtime/api/JSON5Object.rs @@ -202,11 +202,7 @@ impl Stringifier { // allocation (Err → OutOfMemory), but `zig_hash_map`'s grow path currently // allocates infallibly and aborts on OOM, so the Err arm only becomes live // once the collections-side grow is made fallible. - let was_present = self - .visiting - .get_or_put(unwrapped) - .map_err(|_| StringifyError::Js(JsError::OutOfMemory))? - .found_existing; + let was_present = self.visiting.get_or_put(unwrapped).found_existing; if was_present { return Err(global .throw(format_args!("Converting circular structure to JSON5")) diff --git a/src/runtime/api/JSTranspiler.rs b/src/runtime/api/JSTranspiler.rs index f2215c727aa6..f4e90686ec11 100644 --- a/src/runtime/api/JSTranspiler.rs +++ b/src/runtime/api/JSTranspiler.rs @@ -136,10 +136,10 @@ fn level_from_js(global: &JSGlobalObject, value: JSValue) -> JsResult MacroMap { let mut out = MacroMap::default(); - bun_core::handle_oom(out.ensure_unused_capacity(src.count())); + out.ensure_unused_capacity(src.count()); for (k, v) in src.keys().iter().zip(src.values().iter()) { // inner map: `StringArrayHashMap<&'static [u8]>` — `&[u8]: Clone` ⇒ inherent `clone()` works. - let inner = v.clone().expect("OOM"); + let inner = v.clone(); out.put_assume_capacity(k, inner); } out @@ -498,9 +498,7 @@ impl Config { if total_name_buf_len > 0 { let mut buf: Vec = Vec::with_capacity(total_name_buf_len as usize); // errdefer buf.deinit(allocator) → Drop - bun_core::handle_oom( - replacements.ensure_unused_capacity(string_count as usize), - ); + replacements.ensure_unused_capacity(string_count as usize); { let mut length_iter = JSArrayIterator::init(eliminate, global)?; while let Some(value) = length_iter.next()? { @@ -551,7 +549,7 @@ impl Config { // defer iter.deinit() → Drop if iter.len > 0 { - bun_core::handle_oom(replacements.ensure_unused_capacity(iter.len)); + replacements.ensure_unused_capacity(iter.len); // Exception cleanup is covered by RAII: a pending exception // always surfaces as `Err(JsError::Thrown)` through `?`, and @@ -582,8 +580,7 @@ impl Config { // slot). if let Some(expr) = export_replacement_value(value, global, arena)? { replacements - .put(&key, bun_ast::runtime::ReplaceableExport::Replace(expr)) - .map_err(|_| bun_jsc::JsError::OutOfMemory)?; + .put(&key, bun_ast::runtime::ReplaceableExport::Replace(expr)); continue; } @@ -604,15 +601,13 @@ impl Config { ))); } - replacements - .put( - &key, - bun_ast::runtime::ReplaceableExport::Inject { - name: replacement_name.into(), - value: to_replace, - }, - ) - .map_err(|_| bun_jsc::JsError::OutOfMemory)?; + replacements.put( + &key, + bun_ast::runtime::ReplaceableExport::Inject { + name: replacement_name.into(), + value: to_replace, + }, + ); continue; } } @@ -723,7 +718,7 @@ impl TransformTask { err: None, loader, replace_exports: bun_ast::runtime::ReplaceableExportMap { - entries: config.runtime.replace_exports.entries.clone().expect("OOM"), + entries: config.runtime.replace_exports.entries.clone(), }, }; let cx = global.js_thread(); @@ -798,7 +793,7 @@ impl TransformTask { jsx, path: source.path, virtual_source: Some(source), - replace_exports: self.replace_exports.entries.clone().expect("OOM"), + replace_exports: self.replace_exports.entries.clone(), experimental_decorators: tsconfig.is_some_and(|ts| ts.experimental_decorators), emit_decorator_metadata: tsconfig.is_some_and(|ts| ts.emit_decorator_metadata), use_define_for_class_fields: tsconfig @@ -1256,7 +1251,7 @@ impl JSTranspiler { jsx, path: source.path, virtual_source: Some(source), - replace_exports: config.runtime.replace_exports.entries.clone().expect("OOM"), + replace_exports: config.runtime.replace_exports.entries.clone(), macro_js_ctx, experimental_decorators: config .tsconfig diff --git a/src/runtime/api/MarkdownObject.rs b/src/runtime/api/MarkdownObject.rs index 89d9d028e57a..91f61a2189a9 100644 --- a/src/runtime/api/MarkdownObject.rs +++ b/src/runtime/api/MarkdownObject.rs @@ -956,7 +956,7 @@ impl<'a> ParseRenderer<'a> { let child = entry.children.get_index(g, i as u32)?; if child.is_string() { let str = child.to_slice(g)?; - let _ = alt_buf.extend_from_slice(str.slice()); + alt_buf.extend_from_slice(str.slice()); } } if !alt_buf.is_empty() { diff --git a/src/runtime/api/TOMLObject.rs b/src/runtime/api/TOMLObject.rs index 5ae7cb4409e6..5b749f2d782d 100644 --- a/src/runtime/api/TOMLObject.rs +++ b/src/runtime/api/TOMLObject.rs @@ -157,11 +157,7 @@ impl Stringifier { } fn mark_visiting(&mut self, global: &JSGlobalObject, value: JSValue) -> StringifyResult<()> { - let was_present = self - .visiting - .get_or_put(value) - .map_err(|_| StringifyError::Js(JsError::OutOfMemory))? - .found_existing; + let was_present = self.visiting.get_or_put(value).found_existing; if was_present { return Err(global .throw(format_args!("Converting circular structure to TOML")) diff --git a/src/runtime/api/XMLObject.rs b/src/runtime/api/XMLObject.rs index b53543d22420..cf650d732ec7 100644 --- a/src/runtime/api/XMLObject.rs +++ b/src/runtime/api/XMLObject.rs @@ -269,11 +269,7 @@ fn skipped(value: JSValue) -> bool { impl Stringifier { fn mark_visiting(&mut self, global: &JSGlobalObject, value: JSValue) -> StringifyResult<()> { - let was_present = self - .visiting - .get_or_put(value) - .map_err(|_| StringifyError::Js(JsError::OutOfMemory))? - .found_existing; + let was_present = self.visiting.get_or_put(value).found_existing; if was_present { return Err(global .throw(format_args!("Converting circular structure to XML")) diff --git a/src/runtime/api/YAMLObject.rs b/src/runtime/api/YAMLObject.rs index 2e738d26a77a..b28e625d31b6 100644 --- a/src/runtime/api/YAMLObject.rs +++ b/src/runtime/api/YAMLObject.rs @@ -183,7 +183,7 @@ impl Stringifier { let mut prop_names: StringHashMap = StringHashMap::default(); // always rename anchors named "root" to avoid collision with // root anchor/alias - prop_names.put(b"root", 0)?; + prop_names.put(b"root", 0); Ok(Stringifier { stack_check: StackCheck::init(), @@ -235,7 +235,7 @@ impl Stringifier { debug_assert!(unwrapped.is_object()); - let object_entry = self.known_collections.get_or_put(unwrapped)?; + let object_entry = self.known_collections.get_or_put(unwrapped); if object_entry.found_existing { // this will become an alias. increment counters here because // now the anchor/alias is confirmed used. @@ -262,7 +262,7 @@ impl Stringifier { } else { b"value" }; - let name_entry = self.prop_names.get_or_put(key)?; + let name_entry = self.prop_names.get_or_put(key); if name_entry.found_existing { *name_entry.value_ptr += 1; } else { @@ -1156,7 +1156,7 @@ impl<'a> ParserCtx<'a> { JSValue::create_empty_array(self.global, e_array.items.len_u32() as usize)?; args.append(arr); - self.seen_objects.put(key, arr)?; + self.seen_objects.put(key, arr); for (_i, item) in e_array.slice().iter().enumerate() { let i: u32 = u32::try_from(_i).expect("int cast"); @@ -1178,7 +1178,7 @@ impl<'a> ParserCtx<'a> { ); args.append(obj); - self.seen_objects.put(key, obj)?; + self.seen_objects.put(key, obj); for prop in e_object.properties.slice() { let key_expr = prop.key.expect("infallible: prop has key"); diff --git a/src/runtime/api/bun/SSLContextCache.rs b/src/runtime/api/bun/SSLContextCache.rs index f8db90a310f1..cc7b977ae962 100644 --- a/src/runtime/api/bun/SSLContextCache.rs +++ b/src/runtime/api/bun/SSLContextCache.rs @@ -129,7 +129,7 @@ impl SSLContextCache { // Re-check: another caller may have inserted while we were building. // Prefer the already-cached one and drop ours so callers converge. - let gop = bun_core::handle_oom(self.map.get_or_put(d)); + let gop = self.map.get_or_put(d); if gop.found_existing { // SAFETY: existing map value is a live heap Entry (see above). let entry = unsafe { &mut **gop.value_ptr }; diff --git a/src/runtime/api/bun/js_bun_spawn_bindings.rs b/src/runtime/api/bun/js_bun_spawn_bindings.rs index 70910ff9dbf3..eced5ca03823 100644 --- a/src/runtime/api/bun/js_bun_spawn_bindings.rs +++ b/src/runtime/api/bun/js_bun_spawn_bindings.rs @@ -910,15 +910,11 @@ fn spawn_maybe_sync( // `Transpiler::env_mut()` is the audited safe `&mut Loader` accessor // (per-VM DotEnv loader, valid for VM lifetime; centralised // single-unsafe deref). `.map` is its `&'a mut Map` slot. - let envmap = match jsc_vm + let envmap = jsc_vm .transpiler .env_mut() .map - .create_null_delimited_env_map() - { - Ok(m) => m, - Err(_) => return Err(global_this.throw_out_of_memory()), - }; + .create_null_delimited_env_map(); // Note: `as_slice()` *includes* the trailing null, so strip it; the // common tail below re-appends one after the optional NODE_CHANNEL_* // entries. diff --git a/src/runtime/api/cron.rs b/src/runtime/api/cron.rs index ea9ede4d3ad9..8609ee10ef2c 100644 --- a/src/runtime/api/cron.rs +++ b/src/runtime/api/cron.rs @@ -2321,28 +2321,16 @@ unsafe fn spawn_cmd_prepare( } #[cfg(unix)] let envp: *const *const c_char = bun_core::c_environ(); + // `Transpiler::env_mut()` is the audited safe `&mut Loader` accessor + // (process-lifetime singleton; centralised single-unsafe deref). #[cfg(windows)] - let envp_owned; + let envp_owned = vm_mut() + .transpiler + .env_mut() + .map + .create_null_delimited_env_map(); #[cfg(windows)] - let envp: *const *const c_char = { - // `Transpiler::env_mut()` is the audited safe `&mut Loader` accessor - // (process-lifetime singleton; centralised single-unsafe deref). - match vm_mut() - .transpiler - .env_mut() - .map - .create_null_delimited_env_map() - { - Ok(v) => { - envp_owned = v; - envp_owned.as_ptr().cast() - } - Err(_) => { - s!().set_err(format_args!("Failed to create environment block")); - return Err(()); - } - } - }; + let envp: *const *const c_char = envp_owned.as_ptr().cast(); // Ownership note: BOTH // `Source::Pipe` and `WindowsStdioResult::Buffer` own a `Box`, diff --git a/src/runtime/api/js_bundle_completion_task.rs b/src/runtime/api/js_bundle_completion_task.rs index b5099cad4fff..3a505a17703b 100644 --- a/src/runtime/api/js_bundle_completion_task.rs +++ b/src/runtime/api/js_bundle_completion_task.rs @@ -667,7 +667,6 @@ impl JSBundleCompletionTask { // with owned `Vec` payloads; drops at end of scope. if let CompileResult::Err(err) = &compile_result { - // `bun.handleOom(log.addError(..., bun.handleOom(dupe(..))))` this.log.add_error_fmt( None, bun_ast::Loc::EMPTY, @@ -930,7 +929,7 @@ impl CompletionStruct for JSBundleCompletionTask { transpiler.options.env.prefix = Box::from(config.env_prefix.list.as_slice()); // `BundleOptions.bundler_feature_flags: Option>` owns // its set, so clone rather than alias `config.features`. - transpiler.options.bundler_feature_flags = Some(Box::new(config.features.clone()?)); + transpiler.options.bundler_feature_flags = Some(Box::new(config.features.clone())); if config.force_node_env != options::ForceNodeEnv::Unspecified { transpiler.options.force_node_env = config.force_node_env; } diff --git a/src/runtime/bake/DevServer.rs b/src/runtime/bake/DevServer.rs index e8f6e34786c5..29167a0b4d63 100644 --- a/src/runtime/bake/DevServer.rs +++ b/src/runtime/bake/DevServer.rs @@ -989,7 +989,7 @@ pub(crate) fn init(options: Options) -> JsResult> { framework_router::RouteIndex::init(u32::try_from(i).expect("int cast")), true, ), - )?; + ); } break 'router FrameworkRouter::init_empty(&dev.root, types.into_boxed_slice())?; @@ -1274,8 +1274,8 @@ impl DevServer { )?; } - self.server_graph.ensure_stale_bit_capacity(true)?; - self.client_graph.ensure_stale_bit_capacity(true)?; + self.server_graph.ensure_stale_bit_capacity(true); + self.client_graph.ensure_stale_bit_capacity(true); Ok(()) } @@ -1962,7 +1962,7 @@ fn ensure_route_is_bundled( route_bundle::State::Unqueued => { // We already are bundling something, defer the request if dev.current_bundle.is_some() { - dev.next_bundle.route_queue.put(route_bundle_index, ())?; + dev.next_bundle.route_queue.put(route_bundle_index, ()); ctx.on_defer(BundleQueueType::NextBundle)?; dev.route_bundle_ptr(route_bundle_index).server_state = route_bundle::State::DeferredToNextBundle; @@ -2023,7 +2023,7 @@ fn ensure_route_is_bundled( break 'plugin; } PluginState::Pending => { - dev.next_bundle.route_queue.put(route_bundle_index, ())?; + dev.next_bundle.route_queue.put(route_bundle_index, ()); ctx.on_defer(BundleQueueType::NextBundle)?; dev.route_bundle_ptr(route_bundle_index).server_state = route_bundle::State::DeferredToNextBundle; @@ -2059,7 +2059,7 @@ fn ensure_route_is_bundled( } } - dev.next_bundle.route_queue.put(route_bundle_index, ())?; + dev.next_bundle.route_queue.put(route_bundle_index, ()); ctx.on_defer(BundleQueueType::NextBundle)?; dev.route_bundle_ptr(route_bundle_index).server_state = route_bundle::State::Bundling; @@ -3254,10 +3254,8 @@ impl DevServer { let start_data = bv2.start_from_bake_dev_server(&{ let mut bt = bundler::bake_types::EntryPointList::empty(); for (k, v) in entry_points.set.iter() { - bun_core::handle_oom( - bt.set - .put(k, bundler::bake_types::EntryPointFlags(v.bits())), - ); + bt.set + .put(k, bundler::bake_types::EntryPointFlags(v.bits())); } bt })?; @@ -3889,7 +3887,7 @@ pub(super) fn finalize_bundle( let targets = bv2.graph.ast.items_target(); let scbs = bv2.graph.server_component_boundaries.slice(); - let mut scb_bitset = DynamicBitSet::init_empty(input_file_sources.len())?; + let mut scb_bitset = DynamicBitSet::init_empty(input_file_sources.len()); for ((source_index, ssr_index), ref_index) in scbs .list .items_source_index() @@ -4056,7 +4054,7 @@ pub(super) fn finalize_bundle( if looks_like_tailwind { // Note: `get_or_put` consumes the key by value; on miss the key // already lives in the map so the explicit `*key_ptr =` is redundant. - let _ = map.get_or_put(Box::from(key))?; + let _ = map.get_or_put(Box::from(key)); } else { let _ = map.swap_remove(&Box::<[u8]>::from(key)); } @@ -4145,7 +4143,7 @@ pub(super) fn finalize_bundle( } else { 0 })?; - ctx.server_seen_bit_set = DynamicBitSet::init_empty(dev.server_graph.bundled_files.len())?; + ctx.server_seen_bit_set = DynamicBitSet::init_empty(dev.server_graph.bundled_files.len()); dev.incremental_result.had_adjusted_edges = false; @@ -4193,8 +4191,8 @@ pub(super) fn finalize_bundle( } dev.index_failures()?; - dev.client_graph.ensure_stale_bit_capacity(false)?; - dev.server_graph.ensure_stale_bit_capacity(false)?; + dev.client_graph.ensure_stale_bit_capacity(false); + dev.server_graph.ensure_stale_bit_capacity(false); dev.generation = dev.generation.wrapping_add(1); if Environment::ENABLE_LOGS { @@ -4322,8 +4320,8 @@ pub(super) fn finalize_bundle( let _ = errors; // TODO: } - let mut route_bits = DynamicBitSet::init_empty(dev.route_bundles.len())?; - let mut route_bits_client = DynamicBitSet::init_empty(dev.route_bundles.len())?; + let mut route_bits = DynamicBitSet::init_empty(dev.route_bundles.len()); + let mut route_bits_client = DynamicBitSet::init_empty(dev.route_bundles.len()); let mut has_route_bits_set = false; @@ -4541,8 +4539,7 @@ pub(super) fn finalize_bundle( // SAFETY: as above; the exclusive borrow of the socket's // map ends when `entry` dies at the end of this block. let entry = unsafe { &mut (**socket_ptr).referenced_source_maps } - .get_or_put(script_id) - .expect("oom"); + .get_or_put(script_id); if !entry.found_existing { sockets += 1; } @@ -5012,9 +5009,7 @@ impl DevServer { .current_bundle .as_mut() .expect("infallible: bundle active"); - let gop = current_bundle - .resolution_failure_entries - .get_or_put(owner)?; + let gop = current_bundle.resolution_failure_entries.get_or_put(owner); if !gop.found_existing { *gop.value_ptr = Log::init(); } @@ -5426,9 +5421,9 @@ impl DevServer { /// `extra_client_bits` is specified if it is possible that the client graph may /// increase in size while the bits are being used. fn init_graph_trace_state(&self, extra_client_bits: usize) -> crate::Result { - let server_bits = DynamicBitSet::init_empty(self.server_graph.bundled_files.len())?; + let server_bits = DynamicBitSet::init_empty(self.server_graph.bundled_files.len()); let client_bits = - DynamicBitSet::init_empty(self.client_graph.bundled_files.len() + extra_client_bits)?; + DynamicBitSet::init_empty(self.client_graph.bundled_files.len() + extra_client_bits); Ok(GraphTraceState { server_bits, client_bits, @@ -5855,7 +5850,7 @@ impl DevServer { associated_route, file_kind == framework_router::FileKind::Layout, ), - )?; + ); Ok(to_opaque_file_id::<{ bake::Side::Server }>(index)) } @@ -6061,7 +6056,7 @@ impl EntryPointList { abs_path: &[u8], flags: entry_point_list::Flags, ) -> crate::Result<()> { - let gop = self.set.get_or_put(abs_path)?; + let gop = self.set.get_or_put(abs_path); if gop.found_existing { *gop.value_ptr |= flags; } else { @@ -6097,7 +6092,7 @@ impl HTMLRouter { if path == b"/*" { self.fallback = Some(route); } else { - self.map.put(path, route)?; + self.map.put(path, route); } Ok(()) } @@ -6336,10 +6331,7 @@ impl<'a> PromiseEnsureRouteBundledCtx<'a> { .as_mut() .expect("infallible: bundle active"); if cb.promise.strong.has_value() { - cb.promise - .route_bundle_indices - .put(route_bundle_index, ()) - .expect("oom"); + cb.promise.route_bundle_indices.put(route_bundle_index, ()); self.p = Some(cb.promise.strong.get()); return Ok(()); } @@ -6349,10 +6341,7 @@ impl<'a> PromiseEnsureRouteBundledCtx<'a> { .current_bundle .as_mut() .expect("infallible: bundle active"); - cb.promise - .route_bundle_indices - .put(route_bundle_index, ()) - .expect("oom"); + cb.promise.route_bundle_indices.put(route_bundle_index, ()); cb.promise.strong = strong_promise; Ok(()) } @@ -6362,8 +6351,7 @@ impl<'a> PromiseEnsureRouteBundledCtx<'a> { .next_bundle .promise .route_bundle_indices - .put(route_bundle_index, ()) - .expect("oom"); + .put(route_bundle_index, ()); self.p = Some(self.dev_mut().next_bundle.promise.strong.get()); return Ok(()); } @@ -6372,8 +6360,7 @@ impl<'a> PromiseEnsureRouteBundledCtx<'a> { .next_bundle .promise .route_bundle_indices - .put(route_bundle_index, ()) - .expect("oom"); + .put(route_bundle_index, ()); self.dev_mut().next_bundle.promise.strong = strong_promise; Ok(()) } diff --git a/src/runtime/bake/FrameworkRouter.rs b/src/runtime/bake/FrameworkRouter.rs index ba6c27270bfa..8b03864c24ea 100644 --- a/src/runtime/bake/FrameworkRouter.rs +++ b/src/runtime/bake/FrameworkRouter.rs @@ -1139,14 +1139,14 @@ impl FrameworkRouter { } else { p.route_path() }; - let gop = self.static_routes.get_or_put(key)?; + let gop = self.static_routes.get_or_put(key); if gop.found_existing { panic!("TODO: propagate aliased route error"); } *gop.value_ptr = new_route_index; } InsertPattern::Dynamic(p) => { - let gop = self.dynamic_routes.get_or_put(p)?; + let gop = self.dynamic_routes.get_or_put(p); if gop.found_existing { panic!("TODO: propagate aliased route error"); } @@ -1516,7 +1516,7 @@ impl FrameworkRouter { let _entries_lock = fs_ref.fs.entries_mutex.lock_guard(); if let Some(entries) = dir_info.get_entries_const() { for (k, &v) in entries.data.iter() { - let _ = zig_order.put(Box::from(&**k), v); + zig_order.put(Box::from(&**k), v); } } } diff --git a/src/runtime/bake/bake_body.rs b/src/runtime/bake/bake_body.rs index d51f80223766..bc8aa2cfad48 100644 --- a/src/runtime/bake/bake_body.rs +++ b/src/runtime/bake/bake_body.rs @@ -546,14 +546,14 @@ impl Framework { built_in_modules: { // Note: was `ArrayHashMap::from_entries(arena, keys, vals)`; // that constructor doesn't exist on the heap-backed - // `ArrayHashMap` — build it imperatively. `bun.handleOom`. + // `ArrayHashMap` — build it imperatively. let keys: [&'static [u8]; 3] = [ b"bun-framework-react/client.tsx", b"bun-framework-react/server.tsx", b"bun-framework-react/ssr.tsx", ]; let mut m: ArrayHashMap<&'static [u8], BuiltInModule> = ArrayHashMap::new(); - bun_core::handle_oom(m.ensure_total_capacity(keys.len())); + m.ensure_total_capacity(keys.len()); for (k, v) in keys.iter().zip(built_in_values.iter()) { m.put_assume_capacity(*k, *v); } @@ -596,7 +596,7 @@ impl Framework { fw.built_in_modules.put( b"react-refresh/runtime/index.js" as &[u8], react_refresh_code, - )?; + ); } Ok(fw) @@ -622,7 +622,7 @@ impl Framework { file_system_router_types: self.file_system_router_types.clone(), server_components: self.server_components, react_fast_refresh: self.react_fast_refresh, - built_in_modules: bun_core::handle_oom(self.built_in_modules.clone()), + built_in_modules: self.built_in_modules.clone(), } } @@ -882,7 +882,7 @@ impl Framework { let len = array.get_length(global)?; let mut files: ArrayHashMap<&'static [u8], BuiltInModule> = ArrayHashMap::new(); - bun_core::handle_oom(files.ensure_total_capacity(len as usize)); + files.ensure_total_capacity(len as usize); let mut it = array.array_iterator(global)?; let mut i: usize = 0; @@ -1113,7 +1113,7 @@ impl Framework { BuiltInModule::Import(p) => bt::BuiltInModule::Import(p.into()), BuiltInModule::Code(c) => bt::BuiltInModule::Code(c.into()), }; - bun_core::handle_oom(built_in_modules.put(k, bv)); + built_in_modules.put(k, bv); } let server_components = self .server_components diff --git a/src/runtime/bake/dev_server/assets.rs b/src/runtime/bake/dev_server/assets.rs index 1057d6f3e7dd..c61f7371b765 100644 --- a/src/runtime/bake/dev_server/assets.rs +++ b/src/runtime/bake/dev_server/assets.rs @@ -74,7 +74,7 @@ impl Assets { // `gop` holds key/value ptrs into `path_map` and cannot stay live // across calls that take `&mut self`. Capture `index` / // `found_existing` and re-derive the value slot at the end instead. - let gop = self.path_map.get_or_put(abs_path)?; + let gop = self.path_map.get_or_put(abs_path); let path_index = gop.index; let found_existing = gop.found_existing; let existing_entry = if found_existing { @@ -182,7 +182,7 @@ impl Assets { /// `Assets.reindexIfNeeded`. pub(crate) fn reindex_if_needed(&mut self) -> Result<(), bun_alloc::AllocError> { if self.needs_reindex { - self.files.re_index()?; + self.files.re_index(); self.needs_reindex = false; } Ok(()) diff --git a/src/runtime/bake/dev_server/error_report_request.rs b/src/runtime/bake/dev_server/error_report_request.rs index 48bd7434f12d..a4b6630091db 100644 --- a/src/runtime/bake/dev_server/error_report_request.rs +++ b/src/runtime/bake/dev_server/error_report_request.rs @@ -167,7 +167,7 @@ impl ErrorReportRequest { // HMR chunks use this too, but currently do not host their JS code. let mut parsed_source_maps: ArrayHashMap>> = ArrayHashMap::new(); - bun_core::handle_oom(parsed_source_maps.ensure_total_capacity(4)); + parsed_source_maps.ensure_total_capacity(4); // Note: `defer for (parsed_source_maps.values()) |*v| v.deinit()` deleted — // `GetResult` drops its owned `mappings` automatically. @@ -186,7 +186,7 @@ impl ErrorReportRequest { }; // Get and cache the parsed source map - let gop = bun_core::handle_oom(parsed_source_maps.get_or_put(id)); + let gop = parsed_source_maps.get_or_put(id); if !gop.found_existing { match dev.source_maps.get_parsed_source_map(id) { None => { diff --git a/src/runtime/bake/dev_server/hmr_socket.rs b/src/runtime/bake/dev_server/hmr_socket.rs index 38ef17a2be0a..f9cdf1746c28 100644 --- a/src/runtime/bake/dev_server/hmr_socket.rs +++ b/src/runtime/bake/dev_server/hmr_socket.rs @@ -231,7 +231,6 @@ impl HmrSocket { let timer = std::time::Instant::now(); dev.start_async_bundle(event.entry_points, true, timer) - // bun.handleOom(err) — Rust aborts on OOM by default .expect("OOM"); // `event.entry_points.deinit(allocator)` → Drop handles this diff --git a/src/runtime/bake/dev_server/incremental_graph.rs b/src/runtime/bake/dev_server/incremental_graph.rs index 3522f6447791..c699d1c495b1 100644 --- a/src/runtime/bake/dev_server/incremental_graph.rs +++ b/src/runtime/bake/dev_server/incremental_graph.rs @@ -418,15 +418,12 @@ impl IncrementalGraph { /// Grows `stale_files` to cover all currently-known files, filling new /// bits with `are_new_files_stale`. - pub(crate) fn ensure_stale_bit_capacity( - &mut self, - are_new_files_stale: bool, - ) -> Result<(), bun_alloc::AllocError> { + pub(crate) fn ensure_stale_bit_capacity(&mut self, are_new_files_stale: bool) { let want = self.bundled_files.count().max(self.stale_files.bit_length); // Align forward to 8 usize words (8*64 bits). const STEP: usize = core::mem::size_of::() * 8 * 8; let aligned = want.div_ceil(STEP) * STEP; - self.stale_files.resize(aligned, are_new_files_stale) + self.stale_files.resize(aligned, are_new_files_stale); } /// `IncrementalGraph(side).freeFileContent` (client only). @@ -568,7 +565,7 @@ impl IncrementalGraph { } } - let gop = self.bundled_files.get_or_put(key)?; + let gop = self.bundled_files.get_or_put(key); let file_index = FileIndex::::init(gop.index as u32); let found_existing = gop.found_existing; if !found_existing { @@ -810,7 +807,7 @@ impl IncrementalGraph { seen: false, edge_index, }, - )?; + ); } } @@ -1019,7 +1016,7 @@ impl IncrementalGraph { ctx.gts.bits(SIDE).set(imported_file_index.get() as usize); } - let gop = quick_lookup.get_or_put(imported_file_index)?; + let gop = quick_lookup.get_or_put(imported_file_index); if gop.found_existing { if gop.value_ptr.seen { return Ok(EdgeAttachmentResult::Continue); @@ -1289,7 +1286,7 @@ impl IncrementalGraph { is_ssr_graph: bool, is_route: bool, ) -> Result, bun_alloc::AllocError> { - let gop = self.bundled_files.get_or_put(abs_path)?; + let gop = self.bundled_files.get_or_put(abs_path); let idx = gop.index; let found_existing = gop.found_existing; if found_existing { @@ -1348,7 +1345,7 @@ impl IncrementalGraph { abs_path: &[u8], kind: FileKind, ) -> Result, bun_alloc::AllocError> { - let gop = self.bundled_files.get_or_put(abs_path)?; + let gop = self.bundled_files.get_or_put(abs_path); let idx = gop.index; let found_existing = gop.found_existing; if !found_existing { @@ -1376,7 +1373,7 @@ impl IncrementalGraph { if !found_existing { self.first_dep.push(None); self.first_import.push(None); - self.ensure_stale_bit_capacity(true)?; + self.ensure_stale_bit_capacity(true); } Ok(InsertEmptyResult { index: FileIndex::init(idx as u32), @@ -1394,7 +1391,7 @@ impl IncrementalGraph { abs_path: &[u8], ) -> Result<(), crate::Error> { debug_assert!(matches!(SIDE, Side::Server)); - let gop = self.bundled_files.get_or_put(abs_path)?; + let gop = self.bundled_files.get_or_put(abs_path); let file_index = FileIndex::::init(gop.index as u32); let found_existing = gop.found_existing; if !found_existing { @@ -1422,7 +1419,7 @@ impl IncrementalGraph { ) -> Result<(), bun_alloc::AllocError> { let (idx, found_existing) = match key { InsertFailureKey::AbsPath(abs_path) => { - let gop = self.bundled_files.get_or_put(abs_path)?; + let gop = self.bundled_files.get_or_put(abs_path); if !gop.found_existing { *gop.key_ptr = Box::<[u8]>::from(abs_path); } @@ -1435,7 +1432,7 @@ impl IncrementalGraph { } InsertFailureKey::Index(i) => (i as usize, true), }; - self.ensure_stale_bit_capacity(true)?; + self.ensure_stale_bit_capacity(true); self.stale_files.set(idx); match SIDE { @@ -1498,7 +1495,7 @@ impl IncrementalGraph { }; // SAFETY: sibling-field access. unsafe { - let fail_gop = (*dev).bundling_failures.get_or_put(fail_owner)?; + let fail_gop = (*dev).bundling_failures.get_or_put(fail_owner); (*dev) .incremental_result .failures_added diff --git a/src/runtime/bake/dev_server/mod.rs b/src/runtime/bake/dev_server/mod.rs index 71a4951daf9b..606dfd01006d 100644 --- a/src/runtime/bake/dev_server/mod.rs +++ b/src/runtime/bake/dev_server/mod.rs @@ -252,18 +252,14 @@ impl GraphTraceState { Side::Server => &mut self.server_bits, }; if b.unmanaged.bit_length < new_size { - b.resize(new_size, false)?; + b.resize(new_size, false); } Ok(()) } pub(crate) fn clear_and_free(&mut self) { - self.client_bits - .resize(0, false) - .expect("freeing memory can not fail"); - self.server_bits - .resize(0, false) - .expect("freeing memory can not fail"); + self.client_bits.resize(0, false); + self.server_bits.resize(0, false); } } @@ -498,7 +494,7 @@ impl HotReloadEvent { // cached, anyways. // Note: inlined `append_file` body for disjoint borrow // (`self.dirs.keys()` is held immutably across this loop). - bun_core::handle_oom(self.files.get_or_put(source_file_path.slice())); + self.files.get_or_put(source_file_path.slice()); dev.directory_watchers.free_dependency_index(index); } else { // rebuild a new linked list for unaffected files @@ -520,11 +516,11 @@ impl HotReloadEvent { let mut rest_extra: &[u8] = &self.extra_files; while let Some(str_idx) = bun_core::strings::index_of_char_usize(rest_extra, 0) { - bun_core::handle_oom(self.files.put(&rest_extra[0..str_idx as usize], ())); + self.files.put(&rest_extra[0..str_idx as usize], ()); rest_extra = &rest_extra[str_idx as usize + 1..]; } if !rest_extra.is_empty() { - bun_core::handle_oom(self.files.put(rest_extra, ())); + self.files.put(rest_extra, ()); } let changed_file_paths = self.files.keys(); @@ -582,7 +578,7 @@ impl HotReloadEvent { /// Records a changed file path in the pending hot-reload event (deduplicated). pub(crate) fn append_file(&mut self, file_path: &[u8]) { - bun_core::handle_oom(self.files.get_or_put(file_path)); + self.files.get_or_put(file_path); } /// Records a changed directory (and, when present, the changed entry @@ -591,7 +587,7 @@ impl HotReloadEvent { if dir_path.is_empty() { return; } - bun_core::handle_oom(self.dirs.get_or_put(dir_path)); + self.dirs.get_or_put(dir_path); let Some(sub_path) = maybe_sub_path else { return; @@ -1198,18 +1194,11 @@ bun_bundler::link_impl_DevServerHandle! { .unwrap_or(core::ptr::null_mut()) }, register_barrel_with_deferrals(path) => { - let _ = (*this) - .barrel_files_with_deferrals - .get_or_put(path) - .map_err(|_| bun_alloc::out_of_memory()); - Ok(()) + (*this).barrel_files_with_deferrals.get_or_put(path); }, register_barrel_export(barrel_path, alias) => { - // Silently drop on alloc failure. - let Ok(gop) = (*this).barrel_needed_exports.get_or_put(barrel_path) else { - return; - }; - let _ = gop.value_ptr.get_or_put(alias); + let gop = (*this).barrel_needed_exports.get_or_put(barrel_path); + gop.value_ptr.get_or_put(alias); }, } } @@ -1350,7 +1339,7 @@ impl DirectoryWatchStore { // calling self methods that need &mut self. let gop = self.watches.get_or_put( bun_paths::string_paths::without_trailing_slash_windows_path(dir_name_to_watch), - )?; + ); let gop_index = gop.index; let found_existing = gop.found_existing; diff --git a/src/runtime/bake/dev_server/source_map_store.rs b/src/runtime/bake/dev_server/source_map_store.rs index c20acff84659..809807a94756 100644 --- a/src/runtime/bake/dev_server/source_map_store.rs +++ b/src/runtime/bake/dev_server/source_map_store.rs @@ -461,7 +461,7 @@ impl SourceMapStore { script_id: Key, ref_count: u32, ) -> Result, bun_alloc::AllocError> { - let gop = self.entries.get_or_put(script_id)?; + let gop = self.entries.get_or_put(script_id); if !gop.found_existing { debug_assert!(ref_count > 0); // invalid state *gop.value_ptr = Entry { @@ -668,7 +668,6 @@ impl SourceMapStore { let entry = &self.entries.values()[index]; let script_id_decoded = SourceId(script_id.get()); - // bun.handleOom(expr) — Rust aborts on OOM by default; just unwrap the inner Result. let vlq_bytes = entry .render_mappings(script_id_decoded.kind()) .expect("OOM"); diff --git a/src/runtime/bake/mod.rs b/src/runtime/bake/mod.rs index 12136842c27d..68c4b0057705 100644 --- a/src/runtime/bake/mod.rs +++ b/src/runtime/bake/mod.rs @@ -155,7 +155,7 @@ impl Framework { BuiltInModule::Import(p) => BuiltInModule::Import(p.clone()), BuiltInModule::Code(c) => BuiltInModule::Code(c.clone()), }; - bun_core::handle_oom(built_in_modules.put(k, bv)); + built_in_modules.put(k, bv); } let server_components = self .server_components @@ -528,7 +528,7 @@ impl From for Framework { fn from(src: bake_body::Framework) -> Self { let mut built_in_modules = bun_collections::StringArrayHashMap::new(); for (k, v) in src.built_in_modules.iter() { - bun_core::handle_oom(built_in_modules.put(*k, BuiltInModule::from(*v))); + built_in_modules.put(*k, BuiltInModule::from(*v)); } Self { is_built_in_react: src.is_built_in_react, diff --git a/src/runtime/bake/production.rs b/src/runtime/bake/production.rs index 81c32d956928..cfbd69510ba5 100644 --- a/src/runtime/bake/production.rs +++ b/src/runtime/bake/production.rs @@ -271,7 +271,7 @@ fn write_sourcemap_to_disk( let mut key = Vec::with_capacity(6 + without_prefix.len()); write!(&mut key, "bake:/{}", BStr::new(without_prefix)).expect("infallible: in-memory write"); - source_maps.put(&key, OutputFileIndex::init(source_map_index))?; + source_maps.put(&key, OutputFileIndex::init(source_map_index)); Ok(()) } @@ -416,7 +416,7 @@ fn build_with_vm(ctx: Context, cwd: &[u8], pt: &mut PerThread) -> crate::Result< // SAFETY: single-threaded CLI init; `get_or_init` guarantees one-time // setup and `backing` is never moved (static storage). let loader = unsafe { &mut *backing.loader.get() }; - loader.map.put(b"NODE_ENV", b"production")?; + loader.map.put(b"NODE_ENV", b"production"); dotenv::set_instance(std::ptr::from_mut::(loader)); // In-place init via `MaybeUninit` (`init_transpiler_with_options` @@ -764,7 +764,7 @@ fn build_with_vm(ctx: Context, cwd: &[u8], pt: &mut PerThread) -> crate::Result< output_module_map.put( &key, OutputFileIndex::init(u32::try_from(i).expect("int cast")), - )?; + ); } OutputKind::Asset => {} OutputKind::Bytecode => {} @@ -1502,7 +1502,7 @@ impl PerThread { // SAFETY: `vm` is the live per-thread VM from `init_bake` (non-null, // write provenance); outlives `PerThread`. vm: unsafe { bun_ptr::BackRef::from_raw_mut(vm) }, - loaded_files: AutoBitSet::init_empty(0).expect("unreachable"), + loaded_files: AutoBitSet::init_empty(0), all_server_files: None, attached: false, } @@ -1518,7 +1518,7 @@ impl PerThread { source_maps: StringArrayHashMap, ) -> crate::Result { let n = entry_points.files.count(); - let loaded_files = AutoBitSet::init_empty(n)?; + let loaded_files = AutoBitSet::init_empty(n); // errdefer loaded_files.deinit() — handled by Drop on error path // SAFETY: BackRef invariant — vm is the live per-thread VM from `init_bake` diff --git a/src/runtime/cli/audit_command.rs b/src/runtime/cli/audit_command.rs index a38049d404f0..ee8cc4567d4e 100644 --- a/src/runtime/cli/audit_command.rs +++ b/src/runtime/cli/audit_command.rs @@ -331,7 +331,7 @@ fn build_dependency_tree( let resolved_name = pkg_names[resolved_pkg_id as usize].slice(buf); // `StringHashMap::get_or_put` always boxes the key on miss. - let result = dependency_tree.get_or_put(resolved_name)?; + let result = dependency_tree.get_or_put(resolved_name); result.value_ptr.push(Box::<[u8]>::from(package_name)); } } @@ -509,7 +509,7 @@ fn collect_packages_for_audit( versions: Vec::new(), }); let found = (group_idx, packages_list.len() - 1); - by_name.put(pkg_name_hashes[idx], found)?; + by_name.put(pkg_name_hashes[idx], found); found } }; @@ -904,7 +904,7 @@ fn find_dependency_paths( if let Some(dependents) = dependency_tree.get(target_package) { for dependent in dependents { queue.push_back(dependent.clone()); - parent_map.put(dependent, Box::<[u8]>::from(target_package))?; + parent_map.put(dependent, Box::<[u8]>::from(target_package)); } } @@ -912,7 +912,7 @@ fn find_dependency_paths( if visited.contains_key(&*current) { continue; } - visited.put(¤t, ())?; + visited.put(¤t, ()); let mut is_root_dep = false; for dependency in dep_slice { @@ -959,7 +959,7 @@ fn find_dependency_paths( } path.path.push(trace.clone()); - seen_in_trace.put(&trace, ())?; + seen_in_trace.put(&trace, ()); if let Some(parent) = parent_map.get(&*trace) { trace.clone_from(parent); @@ -984,7 +984,7 @@ fn find_dependency_paths( for dependent in dependents { if !visited.contains_key(&**dependent) { queue.push_back(dependent.clone()); - parent_map.put(dependent, current.clone())?; + parent_map.put(dependent, current.clone()); } } } diff --git a/src/runtime/cli/build_command.rs b/src/runtime/cli/build_command.rs index 92003b6f7c64..f6bda7a8bdd3 100644 --- a/src/runtime/cli/build_command.rs +++ b/src/runtime/cli/build_command.rs @@ -447,7 +447,7 @@ impl BuildCommand { if ctx.bundler_options.production { // SAFETY: `env` is a process-lifetime singleton set in `Transpiler::init`. - unsafe { (*this_transpiler.env).map.put(b"NODE_ENV", b"production")? }; + unsafe { (*this_transpiler.env).map.put(b"NODE_ENV", b"production") }; } this_transpiler.configure_defines()?; @@ -1279,7 +1279,7 @@ pub(crate) fn collect_compile_assets( (), ); #[cfg(not(windows))] - let _ = seen.put(key, ()); + seen.put(key, ()); } let mut push = |out: &mut Vec, asset: &[u8], dest: Vec, bytes: Vec| { @@ -1290,7 +1290,7 @@ pub(crate) fn collect_compile_assets( bun_fmt::quote(&dest), )); } - let _ = seen.put(&dest, ()); + seen.put(&dest, ()); out.push(options::OutputFile { loader: Loader::File, input_loader: Loader::File, diff --git a/src/runtime/cli/bunx_command.rs b/src/runtime/cli/bunx_command.rs index 15e2b2287af6..86d7ce81d466 100644 --- a/src/runtime/cli/bunx_command.rs +++ b/src/runtime/cli/bunx_command.rs @@ -761,18 +761,11 @@ impl BunxCommand { force_using_bun, )?; let env_loader = this_transpiler.env_mut(); + env_loader.map.put(b"npm_command", b"exec"); + env_loader.map.put(b"npm_lifecycle_event", b"bunx"); env_loader .map - .put(b"npm_command", b"exec") - .expect("unreachable"); - env_loader - .map - .put(b"npm_lifecycle_event", b"bunx") - .expect("unreachable"); - env_loader - .map - .put(b"npm_lifecycle_script", opts.package_name) - .expect("unreachable"); + .put(b"npm_lifecycle_script", opts.package_name); if opts.package_name == b"bun-repl" { env_loader.map.remove(b"BUN_INSPECT_CONNECT_TO"); @@ -962,7 +955,7 @@ impl BunxCommand { v }; - env_loader.map.put(b"PATH", &path)?; + env_loader.map.put(b"PATH", &path); // SAFETY: `Transpiler::init` always sets `fs` to the process singleton. let fs = unsafe { &mut *this_transpiler.fs }; let uid_digits = bun_core::fmt::digit_count(uid); @@ -1349,12 +1342,9 @@ impl BunxCommand { "installing package: {}", bun_core::fmt::fmt_slice(argv_to_use, " "), ); - env_loader - .map - .put(b"BUN_INTERNAL_BUNX_INSTALL", b"true") - .expect("oom"); + env_loader.map.put(b"BUN_INTERNAL_BUNX_INSTALL", b"true"); - let envp = env_loader.map.create_null_delimited_env_map()?; + let envp = env_loader.map.create_null_delimited_env_map(); let spawn_result = match proc_sync::spawn(&proc_sync::Options { argv: argv_to_use.iter().map(|s| Box::<[u8]>::from(*s)).collect(), diff --git a/src/runtime/cli/create/SourceFileProjectGenerator.rs b/src/runtime/cli/create/SourceFileProjectGenerator.rs index 3301ba5e0523..7dc633bbca92 100644 --- a/src/runtime/cli/create/SourceFileProjectGenerator.rs +++ b/src/runtime/cli/create/SourceFileProjectGenerator.rs @@ -66,8 +66,8 @@ pub(crate) fn generate( // Add Tailwind dependencies if needed if needs_to_inject_tailwind { - result.dependencies.insert(b"tailwindcss")?; - result.dependencies.insert(b"bun-plugin-tailwind")?; + result.dependencies.insert(b"tailwindcss"); + result.dependencies.insert(b"bun-plugin-tailwind"); } // Add shadcn-ui dependencies if needed @@ -75,11 +75,11 @@ pub(crate) fn generate( // https://ui.shadcn.com/docs/installation/manual // This will probably be tricky to keep updated. // but hopefully the dependency scanning will just handle it for us. - result.dependencies.insert(b"tw-animate-css")?; - result.dependencies.insert(b"class-variance-authority")?; - result.dependencies.insert(b"clsx")?; - result.dependencies.insert(b"tailwind-merge")?; - result.dependencies.insert(b"lucide-react")?; + result.dependencies.insert(b"tw-animate-css"); + result.dependencies.insert(b"class-variance-authority"); + result.dependencies.insert(b"clsx"); + result.dependencies.insert(b"tailwind-merge"); + result.dependencies.insert(b"lucide-react"); } let uses_tailwind = has_tailwind_in_dependencies || needs_to_inject_tailwind; @@ -90,8 +90,8 @@ pub(crate) fn generate( // Add react-dom if react is used let _ = result.dependencies.swap_remove(b"react"); let _ = result.dependencies.swap_remove(b"react-dom"); - result.dependencies.insert(b"react-dom@19")?; - result.dependencies.insert(b"react@19")?; + result.dependencies.insert(b"react-dom@19"); + result.dependencies.insert(b"react@19"); let dev_dependencies: &[&[u8]] = &[b"@types/bun", b"@types/react@19", b"@types/react-dom@19"]; @@ -598,7 +598,7 @@ fn get_shadcn_components( let import_records = &all[file.get() as usize]; for import_record in import_records.as_slice() { if import_record.path.text.starts_with(b"@/components/ui/") { - icons.insert(&import_record.path.text[b"@/components/ui/".len()..])?; + icons.insert(&import_record.path.text[b"@/components/ui/".len()..]); } } } diff --git a/src/runtime/cli/create_command.rs b/src/runtime/cli/create_command.rs index 62f438717a75..e069b1683253 100644 --- a/src/runtime/cli/create_command.rs +++ b/src/runtime/cli/create_command.rs @@ -282,7 +282,7 @@ impl CreateCommand { let filesystem: &mut fs::FileSystem = unsafe { &mut *fs::FileSystem::init(None)? }; let mut env_loader = DotEnv::Loader::init(); - env_loader.load_process()?; + env_loader.load_process(); let dirname: &[u8] = if positionals.len() == 1 { bun_paths::basename(template) @@ -1301,7 +1301,7 @@ impl CreateCommand { let mut env_loader = DotEnv::Loader::init(); - env_loader.load_process()?; + env_loader.load_process(); // var unsupported_packages = UnsupportedPackages{}; // SAFETY: single-threaded CLI access to module-level static path buffer @@ -1937,7 +1937,7 @@ impl Example { length: u32::try_from(headers_buf.len() - b"Authorization".len()) .expect("int cast"), }, - })?; + }); } } @@ -2323,7 +2323,7 @@ impl CreateListExamplesCommand { let filesystem = fs::FileSystem::init(None)?; let mut env_loader = DotEnv::Loader::init(); - env_loader.load_process()?; + env_loader.load_process(); let mut progress = Progress { supports_ansi_escape_codes: Output::enable_ansi_colors_stderr(), diff --git a/src/runtime/cli/filter_run.rs b/src/runtime/cli/filter_run.rs index fea69d8562b4..ccbbf8569acd 100644 --- a/src/runtime/cli/filter_run.rs +++ b/src/runtime/cli/filter_run.rs @@ -112,16 +112,16 @@ impl<'a> ProcessHandle<'a> { // Copy to owned — `original_path` borrows env.map which is // mutated by put() below. let original_path: Box<[u8]> = env.map.get(b"PATH").unwrap_or(b"").into(); - let _ = env.map.put(b"PATH", &handle.config.PATH); + env.map.put(b"PATH", &handle.config.PATH); // Restores PATH unconditionally at block exit (success OR error). // Keep the guard armed for the whole block so `?` early-returns also // restore. scopeguard::defer! { // SAFETY: env_ptr valid for the run loop lifetime (see above). - let _ = unsafe { (*env_ptr).map.put(b"PATH", &original_path) }; + unsafe { (*env_ptr).map.put(b"PATH", &original_path) }; } // SAFETY: see above; reborrow through raw ptr to avoid overlapping &mut with guard. - let envp = unsafe { (*env_ptr).map.create_null_delimited_env_map()? }; + let envp = unsafe { (*env_ptr).map.create_null_delimited_env_map() }; // SAFETY: `argv`/`envp` are local null-terminated C-string arrays // with argv[0] non-null; valid for this call. break 'brk unsafe { @@ -1023,7 +1023,7 @@ pub(crate) fn run_scripts_with_filter( state.handles = handles_vec.into_boxed_slice(); for (i, script) in scripts.iter().enumerate() { let handle_ptr: *mut ProcessHandle = &raw mut state.handles[i]; - let res = map.get_or_put(&script.package_name)?; + let res = map.get_or_put(&script.package_name); if res.found_existing { res.value_ptr.push(handle_ptr); // Output.prettyErrorln("error: Duplicate package name: {s}", .{script.package_name}); diff --git a/src/runtime/cli/multi_run.rs b/src/runtime/cli/multi_run.rs index 23ee11cd59cb..eea6443bd124 100644 --- a/src/runtime/cli/multi_run.rs +++ b/src/runtime/cli/multi_run.rs @@ -6,7 +6,7 @@ use std::time::Instant; use crate::Error; use bun_collections::{StringArrayHashMap, VecExt}; use bun_core::strings; -use bun_core::{self as bun, Global, Output, UnwrapOrOom}; +use bun_core::{self as bun, Global, Output}; use bun_event_loop::EventLoopHandle; use bun_event_loop::MiniEventLoop::MiniEventLoop; use bun_install::package_manager::workspace_selection; @@ -162,13 +162,13 @@ impl<'a> ProcessHandle<'a> { // SAFETY: state.env points at the process-lifetime DotEnv loader. let env = unsafe { &mut *env_ptr }; let original_path: Box<[u8]> = env.map.get(b"PATH").map(Box::from).unwrap_or_default(); - let _ = env.map.put(b"PATH", &self.config.path); + env.map.put(b"PATH", &self.config.path); let _restore = scopeguard::guard(original_path, move |original_path| { // SAFETY: env_ptr is the process-lifetime loader; outlives this scope. - let _ = unsafe { (*env_ptr).map.put(b"PATH", &original_path) }; + unsafe { (*env_ptr).map.put(b"PATH", &original_path) }; }); // SAFETY: same loader; the `_restore` guard's closure has not fired yet. - envp = unsafe { (*env_ptr).map.create_null_delimited_env_map()? }; + envp = unsafe { (*env_ptr).map.create_null_delimited_env_map() }; // SAFETY: `argv`/`envp` are local null-terminated C-string arrays // with argv[0] non-null; valid for this call. unsafe { @@ -942,9 +942,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result::from(&value[..])) - .unwrap_or_oom(); + owned_scripts.put(&key[..], Box::<[u8]>::from(&value[..])); } let run_in_bun = ctx.debug.run_in_bun; diff --git a/src/runtime/cli/pack_command.rs b/src/runtime/cli/pack_command.rs index 4b767be83280..5bd3c73eb78e 100644 --- a/src/runtime/cli/pack_command.rs +++ b/src/runtime/cli/pack_command.rs @@ -614,7 +614,7 @@ fn iterate_included_project_tree( )); } bun_sys::FileKind::File => { - let dedupe_entry = subpath_dedupe.get_or_put(entry_subpath.as_bytes())?; + let dedupe_entry = subpath_dedupe.get_or_put(entry_subpath.as_bytes()); debug_assert!(!dedupe_entry.found_existing); if dedupe_entry.found_existing { continue; @@ -751,7 +751,7 @@ fn add_entire_tree( match entry.kind { bun_sys::FileKind::File => { - let dedupe_entry = dedupe.get_or_put(entry_subpath.as_bytes())?; + let dedupe_entry = dedupe.get_or_put(entry_subpath.as_bytes()); if dedupe_entry.found_existing { continue; } @@ -919,7 +919,7 @@ fn iterate_bundled_deps( let entry_subpath_ = entry_subpath(b"node_modules", entry_name.as_bytes())?; - let dedupe_entry = dedupe.get_or_put(entry_subpath_.as_bytes())?; + let dedupe_entry = dedupe.get_or_put(entry_subpath_.as_bytes()); dep.was_packed = true; if dedupe_entry.found_existing { // already got to it in `add_bundled_dep` below @@ -949,7 +949,7 @@ fn iterate_bundled_deps( let entry_subpath_ = entry_subpath(b"node_modules", entry_name)?; - let dedupe_entry = dedupe.get_or_put(entry_subpath_.as_bytes())?; + let dedupe_entry = dedupe.get_or_put(entry_subpath_.as_bytes()); dep.was_packed = true; if dedupe_entry.found_existing { // already got to it in `add_bundled_dep` below @@ -1119,7 +1119,7 @@ fn add_bundled_dep( ) { Ok(dep_dir) => { let dedupe_entry = - dedupe.get_or_put(dep_subpath.as_bytes())?; + dedupe.get_or_put(dep_subpath.as_bytes()); if dedupe_entry.found_existing { continue; } @@ -1168,7 +1168,7 @@ fn add_bundled_dep( }; let dedupe_entry = - dedupe.get_or_put(parent_dep_subpath.as_bytes())?; + dedupe.get_or_put(parent_dep_subpath.as_bytes()); if dedupe_entry.found_existing { continue 'next_dep; } @@ -2041,7 +2041,7 @@ pub(crate) fn pack( // not repeated. unsafe { (*transpiler_for_deinit).deinit() }; } - ctx.manager.env_mut().map.put(b"npm_command", b"pack")?; + ctx.manager.env_mut().map.put(b"npm_command", b"pack"); let (postpack_script, publish_script, postpublish_script, ran_scripts): ( Option>, @@ -3986,7 +3986,6 @@ pub mod bindings { "{}", bun_fmt::bytes_to_hex_lower_string(&sha1_digest) )); - // bun.handleOom → infallible / panic-on-OOM let mut sha512_digest: [u8; sha::SHA512::DIGEST] = [0; sha::SHA512::DIGEST]; let mut sha512 = sha::SHA512::init(); @@ -4076,7 +4075,6 @@ pub mod bindings { #[cfg(windows)] let pathname_string = { let pathname_w = archive_entry_ref.pathname_w(); - // bun.handleOom — panic on OOM let result = bun_core::handle_oom(strings::to_utf8_list_with_type( Vec::new(), pathname_w, diff --git a/src/runtime/cli/package_manager_command.rs b/src/runtime/cli/package_manager_command.rs index 62b21f210e1b..c63e0a617775 100644 --- a/src/runtime/cli/package_manager_command.rs +++ b/src/runtime/cli/package_manager_command.rs @@ -418,7 +418,7 @@ Learn more about these at https://bun.com/docs/cli/pm.\n"; let mut had_err = false; let mut process_env = bun_dotenv::Loader::init(); - process_env.load_process()?; + process_env.load_process(); let cache_dir = fetch_cache_directory_path(&mut process_env, None); let mut rm_buf = PathBuffer::uninit(); let rm_dir = match Dir::cwd().make_open_path(&cache_dir.path, Default::default()) { @@ -976,7 +976,7 @@ fn print_trusted_dependencies_flat( let pkg_names = slice.items_name(); let pkg_count = lockfile.packages.len(); - let mut seen = bun_core::handle_oom(DynamicBitSet::init_empty(pkg_count)); + let mut seen = DynamicBitSet::init_empty(pkg_count); let mut trusted: Vec = Vec::new(); let mut visit = |dep_id: DependencyID| { diff --git a/src/runtime/cli/pm_licenses_command.rs b/src/runtime/cli/pm_licenses_command.rs index 0079a85383ee..6b2e886b20dd 100644 --- a/src/runtime/cli/pm_licenses_command.rs +++ b/src/runtime/cli/pm_licenses_command.rs @@ -670,7 +670,7 @@ impl DiskIndex { if let (Some(name), Some(version)) = (&info.name, &info.version) { let key = disk_key(name, version); if !out.contains_key(&key[..]) { - let _ = out.put(&key, info); + out.put(&key, info); } } } diff --git a/src/runtime/cli/pm_pkg_command.rs b/src/runtime/cli/pm_pkg_command.rs index 556f5cfd0d0c..8422ac7403cb 100644 --- a/src/runtime/cli/pm_pkg_command.rs +++ b/src/runtime/cli/pm_pkg_command.rs @@ -227,11 +227,11 @@ impl PmPkgCommand { bstr::BStr::new(&value[last_index..]) ) .map_err(|_| crate::Error::WriteFailed)?; - results.put(key, new_value.into_boxed_slice())?; + results.put(key, new_value.into_boxed_slice()); continue; } } - results.put(key, value)?; + results.put(key, value); } Err(e) => { if matches!(e, crate::Error::InvalidPath) { diff --git a/src/runtime/cli/pm_trusted_command.rs b/src/runtime/cli/pm_trusted_command.rs index d03bd50c0d34..565eff1a54ae 100644 --- a/src/runtime/cli/pm_trusted_command.rs +++ b/src/runtime/cli/pm_trusted_command.rs @@ -98,7 +98,7 @@ impl UntrustedCommand { let pkg_name = packages.items_name()[package_id as usize].slice(buf); let resolution = &resolutions[package_id as usize]; if !lockfile.has_trusted_dependency(alias, pkg_name, resolution) { - untrusted_dep_ids.put(dep_id, ())?; + untrusted_dep_ids.put(dep_id, ()); } } @@ -161,7 +161,7 @@ impl UntrustedCommand { if scripts_list.total == 0 || scripts_list.items.is_empty() { continue; } - untrusted_deps.put(dep_id, scripts_list)?; + untrusted_deps.put(dep_id, scripts_list); } } @@ -319,7 +319,7 @@ impl TrustCommand { let pkg_name = packages.items_name()[package_id as usize].slice(buf); let resolution = &resolutions[package_id as usize]; if !lockfile.has_trusted_dependency(alias, pkg_name, resolution) { - untrusted_dep_ids.put(dep_id, ())?; + untrusted_dep_ids.put(dep_id, ()); } } @@ -414,7 +414,7 @@ impl TrustCommand { let total = scripts_list.total as usize; // even if it is skipped we still add to scripts_at_depth for logging later - let entry = scripts_at_depth.get_or_put(node_modules.depth)?; + let entry = scripts_at_depth.get_or_put(node_modules.depth); if !entry.found_existing { *entry.value_ptr = Vec::new(); } @@ -425,7 +425,7 @@ impl TrustCommand { }); if !skip { - package_names_to_add.put(alias, ())?; + package_names_to_add.put(alias, ()); scripts_count += total; } } @@ -627,7 +627,7 @@ impl TrustCommand { bun_semver::string::Builder::string_hash(name) as install::TruncatedPackageNameHash, Box::<[u8]>::from(&**name), - )?; + ); } } diff --git a/src/runtime/cli/publish_command.rs b/src/runtime/cli/publish_command.rs index ac6e1736eb84..3f8dda1f3b8f 100644 --- a/src/runtime/cli/publish_command.rs +++ b/src/runtime/cli/publish_command.rs @@ -698,10 +698,7 @@ impl PublishCommand { let script_env = context .script_env .expect("DIRECTORY_PUBLISH=true sets script_env"); - script_env - .map - .put(b"npm_command", b"publish") - .map_err(|_| crate::Error::Alloc(bun_alloc::AllocError))?; + script_env.map.put(b"npm_command", b"publish"); // Note: reshaped for borrowck — `command_ctx: &mut ContextData` // is held by `context`; `run_package_script_foreground` needs @@ -1277,7 +1274,7 @@ impl PublishCommand { let mut req = http::AsyncHTTP::init_sync( http::Method::GET, done_url.clone(), - auth_headers.entries.clone()?, + auth_headers.entries.clone(), auth_headers.content.written_slice(), b"", None, @@ -1545,7 +1542,7 @@ impl PublishCommand { } }; let _close = scopeguard::guard(workspace_root, |fd| { - let _ = fd.close(); + fd.close(); }); Self::normalize_bin(json, &bump, package_name, workspace_root)?; @@ -1584,7 +1581,7 @@ impl PublishCommand { pub(crate) fn find_workspace_readme(abs_workspace_path: &[u8]) -> Option { let workspace_dir = bun_sys::open_dir_absolute(abs_workspace_path).ok()?; let _close = scopeguard::guard(workspace_dir, |d| { - let _ = d.close(); + d.close(); }); let mut iter = DirIterator::iterate(workspace_dir); @@ -1805,7 +1802,7 @@ impl PublishCommand { let (dir, dir_subpath, close_dir) = dir_info; let _close = scopeguard::guard(dir, move |d| { if close_dir { - let _ = d.close(); + d.close(); } }); diff --git a/src/runtime/cli/run_command.rs b/src/runtime/cli/run_command.rs index 87501ccffec9..d832a80b435c 100644 --- a/src/runtime/cli/run_command.rs +++ b/src/runtime/cli/run_command.rs @@ -271,12 +271,8 @@ Full documentation is available at https://bun.com/docs/cli/run let shell_search_path = shell_path.unwrap_or_else(|| env.get(b"PATH").unwrap_or(b"")); let shell_bin = Self::find_shell(shell_search_path, cwd).ok_or(crate::Error::MissingShell)?; - env.map - .put(b"npm_lifecycle_event", name) - .expect("unreachable"); - env.map - .put(b"npm_lifecycle_script", original_script) - .expect("unreachable"); + env.map.put(b"npm_lifecycle_event", name); + env.map.put(b"npm_lifecycle_script", original_script); let mut copy_script_capacity: usize = original_script.len(); for part in passthrough { @@ -387,7 +383,7 @@ Full documentation is available at https://bun.com/docs/cli/run // TODO: remember to free this when we add --filter or --concurrent // in the meantime we don't need to free it. - let envp = env.map.create_null_delimited_env_map()?; + let envp = env.map.create_null_delimited_env_map(); let spawn_result = match sync::spawn(&sync::Options { argv, @@ -663,7 +659,7 @@ Full documentation is available at https://bun.com/docs/cli/run // does NOT straddle `run_env_loader` below (which itself derives // `env_mut()`, popping any outstanding `&mut Loader` tag). let env_loader = this_transpiler.env_mut(); - env_loader.load_process()?; + env_loader.load_process(); if let Some(node_env) = env_loader.get(b"NODE_ENV") { if node_env == b"production" { @@ -684,51 +680,43 @@ Full documentation is available at https://bun.com/docs/cli/run env_loader .map - .put_default(b"npm_config_local_prefix", top_level_dir) - .expect("unreachable"); + .put_default(b"npm_config_local_prefix", top_level_dir); // Propagate --no-orphans / [run] noOrphans to the script's env so any // Bun process the script spawns enables its own watchdog. The env // loader snapshots `environ` before flag parsing runs, so the // `setenv()` in `enable()` isn't reflected here. if bun_io::ParentDeathWatchdog::is_enabled() { - env_loader - .map - .put(b"BUN_FEATURE_FLAG_NO_ORPHANS", b"1") - .expect("unreachable"); + env_loader.map.put(b"BUN_FEATURE_FLAG_NO_ORPHANS", b"1"); } // we have no way of knowing what version they're expecting without running the node executable // running the node executable is too slow // so we will just hardcode it to LTS - env_loader - .map - .put_default( - b"npm_config_user_agent", - // the use of npm/? is copying yarn - // e.g. - // > "yarn/1.22.4 npm/? node/v12.16.3 darwin x64", - const_format::concatcp!( - "bun/", - Global::package_json_version, - " npm/? node/v", - Environment::REPORTED_NODEJS_VERSION, - " ", - Global::os_name, - " ", - Global::arch_name - ) - .as_bytes(), + env_loader.map.put_default( + b"npm_config_user_agent", + // the use of npm/? is copying yarn + // e.g. + // > "yarn/1.22.4 npm/? node/v12.16.3 darwin x64", + const_format::concatcp!( + "bun/", + Global::package_json_version, + " npm/? node/v", + Environment::REPORTED_NODEJS_VERSION, + " ", + Global::os_name, + " ", + Global::arch_name ) - .expect("unreachable"); + .as_bytes(), + ); if env_loader.get(b"npm_execpath").is_none() { // we don't care if this fails if let Ok(self_exe_path) = bun_core::self_exe_path() { env_loader .map - .put_default(b"npm_execpath", self_exe_path.as_bytes()) - .expect("unreachable"); + .put_default(b"npm_execpath", self_exe_path.as_bytes()); } } @@ -737,27 +725,24 @@ Full documentation is available at https://bun.com/docs/cli/run if env_loader.map.get(NpmArgs::PACKAGE_NAME).is_none() { env_loader .map - .put(NpmArgs::PACKAGE_NAME, &package_json.name) - .expect("unreachable"); + .put(NpmArgs::PACKAGE_NAME, &package_json.name); } } env_loader .map - .put_default(b"npm_package_json", package_json.source.path.text) - .expect("unreachable"); + .put_default(b"npm_package_json", package_json.source.path.text); if !package_json.version.is_empty() { if env_loader.map.get(NpmArgs::PACKAGE_VERSION).is_none() { env_loader .map - .put(NpmArgs::PACKAGE_VERSION, &package_json.version) - .expect("unreachable"); + .put(NpmArgs::PACKAGE_VERSION, &package_json.version); } } if let Some(config) = package_json.config.as_deref() { - env_loader.map.ensure_unused_capacity(config.count())?; + env_loader.map.ensure_unused_capacity(config.count()); for (k, v) in config.keys().iter().zip(config.values().iter()) { let key = strings::concat(&[b"npm_package_config_", &k[..]]); env_loader.map.put_assume_capacity(&key, *v); @@ -822,9 +807,9 @@ Full documentation is available at https://bun.com/docs/cli/run let mut inner = bun_resolver::package_json::MacroImportReplacementMap::default(); for (ik, iv) in v.iter() { - inner.put(ik, iv.clone()).unwrap_or_oom(); + inner.put(ik, iv.clone()); } - b.options.macro_remap.put(k, inner).unwrap_or_oom(); + b.options.macro_remap.put(k, inner); } } MacroOptions::Unspecified => {} @@ -1828,11 +1813,7 @@ impl RunCommand { cwd, force_using_bun, )?; - this_transpiler - .env_mut() - .map - .put(b"PATH", &new_path) - .unwrap_or_oom(); + this_transpiler.env_mut().map.put(b"PATH", &new_path); Ok(()) } @@ -1863,16 +1844,14 @@ impl RunCommand { let bun_node_exe = Self::bun_node_file_utf8()?; let bun_node_dir_win = bun_paths::dirname(bun_node_exe.as_bytes()).ok_or(crate::Error::FailedToGetTempPath)?; - let found_node = env_loader - .load_node_js_config( - bun_paths::fs::FileSystem::instance(), - if force_using_bun { - bun_node_exe.as_bytes() - } else { - b"" - }, - ) - .unwrap_or(false); + let found_node = env_loader.load_node_js_config( + bun_paths::fs::FileSystem::instance(), + if force_using_bun { + bun_node_exe.as_bytes() + } else { + b"" + }, + ); let mut needs_to_force_bun = force_using_bun || !found_node; let mut optional_bun_self_path: &[u8] = b""; @@ -1918,18 +1897,11 @@ impl RunCommand { if !force_using_bun { let env_mut = this_transpiler.env_mut(); + env_mut.map.put(b"NODE", bun_node_exe.as_bytes()); env_mut .map - .put(b"NODE", bun_node_exe.as_bytes()) - .unwrap_or_oom(); - env_mut - .map - .put(b"npm_node_execpath", bun_node_exe.as_bytes()) - .unwrap_or_oom(); - env_mut - .map - .put(b"npm_execpath", optional_bun_self_path) - .unwrap_or_oom(); + .put(b"npm_node_execpath", bun_node_exe.as_bytes()); + env_mut.map.put(b"npm_execpath", optional_bun_self_path); } needs_to_force_bun = false; @@ -2062,7 +2034,7 @@ impl RunCommand { // TODO: remember to free this when we add --filter or --concurrent // in the meantime we don't need to free it. - let envp = env.map.create_null_delimited_env_map()?; + let envp = env.map.create_null_delimited_env_map(); let spawn_result = match sync::spawn(&sync::Options { argv, @@ -2340,10 +2312,7 @@ impl RunCommand { force_using_bun, )?; let env_loader: &mut DotEnv::Loader = this_transpiler.env_mut(); - env_loader - .map - .put(b"npm_command", b"run-script") - .expect("unreachable"); + env_loader.map.put(b"npm_command", b"run-script"); let root_dir = root_dir_info; @@ -2378,10 +2347,7 @@ impl RunCommand { long_running: false, ..Default::default() }); - env_loader - .map - .put(b"npm_lifecycle_event", target_name) - .expect("unreachable"); + env_loader.map.put(b"npm_lifecycle_event", target_name); // allocate enough to hold "post${scriptname}" // byte 0 is a placeholder so the "pre" slice @@ -3125,9 +3091,7 @@ impl RunCommand { if !u.starts_with(b"http://") && !u.starts_with(b"https://") { continue; } - let Ok(gop) = seen.get_or_put(u) else { - continue; - }; + let gop = seen.get_or_put(u); if gop.found_existing { continue; } @@ -3498,7 +3462,7 @@ impl RunCommand { }; { - this_transpiler.env_mut().load_process()?; + this_transpiler.env_mut().load_process(); if let Some(node_env) = this_transpiler.env().get(b"NODE_ENV") { if node_env == b"production" { @@ -3518,7 +3482,7 @@ impl RunCommand { if FILTER != Filter::ScriptExclude { if let Some(defaults) = default_completions { - results.ensure_unused_capacity(defaults.len())?; + results.ensure_unused_capacity(defaults.len()); for item in defaults { let _ = results.get_or_put(Box::from(*item)); } @@ -3586,7 +3550,7 @@ impl RunCommand { else { continue; }; - let _ = results.get_or_put(Box::from(appended))?; + let _ = results.get_or_put(Box::from(appended)); } } } @@ -3636,7 +3600,7 @@ impl RunCommand { else { continue; }; - let _ = results.get_or_put(Box::from(appended))?; + let _ = results.get_or_put(Box::from(appended)); } } } @@ -3651,7 +3615,7 @@ impl RunCommand { { if let Some(package_json) = root_dir_info.enclosing_package_json { if let Some(scripts) = package_json.scripts.as_deref() { - results.ensure_unused_capacity(scripts.count())?; + results.ensure_unused_capacity(scripts.count()); if FILTER == Filter::ScriptAndDescriptions { descriptions.reserve(scripts.count()); } diff --git a/src/runtime/cli/test/ChangedFilesFilter.rs b/src/runtime/cli/test/ChangedFilesFilter.rs index a2b1be85e98e..5007a317b43a 100644 --- a/src/runtime/cli/test/ChangedFilesFilter.rs +++ b/src/runtime/cli/test/ChangedFilesFilter.rs @@ -253,7 +253,7 @@ pub(crate) fn filter<'a>( } // BFS backward from every changed file that participates in the graph. - let mut affected = bun_core::handle_oom(DynamicBitSet::init_empty(sources.len())); + let mut affected = DynamicBitSet::init_empty(sources.len()); let mut queue: Vec = Vec::new(); { diff --git a/src/runtime/cli/test/Timings.rs b/src/runtime/cli/test/Timings.rs index 5ddb0dff3e56..a6bd8d712799 100644 --- a/src/runtime/cli/test/Timings.rs +++ b/src/runtime/cli/test/Timings.rs @@ -96,7 +96,7 @@ impl Timings { && ms.is_finite() && ms >= 0.0 { - let _ = map.put(key, ms.round().min(u32::MAX as f64) as u32); + map.put(key, ms.round().min(u32::MAX as f64) as u32); } }); bun_ast::Expr::data_store_reset(); @@ -123,8 +123,8 @@ impl Timings { pub fn record(&mut self, abs_path: &[u8], ms: u32) { let key = Self::key_for(abs_path); - let _ = self.map.put(&key, ms); - let _ = self.measured.put(&key, ms); + self.map.put(&key, ms); + self.measured.put(&key, ms); } pub fn record_since(&mut self, abs_path: &[u8], started_ms: i64) { diff --git a/src/runtime/cli/test/parallel/aggregate.rs b/src/runtime/cli/test/parallel/aggregate.rs index c29f11d380e1..6dc1dd7727ad 100644 --- a/src/runtime/cli/test/parallel/aggregate.rs +++ b/src/runtime/cli/test/parallel/aggregate.rs @@ -151,7 +151,7 @@ pub(crate) fn merge_coverage_fragments( let line = strings::trim_right(raw, b"\r"); if line.starts_with(b"SF:") { let name = &line[3..]; - let gop = bun_core::handle_oom(by_file.get_or_put(name)); + let gop = by_file.get_or_put(name); if !gop.found_existing { let owned: Box<[u8]> = Box::from(name); gop.key_ptr.clone_from(&owned); @@ -175,7 +175,7 @@ pub(crate) fn merge_coverage_fragments( let Ok(cnt) = strings::parse_int::(cnt_s, 10) else { continue; }; - let gop = bun_core::handle_oom(fc.da.get_or_put(ln)); + let gop = fc.da.get_or_put(ln); *gop.value_ptr = if gop.found_existing { gop.value_ptr.saturating_add(cnt) } else { diff --git a/src/runtime/cli/test/parallel/runner.rs b/src/runtime/cli/test/parallel/runner.rs index e6b14c5b2100..83ae372ca687 100644 --- a/src/runtime/cli/test/parallel/runner.rs +++ b/src/runtime/cli/test/parallel/runner.rs @@ -51,8 +51,8 @@ pub(crate) fn run_as_coordinator( if k <= 1 { // Jest sets JEST_WORKER_ID=1 even with --maxWorkers=1; match that so // tests can rely on the var whenever --parallel is passed. - let _ = env.map.put(b"JEST_WORKER_ID", b"1"); - let _ = env.map.put(b"BUN_TEST_WORKER_ID", b"1"); + env.map.put(b"JEST_WORKER_ID", b"1"); + env.map.put(b"BUN_TEST_WORKER_ID", b"1"); // SAFETY: see vm_ptr note above. TestCommand::run_all_tests(reporter, unsafe { &mut *vm_ptr }, files); return Ok(false); @@ -61,13 +61,13 @@ pub(crate) fn run_as_coordinator( // Workers' stderr is a pipe; have them format with ANSI when we will be // rendering to a color terminal so streamed lines match serial output. if Output::enable_ansi_colors_stderr() { - let _ = env.map.put(b"FORCE_COLOR", b"1"); + env.map.put(b"FORCE_COLOR", b"1"); } if ctx.test_options.reporters.junit { // Coordinator's own JunitReporter would otherwise produce an empty // document and overwrite the merged one in writeJUnitReportIfNeeded. if let Some(jr) = reporter.reporters.junit.take() { - let _ = env.map.put(b"BUN_TEST_WORKER_JUNIT", b"1"); + env.map.put(b"BUN_TEST_WORKER_JUNIT", b"1"); drop(jr); } } @@ -80,9 +80,9 @@ pub(crate) fn run_as_coordinator( for i in 0..k { let mut id = Vec::new(); write!(&mut id, "{}", i + 1).unwrap(); - let _ = env.map.put(b"JEST_WORKER_ID", &id); - let _ = env.map.put(b"BUN_TEST_WORKER_ID", &id); - envps.push(env.map.create_null_delimited_env_map()?); + env.map.put(b"JEST_WORKER_ID", &id); + env.map.put(b"BUN_TEST_WORKER_ID", &id); + envps.push(env.map.create_null_delimited_env_map()); } let argv = build_worker_argv(ctx)?; diff --git a/src/runtime/cli/test_command.rs b/src/runtime/cli/test_command.rs index 577d075d380d..0d32f374fa27 100644 --- a/src/runtime/cli/test_command.rs +++ b/src/runtime/cli/test_command.rs @@ -2299,7 +2299,7 @@ impl TestCommand { vm.transpiler.options.env.behavior = bun_bundler::options::EnvBehavior::LoadAllWithoutInlining; - let node_env_entry = env_loader.map.get_or_put_without_value(b"NODE_ENV")?; + let node_env_entry = env_loader.map.get_or_put_without_value(b"NODE_ENV"); if !node_env_entry.found_existing { *node_env_entry.key_ptr = Box::<[u8]>::from(&**node_env_entry.key_ptr); *node_env_entry.value_ptr = DotEnv::HashTableValue { diff --git a/src/runtime/cli/update_interactive_command.rs b/src/runtime/cli/update_interactive_command.rs index fca6aaa3b626..66d4fa6e4b1f 100644 --- a/src/runtime/cli/update_interactive_command.rs +++ b/src/runtime/cli/update_interactive_command.rs @@ -313,9 +313,7 @@ impl UpdateInteractiveCommand { // Group updates by workspace path (store indices to avoid cloning) for (i, update) in updates.iter().enumerate() { - let result = workspace_groups - .get_or_put(&update.workspace_path) - .map_err(|_| crate::Error::Alloc(bun_alloc::AllocError))?; + let result = workspace_groups.get_or_put(&update.workspace_path); if !result.found_existing { *result.value_ptr = Vec::new(); } @@ -431,9 +429,7 @@ impl UpdateInteractiveCommand { // Group updates by workspace let mut catalog_it = catalog_updates.iter(); while let Some((catalog_key, update)) = catalog_it.next() { - let result = workspace_catalog_updates - .get_or_put(&update.workspace_path) - .map_err(|_| crate::Error::Alloc(bun_alloc::AllocError))?; + let result = workspace_catalog_updates.get_or_put(&update.workspace_path); if !result.found_existing { *result.value_ptr = Vec::new(); } @@ -761,9 +757,7 @@ impl UpdateInteractiveCommand { // Group catalog dependencies for pkg in packages { if pkg.is_catalog { - let entry = catalog_map - .get_or_put(&pkg.name) - .map_err(|_| crate::Error::Alloc(bun_alloc::AllocError))?; + let entry = catalog_map.get_or_put(&pkg.name); if !entry.found_existing { *entry.value_ptr = Vec::new(); } diff --git a/src/runtime/cli/upgrade_command.rs b/src/runtime/cli/upgrade_command.rs index fcd16bf1b0bf..50beb2a072ab 100644 --- a/src/runtime/cli/upgrade_command.rs +++ b/src/runtime/cli/upgrade_command.rs @@ -196,7 +196,7 @@ impl UpgradeCommand { length: u32::try_from(b"application/vnd.github.v3+json".len()).expect("int cast"), }, }; - header_entries.append(accept).expect("oom"); + header_entries.append(accept); // defer if SILENT header_entries.deinit() — Drop handles this // Incase they're using a GitHub proxy in e.g. China @@ -232,23 +232,21 @@ impl UpgradeCommand { bstr::BStr::new(access_token), ) .expect("oom"); - header_entries - .append(headers::Entry { - name: HTTP::ETag::StringPointer { - offset: accept.value.offset + accept.value.length, - length: u32::try_from(b"Authorization".len()).expect("int cast"), - }, - value: HTTP::ETag::StringPointer { - offset: u32::try_from( - (accept.value.offset + accept.value.length) as usize - + b"Authorization".len(), - ) - .unwrap(), - length: u32::try_from(b"Bearer ".len() + access_token.len()) - .expect("int cast"), - }, - }) - .expect("oom"); + header_entries.append(headers::Entry { + name: HTTP::ETag::StringPointer { + offset: accept.value.offset + accept.value.length, + length: u32::try_from(b"Authorization".len()).expect("int cast"), + }, + value: HTTP::ETag::StringPointer { + offset: u32::try_from( + (accept.value.offset + accept.value.length) as usize + + b"Authorization".len(), + ) + .unwrap(), + length: u32::try_from(b"Bearer ".len() + access_token.len()) + .expect("int cast"), + }, + }); } } @@ -541,7 +539,7 @@ impl UpgradeCommand { // SAFETY: FileSystem::init returns the process-global singleton; valid for 'static. let filesystem = unsafe { &mut *fs::FileSystem::init(None)? }; let mut env_loader = DotEnv::Loader::init(); - env_loader.load_process()?; + env_loader.load_process(); let use_canary: bool = 'brk: { let default_use_canary = Environment::IS_CANARY; @@ -1320,23 +1318,22 @@ impl UpgradeCommand { { let completions_argv: [&[u8]; 2] = [target_filename.as_bytes(), b"completions"]; - let _ = env_loader.map.put(b"IS_BUN_AUTO_UPDATE", b"true"); + env_loader.map.put(b"IS_BUN_AUTO_UPDATE", b"true"); // `spawn_sync` takes the C-style `[*:null]?[*:0]const u8` envp // directly, so build it from the DotEnv map. Output is buffered and // silently dropped along with any spawn error. - if let Ok(envp) = env_loader.map.create_null_delimited_env_map() { - let _ = spawn_sync::spawn(&spawn_sync::Options { - argv: build_argv(&completions_argv), - envp: Some(envp.as_ptr().cast::<*const c_char>()), - cwd: Box::<[u8]>::from(target_dirname.as_bytes()), - stdout: spawn_sync::SyncStdio::Buffer, - stderr: spawn_sync::SyncStdio::Buffer, - stdin: spawn_sync::SyncStdio::Ignore, - #[cfg(windows)] - windows: spawn_windows_options(), - ..Default::default() - }); - } + let envp = env_loader.map.create_null_delimited_env_map(); + let _ = spawn_sync::spawn(&spawn_sync::Options { + argv: build_argv(&completions_argv), + envp: Some(envp.as_ptr().cast::<*const c_char>()), + cwd: Box::<[u8]>::from(target_dirname.as_bytes()), + stdout: spawn_sync::SyncStdio::Buffer, + stderr: spawn_sync::SyncStdio::Buffer, + stdin: spawn_sync::SyncStdio::Ignore, + #[cfg(windows)] + windows: spawn_windows_options(), + ..Default::default() + }); } Output::print_start_end(ctx.start_time, bun_core::time::nano_timestamp()); diff --git a/src/runtime/crypto/CryptoHasher.rs b/src/runtime/crypto/CryptoHasher.rs index eef63fc555bb..431c6cc5a44e 100644 --- a/src/runtime/crypto/CryptoHasher.rs +++ b/src/runtime/crypto/CryptoHasher.rs @@ -654,11 +654,7 @@ impl CryptoHasher { pub(crate) fn copy(this: &Self, global: &JSGlobalObject, _: &CallFrame) -> JsResult { let copied: CryptoHasher = match this { CryptoHasher::Evp(inner) => CryptoHasher::Evp(Box::new(JsCell::new( - inner - .get() - .copy(boring_engine(global)) - // bun.handleOom → unwrap (abort on OOM) - .expect("OOM"), + inner.get().copy(boring_engine(global)).expect("OOM"), ))), CryptoHasher::Hmac(inner) => 'brk: { // R-2: `HMAC::copy` takes `&mut self` but writes nothing diff --git a/src/runtime/crypto/PasswordObject.rs b/src/runtime/crypto/PasswordObject.rs index f225555fc764..d0d67307e76d 100644 --- a/src/runtime/crypto/PasswordObject.rs +++ b/src/runtime/crypto/PasswordObject.rs @@ -538,7 +538,7 @@ fn password_error_instance(err: &HashError, verb: &str, g: &JSGlobalObject) -> J input: err.name().as_bytes() } ) - .expect("unreachable"); // bun.handleOom + .expect("formatting into a Vec is infallible"); let instance = g.create_error_instance(format_args!( "Password {verb} failed with error \"{}\"", err.name() diff --git a/src/runtime/dns_jsc/dns.rs b/src/runtime/dns_jsc/dns.rs index 6a5f656dee1c..b98dcce18b57 100644 --- a/src/runtime/dns_jsc/dns.rs +++ b/src/runtime/dns_jsc/dns.rs @@ -4847,7 +4847,7 @@ impl Resolver { // any re-entrant call (libuv `uv_poll_*` below do not call back into // this resolver synchronously). let polls = unsafe { self.polls.get_mut() }; - let poll_entry = bun_core::handle_oom(polls.get_or_put(fd)); + let poll_entry = polls.get_or_put(fd); let poll: *mut UvDnsPoll = if poll_entry.found_existing { *poll_entry.value_ptr } else { @@ -4911,7 +4911,7 @@ impl Resolver { // SAFETY: single-JS-thread; the `&mut PollsMap` borrow does not span // any re-entrant call (`FilePoll::register` is a syscall wrapper). let polls = unsafe { self.polls.get_mut() }; - let poll_entry = polls.get_or_put(fd).expect("unreachable"); + let poll_entry = polls.get_or_put(fd); if !poll_entry.found_existing { *poll_entry.value_ptr = diff --git a/src/runtime/ipc.rs b/src/runtime/ipc.rs index 51335632a720..ee421ced971e 100644 --- a/src/runtime/ipc.rs +++ b/src/runtime/ipc.rs @@ -2394,7 +2394,7 @@ fn on_data2(send_queue: &SendQueue, all_data: &[u8]) { let IncomingBuffer::Advanced(adv_buf) = inc else { unreachable!() }; - handle_oom(adv_buf.write(data)); + adv_buf.write(data); }); log!("hit NotEnoughBytes"); return; @@ -2409,7 +2409,7 @@ fn on_data2(send_queue: &SendQueue, all_data: &[u8]) { let IncomingBuffer::Advanced(adv_buf) = inc else { unreachable!() }; - handle_oom(adv_buf.write(data)); + adv_buf.write(data); }); let mut slice_start: usize = 0; loop { diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index edb355d3b465..a430c34da9f0 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -210,7 +210,7 @@ impl ActiveHandle { /// This owner now holds something the stop phase must stop (JS thread). pub(crate) fn register(self) { if let Some(handles) = active_handles() { - bun_core::handle_oom(handles.put(self, ())); + handles.put(self, ()); } } @@ -791,7 +791,7 @@ unsafe fn load_preloads(vm: *mut VirtualMachine) -> bun_jsc::CrateResult<*mut JS // `VirtualMachine::init`. if let Some(log) = unsafe { &*vm }.log { // SAFETY: `log` is the unique per-VM `Box`. - let _ = unsafe { &mut *log.as_ptr() }.add_error_fmt( + unsafe { &mut *log.as_ptr() }.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -807,7 +807,7 @@ unsafe fn load_preloads(vm: *mut VirtualMachine) -> bun_jsc::CrateResult<*mut JS // SAFETY: see above. if let Some(log) = unsafe { &*vm }.log { // SAFETY: `log` is the unique per-VM `Box`. - let _ = unsafe { &mut *log.as_ptr() }.add_error_fmt( + unsafe { &mut *log.as_ptr() }.add_error_fmt( None, bun_ast::Loc::EMPTY, format_args!( @@ -2534,7 +2534,7 @@ fn transpile_source_code_inner( } else { let mut m = bun_resolver::package_json::MacroMap::default(); for (k, v) in src.iter() { - m.insert(k, bun_core::handle_oom(v.clone())); + m.insert(k, v.clone()); } m } @@ -3011,7 +3011,7 @@ fn transpile_source_code_inner( // stacks remap to original positions even on a cache hit. // SAFETY: per fn contract — `jsc_vm` is the live per-thread // VM; `source_mappings` is only touched from the JS thread. - let _ = unsafe { &mut (*jsc_vm).source_mappings }.put_mappings( + unsafe { &mut (*jsc_vm).source_mappings }.put_mappings( source, bun_core::MutableString { list: core::mem::take(&mut entry.sourcemap).into_vec(), diff --git a/src/runtime/node/node_cluster_binding.rs b/src/runtime/node/node_cluster_binding.rs index c9c22e06194f..71d32b8dcb00 100644 --- a/src/runtime/node/node_cluster_binding.rs +++ b/src/runtime/node/node_cluster_binding.rs @@ -140,8 +140,7 @@ pub(crate) fn send_helper_primary(global: &JSGlobalObject, frame: &CallFrame) -> let this_seq = ipc_data.internal_msg_queue.with_mut(|q| { let seq = q.seq; if callback.is_function() { - let _ = q - .callbacks + q.callbacks .put(seq, StrongOptional::create(callback, global)); } q.seq = seq.wrapping_add(1); diff --git a/src/runtime/node/node_crypto_binding.rs b/src/runtime/node/node_crypto_binding.rs index 60980d9cd2e5..3e5061c07417 100644 --- a/src/runtime/node/node_crypto_binding.rs +++ b/src/runtime/node/node_crypto_binding.rs @@ -1221,7 +1221,7 @@ mod _impl { // SAFETY: `maybe_from` is non-null (checked above) and points to a NUL-terminated C string // from BoringSSL's static tables. let from_bytes = unsafe { bun_core::ffi::cstr(maybe_from) }.to_bytes(); - bun_core::handle_oom(hashes.put(from_bytes, ())); + hashes.put(from_bytes, ()); } #[bun_jsc::host_fn] diff --git a/src/runtime/node/node_fs_stat_watcher.rs b/src/runtime/node/node_fs_stat_watcher.rs index 651d661d57f9..e4d2d20eb116 100644 --- a/src/runtime/node/node_fs_stat_watcher.rs +++ b/src/runtime/node/node_fs_stat_watcher.rs @@ -1047,12 +1047,12 @@ impl StatWatcher { js::listener_set_cached(js_this, &args.global_this, args.listener); // `ctx` is a `BackRef` (JSC_BORROW); safe Deref. if let Some(handles) = crate::jsc_hooks::active_handles() { - bun_core::handle_oom(handles.put( + handles.put( crate::jsc_hooks::ActiveHandle::StatWatcher( NonNull::new(this_ptr).expect("init: watcher"), ), (), - )); + ); } // SAFETY: `this_ptr` was just leaked from `Box`; live with refcount 1. InitialStatTask::create_and_schedule(this_ptr); diff --git a/src/runtime/node/node_fs_watcher.rs b/src/runtime/node/node_fs_watcher.rs index b581a1c3ddf7..11a360d2fc60 100644 --- a/src/runtime/node/node_fs_watcher.rs +++ b/src/runtime/node/node_fs_watcher.rs @@ -1247,12 +1247,12 @@ impl FSWatcher { ) }; if let Some(handles) = crate::jsc_hooks::active_handles() { - bun_core::handle_oom(handles.put( + handles.put( crate::jsc_hooks::ActiveHandle::FsWatcher( core::ptr::NonNull::new(ctx).expect("init: watcher"), ), (), - )); + ); } Ok(ctx) } diff --git a/src/runtime/node/node_process.rs b/src/runtime/node/node_process.rs index d021b241ea51..d511ee2e0260 100644 --- a/src/runtime/node/node_process.rs +++ b/src/runtime/node/node_process.rs @@ -351,10 +351,10 @@ mod _impl { let mut k = Vec::with_capacity(2 + name.len()); k.extend_from_slice(b"--"); k.extend_from_slice(name); - bun_core::handle_oom(set.insert(&k)); + set.insert(&k); } if let Some(name) = param.names.short { - bun_core::handle_oom(set.insert(&[b'-', name])); + set.insert(&[b'-', name]); } } } @@ -362,7 +362,7 @@ mod _impl { // land above; an alias takes a value iff its target does. for (from, to) in crate::cli::arguments::NODE_SHORT_ALIASES { if set.contains(to) { - bun_core::handle_oom(set.insert(from)); + set.insert(from); } } set diff --git a/src/runtime/node/node_util_binding.rs b/src/runtime/node/node_util_binding.rs index 335d1741b88c..841239b054e9 100644 --- a/src/runtime/node/node_util_binding.rs +++ b/src/runtime/node/node_util_binding.rs @@ -240,7 +240,7 @@ pub(crate) fn parse_env(global: &JSGlobalObject, frame: &CallFrame) -> JsResult< let str = content.to_js_string(global)?.to_slice(global); let mut p = envloader::Loader::init(); - p.load_from_string::(str.slice())?; + p.load_from_string::(str.slice()); let obj = JSValue::create_empty_object(global, p.map.map.count()); for (k, v) in p.map.map.iter() { diff --git a/src/runtime/node/path_watcher.rs b/src/runtime/node/path_watcher.rs index 715150032bac..1eaef1379201 100644 --- a/src/runtime/node/path_watcher.rs +++ b/src/runtime/node/path_watcher.rs @@ -34,11 +34,11 @@ use bun_collections::HashMap; use bun_collections::{ArrayHashMap, StringArrayHashMap}; #[cfg(not(windows))] use bun_core::ZBox; +use bun_core::ZStr; #[cfg(any(target_os = "linux", target_os = "android"))] use bun_core::strings; #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] use bun_core::{Output, zstr}; -use bun_core::{ZStr, handle_oom}; use bun_paths as path; #[cfg(any(target_os = "linux", target_os = "android"))] use bun_paths::PathBuffer; @@ -482,7 +482,7 @@ pub(crate) fn watch( // scoped to this lookup. if let Some(&existing) = unsafe { (*manager.watchers.get()).get(key) } { // SAFETY: existing is a live PathWatcher under manager.mutex. - unsafe { handle_oom((*existing).handlers.put(ctx, ChangeEvent::default())) }; + unsafe { (*existing).handlers.put(ctx, ChangeEvent::default()) }; manager.mutex.unlock(); return Ok(existing); } @@ -503,9 +503,9 @@ pub(crate) fn watch( platform: PlatformWatch::default(), }); // SAFETY: watcher just allocated; we hold the only reference. - unsafe { handle_oom((*watcher).handlers.put(ctx, ChangeEvent::default())) }; + unsafe { (*watcher).handlers.put(ctx, ChangeEvent::default()) }; // SAFETY: holding manager.mutex; exclusive access to manager.watchers. - unsafe { handle_oom((*manager.watchers.get()).put(key, watcher)) }; + unsafe { (*manager.watchers.get()).put(key, watcher) }; // Linux/FreeBSD: `addWatch` mutates the platform dispatch maps (wd_map/entries) // which live under `manager.mutex`, so call it while still locked. @@ -952,7 +952,7 @@ impl Linux { for &w in watchers.values() { // SAFETY: w live under manager.mutex. unsafe { (*w).emit_overflow() }; - let _ = handle_oom(touched.get_or_put(w)); + let _ = touched.get_or_put(w); } continue; } @@ -977,7 +977,7 @@ impl Linux { path::basename(w.path.as_bytes()), w.is_file, ); - let _ = handle_oom(touched.get_or_put(o.watcher)); + let _ = touched.get_or_put(o.watcher); } // SAFETY: exclusive scoped access to this watcher's wd // list under manager.mutex; the shared borrow above is @@ -1099,7 +1099,7 @@ impl Linux { && !watcher_is_file), ); } - let _ = handle_oom(touched.get_or_put(owner_watcher)); + let _ = touched.get_or_put(owner_watcher); // Recursive: a new directory appeared under this owner's tree — // start watching it so future events inside it are delivered. @@ -1507,7 +1507,7 @@ impl Kqueue { // SAFETY: caller holds manager.mutex; exclusive access to `entries`. unsafe { - handle_oom((*plat).entries.put( + (*plat).entries.put( fd.native() as i32, KqEntry { watcher: core::ptr::from_mut(watcher), @@ -1516,7 +1516,7 @@ impl Kqueue { generation, is_file, }, - )); + ); } watcher.platform.fds.push(fd.native() as i32); Ok(()) @@ -1604,7 +1604,7 @@ impl Kqueue { }; watcher.emit(event_type, rel, entry.is_file); - let _ = handle_oom(touched.get_or_put(entry.watcher)); + let _ = touched.get_or_put(entry.watcher); } for &w in touched.keys() { diff --git a/src/runtime/server/HTMLBundle.rs b/src/runtime/server/HTMLBundle.rs index 73e22881373d..ed0490b299dd 100644 --- a/src/runtime/server/HTMLBundle.rs +++ b/src/runtime/server/HTMLBundle.rs @@ -441,7 +441,7 @@ impl Route { let mut config = JSBundlerConfig::default(); // `Config` owns its fields and // drops on early-return. - config.entry_points.insert(&self.bundle.path)?; + config.entry_points.insert(&self.bundle.path); let xform = &vm.transpiler.options.transform_options; if let Some(public_path) = xform.serve_public_path.as_deref() { if !public_path.is_empty() { @@ -496,25 +496,25 @@ impl Route { } else { (b"false", b"true", b"\"production\"") }; - config.define.put(b"import.meta.env.DEV", dev_bool)?; - config.define.put(b"import.meta.env.PROD", prod_bool)?; - config.define.put(b"import.meta.env.MODE", mode_str)?; - config.define.put(b"import.meta.env.SSR", b"false")?; - config.define.put(b"import.meta.env.STATIC", b"false")?; + config.define.put(b"import.meta.env.DEV", dev_bool); + config.define.put(b"import.meta.env.PROD", prod_bool); + config.define.put(b"import.meta.env.MODE", mode_str); + config.define.put(b"import.meta.env.SSR", b"false"); + config.define.put(b"import.meta.env.STATIC", b"false"); if let Some(define) = &cli.args.serve_define { debug_assert_eq!(define.keys.len(), define.values.len()); // `StringMap` exposes only put/insert (no bulk re-index); // profile if hot. for (k, v) in define.keys.iter().zip(define.values.iter()) { - config.define.put(k, v)?; + config.define.put(k, v); } } if !is_development { config .define - .put(b"process.env.NODE_ENV", b"\"production\"")?; + .put(b"process.env.NODE_ENV", b"\"production\""); config.jsx.development = false; } else { config.force_node_env = bundler_options::ForceNodeEnv::Development; diff --git a/src/runtime/server/ServerConfig.rs b/src/runtime/server/ServerConfig.rs index 076e9cb003b8..ae40a66aee0c 100644 --- a/src/runtime/server/ServerConfig.rs +++ b/src/runtime/server/ServerConfig.rs @@ -647,7 +647,7 @@ fn validate_route_name(global: &JSGlobalObject, path: &[u8]) -> JsResult<()> { )); } - let entry = bun_core::handle_oom(duped_route_names.get_or_put(route_name)); + let entry = duped_route_names.get_or_put(route_name); if entry.found_existing { return Err(global.throw_todo( b"Support for duplicate route parameter names is not yet implemented.\n\n\ diff --git a/src/runtime/shell/EnvMap.rs b/src/runtime/shell/EnvMap.rs index 7ac7347397f2..49be12d8c3e3 100644 --- a/src/runtime/shell/EnvMap.rs +++ b/src/runtime/shell/EnvMap.rs @@ -74,7 +74,7 @@ impl EnvMap { /// NOTE: This will `.ref()` value, so you should `defer value.deref()` it /// before handing it to this function!!! pub(crate) fn insert(&mut self, key: EnvStr, val: EnvStr) { - let result = self.map.get_or_put(key).expect("OOM"); + let result = self.map.get_or_put(key); if !result.found_existing { key.ref_(); } else { @@ -93,7 +93,7 @@ impl EnvMap { } pub(crate) fn ensure_total_capacity(&mut self, new_capacity: usize) { - self.map.ensure_total_capacity(new_capacity).expect("OOM"); + self.map.ensure_total_capacity(new_capacity); } /// NOTE: Make sure you deref the string when done! @@ -105,7 +105,7 @@ impl EnvMap { pub(crate) fn clone(&self) -> EnvMap { let new = EnvMap { - map: self.map.clone().expect("OOM"), + map: self.map.clone(), }; new.ref_strings(); new diff --git a/src/runtime/shell/IOWriter.rs b/src/runtime/shell/IOWriter.rs index 4f8d012cab07..f8b92645ad4c 100644 --- a/src/runtime/shell/IOWriter.rs +++ b/src/runtime/shell/IOWriter.rs @@ -137,7 +137,7 @@ impl Writer { fn tee(&self, chunk: &[u8]) { if let Some(bl) = self.bytelist { // SAFETY: see doc comment. - let _ = unsafe { (*bl).append_slice(chunk) }; + unsafe { (*bl).append_slice(chunk) }; } } } diff --git a/src/runtime/shell/RefCountedStr.rs b/src/runtime/shell/RefCountedStr.rs index b6a67c6fb1da..a026e85157e9 100644 --- a/src/runtime/shell/RefCountedStr.rs +++ b/src/runtime/shell/RefCountedStr.rs @@ -12,7 +12,6 @@ impl RefCountedStr { // Takes ownership of `slice` (global mimalloc) and stores it directly. pub(crate) fn init(slice: Box<[u8]>) -> *mut RefCountedStr { bun_core::scoped_log!(RefCountedEnvStr, "init: {}", bstr::BStr::new(&*slice)); - // bun.handleOom(bun.default_allocator.create(...)) → Box::new (aborts on OOM) bun_core::heap::into_raw(Box::new(RefCountedStr { refcount: Cell::new(1), data: slice, diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index 8a7a39d19a51..f314f9860a6d 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -293,10 +293,10 @@ impl Cp { // Record successful absolute paths so a deferred EBUSY // sibling can be suppressed. if let Some(tgt) = task.tgt_absolute.take() { - bun_core::handle_oom(exec.ebusy.absolute_targets.insert(&tgt)); + exec.ebusy.absolute_targets.insert(&tgt); } if let Some(src) = task.src_absolute.take() { - bun_core::handle_oom(exec.ebusy.absolute_srcs.insert(&src)); + exec.ebusy.absolute_srcs.insert(&src); } } } diff --git a/src/runtime/shell/subproc.rs b/src/runtime/shell/subproc.rs index 2a934c93e0b5..696870d08d8b 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -641,7 +641,7 @@ impl ShellSubprocess { // pointers pushed into `env_array` borrow `inherited_env_storage.storage`). let inherited_env_storage: Option = if !spawn_args.override_env && spawn_args.env_array.is_empty() { - let envmap = bun_core::handle_oom(event_loop.create_null_delimited_env_map()); + let envmap = event_loop.create_null_delimited_env_map(); // Note: `as_slice()` *includes* the trailing null; strip it — // the common tail below re-appends one null terminator. let entries = envmap.as_slice(); @@ -1585,7 +1585,7 @@ impl BufferedOutput { pub(crate) fn append(&mut self, bytes: &[u8]) { match self { BufferedOutput::Bytelist(b) => { - let _ = b.append_slice(bytes); // OOM/capacity: fire-and-forget + b.append_slice(bytes); } BufferedOutput::ArrayBuffer { buf, i } => { let array_buf_slice = buf.slice_mut(); diff --git a/src/runtime/socket/Listener.rs b/src/runtime/socket/Listener.rs index d36d771db941..7498b9ffc0a4 100644 --- a/src/runtime/socket/Listener.rs +++ b/src/runtime/socket/Listener.rs @@ -321,10 +321,10 @@ impl Listener { .with_mut(|r| r.set_strong(this_value, global)); this_ref.poll_ref.with_mut(|p| p.ref_(bun_io::js_vm_ctx())); if let Some(handles) = crate::jsc_hooks::active_handles() { - bun_core::handle_oom(handles.put( + handles.put( crate::jsc_hooks::ActiveHandle::Listener(NonNull::from(this_ref)), (), - )); + ); } return Ok(this_value); } @@ -592,10 +592,10 @@ impl Listener { .with_mut(|r| r.set_strong(this_value, global)); this_ref.poll_ref.with_mut(|p| p.ref_(bun_io::js_vm_ctx())); if let Some(handles) = crate::jsc_hooks::active_handles() { - bun_core::handle_oom(handles.put( + handles.put( crate::jsc_hooks::ActiveHandle::Listener(NonNull::from(this_ref)), (), - )); + ); } Ok(this_value) diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index f125b595d3a6..0b8215c0f5f8 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -2697,8 +2697,7 @@ impl NewSocket { if !remaining_in_input_data.is_empty() { // Result intentionally discarded - let _ = self - .buffered_data_for_node_net + self.buffered_data_for_node_net .with_mut(|b| b.append_slice(remaining_in_input_data)); } @@ -2709,8 +2708,7 @@ impl NewSocket { // slower-path: clone the data, do one write. // Result intentionally discarded - let _ = self - .buffered_data_for_node_net + self.buffered_data_for_node_net .with_mut(|b| b.append_slice(buffer.slice())); // R-2: `write_maybe_corked` takes `&self` and does not touch // `buffered_data_for_node_net`, so a `JsCell::get()` projection @@ -2938,9 +2936,8 @@ impl NewSocket { if buffer_unwritten_data { let remaining = &bytes[uwrote..]; if !remaining.is_empty() { - let _ = self - .buffered_data_for_node_net - .with_mut(|b| b.append_slice(remaining)); // OOM/capacity: fire-and-forget + self.buffered_data_for_node_net + .with_mut(|b| b.append_slice(remaining)); } } diff --git a/src/runtime/test_runner/bun_test.rs b/src/runtime/test_runner/bun_test.rs index 8f2ee1f522c2..9994de727a4f 100644 --- a/src/runtime/test_runner/bun_test.rs +++ b/src/runtime/test_runner/bun_test.rs @@ -1248,7 +1248,7 @@ impl BunTest { .pending_then_refs .borrow_mut() .push(raw_ref.cast_const()); - let _ = result.then( + result.then( global_this, raw_ref, Bun__TestScope__Describe2__bunTestThen, diff --git a/src/runtime/test_runner/jest.rs b/src/runtime/test_runner/jest.rs index 2889638ff424..3da0f43cf2d8 100644 --- a/src/runtime/test_runner/jest.rs +++ b/src/runtime/test_runner/jest.rs @@ -237,7 +237,7 @@ impl<'a> TestRunner<'a> { } pub(crate) fn get_or_put_file(&mut self, file_path: &'static [u8]) -> GetOrPutFileResult { - let entry = self.index.get_or_put(file_path).expect("unreachable"); + let entry = self.index.get_or_put(file_path); if entry.found_existing { return GetOrPutFileResult { file_id: *entry.value_ptr, @@ -247,8 +247,7 @@ impl<'a> TestRunner<'a> { self.files .append(File { source: bun_ast::Source::init_empty_file(file_path), - }) - .expect("unreachable"); + }); *entry.value_ptr = file_id; GetOrPutFileResult { file_id } } diff --git a/src/runtime/test_runner/pretty_format.rs b/src/runtime/test_runner/pretty_format.rs index ed3cf5371ac7..da779c45ea81 100644 --- a/src/runtime/test_runner/pretty_format.rs +++ b/src/runtime/test_runner/pretty_format.rs @@ -1074,7 +1074,7 @@ impl<'a> Formatter<'a> { } } - let entry = self.map.get_or_put(value).expect("unreachable"); + let entry = self.map.get_or_put(value); if entry.found_existing { writer.write_all( pretty_fmt_const::("[Circular]").as_bytes(), diff --git a/src/runtime/test_runner/snapshot.rs b/src/runtime/test_runner/snapshot.rs index 39e1fdd93197..5de58859499e 100644 --- a/src/runtime/test_runner/snapshot.rs +++ b/src/runtime/test_runner/snapshot.rs @@ -124,8 +124,7 @@ impl Snapshots { // owned `snapshot_name` (same bytes as the interned key) instead. let gop = self .counts - .get_or_put(&snapshot_name) - .map_err(Error::from)?; + .get_or_put(&snapshot_name); if gop.found_existing { *gop.value_ptr += 1; } else { diff --git a/src/runtime/timer/timer_object_internals.rs b/src/runtime/timer/timer_object_internals.rs index 039f7b610e36..28725520f60d 100644 --- a/src/runtime/timer/timer_object_internals.rs +++ b/src/runtime/timer/timer_object_internals.rs @@ -1028,7 +1028,7 @@ impl TimerObjectInternals { .maps .get(self.flags.get().kind()) .put(self.id, elt) - }?; + }; } Ok(JSValue::js_number(f64::from(self.id))) } diff --git a/src/runtime/valkey_jsc/valkey.rs b/src/runtime/valkey_jsc/valkey.rs index 68ab3d8cbd8b..6a27b773c50a 100644 --- a/src/runtime/valkey_jsc/valkey.rs +++ b/src/runtime/valkey_jsc/valkey.rs @@ -434,9 +434,7 @@ impl ValkeyClient { promise: cmd.promise, }) .unwrap_or_oom(); - self.write_buffer - .write(&cmd.serialized_data) - .unwrap_or_oom(); + self.write_buffer.write(&cmd.serialized_data); // Free the serialized data since we've copied it to the write buffer // Note: `allocator.free(command.serialized_data)` — Box<[u8]> drops here. } @@ -750,9 +748,7 @@ impl ValkeyClient { ); // Path 1: Buffer already has data, append and process from buffer if !self.read_buffer.remaining().is_empty() { - self.read_buffer - .write(data) - .expect("failed to write to read buffer"); + self.read_buffer.write(data); // Process as many complete messages from the buffer as possible loop { @@ -844,8 +840,7 @@ impl ValkeyClient { } self.reply_scanner.reset(); self.read_buffer - .write(¤t_data_slice[before_read_pos..]) - .expect("failed to write remaining stack data to buffer"); + .write(¤t_data_slice[before_read_pos..]); return Ok(()); // Exit onData, next call will use the buffer path } else { // Any other error is fatal @@ -1349,7 +1344,7 @@ impl ValkeyClient { if !unwritten.is_empty() { // Handle incomplete write. - self.write_buffer.write(unwritten).unwrap_or_oom(); + self.write_buffer.write(unwritten); } return true; @@ -1513,9 +1508,7 @@ impl ValkeyClient { /// Write data to the socket buffer fn write(&mut self, data: &[u8]) -> Result { - self.write_buffer - .write(data) - .map_err(|_| RedisError::OutOfMemory)?; + self.write_buffer.write(data); Ok(data.len()) } @@ -1581,9 +1574,8 @@ impl HasAutoFlusher for ValkeyClient { impl bun_io::Write for ValkeyClient { #[inline] fn write_all(&mut self, buf: &[u8]) -> bun_io::Result<()> { - self.write_buffer - .write(buf) - .map_err(|_| bun_core::Error::Alloc(bun_alloc::AllocError)) + self.write_buffer.write(buf); + Ok(()) } } @@ -1596,9 +1588,8 @@ struct WriteBufWriter<'a>(&'a mut OffsetByteList); impl bun_io::Write for WriteBufWriter<'_> { #[inline] fn write_all(&mut self, buf: &[u8]) -> bun_io::Result<()> { - self.0 - .write(buf) - .map_err(|_| bun_core::Error::Alloc(bun_alloc::AllocError)) + self.0.write(buf); + Ok(()) } } diff --git a/src/runtime/webcore/ArrayBufferSink.rs b/src/runtime/webcore/ArrayBufferSink.rs index 747bd042acbc..b58c803cc286 100644 --- a/src/runtime/webcore/ArrayBufferSink.rs +++ b/src/runtime/webcore/ArrayBufferSink.rs @@ -79,19 +79,13 @@ impl ArrayBufferSink { } pub fn write(&mut self, data: &streams::Result) -> streams::result::Writable { - let len = match self.bytes.write(data.slice()) { - Ok(len) => len, - Err(_) => return streams::result::Writable::Err(syscall::Error::oom()), - }; + let len = self.bytes.write(data.slice()); self.source.ready(None, None); streams::result::Writable::Owned(len as u64) } pub(crate) fn write_latin1(&mut self, data: &streams::Result) -> streams::result::Writable { - let len = match self.bytes.write_latin1(data.slice()) { - Ok(len) => len, - Err(_) => return streams::result::Writable::Err(syscall::Error::oom()), - }; + let len = self.bytes.write_latin1(data.slice()); self.source.ready(None, None); streams::result::Writable::Owned(len as u64) } @@ -102,10 +96,7 @@ impl ArrayBufferSink { // length when the stream encoding is UTF-16. bytemuck checks both at // runtime. let utf16: &[u16] = bytemuck::cast_slice(bytes); - let len = match self.bytes.write_utf16(utf16) { - Ok(len) => len, - Err(_) => return streams::result::Writable::Err(syscall::Error::oom()), - }; + let len = self.bytes.write_utf16(utf16); self.source.ready(None, None); streams::result::Writable::Owned(len as u64) } diff --git a/src/runtime/webcore/fetch.rs b/src/runtime/webcore/fetch.rs index a08f57f10366..efdcbdedf116 100644 --- a/src/runtime/webcore/fetch.rs +++ b/src/runtime/webcore/fetch.rs @@ -265,7 +265,6 @@ fn bun_fetch_preconnect( .throw()); } - // bun.handleOom(url_str.toOwnedSlice(...)) → to_owned_slice() aborts on OOM. // `preconnect` takes a `URL<'static>` that borrows a `Box<[u8]>` href and // assumes ownership when `is_url_owned == true` (it reconstructs the Box // to free it). Hand the allocation off via `heap::alloc`. @@ -537,7 +536,7 @@ fn fetch_impl( } if let Some(req) = request_mut!() { - let _ = req.ensure_url(); // bun.handleOom — aborts on OOM + let _ = req.ensure_url(); break 'extract_url req.url.get().dupe_ref(); } @@ -2106,8 +2105,6 @@ fn fetch_impl( // see https://github.com/oven-sh/bun/issues/2985 promise, ); - // `catch |err| bun.handleOom(err)` — FetchTasklet::queue aborts on OOM. - // `body` has been *moved* into `FetchOptions`; the FetchTasklet now owns // the single live reference. diff --git a/src/runtime/webcore/fetch/FetchTasklet.rs b/src/runtime/webcore/fetch/FetchTasklet.rs index 9c472c096320..8fdc93c8663d 100644 --- a/src/runtime/webcore/fetch/FetchTasklet.rs +++ b/src/runtime/webcore/fetch/FetchTasklet.rs @@ -2025,7 +2025,7 @@ impl FetchTasklet { .map(|s| unsafe { bun_ptr::Interned::assume(s) }.as_bytes()); // `MultiArrayList` owns its // allocation, so clone; AsyncHTTP::init clones again for the client. - let header_entries = bun_core::handle_oom(fetch_tasklet.request_headers.entries.clone()); + let header_entries = fetch_tasklet.request_headers.entries.clone(); // `url` is moved into `AsyncHTTP::init`; capture the one // post-move query (`is_http()`, debug-assert only) up front. let url_is_http = url.is_http(); @@ -2294,7 +2294,7 @@ impl FetchTasklet { // the lock guard drops. let _ = thread_safe_stream_buffer .lock() - .write(http::END_OF_CHUNKED_HTTP1_1_ENCODING_RESPONSE_BODY); // OOM/capacity: fire-and-forget + .write(http::END_OF_CHUNKED_HTTP1_1_ENCODING_RESPONSE_BODY); } if let Some(http_) = self.http.as_mut() { http::http_thread() diff --git a/src/runtime/webcore/s3/client.rs b/src/runtime/webcore/s3/client.rs index a6b43286b9a6..905f9df4a379 100644 --- a/src/runtime/webcore/s3/client.rs +++ b/src/runtime/webcore/s3/client.rs @@ -184,14 +184,13 @@ pub(crate) fn list_objects( ) -> JsResult<()> { let mut search_params: Vec = Vec::::default(); - let _ = search_params.append_slice(b"?"); // OOM/capacity: fire-and-forget + search_params.append_slice(b"?"); if let Some(continuation_token) = list_options.continuation_token.as_ref().map(|s| s.slice()) { let mut buff = vec![0u8; continuation_token.len() * 3]; let encoded = encode_uri_component::(continuation_token, &mut buff).expect("unreachable"); - // OOM/capacity: fire-and-forget - let _ = search_params.append_fmt(format_args!( + search_params.append_fmt(format_args!( "continuation-token={}", bstr::BStr::new(encoded) )); @@ -202,19 +201,17 @@ pub(crate) fn list_objects( let encoded = encode_uri_component::(delimiter, &mut buff).expect("unreachable"); if list_options.continuation_token.is_some() { - let _ = - search_params.append_fmt(format_args!("&delimiter={}", bstr::BStr::new(encoded))); // OOM/capacity: fire-and-forget + search_params.append_fmt(format_args!("&delimiter={}", bstr::BStr::new(encoded))); } else { - let _ = - search_params.append_fmt(format_args!("delimiter={}", bstr::BStr::new(encoded))); // OOM/capacity: fire-and-forget + search_params.append_fmt(format_args!("delimiter={}", bstr::BStr::new(encoded))); } } if list_options.encoding_type.is_some() { if list_options.continuation_token.is_some() || list_options.delimiter.is_some() { - let _ = search_params.append_slice(b"&encoding-type=url"); // OOM/capacity: fire-and-forget + search_params.append_slice(b"&encoding-type=url"); } else { - let _ = search_params.append_slice(b"encoding-type=url"); // OOM/capacity: fire-and-forget + search_params.append_slice(b"encoding-type=url"); } } @@ -223,9 +220,9 @@ pub(crate) fn list_objects( || list_options.delimiter.is_some() || list_options.encoding_type.is_some() { - let _ = search_params.append_fmt(format_args!("&fetch-owner={}", fetch_owner)); // OOM/capacity: fire-and-forget + search_params.append_fmt(format_args!("&fetch-owner={}", fetch_owner)); } else { - let _ = search_params.append_fmt(format_args!("fetch-owner={}", fetch_owner)); // OOM/capacity: fire-and-forget + search_params.append_fmt(format_args!("fetch-owner={}", fetch_owner)); } } @@ -234,25 +231,25 @@ pub(crate) fn list_objects( || list_options.encoding_type.is_some() || list_options.fetch_owner.is_some() { - let _ = search_params.append_slice(b"&list-type=2"); // OOM/capacity: fire-and-forget + search_params.append_slice(b"&list-type=2"); } else { - let _ = search_params.append_slice(b"list-type=2"); // OOM/capacity: fire-and-forget + search_params.append_slice(b"list-type=2"); } if let Some(max_keys) = list_options.max_keys { - let _ = search_params.append_fmt(format_args!("&max-keys={}", max_keys)); // OOM/capacity: fire-and-forget + search_params.append_fmt(format_args!("&max-keys={}", max_keys)); } if let Some(prefix) = list_options.prefix.as_ref().map(|s| s.slice()) { let mut buff = vec![0u8; prefix.len() * 3]; let encoded = encode_uri_component::(prefix, &mut buff).expect("unreachable"); - let _ = search_params.append_fmt(format_args!("&prefix={}", bstr::BStr::new(encoded))); // OOM/capacity: fire-and-forget + search_params.append_fmt(format_args!("&prefix={}", bstr::BStr::new(encoded))); } if let Some(start_after) = list_options.start_after.as_ref().map(|s| s.slice()) { let mut buff = vec![0u8; start_after.len() * 3]; let encoded = encode_uri_component::(start_after, &mut buff).expect("unreachable"); - let _ = search_params.append_fmt(format_args!("&start-after={}", bstr::BStr::new(encoded))); // OOM/capacity: fire-and-forget + search_params.append_fmt(format_args!("&start-after={}", bstr::BStr::new(encoded))); } let result = match this.sign_request::( @@ -344,7 +341,7 @@ pub(crate) fn list_objects( task.http.write(bun_http::AsyncHTTP::init( bun_http::Method::GET, url, - task.headers.entries.clone().expect("OOM"), + task.headers.entries.clone(), headers_buf, b"", bun_http::HTTPClientResultCallback::new_with_release::( @@ -1288,7 +1285,7 @@ fn download_stream( task.http.write(bun_http::AsyncHTTP::init( bun_http::Method::GET, url, - task.headers.entries.clone().expect("OOM"), + task.headers.entries.clone(), headers_buf, b"", bun_http::HTTPClientResultCallback::new_with_release::( diff --git a/src/runtime/webcore/s3/simple_request.rs b/src/runtime/webcore/s3/simple_request.rs index a05b3e529091..4fde9d7e544c 100644 --- a/src/runtime/webcore/s3/simple_request.rs +++ b/src/runtime/webcore/s3/simple_request.rs @@ -672,7 +672,7 @@ pub(crate) fn execute_simple_s3_request( let async_http = AsyncHTTP::init( options.method, url, - task.headers.entries.clone().expect("OOM"), + task.headers.entries.clone(), headers_buf, body, HTTPClientResultCallback::new_with_release::( diff --git a/src/runtime/webcore/streams.rs b/src/runtime/webcore/streams.rs index cfd90b3522d9..e43d0b435bc8 100644 --- a/src/runtime/webcore/streams.rs +++ b/src/runtime/webcore/streams.rs @@ -1700,22 +1700,16 @@ impl HTTPServerWritable { return self.writable_result(len); } - if self.buffer.write(bytes).is_err() { - return Writable::Err(SysError::from_code(sys::E::ENOMEM, sys::Tag::write)); - } + self.buffer.write(bytes); } else if self.buffer.len() as BlobSizeType + len >= self.high_water_mark { // TODO: attempt to write both in a corked buffer? - if self.buffer.write(bytes).is_err() { - return Writable::Err(SysError::from_code(sys::E::ENOMEM, sys::Tag::write)); - } + self.buffer.write(bytes); if self.send_readable(0) { return self.writable_result(len); } } else { // queue the data wait until highWaterMark is reached or the auto flusher kicks in - if self.buffer.write(bytes).is_err() { - return Writable::Err(SysError::from_code(sys::E::ENOMEM, sys::Tag::write)); - } + self.buffer.write(bytes); } self.register_auto_flusher(); @@ -1751,9 +1745,7 @@ impl HTTPServerWritable { do_send = false; } - if self.buffer.write_latin1(bytes).is_err() { - return Writable::Err(SysError::from_code(sys::E::ENOMEM, sys::Tag::write)); - } + self.buffer.write_latin1(bytes); if do_send { if self.send_readable(0) { @@ -1764,16 +1756,12 @@ impl HTTPServerWritable { // kinda fast path: // - combined chunk is large enough to flush automatically // - no backpressure - if self.buffer.write_latin1(bytes).is_err() { - return Writable::Err(SysError::from_code(sys::E::ENOMEM, sys::Tag::write)); - } + self.buffer.write_latin1(bytes); if self.send_readable(0) { return self.writable_result(len); } } else { - if self.buffer.write_latin1(bytes).is_err() { - return Writable::Err(SysError::from_code(sys::E::ENOMEM, sys::Tag::write)); - } + self.buffer.write_latin1(bytes); } self.register_auto_flusher(); @@ -1800,10 +1788,7 @@ impl HTTPServerWritable { // we assume the case of all-ascii UTF-16 string is pretty uncommon // bytes are u16-aligned per Result.slice16 invariant; bytemuck checks at runtime. let utf16: &[u16] = bytemuck::cast_slice(bytes); - let written = match self.buffer.write_utf16(utf16) { - Ok(n) => n, - Err(_) => return Writable::Err(SysError::from_code(sys::E::ENOMEM, sys::Tag::write)), - }; + let written = self.buffer.write_utf16(utf16); let readable_len = self.readable_slice().len(); if readable_len >= self.high_water_mark as usize || self.has_backpressure() { @@ -2427,7 +2412,6 @@ impl NetworkSink { // flush everything and send EOF if let Some(task) = self.task_ref() { let _ = task.write_bytes(b"", true); - // bun.handleOom → Rust aborts on OOM } self.source.close(err); diff --git a/src/runtime/webview/ChromeProcess.rs b/src/runtime/webview/ChromeProcess.rs index 3b9235f9531a..4336f4dc5209 100644 --- a/src/runtime/webview/ChromeProcess.rs +++ b/src/runtime/webview/ChromeProcess.rs @@ -505,7 +505,7 @@ fn spawn( // SAFETY: vm is the per-thread VirtualMachine (valid for the call); // `transpiler.env` is set during VM init and lives for VM lifetime; // `.map` is its `&mut Map` slot. - let env = unsafe { (*(*vm).transpiler.env).map.create_null_delimited_env_map() }?; + let env = unsafe { (*(*vm).transpiler.env).map.create_null_delimited_env_map() }; let opts = SpawnOptions { stdin: Stdio::Ignore, diff --git a/src/runtime/webview/HostProcess.rs b/src/runtime/webview/HostProcess.rs index ee337671cd04..b4962f3f6be5 100644 --- a/src/runtime/webview/HostProcess.rs +++ b/src/runtime/webview/HostProcess.rs @@ -156,7 +156,7 @@ fn spawn(vm: *mut VirtualMachine, stdout_inherit: bool, stderr_inherit: bool) -> // Same pattern as NODE_CHANNEL_FD in js_bun_spawn_bindings.rs. // SAFETY: vm is the per-thread VirtualMachine (valid for the call); // `transpiler.env` is set during VM init and lives for VM lifetime. - let base = unsafe { (*(*vm).transpiler.env).map.create_null_delimited_env_map() }?; + let base = unsafe { (*(*vm).transpiler.env).map.create_null_delimited_env_map() }; let base_slice = base.as_slice(); // base_slice already has a trailing None sentinel; drop it, append our // var, then re-terminate. diff --git a/src/sourcemap/Chunk.rs b/src/sourcemap/Chunk.rs index 899e5671c01f..6750673bc9cb 100644 --- a/src/sourcemap/Chunk.rs +++ b/src/sourcemap/Chunk.rs @@ -646,7 +646,7 @@ impl NewBuilder<'_, VLQSourceMap> { } = self.line_offset_tables { self.line_offset_tables = LineOffsetTables::Owned(OwnedLineOffsetTables( - LineOffsetTable::generate(contents, approximate_line_count).unwrap_or_default(), + LineOffsetTable::generate(contents, approximate_line_count), )); } diff --git a/src/sourcemap/LineOffsetTable.rs b/src/sourcemap/LineOffsetTable.rs index de4051acf294..060109cb66bf 100644 --- a/src/sourcemap/LineOffsetTable.rs +++ b/src/sourcemap/LineOffsetTable.rs @@ -1,7 +1,6 @@ use core::alloc::Allocator; use std::alloc::Global; -use bun_alloc::AllocError; use bun_ast::Loc; use bun_collections::MultiArrayList; use bun_core::strings; @@ -150,7 +149,7 @@ impl LineOffsetTable { } /// `Global`-allocator convenience wrapper around [`generate_in`]. - pub fn generate(contents: &[u8], approximate_line_count: i32) -> Result { + pub fn generate(contents: &[u8], approximate_line_count: i32) -> List { Self::generate_in::(contents, approximate_line_count) } @@ -161,12 +160,12 @@ impl LineOffsetTable { pub fn generate_in( contents: &[u8], approximate_line_count: i32, - ) -> Result, AllocError> { + ) -> List { let alloc = A::default(); let empty_box = || Vec::new_in(alloc).into_boxed_slice(); let mut list = List::::new_in(alloc); // Preallocate the top-level table using the approximate line count from the lexer - list.ensure_unused_capacity(approximate_line_count.max(1) as usize)?; + list.ensure_unused_capacity(approximate_line_count.max(1) as usize); let mut column: i32 = 0; let mut byte_offset_to_first_non_ascii: u32 = i32::MAX as u32; let mut column_byte_offset: u32 = 0; @@ -276,7 +275,7 @@ impl LineOffsetTable { byte_offset_to_start_of_line: line_byte_offset, byte_offset_to_first_non_ascii, columns_for_non_ascii: owned, - })?; + }); column = 0; byte_offset_to_first_non_ascii = i32::MAX as u32; @@ -314,7 +313,7 @@ impl LineOffsetTable { byte_offset_to_start_of_line: line_byte_offset, byte_offset_to_first_non_ascii, columns_for_non_ascii: owned, - })?; + }); } // `shrink_and_free` has no realloc-in-place fast path — it always does a fresh @@ -327,6 +326,6 @@ impl LineOffsetTable { if list.capacity() > list.len() + (list.len() >> 1) { list.shrink_and_free(list.len()); } - Ok(list) + list } } diff --git a/src/sourcemap/Mapping.rs b/src/sourcemap/Mapping.rs index da5fd11c252f..fd1afc3a7d36 100644 --- a/src/sourcemap/Mapping.rs +++ b/src/sourcemap/Mapping.rs @@ -110,8 +110,8 @@ impl ListValue { both_lists!(self, |list| list.memory_cost()) } - fn ensure_total_capacity(&mut self, count: usize) -> Result<(), bun_alloc::AllocError> { - both_lists!(self, |list| list.ensure_total_capacity(count)) + fn try_ensure_total_capacity(&mut self, count: usize) -> Result<(), bun_alloc::AllocError> { + both_lists!(self, |list| list.try_ensure_total_capacity(count)) } } @@ -139,7 +139,7 @@ impl List { }; let mut with_names: MultiArrayList = MultiArrayList::default(); - with_names.ensure_total_capacity(without_names.len())?; + with_names.try_ensure_total_capacity(without_names.len())?; // `without_names` drops at end of scope (was `defer without_names.deinit(allocator)`). // MultiArrayList has no @@ -197,20 +197,19 @@ impl List { }) } - pub(crate) fn append(&mut self, mapping: &Mapping) -> Result<(), bun_alloc::AllocError> { + pub(crate) fn append(&mut self, mapping: &Mapping) { match &mut self.r#impl { ListValue::WithoutNames(list) => { list.append(MappingWithoutName { generated: mapping.generated, original: mapping.original, source_index: mapping.source_index, - })?; + }); } ListValue::WithNames(list) => { - list.append(*mapping)?; + list.append(*mapping); } } - Ok(()) } pub(crate) fn len(&self) -> usize { @@ -277,11 +276,11 @@ impl List { + (self.names.len() * size_of::()) } - pub(crate) fn ensure_total_capacity( + pub(crate) fn try_ensure_total_capacity( &mut self, count: usize, ) -> Result<(), bun_alloc::AllocError> { - self.r#impl.ensure_total_capacity(count) + self.r#impl.try_ensure_total_capacity(count) } } @@ -459,7 +458,7 @@ pub fn parse( // `errdefer mapping.deinit(allocator)` deleted: `List: Drop` and this fn returns no error union. if let Some(count) = estimated_mapping_count { - if mapping.ensure_total_capacity(count).is_err() { + if mapping.try_ensure_total_capacity(count).is_err() { return Err(ParseFail { err: crate::Error::Alloc(bun_alloc::AllocError), loc: Loc::default(), @@ -712,22 +711,19 @@ pub fn parse( } } } - // `catch |err| bun.handleOom(err)` → panic on OOM; do not silently drop the mapping. - mapping - .append(&Mapping { - generated, - original, - source_index, - // Rows before any 5-field segment surface as name_index -1. - // Without the SIMD pre-pass this happens implicitly: the - // list is WithoutNames so append discards this field, and - // find()/ensure_with_names() later fill it with -1 via - // to_named(). The SIMD pre-pass promotes to WithNames up - // front when allow_names is true, so this loop's rows must - // carry -1 explicitly until the first 5-field segment. - name_index: if has_names { name_index } else { -1 }, - }) - .expect("OOM"); + mapping.append(&Mapping { + generated, + original, + source_index, + // Rows before any 5-field segment surface as name_index -1. + // Without the SIMD pre-pass this happens implicitly: the + // list is WithoutNames so append discards this field, and + // find()/ensure_with_names() later fill it with -1 via + // to_named(). The SIMD pre-pass promotes to WithNames up + // front when allow_names is true, so this loop's rows must + // carry -1 explicitly until the first 5-field segment. + name_index: if has_names { name_index } else { -1 }, + }); } if needs_sort && options.sort { @@ -800,7 +796,7 @@ fn parse_simd( let rows = match &mut mapping.r#impl { ListValue::WithoutNames(list) => { if list - .ensure_total_capacity(base.saturating_add(seg_bound)) + .try_ensure_total_capacity(base.saturating_add(seg_bound)) .is_err() { return SimdResult::OutOfMemory; @@ -839,7 +835,7 @@ fn parse_simd( } ListValue::WithNames(list) => { if list - .ensure_total_capacity(base.saturating_add(seg_bound)) + .try_ensure_total_capacity(base.saturating_add(seg_bound)) .is_err() { return SimdResult::OutOfMemory; diff --git a/src/sourcemap_jsc/CodeCoverage.rs b/src/sourcemap_jsc/CodeCoverage.rs index 966f578b8088..7cbbe8c4b06e 100644 --- a/src/sourcemap_jsc/CodeCoverage.rs +++ b/src/sourcemap_jsc/CodeCoverage.rs @@ -41,10 +41,7 @@ pub struct Report { impl Report { pub(crate) fn lines_coverage_fraction(&self) -> f64 { - let mut intersected = self - .executable_lines - .clone() - .unwrap_or_else(|_| bun_alloc::out_of_memory()); + let mut intersected = self.executable_lines.clone(); intersected.set_intersection(&self.lines_which_have_executed); let total_count: f64 = self.executable_lines.count() as f64; @@ -219,10 +216,8 @@ pub mod text { writer.write_all(&pretty_fmt::(" | "))?; - let mut executable_lines_that_havent_been_executed = report - .lines_which_have_executed - .clone() - .unwrap_or_else(|_| bun_alloc::out_of_memory()); + let mut executable_lines_that_havent_been_executed = + report.lines_which_have_executed.clone(); executable_lines_that_havent_been_executed.toggle_all(); // This sets statements in executed scopes @@ -500,8 +495,8 @@ impl ByteRangeMapping { let mut functions: Vec = Vec::new(); functions.reserve_exact(function_blocks.len()); - let mut functions_which_have_executed: Bitset = Bitset::init_empty(function_blocks.len())?; - let mut stmts_which_have_executed: Bitset = Bitset::init_empty(blocks.len())?; + let mut functions_which_have_executed: Bitset = Bitset::init_empty(function_blocks.len()); + let mut stmts_which_have_executed: Bitset = Bitset::init_empty(blocks.len()); let mut stmts: Vec = Vec::new(); stmts.reserve_exact(function_blocks.len()); @@ -510,8 +505,8 @@ impl ByteRangeMapping { if ignore_sourcemap || parsed_mappings_.is_none() { line_count = line_starts.len() as u32; - executable_lines = Bitset::init_empty(line_count as usize)?; - lines_which_have_executed = Bitset::init_empty(line_count as usize)?; + executable_lines = Bitset::init_empty(line_count as usize); + lines_which_have_executed = Bitset::init_empty(line_count as usize); line_hits = vec![0u32; line_count as usize]; let line_hits_slice = line_hits.as_mut_slice(); @@ -615,8 +610,8 @@ impl ByteRangeMapping { } } else if let Some(parsed_mapping) = parsed_mappings_.as_deref() { line_count = (parsed_mapping.input_line_count as u32) + 1; - executable_lines = Bitset::init_empty(line_count as usize)?; - lines_which_have_executed = Bitset::init_empty(line_count as usize)?; + executable_lines = Bitset::init_empty(line_count as usize); + lines_which_have_executed = Bitset::init_empty(line_count as usize); line_hits = vec![0u32; line_count as usize]; let line_hits_slice = line_hits.as_mut_slice(); @@ -809,8 +804,7 @@ impl ByteRangeMapping { source_url: ZigStringSlice, ) -> ByteRangeMapping { ByteRangeMapping { - line_offset_table: LineOffsetTable::generate(source_contents, 0) - .unwrap_or_else(|_| bun_alloc::out_of_memory()), + line_offset_table: LineOffsetTable::generate(source_contents, 0), source_id, source_url, } diff --git a/src/sourcemap_jsc/JSSourceMap.rs b/src/sourcemap_jsc/JSSourceMap.rs index f284e4b80e42..c90638752304 100644 --- a/src/sourcemap_jsc/JSSourceMap.rs +++ b/src/sourcemap_jsc/JSSourceMap.rs @@ -78,7 +78,6 @@ fn find_source_map(global: &JSGlobalObject, frame: &CallFrame) -> JsResult = Box::new([source_url_string.dupe_ref()]); // `SavedSourceMap::get` hands back a +1 ref as an `Arc`; diff --git a/src/sql_jsc/mysql/JSMySQLConnection.rs b/src/sql_jsc/mysql/JSMySQLConnection.rs index 26cbd93b1360..0d3bef8b63f8 100644 --- a/src/sql_jsc/mysql/JSMySQLConnection.rs +++ b/src/sql_jsc/mysql/JSMySQLConnection.rs @@ -890,8 +890,7 @@ impl JSMySQLConnection { pub(crate) fn get_statement_from_signature_name( &self, signature_name: &[u8], - ) -> Result, bun_core::AllocError> - { + ) -> my_sql_connection::PreparedStatementsMapGetOrPutResult<'_> { self.connection_mut().statements.get_or_put(signature_name) } } diff --git a/src/sql_jsc/mysql/MySQLConnection.rs b/src/sql_jsc/mysql/MySQLConnection.rs index 423bd998bb80..15f113c30b86 100644 --- a/src/sql_jsc/mysql/MySQLConnection.rs +++ b/src/sql_jsc/mysql/MySQLConnection.rs @@ -527,9 +527,7 @@ impl MySQLConnection { self.read_buffer.head = 0; self.last_message_start = 0; self.read_buffer.byte_list.clear(); - self.read_buffer - .write(&data[offset.get()..]) - .unwrap_or_else(|_| panic!("failed to write to read buffer")); + self.read_buffer.write(&data[offset.get()..]); } else { bun_core::handle_error_return_trace(err); self.flags.remove(ConnectionFlags::IS_PROCESSING_DATA); @@ -544,9 +542,7 @@ impl MySQLConnection { { self.read_buffer.head = self.last_message_start; - self.read_buffer - .write(data) - .unwrap_or_else(|_| panic!("failed to write to read buffer")); + self.read_buffer.write(data); // reshaped for borrowck — `self.process_packets(self.buffered_reader())` // borrows `&mut self` twice. Construct the reader first; it holds a // `*mut Self` so the second borrow doesn't conflict. @@ -1687,9 +1683,7 @@ impl Writer { impl WriterContext for Writer { fn write(self, data: &[u8]) -> Result<(), AnyMySQLError> { - self.write_buffer() - .write(data) - .map_err(|_| AnyMySQLError::OutOfMemory)?; + self.write_buffer().write(data); Ok(()) } diff --git a/src/sql_jsc/mysql/MySQLQuery.rs b/src/sql_jsc/mysql/MySQLQuery.rs index 515d7f4fd987..85daf00fec31 100644 --- a/src/sql_jsc/mysql/MySQLQuery.rs +++ b/src/sql_jsc/mysql/MySQLQuery.rs @@ -298,16 +298,7 @@ impl MySQLQuery { query_str = Some(query); // errdefer signature.deinit() — `Signature: Drop` handles the error path; on the // found_existing success path below we explicitly drop it. - let entry = match connection.get_statement_from_signature_name(&signature.name) { - Ok(e) => e, - Err(err) => { - // `err` is `bun_core::AllocError`; `throw_error` takes - // `crate::Error` (`From` → OutOfMemory). - let _ = global_object - .throw_error(crate::Error::from(err), "failed to allocate statement"); - return Err(crate::Error::JSError); - } - }; + let entry = connection.get_statement_from_signature_name(&signature.name); if entry.found_existing { let stmt: *mut MySQLStatement = *entry.value_ptr; diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index f575ab14d4f8..a31b0ceb7f51 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -983,8 +983,7 @@ impl PostgresSQLConnection { self.read_buffer.with_mut(|rb| { rb.head = 0; rb.byte_list.clear(); - rb.write(&data[offset..]) - .expect("failed to write to read buffer"); + rb.write(&data[offset..]); }); } else { bun_core::handle_error_return_trace(err); @@ -997,8 +996,7 @@ impl PostgresSQLConnection { } if !done { // read buffer is not empty, so we need to write the data to the buffer and then read it - self.read_buffer - .with_mut(|rb| rb.write(data).expect("failed to write to read buffer")); + self.read_buffer.with_mut(|rb| rb.write(data)); let reader = self.buffered_reader(); match PostgresRequest::on_data(self, reader) { Ok(()) => { @@ -1628,10 +1626,7 @@ impl Writer { // escape hatch needed. pub(crate) fn write(&mut self, data: &[u8]) -> Result<(), AnyPostgresError> { - self.connection - .write_buffer - .with_mut(|b| b.write(data)) - .map_err(|_| AnyPostgresError::OutOfMemory)?; + self.connection.write_buffer.with_mut(|b| b.write(data)); Ok(()) } @@ -2491,14 +2486,12 @@ impl PostgresSQLConnection { MessageType::ParameterStatus => { let parameter_status = protocol::ParameterStatus::decode_internal(reader.reborrow())?; - self.backend_parameters - .with_mut(|m| { - m.insert( - parameter_status.name.slice(), - parameter_status.value.slice(), - ) - }) - .map_err(|_| AnyPostgresError::OutOfMemory)?; + self.backend_parameters.with_mut(|m| { + m.insert( + parameter_status.name.slice(), + parameter_status.value.slice(), + ) + }); // parameter_status dropped at scope end } MessageType::ReadyForQuery => { diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 54e1e2d1954c..47cc6566e020 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -705,18 +705,11 @@ impl PostgresSQLQuery { // until after the raw value-slot ptr is captured). Extract the // raw slot ptr while the borrow is live so the remainder of // this block needs no further `&mut` to the map. - let entry_value_ptr = match connection.statements.with_mut(|s| { - s.get_or_put(&signature.name) - .map(|e| std::ptr::from_mut::<*mut PostgresSQLStatement>(e.value_ptr)) - }) { - Ok(v) => v, - Err(err) => { - drop(signature); - release_query_ref(); - return Err(global_object - .throw_error(crate::Error::from(err), "failed to allocate statement")); - } - }; + let entry_value_ptr = connection.statements.with_mut(|s| { + std::ptr::from_mut::<*mut PostgresSQLStatement>( + s.get_or_put(&signature.name).value_ptr, + ) + }); connection_entry_value = Some(entry_value_ptr); } let can_execute = !connection.has_query_running(); diff --git a/src/sql_jsc/shared/SQLDataCell.rs b/src/sql_jsc/shared/SQLDataCell.rs index 71a681255b53..b1246be419b2 100644 --- a/src/sql_jsc/shared/SQLDataCell.rs +++ b/src/sql_jsc/shared/SQLDataCell.rs @@ -3,7 +3,6 @@ use core::slice; use crate::jsc::{ExternColumnIdentifier, JSGlobalObject, JSType, JSValue, JsError, JsResult}; use bun_collections::StringHashMap; -use bun_core::UnwrapOrOom as _; use bun_core::wtf::WTFStringImpl; use bun_sql::shared::{ColumnIdentifier, Data}; @@ -548,10 +547,7 @@ pub(crate) fn dedupe_columns<'a>( ColumnIdentifier::Name(name) => { // reshaped for borrowck — compute `found_existing` before // mutating `*name_or_index`. - let found_existing = seen_fields - .get_or_put(name.slice()) - .unwrap_or_oom() - .found_existing; + let found_existing = seen_fields.get_or_put(name.slice()).found_existing; if found_existing { *name_or_index = ColumnIdentifier::Duplicate; flags.insert(Flags::HAS_DUPLICATE_COLUMNS); diff --git a/src/standalone_graph/StandaloneModuleGraph.rs b/src/standalone_graph/StandaloneModuleGraph.rs index 6a1a7b82c97b..7d2820a146d5 100644 --- a/src/standalone_graph/StandaloneModuleGraph.rs +++ b/src/standalone_graph/StandaloneModuleGraph.rs @@ -242,11 +242,11 @@ impl StandaloneModuleGraph { } let rel = &key[prefix.len()..]; if recursive { - let _ = seen.put(rel, is_dir); + seen.put(rel, is_dir); } else if let Some(sep) = strings::index_of_char(rel, b'/') { - let _ = seen.put(&rel[..sep as usize], true); + seen.put(&rel[..sep as usize], true); } else { - let _ = seen.put(rel, is_dir); + seen.put(rel, is_dir); } }; for key in self.files.keys() { @@ -693,7 +693,7 @@ impl StandaloneModuleGraph { slice_to_z(raw_const, raw_len, module.bytecode_origin_path), ) }; - let _ = modules.put( + modules.put( name.as_bytes(), File { name: name.as_bytes(), @@ -749,7 +749,7 @@ impl StandaloneModuleGraph { if rest.len() < BASE_PUBLIC_PATH.len() || dirs.contains_key(rest) { break; } - let _ = dirs.put(rest, ()); + dirs.put(rest, ()); } } dirs.lock_pointers(); From aec6dc070863815a3fd833af62e4ab0a774aaff7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 06:10:25 +0000 Subject: [PATCH 5/7] Derive Clone where the manual clones only existed for the old fallible clone() StringArrayHashMap, StringSet and ArrayHashMap implement Clone now, so the entrywise MacroMap rebuilds in RuntimeTranspilerStore, jsc_hooks and JSTranspiler (clone_macro_map), and the hand-written Clone impls and clone() methods on ExternalModules, DependencyMap, Framework and ESMConditions collapse to .clone() / #[derive(Clone)]. Also drops the comments next to changed call sites that still described the removed Result plumbing. --- src/bundler/HTMLScanner.rs | 3 +-- src/bundler/ParseTask.rs | 2 -- .../generateChunksInParallel.rs | 1 - src/bundler/options.rs | 15 +------------ src/install/npm.rs | 5 +---- src/jsc/RuntimeTranspilerStore.rs | 12 +---------- src/resolver/options.rs | 13 +----------- src/resolver/package_json.rs | 15 +++---------- src/runtime/api/JSON5Object.rs | 4 ---- src/runtime/api/JSTranspiler.rs | 21 ++++--------------- src/runtime/bake/bake_body.rs | 13 +----------- src/runtime/cli/build_command.rs | 2 +- src/runtime/jsc_hooks.rs | 20 +----------------- 13 files changed, 15 insertions(+), 111 deletions(-) diff --git a/src/bundler/HTMLScanner.rs b/src/bundler/HTMLScanner.rs index 7793e46be4f5..979d4845e5f8 100644 --- a/src/bundler/HTMLScanner.rs +++ b/src/bundler/HTMLScanner.rs @@ -90,8 +90,7 @@ impl<'a> HTMLScanner<'a> { } fn on_html_parse_error(&mut self, message: &[u8]) { - // Vec/Box allocations abort on OOM; just call. `IntoText for - // Vec` → `Cow::Owned`, so the Log owns and drops the copy. + // `IntoText for Vec` → `Cow::Owned`, so the Log owns and drops the copy. self.log .add_error(Some(self.source), Loc::EMPTY, message.to_vec()); } diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 17d7d655bd0c..9c22cdf58307 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -956,7 +956,6 @@ pub mod parse_worker { Loader::SqliteEmbedded | Loader::Sqlite => { if !topts.target.is_bun() { - // logger OOM-only log.add_error( Some(source), Loc::EMPTY, @@ -1077,7 +1076,6 @@ pub mod parse_worker { Loader::Napi => { // (dap-eval-cb "source.contents.ptr") if topts.target == options::Target::Browser { - // logger OOM-only log.add_error( Some(source), Loc::EMPTY, diff --git a/src/bundler/linker_context/generateChunksInParallel.rs b/src/bundler/linker_context/generateChunksInParallel.rs index 411b8faca7aa..531c9bdda4f8 100644 --- a/src/bundler/linker_context/generateChunksInParallel.rs +++ b/src/bundler/linker_context/generateChunksInParallel.rs @@ -1120,7 +1120,6 @@ pub(crate) fn generate_chunks_in_parallel( })); } else { // an error - // logger OOM-only // Split-borrow — `static_route_visitor.c` holds a // detached `&LinkerContext`; `log_disjoint` returns the // disjoint `Transpiler.log` backref so no `&mut c` is diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 1d1e1e9396db..2a53752ad23a 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -712,6 +712,7 @@ fn default_loaders_match_table() { } // https://webpack.js.org/guides/package-exports/#reference-syntax +#[derive(Clone)] pub struct ESMConditions { pub(crate) default: ConditionsMap, pub(crate) import: ConditionsMap, @@ -775,20 +776,6 @@ impl ESMConditions { }) } - pub fn clone(&self) -> Result { - let default = self.default.clone(); - let import = self.import.clone(); - let require = self.require.clone(); - let style = self.style.clone(); - - Ok(ESMConditions { - default, - import, - require, - style, - }) - } - pub fn append_slice(&mut self, conditions: &[&[u8]]) -> Result<(), bun_alloc::AllocError> { self.default.reserve(conditions.len()); self.import.reserve(conditions.len()); diff --git a/src/install/npm.rs b/src/install/npm.rs index 11ed8dfe470a..74daf29fef1e 100644 --- a/src/install/npm.rs +++ b/src/install/npm.rs @@ -1953,10 +1953,7 @@ impl PackageManifest { } /// Fills `set` with the names listed in `bundle(d)Dependencies`; returns whether it was `true` (bundle everything). -fn collect_bundled_deps( - version_obj: Option<&JSON::E::ObjectJSON>, - set: &mut StringSet, -) -> bool { +fn collect_bundled_deps(version_obj: Option<&JSON::E::ObjectJSON>, set: &mut StringSet) -> bool { set.map.clear_retaining_capacity(); let mut bundle_all_deps = false; if let Some(bundled_deps_value) = version_obj diff --git a/src/jsc/RuntimeTranspilerStore.rs b/src/jsc/RuntimeTranspilerStore.rs index 2796effb4d82..4ef395e860cd 100644 --- a/src/jsc/RuntimeTranspilerStore.rs +++ b/src/jsc/RuntimeTranspilerStore.rs @@ -795,17 +795,7 @@ impl TranspilerJob { { MacroRemap::default() } else { - // Note: `MacroRemap` (StringArrayHashMap of StringArrayHashMap) - // has no nested `Clone` impl (the inherent `clone()` requires - // `V: Clone`). Re-key shallowly here - // matching the build-command conversion (transpiler.rs:2616). - // OOM during the - // inner `clone()` must abort — never silently drop a remapping. - let mut m = MacroRemap::default(); - for (k, v) in transpiler.options.macro_remap.iter() { - m.insert(k, v.clone()); - } - m + transpiler.options.macro_remap.clone() }; // Only diff --git a/src/resolver/options.rs b/src/resolver/options.rs index 9252f7f4f235..3f829cffaba9 100644 --- a/src/resolver/options.rs +++ b/src/resolver/options.rs @@ -19,23 +19,12 @@ pub enum Packages { External, } -#[derive(Default)] +#[derive(Default, Clone)] pub struct ExternalModules { pub patterns: Vec, pub abs_paths: StringSet, pub node_modules: StringSet, } -impl Clone for ExternalModules { - fn clone(&self) -> Self { - // `StringSet::clone` is an inherent fallible method (returns - // `Result<_, AllocError>`), so this can't be `#[derive(Clone)]`. - Self { - patterns: self.patterns.clone(), - abs_paths: self.abs_paths.clone(), - node_modules: self.node_modules.clone(), - } - } -} #[derive(Debug, Clone)] pub struct WildcardPattern { pub prefix: Box<[u8]>, diff --git a/src/resolver/package_json.rs b/src/resolver/package_json.rs index 202edffd5155..33f8a857d4e1 100644 --- a/src/resolver/package_json.rs +++ b/src/resolver/package_json.rs @@ -45,7 +45,9 @@ type ScriptsMap = StringArrayHashMap<&'static [u8]>; type MainFieldMap = StringMap; -#[derive(Default)] +/// Cloning copies the key/value vecs; `SemverString`/`Dependency` are POD +/// over `source_buf`, which every clone keeps borrowing. +#[derive(Default, Clone)] pub struct DependencyMap { pub map: DependencyHashMap, // Borrows the package.json source contents; lifetime-erased to 'static, @@ -53,17 +55,6 @@ pub struct DependencyMap { pub source_buf: &'static [u8], } -impl Clone for DependencyMap { - /// Deep-clones the small key/value vecs; `SemverString`/`Dependency` are - /// POD over `source_buf`. - fn clone(&self) -> Self { - Self { - map: self.map.clone(), - source_buf: self.source_buf, - } - } -} - // Inherent impls cannot carry associated type aliases (stable), so use a free alias. type DependencyHashMap = ArrayHashMap; diff --git a/src/runtime/api/JSON5Object.rs b/src/runtime/api/JSON5Object.rs index b2b8b40e96cc..d3110825cd80 100644 --- a/src/runtime/api/JSON5Object.rs +++ b/src/runtime/api/JSON5Object.rs @@ -198,10 +198,6 @@ impl Stringifier { } // Object or array — check for circular references. - // The call site is wired for fallible - // allocation (Err → OutOfMemory), but `zig_hash_map`'s grow path currently - // allocates infallibly and aborts on OOM, so the Err arm only becomes live - // once the collections-side grow is made fallible. let was_present = self.visiting.get_or_put(unwrapped).found_existing; if was_present { return Err(global diff --git a/src/runtime/api/JSTranspiler.rs b/src/runtime/api/JSTranspiler.rs index f4e90686ec11..f41be705aca3 100644 --- a/src/runtime/api/JSTranspiler.rs +++ b/src/runtime/api/JSTranspiler.rs @@ -132,19 +132,6 @@ fn level_from_js(global: &JSGlobalObject, value: JSValue) -> JsResult`, so an owned copy -/// is needed wherever the map is assigned by value. -fn clone_macro_map(src: &MacroMap) -> MacroMap { - let mut out = MacroMap::default(); - out.ensure_unused_capacity(src.count()); - for (k, v) in src.keys().iter().zip(src.values().iter()) { - // inner map: `StringArrayHashMap<&'static [u8]>` — `&[u8]: Clone` ⇒ inherent `clone()` works. - let inner = v.clone(); - out.put_assume_capacity(k, inner); - } - out -} - const PROP_ITER_OPTS: JSPropertyIteratorOptions = JSPropertyIteratorOptions { skip_empty_name: true, include_value: true, @@ -708,7 +695,7 @@ impl TransformTask { input_code, output_code: BunString::empty(), transpiler: transpiler_copy, - macro_map: clone_macro_map(&config.macro_map), + macro_map: config.macro_map.clone(), tsconfig: config .tsconfig .as_deref() @@ -786,7 +773,7 @@ impl TransformTask { let parse_options = ParseOptions { arena: arena_ref, - macro_remappings: clone_macro_map(&self.macro_map), + macro_remappings: self.macro_map.clone(), dirname_fd: bun_sys::Fd::INVALID, file_descriptor: None, loader: self.loader, @@ -1043,7 +1030,7 @@ impl JSTranspiler { } if config.macro_map.count() > 0 { - transpiler.options.macro_remap = clone_macro_map(&config.macro_map); + transpiler.options.macro_remap = config.macro_map.clone(); } // REPL mode disables DCE to preserve expressions like `42` @@ -1244,7 +1231,7 @@ impl JSTranspiler { let parse_options = ParseOptions { arena, - macro_remappings: clone_macro_map(&config.macro_map), + macro_remappings: config.macro_map.clone(), dirname_fd: bun_sys::Fd::INVALID, file_descriptor: None, loader: loader.unwrap_or(config.default_loader), diff --git a/src/runtime/bake/bake_body.rs b/src/runtime/bake/bake_body.rs index bc8aa2cfad48..8df4c7245327 100644 --- a/src/runtime/bake/bake_body.rs +++ b/src/runtime/bake/bake_body.rs @@ -477,6 +477,7 @@ impl Default for BuildConfigSubset { /// structure is always arena-allocated, usually owned by the arena in `UserOptions` /// /// Full documentation on these fields is located in the TypeScript definitions. +#[derive(Clone)] pub struct Framework { pub is_built_in_react: bool, /// `resolve()` rewrites this in place. Stored as an owned `Vec` so @@ -614,18 +615,6 @@ impl Framework { } } - /// `Framework.clone()` — manual because `ArrayHashMap` exposes a - /// fallible inherent `clone()` rather than `impl Clone`. - pub fn clone(&self) -> Framework { - Framework { - is_built_in_react: self.is_built_in_react, - file_system_router_types: self.file_system_router_types.clone(), - server_components: self.server_components, - react_fast_refresh: self.react_fast_refresh, - built_in_modules: self.built_in_modules.clone(), - } - } - pub fn add_react_install_command_note(log: &mut bun_ast::Log) -> crate::Result<()> { let clone_line_text = log.clone_line_text; log.add_msg(bun_ast::Msg { diff --git a/src/runtime/cli/build_command.rs b/src/runtime/cli/build_command.rs index f6bda7a8bdd3..abed953edb8f 100644 --- a/src/runtime/cli/build_command.rs +++ b/src/runtime/cli/build_command.rs @@ -507,7 +507,7 @@ impl BuildCommand { // perfect field-wise copy is not load-bearing. ct.options.target = bun_ast::Target::Browser; ct.options.server_components = true; - ct.options.conditions = this_transpiler.options.conditions.clone()?; + ct.options.conditions = this_transpiler.options.conditions.clone(); this_transpiler .options .conditions diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index a430c34da9f0..bee79dc73d05 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -2515,29 +2515,11 @@ fn transpile_source_code_inner( let macro_remappings = if macro_mode || !has_any_macro_remappings || is_node_override { bun_resolver::package_json::MacroMap::default() } else { - // Note: `MacroMap`'s value type - // (`StringArrayHashMap>`) has only the fallible - // `clone() -> Result<_, AllocError>` (no trait `Clone`), so - // the outer map can't be `clone()`d generically. Re-key - // shallowly here matching `bun_bundler::transpiler` and treat - // the inner OOM as a process-fatal alloc failure. // SAFETY: per fn contract — `jsc_vm` is the live per-thread // VM and `init_runtime_state` has already `ptr::write`n a // real `Transpiler` into `vm.transpiler` (the `options.jsx` / // `options.loaders` reads below depend on the same invariant). - let src = unsafe { &(*jsc_vm).transpiler.options.macro_remap }; - if src.is_empty() { - // Hot path: a module with no `--define`/`with { type: "macro" }` - // remappings skips the per-entry re-key + per-value fallible - // `clone()` entirely. - bun_resolver::package_json::MacroMap::default() - } else { - let mut m = bun_resolver::package_json::MacroMap::default(); - for (k, v) in src.iter() { - m.insert(k, v.clone()); - } - m - } + unsafe { (*jsc_vm).transpiler.options.macro_remap.clone() } }; let mut should_close_input_file_fd = true; From d74554a9e16a034ed207fc62213bae6073d2b881 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 15 Aug 2026 06:12:52 +0000 Subject: [PATCH 6/7] [autofix.ci] apply automated fixes --- src/codegen/cppbind.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/codegen/cppbind.ts b/src/codegen/cppbind.ts index 9ba8d19ed238..b800fb83a008 100644 --- a/src/codegen/cppbind.ts +++ b/src/codegen/cppbind.ts @@ -702,11 +702,7 @@ function generateRustFn(fn: CppFn, rustRaw: string[], rustWrap: string[]): void ` // SAFETY: \`[[ZIG_EXPORT(check_slow)]]\` extern; ref args are opaque-ZST handles valid for the call;`, ` // any raw-pointer args are forwarded under the wrapper's own \`unsafe fn\` contract.`, ...(ret === "()" - ? [ - ` unsafe { raw::${fn.name}(${callArgsStr}) };`, - ` __scope.return_if_exception()?;`, - ` Ok(())`, - ] + ? [` unsafe { raw::${fn.name}(${callArgsStr}) };`, ` __scope.return_if_exception()?;`, ` Ok(())`] : [ ` let __r = unsafe { raw::${fn.name}(${callArgsStr}) };`, ` __scope.return_if_exception()?;`, From 55a42d9659d58bec6a0fa3ea1bc58bd6140d58fd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 06:58:36 +0000 Subject: [PATCH 7/7] Collapse the ESMConditions rebuild and drop the last comments about discarded results ESMConditions derives Clone now, so BundleOptions::deep_clone can clone it directly. The remaining StringSet::insert callers no longer bind the bool, and the comments that explained discarding a Result from put, insert and append_slice are gone along with the Results. --- .../linker_context/computeCrossChunkDependencies.rs | 2 -- src/bundler/options.rs | 7 +------ src/http_jsc/websocket_client/WebSocketUpgradeClient.rs | 2 +- src/js_parser/parser.rs | 2 +- src/md/blocks.rs | 2 +- src/md/ref_defs.rs | 2 +- src/runtime/cli/test/ChangedFilesFilter.rs | 8 +++----- src/runtime/socket/socket_body.rs | 2 -- 8 files changed, 8 insertions(+), 19 deletions(-) diff --git a/src/bundler/linker_context/computeCrossChunkDependencies.rs b/src/bundler/linker_context/computeCrossChunkDependencies.rs index c12c4613755f..4013f6e6325d 100644 --- a/src/bundler/linker_context/computeCrossChunkDependencies.rs +++ b/src/bundler/linker_context/computeCrossChunkDependencies.rs @@ -299,7 +299,6 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { // Ensure "exports" is included if the current output format needs it // https://github.com/evanw/esbuild/blob/v0.27.2/internal/linker/linker.go#L1049-L1051 if flags.force_include_exports_for_entry_point { - // result intentionally discarded chunk_meta.imports.put( deps.exports_refs[chunk.entry_point.source_index() as usize], (), @@ -309,7 +308,6 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { // Include the wrapper if present // https://github.com/evanw/esbuild/blob/v0.27.2/internal/linker/linker.go#L1053-L1056 if flags.wrap != WrapKind::None { - // result intentionally discarded chunk_meta.imports.put( deps.wrapper_refs[chunk.entry_point.source_index() as usize], (), diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 2a53752ad23a..3d11f644df95 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -1421,12 +1421,7 @@ impl<'a> BundleOptions<'a> { rewrite_jest_for_tests: self.rewrite_jest_for_tests, macro_remap: self.macro_remap.clone(), no_macros: self.no_macros, - conditions: ESMConditions { - default: self.conditions.default.clone(), - import: self.conditions.import.clone(), - require: self.conditions.require.clone(), - style: self.conditions.style.clone(), - }, + conditions: self.conditions.clone(), tree_shaking: self.tree_shaking, tree_shaking_override: self.tree_shaking_override, code_splitting: self.code_splitting, diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index 2275b454fffe..f90be67ab284 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -351,7 +351,7 @@ impl HTTPClient { let mut subprotocols = StringSet::new(); let mut it = HeaderValueIterator::init(protocol_for_subprotocols); while let Some(protocol) = it.next() { - let _ = subprotocols.insert(protocol); // OOM-only Result + subprotocols.insert(protocol); } subprotocols }; diff --git a/src/js_parser/parser.rs b/src/js_parser/parser.rs index c5e28651f3b0..c15ffab3d6ac 100644 --- a/src/js_parser/parser.rs +++ b/src/js_parser/parser.rs @@ -350,7 +350,7 @@ pub mod Runtime { sorted.sort_unstable(); let mut set = StringSet::new(); for flag in sorted { - let _ = set.insert(flag); + set.insert(flag); } Some(Box::new(set)) } diff --git a/src/md/blocks.rs b/src/md/blocks.rs index 4802bfaaef08..2de3b1f463bf 100644 --- a/src/md/blocks.rs +++ b/src/md/blocks.rs @@ -970,7 +970,7 @@ impl Parser<'_> { // First definition wins let label = norm_label.into_boxed_slice(); if !self.ref_def_labels.contains(&label) { - let _ = self.ref_def_labels.insert(&label); + self.ref_def_labels.insert(&label); self.ref_defs.push(crate::ref_defs::RefDef { dest: dest_dupe, title: title_dupe, diff --git a/src/md/ref_defs.rs b/src/md/ref_defs.rs index 69d177e97e73..8972b6a0abbf 100644 --- a/src/md/ref_defs.rs +++ b/src/md/ref_defs.rs @@ -424,7 +424,7 @@ impl Parser<'_> { } let label = norm_label.into_boxed_slice(); if !self.ref_def_labels.contains(&label) { - let _ = self.ref_def_labels.insert(&label); + self.ref_def_labels.insert(&label); // Dupe dest and title since they point into self.buffer which gets reused let dest_dupe: Box<[u8]> = Box::from(result.dest); let title_dupe: Box<[u8]> = Box::from(result.title); diff --git a/src/runtime/cli/test/ChangedFilesFilter.rs b/src/runtime/cli/test/ChangedFilesFilter.rs index 5007a317b43a..09a5547754a2 100644 --- a/src/runtime/cli/test/ChangedFilesFilter.rs +++ b/src/runtime/cli/test/ChangedFilesFilter.rs @@ -422,7 +422,7 @@ fn consume_watch_trigger() -> Option { if !sys::exists(path) { continue; } - let _ = set.insert(path); // OOM-only Result + set.insert(path); } // If every triggering path was a deletion, fall back to git so the // user at least gets the same behaviour as the initial run rather @@ -645,10 +645,8 @@ fn append_paths(set: &mut StringSet, git_root: &[u8], stdout: &[u8]) { if !sys::exists(abs) { continue; } - // `StringSet.insert` dupes the key internally; abort on OOM rather - // than propagating so the set can never be left holding a pointer - // into our stack `buf` on the errdefer cleanup path. - let _ = set.insert(abs); // OOM-only Result + // `StringSet::insert` copies the key, so `abs` may point into our stack `buf`. + set.insert(abs); } } diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 0b8215c0f5f8..e85929a21c7f 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -2696,7 +2696,6 @@ impl NewSocket { } if !remaining_in_input_data.is_empty() { - // Result intentionally discarded self.buffered_data_for_node_net .with_mut(|b| b.append_slice(remaining_in_input_data)); } @@ -2707,7 +2706,6 @@ impl NewSocket { } // slower-path: clone the data, do one write. - // Result intentionally discarded self.buffered_data_for_node_net .with_mut(|b| b.append_slice(buffer.slice())); // R-2: `write_maybe_corked` takes `&self` and does not touch