diff --git a/Cargo.lock b/Cargo.lock index 6bd4f5d4c3fc..0278ef2535dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1462,6 +1462,7 @@ dependencies = [ "bun_options_types", "bun_paths", "bun_sourcemap", + "bun_url", "bun_wyhash", ] @@ -1659,6 +1660,7 @@ dependencies = [ "bun_alloc", "bun_collections", "bun_core", + "bun_opaque", "bun_paths", "bun_wyhash", "thiserror", diff --git a/src/CLAUDE.md b/src/CLAUDE.md index 2b8dcf031cea..e06f08760d01 100644 --- a/src/CLAUDE.md +++ b/src/CLAUDE.md @@ -7,7 +7,7 @@ bun_runtime` (driven by `scripts/build/rust.ts`). Key crates: - `bun_core` (`src/bun_core/`) — strings, formatting, logging, env vars, allocator/heap helpers, the foundation everything else uses - `bun_sys` (`src/sys/`) — cross-platform syscall wrappers (`File`, `Fd`, `Dir`, `Error`) - `bun_paths` (`src/paths/`) — path joining/normalization, the path-buffer pool -- `bun_jsc` (`src/jsc/`) — JSC value types, `Strong`/`Weak`, FFI imports, `URL` +- `bun_jsc` (`src/jsc/`) — JSC value types, `Strong`/`Weak`, FFI imports - `bun_runtime` (`src/runtime/`) — JS-visible APIs (server, fetch, node compat, crypto) - `bun_js_parser`, `bun_js_printer`, `bun_resolver`, `bun_bundler`, `bun_install`, `bun_collections`, `bun_threading`, `bun_alloc` — the rest of the pipeline - `bun_runtime::bin_entry` (`src/runtime/bin_entry/`) — the process entry point (`main`) and the @@ -83,6 +83,12 @@ match File::openat(Fd::cwd(), path, O::RDONLY, 0) { are single chars in Latin-1 but invalid UTF-8 — so converting either direction requires a real encoder, not a cast. +`String` owns one ref when WTF-backed: `Drop` derefs, `Clone` refs, it is +not `Copy`. Borrow with `&String` (or `StringView<'_>` when a by-value borrow +is needed). In an `extern "C"` signature a by-value `String` means ownership +crosses the boundary (C++ `Bun::toStringRef` return / `transferToWTFString()` +consumer); `&String` ⇔ `const BunString*`. + ```rust use bun_core::String; @@ -91,14 +97,20 @@ let s = String::borrow_utf8(utf8_bytes); // no copy; caller keeps slice alive let s = String::static_(b"literal"); // 'static slice, never freed let utf8: ZigStringSlice = s.to_utf8(); // ref-holding view; falls back to allocating a copy -let owned: Vec = s.to_utf8_bytes(); +let owned: Vec = s.to_owned_slice(); ``` +JSValue → string: `value.to_bun_string(global)?` (owned `String`), +`value.to_slice(global)?` (owned UTF-8 `ZigStringSlice`), or +`value.to_js_string_view(global)?` (borrowed `JSStringView` guard; derefs to +`&String` and keeps the `JSString` cell alive while it is in scope). + To/from JS values, use the `bun_jsc::StringJsc` extension trait: ```rust use bun_jsc::StringJsc; -let js: JSValue = s.to_js(global)?; +let js: JSValue = s.to_js(global)?; // JS takes its own ref; `s` still usable +let js: JSValue = s.into_js(global)?; // hands `s`'s ref to the JSString let s = bun_core::String::from_js(value, global)?; let err = s.to_error_instance(global); ``` @@ -157,28 +169,28 @@ let joined = resolve_path::join_string_buf::(&mut *buf, &[a, b] `bun_paths::os_path_buffer_pool` selects the wide (`u16`) variant on Windows and the narrow (`u8`) variant on POSIX. -## URL Parsing (`bun_jsc::URL`) +## URL Parsing (`bun_url::whatwg`) -WHATWG-compliant, backed by WebKit's URL parser. Returns `None` for invalid input. +WHATWG-compliant, backed by WebKit's URL parser. `Parsed` owns the C++ +`WTF::URL` (freed on `Drop`) and derefs to `URL` for the getters; parsing +returns `None` for invalid input. `bun_jsc::url` re-exports both; the +JS-value entry points (`URL::from_js` → `Option`, `URL::href_from_js`) +come from the `bun_jsc::URLJsc` trait. ```rust -use bun_jsc::URL; +use bun_url::whatwg::Parsed; -let url = URL::from_utf8(href)?; // Option> -// caller owns the C++ object — destroy it when done: -// unsafe { URL::destroy(url.as_ptr()) } +let url: Parsed = Parsed::from_utf8(href)?; // or Parsed::from_string(&bun_string)? url.protocol() // bun_core::String url.pathname() // bun_core::String url.host() // bun_core::String — the hostname WITHOUT the port (opposite of JS `host`!) +url.hostname() // bun_core::String — the host WITH the port (opposite of JS `hostname`!) url.port() // u32 (u32::MAX = unset; otherwise u16 range) ``` -`URL::href_from_js`, `URL::file_url_from_string`, `URL::path_from_file_url` -do whole-string conversions. The JSC-free shim `bun_url::whatwg::URL` exposes -`hostname()`, which returns the host WITH the port (also the opposite of JS -`hostname`) — so `bun_jsc::URL::host` and `bun_url::whatwg::URL::hostname` -are effectively swapped relative to their JS namesakes. +`bun_url::href_from_string`, `file_url_from_string`, `path_from_file_url`, +`join` do whole-string conversions. ## MIME Types (`bun_http_types::MimeType`) diff --git a/src/ast_jsc/lib.rs b/src/ast_jsc/lib.rs index 01bf2ea4adf9..939627dd2b30 100644 --- a/src/ast_jsc/lib.rs +++ b/src/ast_jsc/lib.rs @@ -80,7 +80,7 @@ pub fn log_to_js(this: &Log, global: &JSGlobalObject, message: &[u8]) -> JsResul pub fn log_to_js_aggregate_error( this: &Log, global: &JSGlobalObject, - message: bun_core::String, + message: &bun_core::String, ) -> JsResult { global.create_aggregate_error_with_array(message, log_to_js_array(this, global)?) } diff --git a/src/bun_core/lib.rs b/src/bun_core/lib.rs index 10909ef647f7..0301f8ae6eb4 100644 --- a/src/bun_core/lib.rs +++ b/src/bun_core/lib.rs @@ -54,9 +54,9 @@ pub mod string; pub use ::bstr::{BStr, BString, ByteSlice}; pub use string::string_joiner::StringJoiner; pub use string::{ - HashedString, MutableString, NodeEncoding, OwnedString, OwnedStringCell, - SliceWithUnderlyingString, SmolStr, String, StringBuilder, WTFStringImpl, WTFStringImplExt, - WTFStringImplStruct, ZigString, ZigStringSlice, + HashedString, MutableString, NodeEncoding, SliceWithUnderlyingString, SmolStr, String, + StringBuilder, StringView, WTFStringImpl, WTFStringImplExt, WTFStringImplStruct, ZigString, + ZigStringSlice, }; pub use string::{ STRING_ALLOCATION_LIMIT, ZigStringGithubActionFormatter, cheap_prefix_normalizer, diff --git a/src/bun_core/string/mod.rs b/src/bun_core/string/mod.rs index 496ee1f7802c..88dae31a3237 100644 --- a/src/bun_core/string/mod.rs +++ b/src/bun_core/string/mod.rs @@ -1,13 +1,9 @@ -//! `bun_core::string` (formerly the `bun_string` crate) — `bun.String` and -//! friends. +//! `bun_core::string` — `bun.String` and friends. //! //! `String` is the FFI-compatible 5-variant tagged union shared with C++ //! (`BunString` in `src/jsc/bindings/BunString.cpp`). `ZigString` is the //! pointer-tagged borrowed view; `ZigStringSlice` is the owned-or-borrowed //! UTF-8 byte slice. -//! -//! Merged into `bun_core` to break the `bun_core ↔ bun_string` dep edge; -//! the `bun_string` crate is now a thin re-export shim over this module. pub use crate::w; @@ -48,26 +44,32 @@ use core::sync::atomic::{AtomicUsize, Ordering}; pub use wtf::{WTFStringImpl, WTFStringImplExt, WTFStringImplStruct}; // ────────────────────────────────────────────────────────────────────────── -// `bun.String` — 5-variant tagged WTFString-or-ZigString. extern layout -// must match the C++ `BunString` in BunString.cpp, 24 bytes on 64-bit. +// `bun.String` — 5-variant tagged WTFString-or-ZigString, 24 bytes on 64-bit. +// +// Three types, one layout (all 24 bytes, identical ABI to C++ `BunString`): +// - `String`: OWNS one ref when WTF-backed. Not `Copy`. `Drop` = `deref()`, +// `Clone` = `ref()`; for the `ZigString`/`Static`/`Empty`/`Dead` tags both +// are a tag compare and nothing else. Every +1 producer returns this — +// including `extern "C"` declarations: a by-value `String` in an FFI +// signature means ownership crosses (C++ `Bun::toStringRef` return, or a +// Rust return that C++ `transferToWTFString()`s), exactly like `Box`. +// - `&String` is the borrow. `StringView<'a>` is the by-value borrow (C++ +// `Bun::toString`/`toStringView` results, property-iterator names, +// sub-slices of a WTF string). +// `bun_alloc::String` is the `Copy` POD underneath; nothing outside this +// module needs it. // ────────────────────────────────────────────────────────────────────────── -// Canonical layout lives in `bun_alloc` (T0 TYPE_ONLY landing for -// `bun.String`); re-exported so existing `bun_core::{Tag, StringImpl}` paths -// keep working. `String` is a `#[repr(transparent)]` newtype over -// `bun_alloc::String` so the FFI layout has ONE source of truth while this -// crate retains its inherent impl block (toJS/toUTF8/WTF refcounting). pub use bun_alloc::{StringImpl, Tag}; #[repr(transparent)] -#[derive(Clone, Copy)] -pub struct String(pub bun_alloc::String); +pub struct String(bun_alloc::String); // C++ mirror: `struct BunString { BunStringTag tag; BunStringImpl impl; }` // (`headers-handwritten.h`); returned **by value** from every `BunString__*` // FFI below, so size/align drift is silent ABI corruption. crate::assert_ffi_layout!(String, 24, 8); -// FFI surface from `src/jsc/bindings/BunString.cpp`. All return a fresh -// WTF-backed `String` with refcount = 1; caller must `deref()` (or transfer). +// FFI surface from `src/jsc/bindings/BunString.cpp`. Constructors return an +// owned +1 (declared `-> String`). unsafe extern "C" { fn BunString__fromBytes(bytes: *const u8, len: usize) -> String; fn BunString__fromLatin1(bytes: *const u8, len: usize) -> String; @@ -109,6 +111,11 @@ impl String { pub const EMPTY: Self = Self(bun_alloc::String::EMPTY); pub const DEAD: Self = Self(bun_alloc::String::DEAD); + #[inline] + fn into_raw(self) -> bun_alloc::String { + core::mem::ManuallyDrop::new(self).0 + } + #[inline] pub const fn empty() -> Self { Self::EMPTY @@ -205,14 +212,17 @@ impl String { }, }) } - /// Alias of `static_` for callers that spell it `static_str`. + /// `clone_utf8(other)`, unless `other` is byte-equal to `self`, in which + /// case another ref to `self`. #[inline] - pub fn static_str>(s: &'static S) -> Self { - Self::static_(s) + pub fn create_if_different(&self, other: &[u8]) -> Self { + if self.eql_utf8(other) { + return self.clone(); + } + Self::clone_utf8(other) } - /// `bun.String.cloneUTF8` — copies `s` into a fresh WTF::StringImpl - /// (refcount = 1). Caller must `deref()` or transfer ownership. + /// `bun.String.cloneUTF8` — copies `s` into a fresh WTF::StringImpl. pub fn clone_utf8(s: &[u8]) -> Self { if s.is_empty() { return Self::EMPTY; @@ -458,9 +468,8 @@ impl String { Self::clone_utf16(os_path) } } - /// `bun.String.init(WTFStringImpl)` / `WTFString.adopt` — wrap a raw - /// `*mut WTFStringImplStruct`, **adopting** the existing +1 ref (no inc). - /// Inverse of [`leak_wtf_impl`]. Null → `String::EMPTY`. + /// `WTF::adoptRef` — wrap a raw `*mut WTFStringImplStruct`, **adopting** + /// an existing +1 ref (no inc). Inverse of [`leak_wtf_impl`]. Null → `EMPTY`. #[inline] pub fn adopt_wtf_impl(wtf: WTFStringImpl) -> Self { if wtf.is_null() { @@ -473,13 +482,23 @@ impl String { }, }) } + /// `WTF::RefPtr(ptr)` — wrap a raw `*mut WTFStringImplStruct` someone else + /// keeps alive, taking a **new** ref for the returned `String`. + #[inline] + pub fn retain_wtf_impl(wtf: WTFStringImpl) -> Self { + let s = Self::adopt_wtf_impl(wtf); + s.ref_(); + s + } /// Extract the raw `*mut WTFStringImplStruct` /// from a WTF-backed string, transferring ownership of the +1 ref to the caller. Returns /// null for non-WTF tags. Used by SQL data-cell paths that hand the impl pointer to C++. #[inline] pub fn leak_wtf_impl(self) -> WTFStringImpl { - if self.0.tag == Tag::WTFStringImpl { - self.wtf_ptr() + let raw = self.into_raw(); + if raw.tag == Tag::WTFStringImpl { + // SAFETY: tag checked. + unsafe { raw.value.wtf_string_impl } } else { core::ptr::null_mut() } @@ -508,26 +527,18 @@ impl String { } } - /// `String.ref()` — increment WTF refcount; no-op for other tags. #[inline] - pub fn ref_(&self) { + fn ref_(&self) { if self.0.tag == Tag::WTFStringImpl { self.as_wtf().r#ref() } } - /// `String.deref()` — decrement WTF refcount; no-op for other tags. #[inline] - pub fn deref(&self) { + fn deref(&self) { if self.0.tag == Tag::WTFStringImpl { self.as_wtf().deref() } } - /// `String.dupeRef()` — copy + ref. - #[inline] - pub fn dupe_ref(&self) -> Self { - self.ref_(); - *self - } #[inline] pub fn length(&self) -> usize { @@ -630,45 +641,40 @@ impl String { } } - /// `bun.String.trunc` — clamp to `len` code units. The - /// returned `String` borrows the same storage; for `WTFStringImpl` this - /// downgrades to a `ZigString` view (no ref taken), so the original must - /// outlive the result. - pub fn trunc(&self, len: usize) -> String { + /// `bun.String.trunc` — clamp to `len` code units. Borrows `self`'s + /// storage; for `WTFStringImpl` longer than `len` this is a `ZigString` + /// view into the impl's buffer. + #[inline] + pub fn trunc(&self, len: usize) -> StringView<'_> { if self.length() <= len { - // No refcount bump: `String` is `Copy` here (POD #[repr(C)]), so a - // plain copy preserves the borrow semantics. - return *self; + return StringView::new(self); } - String::init(self.to_zig_string().trunc(len)) + StringView::from_zig(self.to_zig_string().trunc(len)) } - /// `bun.String.substring` — borrowed slice from `start_index` - /// to end. The returned `String` borrows the same underlying storage; for - /// `WTFStringImpl` this downgrades to a `ZigString` view (no ref taken), so - /// the original must outlive the result. - pub fn substring(&self, start_index: usize) -> String { + /// `bun.String.substring` — borrowed slice from `start_index` to end. + pub fn substring(&self, start_index: usize) -> StringView<'_> { let len = self.length(); self.substring_with_len(start_index.min(len), len) } /// `bun.String.substringWithLen`. - pub fn substring_with_len(&self, start_index: usize, end_index: usize) -> String { + pub fn substring_with_len(&self, start_index: usize, end_index: usize) -> StringView<'_> { match self.0.tag { Tag::ZigString | Tag::StaticZigString => { - String::init(self.as_zig().substring_with_len(start_index, end_index)) + StringView::from_zig(self.as_zig().substring_with_len(start_index, end_index)) } Tag::WTFStringImpl => { let w = self.as_wtf(); if w.is_8bit() { - String::init(ZigString::init(&w.latin1_slice()[start_index..end_index])) + StringView::from_zig(ZigString::init(&w.latin1_slice()[start_index..end_index])) } else { - String::init(ZigString::init_utf16( + StringView::from_zig(ZigString::init_utf16( &w.utf16_slice()[start_index..end_index], )) } } - _ => *self, + _ => StringView::new(self), } } @@ -693,6 +699,32 @@ impl String { _ => ZigStringSlice::EMPTY, } } + /// Consuming [`to_utf8`]: moves `self`'s ref into the slice instead of + /// taking another, and copies a borrowed `ZigString` so the result never + /// depends on `self`'s backing. + /// + /// [`to_utf8`]: Self::to_utf8 + pub fn into_utf8(self) -> ZigStringSlice { + match self.0.tag { + Tag::WTFStringImpl => { + let wtf = self.as_wtf(); + if !wtf.is_8bit() { + return ZigStringSlice::init_owned(strings::to_utf8_alloc(wtf.utf16_slice())); + } + if let Some(utf8) = strings::to_utf8_from_latin1(wtf.latin1_slice()) { + return ZigStringSlice::init_owned(utf8); + } + let bytes = RawSlice::new(wtf.latin1_slice()); + ZigStringSlice::WTF { + string_impl: self.leak_wtf_impl(), + bytes, + } + } + Tag::ZigString => self.as_zig().to_slice().clone_if_borrowed(), + Tag::StaticZigString => ZigStringSlice::from_utf8_never_free(self.as_zig().slice()), + _ => ZigStringSlice::EMPTY, + } + } /// Like [`to_utf8`] but, for the 8-bit all-ASCII `WTFStringImpl` fast path, /// returns a non-owning [`ZigStringSlice::WtfBorrowed`] view instead of /// [`to_utf8`]'s ref-holding [`ZigStringSlice::WTF`] — skipping the @@ -700,11 +732,11 @@ impl String { /// /// The returned slice borrows the impl's buffer, so it is only safe to pair /// with a value whose `underlying` keeps the impl alive (e.g. the - /// [`SliceWithUnderlyingString`] returned by [`to_slice`]). All other tags + /// [`SliceWithUnderlyingString`] returned by [`into_slice`]). All other tags /// behave exactly like [`to_utf8`] / [`to_utf8_without_ref`]. /// /// [`to_utf8`]: Self::to_utf8 - /// [`to_slice`]: Self::to_slice + /// [`into_slice`]: Self::into_slice #[inline] pub(crate) fn to_utf8_borrowed(&self) -> ZigStringSlice { match self.0.tag { @@ -743,7 +775,7 @@ impl String { } } pub fn to_owned_slice(&self) -> Vec { - self.to_utf8().into_vec() + self.to_utf8_without_ref().into_vec() } pub fn eql_utf8(&self, other: &[u8]) -> bool { @@ -788,29 +820,6 @@ impl String { Self::init(ZigString::from_bytes(value)) } - /// `bun.String.clone` — produce an owned, WTF-backed copy of `self`. - /// WTF-backed inputs just bump the refcount; ZigString inputs are copied - /// into a fresh WTF::StringImpl. - pub fn clone(&self) -> Self { - if self.0.tag == Tag::WTFStringImpl { - return self.dupe_ref(); - } - if self.is_empty() { - return Self::EMPTY; - } - if self.is_utf16() { - let len = self.length(); - let (new, chars) = Self::create_uninitialized_utf16(len); - if new.0.tag != Tag::Dead { - // SAFETY: tag ≠ WTFStringImpl is excluded above so - // `value.zig_string` is the active variant. - chars.copy_from_slice(self.as_zig().utf16_slice()); - } - return new; - } - Self::clone_utf8(self.byte_slice()) - } - /// `bun.String.toZigString` — borrow as a `ZigString` (no ref taken). pub fn to_zig_string(&self) -> ZigString { match self.0.tag { @@ -944,22 +953,9 @@ impl String { self.as_zig().slice() } - /// `bun.String.toUTF8Owned` — like [`to_utf8_without_ref`] but guarantees - /// the returned slice owns its buffer. - pub(crate) fn to_utf8_owned(&self) -> ZigStringSlice { - self.to_utf8_without_ref().clone_if_borrowed() - } - - /// `bun.String.toUTF8Bytes` — owned `Vec` of `self` as UTF-8. + /// `bun.String.toSlice` — consume `self` into a [`SliceWithUnderlyingString`]. #[inline] - pub fn to_utf8_bytes(&self) -> Vec { - self.to_utf8_owned().into_vec() - } - - /// `bun.String.toSlice` — consume `self` into a - /// [`SliceWithUnderlyingString`], leaving `self` as [`EMPTY`]. - #[inline] - pub fn to_slice(&mut self) -> SliceWithUnderlyingString { + pub fn into_slice(self) -> SliceWithUnderlyingString { // Move our ref into `underlying` first, then derive the UTF-8 view as a // *borrow* of that already-pinned impl: the ref-holding `to_utf8()` / // `ZigStringSlice::WTF` variant would be a redundant second handle on @@ -967,19 +963,18 @@ impl String { // `deref` on `deinit`). `WtfBorrowed` keeps the impl pointer so // `SliceWithUnderlyingString::to_thread_safe` can still re-derive after // a thread-safe migration. - let underlying = core::mem::replace(self, Self::EMPTY); - let utf8 = underlying.to_utf8_borrowed(); + let utf8 = self.to_utf8_borrowed(); SliceWithUnderlyingString { utf8, - underlying, + underlying: self, #[cfg(debug_assertions)] did_report_extra_memory_debug: false, } } - /// `bun.String.toThreadSafeSlice` — like [`to_slice`] but + /// `bun.String.toThreadSafeSlice` — like [`into_slice`] but /// guarantees the resulting buffer is safe to send to another thread. - pub fn to_thread_safe_slice(&mut self) -> SliceWithUnderlyingString { + pub fn into_thread_safe_slice(self) -> SliceWithUnderlyingString { if self.0.tag == Tag::WTFStringImpl { let wtf = self.as_wtf(); let slice = wtf.to_utf8_without_ref(); @@ -999,11 +994,10 @@ impl String { // ref would be redundant since `underlying` already keeps the impl // alive. if let ZigStringSlice::Static(bytes) = slice { - self.ref_(); let string_impl = self.wtf_ptr(); return SliceWithUnderlyingString { utf8: ZigStringSlice::WtfBorrowed { string_impl, bytes }, - underlying: *self, + underlying: self, #[cfg(debug_assertions)] did_report_extra_memory_debug: false, }; @@ -1016,7 +1010,7 @@ impl String { did_report_extra_memory_debug: false, }; } - self.to_slice() + self.into_slice() } /// `bun.String.charAt` — code unit at `index`, widened to @@ -1058,7 +1052,7 @@ impl String { } } - // `to_js` / `transfer_to_js` / `create_utf8_for_js` are tier-6 (jsc) — the + // `to_js` / `into_js` / `create_utf8_for_js` are tier-6 (jsc) — the // *_jsc alias pattern: deleted here per PORTING.md, defined as inherent // free fns / extension trait in `bun_jsc::string` (would otherwise create // a `bun_string ↔ bun_jsc` dependency cycle). @@ -1111,21 +1105,6 @@ impl From<&[u16]> for String { Self::from(ZigString::from16_slice(s)) } } -/// `WTFStringImpl` arm of `bun.String.init` — wrap an existing -/// `*WTFStringImplStruct` without touching its refcount. -impl From for String { - #[inline] - fn from(wtf: WTFStringImpl) -> Self { - debug_assert!(!wtf.is_null()); - Self(bun_alloc::String { - tag: Tag::WTFStringImpl, - value: StringImpl { - wtf_string_impl: wtf, - }, - }) - } -} - impl crate::OptionsEnvArg for String { #[inline] fn from_slice(s: &[u8]) -> Self { @@ -1164,94 +1143,94 @@ unsafe impl Send for String {} // `is_thread_safe()`; non-WTF tags are inert and trivially `Sync`. unsafe impl Sync for String {} -// ────────────────────────────────────────────────────────────────────────── -// `OwnedString` — RAII `defer s.deref()`. -// -// `String` is intentionally `#[derive(Copy)]` so it stays bit-identical to the -// C++ `BunString` for FFI by-value passing. That precludes -// `impl Drop for String`. Instead, sites that -// receive a +1 ref (any `clone*`/`create*`/`to_bun_string` constructor) wrap -// it in `OwnedString` to get scope-exit `deref()`. -// -// Prefer this over ad-hoc `scopeguard::guard(s, |s| s.deref())` so the -// pattern is greppable and `?`-early-returns can't skip the release. -// ────────────────────────────────────────────────────────────────────────── -#[repr(transparent)] -pub struct OwnedString(String); - -impl OwnedString { - #[inline] - pub const fn new(s: String) -> Self { - Self(s) - } - /// Disarm: return the inner `String` without `deref()`ing it (transfers - /// the +1 to the caller). +impl Drop for String { #[inline] - pub fn into_inner(self) -> String { - core::mem::ManuallyDrop::new(self).0 + fn drop(&mut self) { + self.deref(); } - /// Borrow the inner `String` by value (it's `Copy`) without bumping the - /// refcount. Do NOT `deref()` the result. +} +impl Clone for String { + /// +1 on the same `WTF::StringImpl` (bitwise for the non-WTF tags). #[inline] - pub fn get(&self) -> String { - self.0 + fn clone(&self) -> Self { + self.ref_(); + Self(self.0) } - /// View `&[OwnedString]` as `&[String]` for FFI sites that take a raw - /// `*const BunString` array (e.g. `BunString__createArray`). Sound because - /// `OwnedString` is `#[repr(transparent)]` over `String`; the borrow keeps - /// every element alive for the call, and `Drop` still runs on the owning - /// slice afterwards. +} + +// ────────────────────────────────────────────────────────────────────────── +// `StringView<'a>` — a by-value *borrow* of a `String`. Holds the same 24 +// bytes but never owns a ref; the lifetime ties it to the `String` (or byte +// slice) it was derived from. Derefs to `&String`. +// ────────────────────────────────────────────────────────────────────────── +#[repr(transparent)] +pub struct StringView<'a>( + core::mem::ManuallyDrop, + core::marker::PhantomData<&'a String>, +); + +impl<'a> StringView<'a> { + pub const EMPTY: StringView<'static> = StringView( + core::mem::ManuallyDrop::new(String::EMPTY), + core::marker::PhantomData, + ); + pub const DEAD: StringView<'static> = StringView( + core::mem::ManuallyDrop::new(String::DEAD), + core::marker::PhantomData, + ); + #[inline] - pub fn as_raw_slice(owned: &[OwnedString]) -> &[String] { - // `#[repr(transparent)]` over `String` ⇒ bytemuck's safe slice peel. - >::peel_slice(owned) + pub fn new(s: &'a String) -> Self { + Self( + core::mem::ManuallyDrop::new(String(s.0)), + core::marker::PhantomData, + ) } -} -// SAFETY: `OwnedString` is `#[repr(transparent)]` with a single `String` field. -unsafe impl bytemuck::TransparentWrapper for OwnedString {} -impl core::ops::Deref for OwnedString { - type Target = String; + /// Borrow `bytes` (no copy); scans and tags UTF-8 if any byte is non-ASCII. #[inline] - fn deref(&self) -> &String { - &self.0 + pub fn from_bytes(bytes: &'a [u8]) -> Self { + Self::from_zig(ZigString::from_bytes(bytes)) } -} -impl core::ops::DerefMut for OwnedString { + /// Borrow `bytes` as UTF-8 (no copy, no scan). #[inline] - fn deref_mut(&mut self) -> &mut String { - &mut self.0 + pub fn borrow_utf8(bytes: &'a [u8]) -> Self { + Self::from_zig(ZigString::init_utf8(bytes)) } -} -impl Drop for OwnedString { + /// `'static` ASCII/Latin-1 literal (no scan). #[inline] - fn drop(&mut self) { - self.0.deref(); + pub fn static_>(s: &'static S) -> StringView<'static> { + StringView( + core::mem::ManuallyDrop::new(String::static_(s)), + core::marker::PhantomData, + ) } -} -impl From for OwnedString { #[inline] - fn from(s: String) -> Self { - Self(s) + fn from_zig(z: ZigString) -> Self { + Self( + core::mem::ManuallyDrop::new(String::wrap_zig(Tag::ZigString, z)), + core::marker::PhantomData, + ) } } -impl Default for OwnedString { +impl StringView<'_> { + /// UTF-8 bytes of the view. Unlike [`String::to_utf8`] this never takes a + /// ref (a view owns nothing); borrows for ASCII, allocates otherwise. #[inline] - fn default() -> Self { - Self(String::EMPTY) + pub fn to_utf8(&self) -> ZigStringSlice { + self.0.to_utf8_without_ref() } } -impl Clone for OwnedString { - /// Bumps the WTF refcount (or copies a `ZigString` into a fresh - /// WTF::StringImpl) and wraps the resulting +1 in a new `OwnedString`. +impl core::ops::Deref for StringView<'_> { + type Target = String; #[inline] - fn clone(&self) -> Self { - Self(self.0.clone()) + fn deref(&self) -> &String { + &self.0 } } -impl core::fmt::Display for OwnedString { +impl core::fmt::Display for StringView<'_> { #[inline] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - core::fmt::Display::fmt(&self.0, f) + core::fmt::Display::fmt(&**self, f) } } @@ -1730,7 +1709,7 @@ pub enum ZigStringSlice { /// can promote it to an owning [`Self::WTF`]. Drop is a no-op. Produced by /// [`String::to_utf8_borrowed`] — it avoids the redundant `ref`/`deref` /// pair that the ref-holding `WTF` variant would cost on the - /// `String::to_slice` hot path. + /// `String::into_slice` hot path. /// /// [`clone_ref`]: ZigStringSlice::clone_ref WtfBorrowed { @@ -1837,7 +1816,7 @@ impl SliceWithUnderlyingString { pub fn dupe_ref(&self) -> SliceWithUnderlyingString { SliceWithUnderlyingString { utf8: ZigStringSlice::EMPTY, - underlying: self.underlying.dupe_ref(), + underlying: self.underlying.clone(), #[cfg(debug_assertions)] did_report_extra_memory_debug: false, } @@ -1849,14 +1828,6 @@ impl SliceWithUnderlyingString { self.utf8.slice() } - /// `deinit` — release `utf8`'s allocation (if any) and deref `underlying`. - /// `Drop` is intentionally not implemented because `underlying: String` - /// is `Copy`. - pub fn deinit(self) { - // `utf8` drops via ZigStringSlice::Drop. - self.underlying.deref(); - } - /// `toThreadSafe` — if `underlying` is WTF-backed, migrate it to a /// thread-safe impl and re-derive `utf8` if it was a ref-counted view /// into the old impl. @@ -2362,51 +2333,3 @@ pub fn cheap_prefix_normalizer<'a>(prefix: &'a [u8], suffix: &'a [u8]) -> [&'a [ // Re-export `wtf::parse_double` at crate root (callers spell it `bun_core::parse_double`). pub use wtf::parse_double; - -/// [`Cell`]-shaped interior-mutable owned `BunString` slot. Layout-identical -/// to `Cell` (`#[repr(transparent)]`) so it's a drop-in field -/// replacement in `#[repr(C)]` FFI structs (`Blob.name`, `Request.url`). -/// -/// Unlike `Cell`, [`set`] derefs the previous value and [`replace`] -/// returns an [`OwnedString`] — so the only way to leak a refcount is to -/// `mem::forget` the cell or its `replace` result. The R-2 `&self` migrations -/// introduced `Cell::set(..)` calls that silently leaked the old +1. -/// -/// [`get`] returns a bitwise `String` copy with **borrow** semantics (no ref -/// bump). Do NOT `.deref()` the returned value. -#[repr(transparent)] -#[derive(Default)] -pub struct OwnedStringCell(core::cell::Cell); - -impl OwnedStringCell { - #[inline] - pub const fn new(s: String) -> Self { - Self(core::cell::Cell::new(s)) - } - #[inline] - pub fn get(&self) -> String { - self.0.get() - } - #[inline] - pub fn set(&self, new: String) { - self.0.replace(new).deref(); - } - #[inline] - pub fn replace(&self, new: String) -> OwnedString { - OwnedString(self.0.replace(new)) - } -} - -impl Drop for OwnedStringCell { - #[inline] - fn drop(&mut self) { - self.0.get_mut().deref(); - } -} - -impl Clone for OwnedStringCell { - #[inline] - fn clone(&self) -> Self { - Self::new(self.0.get().dupe_ref()) - } -} diff --git a/src/bundler/analyze_transpiled_module.rs b/src/bundler/analyze_transpiled_module.rs index 7e99878e1e6f..56cd2eda88df 100644 --- a/src/bundler/analyze_transpiled_module.rs +++ b/src/bundler/analyze_transpiled_module.rs @@ -162,11 +162,23 @@ pub enum Owner { ModuleInfo(*mut ModuleInfo), AllocatedSlice { /// [`MODULE_INFO_ALIGN`]-aligned heap slice from [`dupe_aligned`]; - /// freed in `deinit` via [`free_aligned_dup`]. + /// freed via [`free_aligned_dup`]. slice: *mut [u8], }, } +impl Drop for ModuleInfoDeserialized { + fn drop(&mut self) { + // SAFETY: `owner` is the unique owner of its allocation (see `Owner`). + unsafe { + match self.owner { + Owner::ModuleInfo(mi) => drop(bun_core::heap::take(mi)), + Owner::AllocatedSlice { slice } => free_aligned_dup(slice), + } + } + } +} + impl ModuleInfoDeserialized { // ── safe accessors ─────────────────────────────────────────────────── // All slice fields are non-null self-referential views into `self.owner` @@ -209,29 +221,14 @@ impl ModuleInfoDeserialized { self.record_kinds.slice() } - /// Consumes the heap allocation containing `self` (and, for - /// `Owner::ModuleInfo`, the enclosing `ModuleInfo`). Not `Drop` because it - /// deallocates the object itself and is invoked across FFI on a raw `*mut`. + /// Consumes the heap allocation containing `self`. /// /// # Safety /// `this` must have been produced by [`Self::create`] (heap box) or by /// [`ModuleInfoExt::into_deserialized`]. pub(crate) unsafe fn deinit(this: *mut ModuleInfoDeserialized) { // SAFETY: caller contract — see fn doc above. - unsafe { - match (*this).owner { - Owner::ModuleInfo(mi) => { - // The `*mut ModuleInfo` is stored directly because the printer - // crate's `ModuleInfo` no longer embeds this struct. - drop(bun_core::heap::take(mi)); - drop(bun_core::heap::take(this)); - } - Owner::AllocatedSlice { slice } => { - free_aligned_dup(slice); - drop(bun_core::heap::take(this)); - } - } - } + drop(unsafe { bun_core::heap::take(this) }); } #[inline] diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index 97cd0b348178..30bcbcb35d8f 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -1408,7 +1408,7 @@ pub mod bv2_impl { safe fn __bun_jsc_generate_cached_bytecode( format: crate::options_impl::Format, source: &[u8], - source_provider_url: &mut bun_core::String, + source_provider_url: &bun_core::String, ) -> Option>; } @@ -1446,7 +1446,7 @@ pub mod bv2_impl { pub(crate) fn generate_cached_bytecode( format: crate::options_impl::Format, source: &[u8], - source_provider_url: &mut bun_core::String, + source_provider_url: &bun_core::String, ) -> Option> { __bun_jsc_generate_cached_bytecode(format, source, source_provider_url) } diff --git a/src/bundler/linker_context/generateChunksInParallel.rs b/src/bundler/linker_context/generateChunksInParallel.rs index 762048412283..624581d971d8 100644 --- a/src/bundler/linker_context/generateChunksInParallel.rs +++ b/src/bundler/linker_context/generateChunksInParallel.rs @@ -1053,16 +1053,11 @@ pub(crate) fn generate_chunks_in_parallel( BYTECODE_EXTENSION )) }; - source_provider_url.ref_(); - // RAII: `defer source_provider_url.deref()` — `OwnedString::Drop` - // releases the ref bumped above on every exit path (incl. `break 'brk`). - let mut source_provider_url = - bun_core::OwnedString::new(source_provider_url); if let Some(bytecode) = crate::bundle_v2::dispatch::generate_cached_bytecode( c.options.output_format, &code_result.buffer, - &mut source_provider_url, + &source_provider_url, ) { let source_provider_url_str = source_provider_url.to_utf8(); debug!( diff --git a/src/bundler/linker_context/writeOutputFilesToDisk.rs b/src/bundler/linker_context/writeOutputFilesToDisk.rs index 7fc1deed29db..312dc97ce149 100644 --- a/src/bundler/linker_context/writeOutputFilesToDisk.rs +++ b/src/bundler/linker_context/writeOutputFilesToDisk.rs @@ -400,14 +400,11 @@ pub(crate) fn write_output_files_to_disk( bstr::BStr::new(&chunk.final_rel_path), BYTECODE_EXTENSION, )); - source_provider_url.ref_(); - // `defer source_provider_url.deref()` handled by Drop on OwnedString. - let mut source_provider_url = bun_core::OwnedString::new(source_provider_url); if let Some(bytecode) = crate::bundle_v2::dispatch::generate_cached_bytecode( c.options.output_format, &code_result.buffer, - &mut source_provider_url, + &source_provider_url, ) { let source_provider_url_str = source_provider_url.to_utf8(); debug!( diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index 2bf15e34c745..d9a670faaaf4 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -869,6 +869,12 @@ impl AlreadyBundled { AlreadyBundled::SourceCodeCjs | AlreadyBundled::BytecodeCjs(_) ) } + pub fn into_bytecode(self) -> Box<[u8]> { + match self { + AlreadyBundled::Bytecode(bytes) | AlreadyBundled::BytecodeCjs(bytes) => bytes, + _ => Box::default(), + } + } } /// Output of the transpiler's parse step: the parsed AST plus its source and diff --git a/src/bundler_jsc/options_jsc.rs b/src/bundler_jsc/options_jsc.rs index ea381ce971b6..95d698793939 100644 --- a/src/bundler_jsc/options_jsc.rs +++ b/src/bundler_jsc/options_jsc.rs @@ -3,7 +3,6 @@ // `bun_bundler::options` re-exports `Target`/`Loader` but not `Format`; pull it // from the lower-tier source crate directly. -use bun_core::ZigString; use bun_jsc::ComptimeStringMapExt as _; use bun_options_types::compile_target::CompileTarget; @@ -31,13 +30,12 @@ pub fn loader_from_js( return Err(global.throw_invalid_arguments(format_args!("loader must be a string"))); } - let mut zig_str = ZigString::init(b""); - loader.to_zig_string(&mut zig_str, global)?; - if zig_str.len == 0 { + let loader_str = loader.to_js_string_view(global)?; + if loader_str.is_empty() { return Ok(None); } - let slice = zig_str.to_slice(); + let slice = loader_str.to_utf8(); let Some(v) = bun_ast::Loader::from_string(slice.slice()) else { return Err(global.throw_invalid_arguments(format_args!( diff --git a/src/bundler_jsc/source_map_mode_jsc.rs b/src/bundler_jsc/source_map_mode_jsc.rs index 77f025b5b221..fca2e6c405a2 100644 --- a/src/bundler_jsc/source_map_mode_jsc.rs +++ b/src/bundler_jsc/source_map_mode_jsc.rs @@ -9,7 +9,7 @@ pub fn source_map_mode_from_js( value: JSValue, ) -> JsResult> { if value.is_string() { - let str = value.to_slice_or_null(global)?; + let str = value.to_slice(global)?; let utf8 = str.slice(); if utf8 == b"none" { return Ok(Some(SourceMapMode::None)); diff --git a/src/css_jsc/color_js.rs b/src/css_jsc/color_js.rs index cd57596c9621..e8f69db1959e 100644 --- a/src/css_jsc/color_js.rs +++ b/src/css_jsc/color_js.rs @@ -365,7 +365,7 @@ pub fn js_function_color(global: &JSGlobalObject, frame: &CallFrame) -> JsResult }; 'formatted: { - let mut str: BunString = 'color: { + let str: BunString = 'color: { match format { // resolved above. OutputColorFormat::Ansi => unreachable!(), @@ -594,7 +594,7 @@ pub fn js_function_color(global: &JSGlobalObject, frame: &CallFrame) -> JsResult } }; - return str.transfer_to_js(global); + return str.into_js(global); } // Fallback to CSS string output diff --git a/src/css_jsc/css_internals.rs b/src/css_jsc/css_internals.rs index 9150d19da14a..2aa2a122a1d1 100644 --- a/src/css_jsc/css_internals.rs +++ b/src/css_jsc/css_internals.rs @@ -1,6 +1,6 @@ use bun_alloc::Arena; // bumpalo::Bump re-export use bun_ast::Log; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_css::targets::{Browsers, Targets}; use bun_jsc::{CallFrame, JSGlobalObject, JSValue}; @@ -61,8 +61,8 @@ pub fn _test(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { /// Shared arg-validation for the test-only CSS internals: pulls the next arg, /// throws "{fn_name}: expected {expected_n} arguments, got {got_n}" if absent, /// throws "{fn_name}: expected {arg_label} to be a string" if not a string, -/// otherwise returns the +1-ref BunString wrapped in `OwnedString` for RAII deref. -/// Caller does `.to_utf8()` (borrows the OwnedString, so can't be returned here). +/// otherwise returns the +1-ref `bun_core::String`. +/// Caller does `.to_utf8()` (borrows the bun_core::String, so can't be returned here). fn eat_string_arg( arguments: &mut bun_jsc::ArgumentsSlice<'_>, global: &JSGlobalObject, @@ -70,7 +70,7 @@ fn eat_string_arg( expected_n: u32, got_n: u32, arg_label: &str, -) -> JsResult { +) -> JsResult { let Some(arg) = arguments.next_eat() else { return Err(global.throw(format_args!( "{fn_name}: expected {expected_n} arguments, got {got_n}" @@ -81,7 +81,7 @@ fn eat_string_arg( "{fn_name}: expected {arg_label} to be a string" ))); } - Ok(OwnedString::new(arg.to_bun_string(global)?)) + arg.to_bun_string(global) } fn testing_impl( @@ -238,8 +238,7 @@ fn parser_options_from_js( if val.is_array() { let mut iter = val.array_iterator(global)?; while let Some(item) = iter.next()? { - // `OwnedString` releases the +1 ref at the end of each iteration. - let bunstr = OwnedString::new(item.to_bun_string(global)?); + let bunstr = item.to_bun_string(global)?; let str = bunstr.to_utf8(); if str.slice() == b"DEEP_SELECTOR_COMBINATOR" { opts.flags |= bun_css::ParserFlags::DEEP_SELECTOR_COMBINATOR; diff --git a/src/css_jsc/error_jsc.rs b/src/css_jsc/error_jsc.rs index 09e85ff7050a..37711f023240 100644 --- a/src/css_jsc/error_jsc.rs +++ b/src/css_jsc/error_jsc.rs @@ -17,9 +17,6 @@ where T: Display, { let str = BunString::create_format(format_args!("{}", this.kind)); - // `to_error_instance` consumes the caller's reference (it derefs the string - // itself), so the `+1` from `create_format` must not be dropped again here — - // an extra deref frees the WTFStringImpl while the error still uses it. let js = bun_jsc::bun_string_jsc::to_error_instance(&str, global_this); Ok(js) } diff --git a/src/http/lib.rs b/src/http/lib.rs index 0b163fa7128e..894be820d6ac 100644 --- a/src/http/lib.rs +++ b/src/http/lib.rs @@ -997,7 +997,7 @@ use bun_boringssl as boringssl; use bun_collections::{ArrayHashMap, VecExt}; use bun_core::StringBuilder; use bun_core::{FeatureFlags, Global, Output}; -use bun_core::{OwnedString, String as BunString, Tag as BunStringTag, strings}; +use bun_core::{String as BunString, Tag as BunStringTag, strings}; use bun_http_types::ETag::StringPointer; use bun_uws as uws; // the std Wyhash algorithm, not Wyhash11. @@ -5085,7 +5085,7 @@ impl<'a> HTTPClient<'a> { debug_assert!(string_builder.cap == string_builder.len); let input = BunString::borrow_utf8(string_builder.allocated_slice()); - let normalized_url = OwnedString::new(bun_url::href_from_string(&input)); + let normalized_url = bun_url::href_from_string(&input); if normalized_url.tag() == BunStringTag::Dead { // URL__getHref failed, dont pass dead tagged string to toOwnedSlice. return Err(crate::Error::RedirectURLInvalid); @@ -5141,7 +5141,7 @@ impl<'a> HTTPClient<'a> { debug_assert!(string_builder.cap == string_builder.len); let input = BunString::borrow_utf8(string_builder.allocated_slice()); - let normalized_url = OwnedString::new(bun_url::href_from_string(&input)); + let normalized_url = bun_url::href_from_string(&input); if normalized_url.tag() == BunStringTag::Dead { return Err(crate::Error::RedirectURLInvalid); } @@ -5165,7 +5165,7 @@ impl<'a> HTTPClient<'a> { let base = BunString::borrow_utf8(original_url.href); let rel = BunString::borrow_utf8(location); - let new_url_ = OwnedString::new(bun_url::join(&base, &rel)); + let new_url_ = bun_url::join(&base, &rel); if new_url_.is_empty() { return Err(crate::Error::InvalidRedirectURL); diff --git a/src/http_jsc/method_jsc.rs b/src/http_jsc/method_jsc.rs index d87979689677..f4ca5ac88823 100644 --- a/src/http_jsc/method_jsc.rs +++ b/src/http_jsc/method_jsc.rs @@ -1,6 +1,6 @@ //! JSC bridge for `bun_http_types::Method`. Keeps `bun_http_types` free of JSC types. -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_http_types::Method::Method; use bun_jsc::{JSGlobalObject, JSValue, JsResult, StringJsc as _}; @@ -17,9 +17,7 @@ unsafe extern "C" { /// /// Lives here (not in `bun_http_types`) so the base crate stays JSC-free. pub fn from_js(global_this: &JSGlobalObject, input: JSValue) -> JsResult> { - // `defer str.deref()` — `bun_core::String` is `Copy` (no `Drop`), so wrap the - // +1 ref from `BunString::from_js` in `OwnedString` to release it on scope exit. - let str = OwnedString::new(BunString::from_js(input, global_this)?); + let str = BunString::from_js(input, global_this)?; debug_assert!(str.tag() != bun_core::Tag::Dead); // `Method::which` is keyed on `&[u8]`, so materialize UTF-8 and call it // directly. diff --git a/src/http_jsc/websocket_client.rs b/src/http_jsc/websocket_client.rs index c40a996ebf4c..dd25f7467d04 100644 --- a/src/http_jsc/websocket_client.rs +++ b/src/http_jsc/websocket_client.rs @@ -183,9 +183,7 @@ impl WebSocket { self.clear_send_buffers(true); self.control_frame_started.set(false); self.ping_len.set(0); - if let Some((_, reason)) = self.close_dispatch_pending.take() { - reason.deref(); - } + self.close_dispatch_pending.take(); self.receiving_compressed.set(false); self.message_is_compressed.set(false); self.deflate.replace(None); @@ -294,13 +292,13 @@ impl WebSocket { pub fn handle_close(&self, _socket: Socket, _code: c_int, _reason: *mut c_void) { log!("onClose"); jsc::mark_binding!(); - if let Some((code, mut reason)) = self.close_dispatch_pending.take() { + if let Some((code, reason)) = self.close_dispatch_pending.take() { // The socket closed while our close frame was mid-flush; the peer // either got it or didn't, but JS should still see the // user-initiated code/reason (not an abrupt 1006). self.detach_tcp(); self.clear_data(); - self.dispatch_close(code, &mut reason); + self.dispatch_close(code, reason); // For the socket. self.release_io_ref(); return; @@ -1152,7 +1150,7 @@ impl WebSocket { if self.send_buffer.borrow().readable_length() == 0 { self.shutdown_after_close_frame(); self.clear_data(); - self.dispatch_close(dispatch_code, &mut reason); + self.dispatch_close(dispatch_code, reason); } else { // The close frame was only partially written; the remainder is // in send_buffer. clear_data() would discard it (and the @@ -1178,10 +1176,10 @@ impl WebSocket { } fn finish_pending_close(&self) { - if let Some((code, mut reason)) = self.close_dispatch_pending.take() { + if let Some((code, reason)) = self.close_dispatch_pending.take() { self.shutdown_after_close_frame(); self.clear_data(); - self.dispatch_close(code, &mut reason); + self.dispatch_close(code, reason); } } @@ -1374,7 +1372,7 @@ impl WebSocket { } /// May free `self`. - fn dispatch_close(&self, code: u16, reason: &mut bun_core::String) { + fn dispatch_close(&self, code: u16, reason: bun_core::String) { let Some((out, cpp_ref)) = self.outgoing_websocket.replace(None) else { return; }; diff --git a/src/http_jsc/websocket_client/CppWebSocket.rs b/src/http_jsc/websocket_client/CppWebSocket.rs index e4a48c9d2d6c..15b76a6d5a57 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -62,11 +62,7 @@ unsafe extern "C" { headers: FfiSlice<'_, RawHeader<'_>>, body: FfiSlice<'_>, ); - safe fn WebSocket__didClose( - websocket_context: &CppWebSocket, - code: u16, - reason: &mut BunString, - ); + safe fn WebSocket__didClose(websocket_context: &CppWebSocket, code: u16, reason: BunString); safe fn WebSocket__didReceiveText( websocket_context: &CppWebSocket, clone: bool, @@ -80,7 +76,7 @@ unsafe extern "C" { safe fn WebSocket__rejectUnauthorized(websocket_context: &CppWebSocket) -> bool; safe fn WebSocket__holdPendingActivityForClient(websocket_context: &CppWebSocket); safe fn WebSocket__releasePendingActivityForClient(websocket_context: &CppWebSocket); - safe fn WebSocket__setProtocol(websocket_context: &CppWebSocket, protocol: &mut BunString); + safe fn WebSocket__setProtocol(websocket_context: &CppWebSocket, protocol: BunString); } // Receivers are `&self` (not `&mut self`) because `CppWebSocket` is @@ -118,7 +114,7 @@ impl CppWebSocket { event_loop.exit(); } - pub(crate) fn did_close(&self, code: u16, reason: &mut BunString) { + pub(crate) fn did_close(&self, code: u16, reason: BunString) { let event_loop = VirtualMachine::get().event_loop_mut(); event_loop.enter(); WebSocket__didClose(self, code, reason); @@ -188,7 +184,7 @@ impl CppWebSocket { WebSocket__releasePendingActivityForClient(self); } - pub(crate) fn set_protocol(&self, protocol: &mut BunString) { + pub(crate) fn set_protocol(&self, protocol: BunString) { bun_jsc::mark_binding!(); WebSocket__setProtocol(self, protocol); } diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index 0b4b5609d283..c65cbc6adc7c 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -1160,11 +1160,7 @@ where } if let Some(ws) = this.cpp_websocket() { - let mut protocol_str = BunString::clone_latin1(protocol); - ws.set_protocol(&mut protocol_str); - // `BunString` is `Copy`; explicitly drop the - // ref taken by `clone_latin1`. - protocol_str.deref(); + ws.set_protocol(BunString::clone_latin1(protocol)); } true }; diff --git a/src/install/NetworkTask.rs b/src/install/NetworkTask.rs index 86d57e3e426a..bf3791629f75 100644 --- a/src/install/NetworkTask.rs +++ b/src/install/NetworkTask.rs @@ -490,13 +490,10 @@ impl NetworkTask { name }; - // `OwnedString` derefs the WTF-backed result on scope exit — - // covers both the - // success path and the InvalidURL early returns below. - let tmp = bun_core::OwnedString::new(bun_url::join( + let tmp = bun_url::join( &bun_core::String::borrow_utf8(scope.url.href()), &bun_core::String::borrow_utf8(encoded_name), - )); + ); if tmp.tag() == bun_core::Tag::Dead { if !is_optional { @@ -530,7 +527,7 @@ impl NetworkTask { bun_ast::Loc::EMPTY, format_args!( "Registry URL must be http:// or https://\nReceived: \"{}\"", - *tmp + tmp ), ); } else { @@ -539,14 +536,14 @@ impl NetworkTask { bun_ast::Loc::EMPTY, format_args!( "Registry URL must be http:// or https://\nReceived: \"{}\"", - *tmp + tmp ), ); } return Err(ForManifestError::InvalidURL); } - // This actually duplicates the string! So we defer deref the WTF managed one above. + // This actually duplicates the string! The WTF managed one above drops at scope exit. let url_bytes = tmp.to_owned_slice().into_boxed_slice(); { diff --git a/src/install/hosted_git_info.rs b/src/install/hosted_git_info.rs index 3cf26662d769..7e484ffc3db4 100644 --- a/src/install/hosted_git_info.rs +++ b/src/install/hosted_git_info.rs @@ -50,13 +50,12 @@ //! tags like `github:` which are handled as "shortcuts" by this library. use core::ops::Range; -use core::ptr::NonNull; use bun_alloc::AllocError; use bun_core::StringBuilder; -use bun_core::{OwnedString, strings}; +use bun_core::strings; use bun_url::PercentEncoding; -use bun_url::whatwg::URL as JscUrl; +use bun_url::whatwg::{Parsed, URL}; use enum_map::{Enum, EnumMap}; // ────────────────────────────────────────────────────────────────────────── @@ -255,8 +254,6 @@ impl HostedGitInfo { let Ok(parsed) = parse_url(git_url_mut) else { return Ok(None); }; - // `parsed.url` is `OwnedJscUrl`; Drop handles `defer parsed.url.deinit()`. - let host_provider = match parsed.proto { UrlProtocol::WellFormed(p) => p .host_provider() @@ -333,28 +330,8 @@ impl HostedGitInfo { // parse_url // ────────────────────────────────────────────────────────────────────────── -/// RAII handle over a heap-allocated `WTF::URL` (C++). The allocation comes from -/// `URL__fromString` (C++ `new`), so it MUST be freed via `URL__deinit` — wrapping -/// the pointer in `Box` is allocator-mismatch UB and never runs the C++ destructor. -pub struct OwnedJscUrl(NonNull); -impl core::ops::Deref for OwnedJscUrl { - type Target = JscUrl; - fn deref(&self) -> &JscUrl { - // SAFETY: `from_string`/`from_utf8` returned a live heap WTF::URL we own. - unsafe { self.0.as_ref() } - } -} -impl Drop for OwnedJscUrl { - fn drop(&mut self) { - // SAFETY: pointer is the unique owner of a `new WTF::URL` from C++; `deinit` - // calls `URL__deinit` which `delete`s it. - unsafe { self.0.as_mut() }.deinit(); - } -} - -// `url` is owned: `jsc.URL.fromString` creates it and the holder deinits. pub struct ParsedUrl<'a> { - pub url: OwnedJscUrl, + pub url: Parsed, pub(crate) proto: UrlProtocol<'a>, } @@ -671,7 +648,7 @@ impl<'a> UrlProtocolPair<'a> { } /// Given a protocol pair, create a jsc.URL if possible. May allocate, but owns its memory. - fn to_url(&self) -> Option { + fn to_url(&self) -> Option { let mut protocol_buf: StringWithColonBuffer = [0u8; WellDefinedProtocol::MAX_PROTOCOL_LENGTH + 1]; @@ -693,12 +670,12 @@ impl<'a> UrlProtocolPair<'a> { } } - fn concat_parts_to_url(parts: &[&[u8]]) -> Option { + fn concat_parts_to_url(parts: &[&[u8]]) -> Option { // TODO(markovejnovic): There is a sad unnecessary allocation here that I don't know how to // get rid of -- in theory, the URL layer could allocate once. let new_str = strings::concat(parts); // Drop handles `defer allocator.free(new_str)`. - JscUrl::from_utf8(&new_str).map(OwnedJscUrl) + Parsed::from_utf8(&new_str) } } @@ -911,7 +888,7 @@ impl HostProvider { HostProvider::Sourcehut, ]; - fn extract(self, url: &JscUrl) -> Result, HostedGitInfoError> { + fn extract(self, url: &URL) -> Result, HostedGitInfoError> { (configs()[self].format_extract)(url) } @@ -961,8 +938,8 @@ impl HostProvider { } /// Parse a URL and return the appropriate host provider, if any. - fn from_url(url: &JscUrl) -> Option { - let proto_str = OwnedString::new(url.protocol()); + fn from_url(url: &URL) -> Option { + let proto_str = url.protocol(); // Try shortcut first (github:, gitlab:, etc.) if let Some(provider) = HostProvider::from_shortcut(proto_str.byte_slice(), false) { @@ -973,8 +950,8 @@ impl HostProvider { } /// Given a URL, use the domain in the URL to find the appropriate host provider. - fn from_url_domain(url: &JscUrl) -> Option { - let hostname_str = OwnedString::new(url.hostname()); + fn from_url_domain(url: &URL) -> Option { + let hostname_str = url.hostname(); let hostname_utf8 = hostname_str.to_utf8(); let hostname = strings::without_prefix(hostname_utf8.slice(), b"www."); @@ -1028,10 +1005,9 @@ pub(crate) mod formatters { pub(crate) mod extract { use super::*; - pub(crate) type Type = - fn(url: &JscUrl) -> Result, HostedGitInfoError>; + pub(crate) type Type = fn(url: &URL) -> Result, HostedGitInfoError>; - pub(crate) fn github(url: &JscUrl) -> Result, HostedGitInfoError> { + pub(crate) fn github(url: &URL) -> Result, HostedGitInfoError> { let pathname_owned = url.pathname().to_owned_slice(); let pathname = strings::trim_prefix(&pathname_owned, b"/"); @@ -1063,7 +1039,7 @@ pub(crate) mod formatters { // valid until it's copied into the StringBuilder. let fragment_utf8; let committish: Option<&[u8]> = if type_part.is_none() { - let fragment_str = OwnedString::new(url.fragment_identifier()); + let fragment_str = url.fragment_identifier(); fragment_utf8 = fragment_str.to_utf8(); let fragment = fragment_utf8.slice(); if !fragment.is_empty() { @@ -1099,7 +1075,7 @@ pub(crate) mod formatters { })) } - pub(crate) fn bitbucket(url: &JscUrl) -> Result, HostedGitInfoError> { + pub(crate) fn bitbucket(url: &URL) -> Result, HostedGitInfoError> { let pathname_owned = url.pathname().to_owned_slice(); let pathname = strings::trim_prefix(&pathname_owned, b"/"); @@ -1124,7 +1100,7 @@ pub(crate) mod formatters { return Ok(None); } - let fragment_str = OwnedString::new(url.fragment_identifier()); + let fragment_str = url.fragment_identifier(); let fragment_utf8 = fragment_str.to_utf8(); let fragment = fragment_utf8.slice(); let committish: Option<&[u8]> = if !fragment.is_empty() { @@ -1157,7 +1133,7 @@ pub(crate) mod formatters { })) } - pub(crate) fn gitlab(url: &JscUrl) -> Result, HostedGitInfoError> { + pub(crate) fn gitlab(url: &URL) -> Result, HostedGitInfoError> { let pathname_owned = url.pathname().to_owned_slice(); let pathname = strings::trim_prefix(&pathname_owned, b"/"); @@ -1179,7 +1155,7 @@ pub(crate) mod formatters { return Ok(None); } - let fragment_str = OwnedString::new(url.fragment_identifier()); + let fragment_str = url.fragment_identifier(); let fragment_utf8 = fragment_str.to_utf8(); let committish = fragment_utf8.slice(); @@ -1211,7 +1187,7 @@ pub(crate) mod formatters { })) } - pub(crate) fn gist(url: &JscUrl) -> Result, HostedGitInfoError> { + pub(crate) fn gist(url: &URL) -> Result, HostedGitInfoError> { let pathname_owned = url.pathname().to_owned_slice(); let pathname = strings::trim_prefix(&pathname_owned, b"/"); @@ -1244,7 +1220,7 @@ pub(crate) mod formatters { return Ok(None); } - let fragment_str = OwnedString::new(url.fragment_identifier()); + let fragment_str = url.fragment_identifier(); let fragment_utf8 = fragment_str.to_utf8(); let fragment = fragment_utf8.slice(); let committish: Option<&[u8]> = if !fragment.is_empty() { @@ -1296,7 +1272,7 @@ pub(crate) mod formatters { })) } - pub(crate) fn sourcehut(url: &JscUrl) -> Result, HostedGitInfoError> { + pub(crate) fn sourcehut(url: &URL) -> Result, HostedGitInfoError> { let pathname_owned = url.pathname().to_owned_slice(); let pathname = strings::trim_prefix(&pathname_owned, b"/"); @@ -1321,7 +1297,7 @@ pub(crate) mod formatters { return Ok(None); } - let fragment_str = OwnedString::new(url.fragment_identifier()); + let fragment_str = url.fragment_identifier(); let fragment_utf8 = fragment_str.to_utf8(); let fragment = fragment_utf8.slice(); let committish: Option<&[u8]> = if !fragment.is_empty() { diff --git a/src/install_jsc/hosted_git_info_jsc.rs b/src/install_jsc/hosted_git_info_jsc.rs index 8b2713b0d291..333bdd4d3a2e 100644 --- a/src/install_jsc/hosted_git_info_jsc.rs +++ b/src/install_jsc/hosted_git_info_jsc.rs @@ -73,7 +73,7 @@ pub fn js_parse_url(go: &JSGlobalObject, callframe: &CallFrame) -> JsResult JsResult", npmrc_utf8.slice()); @@ -50,7 +50,7 @@ impl IniTestingAPIs { let Some(envobj) = envjs.get_object() else { return Err(global.throw_type_error(format_args!("env must be an object"))); }; - let mut object_iter = bun_jsc::JSPropertyIterator::init( + let object_iter = bun_jsc::JSPropertyIterator::init( global, envobj, bun_jsc::JSPropertyIteratorOptions::new( @@ -60,15 +60,13 @@ impl IniTestingAPIs { envmap.ensure_total_capacity(object_iter.len)?; - while let Some(key) = object_iter.next()? { + while let Some((key, value)) = object_iter.next()? { let keyslice = key.to_owned_slice(); - let value = object_iter.value; if value.is_undefined() { continue; } - let value_str = value.get_zig_string(global)?; - let slice = value_str.to_owned_slice(); + let slice = value.to_bun_string(global)?.to_owned_slice(); envmap.put( &keyslice, @@ -112,8 +110,6 @@ impl IniTestingAPIs { BunString::from_bytes(&default_registry.email), ) }; - // `defer { *.deref() }` deleted — bun_core::String impls Drop. - // Rust has no field reflection; mirror struct-literal object creation with // a local `PojoFields` impl (the bun_jsc-convention until `#[derive(PojoFields)]` // lands) so each `bun.String → JSValue` encoding interleaves with `put()` and @@ -173,7 +169,7 @@ impl IniTestingAPIs { let arguments = frame.arguments(); let jsstr = arguments[0]; - let bunstr = bun_core::OwnedString::new(jsstr.to_bun_string(global)?); + let bunstr = jsstr.to_js_string_view(global)?; let utf8str = bunstr.to_utf8(); let env = global.bun_vm().as_mut().transpiler.env(); diff --git a/src/install_jsc/install_binding.rs b/src/install_jsc/install_binding.rs index f036c3db81f0..7b48297e59b5 100644 --- a/src/install_jsc/install_binding.rs +++ b/src/install_jsc/install_binding.rs @@ -11,7 +11,7 @@ pub mod bun_install_js_bindings { b"parseLockfile", JSFunction::create( global, - bun_core::String::static_(b"parseLockfile"), + "parseLockfile", // `#[bun_jsc::host_fn]` on the module-scope `js_parse_lockfile` // emits this `JSHostFn`-ABI shim. __jsc_host_js_parse_lockfile, @@ -33,7 +33,7 @@ pub mod bun_install_js_bindings { use core::ptr::NonNull; use bstr::BStr; - use bun_core::{OwnedString, String as BunString}; + use bun_core::String as BunString; use bun_install::lockfile::lockfile_json_stringify_for_debugging::{ WriteStream, WriteStreamOptions, json_stringify, }; @@ -44,7 +44,7 @@ pub mod bun_install_js_bindings { let mut log = bun_ast::Log::init(); let args = frame.arguments(); - let cwd = args[0].to_slice_or_null(global)?; + let cwd = args[0].to_slice(global)?; let dir = match bun_sys::open_dir_absolute_not_for_deleting_or_renaming(cwd.slice()) { Ok(d) => d, @@ -111,11 +111,6 @@ pub mod bun_install_js_bindings { json_stringify(&lockfile_, &mut w).expect("Vec JSON writer is infallible"); let stringified = w.into_bytes(); - // `bun_core::String` is `Copy` (no `Drop`), - // so the +1 from `clone_utf8` must be released via `OwnedString`'s RAII - // — `to_js_by_parse_json` borrows, it does not consume. - let mut str = OwnedString::new(BunString::clone_utf8(&stringified)); - - bun_jsc::bun_string_jsc::to_js_by_parse_json(&mut str, global) + bun_jsc::bun_string_jsc::to_js_by_parse_json(&BunString::borrow_utf8(&stringified), global) } } diff --git a/src/install_jsc/npm_jsc.rs b/src/install_jsc/npm_jsc.rs index 35da95b8c3e2..8fb6beeb89ea 100644 --- a/src/install_jsc/npm_jsc.rs +++ b/src/install_jsc/npm_jsc.rs @@ -52,7 +52,7 @@ impl ManifestBindings { b"parseManifest", JSFunction::create( global, - bun_core::String::static_(b"parseManifest"), + "parseManifest", // `#[bun_jsc::host_fn]` on the module-scope `js_parse_manifest` // emits this `JSHostFn`-ABI shim. __jsc_host_js_parse_manifest, @@ -82,13 +82,10 @@ fn js_parse_manifest(global: &JSGlobalObject, frame: &CallFrame) -> JsResult JsResult Option>; + fn __bun_regex_compile(pattern: &BunString) -> Option>; fn __bun_regex_matches(regex: NonNull<()>, input: &BunString) -> bool; fn __bun_regex_drop(regex: NonNull<()>); } @@ -128,8 +128,8 @@ pub struct RegularExpression { impl RegularExpression { fn matches(&self, input: &BunString) -> bool { let compiled = self.compiled.get_or_init(|| { - // SAFETY: link-time extern; pattern ownership transfers. - unsafe { __bun_regex_compile(BunString::clone_utf8(&self.source)) } + // SAFETY: link-time extern; Yarr compiles the pattern and does not retain it. + unsafe { __bun_regex_compile(&BunString::borrow_utf8(&self.source)) } .map(CompiledRegularExpression) }); match compiled { diff --git a/src/js_parser/fold.rs b/src/js_parser/fold.rs index 911e1e76de30..74125b583e17 100644 --- a/src/js_parser/fold.rs +++ b/src/js_parser/fold.rs @@ -534,7 +534,6 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O let url = p.arena.alloc_slice_copy( format!("{}", bun_url::file_url_from_string(&bunstr)).as_bytes(), ); - bunstr.deref(); return Some(p.new_expr(e_string_init(url), name_loc)); } } diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index 1e8179a709eb..ade58abe1a5f 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -754,7 +754,7 @@ impl<'a> Run<'a> { // SAFETY: `obj` is a live JSC heap cell; `'a` is bounded by the // surrounding stack frame. let obj_ref = unsafe { &*obj }; - let mut object_iter = JSPropertyIterator::init( + let object_iter = JSPropertyIterator::init( self.global, obj_ref, JSPropertyIteratorOptions::new(false, true), @@ -765,8 +765,8 @@ impl<'a> Run<'a> { let mut properties = G::PropertyList::init_capacity(object_iter.len); // (errdefer clearAndFree deleted — drops on `?`) - while let Some(prop) = object_iter.next()? { - let object_value = self.run(object_iter.value)?; + while let Some((prop, prop_value)) = object_iter.next()? { + let object_value = self.run(prop_value)?; // `EString::init` lifetime-erases its borrow // (arena-owned per the parser's `Str` convention). Copy the @@ -809,7 +809,7 @@ impl<'a> Run<'a> { )); } T::String => { - let bun_str = bun_core::OwnedString::new(value.to_bun_string(self.global)?); + let bun_str = value.to_bun_string(self.global)?; // encode into utf16 so the printer escapes the string correctly // UTF-16 → memcpy, Latin-1 → byte-widen. JS-sourced WTF diff --git a/src/js_parser_jsc/expr_jsc.rs b/src/js_parser_jsc/expr_jsc.rs index 396b3985073a..1aed2cfb62ea 100644 --- a/src/js_parser_jsc/expr_jsc.rs +++ b/src/js_parser_jsc/expr_jsc.rs @@ -5,7 +5,7 @@ use bun_ast::{E, Expr, ExprData, G, ToJSError}; use bun_collections::VecExt; use bun_core::{StackCheck, String as BunString, strings}; -use bun_jsc::{JSGlobalObject, JSValue, JsError, bun_string_jsc}; +use bun_jsc::{JSGlobalObject, JSValue, JsError, StringJsc as _}; /// Map a `bun_jsc::JsError` into the AST-layer `ToJSError`. Orphan rules forbid /// `impl From for ToJSError` here (both foreign), so callers use @@ -241,17 +241,16 @@ pub fn toml_datetime_to_js( fn utf8_bytes_to_js(bytes: &[u8], global: &JSGlobalObject) -> Result { if bytes.is_empty() { - let empty = BunString::EMPTY; - return bun_string_jsc::to_js(&empty, global).map_err(js_err); + return BunString::EMPTY.to_js(global).map_err(js_err); } if let Some(utf16) = strings::wtf8_to_utf16_alloc(bytes) { - let (mut out, chars) = BunString::create_uninitialized_utf16(utf16.len()); + let (out, chars) = BunString::create_uninitialized_utf16(utf16.len()); chars.copy_from_slice(&utf16); - bun_string_jsc::transfer_to_js(&mut out, global).map_err(js_err) + out.into_js(global).map_err(js_err) } else { - let (mut out, chars) = BunString::create_uninitialized_latin1(bytes.len()); + let (out, chars) = BunString::create_uninitialized_latin1(bytes.len()); chars.copy_from_slice(bytes); - bun_string_jsc::transfer_to_js(&mut out, global).map_err(js_err) + out.into_js(global).map_err(js_err) } } @@ -282,17 +281,16 @@ macro_rules! impl_string_to_js { } if !s.is_present() { - let emp = BunString::EMPTY; - return bun_string_jsc::to_js(&emp, global).map_err(js_err); + return BunString::EMPTY.to_js(global).map_err(js_err); } if s.is_utf8() { utf8_bytes_to_js(s.slice8(), global) } else { let utf16 = s.slice16(); - let (mut out, chars) = BunString::create_uninitialized_utf16(utf16.len()); + let (out, chars) = BunString::create_uninitialized_utf16(utf16.len()); chars.copy_from_slice(utf16); - bun_string_jsc::transfer_to_js(&mut out, global).map_err(js_err) + out.into_js(global).map_err(js_err) } } }; diff --git a/src/jsc/AsyncModule.rs b/src/jsc/AsyncModule.rs index 1c9d5c721cd3..45da1d373020 100644 --- a/src/jsc/AsyncModule.rs +++ b/src/jsc/AsyncModule.rs @@ -2,7 +2,7 @@ use core::ffi::c_void; use bun_alloc::Arena as ArenaAllocator; use bun_bundler::transpiler::ParseResult; -use bun_core::{OwnedString, String as BunString, ZigString}; +use bun_core::{String as BunString, ZigString}; use bun_install::dependency::Dependency; use bun_install::{DependencyID, Resolution}; use bun_io::KeepAlive; @@ -10,8 +10,8 @@ use bun_resolver::fs as Fs; use crate::virtual_machine::VirtualMachine; use crate::{ - self as jsc, ErrorCode, ErrorableResolvedSource, JSGlobalObject, JSInternalPromise, JSValue, - JsError, JsResult, ResolvedSource, StrongOptional, ZigStringJsc as _, + self as jsc, ErrorableResolvedSource, JSGlobalObject, JSInternalPromise, JSValue, JsError, + JsResult, ResolvedSource, StrongOptional, ZigStringJsc as _, }; bun_core::declare_scope!(AsyncModule, hidden); @@ -148,97 +148,35 @@ impl AsyncModule { } /// Dispatch the (possibly errored) transpile - /// result back into JSC via `Bun__onFulfillAsyncModule`. This is the entry - /// point `RuntimeTranspilerStore::run_from_js_thread` calls when a + /// result back into JSC via `Bun__onFulfillAsyncModule`. Called from + /// `RuntimeTranspilerStore::run_from_js_thread` and `on_done` when a /// concurrent transpile job finishes. pub(crate) fn fulfill( global_this: &JSGlobalObject, promise: JSValue, - resolved_source: &mut ResolvedSource, - err: Option, - specifier_: BunString, - referrer_: BunString, + result: Result, + specifier: &BunString, + referrer: &BunString, log: &mut bun_ast::Log, ) -> JsResult<()> { jsc::mark_binding(); - let mut specifier = specifier_; - let mut referrer = referrer_; - // BunString is `Copy` (no Drop), so deref the held - // refcounts explicitly via scopeguard. The `TopExceptionScope` is - // omitted: `from_js_host_call_generic` already checks the VM for a - // pending exception after the FFI call (host_fn.rs). - // - // The guard captures raw pointers to the locals (not by-value copies) - // so the deref observes the *post-FFI* value of the variable — - // `Bun__onFulfillAsyncModule` receives - // `&mut specifier`/`&mut referrer` and is free to overwrite them. - // Safety: `specifier`/`referrer` are declared above this guard, so - // they outlive it (locals drop in reverse order); the `&mut` reborrow - // passed to FFI below is dead by the time the guard runs. - let sp: *mut BunString = &raw mut specifier; - let rp: *mut BunString = &raw mut referrer; - let _strings_guard = scopeguard::guard((), move |()| { - // SAFETY: `sp`/`rp` point at `specifier`/`referrer` declared above - // this guard; locals drop in reverse order so they outlive it, and - // the `&mut` reborrows passed to FFI are dead by the time this runs. - unsafe { - (*sp).deref(); - (*rp).deref(); - } - }); - - let mut errorable: ErrorableResolvedSource; - if let Some(e) = err { - // `OwnedString` derefs on Drop at the end - // of this `if` arm; `None` is the no-op path. - let _source_code_guard = if resolved_source.source_code_needs_deref { - resolved_source.source_code_needs_deref = false; - Some(OwnedString::new(resolved_source.source_code)) - } else { - None - }; - - if e == crate::CrateError::JSError { - errorable = ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - global_this.take_error(JsError::Thrown), - ); - } else { - // `process_fetch_log` synthesizes a JS - // Error/AggregateError from the parser log and writes it into - // `errorable.result.err.value`. Without this the import promise - // would reject with `undefined` (ModuleLoader.cpp:473). - // call the `virtual_machine` impl directly (takes - // `&JSGlobalObject`) instead of the `module_loader` shim that - // takes `*mut` — avoids a `&T as *const T as *mut T` cast, - // which is UB-adjacent under Stacked Borrows even when the - // callee never writes through it. - errorable = ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - JSValue::UNDEFINED, - ); - crate::virtual_machine::process_fetch_log( - global_this, - specifier, - referrer, - log, - &mut errorable, - e, - ); - } - } else { - errorable = ErrorableResolvedSource::ok(*resolved_source); - } + let mut errorable = match result { + Ok(resolved_source) => ErrorableResolvedSource::ok(resolved_source), + Err( + crate::CrateError::JSError | crate::CrateError::Bundler(bun_bundler::Error::Js(_)), + ) => ErrorableResolvedSource::err(global_this.take_error(JsError::Thrown)), + Err(e) => ErrorableResolvedSource::err(crate::virtual_machine::process_fetch_log( + global_this, + specifier, + referrer, + log, + e, + )), + }; bun_core::scoped_log!(AsyncModule, "fulfill: {}", specifier); jsc::from_js_host_call_generic(global_this, || { - Bun__onFulfillAsyncModule( - global_this, - promise, - &mut errorable, - &mut specifier, - &mut referrer, - ) + Bun__onFulfillAsyncModule(global_this, promise, &mut errorable, specifier, referrer) }) } } @@ -250,16 +188,16 @@ impl AsyncModule { // bun.default_allocator.free(this.expr_blocks); // safe: `JSGlobalObject` is an opaque `UnsafeCell`-backed ZST handle (`&` is -// ABI-identical to non-null `*const`); `ErrorableResolvedSource`/`BunString` -// are `#[repr(C)]` payloads whose `&mut` is exclusive for the call. C++ reads -// from / writes through these in-place; no caller-side raw-pointer precondition. +// ABI-identical to non-null `*const`); `res` stays owned by this frame — C++ +// takes the fields it keeps by transfer (zeroing them) and the rest drops here. unsafe extern "C" { + #[allow(improper_ctypes)] safe fn Bun__onFulfillAsyncModule( global_object: &JSGlobalObject, promise_value: JSValue, res: &mut ErrorableResolvedSource, - specifier: &mut BunString, - referrer: &mut BunString, + specifier: &BunString, + referrer: &BunString, ); } @@ -709,47 +647,17 @@ impl AsyncModule { this.poll_ref.unref(bun_io::posix_event_loop::get_vm_ctx( bun_io::AllocatorType::Js, )); - let errorable: ErrorableResolvedSource = match this.resume_loading_module(&mut log) { - Ok(rs) => ErrorableResolvedSource::ok(rs), - Err( - crate::CrateError::JSError | crate::CrateError::Bundler(bun_bundler::Error::Js(_)), - ) => ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - global_this.take_error(JsError::Thrown), - ), - Err(err) => { - // Pre-seed the - // err so the `&mut` borrow is definitely-initialized; - // `process_fetch_log` overwrites `result.err.value`. - let mut errorable = ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - JSValue::UNDEFINED, - ); - crate::virtual_machine::process_fetch_log( - global_this, - BunString::init(ZigString::init(this.specifier())), - BunString::init(ZigString::init(this.referrer())), - &mut log, - &mut errorable, - err, - ); - errorable - } - }; - let mut errorable = errorable; - // log dropped at scope exit (defer log.deinit()). - - let mut spec = BunString::init(ZigString::from_bytes(this.specifier()).with_encoding()); - let mut ref_ = BunString::init(ZigString::from_bytes(this.referrer()).with_encoding()); - jsc::from_js_host_call_generic(global_this, || { - Bun__onFulfillAsyncModule( - global_this, - this.promise.get().unwrap(), - &mut errorable, - &mut spec, - &mut ref_, - ) - }) + let result = this.resume_loading_module(&mut log); + let spec = BunString::borrow_utf8(this.specifier()); + let referrer = BunString::borrow_utf8(this.referrer()); + Self::fulfill( + global_this, + this.promise.get().unwrap(), + result, + &spec, + &referrer, + &mut log, + ) } // Never returns Err: the `write!`s below go into a `Vec` and their @@ -1307,9 +1215,9 @@ impl AsyncModule { if unsafe { (*jsc_vm).is_watcher_enabled() } { // SAFETY: per-thread VM. let mut resolved_source = unsafe { - (*jsc_vm).ref_counted_resolved_source::( + (*jsc_vm).ref_counted_resolved_source( printer.ctx.get_written(), - BunString::init(specifier), + &BunString::init(specifier), path.text, None, ) @@ -1322,7 +1230,6 @@ impl AsyncModule { Ok(ResolvedSource { source_code: BunString::clone_latin1(printer.ctx.get_written()), - specifier: BunString::init(specifier), source_url: BunString::init(path.text), is_commonjs_module, ..Default::default() diff --git a/src/jsc/BuildMessage.rs b/src/jsc/BuildMessage.rs index 822f5a0ed3c6..6f51acc374c9 100644 --- a/src/jsc/BuildMessage.rs +++ b/src/jsc/BuildMessage.rs @@ -103,7 +103,7 @@ impl BuildMessage { return Ok(JSValue::NULL); } - let str = args[0].get_zig_string(global)?; + let str = args[0].to_bun_string(global)?; if str.eql_comptime(b"default") || str.eql_comptime(b"string") { return Ok(self.to_string_fn(global)); } @@ -118,7 +118,7 @@ impl BuildMessage { object.put( global, b"name", - bun_core::String::static_str(b"BuildMessage").to_js(global)?, + bun_core::String::static_(b"BuildMessage").to_js(global)?, ); object.put(global, b"position", self.get_position(global)?); object.put(global, b"message", self.get_message(global)?); diff --git a/src/jsc/BunCPUProfiler.rs b/src/jsc/BunCPUProfiler.rs index 903d5364bc4c..01df473df31e 100644 --- a/src/jsc/BunCPUProfiler.rs +++ b/src/jsc/BunCPUProfiler.rs @@ -2,7 +2,7 @@ use core::ffi::c_int; use std::io::Write as _; use crate::VM; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; #[cfg(windows)] use bun_paths::OSPathBuffer; use bun_paths::{AutoAbsPathChecked, PathBuffer}; @@ -67,11 +67,6 @@ pub(crate) fn stop_and_write_profile( config.json_format.then_some(&mut json_string), config.md_format.then_some(&mut text_string), ); - // C++ handed back +1 refs into json_string/text_string. `bun_core::String` - // is `Copy` (no Drop), so wrap in `OwnedString` for scope-exit `deref()`. - let json_string = OwnedString::new(json_string); - let text_string = OwnedString::new(text_string); - // Write JSON format if requested and not empty if config.json_format && !json_string.is_empty() { write_profile_to_file(&json_string, config, false)?; diff --git a/src/jsc/BunHeapProfiler.rs b/src/jsc/BunHeapProfiler.rs index 3169f067f2ea..4d1818b43f8e 100644 --- a/src/jsc/BunHeapProfiler.rs +++ b/src/jsc/BunHeapProfiler.rs @@ -1,6 +1,6 @@ use crate::CrateError as Error; use bun_core::Output; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_paths::{AutoAbsPathChecked, PathBuffer, resolve_path}; use bun_sys::{self as sys, E, Fd, FdDirExt}; @@ -26,13 +26,11 @@ pub(crate) fn generate_and_write_profile( vm: &mut VM, config: &HeapProfilerConfig, ) -> Result<(), Error> { - // `defer profile_string.deref()` — `bun_core::String` is `Copy` (no Drop); - // wrap the +1 ref from C++ in `OwnedString` so it's released on every exit path. - let profile_string = OwnedString::new(if config.text_format { + let profile_string = if config.text_format { Bun__generateHeapProfile(vm) } else { Bun__generateHeapSnapshotV8(vm) - }); + }; if profile_string.is_empty() { // No profile data generated diff --git a/src/jsc/CachedBytecode.rs b/src/jsc/CachedBytecode.rs index 5760b9b6cdee..165272e18b83 100644 --- a/src/jsc/CachedBytecode.rs +++ b/src/jsc/CachedBytecode.rs @@ -10,7 +10,7 @@ bun_opaque::opaque_ffi! { unsafe extern "C" { fn generateCachedModuleByteCodeFromSourceCode( - source_provider_url: *mut BunString, + source_provider_url: &BunString, input_code: *const u8, input_source_code_size: usize, output_byte_code: *mut Option>, @@ -19,7 +19,7 @@ unsafe extern "C" { ) -> bool; fn generateCachedCommonJSProgramByteCodeFromSourceCode( - source_provider_url: *mut BunString, + source_provider_url: &BunString, input_code: *const u8, input_source_code_size: usize, output_byte_code: *mut Option>, @@ -38,7 +38,7 @@ impl CachedBytecode { // `CachedBytecode` handle and is invalidated when `deref()` is called. Callers own // the handle and must call `deref()` (or drop via `allocator()`) to free. pub(crate) fn generate_for_esm( - source_provider_url: &mut BunString, + source_provider_url: &BunString, input: &[u8], ) -> Option<(&'static [u8], NonNull)> { let mut this: Option> = None; @@ -68,7 +68,7 @@ impl CachedBytecode { } pub(crate) fn generate_for_cjs( - source_provider_url: &mut BunString, + source_provider_url: &BunString, input: &[u8], ) -> Option<(&'static [u8], NonNull)> { let mut this: Option> = None; @@ -99,7 +99,7 @@ impl CachedBytecode { pub(crate) fn generate( format: Format, input: &[u8], - source_provider_url: &mut BunString, + source_provider_url: &BunString, ) -> Option<(&'static [u8], NonNull)> { match format { Format::Esm => Self::generate_for_esm(source_provider_url, input), @@ -132,7 +132,7 @@ impl bun_alloc::Allocator for CachedBytecode {} pub(crate) fn __bun_jsc_generate_cached_bytecode( format: Format, source: &[u8], - source_provider_url: &mut BunString, + source_provider_url: &BunString, ) -> Option> { crate::virtual_machine::IS_BUNDLER_THREAD_FOR_BYTECODE_CACHE.set(true); crate::initialize(crate::InitializeOptions::default()); diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index f5db6baff174..b1b3ff1bc5c3 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -12,7 +12,7 @@ use crate::virtual_machine::VirtualMachine; use crate::{EventType, JSGlobalObject, JSPromise, JSValue, JsResult, ZigString}; use bun_collections::HashMap; use bun_core::{Output, StackCheck}; -use bun_core::{OwnedString, String as BunString, strings}; +use bun_core::{String as BunString, strings}; /// Thin facade over `bun_js_parser::lexer` / `bun_js_printer` so the call /// sites below can use the `JSLexer.isLatin1Identifier` / @@ -754,7 +754,7 @@ impl<'a> TablePrinter<'a> { } } } else { - let mut cols_iter = jsc::JSPropertyIterator::init( + let cols_iter = jsc::JSPropertyIterator::init( self.global_object, obj, jsc::PropertyIteratorOptions { @@ -763,27 +763,18 @@ impl<'a> TablePrinter<'a> { }, )?; - while let Some(col_key) = cols_iter.next()? { - let value = cols_iter.value; - + while let Some((col_key, value)) = cols_iter.next()? { // find or create the column for the property let col_idx: usize = 'brk: { - let col_str = BunString::init(col_key); - // reshaped for borrowck — split find/append. if let Some(idx) = - columns[1..].iter().position(|col| col.name.eql(&col_str)) + columns[1..].iter().position(|col| col.name.eql(&col_key)) { break 'brk 1 + idx; } - // Need to ref this string because JSPropertyIterator - // uses `toString` instead of `toStringRef` for property - // names. - col_str.ref_(); - columns.push(Column { - name: col_str, + name: (*col_key).clone(), width: 1, }); break 'brk columns.len() - 1; @@ -878,13 +869,6 @@ impl<'a> TablePrinter<'a> { let global_object = self.global_object; let mut columns: Vec = Vec::with_capacity(16); - let mut _deref_names = scopeguard::guard(&mut columns, |cols| { - for col in cols.iter_mut() { - col.name.deref(); - } - }); - // reshaped for borrowck — re-borrow through the guard. - let columns: &mut Vec = &mut **_deref_names; // create the first column " " which is always present columns.push(Column { @@ -931,7 +915,7 @@ impl<'a> TablePrinter<'a> { let mut ctx = Ctx { this: self, cell_text: &mut cell_text, - columns, + columns: &mut columns, rows: &mut rows, idx: 0, err: None, @@ -971,7 +955,7 @@ impl<'a> TablePrinter<'a> { } } else { let tabular_obj = self.tabular_data.to_object(global_object)?; - let mut rows_iter = jsc::JSPropertyIterator::init( + let rows_iter = jsc::JSPropertyIterator::init( global_object, tabular_obj, jsc::PropertyIteratorOptions { @@ -980,13 +964,13 @@ impl<'a> TablePrinter<'a> { }, )?; - while let Some(row_key) = rows_iter.next()? { - let key = RowKey::str(&BunString::init(row_key)); + while let Some((row_key, value)) = rows_iter.next()? { + let key = RowKey::str(&row_key); let row = self.collect_row::( &mut cell_text, - columns, + &mut columns, key, - rows_iter.value, + value, )?; rows.push(row); } @@ -1059,7 +1043,7 @@ impl<'a> TablePrinter<'a> { // render pass: replay each row's pre-formatted cell bytes for row in rows.iter() { - self.print_row(writer, columns, row, &cell_text); + self.print_row(writer, &columns, row, &cell_text); } // print the table bottom border @@ -1147,10 +1131,7 @@ pub fn write_trace(writer: &mut dyn bun_io::Write, global: &JSGlobalObject) { let mut source_code_slice: Option = None; let err = ZigString::init(b"trace output").to_error_instance(global); - { - let exception = holder.zig_exception(); - err.to_zig_exception(global, exception); - } + // `remap_zig_exception` populates `holder.zig_exception()` from `err`. // `exception` and `&holder.need_to_clear_parser_arena_on_deinit` would be // two simultaneous `&mut` into `holder`. Capture the flag in a local and // write it back after. @@ -1223,14 +1204,14 @@ pub enum Colon { ExcludeColon, } -pub struct ErrorDisplayLevelFormatter { - pub name: BunString, +pub struct ErrorDisplayLevelFormatter<'a> { + pub name: &'a BunString, pub(crate) level: ErrorDisplayLevel, pub(crate) enable_colors: bool, pub(crate) colon: Colon, } -impl core::fmt::Display for ErrorDisplayLevelFormatter { +impl core::fmt::Display for ErrorDisplayLevelFormatter<'_> { fn fmt(&self, writer: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { if self.enable_colors { match self.level { @@ -1241,7 +1222,7 @@ impl core::fmt::Display for ErrorDisplayLevelFormatter { } if !self.name.is_empty() { - core::fmt::Display::fmt(&self.name, writer)?; + core::fmt::Display::fmt(self.name, writer)?; } else if self.level == ErrorDisplayLevel::Warn { writer.write_str("warn")?; } else { @@ -1267,10 +1248,10 @@ impl core::fmt::Display for ErrorDisplayLevelFormatter { impl ErrorDisplayLevel { pub(crate) fn formatter( self, - error_name: BunString, + error_name: &BunString, enable_colors: bool, colon: Colon, - ) -> ErrorDisplayLevelFormatter { + ) -> ErrorDisplayLevelFormatter<'_> { ErrorDisplayLevelFormatter { name: error_name, level: self, @@ -2212,20 +2193,15 @@ pub mod formatter { if js_type.is_object() && js_type != jsc::JSType::ProxyObject { if let Some(typeof_symbol) = value.get_own_truthy(global_this, "$$typeof")? { // React 18 and below - let mut react_element_legacy = ZigString::init(b"react.element"); - // For React 19 - https://github.com/oven-sh/bun/issues/17223 - let mut react_element_transitional = - ZigString::init(b"react.transitional.element"); - let mut react_fragment = ZigString::init(b"react.fragment"); - if typeof_symbol.is_same_value( - JSValue::symbol_for(global_this, &mut react_element_legacy), + JSValue::symbol_for(global_this, b"react.element"), global_this, )? || typeof_symbol.is_same_value( - JSValue::symbol_for(global_this, &mut react_element_transitional), + // For React 19 - https://github.com/oven-sh/bun/issues/17223 + JSValue::symbol_for(global_this, b"react.transitional.element"), global_this, )? || typeof_symbol.is_same_value( - JSValue::symbol_for(global_this, &mut react_fragment), + JSValue::symbol_for(global_this, b"react.fragment"), global_this, )? { return Ok(TagResult { @@ -2604,10 +2580,7 @@ pub mod formatter { PercentTag::J => { // JSON.stringify the value using FastStringifier // for SIMD optimization - // `OwnedString` releases the - // +1 WTF ref on every exit (incl. the `?` below). - let mut str = OwnedString::new(BunString::empty()); - next_value.json_stringify_fast(global, &mut str)?; + let str = next_value.json_stringify_fast(global)?; writer.add_for_new_line(str.length()); writer.print(format_args!("{str}")); } @@ -2727,7 +2700,7 @@ pub mod formatter { } #[inline] - pub(crate) fn write_string(&mut self, str: &ZigString) { + pub(crate) fn write_string(&mut self, str: &bun_core::String) { self.print(format_args!("{str}")); } @@ -3196,13 +3169,12 @@ pub mod formatter { fn get_object_name( global_this: &JSGlobalObject, value: JSValue, - ) -> JsResult> { - let mut name_str = ZigString::init(b""); - value.get_class_name(global_this, &mut name_str)?; + ) -> JsResult> { + let name_str = value.get_class_name(global_this)?; if !name_str.eql_comptime(b"Object") { return Ok(Some(name_str)); } else if value.get_prototype(global_this)?.eql_value(JSValue::NULL) { - return Ok(Some(ZigString::static_("[Object: null prototype]"))); + return Ok(Some(bun_core::String::static_("[Object: null prototype]"))); } Ok(None) } @@ -3551,7 +3523,7 @@ pub mod formatter { ) -> JsResult<()> { // This is called from the '%s' formatter, so it can actually be any value use crate::StringJsc as _; - let str = OwnedString::new(BunString::from_js(value, self.global_this)?); + let str = BunString::from_js(value, self.global_this)?; let mut writer = WrappedWriter { ctx: writer_, failed: false, @@ -3693,8 +3665,8 @@ pub mod formatter { failed: false, estimated_line_length: &mut self.estimated_line_length, }; - let zstr = value.get_zig_string(self.global_this)?; - let out_str = zstr.slice(); + let view = value.to_js_string_view(self.global_this)?; + let out_str = view.latin1(); writer.add_for_new_line(out_str.len()); writer.print(format_args!( "{}{}n{}", @@ -3725,15 +3697,13 @@ pub mod formatter { }; } if value.is_cell() { - let mut number_name = ZigString::EMPTY; - value.get_class_name(self.global_this, &mut number_name)?; + let number_name = value.get_class_name(self.global_this)?; - let mut number_value = ZigString::EMPTY; - value.to_zig_string(&mut number_value, self.global_this)?; + let number_value = value.to_js_string_view(self.global_this)?; - if number_name.slice() != b"Number" { + if !number_name.eql_comptime(b"Number") { writer.add_for_new_line( - number_name.len + number_value.len + "[Number ():]".len(), + number_name.length() + number_value.length() + "[Number ():]".len(), ); writer.print(format_args!( "{}[Number ({}): {}]{}", @@ -3748,7 +3718,7 @@ pub mod formatter { return Ok(()); } - writer.add_for_new_line(number_name.len + number_value.len + 4); + writer.add_for_new_line(number_name.length() + number_value.length() + 4); writer.print(format_args!( "{}[{}: {}]{}", pf!(""), @@ -3848,8 +3818,8 @@ pub mod formatter { let description = value.get_description(self.global_this); writer.add_for_new_line("Symbol".len()); - if description.len > 0 { - writer.add_for_new_line(description.len + "()".len()); + if !description.is_empty() { + writer.add_for_new_line(description.length() + "()".len()); writer.print(format_args!( "{}Symbol({}){}", pfmt!("", C), @@ -3924,7 +3894,7 @@ pub mod formatter { // `Function.prototype.constructor === Function`, returning // "Function". The `.name` property is set to the real class name // on the constructor itself. See #29225. - let printable = OwnedString::new(value.get_name(self.global_this)?); + let printable = value.get_name(self.global_this)?; writer.add_for_new_line(printable.length()); // Only report `extends` when the parent is itself a class @@ -3935,11 +3905,11 @@ pub mod formatter { let proto_is_class = !proto.is_empty_or_undefined_or_null() && proto.is_cell() && proto.is_class(self.global_this); - let printable_proto = OwnedString::new(if proto_is_class { + let printable_proto = if proto_is_class { proto.get_name(self.global_this)? } else { BunString::empty() - }); + }; writer.add_for_new_line(printable_proto.length()); if printable.is_empty() { @@ -3995,11 +3965,11 @@ pub mod formatter { pfmt!($s, C) }; } - let printable = OwnedString::new(value.get_name(self.global_this)?); + let printable = value.get_name(self.global_this)?; let proto = value.get_prototype(self.global_this)?; // "Function" | "AsyncFunction" | "GeneratorFunction" | "AsyncGeneratorFunction" - let func_name = OwnedString::new(proto.get_name(self.global_this)?); + let func_name = proto.get_name(self.global_this)?; if printable.is_empty() || func_name.eql(&printable) { if func_name.is_empty() { @@ -4133,14 +4103,13 @@ pub mod formatter { }; } if value.is_cell() { - let mut bool_name = ZigString::EMPTY; - value.get_class_name(self.global_this, &mut bool_name)?; - let mut bool_value = ZigString::EMPTY; - value.to_zig_string(&mut bool_value, self.global_this)?; - - if bool_name.slice() != b"Boolean" { - writer - .add_for_new_line(bool_value.len + bool_name.len + "[Boolean (): ]".len()); + let bool_name = value.get_class_name(self.global_this)?; + let bool_value = value.to_js_string_view(self.global_this)?; + + if !bool_name.eql_comptime(b"Boolean") { + writer.add_for_new_line( + bool_value.length() + bool_name.length() + "[Boolean (): ]".len(), + ); writer.print(format_args!( "{}[Boolean ({}): {}]{}", pf!(""), @@ -4153,7 +4122,7 @@ pub mod formatter { } return Ok(()); } - writer.add_for_new_line(bool_value.len + "[Boolean: ]".len()); + writer.add_for_new_line(bool_value.length() + "[Boolean: ]".len()); writer.print(format_args!( "{}[Boolean: {}]{}", pf!(""), @@ -4211,9 +4180,7 @@ pub mod formatter { failed: false, estimated_line_length: &mut self.estimated_line_length, }; - let mut str = OwnedString::new(BunString::empty()); - - value.json_stringify(self.global_this, self.indent, &mut str)?; + let str = value.json_stringify(self.global_this, self.indent)?; writer.add_for_new_line(str.length()); if js_type == jsc::JSType::JSDate { // in the code for printing dates, it never exceeds this amount @@ -4547,13 +4514,7 @@ pub mod formatter { // formatted `value`; otherwise we fall through to the generic // object printer below. if let Some(hooks) = crate::virtual_machine::runtime_hooks() { - // The hook only ever - // seeds a `ZigString` that `get_class_name` immediately - // overwrites with JSC-owned bytes, so a shared zero buffer is - // sufficient and keeps 512B off every recursive frame. - static NAME_BUF: [u8; 512] = [0; 512]; - let handled = - (hooks.console_print_runtime_object)(self, writer_, value, &NAME_BUF, C)?; + let handled = (hooks.console_print_runtime_object)(self, writer_, value, C)?; if handled { return Ok(()); } @@ -5026,13 +4987,8 @@ pub mod formatter { writer.write_all(pf!("").as_bytes()); writer.write_all(b"<"); - // Both arms of the `type` if/else below assign these, so deferred - // init avoids the dead-store warning. let mut needs_space: bool; - let mut tag_name_str = ZigString::init(b""); - - // `ZigStringSlice` frees on `Drop`, so no explicit cleanup is - // needed. + let tag_name_view; let tag_name_slice: bun_core::ZigStringSlice; let mut is_tag_kind_primitive = false; @@ -5040,23 +4996,26 @@ pub mod formatter { let _tag = Tag::get_advanced(type_value, self.global_this, tag_opts)?; if _tag.cell == jsc::JSType::Symbol { - // nothing + tag_name_slice = bun_core::ZigStringSlice::EMPTY; } else if _tag.cell.is_string_like() { - type_value.to_zig_string(&mut tag_name_str, self.global_this)?; + tag_name_view = type_value.to_js_string_view(self.global_this)?; + tag_name_slice = tag_name_view.to_utf8(); is_tag_kind_primitive = true; } else if _tag.cell.is_object() || type_value.is_callable() { - type_value.get_name_property(self.global_this, &mut tag_name_str)?; - if tag_name_str.len == 0 { - tag_name_str = ZigString::init(b"NoName"); - } + let name = type_value.get_name_property(self.global_this)?; + tag_name_slice = if name.is_empty() { + bun_core::ZigStringSlice::from_utf8_never_free(b"NoName") + } else { + name.to_utf8() + }; } else { - type_value.to_zig_string(&mut tag_name_str, self.global_this)?; + tag_name_view = type_value.to_js_string_view(self.global_this)?; + tag_name_slice = tag_name_view.to_utf8(); } - tag_name_slice = tag_name_str.to_slice(); needs_space = true; } else { - tag_name_slice = ZigString::init(b"unknown").to_slice(); + tag_name_slice = bun_core::ZigStringSlice::from_utf8_never_free(b"unknown"); needs_space = true; } @@ -5113,7 +5072,7 @@ pub mod formatter { } return Ok(()); }; - let mut props_iter = jsc::JSPropertyIterator::init( + let props_iter = jsc::JSPropertyIterator::init( self.global_this, props_obj, jsc::PropertyIteratorOptions { @@ -5130,13 +5089,11 @@ pub mod formatter { let count_without_children = props_iter.len - usize::from(children_prop.is_some()); - while let Some(prop) = props_iter.next()? { - let props_i = props_iter.i as usize; + while let Some((prop, property_value)) = props_iter.next()? { if prop.eql_comptime("children") { continue; } - let property_value = props_iter.value; let tag = Tag::get_advanced(property_value, self.global_this, tag_opts)?; @@ -5156,6 +5113,7 @@ pub mod formatter { pf!(""), pf!("") )); + let props_i = props_iter.i.get() as usize; if tag.cell.is_string_like() && C { writer.write_all(pfmt!("", true).as_bytes()); @@ -5208,15 +5166,15 @@ pub mod formatter { match tag.tag.tag() { Tag::String => { let children_string = - children.get_zig_string(self.global_this)?; - if children_string.len == 0 { + children.to_js_string_view(self.global_this)?; + if children_string.is_empty() { break 'print_children; } if C { writer.write_all(pfmt!("", true).as_bytes()); } writer.write_all(b">"); - if children_string.len < 128 { + if children_string.length() < 128 { writer.write_string(&children_string); } else { self.indent += 1; diff --git a/src/jsc/Debugger.rs b/src/jsc/Debugger.rs index 5f7bd0254bd0..02f850138b13 100644 --- a/src/jsc/Debugger.rs +++ b/src/jsc/Debugger.rs @@ -156,15 +156,15 @@ impl Default for Debugger { } // SAFETY (safe fn): `JSGlobalObject` is an opaque `UnsafeCell`-backed handle -// (`&` is ABI-identical to non-null `*mut`); `BunString` is a `#[repr(C)]` POD -// out-param. Remaining args are by-value scalars. +// (`&` is ABI-identical to non-null `*mut`); `BunString` is a `#[repr(C)]` +// in-param C++ only reads. Remaining args are by-value scalars. unsafe extern "C" { safe fn Bun__createJSDebugger(global: &JSGlobalObject) -> u32; safe fn Bun__ensureDebugger(ctx_id: u32, wait: bool); safe fn Bun__startJSDebuggerThread( global: &JSGlobalObject, ctx_id: u32, - url: &mut BunString, + url: &BunString, from_env: c_int, is_connect: bool, is_node_inspector: bool, @@ -487,15 +487,15 @@ impl Debugger { } = init; if !from_env.is_empty() { - let mut url = BunString::clone_utf8(from_env); + let url = BunString::borrow_utf8(from_env); let _scope = this.enter_event_loop_scope(); - Bun__startJSDebuggerThread(global, ctx_id, &mut url, 1, is_connect, false); + Bun__startJSDebuggerThread(global, ctx_id, &url, 1, is_connect, false); } if let Some(path_or_port) = path_or_port { - let mut url = BunString::clone_utf8(path_or_port); + let url = BunString::borrow_utf8(path_or_port); let _scope = this.enter_event_loop_scope(); - Bun__startJSDebuggerThread(global, ctx_id, &mut url, 0, is_connect, is_node_inspector); + Bun__startJSDebuggerThread(global, ctx_id, &url, 0, is_connect, is_node_inspector); } let _ = this.global().handle_rejected_promises(); @@ -554,7 +554,7 @@ pub fn start_node_inspector_server(url: &mut BunString, wait_for_connection: boo // The URL outlives the process: the debugger struct stores `'static` slices // (CLI-arena lifetimes), so leak the runtime-provided URL the same way. - let url_bytes: &'static [u8] = Box::leak(url.to_utf8_bytes().into_boxed_slice()); + let url_bytes: &'static [u8] = Box::leak(url.to_owned_slice().into_boxed_slice()); this.as_mut().debugger = Some(Box::new(Debugger { path_or_port: Some(url_bytes), wait_for_connection: if wait_for_connection { @@ -808,17 +808,17 @@ unsafe extern "C" { agent: &mut TestReporterHandle, call_frame: &CallFrame, test_id: c_int, - name: &mut BunString, + name: &BunString, item_type: TestType, parent_id: c_int, ); safe fn Bun__TestReporterAgentReportTestFoundWithLocation( agent: &mut TestReporterHandle, test_id: c_int, - name: &mut BunString, + name: &BunString, item_type: TestType, parent_id: c_int, - source_url: &mut BunString, + source_url: &BunString, line: c_int, ); safe fn Bun__TestReporterAgentReportTestStart(agent: &mut TestReporterHandle, test_id: c_int); @@ -835,7 +835,7 @@ impl TestReporterHandle { &mut self, call_frame: &CallFrame, test_id: i32, - name: &mut BunString, + name: &BunString, item_type: TestType, parent_id: i32, ) { @@ -847,10 +847,10 @@ impl TestReporterHandle { pub fn report_test_found_with_location( &mut self, test_id: i32, - name: &mut BunString, + name: &BunString, item_type: TestType, parent_id: i32, - source_url: &mut BunString, + source_url: &BunString, line: i32, ) { Bun__TestReporterAgentReportTestFoundWithLocation( @@ -929,7 +929,7 @@ impl TestReporterAgent { &self, call_frame: &CallFrame, test_id: i32, - name: &mut BunString, + name: &BunString, item_type: TestType, parent_id: i32, ) { diff --git a/src/jsc/ErrorCode.rs b/src/jsc/ErrorCode.rs index 3a310be7472b..2d2442a32ca6 100644 --- a/src/jsc/ErrorCode.rs +++ b/src/jsc/ErrorCode.rs @@ -44,9 +44,7 @@ impl GlobalObjectRef for crate::JSGlobalObject { type ErrorCodeInt = u16; -/// `Bun::ErrorCode` in C++. Modelled as a newtype-over-`u16` so the same type -/// can also carry the legacy sentinels (`PARSER_ERROR` / `JS_ERROR_OBJECT`) -/// without an exhaustive-match obligation. +/// `Bun::ErrorCode` in C++. #[repr(transparent)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct ErrorCode(pub ErrorCodeInt); @@ -62,14 +60,6 @@ include!(concat!(env!("BUN_CODEGEN_DIR"), "/ErrorCode.generated.rs")); // `ERR_SYSTEM_ERROR`): `Bun__createErrorWithCode` indexes `errors[COUNT]` // unchecked. Codes outside ErrorCode.ts go on `SystemError.code` as a literal. -// ────────────────────────────────────────────────────────────────────────── -// Legacy anyerror-wrapper sentinels. -// ────────────────────────────────────────────────────────────────────────── -impl ErrorCode { - pub(crate) const PARSER_ERROR: ErrorCodeInt = 0xFFFE; - pub const JS_ERROR_OBJECT: ErrorCodeInt = 0xFFFD; -} - impl ErrorCode { /// Node `error.code` string (e.g. `"ERR_INVALID_ARG_TYPE"`). #[inline] @@ -84,15 +74,12 @@ impl ErrorCode { /// `Bun__createErrorWithCode`, and returns the constructed Error JSValue. /// The C++ side picks the ctor / `.name` / `.code` from `errors[self.0]`. pub fn fmt(self, global: &G, args: Arguments<'_>) -> JSValue { - let mut message = bun_core::String::create_format(args); + let message = bun_core::String::create_format(args); // `G` is one of the two `#[repr(C)]` opaque ZST `JSGlobalObject` // handles (see `GlobalObjectRef` doc); `opaque_ref` is the safe - // ZST-handle deref proof (panics on null). C++ clones the impl into a - // JSString; `message` is deref'd below after the call. + // ZST-handle deref proof (panics on null). let global = JSGlobalObject::opaque_ref(global.as_global_ptr().cast::()); - let v = Bun__createErrorWithCode(global, self, &mut message); - message.deref(); - v + Bun__createErrorWithCode(global, self, &message) } /// `Error.throw(this, globalThis, fmt, args)` — `.fmt` then @@ -124,7 +111,7 @@ unsafe extern "C" { safe fn Bun__createErrorWithCode( global: &JSGlobalObject, code: ErrorCode, - message: &mut bun_core::String, + message: &bun_core::String, ) -> JSValue; } @@ -165,13 +152,4 @@ impl<'a, G: GlobalObjectRef + ?Sized> ErrorBuilder<'a, G> { } } -// C++ compares parser-error sentinels against these exported statics -// (`extern "C" ZigErrorCode Zig_ErrorCodeParserError;`, headers-handwritten.h). - -#[unsafe(no_mangle)] -static Zig_ErrorCodeParserError: ErrorCodeInt = ErrorCode::PARSER_ERROR; - -#[unsafe(no_mangle)] -static Zig_ErrorCodeJSErrorObject: ErrorCodeInt = ErrorCode::JS_ERROR_OBJECT; - // ported from: src/jsc/bindings/ErrorCode.ts diff --git a/src/jsc/Errorable.rs b/src/jsc/Errorable.rs index 4bedea4943bc..dbb654ccaa3a 100644 --- a/src/jsc/Errorable.rs +++ b/src/jsc/Errorable.rs @@ -1,46 +1,53 @@ +use core::mem::ManuallyDrop; + use crate::JSValue; -use crate::error_code::ErrorCode; -use crate::zig_error_type::ZigErrorType; +/// C++ `Errorable*` (headers-handwritten.h): `{ union { T value; EncodedJSValue err; }; bool success; }`. +/// Owns `value` when `success`; the frame that declares it (Rust or C++) is +/// responsible for dropping it, and consumers take fields out by transfer. #[repr(C)] -pub struct Errorable { +pub struct Errorable { pub result: Result, pub success: bool, } #[repr(C)] -pub union Result { - pub value: T, - pub err: ZigErrorType, +pub union Result { + pub value: ManuallyDrop, + pub err: JSValue, } -impl Errorable { - pub(crate) fn unwrap(self) -> core::result::Result { - if self.success { - // SAFETY: success == true implies the `value` arm is active. - unsafe { Ok(self.result.value) } - } else { - // SAFETY: success == false implies the `err` arm is active. - unsafe { Err(self.result.err.code) } - } - } - +impl Errorable { pub fn ok(val: T) -> Self { Self { - result: Result { value: val }, + result: Result { + value: ManuallyDrop::new(val), + }, success: true, } } - pub fn err(code: ErrorCode, err_value: JSValue) -> Self { + /// `value` is the JS error to throw/reject with. + pub fn err(value: JSValue) -> Self { + // SAFETY: a union has no validity invariant; zeroing the whole of it + // means C++ never sees uninitialized bytes in the `value` arm. + let mut result: Result = unsafe { core::mem::MaybeUninit::zeroed().assume_init() }; + result.err = value; Self { - result: Result { - err: ZigErrorType { - code, - value: err_value, - }, - }, + result, success: false, } } } + +bun_core::assert_ffi_layout!(Errorable, 144, 8); +bun_core::assert_ffi_layout!(Errorable, 32, 8); + +impl Drop for Errorable { + fn drop(&mut self) { + if self.success { + // SAFETY: success == true implies the `value` arm is active. + unsafe { ManuallyDrop::drop(&mut self.result.value) } + } + } +} diff --git a/src/jsc/FetchHeaders.rs b/src/jsc/FetchHeaders.rs index 5f019f49bd6e..c71f0a0d8809 100644 --- a/src/jsc/FetchHeaders.rs +++ b/src/jsc/FetchHeaders.rs @@ -14,7 +14,7 @@ bun_opaque::opaque_ffi! { // `FetchHeaders`/`JSGlobalObject`/`VM` are opaque `UnsafeCell`-backed ZST // handles, so `&T` is ABI-identical to a non-null `*const T` and C++ mutating // header storage / VM state through them is interior mutation invisible to -// Rust. `ZigString` and `String` (`BunString`) are plain `#[repr(C)]` PODs; +// Rust. `ZigString` and `String` (`BunString`) are plain `#[repr(C)]` structs; // `&`/`&mut` refs to them at the FFI boundary are sound (C++ reads/writes // only the named struct). // Shims that traffic only in such refs + scalars are declared `safe fn`; those diff --git a/src/jsc/HTTPServerAgent.rs b/src/jsc/HTTPServerAgent.rs index f222b9a6ac5a..67e0fe073571 100644 --- a/src/jsc/HTTPServerAgent.rs +++ b/src/jsc/HTTPServerAgent.rs @@ -40,6 +40,7 @@ pub struct Route { pub path: BunString, pub r#type: RouteType, pub script_line: i32, + /// Unused; always null/0 (kept for the C++ layout). pub param_names: *mut BunString, pub param_names_len: usize, pub file_path: BunString, @@ -72,22 +73,6 @@ impl Default for Route { } } -impl Drop for Route { - fn drop(&mut self) { - if !self.param_names.is_null() { - let slice = core::ptr::slice_from_raw_parts_mut(self.param_names, self.param_names_len); - // SAFETY: param_names was allocated via the global (mimalloc) allocator as a - // contiguous [BunString; param_names_len]. Reconstructing the Box drops each - // element (deref) and frees the backing storage. - drop(unsafe { bun_core::heap::take(slice) }); - self.param_names = core::ptr::null_mut(); - self.param_names_len = 0; - } - // path, file_path, script_id, script_url are dropped (deref'd) automatically via - // bun_core::String's Drop impl. - } -} - // #endregion // #region C++ agent reference type diff --git a/src/jsc/JSFunction.rs b/src/jsc/JSFunction.rs index c661d70b2693..7fe841a60423 100644 --- a/src/jsc/JSFunction.rs +++ b/src/jsc/JSFunction.rs @@ -49,7 +49,7 @@ pub struct CreateJSFunctionOptions { unsafe extern "C" { safe fn JSFunction__createFromZig( global: &JSGlobalObject, - fn_name: BunString, + fn_name: &BunString, implementation: JSHostFn, arg_count: u32, implementation_visibility: ImplementationVisibility, @@ -63,14 +63,14 @@ unsafe extern "C" { impl JSFunction { pub fn create( global: &JSGlobalObject, - fn_name: impl Into, + fn_name: &'static str, implementation: JSHostFn, function_length: u32, options: CreateJSFunctionOptions, ) -> JSValue { JSFunction__createFromZig( global, - fn_name.into(), + &BunString::static_(fn_name), implementation, function_length, options.implementation_visibility, diff --git a/src/jsc/JSGlobalObject.rs b/src/jsc/JSGlobalObject.rs index 88922b9edf19..46e25ca8cba4 100644 --- a/src/jsc/JSGlobalObject.rs +++ b/src/jsc/JSGlobalObject.rs @@ -14,7 +14,7 @@ use crate::{ }; use bun_core::{Output, fmt as bun_fmt}; -use bun_core::{OwnedString, String as BunString, strings}; +use bun_core::{String as BunString, strings}; // ────────────────────────────────────────────────────────────────────────────── // Opaque FFI handle (Nomicon pattern; !Send + !Sync + !Unpin). @@ -294,7 +294,7 @@ impl JSGlobalObject { debug_assert!(self.has_exception()); return JsError::Thrown; } - let name_value = match BunString::static_str("TODOError").to_js(self) { + let name_value = match BunString::static_("TODOError").to_js(self) { Ok(v) => v, Err(_) => return JsError::Thrown, }; @@ -397,7 +397,6 @@ impl JSGlobalObject { /// "The {argname} argument is invalid. Received {value}" pub fn throw_invalid_argument_value(&self, argname: &[u8], value: JSValue) -> JsError { - // `defer actual_string_value.deref()` → OwnedString's Drop releases the +1 ref. let actual_string_value = match Self::determine_specific_type(self, value) { Ok(s) => s, Err(e) => return e, @@ -473,29 +472,23 @@ impl JSGlobalObject { } } - /// Returns a +1-ref'd `BunString` describing `value`'s type for error messages. - /// The result is wrapped in [`OwnedString`] so the ref is released on drop — - /// `bun_core::String` is `Copy` and has no `Drop`, so a bare `BunString` - /// here would leak. - pub fn determine_specific_type(global: &Self, value: JSValue) -> JsResult { + /// Describes `value`'s type for error messages. + pub fn determine_specific_type(global: &Self, value: JSValue) -> JsResult { // The C++ side opens a `DECLARE_THROW_SCOPE`; under // `BUN_JSC_validateExceptionChecks=1` its dtor sets `m_needExceptionCheck`, so we // must have a Rust-side scope live across the FFI call (and query it) rather than // post-hoc `has_exception()` (whose own scope ctor would assert first). crate::top_scope!(scope, global); - // `errdefer str.deref()` → wrapping immediately in OwnedString releases the - // +1 ref on the early-return path below. - let str = OwnedString::new(Bun__ErrorCode__determineSpecificType(global, value)); + let str = Bun__ErrorCode__determineSpecificType(global, value); scope.return_if_exception()?; Ok(str) } /// Renders `value` the way Node's `ERR_INVALID_ARG_VALUE` does (`util.inspect` - /// quoting, via the same C++ formatter the C++ overloads use). Returns a - /// +1-ref'd string wrapped in [`OwnedString`] so the ref is released on drop. - pub fn inspect_for_error_message(global: &Self, value: JSValue) -> JsResult { + /// quoting, via the same C++ formatter the C++ overloads use). + pub fn inspect_for_error_message(global: &Self, value: JSValue) -> JsResult { crate::top_scope!(scope, global); - let str = OwnedString::new(Bun__ErrorCode__inspectForErrorMessage(global, value)); + let str = Bun__ErrorCode__inspectForErrorMessage(global, value); scope.return_if_exception()?; Ok(str) } @@ -598,14 +591,7 @@ impl JSGlobalObject { expected_type: &str, value: JSValue, ) -> JsError { - let actual_type = if value.js_type().is_array() { - bun_core::ZigString::static_(b"array") - } else { - match value.js_type_string(self).get_zig_string(self) { - Ok(s) => s, - Err(e) => return e, - } - }; + let actual_type = value.type_name(self); self.err( JscError::INVALID_ARG_TYPE, format_args!( @@ -647,19 +633,14 @@ impl JSGlobalObject { typename: &[u8], value: JSValue, ) -> JsError { - // `ZigStringSlice` is RAII: `Owned` frees - // its `Vec`, `WTF` derefs the backing `WTFStringImpl` in `Drop`. - let ty_str = match value.js_type_string(self).to_slice(self) { - Ok(s) => s, - Err(e) => return e, - }; + let ty_str = value.js_type_string(self); self.err( JscError::INVALID_ARG_TYPE, format_args!( "The \"{}\" property must be of type {}. Received {}", bstr::BStr::new(field), bstr::BStr::new(typename), - bstr::BStr::new(ty_str.slice()) + ty_str ), ) .throw() @@ -704,14 +685,14 @@ impl JSGlobalObject { pub(crate) fn run_on_load_plugins( &self, - namespace_: BunString, - path: BunString, + namespace_: &BunString, + path: &BunString, target: BunPluginTarget, ) -> JsResult> { crate::mark_binding(); - let ns = (namespace_.length() > 0).then_some(&namespace_); + let ns = (namespace_.length() > 0).then_some(namespace_); let result = - crate::from_js_host_call(self, || Bun__runOnLoadPlugins(self, ns, &path, target))?; + crate::from_js_host_call(self, || Bun__runOnLoadPlugins(self, ns, path, target))?; if result.is_undefined_or_null() { return Ok(None); } @@ -720,15 +701,15 @@ impl JSGlobalObject { pub(crate) fn run_on_resolve_plugins( &self, - namespace_: BunString, - path: BunString, - source: BunString, + namespace_: &BunString, + path: &BunString, + source: &BunString, target: BunPluginTarget, ) -> JsResult> { crate::mark_binding(); - let ns = (namespace_.length() > 0).then_some(&namespace_); + let ns = (namespace_.length() > 0).then_some(namespace_); let result = crate::from_js_host_call(self, || { - Bun__runOnResolvePlugins(self, ns, &path, &source, target) + Bun__runOnResolvePlugins(self, ns, path, source, target) })?; if result.is_undefined_or_null() { return Ok(None); @@ -741,7 +722,7 @@ impl JSGlobalObject { // there are no interpolated args — fast path for constant messages. if let Some(fmt) = args.as_str() { if strings::is_all_ascii(fmt.as_bytes()) { - return BunString::static_str(fmt).to_error_instance(self); + return BunString::static_(fmt).to_error_instance(self); } else { return ZigString::init_utf8(fmt.as_bytes()).to_error_instance(self); } @@ -971,7 +952,7 @@ impl JSGlobalObject { pub fn create_aggregate_error_with_array( &self, - message: BunString, + message: &BunString, error_array: JSValue, ) -> JsResult { debug_assert!(error_array.is_array()); @@ -1448,31 +1429,24 @@ use bun_core::fmt::VecWriter as WriteVec; // ────────────────────────────────────────────────────────────────────────────── #[unsafe(no_mangle)] -unsafe extern "C" fn Zig__GlobalObject__resolve( - res: *mut ErrorableString, - global: *const JSGlobalObject, - specifier: *mut BunString, - source: *mut BunString, - query: *mut BunString, +extern "C" fn Zig__GlobalObject__resolve( + res: &mut ErrorableString, + global: &JSGlobalObject, + specifier: &BunString, + source: &BunString, + query: &mut BunString, ) { crate::mark_binding(); - // SAFETY: C++ passes valid non-null pointers. `BunString` is `Copy`, so - // `*specifier` / `*source` is a bitwise load — no refcount bump (the - // caller still owns the ref). - let (global, specifier, source) = unsafe { (&*global, *specifier, *source) }; - // SAFETY: C++ passes valid non-null pointers. - let (res, query) = unsafe { (&mut *res, &mut *query) }; - if VirtualMachine::resolve( - res, + match VirtualMachine::resolve_maybe_needs_trailing_slash::( global, specifier, source, Some(query), crate::virtual_machine::ResolveMode::Esm, - ) - .is_err() - { - debug_assert!(global.has_exception()); + ) { + Ok(Ok(path)) => *res = ErrorableString::ok(path), + Ok(Err(value)) => *res = ErrorableString::err(value), + Err(_) => debug_assert!(global.has_exception()), } } @@ -1575,7 +1549,7 @@ unsafe extern "C" { safe fn JSC__JSGlobalObject__createAggregateErrorWithArray( global: &JSGlobalObject, error_array: JSValue, - message: BunString, + message: &BunString, options: JSValue, ) -> JSValue; safe fn JSC__JSGlobalObject__generateHeapSnapshot(this: &JSGlobalObject) -> JSValue; diff --git a/src/jsc/JSObject.rs b/src/jsc/JSObject.rs index 4ef2f43c9cfe..5834b28293e3 100644 --- a/src/jsc/JSObject.rs +++ b/src/jsc/JSObject.rs @@ -234,20 +234,11 @@ impl Default for ExternColumnIdentifier { } } -impl ExternColumnIdentifier { - pub(crate) fn string(&mut self) -> Option<&mut BunString> { - match self.tag { - // SAFETY: tag == 2 means `value.name` is the active union field. - 2 => Some(unsafe { &mut *self.value.name }), - _ => None, - } - } -} - impl Drop for ExternColumnIdentifier { fn drop(&mut self) { - if let Some(str) = self.string() { - str.deref(); + if self.tag == 2 { + // SAFETY: tag == 2 means `value.name` is the active union field. + unsafe { core::mem::ManuallyDrop::drop(&mut self.value.name) }; } } } diff --git a/src/jsc/JSPropertyIterator.rs b/src/jsc/JSPropertyIterator.rs index 9d1d399a00c4..77fb7017e9bf 100644 --- a/src/jsc/JSPropertyIterator.rs +++ b/src/jsc/JSPropertyIterator.rs @@ -1,8 +1,8 @@ +use core::cell::Cell; use core::ptr::NonNull; use crate::host_fn::from_js_host_call_generic; use crate::{JSGlobalObject, JSObject, JSValue, JsResult}; -use bun_core as bstr; /// Runtime flag set passed to [`JSPropertyIterator::init`]. /// @@ -100,19 +100,14 @@ impl IntoIterObject for &mut JSObject { pub struct JSPropertyIterator<'a> { pub len: usize, - pub(crate) i: u32, - pub(crate) iter_i: u32, + /// Index of the property last yielded by `next()`. + pub(crate) i: Cell, + iter_i: Cell, /// null if and only if `object` has no properties (i.e. `len == 0`) pub(crate) impl_: Option>, pub(crate) global_object: &'a JSGlobalObject, pub(crate) object: *mut JSObject, - /// Current property value being yielded (only meaningful when - /// `options.include_value` is set). - // The bare JSValue field is sound because this struct is stack-only (`'a` borrow); - // conservative stack scan keeps it alive. Do NOT box this struct. - pub value: JSValue, - options: JSPropertyIteratorOptions, } @@ -158,29 +153,30 @@ impl<'a> JSPropertyIterator<'a> { Ok(Self { len, - i: 0, - iter_i: 0, + i: Cell::new(0), + iter_i: Cell::new(0), impl_, global_object, object, - value: JSValue::ZERO, options, }) } - /// The bun.String returned has not incremented its reference count. - pub fn next(&mut self) -> JsResult> { - // Reuse stack space. + /// The name borrows the C++ iterator's storage (no ref) and is valid until + /// `self` drops, hence `&self`: a yielded name may be held across later + /// calls. The value is `JSValue::ZERO` unless `options.include_value`. + pub fn next(&self) -> JsResult, JSValue)>> { loop { - let i: usize = self.iter_i as usize; + let i: usize = self.iter_i.get() as usize; if i >= self.len { - self.i = self.iter_i; + self.i.set(self.iter_i.get()); return Ok(None); } - self.i = self.iter_i; - self.iter_i += 1; - let mut name = bstr::String::DEAD; + self.i.set(self.iter_i.get()); + self.iter_i.set(self.iter_i.get() + 1); + let mut name = bun_core::StringView::DEAD; + let mut value = JSValue::ZERO; if self.options.include_value { let iter = self.impl_.expect("len > 0 implies impl_ is Some").as_ptr(); // `JSPropertyIteratorImpl`/`JSObject` are opaque ZST handles; @@ -208,7 +204,7 @@ impl<'a> JSPropertyIterator<'a> { continue; } current.ensure_still_alive(); - self.value = current; + value = current; } else { // Exception check is unnecessary here because it won't throw. let iter = self.impl_.expect("len > 0 implies impl_ is Some").as_ptr(); @@ -229,7 +225,7 @@ impl<'a> JSPropertyIterator<'a> { continue; } - return Ok(Some(name)); + return Ok(Some((name, value))); } } } @@ -272,7 +268,7 @@ impl JSPropertyIteratorImpl { iter: &mut JSPropertyIteratorImpl, global_object: &JSGlobalObject, object: &JSObject, - property_name: &mut bstr::String, + property_name: &mut bun_core::StringView<'_>, i: usize, ) -> JsResult { // The FFI may return `.zero` without throwing, so the non-generic @@ -287,7 +283,7 @@ impl JSPropertyIteratorImpl { iter: &mut JSPropertyIteratorImpl, global_object: &JSGlobalObject, object: &JSObject, - property_name: &mut bstr::String, + property_name: &mut bun_core::StringView<'_>, i: usize, ) -> JsResult { from_js_host_call_generic(global_object, || { @@ -304,7 +300,7 @@ impl JSPropertyIteratorImpl { // safe fn: `JSPropertyIteratorImpl`/`JSGlobalObject`/`JSObject` are `opaque_ffi!` // ZST handles (`&`/`&mut` are ABI-identical to non-null `*const`/`*mut`); -// `bstr::String` is a `#[repr(C)]` out-param the C++ side fills in-place; remaining +// `StringView` is a 24-byte out-param the C++ side fills in-place (borrowed, +0); remaining // args are by-value scalars. Only `deinit` (frees the allocation) keeps a raw // `*mut` and stays `unsafe`. unsafe extern "C" { @@ -320,19 +316,19 @@ unsafe extern "C" { iter: &mut JSPropertyIteratorImpl, global_object: &JSGlobalObject, object: &JSObject, - property_name: &mut bstr::String, + property_name: &mut bun_core::StringView<'_>, i: usize, ) -> JSValue; safe fn Bun__JSPropertyIterator__getNameAndValueNonObservable( iter: &mut JSPropertyIteratorImpl, global_object: &JSGlobalObject, object: &JSObject, - property_name: &mut bstr::String, + property_name: &mut bun_core::StringView<'_>, i: usize, ) -> JSValue; safe fn Bun__JSPropertyIterator__getName( iter: &mut JSPropertyIteratorImpl, - property_name: &mut bstr::String, + property_name: &mut bun_core::StringView<'_>, i: usize, ); fn Bun__JSPropertyIterator__deinit(iter: *mut JSPropertyIteratorImpl); diff --git a/src/jsc/JSString.rs b/src/jsc/JSString.rs index ef62ea7fb9ff..35d88023068b 100644 --- a/src/jsc/JSString.rs +++ b/src/jsc/JSString.rs @@ -1,7 +1,7 @@ use core::ffi::c_void; use crate::{JSGlobalObject, JSValue, JsResult}; -use bun_core::ZigString; +use bun_core::StringView; use bun_core::zig_string::Slice as ZigStringSlice; bun_opaque::opaque_ffi! { @@ -9,15 +9,11 @@ bun_opaque::opaque_ffi! { pub struct JSString; } -// NOTE: the C++ side may mutate through several of these `*JSString` / -// `*JSGlobalObject` params, but the C ABI does not distinguish `*const T` from `*mut T`. We -// intentionally declare them `*const` here — matching the convention in -// JSGlobalObject.rs / JSValue.rs — so that callers can pass `&self` / `&global` -// directly without an `as *const _ as *mut _` cast. `JSString` and -// `JSGlobalObject` are opaque zero-sized handles in Rust, so a shared `&` borrow -// covers zero bytes and C++ mutating the underlying GC cell does not violate -// Rust's aliasing rules. unsafe extern "C" { + pub(crate) safe fn JSC__JSString__view<'a>( + this: &'a JSString, + global: &JSGlobalObject, + ) -> StringView<'a>; fn JSC__JSString__iterator(this: &JSString, global_object: &JSGlobalObject, iter: *mut c_void); safe fn JSC__JSString__length(this: &JSString) -> usize; safe fn JSC__JSString__is8Bit(this: &JSString) -> bool; @@ -28,53 +24,19 @@ impl JSString { JSValue::from_cell(self) } - pub(crate) fn to_zig_string( - &self, - global: &JSGlobalObject, - zig_str: &mut ZigString, - ) -> JsResult<()> { - // SAFETY: `zig_str` is a live out-parameter for the duration of the call. - unsafe { crate::cpp::JSC__JSString__toZigString(self, global, zig_str) } - } - + #[inline] pub fn ensure_still_alive(&self) { // Keep the cell pointer observable to the GC's conservative stack scan. core::hint::black_box(std::ptr::from_ref::(self)); } - pub fn get_zig_string(&self, global: &JSGlobalObject) -> JsResult { - let mut out = ZigString::init(b""); - self.to_zig_string(global, &mut out)?; - Ok(out) - } - - #[inline] - pub fn view(&self, global: &JSGlobalObject) -> JsResult { - self.get_zig_string(global) - } - - /// doesn't always allocate - pub fn to_slice(&self, global: &JSGlobalObject) -> JsResult { - let mut str = ZigString::init(b""); - self.to_zig_string(global, &mut str)?; - Ok(str.to_slice()) - } - - // `to_slice_clone` always allocates - // an owned UTF-8 copy so the result outlives the GC'd JSString. Returning - // `to_slice()` here (a borrow that may alias JSC-owned memory) would hand - // callers a use-after-free once the cell is collected. - - pub fn to_slice_clone(&self, global: &JSGlobalObject) -> JsResult { - let mut str = ZigString::init(b""); - self.to_zig_string(global, &mut str)?; - Ok(str.to_slice_clone()) + /// Throws when resolving a rope runs out of memory. + #[track_caller] + pub fn view<'a>(&'a self, global: &JSGlobalObject) -> JsResult> { + let view = crate::call_check_slow(global, || JSC__JSString__view(self, global))?; + Ok(JSStringView { cell: self, view }) } - // `to_slice_z` guarantees a trailing NUL - // sentinel. `to_slice()` is not NUL-terminated; passing it to a C API that - // expects one reads past the buffer end. - pub fn iterator(&self, global_object: &JSGlobalObject, iter: &mut Iterator) { // SAFETY: `self`/`global_object` are valid opaque GC-cell handles; `iter` // is a caller-owned `Iterator` (extern struct) passed through to C++. @@ -90,6 +52,46 @@ impl JSString { } } +/// A JSString's characters, borrowed via `JSString::view` (a substring rope +/// is viewed in place, not flattened). Keeps the cell observable to the GC's +/// conservative stack scan until dropped (the Rust counterpart of +/// `GCOwnedDataScope`), so a string `toString()` just created cannot be +/// collected while its characters are in use. +pub struct JSStringView<'a> { + pub(crate) cell: &'a JSString, + pub(crate) view: StringView<'a>, +} + +impl JSStringView<'_> { + /// UTF-8 bytes; borrows when 8-bit ASCII, allocates otherwise. Never refs. + #[inline] + pub fn to_utf8(&self) -> ZigStringSlice { + self.view.to_utf8() + } +} + +impl core::ops::Deref for JSStringView<'_> { + type Target = bun_core::String; + + #[inline] + fn deref(&self) -> &bun_core::String { + &self.view + } +} + +impl core::fmt::Display for JSStringView<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::Display::fmt(&*self.view, f) + } +} + +impl Drop for JSStringView<'_> { + #[inline] + fn drop(&mut self) { + self.cell.ensure_still_alive(); + } +} + pub(crate) type JStringIteratorAppend8Callback = unsafe extern "C" fn(*mut Iterator, *const u8, u32); pub(crate) type JStringIteratorAppend16Callback = diff --git a/src/jsc/JSValue.rs b/src/jsc/JSValue.rs index 791e86e4681c..4a9b816e4613 100644 --- a/src/jsc/JSValue.rs +++ b/src/jsc/JSValue.rs @@ -12,7 +12,7 @@ use core::marker::PhantomData; use crate::array_buffer::MarkedArrayBuffer_deallocator; use crate::{ AnyPromise, ArrayBuffer, BuiltinName, JSArrayIterator, JSGlobalObject, JSInternalPromise, - JSObject, JSPromise, JSString, JSType, JsClass, JsError, JsResult, ZigException, + JSObject, JSPromise, JSString, JSStringView, JSType, JsClass, JsError, JsResult, ZigException, bun_string_jsc, ffi, host_fn, }; @@ -843,51 +843,29 @@ impl JSValue { } #[track_caller] pub fn to_js_string<'a>(self, global: &'a JSGlobalObject) -> JsResult<&'a JSString> { - // `[[ZIG_EXPORT(null_is_throw)]]` — null ⟺ threw. - // S008: `JSString` is an `opaque_ffi!` ZST, so the non-null pointer - // returned on the `Ok` path is safely reborrowed via `opaque_ref` - // (zero-byte deref; see `bun_opaque::opaque_deref`). crate::call_null_is_throw(global, || JSC__JSValue__toStringOrNull(self, global)) .map(|p| JSString::opaque_ref(p.as_ptr())) } + /// [`to_js_string`] plus a borrowed view of its characters, in one FFI + /// call. The returned guard keeps the cell alive while in scope. + #[track_caller] + pub fn to_js_string_view<'a>(self, global: &'a JSGlobalObject) -> JsResult> { + let mut view = bun_core::StringView::EMPTY; + crate::call_null_is_throw(global, || { + JSC__JSValue__toJSStringView(self, global, &mut view) + }) + .map(|p| JSStringView { + cell: JSString::opaque_ref(p.as_ptr()), + view, + }) + } pub fn to_bun_string(self, global: &JSGlobalObject) -> JsResult { bun_string_jsc::from_js(self, global) } - pub fn to_zig_string( - self, - out: &mut bun_core::ZigString, - global: &JSGlobalObject, - ) -> JsResult<()> { - host_fn::from_js_host_call_generic(global, || JSC__JSValue__toZigString(self, out, global)) - } + /// `toString()` then UTF-8. The slice holds its own ref/allocation, so it + /// is independent of the `JSString` cell. pub fn to_slice(self, global: &JSGlobalObject) -> JsResult { - // `to_bun_string` returns a +1 ref; `bun_core::String` is - // `Copy` (no `Drop`), so wrap in `OwnedString` for the scope-exit - // `deref()`. `to_utf8()` takes its own ref (or owned alloc) so the - // slice survives the drop. - let s = bun_core::OwnedString::new(self.to_bun_string(global)?); - Ok(s.to_utf8()) - } - /// Call `toString()` on the JSValue and clone the result. - /// On exception or out of memory, this returns a `JsError`. - /// - /// Remember that `Symbol` throws an exception when you call `toString()`. - /// - /// The returned slice is *always* heap-owned and independent of the backing - /// `JSString` cell, so it outlives GC. Allocator param dropped per - /// PORTING.md (default_allocator only). - pub fn to_slice_clone(self, global: &JSGlobalObject) -> JsResult { - self.to_js_string(global)?.to_slice_clone(global) - } - /// Call `toString()` on the JSValue and clone the result. - /// - /// `bun_core::String` is `Copy` and has NO `Drop`; `OwnedString` provides - /// the scope-exit `deref()`. `to_utf8()` refs the - /// underlying WTFStringImpl (or heap-clones) so the slice survives the - /// `OwnedString` drop. - pub fn to_slice_or_null(self, global: &JSGlobalObject) -> JsResult { - let s = bun_core::OwnedString::new(self.to_bun_string(global)?); - Ok(s.to_utf8()) + Ok(self.to_bun_string(global)?.into_utf8()) } pub fn to_zig_exception(self, global: &JSGlobalObject, exception: &mut ZigException) { JSC__JSValue__toZigException(self, global, exception) @@ -904,17 +882,26 @@ impl JSValue { ) -> JsResult { E::from_js_value(self, global, property_name) } - pub fn as_string(self) -> *mut JSString { + pub fn as_string(self) -> &'static JSString { debug_assert!(self.is_string_literal()); - JSC__JSValue__asString(self) + JSString::opaque_ref(JSC__JSValue__asString(self)) + } + /// JS `typeof`, or `"array"` for arrays. + pub fn type_name<'a>(self, global: &'a JSGlobalObject) -> bun_core::StringView<'a> { + if self.js_type().is_array() { + return bun_core::StringView::static_(b"array"); + } + self.js_type_string(global) } - /// `jsTypeString()` — calls `JSC::jsTypeStringForValue`, returning the - /// JS `typeof` result as a `JSString*` cell (e.g. `"object"`, `"number"`). - /// Never throws; lifetime tied to `global` (cell is GC-rooted by the VM's - /// SmallStrings table). - pub fn js_type_string<'a>(self, global: &'a JSGlobalObject) -> &'a JSString { - // FFI returns a non-null SmallStrings cell (opaque ZST handle). - JSString::opaque_ref(JSC__jsTypeStringForValue(global, self)) + /// `jsTypeString()` — the JS `typeof` result (e.g. `"object"`, `"number"`). + /// Never throws; the backing cell is GC-rooted by the VM's SmallStrings + /// table. + pub fn js_type_string<'a>(self, global: &'a JSGlobalObject) -> bun_core::StringView<'a> { + let cell = JSString::opaque_ref::<'a>(JSC__jsTypeStringForValue(global, self)); + crate::validation_scope!(scope, global); + let view = crate::js_string::JSC__JSString__view(cell, global); + scope.assert_no_exception(); + view } pub fn as_array_buffer(self, global: &JSGlobalObject) -> Option { let mut out = ArrayBuffer::default(); @@ -1079,14 +1066,6 @@ impl JSValue { None } } - /// `JSValue.getZigString` — read a JS string into a `ZigString` view. - /// Convenience wrapper over [`JSValue::to_zig_string`] that returns the - /// out-param by value. - pub fn get_zig_string(self, global: &JSGlobalObject) -> JsResult { - let mut out = bun_core::ZigString::EMPTY; - self.to_zig_string(&mut out, global)?; - Ok(out) - } } // ────────────────────────────────────────────────────────────────────────── @@ -1594,23 +1573,22 @@ impl JSValue { self, global: &JSGlobalObject, indent: u32, - out: &mut bun_core::String, - ) -> JsResult<()> { + ) -> JsResult { + let mut out = bun_core::String::empty(); host_fn::from_js_host_call_generic(global, || { - JSC__JSValue__jsonStringify(self, global, indent, out) - }) + JSC__JSValue__jsonStringify(self, global, indent, &mut out) + })?; + Ok(out) } /// `JSValue.jsonStringifyFast` — `JSON.stringify(this)` /// with no indent / no replacer (fast path used by SQL value binders). - pub fn json_stringify_fast( - self, - global: &JSGlobalObject, - out: &mut bun_core::String, - ) -> JsResult<()> { + pub fn json_stringify_fast(self, global: &JSGlobalObject) -> JsResult { + let mut out = bun_core::String::empty(); host_fn::from_js_host_call_generic(global, || { - JSC__JSValue__jsonStringifyFast(self, global, out) - }) + JSC__JSValue__jsonStringifyFast(self, global, &mut out) + })?; + Ok(out) } pub fn temporal_type(self) -> TemporalType { @@ -1842,16 +1820,8 @@ impl FromAny for &str { } } impl FromAny for Box<[bun_core::String]> { - /// The boxed - /// slice is consumed: every element's WTF refcount is dropped and the - /// backing allocation freed via `Box` drop. `bun_core::String` is `Copy` - /// with no `Drop`, so the explicit `deref()` loop is required. fn into_js_value(self, global: &JSGlobalObject) -> JsResult { - let result = bun_string_jsc::to_js_array(global, &self); - for out in self.iter() { - out.deref(); - } - result + bun_string_jsc::to_js_array(global, &self) } } impl FromAny for Option { @@ -2067,7 +2037,7 @@ unsafe extern "C" { function: JSValue, global: *const JSGlobalObject, bind_this: JSValue, - name: *const bun_core::String, + name: &bun_core::String, length: f64, args: *const JSValue, args_len: usize, @@ -2116,6 +2086,11 @@ unsafe extern "C" { value: JSValue, ); safe fn JSC__JSValue__toStringOrNull(this: JSValue, global: &JSGlobalObject) -> *mut JSString; + safe fn JSC__JSValue__toJSStringView<'a>( + this: JSValue, + global: &'a JSGlobalObject, + view: &mut bun_core::StringView<'a>, + ) -> *mut JSString; safe fn JSC__JSValue__asString(this: JSValue) -> *mut JSString; safe fn JSC__jsTypeStringForValue(global: &JSGlobalObject, value: JSValue) -> *mut JSString; safe fn JSC__JSValue__asArrayBuffer( @@ -2144,11 +2119,6 @@ unsafe extern "C" { this: JSValue, global: &JSGlobalObject, ) -> f64; - safe fn JSC__JSValue__toZigString( - this: JSValue, - out: &mut bun_core::ZigString, - global: &JSGlobalObject, - ); safe fn JSC__JSValue__isTerminationException(this: JSValue) -> bool; safe fn JSC__JSValue__isException(this: JSValue, vm: &crate::VM) -> bool; fn Bun__JSValue__call( @@ -2252,11 +2222,7 @@ pub struct StringFormatter<'a> { impl core::fmt::Display for StringFormatter<'_> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self.value.to_bun_string(self.global) { - Ok(s) => { - let r = core::fmt::Display::fmt(&s, f); - s.deref(); - r - } + Ok(s) => core::fmt::Display::fmt(&s, f), Err(_) => Err(core::fmt::Error), } } @@ -2363,27 +2329,21 @@ impl JSValue { })?; Ok(ret) } - /// `JSValue.getClassName` — writes the class name into `ret`. - pub fn get_class_name( - self, - global: &JSGlobalObject, - ret: &mut bun_core::ZigString, - ) -> JsResult<()> { + /// `JSValue.getClassName`. + pub fn get_class_name(self, global: &JSGlobalObject) -> JsResult { if !self.is_cell() { - *ret = bun_core::ZigString::init(b"[not a class]"); - return Ok(()); + return Ok(bun_core::String::static_(b"[not a class]")); } - host_fn::from_js_host_call_generic(global, || JSC__JSValue__getClassName(self, global, ret)) + host_fn::from_js_host_call_generic(global, || JSC__JSValue__getClassName(self, global)) } - /// `JSValue.getDescription` — symbol description (empty if none). - pub fn get_description(self, global: &JSGlobalObject) -> bun_core::ZigString { - let mut zs = bun_core::ZigString::EMPTY; - JSC__JSValue__getSymbolDescription(self, global, &mut zs); - zs + /// `JSValue.getDescription` — symbol description (empty if none), + /// borrowed from the Symbol. + pub fn get_description<'a>(self, global: &'a JSGlobalObject) -> bun_core::StringView<'a> { + JSC__JSValue__getSymbolDescription(self, global) } /// `JSValue.symbolFor(global, key)` — `Symbol.for(key)`. - pub fn symbol_for(global: &JSGlobalObject, key: &mut bun_core::ZigString) -> JSValue { - JSC__JSValue__symbolFor(global, key) + pub fn symbol_for(global: &JSGlobalObject, key: &'static [u8]) -> JSValue { + JSC__JSValue__symbolFor(global, &bun_core::String::static_(key)) } // ── Property access. ────────────────────────── @@ -2602,26 +2562,19 @@ impl JSValue { index => Some(index as u32), } } - /// `JSValue.getNameProperty` — write the value's - /// `.name` (function/class name) into `ret`. No-op for empty/`undefined`/`null`. - pub fn get_name_property( - self, - global: &JSGlobalObject, - ret: &mut bun_core::ZigString, - ) -> JsResult<()> { + /// `JSValue.getNameProperty` — the value's `.name` (function/class + /// name). Empty for empty/`undefined`/`null`. + pub fn get_name_property(self, global: &JSGlobalObject) -> JsResult { if self.is_empty_or_undefined_or_null() { - return Ok(()); + return Ok(bun_core::String::empty()); } unsafe extern "C" { safe fn JSC__JSValue__getNameProperty( this: JSValue, global: &JSGlobalObject, - ret: &mut bun_core::ZigString, - ); + ) -> bun_core::String; } - host_fn::from_js_host_call_generic(global, || { - JSC__JSValue__getNameProperty(self, global, ret) - }) + host_fn::from_js_host_call_generic(global, || JSC__JSValue__getNameProperty(self, global)) } // ── Proxy internals. ─────────────────────────────── @@ -2750,20 +2703,12 @@ unsafe extern "C" { global: &JSGlobalObject, out: &mut bun_core::String, ); - safe fn JSC__JSValue__getClassName( + safe fn JSC__JSValue__getClassName(this: JSValue, global: &JSGlobalObject) -> bun_core::String; + safe fn JSC__JSValue__getSymbolDescription<'a>( this: JSValue, - global: &JSGlobalObject, - out: &mut bun_core::ZigString, - ); - safe fn JSC__JSValue__getSymbolDescription( - this: JSValue, - global: &JSGlobalObject, - out: &mut bun_core::ZigString, - ); - safe fn JSC__JSValue__symbolFor( - global: &JSGlobalObject, - key: &mut bun_core::ZigString, - ) -> JSValue; + global: &'a JSGlobalObject, + ) -> bun_core::StringView<'a>; + safe fn JSC__JSValue__symbolFor(global: &JSGlobalObject, key: &bun_core::String) -> JSValue; safe fn JSC__JSValue__getOwn( this: JSValue, global: &JSGlobalObject, diff --git a/src/jsc/ModuleLoader.rs b/src/jsc/ModuleLoader.rs index e10fe68f1bfc..1cda0b75f849 100644 --- a/src/jsc/ModuleLoader.rs +++ b/src/jsc/ModuleLoader.rs @@ -1,19 +1,17 @@ -//! The `ModuleLoader` struct, `FetchFlags`, and the `HardcodedModule` -//! re-export compile against the `lib.rs` stub surface. -//! `transpile_source_code` / `fetch_builtin_module` / `resolve_embedded_file` -//! and the `Bun__*` extern entry points reach into `bun_runtime::node::fs` / -//! `bun_transpiler` internals / gated bundler types (forward-dep cycle on -//! `bun_jsc`). - -use core::ffi::c_void; -use core::ptr::NonNull; +//! The `ModuleLoader` struct, `FetchFlags`, and the builtin-module lookup +//! helpers. `transpile_source_code` / `fetch_builtin_module` and the +//! `Bun__transpile*` / `Bun__resolve*` C++ entry points live in +//! `bun_runtime::jsc_hooks` (they reach into `node::fs`, the transpiler, and +//! the standalone graph); this crate calls the first two through link-time +//! `extern "Rust"` decls. use bun_alloc::Arena as ArenaAllocator; +use bun_bundler::transpiler::PluginRunner; use bun_options_types::LoaderExt as _; use crate::virtual_machine::VirtualMachine; use crate::{ - self as jsc, ErrorCode, ErrorableResolvedSource, JSGlobalObject, JSInternalPromise, JSValue, + self as jsc, ErrorableResolvedSource, JSGlobalObject, JSInternalPromise, JSValue, ResolvedSource, }; @@ -110,282 +108,65 @@ impl FetchFlags { } } -// ────────────────────────────────────────────────────────────────────────── -// §Dispatch — `bun_runtime` loader vtable. -// -// `transpile_source_code` / `fetch_builtin_module` / `Bun__transpileFile` -// reach into `bun_runtime::node::fs` (read-file), `bun_transpiler::ParseResult`, -// `bun_bundler::analyze_transpiled_module`, the source-code printer pool, and -// `webcore::Blob` — every one a forward-dep on `bun_jsc`. Per PORTING.md -// §Dispatch (cold-path: called per-import, not per-tick), the low tier owns -// the extern-"C" symbol and a manual vtable; `bun_runtime` installs the body. -// ────────────────────────────────────────────────────────────────────────── - -/// `transpile_source_code` parameters that name only low-tier types. The -/// remaining params (`path: Fs.Path`, `loader: options.Loader`, -/// `module_type: options.ModuleType`, `printer: *BufferPrinter`) are passed -/// through the `extra: *mut c_void` slot — the high-tier hook owns the cast. pub struct TranspileArgs<'a> { pub specifier: &'a [u8], pub referrer: &'a [u8], - pub input_specifier: bun_core::String, + pub input_specifier: &'a bun_core::String, pub log: *mut bun_ast::Log, pub virtual_source: Option<&'a bun_ast::Source>, - pub global_object: *mut JSGlobalObject, + pub global_object: &'a JSGlobalObject, pub flags: FetchFlags, - /// `*mut TranspileExtra` — opaque, owned by the high tier. Null when - /// called from the low-tier `Bun__*` shims (the hook recomputes them from - /// `specifier`). - pub extra: *mut c_void, + /// Raw so the `.wasm` re-entry can mutate `loader` and recurse. + pub extra: *mut TranspileExtra, } -/// Concrete shape behind [`TranspileArgs::extra`]. Declared here (not in -/// `bun_runtime`) so both tiers agree on layout; every field type is already a -/// `bun_jsc` dep (`bun_resolver`, `bun_bundler::options`, `bun_js_printer`). -/// -/// Bundled into one struct (rather than positional params) -/// because the §Dispatch fn-ptr signature must be -/// stable across the crate boundary. -#[repr(C)] pub struct TranspileExtra { pub path: bun_resolver::fs::Path<'static>, pub loader: bun_ast::Loader, pub module_type: bun_bundler::options::ModuleType, - /// `*js_printer.BufferPrinter` — the per-VM shared printer. Never null - /// when `extra` itself is non-null. + /// `*js_printer.BufferPrinter` — the per-VM shared printer. Never null. pub source_code_printer: *mut bun_js_printer::BufferPrinter, /// `?*?*jsc.JSInternalPromise` — out-param for the async-module path. /// Null forbids async resolution. pub promise_ptr: *mut *mut JSInternalPromise, } -/// Result of `LoaderHooks::fetch_builtin_module` — tri-state because -/// an ERROR during builtin lookup must be -/// surfaced to C++ (return `true` with `ret` populated as `.err`) rather than -/// falling through to filesystem resolution. -#[repr(u8)] -#[derive(Copy, Clone, PartialEq, Eq)] -pub enum FetchBuiltinResult { - /// Not a builtin/standalone-graph module — caller falls through. - NotFound, - /// Builtin found; `*out` is populated with `.ok(resolved)`. - Found, - /// Lookup errored; `*out` is populated with `.err(...)` (via - /// `VirtualMachine::process_fetch_log`). Caller must return `true`. - Errored, -} - -pub struct LoaderHooks { - /// `ModuleLoader.transpileSourceCode(...)` — full body. Returns `false` - /// on error (error is written into `*ret` as `.err(...)`). - pub transpile_source_code: unsafe fn( +unsafe extern "Rust" { + /// Defined in `bun_runtime::jsc_hooks`. + pub(crate) fn __bun_transpile_source_code( jsc_vm: *mut VirtualMachine, args: &TranspileArgs<'_>, - ret: *mut ErrorableResolvedSource, - ) -> bool, - /// `ModuleLoader.fetchBuiltinModule(jsc_vm, specifier)` — writes `*out` - /// (as `ErrorableResolvedSource`) and returns a tri-state. On - /// `Found`/`Errored`, `*out` is populated; on `NotFound` it is untouched. - pub fetch_builtin_module: unsafe fn( - jsc_vm: *mut VirtualMachine, - global: *mut JSGlobalObject, + ) -> Result; + /// Defined in `bun_runtime::jsc_hooks`. `None` when the specifier is not a + /// builtin / standalone-graph module. + pub(crate) safe fn __bun_fetch_builtin_module( + jsc_vm: &VirtualMachine, + global: &JSGlobalObject, specifier: &bun_core::String, - referrer: &bun_core::String, - out: *mut ErrorableResolvedSource, - ) -> FetchBuiltinResult, - /// `ModuleLoader.getHardcodedModule(jsc_vm, specifier, hardcoded)` — - /// per-variant body of the builtin-module fast path. `false` ⇒ `None` - /// (recognised but not currently servable); `true` ⇒ `*out` populated. - pub get_hardcoded_module: unsafe fn( - jsc_vm: *mut VirtualMachine, - specifier: &bun_core::String, - hardcoded: bun_resolve_builtins::Module, - out: *mut ResolvedSource, - ) -> bool, - /// `ModuleLoader.resolveEmbeddedFile(vm, &path_buf, input_path, "node")` - /// — extracts an embedded `.node` addon - /// from the standalone-module graph to a real on-disk temp file and writes - /// the resulting path back into `*in_out_str`. Returns `true` on success. - /// Body lives in `bun_runtime` (reaches into `node::fs` + - /// `StandaloneModuleGraph`). - pub resolve_embedded_node_file: - unsafe fn(vm: *mut VirtualMachine, in_out_str: *mut bun_core::String) -> bool, - /// `Bun__transpileVirtualModule` body — - /// transpiles plugin-provided source through the per-thread `BufferPrinter` - /// (a `bun_runtime` thread-local). Writes `*ret` (always — `.ok` or `.err`) - /// and always returns `true` - /// (the C++ caller already proved `plugin_runner != null`). - pub transpile_virtual_module: unsafe fn( - global: *mut JSGlobalObject, - specifier: *const bun_core::String, - referrer: *const bun_core::String, - source_code: *mut bun_core::ZigString, - loader: bun_options_types::schema::api::Loader, - ret: *mut ErrorableResolvedSource, - ) -> bool, - /// `Bun__transpileFile` body — needs `options.getLoaderAndVirtualSource`, - /// `node_module_module`, `webcore.Blob`, the concurrent-transpiler queue. - /// Returns the in-flight promise when `allow_promise && async`, else null - /// (result is in `*ret`). - pub transpile_file: unsafe fn( - jsc_vm: *mut VirtualMachine, - global: *mut JSGlobalObject, - specifier: *const bun_core::String, - referrer: *const bun_core::String, - type_attribute: *const bun_core::String, - ret: *mut ErrorableResolvedSource, - allow_promise: bool, - is_commonjs_require: bool, - force_loader: u8, - ) -> *mut c_void, -} - -unsafe extern "Rust" { - /// The single `&'static` instance, defined `#[no_mangle]` in - /// `bun_runtime::jsc_hooks`. Link-time resolved — no `AtomicPtr`, no - /// init-order hazard. `LoaderHooks` is a `#[repr(Rust)]` POD of fn-ptrs - /// with a single immutable definition; reading it has no precondition - /// beyond the link succeeding → `safe static`. - safe static __BUN_LOADER_HOOKS: LoaderHooks; -} - -#[inline] -fn loader_hooks() -> Option<&'static LoaderHooks> { - // Link-time-resolved `&'static` Rust-ABI static. Always `Some`. - Some(&__BUN_LOADER_HOOKS) -} - -/// `ModuleLoader.transpileSourceCode(...)` — thin shim over the §Dispatch -/// hook. PERF: the indirection -/// is one fn-ptr per import, dwarfed by the parser/printer work it does. -pub(crate) fn transpile_source_code( - jsc_vm: &mut VirtualMachine, - args: &TranspileArgs<'_>, - ret: &mut ErrorableResolvedSource, -) -> bool { - let Some(hooks) = loader_hooks() else { - // No high tier (unit tests) — fail closed. - return false; - }; - // SAFETY: hook contract — `jsc_vm` is the live per-thread VM. - unsafe { (hooks.transpile_source_code)(jsc_vm, args, ret) } -} - -/// `ModuleLoader.fetchBuiltinModule(jsc_vm, specifier)`. -pub(crate) fn fetch_builtin_module( - jsc_vm: &mut VirtualMachine, - global: NonNull, - specifier: &bun_core::String, - referrer: &bun_core::String, - out: &mut ErrorableResolvedSource, -) -> FetchBuiltinResult { - let Some(hooks) = loader_hooks() else { - return FetchBuiltinResult::NotFound; - }; - // SAFETY: hook contract — `jsc_vm` is the live per-thread VM; `out` is a - // valid out-param; `global` is the live JS-thread global passed through - // opaquely to the §Dispatch hook. - unsafe { (hooks.fetch_builtin_module)(jsc_vm, global.as_ptr(), specifier, referrer, out) } -} - -/// `VirtualMachine.processFetchLog(global, specifier, referrer, log, &errorable, -/// err)` — synthesizes a JS error from the parser/resolve `log` and writes it -/// into `errorable` so the C++ side (`Bun__onFulfillAsyncModule`, -/// ModuleLoader.cpp:473) rejects the import promise with a real Error instead -/// of `undefined`. -/// -/// No `LoaderHooks` indirection is needed here — `BuildMessage` / -/// `ResolveMessage` live in this crate — so this forwards to the real impl in -/// [`crate::virtual_machine::process_fetch_log`]. -pub fn process_fetch_log( - global: &JSGlobalObject, - specifier: bun_core::String, - referrer: bun_core::String, - log: &mut bun_ast::Log, - errorable: &mut ErrorableResolvedSource, - err: crate::CrateError, -) { - crate::virtual_machine::process_fetch_log(global, specifier, referrer, log, errorable, err) -} - -// ────────────────────────────────────────────────────────────────────────── -// extern "C" entry points — these are the symbols C++ calls. Bodies dispatch -// through `LoaderHooks`; the high tier owns the real logic. -// ────────────────────────────────────────────────────────────────────────── - -#[unsafe(no_mangle)] -unsafe extern "C" fn Bun__transpileFile( - jsc_vm: *mut VirtualMachine, - global_object: *mut JSGlobalObject, - specifier_ptr: *mut bun_core::String, - referrer: *mut bun_core::String, - type_attribute: *const bun_core::String, - ret: *mut ErrorableResolvedSource, - allow_promise: bool, - is_commonjs_require: bool, - force_loader_type: u8, // bun.schema.api.Loader — passed as raw u8 across the cycle -) -> *mut c_void { - jsc::mark_binding(); - let Some(hooks) = loader_hooks() else { - // SAFETY: C++ passed a valid out-param. - unsafe { - *ret = ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - JSValue::UNDEFINED, - ) - }; - return core::ptr::null_mut(); - }; - // SAFETY: hook contract — all pointers are valid for the call (C++ ABI). - unsafe { - (hooks.transpile_file)( - jsc_vm, - global_object, - specifier_ptr, - referrer, - type_attribute, - ret, - allow_promise, - is_commonjs_require, - force_loader_type, - ) - } + ) -> Option; } #[unsafe(no_mangle)] -unsafe extern "C" fn Bun__fetchBuiltinModule( - jsc_vm: *mut VirtualMachine, - global_object: *mut JSGlobalObject, - specifier: *const bun_core::String, - referrer: *const bun_core::String, - ret: *mut ErrorableResolvedSource, +extern "C" fn Bun__fetchBuiltinModule( + jsc_vm: &VirtualMachine, + global_object: &JSGlobalObject, + specifier: &bun_core::String, + ret: &mut ErrorableResolvedSource, ) -> bool { jsc::mark_binding(); - // SAFETY: C++ passed valid pointers; `jsc_vm` is the live per-thread VM and - // `global_object` is the live JS-thread global. JSC never passes null. - let (jsc_vm, global_object, specifier, referrer, ret) = unsafe { - ( - &mut *jsc_vm, - NonNull::new_unchecked(global_object), - &*specifier, - &*referrer, - &mut *ret, - ) - }; - // When `fetchBuiltinModule` - // ERRORS, it calls `VirtualMachine.processFetchLog(..., ret, err)` and - // returns **true** (so C++ surfaces the error instead of falling through to - // filesystem resolution). The hook writes `ret` directly on Found/Errored. - match fetch_builtin_module(jsc_vm, global_object, specifier, referrer, ret) { - FetchBuiltinResult::NotFound => false, - FetchBuiltinResult::Found | FetchBuiltinResult::Errored => true, + match __bun_fetch_builtin_module(jsc_vm, global_object, specifier) { + Some(resolved) => { + *ret = ErrorableResolvedSource::ok(resolved); + true + } + None => false, } } /// Linear scan over the `BUN_ALIASES` const tables (PERF: could replace with /// a `comptime_string_map!`). #[inline] -fn bun_aliases_get(name: &[u8]) -> Option { +pub fn bun_aliases_get(name: &[u8]) -> Option { // Keep the raw-table scan in agreement with `Alias::get`'s flag gate so // `require.resolve.paths` / `Module._resolveLookupPaths` (which reach // here via `ModuleLoader__isBuiltin`) don't report a gated-off specifier @@ -416,74 +197,6 @@ pub fn exposed_internal_tag(spec: &[u8]) -> Option<(Vec, crate::ResolvedSour Some((name, tag)) } -/// C++ entry point: if `specifier` names a builtin module, writes its resolved source into `ret` and returns `true`. -#[unsafe(no_mangle)] -unsafe extern "C" fn Bun__resolveAndFetchBuiltinModule( - jsc_vm: *mut VirtualMachine, - specifier: *mut bun_core::String, - ret: *mut ErrorableResolvedSource, -) -> bool { - jsc::mark_binding(); - // SAFETY: C++ passed valid pointers; `jsc_vm` is the live per-thread VM. - let specifier = unsafe { &*specifier }; - let spec_utf8 = specifier.to_utf8(); - if let Some((name, tag)) = exposed_internal_tag(spec_utf8.slice()) { - let resolved = ResolvedSource { - source_code: bun_core::String::empty(), - specifier: *specifier, - source_url: bun_core::String::clone_utf8(&name), - tag, - source_code_needs_deref: false, - ..ResolvedSource::default() - }; - // SAFETY: C++ passed a valid out-param. - unsafe { *ret = ErrorableResolvedSource::ok(resolved) }; - return true; - } - let Some(alias) = bun_aliases_get(spec_utf8.slice()) else { - return false; - }; - let Some(&hardcoded) = bun_resolve_builtins::Module::MAP.get(alias.path.as_bytes()) else { - debug_assert!(false); - return false; - }; - let Some(hooks) = loader_hooks() else { - return false; - }; - let mut resolved = ResolvedSource::default(); - // SAFETY: hook contract — `jsc_vm` is the live per-thread VM; `&mut - // resolved` is a valid out-param. - if !unsafe { (hooks.get_hardcoded_module)(jsc_vm, specifier, hardcoded, &raw mut resolved) } { - return false; - } - // SAFETY: C++ passed a valid out-param. - unsafe { *ret = ErrorableResolvedSource::ok(resolved) }; - true -} - -/// Support embedded .node files. -#[unsafe(no_mangle)] -unsafe extern "C" fn Bun__resolveEmbeddedNodeFile( - vm: *mut VirtualMachine, - in_out_str: *mut bun_core::String, -) -> bool { - jsc::mark_binding(); - if VirtualMachine::get().standalone_module_graph.is_none() { - return false; - } - // `ModuleLoader.resolveEmbeddedFile` reaches into `bun_runtime::node::fs` + - // `StandaloneModuleGraph` — forward-dep on `bun_jsc`. Per §Dispatch the low - // tier owns the extern symbol and dispatches through `LoaderHooks`; the - // high tier extracts the embedded addon to a temp file and writes the - // on-disk path back into `*in_out_str`. - let Some(hooks) = loader_hooks() else { - unreachable!() - }; - // SAFETY: hook contract — `vm` is the live per-thread VM; `in_out_str` is a - // valid in/out `bun.String*` (C++ ABI, BunProcess.cpp:463). - unsafe { (hooks.resolve_embedded_node_file)(vm, in_out_str) } -} - /// C++ entry point: whether `data[..len]` names a builtin module. #[unsafe(no_mangle)] unsafe extern "C" fn ModuleLoader__isBuiltin(data: *const u8, len: usize) -> bool { @@ -492,25 +205,6 @@ unsafe extern "C" fn ModuleLoader__isBuiltin(data: *const u8, len: usize) -> boo bun_aliases_get(str).is_some() || exposed_internal_tag(str).is_some() } -// The pure byte-string -// `extractNamespace` / `couldBePlugin` helpers live in -// `bun_bundler::transpiler::PluginRunner` — `bun_bundler` is already a -// `bun_jsc` dep, so `Bun__runVirtualModule` calls them directly rather than -// duplicating them here. -use bun_bundler::transpiler::PluginRunner; - -// `ModuleLoader.resolveEmbeddedFile` -// lives in `bun_runtime::jsc_hooks::resolve_embedded_file_to_buf` -// per PORTING.md §Forbidden ("dep-cycle: MOVE the code to the right crate") — -// the body reaches into `bun_standalone_graph` + `bun_sys::Tmpfile` + -// `node::fs`, none of which are `bun_jsc` deps. Three callers live in -// `bun_runtime`: -// - `Bun__resolveEmbeddedNodeFile` above (extname `"node"`, goes through -// `LoaderHooks::resolve_embedded_node_file` to bridge the crate gap). -// - The `.sqlite` arm of `transpileSourceCode`. -// - `ffi_body::FFI::open` (extname `"so"`/`"dylib"`/`"dll"`; same-crate -// call to `resolve_embedded_file_to_buf`, no hook needed). - /// C++ entry point: picks the loader for a specifier from its file extension and the VM's loader map. #[unsafe(no_mangle)] extern "C" fn Bun__getDefaultLoader( @@ -533,37 +227,6 @@ extern "C" fn Bun__getDefaultLoader( loader } -/// C++ entry point: transpiles a plugin-provided virtual module's source, writing the result into `ret`. -#[unsafe(no_mangle)] -unsafe extern "C" fn Bun__transpileVirtualModule( - global: *mut JSGlobalObject, - specifier: *const bun_core::String, - referrer: *const bun_core::String, - source_code: *mut bun_core::ZigString, - loader: bun_options_types::schema::api::Loader, - ret: *mut ErrorableResolvedSource, -) -> bool { - jsc::mark_binding(); - // Body drives `transpileSourceCode` through the per-thread `BufferPrinter` - // (a `bun_runtime` thread-local), so per §Dispatch the low tier owns the - // extern symbol and dispatches; `bun_runtime` installs the body. Same - // shape as `Bun__transpileFile` above. - let Some(hooks) = loader_hooks() else { - // SAFETY: C++ passed a valid out-param. - unsafe { - *ret = ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - JSValue::UNDEFINED, - ); - } - return true; - }; - // SAFETY: hook contract — all pointers are valid for the call (C++ ABI). - unsafe { - (hooks.transpile_virtual_module)(global, specifier, referrer, source_code, loader, ret) - } -} - /// C++ entry point: runs the plugin for a virtual-module specifier, returning its exports (or zero when no plugin runner is set). #[unsafe(no_mangle)] unsafe extern "C" fn Bun__runVirtualModule( @@ -591,8 +254,8 @@ unsafe extern "C" fn Bun__runVirtualModule( }; match global.run_on_load_plugins( - bun_core::String::init(bun_core::ZigString::init(namespace)), - bun_core::String::init(bun_core::ZigString::init(after_namespace)), + &bun_core::String::init(namespace), + &bun_core::String::init(after_namespace), crate::BunPluginTarget::Bun, ) { Ok(Some(v)) => v, diff --git a/src/jsc/NodeCompileCache.rs b/src/jsc/NodeCompileCache.rs index ba8f8a793d33..7acc58cdf3fa 100644 --- a/src/jsc/NodeCompileCache.rs +++ b/src/jsc/NodeCompileCache.rs @@ -106,6 +106,11 @@ impl AlignedBlob { }) } + fn as_slice(&self) -> &[u8] { + // SAFETY: `ptr` is valid for `len` bytes for the lifetime of `self`. + unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) } + } + fn as_mut_slice(&mut self) -> &mut [u8] { // SAFETY: `ptr` is valid for `len` bytes for the lifetime of `self`. unsafe { core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) } @@ -542,7 +547,11 @@ pub fn get_dir() -> Option> { /// Module-fetch hook: register/refresh the entry for `filename`; returns the /// validated bytecode blob when the on-disk cache matches `code` (post- /// transpile text). The pointer stays valid for the process (entry map owns it). -pub fn fetch(filename: &[u8], is_cjs: bool, code: &[u8]) -> Option<(*mut u8, usize)> { +pub fn fetch( + filename: &[u8], + is_cjs: bool, + code: &[u8], +) -> Option { if !is_enabled() || filename.is_empty() || !bun_paths::is_absolute(filename) { return None; } @@ -558,7 +567,10 @@ pub fn fetch(filename: &[u8], is_cjs: bool, code: &[u8]) -> Option<(*mut u8, usi if let Some(entry) = state.entries.get(&key) { if entry.code_hash == code_hash && entry.code_size == code_size { // Same module, unchanged code (e.g. re-required): reuse. - return entry.blob.as_ref().map(|b| (b.ptr.as_ptr(), b.len)); + return entry + .blob + .as_ref() + .map(|b| crate::resolved_source::Bytecode::borrowed(b.as_slice())); } } @@ -580,7 +592,10 @@ pub fn fetch(filename: &[u8], is_cjs: bool, code: &[u8]) -> Option<(*mut u8, usi type_name(is_cjs), display_name(filename, is_cjs) ); - entry.blob.as_ref().map(|b| (b.ptr.as_ptr(), b.len)) + entry + .blob + .as_ref() + .map(|b| crate::resolved_source::Bytecode::borrowed(b.as_slice())) } else { cclog!( "[compile cache] code cache for {} {} was not initialized, initializing the in-memory entry\n", @@ -890,11 +905,10 @@ fn generate_bytecode(format: Format, code: &[u8], url: &[u8]) -> Option BunString { match get_dir() { Some(dir) => BunString::clone_utf8(&dir), - None => BunString::empty(), + None => BunString::EMPTY, } } diff --git a/src/jsc/NodeModuleModule.rs b/src/jsc/NodeModuleModule.rs index fb2bea6b161f..1b31bb6a44a5 100644 --- a/src/jsc/NodeModuleModule.rs +++ b/src/jsc/NodeModuleModule.rs @@ -1,10 +1,10 @@ use crate::{ - self as jsc, ErrorableString, JSArray, JSGlobalObject, JSValue, JsResult, StringJsc, Strong, + self as jsc, JSArray, JSGlobalObject, JSValue, JsResult, StringJsc, Strong, VirtualMachineRef as VirtualMachine, }; use bun_ast::Loader; use bun_bundler::options::DEFAULT_LOADERS; -use bun_core::{OwnedString, String as BunString, strings}; +use bun_core::{String as BunString, strings}; use bun_options_types::LoaderExt as _; use bun_options_types::schema::api; @@ -36,7 +36,7 @@ impl ApiLoader { #[unsafe(no_mangle)] extern "C" fn NodeModuleModule__findPath( global: &JSGlobalObject, - request_bun_str: BunString, + request_bun_str: &BunString, paths_maybe: *mut JSArray, ) -> JSValue { // `JSArray` is an `opaque_ffi!` ZST handle; `opaque_ref` is the centralised @@ -49,7 +49,7 @@ extern "C" fn NodeModuleModule__findPath( // https://github.com/nodejs/node/blob/40ef9d541ed79470977f90eb445c291b95ab75a0/lib/internal/modules/cjs/loader.js#L666 fn find_path( global: &JSGlobalObject, - request_bun_str: BunString, + request_bun_str: &BunString, paths_maybe: Option<&JSArray>, ) -> JsResult { let request_slice = request_bun_str.to_utf8(); @@ -61,14 +61,13 @@ fn find_path( } // for each path - let mut found = if let Some(paths) = paths_maybe { + let found = if let Some(paths) = paths_maybe { 'found: { let mut iter = paths.iterator(global)?; while let Some(path) = iter.next()? { - // `OwnedString` releases the +1 from `from_js` on drop. - let cur_path = OwnedString::new(BunString::from_js(path, global)?); + let cur_path = BunString::from_js(path, global)?; - if let Some(found) = find_path_inner(request_bun_str, cur_path.get(), global)? { + if let Some(found) = find_path_inner(request_bun_str, &cur_path, global)? { break 'found Some(found); } } @@ -76,34 +75,29 @@ fn find_path( break 'found None; } } else { - find_path_inner(request_bun_str, BunString::static_(b""), global)? + find_path_inner(request_bun_str, &BunString::EMPTY, global)? }; - if let Some(str) = found.as_mut() { - return str.transfer_to_js(global); + if let Some(str) = found { + return str.into_js(global); } Ok(JSValue::FALSE) } fn find_path_inner( - request: BunString, - cur_path: BunString, + request: &BunString, + cur_path: &BunString, global: &JSGlobalObject, ) -> JsResult> { - // SAFETY: zero-init is the documented `ErrorableString` "empty" state; the - // callee fully overwrites it on both ok/err paths. - let mut errorable: ErrorableString = unsafe { bun_core::ffi::zeroed_unchecked() }; - // `bun_core::String` is `Copy` — passing by value makes no refcount change. - VirtualMachine::resolve_maybe_needs_trailing_slash::( - &mut errorable, + Ok(VirtualMachine::resolve_maybe_needs_trailing_slash::( global, request, cur_path, None, crate::virtual_machine::ResolveMode::RequireResolve, - )?; - Ok(errorable.unwrap().ok()) + )? + .ok()) } pub fn stat(path: &[u8]) -> i32 { diff --git a/src/jsc/PluginRunner.rs b/src/jsc/PluginRunner.rs index 4e321cdf7bf3..84837c082e7d 100644 --- a/src/jsc/PluginRunner.rs +++ b/src/jsc/PluginRunner.rs @@ -10,7 +10,7 @@ use std::io::Write as _; use bun_bundler::transpiler::{BunPluginTarget, PluginResolver}; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_paths::fs::Path as FsPath; use crate::JSGlobalObject; @@ -63,13 +63,13 @@ impl PluginResolver for PluginRunner { }; let Some(on_resolve_plugin) = global .run_on_resolve_plugins( - namespace, - BunString::init(specifier).substring(if namespace.length() > 0 { + &namespace, + &BunString::init(specifier).substring(if namespace.length() > 0 { namespace.length() + 1 } else { 0 }), - BunString::init(importer), + &BunString::init(importer), target, ) .map_err(js_err)? @@ -87,10 +87,7 @@ impl PluginResolver for PluginRunner { return Ok(None); } - // `bun_core::String` - // is `Copy` (no `Drop`), so RAII-wrap the +1 WTF ref across every - // remaining `?` / early-return. - let file_path = OwnedString::new(path_value.to_bun_string(global).map_err(js_err)?); + let file_path = path_value.to_bun_string(global).map_err(js_err)?; if file_path.length() == 0 { log.add_error( @@ -121,22 +118,18 @@ impl PluginResolver for PluginRunner { let namespace_str = namespace_value.to_bun_string(global).map_err(js_err)?; if namespace_str.length() == 0 { - namespace_str.deref(); break 'brk BunString::init(b"file"); } if namespace_str.eql_comptime(b"file") { - namespace_str.deref(); break 'brk BunString::init(b"file"); } if namespace_str.eql_comptime(b"bun") { - namespace_str.deref(); break 'brk BunString::init(b"bun"); } if namespace_str.eql_comptime(b"node") { - namespace_str.deref(); break 'brk BunString::init(b"node"); } @@ -147,7 +140,6 @@ impl PluginResolver for PluginRunner { break 'brk BunString::init(b"file"); }; - let user_namespace = OwnedString::new(user_namespace); // `FsPath<'static>` borrows, so the formatted buffer is leaked to // model the caller-owns-forever contract (these are diff --git a/src/jsc/RegularExpression.rs b/src/jsc/RegularExpression.rs index 8d0b27c0f311..dcf98c4298d0 100644 --- a/src/jsc/RegularExpression.rs +++ b/src/jsc/RegularExpression.rs @@ -32,17 +32,19 @@ pub enum RegularExpressionError { // query/compile shims are therefore declared `safe fn`; only `deinit` (which // frees the allocation) keeps a raw `*mut` and stays `unsafe`. unsafe extern "C" { - safe fn Yarr__RegularExpression__init(pattern: BunString, flags: u16) - -> *mut RegularExpression; + safe fn Yarr__RegularExpression__init( + pattern: &BunString, + flags: u16, + ) -> *mut RegularExpression; fn Yarr__RegularExpression__deinit(pattern: *mut RegularExpression); safe fn Yarr__RegularExpression__isValid(this: &RegularExpression) -> bool; - safe fn Yarr__RegularExpression__matches(this: &RegularExpression, string: BunString) -> i32; + safe fn Yarr__RegularExpression__matches(this: &RegularExpression, string: &BunString) -> i32; } impl RegularExpression { #[inline] pub fn init( - pattern: BunString, + pattern: &BunString, flags: Flags, ) -> Result<*mut RegularExpression, RegularExpressionError> { let regex = Yarr__RegularExpression__init(pattern, flags as u16); @@ -69,7 +71,7 @@ impl RegularExpression { /// Simple boolean matcher #[inline] - pub fn matches(&mut self, str: BunString) -> bool { + pub fn matches(&mut self, str: &BunString) -> bool { Yarr__RegularExpression__matches(self, str) >= 0 } @@ -90,7 +92,7 @@ impl RegularExpression { // ────────────────────────────────────────────────────────────────────────── #[unsafe(no_mangle)] -fn __bun_regex_compile(pattern: BunString) -> Option> { +fn __bun_regex_compile(pattern: &BunString) -> Option> { // Idempotent. Only the install commands reach this before initializing // JSC themselves, and the defaults are right for them; every other command // has already initialized JSC with its own options by the time a matcher @@ -107,7 +109,7 @@ fn __bun_regex_matches(regex: core::ptr::NonNull<()>, input: &BunString) -> bool // `RegularExpression` is an `opaque_ffi!` ZST handle; `opaque_mut` is the // centralised non-null deref proof. `regex` was produced by // `__bun_regex_compile` and remains live until `__bun_regex_drop`. - RegularExpression::opaque_mut(regex.as_ptr().cast()).matches(*input) + RegularExpression::opaque_mut(regex.as_ptr().cast()).matches(input) } #[unsafe(no_mangle)] diff --git a/src/jsc/ResolveMessage.rs b/src/jsc/ResolveMessage.rs index 3c3bdd891a4a..014fa188909b 100644 --- a/src/jsc/ResolveMessage.rs +++ b/src/jsc/ResolveMessage.rs @@ -123,9 +123,7 @@ impl ResolveMessage { }; }; - let atom = bun_core::String::create_atom(code); - // `defer atom.deref()` — `String` derefs on Drop. - atom.to_js(global) + bun_core::String::create_atom(code).into_js(global) } _ => Ok(JSValue::UNDEFINED), } @@ -285,7 +283,7 @@ impl ResolveMessage { return Ok(JSValue::NULL); } - let str = args[0].get_zig_string(global)?; + let str = args[0].to_bun_string(global)?; if str.eql_comptime(b"default") || str.eql_comptime(b"string") { return Ok(this.to_string_fn(global)); } @@ -300,7 +298,7 @@ impl ResolveMessage { object.put( global, b"name", - bun_core::String::static_str(b"ResolveMessage").to_js(global)?, + bun_core::String::static_(b"ResolveMessage").to_js(global)?, ); object.put(global, b"position", Self::get_position(this, global)?); object.put(global, b"message", Self::get_message(this, global)?); diff --git a/src/jsc/ResolvedSource.rs b/src/jsc/ResolvedSource.rs index cd97bbcfc0ac..df33467e3192 100644 --- a/src/jsc/ResolvedSource.rs +++ b/src/jsc/ResolvedSource.rs @@ -1,4 +1,4 @@ -use core::ffi::c_void; +use bun_bundler::analyze_transpiled_module::ModuleInfoDeserialized; use bun_core::String as BunString; @@ -8,18 +8,14 @@ use crate::JSValue; // half of the table is code-generated (see `generated_resolved_source_tag.rs`). pub use crate::resolved_source_tag::ResolvedSourceTag as Tag; -// `Copy` is required by `Errorable` (the `#[repr(C)]` tagged-union it -// travels through to C++). All fields are POD; `BunString` is a tagged pointer -// pair and is `Copy`. +/// C++ `ResolvedSource` (headers-handwritten.h). Every string field is owned +/// by whichever frame holds the struct: dropped here on the Rust side, or by +/// `~ErrorableResolvedSource` once written into a C++ out-param. Consumers +/// (`Zig::SourceProvider::create`) take the fields they keep by transfer. #[repr(C)] -#[derive(Copy, Clone)] +#[derive(Default)] pub struct ResolvedSource { - /// Specifier's lifetime is the caller from C++ - /// https://github.com/oven-sh/bun/issues/9521 - pub specifier: BunString, pub source_code: BunString, - - /// source_url is eventually deref'd on success pub source_url: BunString, pub is_commonjs_module: bool, @@ -28,24 +24,17 @@ pub struct ResolvedSource { /// the JSFunction extension. It is kept alive by /// - This structure is stored on the stack /// - There is a JSC::Strong reference to it - // The bare JSValue field is sound here — ResolvedSource is #[repr(C)] and lives - // on the stack while crossing to C++ (see comment above + headers-handwritten.h). pub cjs_custom_extension_index: JSValue, - pub allocator: *mut c_void, - pub jsvalue_for_export: JSValue, pub tag: Tag, - /// This is for source_code - pub source_code_needs_deref: bool, pub already_bundled: bool, - // -- Bytecode cache fields -- - pub bytecode_cache: *mut u8, - pub bytecode_cache_size: usize, - pub module_info: *mut c_void, + pub bytecode_cache: Bytecode, + /// `Zig::SourceProvider` takes it (nulling the field). + pub module_info: Option>, /// The file path used as the source origin for bytecode cache validation. /// JSC validates bytecode by checking if the origin URL matches exactly what /// was used at build time. If empty, the origin is derived from source_url. @@ -53,94 +42,66 @@ pub struct ResolvedSource { pub bytecode_origin_path: BunString, } -impl Default for ResolvedSource { +/// `ResolvedSource.bytecode_cache`: C++ sees `{ uint8_t* ptr; size_t len; bool owned; }`. +/// When `owned`, `ptr` is a `heap::into_raw(Box<[u8]>)` freed on drop (or by +/// the C++ consumer once it `std::exchange`s the pointer out); otherwise it is +/// borrowed from the standalone module graph or the compile cache. +#[repr(C)] +pub struct Bytecode { + ptr: *mut u8, + len: usize, + owned: bool, +} + +impl Default for Bytecode { fn default() -> Self { Self { - specifier: BunString::empty(), - source_code: BunString::empty(), - source_url: BunString::empty(), - is_commonjs_module: false, - cjs_custom_extension_index: JSValue::ZERO, - allocator: core::ptr::null_mut(), - jsvalue_for_export: JSValue::ZERO, - tag: Tag::Javascript, - source_code_needs_deref: true, - already_bundled: false, - bytecode_cache: core::ptr::null_mut(), - bytecode_cache_size: 0, - module_info: core::ptr::null_mut(), - bytecode_origin_path: BunString::empty(), + ptr: core::ptr::null_mut(), + len: 0, + owned: false, } } } -// ────────────────────────────────────────────────────────────────────────── -// RAII owner for the +1 `BunString` refs inside a `ResolvedSource`. -// -// `ResolvedSource` itself MUST stay `#[repr(C), Copy]` (it crosses to C++ by -// value through `Errorable`), so it cannot have `Drop`. That -// makes every Rust-side construction a leak hazard: `source_code` is a fresh -// `String::clone_utf8/clone_latin1` (+1 WTF refcount holding the entire -// transpiled module text — kilobytes-to-megabytes), and any error path or -// early return between construction and `into_ffi()` would orphan it. -// -// Hold the in-flight value as `OwnedResolvedSource`; the only way to extract -// the raw `ResolvedSource` for FFI is `into_ffi()` (consumes, forgets). If the -// owner is dropped instead, every contained `BunString` is `deref()`d. -// -// The `module_info` pointer (a `Box` leaked via -// `heap::into_raw`) is intentionally NOT freed here — its ownership protocol -// is separate (C++ calls `Bun__free_module_info` on success; on Rust-side drop -// it would still leak today, tracked separately). -// ────────────────────────────────────────────────────────────────────────── -#[repr(transparent)] -#[derive(Default)] -pub struct OwnedResolvedSource(ResolvedSource); - -/// Adopt a freshly-constructed `ResolvedSource`. The caller transfers the -/// +1 on every `BunString` field to this owner. -impl From for OwnedResolvedSource { - #[inline] - fn from(rs: ResolvedSource) -> Self { - Self(rs) - } -} - -impl OwnedResolvedSource { - /// Hand the raw value to C++ (which takes over the `deref()` obligation - /// per `headers-handwritten.h` `BunString::deref` callers in - /// `Zig::ResolvedSource` consumers). After this, Rust must not touch the - /// strings. - #[inline] - pub fn into_ffi(self) -> ResolvedSource { - core::mem::ManuallyDrop::new(self).0 - } - - /// Borrow the inner value for in-place mutation while keeping RAII - /// ownership. Used for the `source_url`/`specifier` late-fill in - /// `RuntimeTranspilerStore::run_from_js_thread`. - #[inline] - pub(crate) fn as_mut(&mut self) -> &mut ResolvedSource { - &mut self.0 +impl Bytecode { + pub fn borrowed(bytes: &[u8]) -> Self { + if bytes.is_empty() { + return Self::default(); + } + Self { + ptr: bytes.as_ptr().cast_mut(), + len: bytes.len(), + owned: false, + } } - - #[inline] - pub fn get(&self) -> &ResolvedSource { - &self.0 + pub fn owned(bytes: Box<[u8]>) -> Self { + if bytes.is_empty() { + return Self::default(); + } + let len = bytes.len(); + Self { + ptr: bun_core::heap::into_raw(bytes).cast::(), + len, + owned: true, + } } } -impl Drop for OwnedResolvedSource { - #[inline] +impl Drop for Bytecode { fn drop(&mut self) { - // `source_code_needs_deref` mirrors the C++ consumer's gate (when - // `false`, the source_code is a borrowed/static slice the consumer - // must not deref either). - if self.0.source_code_needs_deref { - self.0.source_code.deref(); + if self.owned && !self.ptr.is_null() { + ResolvedSource__freeBytecode(self.ptr); } - self.0.specifier.deref(); - self.0.source_url.deref(); - self.0.bytecode_origin_path.deref(); } } + +/// `~ErrorableResolvedSource` / `JSC::CachedBytecode` destructor for an owned +/// `Bytecode` (see above). +#[unsafe(no_mangle)] +extern "C" fn ResolvedSource__freeBytecode(bytecode: *mut u8) { + // SAFETY: only called with the `heap::into_raw(Box<[u8]>)` base pointer; + // mimalloc recovers the size from the heap. + unsafe { bun_alloc::default_alloc::free(bytecode.cast()) }; +} + +bun_core::assert_ffi_layout!(ResolvedSource, 136, 8); diff --git a/src/jsc/RuntimeTranspilerCache.rs b/src/jsc/RuntimeTranspilerCache.rs index b4705f2ee21e..4bd6b5ae94a3 100644 --- a/src/jsc/RuntimeTranspilerCache.rs +++ b/src/jsc/RuntimeTranspilerCache.rs @@ -223,49 +223,15 @@ impl Metadata { // against the hand-summed constant drifting from the field list. const _: () = assert!(Metadata::SIZE == 4 + 1 + 1 + 12 * 8); -pub enum OutputCode { - Utf8(Box<[u8]>), - String(BunString), -} - -impl Default for OutputCode { - fn default() -> Self { - OutputCode::Utf8(Box::default()) - } -} - -impl OutputCode { - pub fn byte_slice(&self) -> &[u8] { - match self { - OutputCode::Utf8(b) => b, - OutputCode::String(s) => s.byte_slice(), - } - } - - fn deinit(&mut self) { - match core::mem::take(self) { - OutputCode::Utf8(_b) => {} - OutputCode::String(s) => s.deref(), - } - } -} - #[derive(Default)] pub struct Entry { pub metadata: Metadata, - pub output_code: OutputCode, + pub output_code: BunString, pub sourcemap: Box<[u8]>, pub esm_record: Box<[u8]>, } impl Entry { - #[cfg(bun_debug)] - pub(crate) fn deinit(&mut self) { - self.output_code.deinit(); - self.sourcemap = Box::default(); - self.esm_record = Box::default(); - } - pub(crate) fn save( destination_dir: Fd, destination_path: &ZStr, @@ -274,7 +240,7 @@ impl Entry { features_hash: u64, sourcemap: &[u8], esm_record: &[u8], - output_code: &OutputCode, + output_code: &BunString, exports_kind: ExportsKind, ) -> crate::CrateResult<()> { let _tracer = bun_core::perf::trace("RuntimeTranspilerCache.save"); @@ -312,19 +278,12 @@ impl Entry { ExportsKind::Cjs => ModuleType::Cjs, _ => ModuleType::Esm, }, - output_encoding: match output_code { - OutputCode::Utf8(_) => Encoding::UTF8, - // `bun_core::String` has no `.encoding()`; derive it - // from the `is_*` predicates. - OutputCode::String(str) => { - if str.is_utf16() { - Encoding::UTF16 - } else if str.is_utf8() { - Encoding::UTF8 - } else { - Encoding::LATIN1 - } - } + output_encoding: if output_code.is_utf16() { + Encoding::UTF16 + } else if output_code.is_utf8() { + Encoding::UTF8 + } else { + Encoding::LATIN1 }, sourcemap_byte_length: sourcemap.len() as u64, output_byte_offset: Metadata::SIZE as u64, @@ -433,12 +392,12 @@ impl Entry { } debug_assert!( - matches!(&self.output_code, OutputCode::Utf8(b) if b.is_empty()), + self.output_code.is_empty(), "this should be the default value" ); self.output_code = if self.metadata.output_byte_length == 0 { - OutputCode::String(BunString::empty()) + BunString::empty() } else { match self.metadata.output_encoding { Encoding::UTF8 => { @@ -467,8 +426,6 @@ impl Entry { if bytes.is_empty() { return Err(crate::CrateError::Alloc(bun_alloc::AllocError)); } - // errdefer scratch.deref() — BunString is `Copy`, so guard explicitly. - let errdefer = scopeguard::guard(scratch, |s| s.deref()); let read_bytes = file.pread_all(bytes, self.metadata.output_byte_offset)?; if read_bytes as u64 != self.metadata.output_byte_length { return Err(crate::CrateError::MissingData); @@ -480,15 +437,12 @@ impl Entry { if bun_core::strings::is_all_ascii(bytes) { // Fast path: ASCII ⊂ Latin-1, so `scratch` is already - // the correct `BunString` — hand it straight to the - // consumer as `OutputCode::String`. - scopeguard::ScopeGuard::into_inner(errdefer); - OutputCode::String(scratch) + // the correct `BunString`. + scratch } else { // Rare path: real multi-byte UTF-8. Transcode into a - // fresh WTF string and drop the Latin-1 scratch (the - // guard derefs it on scope exit). - OutputCode::String(BunString::clone_utf8(bytes)) + // fresh WTF string; the Latin-1 scratch drops. + BunString::clone_utf8(bytes) } } Encoding::LATIN1 => { @@ -500,8 +454,6 @@ impl Entry { if bytes.is_empty() { return Err(crate::CrateError::Alloc(bun_alloc::AllocError)); } - // errdefer latin1.deref() — BunString is `Copy`, so guard explicitly. - let errdefer = scopeguard::guard(latin1, |s| s.deref()); let read_bytes = file.pread_all(bytes, self.metadata.output_byte_offset)?; if self.metadata.output_hash != 0 { @@ -514,8 +466,7 @@ impl Entry { return Err(crate::CrateError::MissingData); } - scopeguard::ScopeGuard::into_inner(errdefer); - OutputCode::String(latin1) + latin1 } Encoding::UTF16 => { let char_len = (self.metadata.output_byte_length / 2) as usize; @@ -525,8 +476,6 @@ impl Entry { if chars.is_empty() { return Err(crate::CrateError::Alloc(bun_alloc::AllocError)); } - let errdefer = scopeguard::guard(string, |s| s.deref()); - // `chars` is `&mut [u16; char_len]` backed by contiguous // WTFString storage; reinterpret as bytes for pread via the // safe POD cast (`u16` → `u8` always satisfies size/align). @@ -544,18 +493,13 @@ impl Entry { } } - scopeguard::ScopeGuard::into_inner(errdefer); - OutputCode::String(string) + string } _ => unreachable!("Unexpected output encoding"), } }; - // BunString is Copy with no Drop, so dropping `Entry` on error does NOT - // deref the WTFStringImpl — must do it explicitly here. - let output_code_errdefer = scopeguard::guard(&mut self.output_code, |oc| oc.deinit()); - if self.metadata.sourcemap_byte_length > 0 { self.sourcemap = pread_box( file, @@ -580,7 +524,6 @@ impl Entry { self.esm_record = esm_record; } - scopeguard::ScopeGuard::into_inner(output_code_errdefer); Ok(()) } } @@ -803,12 +746,7 @@ impl RuntimeTranspilerCache { } let mut reader = bun_io::FixedBufferStream::new(&metadata_bytes_buf[0..metadata_bytes]); - let mut entry = Entry { - metadata: Metadata::default(), - output_code: OutputCode::Utf8(Box::default()), - sourcemap: Box::default(), - esm_record: Box::default(), - }; + let mut entry = Entry::default(); entry.metadata.decode(&mut reader)?; if entry.metadata.input_hash != input_hash || entry.metadata.input_byte_length != input_stat_size @@ -840,19 +778,6 @@ impl RuntimeTranspilerCache { let _tracer = bun_core::perf::trace("RuntimeTranspilerCache.toFile"); let mut cache_file_path_buf = PathBuffer::uninit(); - // `OutputCode::Utf8` owns a `Box<[u8]>`, so we copy. - // PERF: add a borrowed `OutputCode` variant to avoid the copy. - // - // The non-UTF-8 arm is a by-value copy, **no** - // `dupe_ref()` and **no** matching `deref()`. `BunString` is `Copy` and - // `OutputCode` has no `Drop`, so `*source_code` here is a - // refcount-neutral borrow. - let output_code: OutputCode = if source_code.is_utf8() { - OutputCode::Utf8(Box::from(source_code.byte_slice())) - } else { - OutputCode::String(*source_code) - }; - let cache_file_path = Self::get_cache_file_path(&mut cache_file_path_buf, input_hash)?; bun_core::scoped_log!( cache, @@ -895,7 +820,7 @@ impl RuntimeTranspilerCache { features_hash, sourcemap, esm_record, - &output_code, + source_code, exports_kind, ) } @@ -980,9 +905,7 @@ impl RuntimeTranspilerCache { #[cfg(bun_debug)] { if !BUN_DEBUG_RESTORE_FROM_CACHE.load(Ordering::Relaxed) { - if let Some(mut entry) = self.entry.take() { - entry.deinit(); - } + self.entry = None; } } diff --git a/src/jsc/RuntimeTranspilerStore.rs b/src/jsc/RuntimeTranspilerStore.rs index 21baa614bb77..ad87fcb9dcf1 100644 --- a/src/jsc/RuntimeTranspilerStore.rs +++ b/src/jsc/RuntimeTranspilerStore.rs @@ -34,16 +34,14 @@ use bun_watcher::Watcher; use crate::async_module::AsyncModule; use crate::event_loop::{ConcurrentTask, EventLoop}; use crate::hot_reloader::ImportWatcher; -use crate::resolved_source::OwnedResolvedSource; use crate::resolved_source_tag::ResolvedSourceTag; use crate::runtime_transpiler_cache::{ - Entry as CacheEntry, ModuleType as CacheModuleType, OutputCode, + Entry as CacheEntry, ModuleType as CacheModuleType, RuntimeTranspilerCache as JscRuntimeTranspilerCache, }; use crate::strong::Optional as StrongOptional; -use crate::virtual_machine::{SourceMapHandlerGetter, VirtualMachine, create_if_different}; +use crate::virtual_machine::{SourceMapHandlerGetter, VirtualMachine}; use crate::{JSGlobalObject, JSInternalPromise, JSValue, JsResult, ResolvedSource}; -use bun_core::OwnedString; // LAYERING: `ParseOptions.runtime_transpiler_cache` carries the canonical // lower-tier type from `bun_js_parser` (re-exported via `bun_bundler`). The @@ -333,16 +331,14 @@ impl RuntimeTranspilerStore { // NOTE: DirInfo should already be cached since module loading happens // after module resolution, so this should be cheap - let mut resolved_source = OwnedResolvedSource::default(); + let mut resolved_source = ResolvedSource::default(); if let Some(pkg) = package_json { match pkg.module_type { ModuleType::Cjs => { - resolved_source.as_mut().tag = ResolvedSourceTag::PackageJsonTypeCommonjs; - resolved_source.as_mut().is_commonjs_module = true; - } - ModuleType::Esm => { - resolved_source.as_mut().tag = ResolvedSourceTag::PackageJsonTypeModule + resolved_source.tag = ResolvedSourceTag::PackageJsonTypeCommonjs; + resolved_source.is_commonjs_module = true; } + ModuleType::Esm => resolved_source.tag = ResolvedSourceTag::PackageJsonTypeModule, ModuleType::Unknown => {} } } @@ -356,17 +352,16 @@ impl RuntimeTranspilerStore { let job: *mut TranspilerJob = self .store .get_init(TranspilerJob { - non_threadsafe_input_specifier: OwnedString::new(input_specifier), + non_threadsafe_input_specifier: input_specifier, path: owned_path, global_this: BackRef::new(global_object), - non_threadsafe_referrer: OwnedString::new(referrer), + non_threadsafe_referrer: referrer, vm, ticket: None, log: bun_ast::Log::init(), loader, promise: StrongOptional::create(JSValue::from_cell(promise), global_object), poll_ref: KeepAlive::default(), - fetcher: Fetcher::File, resolved_source, generation_number: self.generation_number.load(Ordering::SeqCst), parse_error: None, @@ -408,10 +403,8 @@ pub struct TranspilerJob { // `ParseOptions.path` / `bun_ast::Source.path` use). The slices borrow the // Box'd buffer allocated in `transpile()` and freed in `reset_for_pool()`. pub path: bun_paths::fs::Path<'static>, - /// RAII: `Drop` derefs the WTF refcount — torn down by - /// `HiveArray::put` → `drop_in_place` (not in `reset_for_pool`). - pub(crate) non_threadsafe_input_specifier: OwnedString, - pub(crate) non_threadsafe_referrer: OwnedString, + pub(crate) non_threadsafe_input_specifier: bun_core::String, + pub(crate) non_threadsafe_referrer: bun_core::String, pub(crate) loader: Loader, pub(crate) promise: StrongOptional, // Note: struct is stored in a HiveArray and crosses to a worker thread; @@ -423,16 +416,12 @@ pub struct TranspilerJob { /// pushes to are all VM-owned, and the VM's teardown waits for the ticket. pub(crate) ticket: Option, pub global_this: BackRef, - pub(crate) fetcher: Fetcher, pub(crate) poll_ref: KeepAlive, pub(crate) generation_number: u32, pub(crate) log: bun_ast::Log, pub(crate) parse_error: Option, - /// RAII-owned: holds +1 on `source_code`/`source_url`/`specifier`/ - /// `bytecode_origin_path` until `run_from_js_thread` `take()`s and - /// `into_ffi()`s to C++. Dropped (via `HiveArray::put` → `drop_in_place`) - /// on any path that skips `run_from_js_thread` derefs them. - pub(crate) resolved_source: OwnedResolvedSource, + /// Moved out by `run_from_js_thread`; dropped with the slot otherwise. + pub(crate) resolved_source: ResolvedSource, pub(crate) work_task: WorkPoolTask, /// INTRUSIVE — `UnboundedQueue` link. pub(crate) next: unbounded_queue::Link, @@ -447,21 +436,6 @@ unsafe impl unbounded_queue::Linked for TranspilerJob { } } -pub enum Fetcher { - VirtualModule(String), - File, -} - -// Note: `bun_core::String` is `Copy` with manual `.deref()`; -// decrement explicitly when replacing the enum value. -impl Fetcher { - fn deinit(&mut self) { - if let Fetcher::VirtualModule(s) = self { - s.deref(); - } - } -} - /// Per-worker output buffer. The printer is the **only** state /// retained across `run()` calls — its backing `Vec` is genuinely worth /// reusing (capped at 512 K / 2 M below). The parse arena and AST memory @@ -503,14 +477,11 @@ impl TranspilerJob { /// `run_from_js_thread`. /// /// Note: `HiveArrayFallback::put` runs `drop_in_place` on the slot (see - /// hive_array.rs note), so the Drop-carrying fields — `OwnedString` ×2, - /// `OwnedResolvedSource`, `Log`, `StrongOptional` — are torn down *there*, - /// not here. This function handles only the teardown that field drop glue - /// does **not** cover: the leaked `path.text` Box, `poll_ref.disable()`, - /// and `fetcher.deinit()` (whose payload `bun_core::String` is `Copy` with - /// manual `.deref()`). Doing both — explicit `take()` here *and* - /// `drop_in_place` in `put()` — would double-drop should any future field's - /// `Default` not be trivially droppable. + /// hive_array.rs note), so the Drop-carrying fields — `bun_core::String` ×2, + /// `ResolvedSource`, `Log`, `StrongOptional` — are torn down + /// *there*, not here. This function handles only the teardown that field + /// drop glue does **not** cover: the leaked `path.text` Box and + /// `poll_ref.disable()`. fn reset_for_pool(&mut self) { // bun.default_allocator.free(this.path.text) — `path.text` was Box-duplicated in // `transpile()`; reconstruct the Box and drop it. @@ -523,7 +494,6 @@ impl TranspilerJob { } self.poll_ref.disable(); - self.fetcher.deinit(); // Remaining fields with Drop glue are handled by `store.put()` → // `drop_in_place`; do NOT `take()` them here (would drop the empty // replacement a second time). @@ -553,28 +523,19 @@ impl TranspilerJob { // vtable; resolve it via the `get_vm_ctx` hook (registered by `bun_runtime::init`). self.poll_ref.unref(get_vm_ctx(AllocatorType::Js)); - let referrer = core::mem::take(&mut self.non_threadsafe_referrer).into_inner(); + let referrer = core::mem::take(&mut self.non_threadsafe_referrer); let mut log = core::mem::replace(&mut self.log, bun_ast::Log::init()); - // Take RAII ownership out of the job; `into_ffi()` below transfers the - // +1 strings to `AsyncModule::fulfill` → C++ `Zig::ResolvedSource`. - let mut owned_resolved_source = core::mem::take(&mut self.resolved_source); - let resolved_source = owned_resolved_source.as_mut(); - let specifier = 'brk: { - if self.parse_error.is_some() { - break 'brk String::clone_utf8(self.path.text); + let (specifier, result) = match self.parse_error { + Some(e) => (String::clone_utf8(self.path.text), Err(e)), + None => { + let mut resolved_source = core::mem::take(&mut self.resolved_source); + let out = core::mem::take(&mut self.non_threadsafe_input_specifier); + debug_assert!(resolved_source.source_url.is_empty()); + resolved_source.source_url = out.create_if_different(self.path.text); + (out, Ok(resolved_source)) } - - let out = core::mem::take(&mut self.non_threadsafe_input_specifier).into_inner(); - - debug_assert!(resolved_source.source_url.is_empty()); - debug_assert!(resolved_source.specifier.is_empty()); - resolved_source.source_url = create_if_different(&out, self.path.text); - resolved_source.specifier = out.dupe_ref(); - break 'brk out; }; - let parse_error = self.parse_error; - self.promise.deinit(); self.reset_for_pool(); @@ -586,14 +547,12 @@ impl TranspilerJob { .put(std::ptr::from_mut::(self)) }; - let mut resolved_source = owned_resolved_source.into_ffi(); AsyncModule::fulfill( &global_this, promise, - &mut resolved_source, - parse_error, - specifier, - referrer, + result, + &specifier, + &referrer, &mut log, ) } @@ -688,7 +647,7 @@ impl TranspilerJob { let path = self.path; let specifier = self.path.text; let loader = self.loader; - let this_tag = self.resolved_source.get().tag; + let this_tag = self.resolved_source.tag; // RuntimeTranspilerCache has no per-allocator fields (Box<[u8]> + global mimalloc). // LAYERING: this is the canonical `bun_ast::RuntimeTranspilerCache` @@ -995,33 +954,24 @@ impl TranspilerJob { dump_source_string(vm, specifier, entry.output_code.byte_slice()); } - let module_info: *mut c_void = if use_isolation_source_provider_cache + let module_info = if use_isolation_source_provider_cache && entry.metadata.module_type != CacheModuleType::Cjs && !entry.esm_record.is_empty() { analyze_transpiled_module::ModuleInfoDeserialized::create_from_cached_record( &entry.esm_record, ) - .map(|b| bun_core::heap::into_raw(b).cast()) - .unwrap_or(ptr::null_mut()) } else { - ptr::null_mut() + None }; - self.resolved_source = OwnedResolvedSource::from(ResolvedSource { - source_code: match &mut entry.output_code { - OutputCode::String(s) => *s, - OutputCode::Utf8(utf8) => { - let result = String::clone_utf8(utf8); - *utf8 = Box::default(); - result - } - }, + self.resolved_source = ResolvedSource { + source_code: core::mem::take(&mut entry.output_code), is_commonjs_module: entry.metadata.module_type == CacheModuleType::Cjs, module_info, tag: this_tag, ..Default::default() - }); + }; return; } @@ -1029,27 +979,17 @@ impl TranspilerJob { if !matches!(parse_result.already_bundled, AlreadyBundled::None) { let already_bundled = core::mem::take(&mut parse_result.already_bundled); let is_commonjs_module = already_bundled.is_common_js(); - let (bytecode_cache, bytecode_cache_size) = match already_bundled { - AlreadyBundled::Bytecode(bytes) | AlreadyBundled::BytecodeCjs(bytes) => { - let len = bytes.len(); - if len == 0 { - (ptr::null_mut(), 0) - } else { - (bun_core::heap::into_raw(bytes).cast::(), len) - } - } - _ => (ptr::null_mut(), 0), - }; - self.resolved_source = OwnedResolvedSource::from(ResolvedSource { + let bytecode_cache = + crate::resolved_source::Bytecode::owned(already_bundled.into_bytecode()); + self.resolved_source = ResolvedSource { source_code: String::clone_latin1(&parse_result.source.contents), already_bundled: true, bytecode_cache, - bytecode_cache_size, is_commonjs_module, tag: this_tag, ..Default::default() - }); - self.resolved_source.as_mut().source_code.ensure_hash(); + }; + self.resolved_source.source_code.ensure_hash(); return; } @@ -1209,18 +1149,16 @@ impl TranspilerJob { break 'brk result; }; - self.resolved_source = OwnedResolvedSource::from(ResolvedSource { + self.resolved_source = ResolvedSource { source_code, is_commonjs_module, - module_info: module_info - .map(|mi| { - use analyze_transpiled_module::ModuleInfoExt; - bun_core::heap::into_raw(mi.into_deserialized()).cast() - }) - .unwrap_or(ptr::null_mut()), + module_info: module_info.map(|mi| { + use analyze_transpiled_module::ModuleInfoExt; + mi.into_deserialized() + }), tag: this_tag, ..Default::default() - }); + }; // `arena` and `ast_memory_store` drop here (after `_ast_scope` restores // the thread-local AST heap pointer), `mi_heap_destroy`ing every parse diff --git a/src/jsc/StringBuilder.rs b/src/jsc/StringBuilder.rs index 8161b439bd7d..37d8b56c26cf 100644 --- a/src/jsc/StringBuilder.rs +++ b/src/jsc/StringBuilder.rs @@ -42,7 +42,7 @@ impl StringBuilder { StringBuilder__appendUsize(self, value) } - pub fn append_string(&mut self, value: String) { + pub fn append_string(&mut self, value: &String) { StringBuilder__appendString(self, value) } @@ -85,7 +85,7 @@ unsafe extern "C" { safe fn StringBuilder__appendDouble(this: &mut StringBuilder, num: f64); safe fn StringBuilder__appendInt(this: &mut StringBuilder, num: i32); safe fn StringBuilder__appendUsize(this: &mut StringBuilder, num: usize); - safe fn StringBuilder__appendString(this: &mut StringBuilder, str: String); + safe fn StringBuilder__appendString(this: &mut StringBuilder, str: &String); safe fn StringBuilder__appendLChar(this: &mut StringBuilder, c: u8); safe fn StringBuilder__appendUChar(this: &mut StringBuilder, c: u16); safe fn StringBuilder__toString(this: &mut StringBuilder, global: &JSGlobalObject) -> JSValue; diff --git a/src/jsc/SystemError.rs b/src/jsc/SystemError.rs index b2fd3c3b13df..5ff665b86157 100644 --- a/src/jsc/SystemError.rs +++ b/src/jsc/SystemError.rs @@ -1,7 +1,7 @@ use core::ffi::c_int; use core::fmt; -use bun_core::{OwnedString, String}; +use bun_core::String; use crate::{JSGlobalObject, JSPromise, JSValue}; @@ -10,28 +10,28 @@ use crate::{JSGlobalObject, JSPromise, JSValue}; pub struct SystemError { pub errno: c_int, /// label for errno - pub code: OwnedString, + pub code: bun_core::String, /// it is illegal to have an empty message - pub message: OwnedString, - pub path: OwnedString, - pub syscall: OwnedString, - pub hostname: OwnedString, + pub message: bun_core::String, + pub path: bun_core::String, + pub syscall: bun_core::String, + pub hostname: bun_core::String, /// MinInt = no file descriptor pub fd: c_int, - pub dest: OwnedString, + pub dest: bun_core::String, } impl Default for SystemError { fn default() -> Self { Self { errno: 0, - code: OwnedString::default(), - message: OwnedString::default(), - path: OwnedString::default(), - syscall: OwnedString::default(), - hostname: OwnedString::default(), + code: bun_core::String::default(), + message: bun_core::String::default(), + path: bun_core::String::default(), + syscall: bun_core::String::default(), + hostname: bun_core::String::default(), fd: c_int::MIN, - dest: OwnedString::default(), + dest: bun_core::String::default(), } } } @@ -145,8 +145,8 @@ pub fn verify_error_to_js( let reason: &[u8] = err.reason_bytes(); let fallback = SystemError { - code: String::clone_utf8(code).into(), - message: String::clone_utf8(reason).into(), + code: String::clone_utf8(code), + message: String::clone_utf8(reason), ..Default::default() }; diff --git a/src/jsc/URL.rs b/src/jsc/URL.rs index 36c2dc07e26d..1e0d91c83c34 100644 --- a/src/jsc/URL.rs +++ b/src/jsc/URL.rs @@ -1,104 +1,31 @@ use core::ptr::NonNull; use bun_core::String; -use bun_jsc::{JSGlobalObject, JSValue, JsResult}; +pub use bun_url::whatwg::{Parsed, URL}; -bun_opaque::opaque_ffi! { - /// Opaque handle to a WebKit `WTF::URL` allocated on the C++ side. - pub struct URL; -} +use crate::{JSGlobalObject, JSValue, JsResult}; -// Getters take `&URL` (non-null `*const URL` at the C ABI; BunString.cpp never -// mutates the WTF::URL on read). `&mut String` for the in/out params is -// ABI-identical to non-null `*mut String`. `URL__deinit` consumes the C++ -// allocation, so it keeps a raw pointer and stays `unsafe fn`. unsafe extern "C" { safe fn URL__fromJS(value: JSValue, global: &JSGlobalObject) -> *mut URL; - safe fn URL__fromString(input: &mut String) -> *mut URL; - safe fn URL__protocol(url: &URL) -> String; - safe fn URL__username(url: &URL) -> String; - safe fn URL__password(url: &URL) -> String; - safe fn URL__host(url: &URL) -> String; - safe fn URL__port(url: &URL) -> u32; - fn URL__deinit(url: *mut URL); - safe fn URL__pathname(url: &URL) -> String; safe fn URL__getHrefFromJS(value: JSValue, global: &JSGlobalObject) -> String; - safe fn URL__getFileURLString(input: &mut String) -> String; - safe fn URL__pathFromFileURL(input: &mut String) -> String; } -impl URL { - pub fn file_url_from_string(str: String) -> String { - let mut input = str; - URL__getFileURLString(&mut input) - } - - pub fn path_from_file_url(str: String) -> String { - let mut input = str; - URL__pathFromFileURL(&mut input) - } - - /// This percent-encodes the URL, punycode-encodes the hostname, and returns the result - /// If it fails, the tag is marked Dead +/// JS-value entry points for [`URL`]; the rest of the API lives on +/// `bun_url::whatwg::URL`. +pub trait URLJsc { + /// Percent-encodes the URL, punycode-encodes the hostname, and returns the + /// result. If it fails, the tag is marked Dead. #[track_caller] - pub fn href_from_js(value: JSValue, global: &JSGlobalObject) -> JsResult { + fn href_from_js(value: JSValue, global: &JSGlobalObject) -> JsResult { crate::call_check_slow(global, || URL__getHrefFromJS(value, global)) } #[track_caller] - pub fn from_js(value: JSValue, global: &JSGlobalObject) -> JsResult>> { - crate::call_check_slow(global, || URL__fromJS(value, global)).map(NonNull::new) - } - - pub fn from_utf8(input: &[u8]) -> Option> { - Self::from_string(String::borrow_utf8(input)) - } - - pub fn from_string(str: String) -> Option> { - let mut input = str; - NonNull::new(URL__fromString(&mut input)) - } - // from_js/from_string/from_utf8 return an owned C++ heap pointer that the - // caller must destroy(). - - pub fn protocol(&self) -> String { - URL__protocol(self) - } - - pub fn username(&self) -> String { - URL__username(self) - } - - pub fn password(&self) -> String { - URL__password(self) - } - - /// Returns the host WITHOUT the port. - /// - /// Note that this does NOT match JS behavior, which returns the host with the port. The - /// with-port form lives on the JSC-free shim as `bun_url::whatwg::URL::hostname`. - /// - /// ```text - /// URL("http://example.com:8080").host() => "example.com" - /// ``` - pub fn host(&self) -> String { - URL__host(self) - } - - /// Returns `u32::MAX` if the port is not set. Otherwise, `port` - /// is guaranteed to be within the `u16` range. - pub fn port(&self) -> u32 { - URL__port(self) - } - - // Kept as explicit destroy (not Drop) — URL is an opaque #[repr(C)] FFI - // handle constructed/destroyed across the C++ boundary. - pub unsafe fn destroy(this: *mut Self) { - // SAFETY: `this` is a valid *URL from C++; freed exactly once - unsafe { URL__deinit(this) } - } - - pub fn pathname(&self) -> String { - URL__pathname(self) + fn from_js(value: JSValue, global: &JSGlobalObject) -> JsResult> { + crate::call_check_slow(global, || URL__fromJS(value, global)) + // SAFETY: `URL__fromJS` returns a fresh heap `WTF::URL` (or null). + .map(|p| NonNull::new(p).map(|p| unsafe { Parsed::from_raw(p) })) } } + +impl URLJsc for URL {} diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index c5029b0bbc46..dd4b2cf037c3 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -17,9 +17,8 @@ use crate::module_loader::{self as ModuleLoader, FetchFlags}; use crate::rare_data::RareData; use crate::saved_source_map::SavedSourceMap; use crate::{ - self as jsc, ErrorCode, ErrorableResolvedSource, ErrorableString, Exception, JSGlobalObject, - JSInternalPromise, JSValue, JsResult, OpaqueCallback, PlatformEventLoop, ResolvedSource, VM, - ZigException, + self as jsc, Exception, JSGlobalObject, JSInternalPromise, JSValue, JsResult, OpaqueCallback, + PlatformEventLoop, ResolvedSource, VM, ZigException, }; pub use crate::process_auto_killer as ProcessAutoKiller; @@ -580,13 +579,12 @@ impl ExitHandler { #[unsafe(no_mangle)] pub(crate) extern "C" fn Bun__VM__entryRootKey( vm: &VirtualMachine, - out: &mut bun_core::String, - ) { - *out = if !vm.transpiler.options.disable_transpilation && !vm.main_is_html_entrypoint { - bun_core::String::static_(MAIN_FILE_NAME) + ) -> bun_core::StringView<'_> { + if !vm.transpiler.options.disable_transpilation && !vm.main_is_html_entrypoint { + bun_core::StringView::static_(MAIN_FILE_NAME) } else { - bun_core::String::borrow_utf8(vm.main()) - }; + bun_core::StringView::borrow_utf8(vm.main()) + } } #[unsafe(no_mangle)] @@ -1432,12 +1430,12 @@ impl VirtualMachine { let display = result .to_error() .unwrap_or(result) - .get_zig_string(global) + .to_js_string_view(global) .ok(); match display { - Some(zs) => { - let utf8 = zs.to_owned_slice(); - let _ = writer.write_all(utf8.as_slice()); + Some(s) => { + let utf8 = s.to_utf8(); + let _ = writer.write_all(utf8.slice()); let _ = writer.write_all(b"\n"); } None => { @@ -2170,7 +2168,6 @@ pub struct RuntimeHooks { formatter: &'a mut crate::console_object::Formatter<'f>, writer: &'a mut dyn bun_io::Write, value: JSValue, - name_buf: &'a [u8; 512], enable_ansi_colors: bool, ) -> JsResult, /// Applies `--compile`-baked runtime flags to the @@ -2727,7 +2724,6 @@ impl VirtualMachine { ) -> crate::CrateResult<*mut JSInternalPromise> { self.has_loaded = false; self.set_main(entry_path); - self.main_resolved_path.deref(); self.main_resolved_path = bun_core::String::empty(); self.main_hash = bun_watcher::Watcher::get_hash(entry_path); self.overridden_main.deinit(); @@ -2898,22 +2894,16 @@ impl VirtualMachine { } } -/// Synthesize a JS -/// `BuildMessage` / `ResolveMessage` / `AggregateError` from the parser -/// `log` and write it into `ret` as `.err(..)` so the C++ module-loader -/// (`Bun__onFulfillAsyncModule`, ModuleLoader.cpp) rejects the import promise -/// with a real Error instead of `undefined`. -/// -/// Free function; takes `&JSGlobalObject` directly rather -/// than `&mut VirtualMachine` because the body never touches VM state. -pub(crate) fn process_fetch_log( +/// Synthesize a JS `BuildMessage` / `ResolveMessage` / `AggregateError` from +/// the parser `log` for a failed fetch, so the import promise rejects with a +/// real Error instead of `undefined`. +pub fn process_fetch_log( global_this: &JSGlobalObject, - specifier: bun_core::String, - referrer: bun_core::String, + specifier: &bun_core::String, + referrer: &bun_core::String, log: &mut bun_ast::Log, - ret: &mut ErrorableResolvedSource, err: crate::CrateError, -) { +) -> JSValue { use crate::{BuildMessage, ResolveMessage}; // Helper: on error, swap in the pending exception value. @@ -2954,25 +2944,21 @@ pub(crate) fn process_fetch_log( ..Default::default() } }; - *ret = ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - take(BuildMessage::create(global_this, msg)), - ); + take(BuildMessage::create(global_this, msg)) } 1 => { // Note: `Msg` is not `Copy`, so move it out — the caller deinits // the log immediately after, so consuming the vec is sound. let msg = log.msgs.swap_remove(0); - let value = match msg.metadata { + match msg.metadata { bun_ast::Metadata::Build => take(BuildMessage::create(global_this, msg)), bun_ast::Metadata::Resolve(_) => take(ResolveMessage::create( global_this, &msg, referrer_utf8.slice(), )), - }; - *ret = ErrorableResolvedSource::err(ErrorCode(ErrorCode::JS_ERROR_OBJECT), value); + } } _ => { @@ -3005,10 +2991,7 @@ pub(crate) fn process_fetch_log( ); let mut message = crate::ZigString::init(message_text); message.mark_global(); - *ret = ErrorableResolvedSource::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - take(global_this.create_aggregate_error(&errors_stack[..len], &message)), - ); + take(global_this.create_aggregate_error(&errors_stack[..len], &message)) } } } @@ -3417,16 +3400,6 @@ fn normalize_source(source: &[u8]) -> &[u8] { source } -/// `bun.String.createIfDifferent` — `clone_utf8(other)` unless `other` is -/// byte-equal to `s`, in which case bump `s`'s refcount instead. -#[inline] -pub(crate) fn create_if_different(s: &bun_core::String, other: &[u8]) -> bun_core::String { - if s.eql_utf8(other) { - return s.dupe_ref(); - } - bun_core::String::clone_utf8(other) -} - // Additional FFI used by the formerly-gated impl. // C++ side defines `extern "C" SYSV_ABI` (BakeAdditionsToGlobalObject.cpp). // @@ -4109,44 +4082,28 @@ impl VirtualMachine { } /// Builds a `ResolvedSource` backed by a ref-counted copy of `code` interned in the VM's ref-string map. - pub fn ref_counted_resolved_source( + pub fn ref_counted_resolved_source( &mut self, code: &[u8], - specifier: bun_core::String, + specifier: &bun_core::String, source_url: &[u8], hash_: Option, ) -> ResolvedSource { // refCountedString will panic if the code is empty if code.is_empty() { return ResolvedSource { - source_code: bun_core::String::init(b""), - specifier, - source_url: create_if_different(&specifier, source_url), - source_code_needs_deref: false, + source_url: specifier.create_if_different(source_url), ..Default::default() }; } - // Const-generic bool can't be `!ADD_DOUBLE_REF`, so branch. - let source = if ADD_DOUBLE_REF { - self.ref_counted_string::(code, hash_) - } else { - self.ref_counted_string::(code, hash_) - }; + let source = self.ref_counted_string::(code, hash_); // SAFETY: `ref_counted_string` returns a live `*mut RefString` held in - // `self.ref_strings`; we own +1 (or +3 below) until JSC calls the - // external-string finalizer. + // `self.ref_strings` until JSC calls the external-string finalizer. let source_ref = unsafe { &*source }; - if ADD_DOUBLE_REF { - source_ref.ref_(); - source_ref.ref_(); - } ResolvedSource { - source_code: bun_core::String::adopt_wtf_impl(source_ref.impl_), - specifier, - source_url: create_if_different(&specifier, source_url), - allocator: source.cast::(), - source_code_needs_deref: false, + source_code: bun_core::String::retain_wtf_impl(source_ref.impl_), + source_url: specifier.create_if_different(source_url), ..Default::default() } } @@ -4232,22 +4189,17 @@ impl VirtualMachine { pub(crate) fn fetch_without_on_load_plugins( jsc_vm: &mut VirtualMachine, global_object: &JSGlobalObject, - specifier: bun_core::String, - referrer: bun_core::String, + specifier: &bun_core::String, + referrer: &bun_core::String, log: &mut bun_ast::Log, flags: FetchFlags, ) -> crate::CrateResult { debug_assert!(VirtualMachine::is_loaded()); - let global_ptr = core::ptr::NonNull::from(global_object); - let mut ret = ErrorableResolvedSource::ok(ResolvedSource::default()); - let builtin = - ModuleLoader::fetch_builtin_module(jsc_vm, global_ptr, &specifier, &referrer, &mut ret); - match builtin { - ModuleLoader::FetchBuiltinResult::Found | ModuleLoader::FetchBuiltinResult::Errored => { - return ret.unwrap().map_err(Into::into); - } - ModuleLoader::FetchBuiltinResult::NotFound => {} + if let Some(resolved) = + ModuleLoader::__bun_fetch_builtin_module(jsc_vm, global_object, specifier) + { + return Ok(resolved); } let specifier_clone = specifier.to_utf8(); @@ -4335,18 +4287,18 @@ impl VirtualMachine { input_specifier: specifier, log: std::ptr::from_mut::(log), virtual_source: lr.virtual_source, - global_object: std::ptr::from_ref::(global_object).cast_mut(), + global_object, flags, - extra: (&raw mut extra).cast::(), + extra: &raw mut extra, }; - let mut ret = ErrorableResolvedSource::ok(ResolvedSource::default()); - let ok = ModuleLoader::transpile_source_code(guard.0, &args, &mut ret); - - if !ok && flags == FetchFlags::PrintSource { + // SAFETY: `guard.0` is the live per-thread VM; `args.extra` points at + // the live `extra` above. + let result = unsafe { ModuleLoader::__bun_transpile_source_code(guard.0, &args) }; + if result.is_err() && flags == FetchFlags::PrintSource { guard.1 = true; // errdefer } // `blob_to_deinit` drop guard fires here. - ret.unwrap().map_err(Into::into) + result } /// Dupe `s` into a VM-owned allocation for the `_resolve` fast-paths. @@ -4548,34 +4500,16 @@ impl VirtualMachine { Ok(()) } - /// Resolves `specifier` relative to `source`, writing the result or error into `res`. - pub(crate) fn resolve( - res: &mut ErrorableString, - global: &JSGlobalObject, - specifier: bun_core::String, - source: bun_core::String, - query_string: Option<&mut bun_core::String>, - mode: ResolveMode, - ) -> JsResult<()> { - Self::resolve_maybe_needs_trailing_slash::( - res, - global, - specifier, - source, - query_string, - mode, - ) - } - - /// Module-resolution core: resolves `specifier` relative to `source`, with path-length checks when `IS_A_FILE_PATH`. + /// Module-resolution core: resolves `specifier` relative to `source`, with + /// path-length checks when `IS_A_FILE_PATH`. `Ok(Err(value))` is a + /// resolution failure to be thrown/rejected with `value`. pub fn resolve_maybe_needs_trailing_slash( - res: &mut ErrorableString, global: &JSGlobalObject, - specifier: bun_core::String, - source: bun_core::String, + specifier: &bun_core::String, + source: &bun_core::String, query_string: Option<&mut bun_core::String>, mode: ResolveMode, - ) -> JsResult<()> { + ) -> JsResult> { const MAX_LEN: usize = (bun_paths::MAX_PATH_BYTES as f64 * 1.5) as usize; // `data:` URLs carry the module source inline and never touch the // filesystem, so the path-length cap does not apply to them. @@ -4596,11 +4530,11 @@ impl VirtualMachine { data: bun_ast::range_data(None, bun_ast::Range::NONE, printed), ..Default::default() }; - *res = ErrorableString::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - crate::ResolveMessage::create(global, &msg, source_utf8.slice())?, - ); - return Ok(()); + return Ok(Err(crate::ResolveMessage::create( + global, + &msg, + source_utf8.slice(), + )?)); } let mut result = ResolveFunctionResult::default(); @@ -4622,13 +4556,12 @@ impl VirtualMachine { }; if let Some(resolved_path) = plugin_runner_on_resolve_jsc( global, - bun_core::String::init(namespace), - bun_core::String::borrow_utf8(after_namespace), + &bun_core::String::init(namespace), + &bun_core::String::borrow_utf8(after_namespace), source, crate::BunPluginTarget::Bun, )? { - *res = resolved_path; - return Ok(()); + return Ok(resolved_path); } } } @@ -4638,20 +4571,18 @@ impl VirtualMachine { bun_ast::Target::Bun, Default::default(), ) { - *res = ErrorableString::ok( + return Ok(Ok( if mode == ResolveMode::RequireResolve && hardcoded.node_builtin { - specifier.dupe_ref() + specifier.clone() } else { bun_core::String::init(hardcoded.path.as_bytes()) }, - ); - return Ok(()); + )); } // Node's `--expose-internals`. if ModuleLoader::exposed_internal_tag(specifier_utf8.slice()).is_some() { - *res = ErrorableString::ok(specifier.dupe_ref()); - return Ok(()); + return Ok(Ok(specifier.clone())); } // Swap in a fresh log so resolver errors don't pollute the VM's main log. @@ -4745,23 +4676,18 @@ impl VirtualMachine { ..Default::default() } }); - *res = ErrorableString::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - crate::ResolveMessage::create(global, &msg, source_utf8.slice())?, - ); - return Ok(()); + return Ok(Err(crate::ResolveMessage::create( + global, + &msg, + source_utf8.slice(), + )?)); } if let Some(query) = query_string { - *query = if !result.query_string.is_empty() { - bun_core::String::clone_utf8(result.query_string) - } else { - bun_core::String::empty() - }; + *query = bun_core::String::clone_utf8(result.query_string); } - *res = ErrorableString::ok(bun_core::String::clone_utf8(result.path)); - Ok(()) + Ok(Ok(bun_core::String::clone_utf8(result.path))) } /// Worker-thread teardown. pub fn destroy(&mut self) { @@ -4816,6 +4742,7 @@ impl VirtualMachine { unsafe { self.transpiler.deinit() }; drop(core::mem::take(&mut self.resolved_path_dups)); + drop(core::mem::take(&mut self.main_resolved_path)); self.overridden_main.deinit(); @@ -4878,7 +4805,6 @@ impl VirtualMachine { ) -> crate::CrateResult<*mut JSInternalPromise> { self.has_loaded = false; self.set_main(entry_path); - self.main_resolved_path.deref(); self.main_resolved_path = bun_core::String::empty(); self.main_hash = bun_watcher::Watcher::get_hash(entry_path); self.overridden_main.deinit(); @@ -5138,7 +5064,6 @@ impl VirtualMachine { self.has_patched_run_main = false; self.set_main(b""); self.main_hash = 0; - self.main_resolved_path.deref(); self.main_resolved_path = bun_core::String::empty(); self.unhandled_error_counter = 0; // The finished file's plugins are dropped with its global; the next @@ -5524,7 +5449,6 @@ impl VirtualMachine { bun_sourcemap::SourceContentHandling::NoSourceContents, ) { if let Some(source_url) = lookup.display_source_url_if_needed(path) { - frame.source_url.deref(); frame.source_url = source_url; } // Direct copy; both sides are @@ -5674,10 +5598,8 @@ impl VirtualMachine { { continue; } - // Note: `frames[j] = frame`. `ZigStackFrame` impls - // `Drop` so `copy_within` is unavailable; swap instead — - // the discarded tail past `j` is never read after we - // truncate `frames_len` below. + // Swap rather than overwrite: the discarded tail past `j` + // still owns its strings and is released with the Holder. frames_buf.swap(j, i); j += 1; } @@ -5771,7 +5693,6 @@ impl VirtualMachine { }; if let Some(src) = display_url { - frames[top].source_url.deref(); frames[top].source_url = src; } @@ -5790,10 +5711,8 @@ impl VirtualMachine { let Ok(original_source) = Self::fetch_without_on_load_plugins( self, global, - // `top.source_url` is passed by - // value (no `dupeRef`); `bun_core::String` is `Copy`. - frames[top].source_url, - bun_core::String::empty(), + &frames[top].source_url, + &bun_core::String::empty(), &mut log, FetchFlags::PrintSource, ) else { @@ -5801,23 +5720,8 @@ impl VirtualMachine { break 'code bun_core::ZigStringSlice::EMPTY; }; *must_reset_parser_arena_later = true; - // Note: the transpile path `clone_utf8`s the source for - // `.print_source` - // (the backing `parse_result` drops on return — see - // jsc_hooks.rs Note at the `PrintSource` arm), leaving - // `source_code` with a +1 strong ref this caller never - // consumed. `to_utf8()` takes its own ref via - // `ZigStringSlice::WTF`, so balance the clone here. Also - // release the `dupe_ref` / `create_if_different` refs on - // `specifier` / `source_url` — this caller never reads them. - // Skipping the `source_code` deref leaks one WTFStringImpl - // (~file-size) per `Bun.inspect(new Error)` and fails - // inspect-error-leak.test.js. - let code = original_source.source_code.to_utf8(); - original_source.source_code.deref(); - original_source.specifier.deref(); - original_source.source_url.deref(); - code + // `to_utf8()` takes its own ref; `original_source` drops here. + original_source.source_code.to_utf8() }; if enable_source_code_preview.get() && code.slice().is_empty() { @@ -5884,7 +5788,6 @@ impl VirtualMachine { bun_sourcemap::SourceContentHandling::NoSourceContents, ) { if let Some(src) = lookup.display_source_url_if_needed(source_url.slice()) { - frames[i].source_url.deref(); frames[i].source_url = src; } let mapping = lookup.mapping; @@ -6000,11 +5903,6 @@ impl VirtualMachine { ); drop(source_code_slice); - // `exception_holder.deinit` - // releases the WTFString refs (`name`/`message`/stack-frame - // `function_name`/`source_url`/source-line bodies) populated by - // `JSC__JSValue__toZigException`. Skipping this leaks ~1 KB/error and - // OOMs the inspect-error-leak test. exception_holder.deinit(self); result } @@ -6156,8 +6054,8 @@ impl VirtualMachine { } let _ = last_pad; - let name = exception.name; - let message = exception.message; + let name = &exception.name; + let message = &exception.message; let is_error_instance = error_instance != JSValue::ZERO && error_instance.is_cell() @@ -6167,37 +6065,20 @@ impl VirtualMachine { // `Formatter<'2>::format`, which requires an unbounded (VM-lifetime) // borrow. `global()` returns `&'static` so the borrow detaches. let global_ref = self.global(); - // Note: hold the owning `bun_core::String` - // alongside the slice so the latin1 view stays live for this fn. - // `bun_core::String` is `Copy` (no `Drop`), so use a scopeguard to - // run `.deref()` on every exit path. - let mut code_string_guard = scopeguard::guard(None::, |s| { - if let Some(s) = s { - s.deref(); - } - }); + // Holds the owning `bun_core::String` so the latin1 view below stays + // live for this fn. + let code_string: Option; let code: Option<&[u8]> = if is_error_instance { // SAFETY: `is_error_instance` ⇒ `get_object()` is `Some`. let obj = unsafe { &mut *error_instance.get_object().unwrap_unchecked() }; if let Some(code_value) = obj.get_code_property_vm_inquiry(global_ref) { if code_value.is_string() { match code_value.to_bun_string(global_ref) { - Ok(code_string) if code_string.is_8bit() => { - // SAFETY: `code_string` is moved into - // `code_string_guard` and outlives the borrow. - let bytes: &[u8] = unsafe { - bun_core::ffi::slice( - code_string.latin1().as_ptr(), - code_string.latin1().len(), - ) - }; - *code_string_guard = Some(code_string); - Some(bytes) - } - Ok(s) => { - s.deref(); - None + Ok(s) if s.is_8bit() => { + code_string = Some(s); + code_string.as_ref().map(|s| s.latin1()) } + Ok(_) => None, Err(_) => bun_core::out_of_memory(), } } else { @@ -6356,7 +6237,7 @@ impl VirtualMachine { let mut saw_cause = false; // SAFETY: `is_error_instance` ⇒ object. let error_obj = unsafe { error_instance.get_object().unwrap_unchecked() }; - let mut iterator = crate::JSPropertyIterator::init( + let iterator = crate::JSPropertyIterator::init( global_ref, error_obj, crate::JSPropertyIteratorOptions { @@ -6369,8 +6250,7 @@ impl VirtualMachine { )?; let longest_name = iterator.get_longest_property_name().min(10); let mut is_first_property = true; - while let Some(field) = iterator.next()? { - let value = iterator.value; + while let Some((field, value)) = iterator.next()? { if field.eql_comptime(b"message") || field.eql_comptime(b"name") || field.eql_comptime(b"stack") @@ -6547,8 +6427,8 @@ impl VirtualMachine { } fn print_error_name_and_message( - name: bun_core::String, - message: bun_core::String, + name: &bun_core::String, + message: &bun_core::String, is_browser_error: bool, optional_code: Option<&[u8]>, writer: &mut bun_core::io::Writer, @@ -6595,20 +6475,26 @@ impl VirtualMachine { }; if has_prefix { break 'brk ( - bun_core::String::init(code), + bun_core::StringView::from_bytes(code), message.substring(code.len() + 2), ); } } } - (bun_core::String::empty(), message) + ( + bun_core::StringView::EMPTY, + bun_core::StringView::new(message), + ) } } else { - (name, message) + ( + bun_core::StringView::new(name), + bun_core::StringView::new(message), + ) }; pretty_write!( "{}{}\n", - error_display_level.formatter(display_name, allow_ansi_color, Colon::IncludeColon), + error_display_level.formatter(&display_name, allow_ansi_color, Colon::IncludeColon), display_message, )?; } else if !name.is_empty() { @@ -6621,7 +6507,7 @@ impl VirtualMachine { pretty_write!( "{}{}\n", error_display_level.formatter( - bun_core::String::empty(), + &bun_core::String::empty(), allow_ansi_color, Colon::IncludeColon ), @@ -6631,7 +6517,7 @@ impl VirtualMachine { pretty_write!( "{}\n", error_display_level.formatter( - bun_core::String::empty(), + &bun_core::String::empty(), allow_ansi_color, Colon::ExcludeColon ), @@ -6853,9 +6739,7 @@ fn wrap_unhandled_rejection_error_for_uncaught_exception( without a catch block, or by rejecting a promise which was not handled with .catch(). \ The promise rejected with the reason \""; if reason_str.is_string() { - // SAFETY: `as_string()` returns a non-null `*mut JSString` when - // `is_string()` is true; `view()` borrows it for the `write!` below. - let view = unsafe { (*reason_str.as_string()).view(global_object) }?; + let view = reason_str.as_string().view(global_object)?; return Ok(global_object .err( crate::ErrorCode::ERR_UNHANDLED_REJECTION, @@ -6874,17 +6758,18 @@ fn wrap_unhandled_rejection_error_for_uncaught_exception( /// `None` when no `Bun.plugin()` `onResolve` callback claimed the specifier. pub(crate) fn plugin_runner_on_resolve_jsc( global: &JSGlobalObject, - namespace: bun_core::String, - specifier: bun_core::String, - importer: bun_core::String, + namespace: &bun_core::String, + specifier: &bun_core::String, + importer: &bun_core::String, target: crate::BunPluginTarget, -) -> JsResult> { +) -> JsResult>> { use crate::StringJsc as _; + let empty = bun_core::String::EMPTY; let Some(on_resolve_plugin) = global.run_on_resolve_plugins( if namespace.length() > 0 && !namespace.eql_comptime(b"file") { namespace } else { - bun_core::String::static_(b"") + &empty }, specifier, importer, @@ -6903,42 +6788,36 @@ pub(crate) fn plugin_runner_on_resolve_jsc( return Ok(None); } if !path_value.is_string() { - return Ok(Some(ErrorableString::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - bun_core::String::static_(b"Expected \"path\" to be a string in onResolve plugin") - .to_error_instance(global), - ))); + return Ok(Some(Err(bun_core::String::static_( + b"Expected \"path\" to be a string in onResolve plugin", + ) + .to_error_instance(global)))); } - let file_path = bun_core::OwnedString::new(path_value.to_bun_string(global)?); + let file_path = path_value.to_bun_string(global)?; if file_path.length() == 0 { - return Ok(Some(ErrorableString::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - bun_core::String::static_( - b"Expected \"path\" to be a non-empty string in onResolve plugin", - ) - .to_error_instance(global), - ))); + return Ok(Some(Err(bun_core::String::static_( + b"Expected \"path\" to be a non-empty string in onResolve plugin", + ) + .to_error_instance(global)))); } else if file_path.eql_comptime(b".") || file_path.eql_comptime(b"..") || file_path.eql_comptime(b"...") || file_path.eql_comptime(b" ") { - return Ok(Some(ErrorableString::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - bun_core::String::static_(b"\"path\" is invalid in onResolve plugin") - .to_error_instance(global), - ))); + return Ok(Some(Err(bun_core::String::static_( + b"\"path\" is invalid in onResolve plugin", + ) + .to_error_instance(global)))); } let user_namespace: bun_core::String = 'brk: { if let Some(namespace_value) = on_resolve_plugin.get(global, b"namespace")? { if !namespace_value.is_string() { - return Ok(Some(ErrorableString::err( - ErrorCode(ErrorCode::JS_ERROR_OBJECT), - bun_core::String::static_(b"Expected \"namespace\" to be a string") - .to_error_instance(global), - ))); + return Ok(Some(Err(bun_core::String::static_( + b"Expected \"namespace\" to be a string", + ) + .to_error_instance(global)))); } let namespace_str = namespace_value.to_bun_string(global)?; @@ -6946,38 +6825,28 @@ pub(crate) fn plugin_runner_on_resolve_jsc( break 'brk bun_core::String::static_(b"file"); } if namespace_str.eql_comptime(b"file") { - namespace_str.deref(); break 'brk bun_core::String::static_(b"file"); } if namespace_str.eql_comptime(b"bun") { - namespace_str.deref(); break 'brk bun_core::String::static_(b"bun"); } if namespace_str.eql_comptime(b"node") { - namespace_str.deref(); break 'brk bun_core::String::static_(b"node"); } break 'brk namespace_str; } break 'brk bun_core::String::static_(b"file"); }; - // `bun_core::String` - // is `Copy` (no `Drop`), so guard the WTF refcount across the remaining - // early-return paths. - let user_namespace = scopeguard::guard(user_namespace, |s| s.deref()); // A `file`-namespace result (the default) is a filesystem path, not a new // specifier: hand it back unprefixed. Other namespaces keep the `ns:path` // form the module loader dispatches on. if user_namespace.eql_comptime(b"file") { - return Ok(Some(ErrorableString::ok(file_path.into_inner()))); + return Ok(Some(Ok(file_path))); } - // Our slow way of cloning the string into memory owned by JSC. - use std::io::Write as _; - let mut combined_string: Vec = Vec::new(); - write!(&mut combined_string, "{}:{}", *user_namespace, file_path).expect("unreachable"); - let out_ = bun_core::String::borrow_utf8(&combined_string); - let out = out_.to_js(global)?.to_bun_string(global)?; - Ok(Some(ErrorableString::ok(out))) + Ok(Some(Ok(bun_core::String::create_format(format_args!( + "{}:{}", + user_namespace, file_path + ))))) } diff --git a/src/jsc/ZigErrorType.rs b/src/jsc/ZigErrorType.rs deleted file mode 100644 index 6cd55d26e67d..000000000000 --- a/src/jsc/ZigErrorType.rs +++ /dev/null @@ -1,11 +0,0 @@ -use crate::JSValue; -use crate::error_code::ErrorCode; - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct ZigErrorType { - pub(crate) code: ErrorCode, - // Bare JSValue field is OK here — this is a #[repr(C)] FFI payload - // passed by value across the C++ boundary, not a heap-allocated Rust struct. - pub value: JSValue, -} diff --git a/src/jsc/ZigException.rs b/src/jsc/ZigException.rs index 7852d6f5d457..774a6cbc2e80 100644 --- a/src/jsc/ZigException.rs +++ b/src/jsc/ZigException.rs @@ -1,5 +1,4 @@ use core::ffi::{c_int, c_void}; -use core::mem::MaybeUninit; use core::ptr; use crate::exception_list; @@ -54,31 +53,6 @@ impl ZigException { ZigException__collectSourceLines(value, global, self); } - // Kept as explicit `deinit` (not `Drop`) — this is a #[repr(C)] FFI - // payload whose lifetime is gated by `Holder.loaded`; C++ constructs/populates it. - pub(crate) fn deinit(&mut self) { - self.syscall.deref(); - self.system_code.deref(); - self.path.deref(); - - self.name.deref(); - self.message.deref(); - - for line in self.stack.source_lines_mut() { - line.deref(); - } - - for frame in self.stack.frames_mutable() { - frame.deinit(); - } - - if let Some(source) = self.stack.referenced_source_provider { - // Pointer was set by JSC (C++) and is valid until this deref releases it. - // `SourceProvider` is an opaque ZST handle. - crate::SourceProvider::opaque_mut(source.as_ptr()).deref(); - } - } - // `ZigException__fromException` is declared in headers.h but has no C++ // body (bindings.cpp dropped it; the only producer is // `JSC__JSValue__toZigException` which writes through an out-param), so @@ -107,15 +81,13 @@ impl ZigException { } } -#[repr(C)] +/// Backing storage for a `ZigException`'s stack; C++ fills `source_lines` / +/// `frames` through the pointers in `zig_exception.stack`. pub struct Holder { pub(crate) source_line_numbers: [i32; Self::SOURCE_LINES_COUNT], - pub(crate) source_lines: [String; Self::SOURCE_LINES_COUNT], - pub(crate) frames: [ZigStackFrame; Self::FRAME_COUNT], - pub(crate) loaded: bool, - // Never read until `loaded` flips and `zig_exception()` writes it; - // all access must be gated on `loaded`. - pub(crate) zig_exception: MaybeUninit, + source_lines: [String; Self::SOURCE_LINES_COUNT], + frames: [ZigStackFrame; Self::FRAME_COUNT], + pub(crate) zig_exception: Option, pub(crate) need_to_clear_parser_arena_on_deinit: bool, } @@ -128,8 +100,7 @@ impl Holder { frames: core::array::from_fn(|_| ZigStackFrame::ZERO), source_line_numbers: [-1; Self::SOURCE_LINES_COUNT], source_lines: core::array::from_fn(|_| String::EMPTY), - zig_exception: MaybeUninit::uninit(), - loaded: false, + zig_exception: None, need_to_clear_parser_arena_on_deinit: false, } } @@ -138,68 +109,38 @@ impl Holder { Self::zero() } - // Not just `Drop` — takes the `vm` parameter for `reset_arena`. Callers - // should call this explicitly at the tail (it does the arena reset which - // `Drop` cannot), but the string-ref release half is also covered by - // `Drop` below so an early `?`/return between population and the tail - // call won't leak WTF string refs. + /// `Drop` releases the strings; this resets the parser arena used while + /// collecting source lines, which needs `vm`. pub(crate) fn deinit(&mut self, vm: &mut VirtualMachine) { - if self.loaded { - // SAFETY: `loaded == true` ⇔ `zig_exception()` has written this slot. - unsafe { self.zig_exception.assume_init_mut() }.deinit(); - // Make idempotent so the subsequent `Drop` is a no-op. - self.loaded = false; - } - if self.need_to_clear_parser_arena_on_deinit { + if core::mem::take(&mut self.need_to_clear_parser_arena_on_deinit) { ModuleLoader::reset_arena(vm); } } pub fn zig_exception(&mut self) -> &mut ZigException { - if !self.loaded { - self.zig_exception.write(ZigException { - r#type: JSErrorCode(255), - runtime_type: JSRuntimeType::NOTHING, - name: String::EMPTY, - message: String::EMPTY, - exception: ptr::null_mut(), - stack: ZigStackTrace { - source_lines_ptr: self.source_lines.as_mut_ptr(), - source_lines_numbers: self.source_line_numbers.as_mut_ptr(), - source_lines_len: Self::SOURCE_LINES_COUNT as u8, - source_lines_to_collect: Self::SOURCE_LINES_COUNT as u8, - frames_ptr: self.frames.as_mut_ptr(), - frames_len: 0, - frames_cap: Self::FRAME_COUNT as u8, - referenced_source_provider: None, - }, - errno: 0, - syscall: String::EMPTY, - system_code: String::EMPTY, - path: String::EMPTY, - remapped: false, - fd: -1, - browser_url: String::EMPTY, - }); - self.loaded = true; - } - - // SAFETY: either the branch above just wrote it, or `loaded` was already - // true from a prior call that wrote it. - unsafe { self.zig_exception.assume_init_mut() } - } -} - -impl Drop for Holder { - // Covers the string-ref-release half of cleanup. The explicit - // `deinit(&mut self, vm)` clears `loaded` after running, so this is a - // no-op on the happy path; it only fires when an early-return/`?`/panic - // skips the tail `deinit` call. - fn drop(&mut self) { - if self.loaded { - // SAFETY: `loaded == true` ⇔ `zig_exception()` has written this slot. - unsafe { self.zig_exception.assume_init_mut() }.deinit(); - self.loaded = false; - } + self.zig_exception.get_or_insert_with(|| ZigException { + r#type: JSErrorCode(255), + runtime_type: JSRuntimeType::NOTHING, + name: String::EMPTY, + message: String::EMPTY, + exception: ptr::null_mut(), + stack: ZigStackTrace { + source_lines_ptr: self.source_lines.as_mut_ptr(), + source_lines_numbers: self.source_line_numbers.as_mut_ptr(), + source_lines_len: Self::SOURCE_LINES_COUNT as u8, + source_lines_to_collect: Self::SOURCE_LINES_COUNT as u8, + frames_ptr: self.frames.as_mut_ptr(), + frames_len: 0, + frames_cap: Self::FRAME_COUNT as u8, + referenced_source_provider: None, + }, + errno: 0, + syscall: String::EMPTY, + system_code: String::EMPTY, + path: String::EMPTY, + remapped: false, + fd: -1, + browser_url: String::EMPTY, + }) } } diff --git a/src/jsc/ZigStackFrame.rs b/src/jsc/ZigStackFrame.rs index e77d7bda1004..fdb7311685fe 100644 --- a/src/jsc/ZigStackFrame.rs +++ b/src/jsc/ZigStackFrame.rs @@ -28,20 +28,6 @@ pub struct ZigStackFrame { } impl ZigStackFrame { - /// Explicit deref of owned strings. - /// - /// Intentionally NOT `Drop`: this `#[repr(C)]` extern struct lives both in - /// C++-populated buffers (`ZigStackTrace.frames_ptr`) and in the Rust-owned - /// `Holder.frames: [ZigStackFrame; 32]` array. `Holder::deinit()` calls - /// `ZigException::deinit()` → `frame.deinit()` to release the strings, but - /// the array elements are then later dropped by Rust when `Holder` itself - /// drops. A `Drop` impl would deref the same `WTF::StringImpl` a second - /// time (UAF). Explicit `deinit` only. - pub(crate) fn deinit(&mut self) { - self.function_name.deref(); - self.source_url.deref(); - } - pub(crate) fn snapshot( &self, root_path: &[u8], @@ -92,9 +78,9 @@ impl ZigStackFrame { bun_paths::resolve_path::relative(dir, source_url) } - pub fn name_formatter(&self, enable_color: bool) -> NameFormatter { + pub fn name_formatter(&self, enable_color: bool) -> NameFormatter<'_> { NameFormatter { - function_name: self.function_name, + function_name: &self.function_name, code_type: self.code_type, enable_color, is_async: self.is_async, @@ -102,14 +88,14 @@ impl ZigStackFrame { } pub(crate) fn source_url_formatter<'a>( - &self, + &'a self, root_path: &'a [u8], origin: Option<&'a ZigURL<'a>>, line_column: LineColumn, enable_color: bool, ) -> SourceURLFormatter<'a> { SourceURLFormatter { - source_url: self.source_url, + source_url: &self.source_url, line_column, origin, root_path, @@ -128,7 +114,7 @@ pub(crate) enum LineColumn { } pub struct SourceURLFormatter<'a> { - pub(crate) source_url: BunString, + pub(crate) source_url: &'a BunString, pub(crate) position: ZigStackFramePosition, pub(crate) enable_color: bool, pub(crate) origin: Option<&'a ZigURL<'a>>, @@ -237,16 +223,16 @@ impl<'a> fmt::Display for SourceURLFormatter<'a> { } } -pub struct NameFormatter { - pub(crate) function_name: BunString, +pub struct NameFormatter<'a> { + pub(crate) function_name: &'a BunString, pub(crate) code_type: ZigStackFrameCode, pub(crate) enable_color: bool, pub(crate) is_async: bool, } -impl fmt::Display for NameFormatter { +impl fmt::Display for NameFormatter<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let name = &self.function_name; + let name = self.function_name; match self.code_type { ZigStackFrameCode::EVAL => { diff --git a/src/jsc/ZigStackTrace.rs b/src/jsc/ZigStackTrace.rs index aea7915a306f..1b4692afaa67 100644 --- a/src/jsc/ZigStackTrace.rs +++ b/src/jsc/ZigStackTrace.rs @@ -29,6 +29,14 @@ pub struct ZigStackTrace { pub(crate) referenced_source_provider: Option>, } +impl Drop for ZigStackTrace { + fn drop(&mut self) { + if let Some(source) = self.referenced_source_provider.take() { + SourceProvider::opaque_mut(source.as_ptr()).deref(); + } + } +} + impl ZigStackTrace { pub fn from_frames(frames_slice: &mut [ZigStackFrame]) -> ZigStackTrace { ZigStackTrace { @@ -79,20 +87,6 @@ impl ZigStackTrace { unsafe { bun_core::ffi::slice(self.frames_ptr, self.frames_len as usize) } } - pub(crate) fn frames_mutable(&mut self) -> &mut [ZigStackFrame] { - // SAFETY: frames_ptr points to a caller-owned buffer of at least frames_len elements. - unsafe { bun_core::ffi::slice_mut(self.frames_ptr, self.frames_len as usize) } - } - - /// Mutable view of the populated source-line strings (`[0..source_lines_len]`). - #[inline] - pub(crate) fn source_lines_mut(&mut self) -> &mut [BunString] { - // SAFETY: `source_lines_ptr` points to a caller-owned buffer of at least - // `source_lines_len` initialized elements (populated by C++ via FFI). - // The borrow is tied to `&mut self`. - unsafe { bun_core::ffi::slice_mut(self.source_lines_ptr, self.source_lines_len as usize) } - } - /// Immutable view of the populated source-line numbers (`[0..source_lines_len]`). #[inline] pub(crate) fn source_line_numbers(&self) -> &[i32] { diff --git a/src/jsc/bindings/BakeAdditionsToGlobalObject.cpp b/src/jsc/bindings/BakeAdditionsToGlobalObject.cpp index 8808e747588a..ac403b5ec3ec 100644 --- a/src/jsc/bindings/BakeAdditionsToGlobalObject.cpp +++ b/src/jsc/bindings/BakeAdditionsToGlobalObject.cpp @@ -84,7 +84,7 @@ extern "C" SYSV_ABI JSC::EncodedJSValue Bake__getBundleNewRouteJSFunction(JSC::J return JSValue::encode(value); } -extern "C" SYSV_ABI JSC::EncodedJSValue Bake__bundleNewRouteJSFunctionImpl(JSC::JSGlobalObject* globalObject, void* requestPtr, BunString url); +extern "C" SYSV_ABI JSC::EncodedJSValue Bake__bundleNewRouteJSFunctionImpl(JSC::JSGlobalObject* globalObject, void* requestPtr, const BunString* url); BUN_DEFINE_HOST_FUNCTION(jsFunctionBakeGetBundleNewRouteJSFunction, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callframe)) { auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); @@ -114,7 +114,7 @@ BUN_DEFINE_HOST_FUNCTION(jsFunctionBakeGetBundleNewRouteJSFunction, (JSC::JSGlob BunString url = Bun::toString(urlValue.getString(globalObject)); RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(jsUndefined())); - return Bake__bundleNewRouteJSFunctionImpl(globalObject, request->m_ctx, url); + return Bake__bundleNewRouteJSFunctionImpl(globalObject, request->m_ctx, &url); } extern "C" SYSV_ABI JSC::EncodedJSValue Bake__getNewRouteParamsJSFunction(JSC::JSGlobalObject* globalObject) diff --git a/src/jsc/bindings/BunAnalyzeTranspiledModule.cpp b/src/jsc/bindings/BunAnalyzeTranspiledModule.cpp index fdfaadacaf1c..0951f1592ddd 100644 --- a/src/jsc/bindings/BunAnalyzeTranspiledModule.cpp +++ b/src/jsc/bindings/BunAnalyzeTranspiledModule.cpp @@ -171,19 +171,19 @@ extern "C" EncodedJSValue Bun__analyzeTranspiledModule(JSGlobalObject* globalObj auto provider = static_cast(sourceCode.provider()); - if (provider->m_resolvedSource.module_info == nullptr) { + if (provider->m_moduleInfo == nullptr) { dataLog("[note] module_info is null for module: ", moduleKey.utf8(), "\n"); RELEASE_AND_RETURN(scope, JSValue::encode(rejectWithError(createError(globalObject, WTF::String::fromLatin1("module_info is null"))))); } - auto* moduleInfo = static_cast(provider->m_resolvedSource.module_info); + auto* moduleInfo = provider->m_moduleInfo; auto moduleRecord = zig__ModuleInfoDeserialized__toJSModuleRecord(globalObject, vm, moduleKey, sourceCode, moduleInfo); // Under --isolate the same SourceProvider is reused across globals via the // IsolatedModuleCache, so module_info must remain alive on the provider; // ~SourceProvider frees it. Otherwise, free now. if (!Bun::IsolatedModuleCache::canUse(vm, uncheckedDowncast(globalObject)->bunVM())) { zig__ModuleInfoDeserialized__deinit(moduleInfo); - provider->m_resolvedSource.module_info = nullptr; + provider->m_moduleInfo = nullptr; } if (moduleRecord == nullptr) { RELEASE_AND_RETURN(scope, JSValue::encode(rejectWithError(createError(globalObject, WTF::String::fromLatin1("parseFromSourceCode failed"))))); diff --git a/src/jsc/bindings/BunDebugger.cpp b/src/jsc/bindings/BunDebugger.cpp index 86556dc0b14e..5fa800117b28 100644 --- a/src/jsc/bindings/BunDebugger.cpp +++ b/src/jsc/bindings/BunDebugger.cpp @@ -951,7 +951,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunction_closeNodeInspector, (JSGlobalObject*, CallFr return JSValue::encode(jsUndefined()); } -extern "C" void Bun__startJSDebuggerThread(Zig::GlobalObject* debuggerGlobalObject, ScriptExecutionContextIdentifier scriptId, BunString* portOrPathString, int isAutomatic, bool isUrlServer, bool isNodeInspector) +extern "C" void Bun__startJSDebuggerThread(Zig::GlobalObject* debuggerGlobalObject, ScriptExecutionContextIdentifier scriptId, const BunString* portOrPathString, int isAutomatic, bool isUrlServer, bool isNodeInspector) { if (!debuggerScriptExecutionContext) debuggerScriptExecutionContext = debuggerGlobalObject->scriptExecutionContext(); diff --git a/src/jsc/bindings/BunPlugin.cpp b/src/jsc/bindings/BunPlugin.cpp index 5b21bae2b5a2..fb831a647128 100644 --- a/src/jsc/bindings/BunPlugin.cpp +++ b/src/jsc/bindings/BunPlugin.cpp @@ -721,7 +721,7 @@ void JSModuleMock::visitChildrenImpl(JSCell* cell, Visitor& visitor) DEFINE_VISIT_CHILDREN(JSModuleMock); -EncodedJSValue BunPlugin::OnLoad::run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path) +EncodedJSValue BunPlugin::OnLoad::run(JSC::JSGlobalObject* globalObject, const BunString* namespaceString, const BunString* path) { Group* groupPtr = this->group(namespaceString ? namespaceString->toWTFString(BunString::ZeroCopy) : String()); if (groupPtr == nullptr) { @@ -791,7 +791,7 @@ std::optional BunPlugin::OnLoad::resolveVirtualModule(const String& path return virtualModules->contains(path) ? std::optional { path } : std::nullopt; } -EncodedJSValue BunPlugin::OnResolve::run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* importer) +EncodedJSValue BunPlugin::OnResolve::run(JSC::JSGlobalObject* globalObject, const BunString* namespaceString, const BunString* path, const BunString* importer) { Group* groupPtr = this->group(namespaceString ? namespaceString->toWTFString(BunString::ZeroCopy) : String()); if (groupPtr == nullptr) { @@ -892,12 +892,12 @@ EncodedJSValue BunPlugin::OnResolve::run(JSC::JSGlobalObject* globalObject, BunS } // namespace Zig -extern "C" JSC::EncodedJSValue Bun__runOnResolvePlugins(Zig::GlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* from, BunPluginTarget target) +extern "C" JSC::EncodedJSValue Bun__runOnResolvePlugins(Zig::GlobalObject* globalObject, const BunString* namespaceString, const BunString* path, const BunString* from, BunPluginTarget target) { return globalObject->onResolvePlugins.run(globalObject, namespaceString, path, from); } -extern "C" JSC::EncodedJSValue Bun__runOnLoadPlugins(Zig::GlobalObject* globalObject, BunString* namespaceString, BunString* path, BunPluginTarget target) +extern "C" JSC::EncodedJSValue Bun__runOnLoadPlugins(Zig::GlobalObject* globalObject, const BunString* namespaceString, const BunString* path, BunPluginTarget target) { return globalObject->onLoadPlugins.run(globalObject, namespaceString, path); } diff --git a/src/jsc/bindings/BunPlugin.h b/src/jsc/bindings/BunPlugin.h index 9f83f1710f32..49dc77b775b7 100644 --- a/src/jsc/bindings/BunPlugin.h +++ b/src/jsc/bindings/BunPlugin.h @@ -78,7 +78,7 @@ class BunPlugin { VirtualModuleMap* _Nullable virtualModules = nullptr; bool mustDoExpensiveRelativeLookup = false; - JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path); + JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, const BunString* namespaceString, const BunString* path); bool hasVirtualModules() const { return virtualModules != nullptr; } @@ -110,7 +110,7 @@ class BunPlugin { { } - JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* importer); + JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, const BunString* namespaceString, const BunString* path, const BunString* importer); }; }; diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index d3512e67bbcd..583c1dde12f1 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -137,7 +137,7 @@ extern "C" bool Bun__Node__ProcessNoWarnings; extern "C" bool Bun__Node__ProcessTraceWarnings; extern "C" bool Bun__Node__ProcessTraceDeprecation; extern "C" bool Bun__Node__ProcessPendingDeprecation; -extern "C" bool Bun__Node__getRedirectWarnings(BunString* out); +extern "C" BunString Bun__Node__getRedirectWarnings(); extern "C" size_t Bun__Node__getDisabledWarnings(const uint8_t** bufs, size_t* lens, size_t cap); extern "C" bool Bun__getEnvValue(JSC::JSGlobalObject* globalObject, const ZigString* name, ZigString* value); extern "C" bool Bun__Node__ProcessThrowDeprecation; @@ -332,7 +332,7 @@ JSC_DEFINE_CUSTOM_SETTER(Process_defaultSetter, (JSC::JSGlobalObject * globalObj return true; } -extern "C" bool Bun__resolveEmbeddedNodeFile(void*, BunString*); +extern "C" BunString Bun__resolveEmbeddedNodeFile(const BunString*); #if OS(WINDOWS) extern "C" HMODULE Bun__LoadLibraryBunString(BunString*); #endif @@ -479,8 +479,9 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( [[maybe_unused]] bool fromEmbedded = false; if (filename.startsWith(StandaloneModuleGraph__base_path)) { BunString bunStr = Bun::toString(filename); - if (Bun__resolveEmbeddedNodeFile(globalObject->bunVM(), &bunStr)) { - filename = bunStr.transferToWTFString(); + BunString resolved = Bun__resolveEmbeddedNodeFile(&bunStr); + if (resolved.tag != BunStringTag::Dead) { + filename = resolved.transferToWTFString(); // The extracted file is content-hashed and shared across dlopens // and restarts (#29587), so it is never deleted here. fromEmbedded = true; @@ -1661,8 +1662,8 @@ JSObject* Process::ensureOnWarning(Zig::GlobalObject* globalObject) args.append(this); // --redirect-warnings, then NODE_REDIRECT_WARNINGS. JSValue redirectPath = jsUndefined(); - BunString redirect; - if (Bun__Node__getRedirectWarnings(&redirect)) { + BunString redirect = Bun__Node__getRedirectWarnings(); + if (redirect.tag != BunStringTag::Dead) { redirectPath = jsString(vm, redirect.transferToWTFString()); } else { ZigString name = toZigString("NODE_REDIRECT_WARNINGS"_s); @@ -4560,10 +4561,7 @@ JSC_DEFINE_CUSTOM_GETTER(processTitle, (JSC::JSGlobalObject * globalObject, JSC: auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); #if !OS(WINDOWS) - BunString str; - Bun__Process__getTitle(globalObject, &str); - auto value = str.transferToWTFString(); - auto* result = jsString(globalObject->vm(), WTF::move(value)); + auto* result = jsString(globalObject->vm(), Bun__Process__getTitle(globalObject).transferToWTFString()); RETURN_IF_EXCEPTION(scope, {}); RELEASE_AND_RETURN(scope, JSValue::encode(result)); #else @@ -4572,10 +4570,7 @@ JSC_DEFINE_CUSTOM_GETTER(processTitle, (JSC::JSGlobalObject * globalObject, JSC: // that uv_get_process_title reads is unavailable in console-less // processes (CI) and never reflects the CLI flag. if (Bun__Process__hasTitle()) { - BunString str; - Bun__Process__getTitle(globalObject, &str); - auto value = str.transferToWTFString(); - auto* result = jsString(vm, WTF::move(value)); + auto* result = jsString(vm, Bun__Process__getTitle(globalObject).transferToWTFString()); RETURN_IF_EXCEPTION(scope, {}); RELEASE_AND_RETURN(scope, JSValue::encode(result)); } @@ -4601,16 +4596,16 @@ JSC_DEFINE_CUSTOM_SETTER(setProcessTitle, (JSC::JSGlobalObject * globalObject, J if (!thisObject || !jsString) { return false; } + WTF::String wtfStr = jsString->value(globalObject); + RETURN_IF_EXCEPTION(scope, false); #if !OS(WINDOWS) - BunString str = Bun::toStringRef(globalObject, jsString); + BunString str = Bun::toString(wtfStr); Bun__Process__setTitle(globalObject, &str); return true; #else - WTF::String wtfStr = jsString->value(globalObject); - RETURN_IF_EXCEPTION(scope, false); // Update the store first so the getter reflects the assignment; the uv // call is best-effort (it fails in console-less processes). - BunString str = Bun::toStringRef(globalObject, jsString); + BunString str = Bun::toString(wtfStr); Bun__Process__setTitle(globalObject, &str); CString cstr = wtfStr.utf8(); uv_set_process_title(cstr.data()); diff --git a/src/jsc/bindings/BunString.cpp b/src/jsc/bindings/BunString.cpp index 5ec07a9770c1..a309d8e5e2d3 100644 --- a/src/jsc/bindings/BunString.cpp +++ b/src/jsc/bindings/BunString.cpp @@ -55,7 +55,7 @@ extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__WTFStringImpl__destroy(WTF::StringI extern "C" [[ZIG_EXPORT(nothrow)]] bool BunString__fromJS(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue encodedValue, BunString* bunString) { JSC::JSValue value = JSC::JSValue::decode(encodedValue); - *bunString = Bun::toString(globalObject, value); + *bunString = Bun::toStringRef(globalObject, value); return bunString->tag != BunStringTag::Dead; } @@ -115,20 +115,13 @@ JSC::JSValue BunString::transferToJS(JSC::JSGlobalObject* globalObject) } if (this->tag == BunStringTag::WTFStringImpl) [[likely]] { -#if ASSERT_ENABLED - unsigned refCount = this->impl.wtf->refCount(); - ASSERT(refCount > 0 && !this->impl.wtf->isEmpty()); -#endif - auto str = this->toWTFString(); -#if ASSERT_ENABLED - unsigned newRefCount = this->impl.wtf->refCount(); - ASSERT(newRefCount == refCount + 1); -#endif - this->impl.wtf->deref(); + ASSERT(this->impl.wtf->refCount() > 0 && !this->impl.wtf->isEmpty()); + auto str = WTF::String(adoptRef(*this->impl.wtf)); *this = { .tag = BunStringTag::Dead }; return jsString(vm, WTF::move(str)); } + // ZigString / StaticZigString: copies (the bytes are borrowed). WTF::String str = this->toWTFString(); *this = { .tag = BunStringTag::Dead }; return jsString(vm, WTF::move(str)); @@ -172,26 +165,6 @@ JSC::JSString* toJS(JSC::JSGlobalObject* globalObject, BunString bunString) UNREACHABLE(); } -BunString toString(const char* bytes, size_t length) -{ - return BunString__fromBytes(bytes, length); -} - -BunString fromJS(JSC::JSGlobalObject* globalObject, JSValue value) -{ - WTF::String str = value.toWTFString(globalObject); - if (str.isNull()) [[unlikely]] { - return { BunStringTag::Dead }; - } - if (str.length() == 0) [[unlikely]] { - return { BunStringTag::Empty }; - } - - auto impl = str.releaseImpl(); - - return { BunStringTag::WTFStringImpl, { .wtf = impl.leakRef() } }; -} - extern "C" [[ZIG_EXPORT(nothrow)]] void BunString__toThreadSafe(BunString* str) { if (str->tag == BunStringTag::WTFStringImpl) { @@ -207,11 +180,6 @@ extern "C" [[ZIG_EXPORT(nothrow)]] void BunString__toThreadSafe(BunString* str) } } -BunString toString(JSC::JSGlobalObject* globalObject, JSValue value) -{ - return fromJS(globalObject, value); -} - BunString toStringRef(JSC::JSGlobalObject* globalObject, JSValue value) { auto str = value.toWTFString(globalObject); @@ -222,11 +190,7 @@ BunString toStringRef(JSC::JSGlobalObject* globalObject, JSValue value) return { BunStringTag::Empty }; } - StringImpl* impl = str.impl(); - - impl->ref(); - - return { BunStringTag::WTFStringImpl, { .wtf = impl } }; + return { BunStringTag::WTFStringImpl, { .wtf = str.releaseImpl().leakRef() } }; } BunString toString(WTF::String& wtfString) @@ -461,7 +425,7 @@ extern "C" BunString BunString__createExternal(const char* bytes, size_t length, extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue BunString__toJSON( JSC::JSGlobalObject* globalObject, - BunString* bunString) + const BunString* bunString) { auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); JSC::JSValue result = JSC::JSONParse(globalObject, bunString->toWTFString()); @@ -500,7 +464,7 @@ extern "C" JSC::EncodedJSValue BunString__createArray( return JSValue::encode(array); } -extern "C" BunString URL__getFileURLString(BunString* filePath) +extern "C" BunString URL__getFileURLString(const BunString* filePath) { return Bun::toStringRef(WTF::URL::fileURLWithFileSystemPath(filePath->toWTFString()).stringWithoutFragmentIdentifier()); } @@ -516,7 +480,7 @@ extern "C" size_t URL__originLength(const char* latin1_slice, size_t len) return url.pathStart(); } -extern "C" JSC::EncodedJSValue BunString__toJSDOMURL(JSC::JSGlobalObject* lexicalGlobalObject, BunString* bunString) +extern "C" JSC::EncodedJSValue BunString__toJSDOMURL(JSC::JSGlobalObject* lexicalGlobalObject, const BunString* bunString) { auto& globalObject = *uncheckedDowncast(lexicalGlobalObject); auto& vm = globalObject.vm(); @@ -566,7 +530,7 @@ extern "C" BunString URL__getHrefFromJS(EncodedJSValue encodedValue, JSC::JSGlob return Bun::toStringRef(url.string()); } -extern "C" BunString URL__getHref(BunString* input) +extern "C" BunString URL__getHref(const BunString* input) { auto&& str = input->toWTFString(); auto url = WTF::URL(str); @@ -576,7 +540,7 @@ extern "C" BunString URL__getHref(BunString* input) return Bun::toStringRef(url.string()); } -extern "C" BunString URL__pathFromFileURL(BunString* input) +extern "C" BunString URL__pathFromFileURL(const BunString* input) { auto&& str = input->toWTFString(); auto url = WTF::URL(str); @@ -586,7 +550,7 @@ extern "C" BunString URL__pathFromFileURL(BunString* input) return Bun::toStringRef(url.fileSystemPath()); } -extern "C" BunString URL__getHrefJoin(BunString* baseStr, BunString* relativeStr) +extern "C" BunString URL__getHrefJoin(const BunString* baseStr, const BunString* relativeStr) { auto base = baseStr->toWTFString(); auto relative = relativeStr->toWTFString(); @@ -601,11 +565,11 @@ extern "C" BunString URL__fragmentIdentifier(WTF::URL* url) { const auto& fragment = url->fragmentIdentifier().isEmpty() ? emptyString() - : url->fragmentIdentifier().toStringWithoutCopying(); + : url->fragmentIdentifier().toString(); return Bun::toStringRef(fragment); } -extern "C" WTF::URL* URL__fromString(BunString* input) +extern "C" WTF::URL* URL__fromString(const BunString* input) { auto&& str = input->toWTFString(); auto url = WTF::URL(str); @@ -617,7 +581,7 @@ extern "C" WTF::URL* URL__fromString(BunString* input) extern "C" BunString URL__protocol(WTF::URL* url) { - return Bun::toStringRef(url->protocol().toStringWithoutCopying()); + return Bun::toStringRef(url->protocol().toString()); } extern "C" void URL__deinit(WTF::URL* url) @@ -649,7 +613,7 @@ extern "C" BunString URL__password(WTF::URL* url) /// ``` extern "C" BunString URL__host(WTF::URL* url) { - return Bun::toStringRef(url->host().toStringWithoutCopying()); + return Bun::toStringRef(url->host().toString()); } /// Returns the host WITH the port. @@ -677,7 +641,7 @@ extern "C" uint32_t URL__port(WTF::URL* url) extern "C" BunString URL__pathname(WTF::URL* url) { - return Bun::toStringRef(url->path().toStringWithoutCopying()); + return Bun::toStringRef(url->path().toString()); } WTF::String BunString::toWTFString() const @@ -760,8 +724,7 @@ WTF::String BunString::transferToWTFString() } else if (this->tag == BunStringTag::WTFStringImpl) { ASSERT(this->impl.wtf->refCount() > 0 && !this->impl.wtf->isEmpty()); - auto str = WTF::String(this->impl.wtf); - this->impl.wtf->deref(); + auto str = WTF::String(adoptRef(*this->impl.wtf)); *this = Zig::BunStringEmpty; return str; } diff --git a/src/jsc/bindings/ErrorCode.cpp b/src/jsc/bindings/ErrorCode.cpp index 371b2e5e9af3..c928b24e8c68 100644 --- a/src/jsc/bindings/ErrorCode.cpp +++ b/src/jsc/bindings/ErrorCode.cpp @@ -1702,7 +1702,7 @@ static JSValue ERR_INVALID_ARG_VALUE(JSC::ThrowScope& throwScope, JSC::JSGlobalO return createError(globalObject, code, builder.toString()); } -extern "C" JSC::EncodedJSValue Bun__createErrorWithCode(JSC::JSGlobalObject* globalObject, ErrorCode code, BunString* message) +extern "C" JSC::EncodedJSValue Bun__createErrorWithCode(JSC::JSGlobalObject* globalObject, ErrorCode code, const BunString* message) { return JSValue::encode(createError(globalObject, code, message->toWTFString(BunString::ZeroCopy))); } diff --git a/src/jsc/bindings/InspectorBunFrontendDevServerAgent.cpp b/src/jsc/bindings/InspectorBunFrontendDevServerAgent.cpp index a6116137e580..1b290de4f7f0 100644 --- a/src/jsc/bindings/InspectorBunFrontendDevServerAgent.cpp +++ b/src/jsc/bindings/InspectorBunFrontendDevServerAgent.cpp @@ -143,12 +143,12 @@ void InspectorBunFrontendDevServerAgent__notifyBundleComplete(InspectorBunFronte agent->bundleComplete(devServerId, durationMs); } -void InspectorBunFrontendDevServerAgent__notifyBundleFailed(InspectorBunFrontendDevServerAgent* agent, int devServerId, BunString* buildErrorsPayloadBase64) +void InspectorBunFrontendDevServerAgent__notifyBundleFailed(InspectorBunFrontendDevServerAgent* agent, int devServerId, BunString buildErrorsPayloadBase64) { - agent->bundleFailed(devServerId, buildErrorsPayloadBase64->transferToWTFString()); + agent->bundleFailed(devServerId, buildErrorsPayloadBase64.transferToWTFString()); } -void InspectorBunFrontendDevServerAgent__notifyClientNavigated(InspectorBunFrontendDevServerAgent* agent, int devServerId, int connectionId, BunString* url, int routeBundleId) +void InspectorBunFrontendDevServerAgent__notifyClientNavigated(InspectorBunFrontendDevServerAgent* agent, int devServerId, int connectionId, const BunString* url, int routeBundleId) { std::optional optionalRouteBundleId; if (routeBundleId > -1) { @@ -158,7 +158,7 @@ void InspectorBunFrontendDevServerAgent__notifyClientNavigated(InspectorBunFront agent->clientNavigated(devServerId, connectionId, url->toWTFString(), optionalRouteBundleId); } -void InspectorBunFrontendDevServerAgent__notifyConsoleLog(InspectorBunFrontendDevServerAgent* agent, int devServerId, char kind, BunString* data) +void InspectorBunFrontendDevServerAgent__notifyConsoleLog(InspectorBunFrontendDevServerAgent* agent, int devServerId, char kind, const BunString* data) { agent->consoleLog(devServerId, kind, data->toWTFString()); } diff --git a/src/jsc/bindings/InspectorTestReporterAgent.cpp b/src/jsc/bindings/InspectorTestReporterAgent.cpp index 8186f1520d7e..b91633943ebe 100644 --- a/src/jsc/bindings/InspectorTestReporterAgent.cpp +++ b/src/jsc/bindings/InspectorTestReporterAgent.cpp @@ -31,7 +31,7 @@ enum class BunTestType : uint8_t { Describe, }; -void Bun__TestReporterAgentReportTestFound(Inspector::InspectorTestReporterAgent* agent, JSC::CallFrame* callFrame, int testId, BunString* name, BunTestType item_type, int parentId) +void Bun__TestReporterAgentReportTestFound(Inspector::InspectorTestReporterAgent* agent, JSC::CallFrame* callFrame, int testId, const BunString* name, BunTestType item_type, int parentId) { auto str = name->toWTFString(BunString::ZeroCopy); @@ -50,7 +50,7 @@ void Bun__TestReporterAgentReportTestFound(Inspector::InspectorTestReporterAgent agent->reportTestFound(callFrame, testId, str, type, parentId); } -void Bun__TestReporterAgentReportTestFoundWithLocation(Inspector::InspectorTestReporterAgent* agent, int testId, BunString* name, BunTestType item_type, int parentId, BunString* sourceURL, int line) +void Bun__TestReporterAgentReportTestFoundWithLocation(Inspector::InspectorTestReporterAgent* agent, int testId, const BunString* name, BunTestType item_type, int parentId, const BunString* sourceURL, int line) { auto str = name->toWTFString(BunString::ZeroCopy); auto sourceURLStr = sourceURL->toWTFString(BunString::ZeroCopy); diff --git a/src/jsc/bindings/InternalModuleRegistry.cpp b/src/jsc/bindings/InternalModuleRegistry.cpp index f62c5ba050f9..3c050fdd8b49 100644 --- a/src/jsc/bindings/InternalModuleRegistry.cpp +++ b/src/jsc/bindings/InternalModuleRegistry.cpp @@ -15,16 +15,19 @@ #include "NativeModuleImpl.h" namespace Bun { -extern "C" bool BunTest__shouldGenerateCodeCoverage(BunString sourceURL); -extern "C" void ByteRangeMapping__generate(BunString sourceURL, BunString code, int sourceID); +extern "C" bool BunTest__shouldGenerateCodeCoverage(const BunString* sourceURL); +extern "C" void ByteRangeMapping__generate(const BunString* sourceURL, const BunString* code, int sourceID); static void maybeAddCodeCoverage(JSC::VM& vm, const JSC::SourceCode& code) { #if ASSERT_ENABLED bool isCodeCoverageEnabled = !!vm.controlFlowProfiler(); - bool shouldGenerateCodeCoverage = isCodeCoverageEnabled && BunTest__shouldGenerateCodeCoverage(Bun::toString(code.provider()->sourceURL())); + BunString sourceURL = Bun::toString(code.provider()->sourceURL()); + bool shouldGenerateCodeCoverage = isCodeCoverageEnabled && BunTest__shouldGenerateCodeCoverage(&sourceURL); if (shouldGenerateCodeCoverage) { - ByteRangeMapping__generate(Bun::toString(code.provider()->sourceURL()), Bun::toString(code.provider()->source().toStringWithoutCopying()), code.provider()->asID()); + WTF::String sourceString = code.provider()->source().toStringWithoutCopying(); + BunString source = Bun::toString(sourceString); + ByteRangeMapping__generate(&sourceURL, &source, code.provider()->asID()); } #endif } diff --git a/src/jsc/bindings/IsolatedModuleCache.cpp b/src/jsc/bindings/IsolatedModuleCache.cpp index a99c27b8dee5..c4ecfd5050ba 100644 --- a/src/jsc/bindings/IsolatedModuleCache.cpp +++ b/src/jsc/bindings/IsolatedModuleCache.cpp @@ -31,7 +31,7 @@ Zig::SourceProvider* IsolatedModuleCache::lookup(JSC::VM& vm, const WTF::String& void IsolatedModuleCache::insert(JSC::VM& vm, const WTF::String& key, Zig::SourceProvider& provider) { - if (!isTagCacheable(static_cast(provider.m_resolvedSource.tag))) + if (!isTagCacheable(static_cast(provider.m_tag))) return; auto result = WebCore::clientData(vm)->isolationSourceProviderCache.add(key, RefPtr(&provider)); ASSERT_WITH_MESSAGE(result.isNewEntry, "IsolatedModuleCache::insert for already-cached key — a lookup was bypassed"); diff --git a/src/jsc/bindings/IsolatedModuleCache.h b/src/jsc/bindings/IsolatedModuleCache.h index bfe618a84cd4..3f764e402cbe 100644 --- a/src/jsc/bindings/IsolatedModuleCache.h +++ b/src/jsc/bindings/IsolatedModuleCache.h @@ -19,7 +19,7 @@ namespace Bun { // Storage lives on JSVMClientData; this class is a stateless facade so the // gating, key, and tag-cacheability decisions live in exactly one place. The // map stores Zig::SourceProvider directly (not a wrapper struct) — everything -// callers need to branch on (sourceType(), m_resolvedSource.tag, module_info) +// callers need to branch on (sourceType(), m_tag, m_moduleInfo) // already lives on the provider. class IsolatedModuleCache { public: @@ -51,7 +51,7 @@ class IsolatedModuleCache { static Zig::SourceProvider* lookup(JSC::VM&, const WTF::String& key); - // Inserts only when isTagCacheable(provider.m_resolvedSource.tag); no-op + // Inserts only when isTagCacheable(provider.m_tag); no-op // otherwise. Asserts isNewEntry — a duplicate insert means a lookup was // bypassed, which is exactly the gating bug this consolidation prevents. static void insert(JSC::VM&, const WTF::String& key, Zig::SourceProvider&); diff --git a/src/jsc/bindings/JSCommonJSExtensions.cpp b/src/jsc/bindings/JSCommonJSExtensions.cpp index 951da1a479b6..08425f555189 100644 --- a/src/jsc/bindings/JSCommonJSExtensions.cpp +++ b/src/jsc/bindings/JSCommonJSExtensions.cpp @@ -261,8 +261,6 @@ JSC::EncodedJSValue builtinLoader(JSC::JSGlobalObject* globalObject, JSC::CallFr BunString empty = BunStringEmpty; JSC::VM& vm = globalObject->vm(); ErrorableResolvedSource res; - res.success = false; - memset(&res.result, 0, sizeof res.result); JSValue result = fetchCommonJSModuleNonBuiltin( global->bunVM(), diff --git a/src/jsc/bindings/JSCommonJSModule.cpp b/src/jsc/bindings/JSCommonJSModule.cpp index 4bd9e99dcde5..10982ccea9c9 100644 --- a/src/jsc/bindings/JSCommonJSModule.cpp +++ b/src/jsc/bindings/JSCommonJSModule.cpp @@ -546,7 +546,7 @@ JSC_DEFINE_CUSTOM_GETTER(getterPaths, (JSC::JSGlobalObject * globalObject, JSC:: auto filenameWtfStr = filename.toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, {}); BunString filenameStr = Bun::toString(filenameWtfStr); - JSValue paths = JSValue::decode(Resolver__nodeModulePathsJSValue(filenameStr, globalObject, true)); + JSValue paths = JSValue::decode(Resolver__nodeModulePathsJSValue(&filenameStr, globalObject, true)); RETURN_IF_EXCEPTION(scope, {}); thisObject->m_paths.set(globalObject->vm(), thisObject, paths); return JSValue::encode(paths); @@ -1373,14 +1373,11 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionRequireNativeModule, (JSGlobalObject * lexica WTF::String specifier = specifierValue.toWTFString(globalObject); RETURN_IF_EXCEPTION(throwScope, {}); ErrorableResolvedSource res; - res.success = false; - memset(&res.result, 0, sizeof res.result); BunString specifierStr = Bun::toString(specifier); auto result = fetchBuiltinModuleWithoutResolution(globalObject, &specifierStr, &res); RETURN_IF_EXCEPTION(throwScope, {}); - if (result) { - if (res.success) - return JSC::JSValue::encode(result); + if (result.kind == BuiltinModule::Kind::Exports) { + return JSC::JSValue::encode(result.exports); } throwScope.assertNoExceptionExceptTermination(); return throwVMError(globalObject, throwScope, "Failed to fetch builtin module"_s); @@ -1404,21 +1401,15 @@ void JSCommonJSModule::evaluate( auto& vm = JSC::getVM(globalObject); if (globalObject->hasOverriddenModuleWrapper) [[unlikely]] { - auto string = source.source_code.toWTFString(BunString::ZeroCopy); + auto string = source.source_code.transferToWTFString(); auto trimStart = string.find('\n'); if (trimStart != WTF::notFound) { - if (source.needsDeref && !isBuiltIn) { - source.needsDeref = false; - source.source_code.deref(); - } - auto wrapperStart = globalObject->m_moduleWrapperStart; - auto wrapperEnd = globalObject->m_moduleWrapperEnd; - source.source_code = Bun::toStringRef(makeString( - wrapperStart, + string = makeString( + globalObject->m_moduleWrapperStart, string.substring(trimStart, string.length() - trimStart - 4), - wrapperEnd)); - source.needsDeref = true; + globalObject->m_moduleWrapperEnd); } + source.source_code = Bun::toStringRef(string); } auto sourceProvider = Zig::SourceProvider::create(globalObject, source, JSC::SourceProviderSourceType::Program, isBuiltIn); @@ -1465,12 +1456,7 @@ void JSCommonJSModule::evaluateWithPotentiallyOverriddenCompile( throwTypeError(globalObject, scope, "overridden module._compile is not a function (called from overridden Module._extensions)"_s); return; } - WTF::String sourceString = source.source_code.toWTFString(BunString::ZeroCopy); - RETURN_IF_EXCEPTION(scope, ); - if (source.needsDeref) { - source.needsDeref = false; - source.source_code.deref(); - } + WTF::String sourceString = source.source_code.transferToWTFString(); // Remove the wrapper from the source string, since the transpiler has added it. auto trimStart = sourceString.find('\n'); WTF::String sourceStringWithoutWrapper; @@ -1534,9 +1520,8 @@ std::optional createCommonJSModule( if (globalObject->hasOverriddenModuleWrapper) [[unlikely]] { auto concat = makeString( globalObject->m_moduleWrapperStart, - source.source_code.toWTFString(BunString::ZeroCopy), + source.source_code.transferToWTFString(), globalObject->m_moduleWrapperEnd); - source.source_code.deref(); source.source_code = Bun::toStringRef(concat); } diff --git a/src/jsc/bindings/JSCommonJSModule.h b/src/jsc/bindings/JSCommonJSModule.h index fb8b70e52877..398057728060 100644 --- a/src/jsc/bindings/JSCommonJSModule.h +++ b/src/jsc/bindings/JSCommonJSModule.h @@ -110,11 +110,6 @@ class JSCommonJSModule final : public JSC::JSDestructibleObject { JSC::JSString* key, JSValue exportsObject, bool hasEvaluated, JSValue parent); - static JSCommonJSModule* create( - Zig::GlobalObject* globalObject, - const WTF::String& key, - ResolvedSource resolvedSource); - static JSObject* createBoundRequireFunction(VM& vm, JSGlobalObject* lexicalGlobalObject, const WTF::String& pathString); void toSyntheticSource(JSC::JSGlobalObject* globalObject, diff --git a/src/jsc/bindings/JSEnvironmentVariableMap.cpp b/src/jsc/bindings/JSEnvironmentVariableMap.cpp index 64883a535a53..15036a0ba300 100644 --- a/src/jsc/bindings/JSEnvironmentVariableMap.cpp +++ b/src/jsc/bindings/JSEnvironmentVariableMap.cpp @@ -39,7 +39,7 @@ extern "C" size_t Bun__getEnvCount(JSGlobalObject* globalObject, void** list_ptr extern "C" size_t Bun__getEnvKey(void* list, size_t index, unsigned char** out); extern "C" bool Bun__getEnvValue(JSGlobalObject* globalObject, const ZigString* name, ZigString* value); -extern "C" bool Bun__getEnvValueBunString(JSGlobalObject* globalObject, const BunString* name, BunString* value); +extern "C" BunString Bun__getEnvValueBunString(JSGlobalObject* globalObject, const BunString* name); extern "C" void Bun__setEnvValue(JSGlobalObject* globalObject, const BunString* name, const BunString* value); extern "C" bool Bun__Node__ProcessPendingDeprecation; @@ -243,8 +243,8 @@ JSC_DEFINE_CUSTOM_GETTER(jsGetterProxyEnvironmentVariable, (JSGlobalObject * glo return JSValue::encode(jsUndefined()); BunString name = Bun::toStringView(propertyName.publicName()); - BunString value = { BunStringTag::Dead }; - if (!Bun__getEnvValueBunString(globalObject, &name, &value)) { + BunString value = Bun__getEnvValueBunString(globalObject, &name); + if (value.tag == BunStringTag::Dead) { return JSValue::encode(jsUndefined()); } RELEASE_AND_RETURN(scope, JSValue::encode(jsString(vm, value.toWTFString()))); @@ -471,7 +471,7 @@ JSC_DEFINE_CUSTOM_SETTER(jsBunConfigVerboseFetchSetter, (JSGlobalObject * global } #if OS(WINDOWS) -extern "C" void Bun__Process__editWindowsEnvVar(BunString, BunString); +extern "C" void Bun__Process__editWindowsEnvVar(const BunString*, const BunString*); // Windows Proxy set/defineProperty write path: DEP0104 + ToString via coerceEnvValue, // plus the TZ side effect so it survives `delete process.env.TZ`. Returns the string. @@ -531,9 +531,13 @@ JSC_DEFINE_HOST_FUNCTION(jsEditWindowsEnvVar, (JSGlobalObject * global, JSC::Cal if (arg2.isCell()) { WTF::String string2 = arg2.toWTFString(global); RETURN_IF_EXCEPTION(scope, {}); - Bun__Process__editWindowsEnvVar(Bun::toString(string1), Bun::toString(string2)); + BunString k = Bun::toString(string1); + BunString v = Bun::toString(string2); + Bun__Process__editWindowsEnvVar(&k, &v); } else { - Bun__Process__editWindowsEnvVar(Bun::toString(string1), { .tag = BunStringTag::Dead }); + BunString k = Bun::toString(string1); + BunString v = { .tag = BunStringTag::Dead }; + Bun__Process__editWindowsEnvVar(&k, &v); } RELEASE_AND_RETURN(scope, JSValue::encode(jsUndefined())); } @@ -549,10 +553,9 @@ static ALWAYS_INLINE void syncWindowsEnv(SharedEnvStore* store, const String& ke #if OS(WINDOWS) if (!store || !store->isMainRooted()) return; - if (value) - Bun__Process__editWindowsEnvVar(Bun::toString(key), Bun::toString(*value)); - else - Bun__Process__editWindowsEnvVar(Bun::toString(key), { .tag = BunStringTag::Dead }); + BunString k = Bun::toString(key); + BunString v = value ? Bun::toString(*value) : BunString { .tag = BunStringTag::Dead }; + Bun__Process__editWindowsEnvVar(&k, &v); #else UNUSED_PARAM(store); UNUSED_PARAM(key); diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index 79c18a0526cf..fbc9f3f17d0e 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -48,25 +48,7 @@ using namespace JSC; using namespace Zig; using namespace WebCore; -class ResolvedSourceCodeHolder { -public: - ResolvedSourceCodeHolder(ErrorableResolvedSource* res_) - : res(res_) - { - } - - ~ResolvedSourceCodeHolder() - { - if (res->success && res->result.value.source_code.tag == BunStringTag::WTFStringImpl && res->result.value.needsDeref) { - res->result.value.needsDeref = false; - res->result.value.source_code.impl.wtf->deref(); - } - } - - ErrorableResolvedSource* res; -}; - -extern "C" BunLoaderType Bun__getDefaultLoader(JSC::JSGlobalObject*, BunString* specifier); +extern "C" BunLoaderType Bun__getDefaultLoader(JSC::JSGlobalObject*, const BunString* specifier); static JSC::JSPromise* rejectedInternalPromise(JSC::JSGlobalObject* globalObject, JSC::JSValue value) { @@ -362,7 +344,6 @@ static JSValue handleVirtualModuleResult( auto scope = DECLARE_THROW_SCOPE(vm); auto onLoadResult = handleOnLoadResult(globalObject, virtualModuleResult, specifier, wasModuleMock); RETURN_IF_EXCEPTION(scope, {}); - ResolvedSourceCodeHolder sourceCodeHolder(res); const auto reject = [&](JSC::JSValue exception) -> JSValue { if constexpr (allowPromise) { @@ -407,7 +388,7 @@ static JSValue handleVirtualModuleResult( case OnLoadResultTypeCode: { Bun__transpileVirtualModule(globalObject, specifier, referrer, &onLoadResult.value.sourceText.string, onLoadResult.value.sourceText.loader, res); if (!res->success) { - RELEASE_AND_RETURN(scope, reject(JSValue::decode(res->result.err.value))); + RELEASE_AND_RETURN(scope, reject(JSValue::decode(res->result.err))); } auto provider = Zig::SourceProvider::create(globalObject, res->result.value); @@ -479,16 +460,15 @@ extern "C" void Bun__onFulfillAsyncModule( Zig::GlobalObject* globalObject, JSC::EncodedJSValue encodedPromiseValue, ErrorableResolvedSource* res, - BunString* specifier, - BunString* referrer) + const BunString* specifier, + const BunString* referrer) { - ResolvedSourceCodeHolder sourceCodeHolder(res); auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); JSC::JSPromise* promise = uncheckedDowncast(JSC::JSValue::decode(encodedPromiseValue)); if (!res->success) { - RELEASE_AND_RETURN(scope, promise->reject(vm, JSValue::decode(res->result.err.value))); + RELEASE_AND_RETURN(scope, promise->reject(vm, JSValue::decode(res->result.err))); } auto* specifierValue = Bun::toJS(globalObject, *specifier); @@ -534,43 +514,40 @@ extern "C" void Bun__onFulfillAsyncModule( } } -JSValue fetchBuiltinModuleWithoutResolution( +BuiltinModule fetchBuiltinModuleWithoutResolution( Zig::GlobalObject* globalObject, - BunString* specifier, + const BunString* specifier, ErrorableResolvedSource* res) { + using Kind = BuiltinModule::Kind; void* bunVM = globalObject->bunVM(); auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); - BunString referrer = BunStringEmpty; - if (Bun__fetchBuiltinModule(bunVM, globalObject, specifier, &referrer, res)) { - if (!res->success) { - return {}; - } + if (Bun__fetchBuiltinModule(bunVM, globalObject, specifier, res)) { + ASSERT(res->success); auto tag = res->result.value.tag; switch (tag) { // require("bun") case SyntheticModuleType::BunObject: { - return globalObject->bunObject(); + return { Kind::Exports, globalObject->bunObject() }; } // require("module"), require("node:module") case SyntheticModuleType::NodeModule: { - return globalObject->m_nodeModuleConstructor.getInitializedOnMainThread(globalObject); + return { Kind::Exports, globalObject->m_nodeModuleConstructor.getInitializedOnMainThread(globalObject) }; } // require("process"), require("node:process") case SyntheticModuleType::NodeProcess: { - return globalObject->processObject(); + return { Kind::Exports, globalObject->processObject() }; } case SyntheticModuleType::ESM: { - res->success = false; - RELEASE_AND_RETURN(scope, jsNumber(-1)); + return { Kind::Source }; } // A text file embedded by `bun build --compile`: the string is `module.exports`. case SyntheticModuleType::ExportDefaultObject: { - return JSC::JSValue::decode(res->result.value.jsvalue_for_export); + return { Kind::Exports, JSC::JSValue::decode(res->result.value.jsvalue_for_export) }; } default: { @@ -578,11 +555,9 @@ JSValue fetchBuiltinModuleWithoutResolution( constexpr auto mask = (SyntheticModuleType::InternalModuleRegistryFlag - 1); auto result = globalObject->internalModuleRegistry()->requireId(globalObject, vm, static_cast(tag & mask)); RETURN_IF_EXCEPTION(scope, {}); - return result; - } else { - res->success = false; - RELEASE_AND_RETURN(scope, jsNumber(-1)); + return { Kind::Exports, result }; } + return { Kind::Source }; } } } @@ -591,15 +566,12 @@ JSValue fetchBuiltinModuleWithoutResolution( JSValue resolveAndFetchBuiltinModule( Zig::GlobalObject* globalObject, - BunString* specifier) + const BunString* specifier) { - void* bunVM = globalObject->bunVM(); auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); ErrorableResolvedSource res; - res.success = false; - memset(&res.result, 0, sizeof res.result); - if (Bun__resolveAndFetchBuiltinModule(bunVM, specifier, &res)) { + if (Bun__resolveAndFetchBuiltinModule(specifier, &res)) { ASSERT(res.success); auto tag = res.result.value.tag; @@ -673,11 +645,7 @@ JSValue fetchCommonJSModule( auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); ErrorableResolvedSource resValue; - resValue.success = false; - memset(&resValue.result, 0, sizeof resValue.result); - ErrorableResolvedSource* res = &resValue; - ResolvedSourceCodeHolder sourceCodeHolder(res); BunString specifier = Bun::toString(specifierWtfString); @@ -730,24 +698,28 @@ JSValue fetchCommonJSModule( auto builtin = fetchBuiltinModuleWithoutResolution(globalObject, &specifier, res); RETURN_IF_EXCEPTION(scope, {}); - if (builtin) { - if (!res->success) { - // A file embedded in a standalone executable is served by the builtin probe. - // A CommonJS one is evaluated right here like any require()d CJS file (the - // module loader path would find `target` already in the require map and - // never give it its source); only ES modules go through the loader. - if (res->result.value.isCommonJSModule) { - res->success = true; - target->evaluate(globalObject, specifierWtfString, res->result.value); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); - } - RELEASE_AND_RETURN(scope, builtin); + switch (builtin.kind) { + case BuiltinModule::Kind::Source: { + // A file embedded in a standalone executable is served by the builtin probe. + // A CommonJS one is evaluated right here like any require()d CJS file (the + // module loader path would find `target` already in the require map and + // never give it its source); only ES modules go through the loader, which + // fetches its own copy — this one is released with `res`. + if (res->result.value.isCommonJSModule) { + target->evaluate(globalObject, specifierWtfString, res->result.value); + RETURN_IF_EXCEPTION(scope, {}); + RELEASE_AND_RETURN(scope, target); } - target->setExportsObject(builtin); + RELEASE_AND_RETURN(scope, jsNumber(-1)); + } + case BuiltinModule::Kind::Exports: { + target->setExportsObject(builtin.exports); target->hasEvaluated = true; RELEASE_AND_RETURN(scope, target); } + case BuiltinModule::Kind::None: + break; + } // When "bun test" is NOT enabled, disable users from overriding builtin modules if (!isBunTest) { @@ -808,7 +780,7 @@ JSValue fetchCommonJSModule( // The wrapper override only affects CJS evaluation; if it's // active, fall through and re-transpile so the override can run. if (!globalObject->hasOverriddenModuleWrapper) { - target->evaluate(globalObject, Ref(*cached), cached->m_resolvedSource.tag == ResolvedSourceTagPackageJSONTypeModule); + target->evaluate(globalObject, Ref(*cached), cached->m_tag == ResolvedSourceTagPackageJSONTypeModule); RETURN_IF_EXCEPTION(scope, {}); RELEASE_AND_RETURN(scope, target); } @@ -964,7 +936,6 @@ static JSValue fetchESMSourceCode( void* bunVM = globalObject->bunVM(); auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); - ResolvedSourceCodeHolder sourceCodeHolder(res); const auto reject = [&](JSC::JSValue exception) -> JSValue { if constexpr (allowPromise) { @@ -1007,13 +978,8 @@ static JSValue fetchESMSourceCode( } } - if (Bun__fetchBuiltinModule(bunVM, globalObject, specifier, referrer, res)) { - if (!res->success) { - throwException(scope, res->result.err, globalObject); - auto* exception = scope.exception(); - (void)scope.tryClearException(); - RELEASE_AND_RETURN(scope, reject(exception)); - } + if (Bun__fetchBuiltinModule(bunVM, globalObject, specifier, res)) { + ASSERT(res->success); // This can happen if it's a `bun build --compile`'d CommonJS file if (res->result.value.isCommonJSModule) { @@ -1119,7 +1085,7 @@ static JSValue fetchESMSourceCode( // affects CJS evaluation, so don't serve a cached Program-type provider // when one is active in this global — fall through to re-transpile. if (!globalObject->hasOverriddenModuleWrapper) { - auto created = Bun::createCommonJSModule(globalObject, specifierJS, Ref(*cached), cached->m_resolvedSource.tag == ResolvedSourceTagPackageJSONTypeModule); + auto created = Bun::createCommonJSModule(globalObject, specifierJS, Ref(*cached), cached->m_tag == ResolvedSourceTagPackageJSONTypeModule); EXCEPTION_ASSERT(created.has_value() == !scope.exception()); if (created.has_value()) { RELEASE_AND_RETURN(scope, rejectOrResolve(JSSourceCode::create(vm, WTF::move(created.value())))); @@ -1281,8 +1247,6 @@ BUN_DEFINE_HOST_FUNCTION(jsFunctionOnLoadObjectResultResolve, (JSC::JSGlobalObje { auto& vm = JSC::getVM(globalObject); ErrorableResolvedSource res; - res.success = false; - memset(&res.result, 0, sizeof res.result); JSC::JSValue objectResult = callFrame->argument(0); PendingVirtualModuleResult* pendingModule = uncheckedDowncast(callFrame->argument(1)); JSC::JSValue specifierString = pendingModule->internalField(0).get(); @@ -1291,9 +1255,13 @@ BUN_DEFINE_HOST_FUNCTION(jsFunctionOnLoadObjectResultResolve, (JSC::JSGlobalObje pendingModule->internalField(1).set(vm, pendingModule, JSC::jsUndefined()); JSC::JSPromise* promise = pendingModule->internalPromise(); - BunString specifier = Bun::toString(globalObject, specifierString); - BunString referrer = Bun::toString(globalObject, referrerString); auto scope = DECLARE_THROW_SCOPE(vm); + WTF::String specifierWtf = specifierString.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); + WTF::String referrerWtf = referrerString.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); + BunString specifier = Bun::toString(specifierWtf); + BunString referrer = Bun::toString(referrerWtf); bool wasModuleMock = pendingModule->wasModuleMock; diff --git a/src/jsc/bindings/ModuleLoader.h b/src/jsc/bindings/ModuleLoader.h index 6076489f606b..3ed72ca6830e 100644 --- a/src/jsc/bindings/ModuleLoader.h +++ b/src/jsc/bindings/ModuleLoader.h @@ -117,11 +117,24 @@ JSValue fetchCommonJSModuleNonBuiltin( JSValue resolveAndFetchBuiltinModule( Zig::GlobalObject* globalObject, - BunString* specifier); + const BunString* specifier); + +struct BuiltinModule { + enum class Kind : uint8_t { + /// Not a builtin; `res` is untouched. + None, + /// `exports` is the module's exports value. + Exports, + /// `res` holds the module's source; the caller evaluates it. + Source, + }; + Kind kind = Kind::None; + JSValue exports {}; +}; -JSValue fetchBuiltinModuleWithoutResolution( +BuiltinModule fetchBuiltinModuleWithoutResolution( Zig::GlobalObject* globalObject, - BunString* specifier, + const BunString* specifier, ErrorableResolvedSource* res); } // namespace Bun diff --git a/src/jsc/bindings/NodeDirent.cpp b/src/jsc/bindings/NodeDirent.cpp index aa71e7db1d5a..9066d19d1dfe 100644 --- a/src/jsc/bindings/NodeDirent.cpp +++ b/src/jsc/bindings/NodeDirent.cpp @@ -327,40 +327,38 @@ extern "C" JSC::EncodedJSValue Bun__JSDirentObjectConstructor(Zig::GlobalObject* return JSValue::encode(globalobject->m_JSDirentClassStructure.constructor(globalobject)); } -extern "C" JSC::EncodedJSValue Bun__Dirent__toJS(Zig::GlobalObject* globalObject, int type, BunString* name, BunString* path, JSString** previousPath) +extern "C" JSC::EncodedJSValue Bun__Dirent__toJS(Zig::GlobalObject* globalObject, int type, BunString name, BunString path, JSString** previousPath) { auto& vm = globalObject->vm(); auto* structure = globalObject->m_JSDirentClassStructure.get(globalObject); auto* object = JSC::JSFinalObject::create(vm, structure); JSString* pathValue = nullptr; - if (path && path->tag == BunStringTag::WTFStringImpl && previousPath && *previousPath) { + if (path.tag == BunStringTag::WTFStringImpl && previousPath && *previousPath) { // The caller (readdir result toJS loop) already deduplicates the // underlying StringImpl per directory, so consecutive entries that - // share a parent path arrive here with the same `path->impl.wtf` + // share a parent path arrive here with the same `path.impl.wtf` // pointer that we adopted into `*previousPath` last call. Compare the // impl pointer directly instead of materializing a // GCOwnedDataScope via JSString::view(), whose // construction/destruction acquires a WTF::Lock and touches a // HashTable per call in debug builds. auto* prevImpl = (*previousPath)->tryGetValueImpl(); - if (prevImpl && (prevImpl == path->impl.wtf || WTF::equal(prevImpl, path->impl.wtf))) { + if (prevImpl && (prevImpl == path.impl.wtf || WTF::equal(prevImpl, path.impl.wtf))) { pathValue = *previousPath; - - // Decrement the ref count of the previous path - auto pathString = path->transferToWTFString(); + path.deref(); } } if (!pathValue) { - auto pathString = path->transferToWTFString(); + auto pathString = path.transferToWTFString(); pathValue = jsString(vm, WTF::move(pathString)); if (previousPath) { *previousPath = pathValue; } } - auto nameString = name->transferToWTFString(); + auto nameString = name.transferToWTFString(); auto nameValue = jsString(vm, WTF::move(nameString)); auto typeValue = jsNumber(type); object->putDirectOffset(vm, 0, nameValue); diff --git a/src/jsc/bindings/PathInlines.h b/src/jsc/bindings/PathInlines.h index dc39d5a58939..49abea253b3a 100644 --- a/src/jsc/bindings/PathInlines.h +++ b/src/jsc/bindings/PathInlines.h @@ -55,7 +55,7 @@ ALWAYS_INLINE bool isAbsolutePath(WTF::String input) #undef IS_LETTER #undef IS_SLASH -extern "C" BunString ResolvePath__joinAbsStringBufCurrentPlatformBunString(JSC::JSGlobalObject*, BunString); +extern "C" BunString ResolvePath__joinAbsStringBufCurrentPlatformBunString(JSC::JSGlobalObject*, const BunString*); /// CWD is determined by the global object's current cwd. ALWAYS_INLINE WTF::String pathResolveWTFString(JSC::JSGlobalObject* globalToGetCwdFrom, const WTF::String& input) @@ -63,6 +63,6 @@ ALWAYS_INLINE WTF::String pathResolveWTFString(JSC::JSGlobalObject* globalToGetC if (isAbsolutePath(input)) return input; BunString in = Bun::toString(input); - BunString out = ResolvePath__joinAbsStringBufCurrentPlatformBunString(globalToGetCwdFrom, in); + BunString out = ResolvePath__joinAbsStringBufCurrentPlatformBunString(globalToGetCwdFrom, &in); return out.transferToWTFString(); } diff --git a/src/jsc/bindings/RegularExpression.cpp b/src/jsc/bindings/RegularExpression.cpp index 1a4b03568917..ca602576c737 100644 --- a/src/jsc/bindings/RegularExpression.cpp +++ b/src/jsc/bindings/RegularExpression.cpp @@ -6,14 +6,14 @@ using namespace JSC; using namespace JSC::Yarr; -extern "C" RegularExpression* Yarr__RegularExpression__init(BunString pattern, uint16_t flags) +extern "C" RegularExpression* Yarr__RegularExpression__init(const BunString* pattern, uint16_t flags) { // TODO: Remove this, we technically are accessing options before we finalize them. // This means you cannot use BUN_JSC_dumpCompiledRegExpPatterns on the flag passed to `bun test -t` // NOLINTBEGIN Options::AllowUnfinalizedAccessScope scope {}; // NOLINTEND - return new RegularExpression(pattern.toWTFString(BunString::ZeroCopy), OptionSet(static_cast(flags))); + return new RegularExpression(pattern->toWTFString(BunString::ZeroCopy), OptionSet(static_cast(flags))); } extern "C" void Yarr__RegularExpression__deinit(RegularExpression* re) { @@ -27,15 +27,7 @@ extern "C" int Yarr__RegularExpression__matchedLength(RegularExpression* re) { return re->matchedLength(); } -extern "C" int Yarr__RegularExpression__searchRev(RegularExpression* re, BunString string) +extern "C" int Yarr__RegularExpression__matches(RegularExpression* re, const BunString* string) { - return re->searchRev(string.toWTFString(BunString::ZeroCopy)); -} -// extern "C" int Yarr__RegularExpression__match(RegularExpression* re, BunString string, int32_t start, int32_t* matchLength) -// { -// return re->match(string.toWTFString(BunString::ZeroCopy), start, matchLength); -// } -extern "C" int Yarr__RegularExpression__matches(RegularExpression* re, BunString string) -{ - return re->match(string.toWTFString(BunString::ZeroCopy), 0, 0); + return re->match(string->toWTFString(BunString::ZeroCopy), 0, 0); } diff --git a/src/jsc/bindings/StringBuilderBinding.cpp b/src/jsc/bindings/StringBuilderBinding.cpp index 4e397570bdb1..1d419eedba9c 100644 --- a/src/jsc/bindings/StringBuilderBinding.cpp +++ b/src/jsc/bindings/StringBuilderBinding.cpp @@ -40,9 +40,9 @@ extern "C" void StringBuilder__appendUsize(WTF::StringBuilder* builder, size_t n builder->append(num); } -extern "C" void StringBuilder__appendString(WTF::StringBuilder* builder, BunString str) +extern "C" void StringBuilder__appendString(WTF::StringBuilder* builder, const BunString* str) { - str.appendToBuilder(*builder); + str->appendToBuilder(*builder); } extern "C" void StringBuilder__appendLChar(WTF::StringBuilder* builder, Latin1Character c) @@ -55,9 +55,9 @@ extern "C" void StringBuilder__appendUChar(WTF::StringBuilder* builder, UChar c) builder->append(c); } -extern "C" void StringBuilder__appendQuotedJsonString(WTF::StringBuilder* builder, BunString str) +extern "C" void StringBuilder__appendQuotedJsonString(WTF::StringBuilder* builder, const BunString* str) { - auto string = str.toWTFString(BunString::ZeroCopy); + auto string = str->toWTFString(BunString::ZeroCopy); builder->appendQuotedJSONString(string); } diff --git a/src/jsc/bindings/ZigException.cpp b/src/jsc/bindings/ZigException.cpp index 460b343833af..cb13192c65cb 100644 --- a/src/jsc/bindings/ZigException.cpp +++ b/src/jsc/bindings/ZigException.cpp @@ -683,11 +683,6 @@ __attribute__((minsize)) static void fromErrorInstance(ZigException& except, JSC } { - for (int i = 1; i < except.stack.frames_len; i++) { - auto frame = except.stack.frames_ptr[i]; - frame.function_name.deref(); - frame.source_url.deref(); - } except.stack.frames_len = 1; PropertySlot slot = PropertySlot(obj, PropertySlot::InternalMethodType::VMInquiry, &vm); except.stack.frames_ptr[0].remapped = obj->getNonIndexPropertySlot(global, names.originalLinePublicName(), slot); diff --git a/src/jsc/bindings/ZigGlobalObject.cpp b/src/jsc/bindings/ZigGlobalObject.cpp index 2e516e1fb74e..63b7abb9fd65 100644 --- a/src/jsc/bindings/ZigGlobalObject.cpp +++ b/src/jsc/bindings/ZigGlobalObject.cpp @@ -3418,7 +3418,6 @@ JSC::Identifier GlobalObject::moduleLoaderResolve(JSGlobalObject* jsGlobalObject } ErrorableString res; - res.success = false; BunString keyZ = Bun::toString(keyString); BunString referrerZ = Bun::toString(referrerString); BunString queryZ = BunStringEmpty; @@ -3504,7 +3503,6 @@ JSC::JSPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* jsGlobalO } ErrorableString res; - res.success = false; BunString moduleNameZ = Bun::toString(moduleName); BunString sourceOriginZ = Bun::toString(sourceOriginStringHolder); BunString queryZ = BunStringEmpty; @@ -3589,10 +3587,6 @@ JSC::JSPromise* GlobalObject::moduleLoaderFetch(JSGlobalObject* globalObject, auto source = Bun::toString(sourceString); auto typeAttribute = Bun::toString(typeAttributeString); ErrorableResolvedSource res; - res.success = false; - // zero-initialize entire result union. zeroed BunString has BunStringTag::Dead, and zeroed - // EncodedJSValues are empty, which our code should be handling - memset(&res.result, 0, sizeof res.result); // require(esm) needs the entire dependency graph to load without yielding // to microtasks. The async fetch path goes through the transpiler thread @@ -3641,7 +3635,7 @@ JSC::JSObject* GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObje } extern "C" bool Bun__VM__entryEvaluationStarted(void*); -extern "C" void Bun__VM__entryRootKey(void*, BunString*); +extern "C" BunString Bun__VM__entryRootKey(void*); extern "C" void Bun__VM__noteEntryEvaluationStarted(void*); // A module body is about to run. That means "the entry's graph is linked and executing" only if it is @@ -3654,8 +3648,7 @@ static void noteModuleEvaluation(Zig::GlobalObject* globalObject, JSModuleLoader void* bunVM = globalObject->bunVM(); if (Bun__VM__entryEvaluationStarted(bunVM)) return; - BunString rootKey; - Bun__VM__entryRootKey(bunVM, &rootKey); + BunString rootKey = Bun__VM__entryRootKey(bunVM); auto* entry = moduleLoader->registryEntry(JSC::Identifier::fromString(globalObject->vm(), rootKey.toWTFString(BunString::ZeroCopy))); if (!entry) return; diff --git a/src/jsc/bindings/ZigSourceProvider.cpp b/src/jsc/bindings/ZigSourceProvider.cpp index 8729da46df75..47cba3805e29 100644 --- a/src/jsc/bindings/ZigSourceProvider.cpp +++ b/src/jsc/bindings/ZigSourceProvider.cpp @@ -41,13 +41,14 @@ SourceOrigin toSourceOrigin(const String& sourceURL, bool isBuiltin) } extern "C" int ByteRangeMapping__getSourceID(void* mappings); -extern "C" void* ByteRangeMapping__find(BunString sourceURL); +extern "C" void* ByteRangeMapping__find(const BunString* sourceURL); -extern "C" void ByteRangeMapping__generate(BunString sourceURL, BunString code, int sourceID); +extern "C" void ByteRangeMapping__generate(const BunString* sourceURL, const BunString* code, int sourceID); JSC::SourceID sourceIDForSourceURL(const WTF::String& sourceURL) { - void* mappings = ByteRangeMapping__find(Bun::toString(sourceURL)); + BunString sourceURLBunString = Bun::toString(sourceURL); + void* mappings = ByteRangeMapping__find(&sourceURLBunString); if (!mappings) { return 0; } @@ -55,9 +56,9 @@ JSC::SourceID sourceIDForSourceURL(const WTF::String& sourceURL) return ByteRangeMapping__getSourceID(mappings); } -extern "C" bool BunTest__shouldGenerateCodeCoverage(BunString sourceURL); -extern "C" void Bun__addSourceProviderSourceMap(void* bun_vm, SourceProvider* opaque_source_provider, BunString* specifier); -extern "C" void Bun__removeSourceProviderSourceMap(void* bun_vm, SourceProvider* opaque_source_provider, BunString* specifier); +extern "C" bool BunTest__shouldGenerateCodeCoverage(const BunString* sourceURL); +extern "C" void Bun__addSourceProviderSourceMap(void* bun_vm, SourceProvider* opaque_source_provider, const BunString* specifier); +extern "C" void Bun__removeSourceProviderSourceMap(void* bun_vm, SourceProvider* opaque_source_provider, const BunString* specifier); Ref SourceProvider::create( Zig::GlobalObject* globalObject, @@ -73,27 +74,22 @@ Ref SourceProvider::create( sourceType = JSC::SourceProviderSourceType::BunTranspiledModule; } - auto string = resolvedSource.source_code.toWTFString(BunString::ZeroCopy); - auto sourceURLString = resolvedSource.source_url.toWTFString(BunString::ZeroCopy); + auto string = resolvedSource.source_code.transferToWTFString(); + auto sourceURLString = resolvedSource.source_url.transferToWTFString(); bool isCodeCoverageEnabled = !!globalObject->vm().controlFlowProfiler(); - bool shouldGenerateCodeCoverage = isCodeCoverageEnabled && !isBuiltin && BunTest__shouldGenerateCodeCoverage(resolvedSource.source_url); - - if (resolvedSource.needsDeref && !isBuiltin) { - resolvedSource.needsDeref = false; - resolvedSource.source_code.deref(); - // Do not deref either source_url or specifier - // Specifier's lifetime is the JSValue, mostly - // source_url is owned by the string above - // https://github.com/oven-sh/bun/issues/9521 + bool shouldGenerateCodeCoverage = false; + if (isCodeCoverageEnabled && !isBuiltin) { + BunString sourceURLBunString = Bun::toString(sourceURLString); + shouldGenerateCodeCoverage = BunTest__shouldGenerateCodeCoverage(&sourceURLBunString); } // Compute source origin: use explicit bytecode_origin_path if provided, otherwise derive from source_url. // bytecode_origin_path is used for bytecode cache validation where the origin must match // exactly what was used at build time. const auto getSourceOrigin = [&]() -> SourceOrigin { - auto bytecodeOriginPath = resolvedSource.bytecode_origin_path.toWTFString(BunString::ZeroCopy); + auto bytecodeOriginPath = resolvedSource.bytecode_origin_path.transferToWTFString(); if (!bytecodeOriginPath.isNull() && !bytecodeOriginPath.isEmpty()) { // Convert file path to file:// URL (same as build time) return SourceOrigin(WTF::URL::fileURLWithFileSystemPath(bytecodeOriginPath)); @@ -102,28 +98,21 @@ Ref SourceProvider::create( }; const auto getProvider = [&]() -> Ref { + auto origin = getSourceOrigin(); if (resolvedSource.bytecode_cache != nullptr) { - const auto destructorPtr = [](const void* ptr) { - // `bytecode_cache` was `heap::into_raw`'d from a Rust `Box<[u8]>` - // (the global allocator); free with `defaultAllocatorFree` so - // it agrees with the `#[global_allocator]`. - Bun::defaultAllocatorFree(const_cast(ptr)); - }; - const auto destructorNoOp = [](const void* ptr) { - // no-op, for bun build --compile. + const auto destructorOwned = [](const void* ptr) { + ResolvedSource__freeBytecode(static_cast(const_cast(ptr))); }; - const auto destructor = resolvedSource.needsDeref ? destructorPtr : destructorNoOp; - - auto origin = getSourceOrigin(); - - Ref bytecode = JSC::CachedBytecode::create(std::span(resolvedSource.bytecode_cache, resolvedSource.bytecode_cache_size), destructor, {}); + // Borrowed from the standalone module graph / compile cache. + const auto destructorNoOp = [](const void*) {}; + Ref bytecode = JSC::CachedBytecode::create(std::span(std::exchange(resolvedSource.bytecode_cache, nullptr), resolvedSource.bytecode_cache_size), resolvedSource.bytecode_cache_owned ? destructorOwned : destructorNoOp, {}); auto provider = adoptRef(*new SourceProvider( globalObject->bunVM(), resolvedSource, - string.isNull() ? *StringImpl::empty() : *string.impl(), + string.isNull() ? Ref { *StringImpl::empty() } : Ref { *string.impl() }, JSC::SourceTaintedOrigin::Untainted, origin, - sourceURLString.impl(), TextPosition(), + WTF::move(sourceURLString), TextPosition(), sourceType)); provider->m_cachedBytecode = WTF::move(bytecode); return provider; @@ -132,21 +121,25 @@ Ref SourceProvider::create( return adoptRef(*new SourceProvider( globalObject->bunVM(), resolvedSource, - string.isNull() ? *StringImpl::empty() : *string.impl(), + string.isNull() ? Ref { *StringImpl::empty() } : Ref { *string.impl() }, JSC::SourceTaintedOrigin::Untainted, - getSourceOrigin(), - sourceURLString.impl(), TextPosition(), + origin, + WTF::move(sourceURLString), TextPosition(), sourceType)); }; auto provider = getProvider(); if (shouldGenerateCodeCoverage) { - ByteRangeMapping__generate(Bun::toString(provider->sourceURL()), Bun::toString(provider->source().toStringWithoutCopying()), provider->asID()); + BunString providerURL = Bun::toString(provider->sourceURL()); + WTF::String providerSourceString = provider->source().toStringWithoutCopying(); + BunString providerSource = Bun::toString(providerSourceString); + ByteRangeMapping__generate(&providerURL, &providerSource, provider->asID()); } - if (resolvedSource.already_bundled) { - Bun__addSourceProviderSourceMap(globalObject->bunVM(), provider.ptr(), &resolvedSource.source_url); + if (provider->m_alreadyBundled) { + BunString str = Bun::toString(provider->sourceURL()); + Bun__addSourceProviderSourceMap(globalObject->bunVM(), provider.ptr(), &str); } return provider; @@ -159,23 +152,13 @@ StringView SourceProvider::source() const SourceProvider::~SourceProvider() { - if (m_resolvedSource.already_bundled) { + if (m_alreadyBundled) { BunString str = Bun::toString(sourceURL()); Bun__removeSourceProviderSourceMap(m_bunVM, this, &str); } - if (m_resolvedSource.module_info != nullptr) { - zig__ModuleInfoDeserialized__deinit(static_cast(m_resolvedSource.module_info)); - m_resolvedSource.module_info = nullptr; + if (m_moduleInfo) { + zig__ModuleInfoDeserialized__deinit(m_moduleInfo); } - // The Rust side hands these as +1 (RuntimeTranspilerStore::run_from_js_thread: - // `out.dupeRef()` / `out.createIfDifferent(..)`; ModuleLoader paths likewise). - // #9521 removed the early deref in `create()` because these strings are still - // read after that point; the matching deref belongs here, once all uses are done. - // `source_code` is intentionally NOT deref'd here — its +1 is consumed in - // `create()` (gated on `needsDeref && !isBuiltin`) or by ResolvedSourceCodeHolder. - m_resolvedSource.specifier.deref(); - m_resolvedSource.source_url.deref(); - m_resolvedSource.bytecode_origin_path.deref(); } extern "C" void CachedBytecode__deref(JSC::CachedBytecode* cachedBytecode) @@ -196,7 +179,7 @@ static JSC::VM& getVMForBytecodeCache() return *vmForBytecodeCache; } -extern "C" bool generateCachedModuleByteCodeFromSourceCode(BunString* sourceProviderURL, const Latin1Character* inputSourceCode, size_t inputSourceCodeSize, const uint8_t** outputByteCode, size_t* outputByteCodeSize, JSC::CachedBytecode** cachedBytecodePtr) +extern "C" bool generateCachedModuleByteCodeFromSourceCode(const BunString* sourceProviderURL, const Latin1Character* inputSourceCode, size_t inputSourceCodeSize, const uint8_t** outputByteCode, size_t* outputByteCodeSize, JSC::CachedBytecode** cachedBytecodePtr) { std::span sourceCodeSpan(inputSourceCode, inputSourceCodeSize); JSC::SourceCode sourceCode = JSC::makeSource(WTF::String(sourceCodeSpan), toSourceOrigin(sourceProviderURL->toWTFString(), false), JSC::SourceTaintedOrigin::Untainted); @@ -231,7 +214,7 @@ extern "C" bool generateCachedModuleByteCodeFromSourceCode(BunString* sourceProv return true; } -extern "C" bool generateCachedCommonJSProgramByteCodeFromSourceCode(BunString* sourceProviderURL, const Latin1Character* inputSourceCode, size_t inputSourceCodeSize, const uint8_t** outputByteCode, size_t* outputByteCodeSize, JSC::CachedBytecode** cachedBytecodePtr) +extern "C" bool generateCachedCommonJSProgramByteCodeFromSourceCode(const BunString* sourceProviderURL, const Latin1Character* inputSourceCode, size_t inputSourceCodeSize, const uint8_t** outputByteCode, size_t* outputByteCodeSize, JSC::CachedBytecode** cachedBytecodePtr) { std::span sourceCodeSpan(inputSourceCode, inputSourceCodeSize); diff --git a/src/jsc/bindings/ZigSourceProvider.h b/src/jsc/bindings/ZigSourceProvider.h index 3513fbbe6140..42cc609ec966 100644 --- a/src/jsc/bindings/ZigSourceProvider.h +++ b/src/jsc/bindings/ZigSourceProvider.h @@ -16,6 +16,8 @@ class SourceProvider; #include #include +struct bun_ModuleInfoDeserialized; + namespace Zig { class GlobalObject; @@ -42,18 +44,24 @@ class SourceProvider final : public JSC::SourceProvider { return m_cachedBytecode.copyRef(); }; - ResolvedSource m_resolvedSource; + // Taken from the ResolvedSource at create(); freed in the destructor (or + // earlier by BunAnalyzeTranspiledModule once consumed). + bun_ModuleInfoDeserialized* m_moduleInfo { nullptr }; + uint32_t m_tag { 0 }; + bool m_alreadyBundled { false }; private: - SourceProvider(void* bunVM, ResolvedSource resolvedSource, Ref&& sourceImpl, + SourceProvider(void* bunVM, ResolvedSource& resolvedSource, Ref&& sourceImpl, JSC::SourceTaintedOrigin taintedness, const SourceOrigin& sourceOrigin, WTF::String&& sourceURL, const TextPosition& startPosition, JSC::SourceProviderSourceType sourceType) : Base(sourceOrigin, WTF::move(sourceURL), String(), taintedness, startPosition, sourceType) + , m_moduleInfo(std::exchange(resolvedSource.module_info, nullptr)) + , m_tag(resolvedSource.tag) + , m_alreadyBundled(resolvedSource.already_bundled) , m_bunVM(bunVM) - , m_source(sourceImpl) + , m_source(WTF::move(sourceImpl)) { - m_resolvedSource = resolvedSource; } // Stored directly (not via the creating global) so the destructor stays diff --git a/src/jsc/bindings/bindings.cpp b/src/jsc/bindings/bindings.cpp index 459d17d0d4bf..9ef19f859243 100644 --- a/src/jsc/bindings/bindings.cpp +++ b/src/jsc/bindings/bindings.cpp @@ -3333,15 +3333,16 @@ JSC::JSObject* JSC__JSCell__toObject(JSC::JSCell* cell, JSC::JSGlobalObject* glo #pragma mark - JSC::JSString -// Throws (and leaves *arg2 empty) when resolving a rope runs out of memory. -[[ZIG_EXPORT(check_slow)]] void JSC__JSString__toZigString(JSC::JSString* arg0, JSC::JSGlobalObject* arg1, ZigString* arg2) +// Throws (and returns empty) when resolving a rope runs out of memory. +// `JSString::view`: a substring rope is viewed in place; other ropes resolve +// (and can throw on OOM). The characters belong to `str` (or its base), which +// the caller keeps alive. +BunString JSC__JSString__view(JSC::JSString* str, JSC::JSGlobalObject* global) { - auto& vm = JSC::getVM(arg1); - auto scope = DECLARE_THROW_SCOPE(vm); - auto value = arg0->value(arg1); - RETURN_IF_EXCEPTION(scope, void()); - // ->value returns a reference to the same string as the one owned by the JSString. - *arg2 = Zig::toZigString(value.data.impl()); + auto scope = DECLARE_THROW_SCOPE(JSC::getVM(global)); + auto view = str->view(global); + RETURN_IF_EXCEPTION(scope, BunStringEmpty); + return Bun::toStringView(view.data); } bool JSC__JSString__is8Bit(const JSC::JSString* arg0) { return arg0->is8Bit(); }; @@ -3679,8 +3680,7 @@ CPP_DECL void JSC__JSValue__putIndex(JSC::EncodedJSValue JSValue0, JSC::JSGlobal { JSC::JSValue value = JSC::JSValue::decode(JSValue0); JSC::JSValue value2 = JSC::JSValue::decode(JSValue3); - JSC::JSArray* array = uncheckedDowncast(value); - array->putDirectIndex(arg1, arg2, value2); + asObject(value)->putDirectIndex(arg1, arg2, value2); } CPP_DECL void JSC__JSValue__push(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, JSC::EncodedJSValue JSValue3) @@ -3722,11 +3722,11 @@ JSC::EncodedJSValue JSC__JSGlobalObject__createAggregateError(JSC::JSGlobalObjec RELEASE_AND_RETURN(scope, JSC::JSValue::encode(JSC::createAggregateError(vm, errorStructure, array, message, cause, nullptr, JSC::TypeNothing, false))); } -JSC::EncodedJSValue JSC__JSGlobalObject__createAggregateErrorWithArray(JSC::JSGlobalObject* global, JSC::JSArray* array, BunString message, JSValue cause) +JSC::EncodedJSValue JSC__JSGlobalObject__createAggregateErrorWithArray(JSC::JSGlobalObject* global, JSC::JSArray* array, const BunString* message, JSValue cause) { auto& vm = JSC::getVM(global); JSC::Structure* errorStructure = global->errorStructure(JSC::ErrorType::AggregateError); - WTF::String messageString = message.toWTFString(); + WTF::String messageString = message->toWTFString(); return JSC::JSValue::encode(JSC::createAggregateError(vm, errorStructure, array, messageString, cause, nullptr, JSC::TypeNothing, false)); } @@ -3792,35 +3792,6 @@ JSC::EncodedJSValue ZigString__toValueGC(const ZigString* arg0, JSC::JSGlobalObj return JSC::JSValue::encode(JSC::jsString(arg1->vm(), Zig::toStringCopy(*arg0))); } -void JSC__JSValue__toZigString(JSC::EncodedJSValue JSValue0, ZigString* arg1, JSC::JSGlobalObject* arg2) -{ - JSC::JSValue value = JSC::JSValue::decode(JSValue0); - - // if (!value.isString()) { - // arg1->len = 0; - // arg1->ptr = nullptr; - // return; - // } - - auto* strValue = value.toStringOrNull(arg2); - - if (!strValue) [[unlikely]] { - arg1->len = 0; - arg1->ptr = nullptr; - return; - } - - auto str = strValue->value(arg2); - - if (str->is8Bit()) { - arg1->ptr = str->span8().data(); - } else { - arg1->ptr = Zig::taggedUTF16Ptr(str->span16().data()); - } - - arg1->len = str->length(); -} - JSC::EncodedJSValue ZigString__external(const ZigString* arg0, JSC::JSGlobalObject* arg1, void* arg2, void (*ArgFn3)(void* arg0, void* arg1, size_t arg2)) { ZigString str @@ -4861,29 +4832,26 @@ JSC::EncodedJSValue JSC__JSValue__getIfPropertyExistsFromPath(JSC::EncodedJSValu return {}; } -void JSC__JSValue__getSymbolDescription(JSC::EncodedJSValue symbolValue_, JSC::JSGlobalObject* arg1, ZigString* arg2) - +BunString JSC__JSValue__getSymbolDescription(JSC::EncodedJSValue symbolValue_, JSC::JSGlobalObject* arg1) { JSC::JSValue symbolValue = JSC::JSValue::decode(symbolValue_); if (!symbolValue.isSymbol()) - return; + return BunStringEmpty; JSC::Symbol* symbol = JSC::asSymbol(symbolValue); auto& uid = symbol->uid(); if (!uid.isNullSymbol() && !uid.isEmpty()) { - *arg2 = Zig::toZigString(static_cast(uid)); - } else { - *arg2 = ZigStringEmpty; + return Bun::toString(&static_cast(uid)); } + return BunStringEmpty; } -JSC::EncodedJSValue JSC__JSValue__symbolFor(JSC::JSGlobalObject* globalObject, ZigString* arg2) +JSC::EncodedJSValue JSC__JSValue__symbolFor(JSC::JSGlobalObject* globalObject, const BunString* key) { - auto& vm = JSC::getVM(globalObject); - WTF::String string = Zig::toString(*arg2); + WTF::String string = key->toWTFString(BunString::ZeroCopy); return JSC::JSValue::encode(JSC::Symbol::create(vm, vm.symbolRegistry().symbolForKey(string))); } @@ -4964,6 +4932,18 @@ JSC::JSObject* JSC__JSValue__toObject(JSC::EncodedJSValue JSValue0, JSC::JSGloba return value.toStringOrNull(arg1); } +/// `toStringOrNull` + `JSString::view` in one call. +JSC::JSString* JSC__JSValue__toJSStringView(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* global, BunString* view) +{ + auto scope = DECLARE_THROW_SCOPE(JSC::getVM(global)); + auto* str = JSC::JSValue::decode(JSValue0).toStringOrNull(global); + RETURN_IF_EXCEPTION(scope, nullptr); + auto data = str->view(global); + RETURN_IF_EXCEPTION(scope, nullptr); + *view = Bun::toStringView(data.data); + return str; +} + [[ZIG_EXPORT(check_slow)]] bool JSC__JSValue__toMatch(JSC::EncodedJSValue regexValue, JSC::JSGlobalObject* global, JSC::EncodedJSValue value) { ASSERT_NO_PENDING_EXCEPTION(global); @@ -5001,13 +4981,19 @@ void JSC__VM__releaseWeakRefs(JSC::VM* arg0) arg0->finalizeSynchronousJSExecution(); } -void JSC__JSValue__getClassName(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString* arg2) +static BunString toStringAdopt(WTF::String&& s) +{ + if (s.isEmpty()) + return BunStringEmpty; + return { BunStringTag::WTFStringImpl, { .wtf = s.releaseImpl().leakRef() } }; +} + +BunString JSC__JSValue__getClassName(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1) { JSValue value = JSValue::decode(JSValue0); JSC::JSCell* cell = value.asCell(); if (cell == nullptr || !cell->isObject()) { - arg2->len = 0; - return; + return BunStringEmpty; } const char* ptr = cell->className(); @@ -5015,19 +5001,18 @@ void JSC__JSValue__getClassName(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObjec // Fallback to .name if className is empty if (view.length() == 0 || StringView("Function"_s) == view) { - JSC__JSValue__getNameProperty(JSValue0, arg1, arg2); - return; + return JSC__JSValue__getNameProperty(JSValue0, arg1); } JSObject* obj = value.toObject(arg1); auto calculated = JSObject::calculatedClassName(obj); if (calculated.length() > 0) { - *arg2 = Zig::toZigString(calculated); - return; + return toStringAdopt(WTF::move(calculated)); } - *arg2 = Zig::toZigString(view); + // `className()` is a static C string. + return { BunStringTag::StaticZigString, { .zig = { reinterpret_cast(ptr), view.length() } } }; } bool JSC__JSValue__getClassInfoName(JSValue value, const uint8_t** outPtr, size_t* outLen) @@ -5040,25 +5025,23 @@ bool JSC__JSValue__getClassInfoName(JSValue value, const uint8_t** outPtr, size_ return false; } -void JSC__JSValue__getNameProperty(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString* arg2) +BunString JSC__JSValue__getNameProperty(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1) { JSC::JSObject* obj = JSC::JSValue::decode(JSValue0).getObject(); JSC::VM& vm = arg1->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (obj == nullptr) { - arg2->len = 0; - return; + return BunStringEmpty; } JSC::JSValue name = obj->getIfPropertyExists(arg1, vm.propertyNames->toStringTagSymbol); - RETURN_IF_EXCEPTION(scope, ); + RETURN_IF_EXCEPTION(scope, BunStringEmpty); if (name && name.isString()) { auto str = name.toWTFString(arg1); if (!str.isEmpty()) { - *arg2 = Zig::toZigString(str); - return; + return toStringAdopt(WTF::move(str)); } } @@ -5066,22 +5049,17 @@ void JSC__JSValue__getNameProperty(JSC::EncodedJSValue JSValue0, JSC::JSGlobalOb WTF::String actualName = function->name(vm); if (!actualName.isEmpty() || function->isHostOrBuiltinFunction()) { - *arg2 = Zig::toZigString(actualName); - return; + return toStringAdopt(WTF::move(actualName)); } - actualName = function->jsExecutable()->name().string(); - - *arg2 = Zig::toZigString(actualName); - return; + return Bun::toStringRef(function->jsExecutable()->name().string()); } if (JSC::InternalFunction* function = dynamicDowncast(obj)) { - *arg2 = Zig::toZigString(function->name()); - return; + return Bun::toStringRef(function->name()); } - arg2->len = 0; + return BunStringEmpty; } [[ZIG_EXPORT(check_slow)]] void JSC__JSValue__getName(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* globalObject, BunString* arg2) @@ -6180,7 +6158,7 @@ extern "C" JSC::EncodedJSValue JSC__JSValue__getOwnByValue(JSC::EncodedJSValue v } } -extern "C" [[ZIG_EXPORT(check_slow)]] double Bun__parseDate(JSC::JSGlobalObject* globalObject, BunString* str) +extern "C" [[ZIG_EXPORT(check_slow)]] double Bun__parseDate(JSC::JSGlobalObject* globalObject, const BunString* str) { auto& vm = JSC::getVM(globalObject); return vm.dateCache.parseDate(globalObject, vm, str->toWTFString()); @@ -6623,7 +6601,7 @@ extern "C" EncodedJSValue ExpectStatic__getPrototype(JSC::JSGlobalObject* global extern "C" EncodedJSValue JSFunction__createFromZig( JSC::JSGlobalObject* global, - BunString fn_name, + const BunString* fn_name, NativeFunction implementation, unsigned arg_count, ImplementationVisibility implementation_visibility, @@ -6631,7 +6609,7 @@ extern "C" EncodedJSValue JSFunction__createFromZig( NativeFunction constructorOrNull) { VM& vm = global->vm(); - auto name = fn_name.toWTFString(); + auto name = fn_name->toWTFString(); return JSValue::encode(JSFunction::create( vm, global, diff --git a/src/jsc/bindings/blob.cpp b/src/jsc/bindings/blob.cpp index 1bdbf7598ab6..798b867d345d 100644 --- a/src/jsc/bindings/blob.cpp +++ b/src/jsc/bindings/blob.cpp @@ -2,7 +2,7 @@ #include "ZigGeneratedClasses.h" extern "C" JSC::EncodedJSValue SYSV_ABI Blob__create(JSC::JSGlobalObject* globalObject, void* impl); -extern "C" void Blob__setAsFile(void* impl, BunString* filename); +extern "C" void Blob__setAsFile(void* impl, const BunString* filename); namespace WebCore { diff --git a/src/jsc/bindings/headers-handwritten.h b/src/jsc/bindings/headers-handwritten.h index 24a4642ffb4e..c7627508d487 100644 --- a/src/jsc/bindings/headers-handwritten.h +++ b/src/jsc/bindings/headers-handwritten.h @@ -9,7 +9,6 @@ #ifndef HEADERS_HANDWRITTEN #define HEADERS_HANDWRITTEN -typedef uint16_t ZigErrorCode; typedef struct VirtualMachine VirtualMachine; // exists to make headers.h happy typedef struct CppWebSocket CppWebSocket; @@ -96,54 +95,69 @@ typedef struct BunString { } BunString; -typedef struct ZigErrorType { - ZigErrorCode code; - JSC::EncodedJSValue value; -} ZigErrorType; -typedef union ErrorableZigStringResult { - ZigString value; - ZigErrorType err; -} ErrorableZigStringResult; -typedef struct ErrorableZigString { - ErrorableZigStringResult result; - bool success; -} ErrorableZigString; typedef union ErrorableStringResult { BunString value; - ZigErrorType err; + JSC::EncodedJSValue err; } ErrorableStringResult; typedef struct ErrorableString { - ErrorableStringResult result; - bool success; + ErrorableStringResult result {}; + bool success { false }; } ErrorableString; +static_assert(sizeof(ErrorableString) == 32 && alignof(ErrorableString) == 8, "ErrorableString layout is mirrored in src/jsc/Errorable.rs"); +struct bun_ModuleInfoDeserialized; +// Every BunString here is owned by whichever frame holds the struct (see +// ~ErrorableResolvedSource / Rust `Drop`). Consumers that keep a string take it +// with `transferToWTFString()`, which leaves the field empty. typedef struct ResolvedSource { - BunString specifier; BunString source_code; BunString source_url; bool isCommonJSModule; JSC::EncodedJSValue cjsCustomExtension; - void* allocator; JSC::EncodedJSValue jsvalue_for_export; uint32_t tag; - bool needsDeref; bool already_bundled; // -- Bytecode cache fields -- + // Owned (`ResolvedSource__freeBytecode`) iff `bytecode_cache_owned`; otherwise + // borrowed from the standalone module graph / compile cache. uint8_t* bytecode_cache; size_t bytecode_cache_size; - void* module_info; + bool bytecode_cache_owned; + // Owned; Zig::SourceProvider takes it (nulling the field). + bun_ModuleInfoDeserialized* module_info; // File path used as source origin for bytecode cache validation. // Converted to file:// URL. If empty, origin is derived from source_url. BunString bytecode_origin_path; } ResolvedSource; +static_assert(sizeof(ResolvedSource) == 136, "ResolvedSource layout is mirrored in src/jsc/ResolvedSource.rs"); inline constexpr uint32_t ResolvedSourceTagPackageJSONTypeModule = 1; typedef union ErrorableResolvedSourceResult { ResolvedSource value; - ZigErrorType err; + JSC::EncodedJSValue err; } ErrorableResolvedSourceResult; -typedef struct ErrorableResolvedSource { - ErrorableResolvedSourceResult result; - bool success; -} ErrorableResolvedSource; +extern "C" void zig__ModuleInfoDeserialized__deinit(bun_ModuleInfoDeserialized* info); +extern "C" void ResolvedSource__freeBytecode(uint8_t* bytecode); +struct ErrorableResolvedSource { + WTF_MAKE_NONCOPYABLE(ErrorableResolvedSource); + +public: + ErrorableResolvedSourceResult result {}; + bool success { false }; + + ErrorableResolvedSource() = default; + ~ErrorableResolvedSource() + { + if (!success) + return; + result.value.source_code.deref(); + result.value.source_url.deref(); + result.value.bytecode_origin_path.deref(); + if (result.value.bytecode_cache_owned && result.value.bytecode_cache) + ResolvedSource__freeBytecode(result.value.bytecode_cache); + if (result.value.module_info) + zig__ModuleInfoDeserialized__deinit(result.value.module_info); + } +}; +static_assert(sizeof(ErrorableResolvedSource) == 144 && alignof(ErrorableResolvedSource) == 8, "ErrorableResolvedSource layout is mirrored in src/jsc/Errorable.rs"); typedef struct SystemError { int errno_; @@ -311,8 +325,6 @@ extern "C" JSC::EncodedJSValue BunString__toJS(JSC::JSGlobalObject*, const BunSt namespace Bun { JSC::JSString* toJS(JSC::JSGlobalObject*, BunString); -BunString toString(JSC::JSGlobalObject* globalObject, JSC::JSValue value); -BunString toString(const char* bytes, size_t length); BunString toString(WTF::String& wtfString); BunString toString(const WTF::String& wtfString); BunString toString(WTF::StringImpl* wtfString); @@ -342,15 +354,13 @@ typedef struct { extern "C" const char* Bun__userAgent; -extern "C" ZigErrorCode Zig_ErrorCodeParserError; - extern "C" void ZigString__free(const unsigned char* ptr, size_t len, void* allocator); extern "C" bool Bun__transpileVirtualModule( JSC::JSGlobalObject* global, const BunString* specifier, const BunString* referrer, - ZigString* sourceCode, + const ZigString* sourceCode, BunLoaderType loader, ErrorableResolvedSource* result); @@ -361,8 +371,8 @@ extern "C" JSC::EncodedJSValue Bun__runVirtualModule( extern "C" JSC::JSPromise* Bun__transpileFile( void* bunVM, JSC::JSGlobalObject* global, - BunString* specifier, - BunString* referrer, + const BunString* specifier, + const BunString* referrer, const BunString* typeAttribute, ErrorableResolvedSource* result, bool allowPromise, @@ -373,10 +383,8 @@ extern "C" bool Bun__fetchBuiltinModule( void* bunVM, JSC::JSGlobalObject* global, const BunString* specifier, - const BunString* referrer, ErrorableResolvedSource* result); extern "C" bool Bun__resolveAndFetchBuiltinModule( - void* bunVM, const BunString* specifier, ErrorableResolvedSource* result); extern "C" bool Bun__VM__useIsolationSourceProviderCache(void* bunVM); diff --git a/src/jsc/bindings/headers.h b/src/jsc/bindings/headers.h index e8e5c209d607..8c58db44f1a5 100644 --- a/src/jsc/bindings/headers.h +++ b/src/jsc/bindings/headers.h @@ -109,7 +109,7 @@ CPP_DECL bool JSC__JSString__is8Bit(const JSC::JSString* arg0); CPP_DECL void JSC__JSString__iterator(JSC::JSString* arg0, JSC::JSGlobalObject* arg1, void* arg2); CPP_DECL size_t JSC__JSString__length(const JSC::JSString* arg0); CPP_DECL JSC::JSObject* JSC__JSString__toObject(JSC::JSString* arg0, JSC::JSGlobalObject* arg1); -CPP_DECL void JSC__JSString__toZigString(JSC::JSString* arg0, JSC::JSGlobalObject* arg1, ZigString* arg2); +CPP_DECL BunString JSC__JSString__view(JSC::JSString* arg0, JSC::JSGlobalObject* arg1); #pragma mark - JSC::JSModuleLoader @@ -228,12 +228,12 @@ CPP_DECL JSC::EncodedJSValue JSC__JSValue__fromUInt64NoTruncate(JSC::JSGlobalObj CPP_DECL JSC::EncodedJSValue JSC__JSValue__bigIntFromLatin1(JSC::JSGlobalObject* arg0, const uint8_t* arg1, size_t arg2); CPP_DECL JSC::EncodedJSValue JSC__JSValue__fromTimevalNoTruncate(JSC::JSGlobalObject* arg0, int64_t nsec, int64_t sec); CPP_DECL JSC::EncodedJSValue JSC__JSValue__bigIntSum(JSC::JSGlobalObject* arg0, JSC::EncodedJSValue JSValue0, JSC::EncodedJSValue JSValue1); -CPP_DECL void JSC__JSValue__getClassName(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString* arg2); +CPP_DECL BunString JSC__JSValue__getClassName(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); CPP_DECL JSC::EncodedJSValue JSC__JSValue__getIfPropertyExistsFromPath(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, JSC::EncodedJSValue JSValue2); CPP_DECL double JSC__JSValue__getLengthIfPropertyExistsInternal(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); -CPP_DECL void JSC__JSValue__getNameProperty(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString* arg2); +CPP_DECL BunString JSC__JSValue__getNameProperty(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); CPP_DECL JSC::EncodedJSValue JSC__JSValue__getPrototype(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); -CPP_DECL void JSC__JSValue__getSymbolDescription(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString* arg2); +CPP_DECL BunString JSC__JSValue__getSymbolDescription(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); CPP_DECL double JSC__JSValue__getUnixTimestamp(JSC::EncodedJSValue JSValue0); CPP_DECL bool JSC__JSValue__hasOwnProperty(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString arg2); CPP_DECL bool JSC__JSValue__isAggregateError(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); @@ -280,7 +280,7 @@ CPP_DECL void JSC__JSValue__putIndex(JSC::EncodedJSValue JSValue0, JSC::JSGlobal CPP_DECL void JSC__JSValue__putRecord(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString* arg2, ZigString* arg3, size_t arg4); CPP_DECL bool JSC__JSValue__strictDeepEquals(JSC::EncodedJSValue JSValue0, JSC::EncodedJSValue JSValue1, JSC::JSGlobalObject* arg2); CPP_DECL bool JSC__JSValue__stringIncludes(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, JSC::EncodedJSValue JSValue2); -CPP_DECL JSC::EncodedJSValue JSC__JSValue__symbolFor(JSC::JSGlobalObject* arg0, ZigString* arg1); +CPP_DECL JSC::EncodedJSValue JSC__JSValue__symbolFor(JSC::JSGlobalObject* arg0, const BunString* arg1); CPP_DECL bool JSC__JSValue__symbolKeyFor(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigString* arg2); CPP_DECL bool JSC__JSValue__toBoolean(JSC::EncodedJSValue JSValue0); CPP_DECL JSC::EncodedJSValue JSC__JSValue__toError_(JSC::EncodedJSValue JSValue0); @@ -290,9 +290,9 @@ CPP_DECL bool JSC__JSValue__toMatch(JSC::EncodedJSValue JSValue0, JSC::JSGlobalO CPP_DECL JSC::JSObject* JSC__JSValue__toObject(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); CPP_DECL JSC::JSString* JSC__JSValue__toString(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); CPP_DECL JSC::JSString* JSC__JSValue__toStringOrNull(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1); +CPP_DECL JSC::JSString* JSC__JSValue__toJSStringView(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* global, BunString* view); CPP_DECL uint64_t JSC__JSValue__toUInt64NoTruncate(JSC::EncodedJSValue JSValue0); CPP_DECL void JSC__JSValue__toZigException(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1, ZigException* arg2); -CPP_DECL void JSC__JSValue__toZigString(JSC::EncodedJSValue JSValue0, ZigString* arg1, JSC::JSGlobalObject* arg2); #pragma mark - JSC::VM @@ -432,7 +432,7 @@ ZIG_DECL void Zig__GlobalObject__fetch(ErrorableResolvedSource* arg0, JSC::JSGlo ZIG_DECL void Zig__GlobalObject__onCrash(); ZIG_DECL JSC::EncodedJSValue Zig__GlobalObject__promiseRejectionTracker(JSC::JSGlobalObject* arg0, JSC::JSPromise* arg1, uint32_t JSPromiseRejectionOperation2); ZIG_DECL JSC::EncodedJSValue Zig__GlobalObject__reportUncaughtException(JSC::JSGlobalObject* arg0, JSC::Exception* arg1); -ZIG_DECL void Zig__GlobalObject__resolve(ErrorableString* arg0, JSC::JSGlobalObject* arg1, BunString* arg2, BunString* arg3, BunString* arg4); +ZIG_DECL void Zig__GlobalObject__resolve(ErrorableString* arg0, JSC::JSGlobalObject* arg1, const BunString* arg2, const BunString* arg3, BunString* arg4); #endif @@ -665,8 +665,8 @@ ZIG_DECL JSC::EncodedJSValue Bun__Process__getCwd(JSC::JSGlobalObject* arg0); ZIG_DECL JSC::EncodedJSValue Bun__Process__createExecArgv(JSC::JSGlobalObject* arg0); ZIG_DECL JSC::EncodedJSValue Bun__Process__getExecPath(JSC::JSGlobalObject* arg0); ZIG_DECL bool Bun__Process__hasTitle(); -ZIG_DECL void Bun__Process__getTitle(JSC::JSGlobalObject* arg0, BunString* arg1); -ZIG_DECL void Bun__Process__setTitle(JSC::JSGlobalObject* arg0, BunString* arg1); +ZIG_DECL BunString Bun__Process__getTitle(JSC::JSGlobalObject* arg0); +ZIG_DECL void Bun__Process__setTitle(JSC::JSGlobalObject* arg0, const BunString* arg1); ZIG_DECL JSC::EncodedJSValue Bun__Process__setCwd(JSC::JSGlobalObject* arg0, ZigString* arg1); ZIG_DECL JSC::EncodedJSValue Bun__Process__getEval(JSC::JSGlobalObject* arg0); diff --git a/src/jsc/bindings/helpers.h b/src/jsc/bindings/helpers.h index cb0c176dd168..47185073091a 100644 --- a/src/jsc/bindings/helpers.h +++ b/src/jsc/bindings/helpers.h @@ -318,15 +318,6 @@ static ZigString toZigString(const WTF::StringView& str) str.length() }; } -static ZigString toZigString(JSC::JSString& str, JSC::JSGlobalObject* global) -{ - if (str.isSubstring()) { - return toZigString(str.view(global)); - } - - return toZigString(str.value(global)); -} - static ZigString toZigString(JSC::JSString* str, JSC::JSGlobalObject* global) { if (str->isSubstring()) { @@ -335,31 +326,10 @@ static ZigString toZigString(JSC::JSString* str, JSC::JSGlobalObject* global) return toZigString(str->value(global)); } -static void throwException(JSC::ThrowScope& scope, ZigErrorType err, JSC::JSGlobalObject* global) +static void throwException(JSC::ThrowScope& scope, JSC::EncodedJSValue err, JSC::JSGlobalObject* global) { scope.throwException(global, - JSC::Exception::create(global->vm(), JSC::JSValue::decode(err.value))); -} - -static ZigString toZigString(JSC::JSValue val, JSC::JSGlobalObject* global) -{ - auto scope = DECLARE_THROW_SCOPE(global->vm()); - auto* str = val.toString(global); - - if (scope.exception()) [[unlikely]] { - (void)scope.tryClearException(); - scope.release(); - return ZigStringEmpty; - } - - auto view = str->view(global); - if (scope.exception()) [[unlikely]] { - (void)scope.tryClearException(); - scope.release(); - return ZigStringEmpty; - } - - return toZigString(view); + JSC::Exception::create(global->vm(), JSC::JSValue::decode(err))); } static const WTF::String toStringStatic(ZigString str) diff --git a/src/jsc/bindings/webcore/WebSocket.cpp b/src/jsc/bindings/webcore/WebSocket.cpp index e03df9f27f7b..e1d312153563 100644 --- a/src/jsc/bindings/webcore/WebSocket.cpp +++ b/src/jsc/bindings/webcore/WebSocket.cpp @@ -1724,9 +1724,9 @@ extern "C" void WebSocket__didAbruptClose(WebCore::WebSocket* webSocket, Bun::We { webSocket->didFailWithErrorCode(errorCode); } -extern "C" void WebSocket__didClose(WebCore::WebSocket* webSocket, uint16_t errorCode, BunString* reason) +extern "C" void WebSocket__didClose(WebCore::WebSocket* webSocket, uint16_t errorCode, BunString reason) { - WTF::String wtf_reason = reason->transferToWTFString(); + WTF::String wtf_reason = reason.transferToWTFString(); // The Rust client only calls this after a completed close handshake // (received Close → echoed Close, or sent Close on ws.close()). For a // server-initiated close m_state is still OPEN here; transition to @@ -1829,7 +1829,7 @@ void WebCore::WebSocket::setProtocol(const String& protocol) m_subprotocol = protocol; } -extern "C" void WebSocket__setProtocol(WebCore::WebSocket* webSocket, BunString* protocol) +extern "C" void WebSocket__setProtocol(WebCore::WebSocket* webSocket, BunString protocol) { - webSocket->setProtocol(protocol->transferToWTFString()); + webSocket->setProtocol(protocol.transferToWTFString()); } diff --git a/src/jsc/bindings/webcore/Worker.cpp b/src/jsc/bindings/webcore/Worker.cpp index 901b64f3f825..4f8174b8354e 100644 --- a/src/jsc/bindings/webcore/Worker.cpp +++ b/src/jsc/bindings/webcore/Worker.cpp @@ -188,10 +188,10 @@ extern "C" void WebWorker__parentContextWillDestroy(WorkerMessagingProxy* proxy) // An uncaught error inside the worker: dispatch 'error' on the worker's own global scope, then report // it to the Worker object. -extern "C" void WebWorker__dispatchError(Zig::GlobalObject* globalObject, WorkerMessagingProxy* proxy, BunString* message, JSC::EncodedJSValue errorValue) +extern "C" void WebWorker__dispatchError(Zig::GlobalObject* globalObject, WorkerMessagingProxy* proxy, BunString message, JSC::EncodedJSValue errorValue) { JSC::JSValue error = JSC::JSValue::decode(errorValue); - String messageStr = message->transferToWTFString(); + String messageStr = message.transferToWTFString(); ErrorEvent::Init init; init.message = messageStr; init.error = error; diff --git a/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp b/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp index 4559dee43877..98c2db8b5f53 100644 --- a/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp +++ b/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp @@ -53,8 +53,8 @@ extern "C" { void* WebWorker__create( WorkerMessagingProxy*, void* parentVM, - BunString name, - BunString url, + const BunString* name, + const BunString* url, BunString* errorMessage, uint32_t parentContextId, uint32_t contextId, @@ -143,11 +143,13 @@ ExceptionOr WorkerMessagingProxy::startWorkerGlobalScope(const String& scr // The thread holds a ref on the proxy until releaseWorkerThread(). ref(); BunString errorMessage = BunStringEmpty; + BunString name = Bun::toString(m_options.name); + BunString url = Bun::toString(scriptURL); m_workerThread = WebWorker__create( this, WebCore::clientData(m_scriptExecutionContext->vm())->bunVM, - Bun::toString(m_options.name), - Bun::toString(scriptURL), + &name, + &url, &errorMessage, m_loaderContextIdentifier, m_workerContextIdentifier, @@ -167,7 +169,7 @@ ExceptionOr WorkerMessagingProxy::startWorkerGlobalScope(const String& scr if (!m_workerThread) { m_state.store(State::Closed); deref(); - return Exception { TypeError, errorMessage.toWTFString(BunString::ZeroCopy) }; + return Exception { TypeError, errorMessage.transferToWTFString() }; } return {}; } diff --git a/src/jsc/bun_string_jsc.rs b/src/jsc/bun_string_jsc.rs index 7edd84e60e58..2cc22a65ddf9 100644 --- a/src/jsc/bun_string_jsc.rs +++ b/src/jsc/bun_string_jsc.rs @@ -18,7 +18,7 @@ use crate::{CallFrame, JSGlobalObject, JSValue, JsError, JsResult, ZigStringJsc // `Bun__parseDate`) are NOT redeclared here — route through `crate::cpp::*`, // which owns the canonical extern decl + per-mode exception scope. unsafe extern "C" { - safe fn BunString__toJSDOMURL(global_object: &JSGlobalObject, in_: &mut String) -> JSValue; + safe fn BunString__toJSDOMURL(global_object: &JSGlobalObject, in_: &String) -> JSValue; fn BunString__createArray( global_object: &JSGlobalObject, ptr: *const String, @@ -30,29 +30,25 @@ unsafe extern "C" { } // ── bun.String methods ────────────────────────────────────────────────────── +/// Consume `this`: the +1 moves into the resulting `JSString` (no ref/deref +/// pair). Borrowed (`ZigString`) contents are copied. #[track_caller] -pub fn transfer_to_js(this: &mut String, global_this: &JSGlobalObject) -> JsResult { - // SAFETY: `this` is a live `&mut String`; the cppbind wrapper opens its own - // validation scope and converts `.zero` to `Err(JsError::Thrown)`. - unsafe { crate::cpp::BunString__transferToJS(this, global_this) } +pub(crate) fn into_js(mut this: String, global_this: &JSGlobalObject) -> JsResult { + // SAFETY: C++ moves the ref out of `this` (leaving it Dead) and the cppbind + // wrapper opens its own validation scope. + unsafe { crate::cpp::BunString__transferToJS(&raw mut this, global_this) } } pub fn to_error_instance(this: &String, global_object: &JSGlobalObject) -> JSValue { - let result = JSC__createError(global_object, this); - this.deref(); - result + JSC__createError(global_object, this) } pub(crate) fn to_type_error_instance(this: &String, global_object: &JSGlobalObject) -> JSValue { - let result = JSC__createTypeError(global_object, this); - this.deref(); - result + JSC__createTypeError(global_object, this) } pub(crate) fn to_range_error_instance(this: &String, global_object: &JSGlobalObject) -> JSValue { - let result = JSC__createRangeError(global_object, this); - this.deref(); - result + JSC__createRangeError(global_object, this) } #[inline] @@ -89,7 +85,7 @@ pub fn to_js(this: &String, global_object: &JSGlobalObject) -> JsResult /// `BunString__toJSDOMURL` opens a `DECLARE_THROW_SCOPE` and throws (returning /// encoded `0`) when the string is not a valid URL, so wrap it in a validation -/// scope exactly like `to_js`/`transfer_to_js` above. Without this, under +/// scope exactly like `to_js`/`into_js` above. Without this, under /// `BUN_JSC_validateExceptionChecks=1` the C++ ThrowScope's destructor /// `simulateThrow()` leaves `m_needExceptionCheck` set and the caller's /// `to_js_host_call` scope dtor asserts "unchecked exception". @@ -97,7 +93,7 @@ pub fn to_js(this: &String, global_object: &JSGlobalObject) -> JsResult /// Routing the FFI through `from_js_host_call` observes the exception at the /// call site and surfaces it as `Err(JsError::Thrown)`. #[track_caller] -pub fn to_jsdomurl(this: &mut String, global_object: &JSGlobalObject) -> JsResult { +pub fn to_jsdomurl(this: &String, global_object: &JSGlobalObject) -> JsResult { crate::from_js_host_call(global_object, || BunString__toJSDOMURL(global_object, this)) } @@ -111,11 +107,8 @@ pub fn to_js_array(global_object: &JSGlobalObject, array: &[String]) -> JsResult } #[track_caller] -pub fn to_js_by_parse_json( - self_: &mut String, - global_object: &JSGlobalObject, -) -> JsResult { - // SAFETY: `self_` is a live `&mut String`. +pub fn to_js_by_parse_json(self_: &String, global_object: &JSGlobalObject) -> JsResult { + // SAFETY: `self_` is a live `&String`. unsafe { crate::cpp::BunString__toJSON(global_object, self_) } } @@ -132,8 +125,8 @@ pub fn create_utf8_for_js(global_object: &JSGlobalObject, utf8_slice: &[u8]) -> } #[track_caller] -pub fn parse_date(this: &mut String, global_object: &JSGlobalObject) -> JsResult { - // SAFETY: `this` is a live `&mut String`; cppbind wrapper opens its own scope. +pub fn parse_date(this: &String, global_object: &JSGlobalObject) -> JsResult { + // SAFETY: `this` is a live `&String`; cppbind wrapper opens its own scope. unsafe { crate::cpp::Bun__parseDate(global_object, this) } } @@ -145,11 +138,11 @@ pub(crate) fn slice_with_underlying_string_to_js( slice_with_underlying_string_to_js_with_options(this, global_object, false) } -pub(crate) fn slice_with_underlying_string_transfer_to_js( - this: &mut SliceWithUnderlyingString, +pub(crate) fn slice_with_underlying_string_into_js( + mut this: SliceWithUnderlyingString, global_object: &JSGlobalObject, ) -> JsResult { - slice_with_underlying_string_to_js_with_options(this, global_object, true) + slice_with_underlying_string_to_js_with_options(&mut this, global_object, true) } fn slice_with_underlying_string_to_js_with_options( @@ -208,7 +201,7 @@ fn slice_with_underlying_string_to_js_with_options( if transfer { this.utf8 = ZigStringSlice::default(); - transfer_to_js(&mut this.underlying, global_object) + into_js(core::mem::take(&mut this.underlying), global_object) } else { to_js(&this.underlying, global_object) } @@ -232,10 +225,7 @@ pub fn js_escape_reg_exp(global: &JSGlobalObject, call_frame: &CallFrame) -> JsR return Err(JsError::OutOfMemory); } - let output = String::clone_utf8(&buf); - let js = to_js(&output, global); - output.deref(); - js + create_utf8_for_js(global, &buf) } #[bun_jsc::host_fn] @@ -260,10 +250,7 @@ pub fn js_escape_reg_exp_for_package_name_matching( return Err(JsError::OutOfMemory); } - let output = String::clone_utf8(&buf); - let js = to_js(&output, global); - output.deref(); - js + create_utf8_for_js(global, &buf) } // ── unicode TestingAPIs ───────────────────────────────────────────────────── @@ -303,9 +290,9 @@ pub mod unicode_testing_apis { // NUL **in** `result.len()`, so slice it off before handing to JSC. debug_assert_eq!(result.last().copied(), Some(0)); - let out = String::clone_utf16(&result[..result.len() - 1]); - let js = to_js(&out, global_this); - out.deref(); - js + into_js( + String::clone_utf16(&result[..result.len() - 1]), + global_this, + ) } } diff --git a/src/jsc/comptime_string_map_jsc.rs b/src/jsc/comptime_string_map_jsc.rs index 84757935f431..691d081add44 100644 --- a/src/jsc/comptime_string_map_jsc.rs +++ b/src/jsc/comptime_string_map_jsc.rs @@ -3,7 +3,7 @@ //! here. use crate::{JSGlobalObject, JSValue, JsResult}; -use bun_core::{OwnedString, String as BunString, Tag}; +use bun_core::{String as BunString, Tag}; // `from_js` on `bun_core::String` is provided by the `StringJsc` extension // trait, which is allowed here because this file lives in `src/jsc/`. use crate::StringJsc as _; @@ -19,8 +19,7 @@ where M: bun_core::comptime_string_map::ComptimeStringMap, M::Value: Copy, { - // `defer str.deref()` — `OwnedString` releases the +1 ref on Drop. - let str = OwnedString::new(BunString::from_js(input, global_this)?); + let str = BunString::from_js(input, global_this)?; debug_assert!(str.tag() != Tag::Dead); // Map keys are `&[u8]`, so materialize UTF-8 bytes and do a direct // lookup. diff --git a/src/jsc/generated.rs b/src/jsc/generated.rs index b4d7232ca584..b437437eb2f9 100644 --- a/src/jsc/generated.rs +++ b/src/jsc/generated.rs @@ -41,10 +41,17 @@ use crate::{JSCArrayBuffer, JSGlobalObject, JSValue, JsResult}; #[derive(Debug, Default)] pub struct GenOpt(Option); -impl GenOpt { +impl GenOpt { #[inline] - pub fn get(&self) -> Option { - self.0.clone() + pub fn get(&self) -> Option + where + T: Copy, + { + self.0 + } + #[inline] + pub fn as_ref(&self) -> Option<&T> { + self.0.as_ref() } } @@ -52,10 +59,17 @@ impl GenOpt { #[derive(Debug)] pub struct GenVal(T); -impl GenVal { +impl GenVal { + #[inline] + pub fn get(&self) -> T + where + T: Copy, + { + self.0 + } #[inline] - pub fn get(&self) -> T { - self.0.clone() + pub fn as_ref(&self) -> &T { + &self.0 } } @@ -320,31 +334,11 @@ pub struct SSLConfig { // ── refcount release on drop ────────────────────────────────────────────── // // `adopt_string` adopts a +1 `WTF::StringImpl` ref into a `GenString` -// (= `bun_core::String`), which is `Copy` and has no `Drop`. So the -// container's `Drop` deref's every owned string field to release those refs. +// (= `bun_core::String`), which releases it on drop. // -// `GenArrayBuffer` / `GenBlob` raw-pointer payloads likewise carry an adopted -// +1 ref (C++ `ExternTraits>::convertToExtern` calls `leakRef()`); +// `GenArrayBuffer` / `GenBlob` raw-pointer payloads carry an adopted +1 ref +// (C++ `ExternTraits>::convertToExtern` calls `leakRef()`); // released here via the matching `ExternalSharedDescriptor::ext_deref`. -// -// `.get()` on `GenOpt` / `GenVal` returns a *bitwise* `Clone` of the -// `bun_core::String` (the derived `Clone`, not the inherent `clone()` which -// bumps), so it does not take an additional ref — the single adopted ref stays -// owned by the field and is released exactly once below. - -#[inline] -fn release_gen_opt_string(s: &GenOpt) { - if let Some(string) = &s.0 { - // Releases the +1 ref adopted by `adopt_opt_string` / `adopt_string`. - string.deref(); - } -} - -#[inline] -fn release_gen_val_string(s: &GenVal) { - // Releases the +1 ref adopted by `adopt_string`. - s.0.deref(); -} #[inline] fn release_gen_val_array_buffer(b: &GenVal) { @@ -371,8 +365,7 @@ fn release_gen_val_blob(b: &GenVal) { impl Drop for SSLConfigAlpnProtocols { fn drop(&mut self) { match self { - SSLConfigAlpnProtocols::None => {} - SSLConfigAlpnProtocols::String(v) => release_gen_val_string(v), + SSLConfigAlpnProtocols::None | SSLConfigAlpnProtocols::String(_) => {} SSLConfigAlpnProtocols::Buffer(v) => release_gen_val_array_buffer(v), } } @@ -381,7 +374,7 @@ impl Drop for SSLConfigAlpnProtocols { impl Drop for SSLConfigSingleFile { fn drop(&mut self) { match self { - SSLConfigSingleFile::String(v) => release_gen_val_string(v), + SSLConfigSingleFile::String(_) => {} SSLConfigSingleFile::Buffer(v) => release_gen_val_array_buffer(v), SSLConfigSingleFile::File(v) => release_gen_val_blob(v), } @@ -392,30 +385,13 @@ impl Drop for SSLConfigFile { fn drop(&mut self) { // `Array` recursively drops each `SSLConfigSingleFile`. match self { - SSLConfigFile::None | SSLConfigFile::Array(_) => {} - SSLConfigFile::String(v) => release_gen_val_string(v), + SSLConfigFile::None | SSLConfigFile::Array(_) | SSLConfigFile::String(_) => {} SSLConfigFile::Buffer(v) => release_gen_val_array_buffer(v), SSLConfigFile::File(v) => release_gen_val_blob(v), } } } -impl Drop for SSLConfig { - fn drop(&mut self) { - release_gen_opt_string(&self.passphrase); - release_gen_opt_string(&self.dh_params_file); - release_gen_opt_string(&self.server_name); - // `ca` / `cert` / `key`: `SSLConfigFile` — released by its own `Drop`. - release_gen_opt_string(&self.key_file); - release_gen_opt_string(&self.cert_file); - release_gen_opt_string(&self.ca_file); - // `alpn_protocols`: `SSLConfigAlpnProtocols` — released by its own `Drop`. - release_gen_opt_string(&self.ciphers); - release_gen_opt_string(&self.sigalgs); - release_gen_opt_string(&self.ecdh_curve); - } -} - // ── extern layouts ──────────────────────────────────────────────────────── /// `BindgenSSLConfigSingleFile.ExternType` = @@ -643,15 +619,6 @@ pub struct SocketConfig { pub ipv6_only: bool, } -impl Drop for SocketConfig { - fn drop(&mut self) { - // `tls`: `SocketConfigTls::Object` holds `SSLConfig`, released by its - // own `Drop`. `handlers`: only `JSValue`s — no owned refs. - release_gen_opt_string(&self.unix_); - release_gen_opt_string(&self.hostname); - } -} - /// `BindgenSocketConfigTLS.ExternType` = /// `ExternTaggedUnion(&.{ u8, bool, ExternSSLConfig })`. #[repr(C)] diff --git a/src/jsc/lib.rs b/src/jsc/lib.rs index 38ec770dffbe..f6eacffff526 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -84,8 +84,6 @@ pub mod source_provider; pub mod url_search_params; #[path = "WTF.rs"] pub mod wtf; -#[path = "ZigErrorType.rs"] -pub mod zig_error_type; #[path = "ZigStackFrameCode.rs"] pub mod zig_stack_frame_code; #[path = "ZigStackFramePosition.rs"] @@ -762,7 +760,7 @@ mod __macro_smoke { // newtypes; the real opaque-FFI structs now live in their own files and are // surfaced here at the crate root. pub use self::dom_form_data::DOMFormData; -pub use self::url::URL; +pub use self::url::{URL, URLJsc}; pub use self::zig_stack_frame::ZigStackFrame; pub use self::zig_stack_trace::ZigStackTrace; pub use abort_signal::{AbortSignal, AbortSignalRef}; @@ -799,9 +797,8 @@ impl Default for IntegerRange { } // ────────────────────────────────────────────────────────────────────────── -// ResolvedSource — `#[repr(C)]` mirror of the C struct in -// src/jsc/bindings/headers-handwritten.h:115. Passed by value across the -// Rust → C++ module-loader boundary (`ErrorableResolvedSource`). +// ResolvedSource — `#[repr(C)]` mirror of the C++ struct in +// src/jsc/bindings/headers-handwritten.h. // ────────────────────────────────────────────────────────────────────────── #[path = "ResolvedSource.rs"] pub mod resolved_source; @@ -1124,10 +1121,7 @@ impl FromJsEnum for bun_sys::SignalCode { ); } let s = bun_string_jsc::from_js(v, global)?; - let utf8 = s.to_utf8(); - let hit = bun_sys::signal_code::from_name(utf8.slice()); - drop(utf8); - s.deref(); + let hit = bun_sys::signal_code::from_name(s.to_utf8().slice()); match hit { Some(code) => Ok(code), None => { @@ -1205,13 +1199,10 @@ impl FromJsEnum for bun_http_types::FetchCacheMode::FetchCacheMode { } } -// `URL::path_from_file_url` / `URL::href_from_js` live in `URL.rs` (the -// dedicated port file); the lib.rs copies were duplicate definitions. - // JSString (real module in JSString.rs). #[path = "JSString.rs"] pub mod js_string; -pub use self::js_string::JSString; +pub use self::js_string::{JSString, JSStringView}; #[path = "RefString.rs"] pub mod ref_string; @@ -1387,9 +1378,11 @@ pub use self::codegen as Codegen; /// Extension trait providing JSC-aware methods on `bun_core::String`. pub trait StringJsc { fn from_js(value: JSValue, global: &JSGlobalObject) -> JsResult; + /// Borrow: JSC takes its own ref (or copies borrowed bytes). fn to_js(&self, global: &JSGlobalObject) -> JsResult; - fn transfer_to_js(&mut self, global: &JSGlobalObject) -> JsResult; - fn to_js_by_parse_json(&mut self, global: &JSGlobalObject) -> JsResult; + /// Consume: the +1 moves into the `JSString`. + fn into_js(self, global: &JSGlobalObject) -> JsResult; + fn to_js_by_parse_json(&self, global: &JSGlobalObject) -> JsResult; fn to_error_instance(&self, global: &JSGlobalObject) -> JSValue; fn to_type_error_instance(&self, global: &JSGlobalObject) -> JSValue; fn to_range_error_instance(&self, global: &JSGlobalObject) -> JSValue; @@ -1401,10 +1394,10 @@ impl StringJsc for bun_core::String { fn to_js(&self, global: &JSGlobalObject) -> JsResult { bun_string_jsc::to_js(self, global) } - fn transfer_to_js(&mut self, global: &JSGlobalObject) -> JsResult { - bun_string_jsc::transfer_to_js(self, global) + fn into_js(self, global: &JSGlobalObject) -> JsResult { + bun_string_jsc::into_js(self, global) } - fn to_js_by_parse_json(&mut self, global: &JSGlobalObject) -> JsResult { + fn to_js_by_parse_json(&self, global: &JSGlobalObject) -> JsResult { bun_string_jsc::to_js_by_parse_json(self, global) } fn to_error_instance(&self, global: &JSGlobalObject) -> JSValue { @@ -1420,11 +1413,11 @@ impl StringJsc for bun_core::String { /// Extension trait providing JSC-aware methods on /// `bun_core::SliceWithUnderlyingString` (lower-tier, no JSC dep) — -/// `to_js`, `transfer_to_js`, `report_extra_memory`; the free-function bodies +/// `to_js`, `into_js`, `report_extra_memory`; the free-function bodies /// live in [`bun_string_jsc`]. pub trait SliceWithUnderlyingStringJsc { fn to_js(&mut self, global: &JSGlobalObject) -> JsResult; - fn transfer_to_js(&mut self, global: &JSGlobalObject) -> JsResult; + fn into_js(self, global: &JSGlobalObject) -> JsResult; fn report_extra_memory(&mut self, vm: &VM); } impl SliceWithUnderlyingStringJsc for bun_core::SliceWithUnderlyingString { @@ -1433,8 +1426,8 @@ impl SliceWithUnderlyingStringJsc for bun_core::SliceWithUnderlyingString { bun_string_jsc::slice_with_underlying_string_to_js(self, global) } #[inline] - fn transfer_to_js(&mut self, global: &JSGlobalObject) -> JsResult { - bun_string_jsc::slice_with_underlying_string_transfer_to_js(self, global) + fn into_js(self, global: &JSGlobalObject) -> JsResult { + bun_string_jsc::slice_with_underlying_string_into_js(self, global) } /// Account `utf8`'s backing allocation against the GC heap unless it is /// already JSC-owned (WTF-backed) or borrowed. diff --git a/src/jsc/modules/BunJSCModule.h b/src/jsc/modules/BunJSCModule.h index 02ae3334d2b7..6818e27aa2c9 100644 --- a/src/jsc/modules/BunJSCModule.h +++ b/src/jsc/modules/BunJSCModule.h @@ -901,7 +901,7 @@ JSC_DEFINE_HOST_FUNCTION(functionDeserialize, (JSGlobalObject * globalObject, Ca } extern "C" JSC::EncodedJSValue ByteRangeMapping__findExecutedLines( - JSC::JSGlobalObject*, BunString sourceURL, BasicBlockRange* ranges, + JSC::JSGlobalObject*, const BunString* sourceURL, BasicBlockRange* ranges, size_t len, size_t functionOffset, bool ignoreSourceMap); JSC_DEFINE_HOST_FUNCTION(functionCodeCoverageForFile, @@ -947,8 +947,9 @@ JSC_DEFINE_HOST_FUNCTION(functionCodeCoverageForFile, basicBlocks.append(range); } + BunString fileNameBunString = Bun::toString(fileName); return ByteRangeMapping__findExecutedLines( - globalObject, Bun::toString(fileName), basicBlocks.begin(), + globalObject, &fileNameBunString, basicBlocks.begin(), basicBlocks.size(), functionStartOffset, ignoreSourceMap); } diff --git a/src/jsc/modules/NodeModuleModule.cpp b/src/jsc/modules/NodeModuleModule.cpp index a58d86d06836..7cef4164b64d 100644 --- a/src/jsc/modules/NodeModuleModule.cpp +++ b/src/jsc/modules/NodeModuleModule.cpp @@ -223,8 +223,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionWrap, (JSC::JSGlobalObject * globalObject, JS RELEASE_AND_RETURN(scope, JSValue::encode(jsString(globalObject, prefix, code, suffix))); } -extern "C" void Bun__Node__Path_joinWTF(BunString* lhs, const char* rhs, - size_t len, BunString* result); +extern "C" BunString Bun__Node__Path_joinWTF(const BunString* lhs, const char* rhs, size_t len); JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleCreateRequire, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) @@ -268,13 +267,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleCreateRequire, // https://github.com/nodejs/node/blob/2eff28fb7a93d3f672f80b582f664a7c701569fb/lib/internal/modules/cjs/loader.js#L1603-L1620 if (trailingSlash) { BunString lhs = Bun::toString(val); - BunString result; - Bun__Node__Path_joinWTF(&lhs, "noop.js", sizeof("noop.js") - 1, &result); - val = result.toWTFString(); - if (!val.isNull()) { - ASSERT(val.impl()->refCount() == 2); - val.impl()->deref(); - } + val = Bun__Node__Path_joinWTF(&lhs, "noop.js", sizeof("noop.js") - 1).transferToWTFString(); } RELEASE_AND_RETURN( @@ -526,7 +519,7 @@ JSC::JSValue resolveLookupPaths(JSC::JSGlobalObject* globalObject, String reques auto filenameValue = parent.filename->value(globalObject); RETURN_IF_EXCEPTION(scope, {}); auto filename = Bun::toString(filenameValue); - auto paths = JSValue::decode(Resolver__nodeModulePathsJSValue(filename, globalObject, true)); + auto paths = JSValue::decode(Resolver__nodeModulePathsJSValue(&filename, globalObject, true)); RELEASE_AND_RETURN(scope, paths); } else { auto array = JSC::constructEmptyArray(globalObject, nullptr, 0); @@ -556,7 +549,7 @@ JSC::JSValue resolveLookupPaths(JSC::JSGlobalObject* globalObject, String reques } extern "C" JSC::EncodedJSValue NodeModuleModule__findPath(JSGlobalObject*, - BunString, JSArray*); + const BunString*, JSArray*); JSC_DEFINE_HOST_FUNCTION(jsFunctionFindPath, (JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) { @@ -572,7 +565,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionFindPath, (JSGlobalObject * globalObject, JSC JSArray* paths = paths_value.isCell() ? dynamicDowncast(paths_value) : nullptr; - return NodeModuleModule__findPath(globalObject, request_bun_str, paths); + return NodeModuleModule__findPath(globalObject, &request_bun_str, paths); } // These two setters are only used if you directly hit diff --git a/src/jsc/modules/NodeModuleModule.h b/src/jsc/modules/NodeModuleModule.h index edb1c4429453..8d496eb9f4e1 100644 --- a/src/jsc/modules/NodeModuleModule.h +++ b/src/jsc/modules/NodeModuleModule.h @@ -21,7 +21,7 @@ JSC_DECLARE_HOST_FUNCTION(jsFunctionIsModuleResolveFilenameSlowPathEnabled); JSC::JSValue createStreamIterEnabledFlag(Zig::GlobalObject*); void addNodeModuleConstructorProperties(JSC::VM &vm, Zig::GlobalObject *globalObject); -extern "C" JSC::EncodedJSValue Resolver__nodeModulePathsJSValue(BunString specifier, JSC::JSGlobalObject*, bool use_dirname); +extern "C" JSC::EncodedJSValue Resolver__nodeModulePathsJSValue(const BunString* specifier, JSC::JSGlobalObject*, bool use_dirname); extern "C" bool ModuleLoader__isBuiltin(const char* data, size_t len); struct PathResolveModule { diff --git a/src/jsc/node_path.rs b/src/jsc/node_path.rs index e00df5bb73c2..57decd83c42f 100644 --- a/src/jsc/node_path.rs +++ b/src/jsc/node_path.rs @@ -140,14 +140,14 @@ impl Clone for PathLike { // buffer) alongside the bumped `underlying` ref. Self::SliceWithUnderlyingString(SliceWithUnderlyingString { utf8: s.utf8.clone_ref(), - underlying: s.underlying.dupe_ref(), + underlying: s.underlying.clone(), #[cfg(debug_assertions)] did_report_extra_memory_debug: s.did_report_extra_memory_debug, }) } Self::ThreadsafeString(s) => Self::ThreadsafeString(SliceWithUnderlyingString { utf8: s.utf8.clone_ref(), - underlying: s.underlying.dupe_ref(), + underlying: s.underlying.clone(), #[cfg(debug_assertions)] did_report_extra_memory_debug: s.did_report_extra_memory_debug, }), @@ -168,9 +168,8 @@ impl Drop for PathLike { b.buffer.unpin(); } } - Self::SliceWithUnderlyingString(s) | Self::ThreadsafeString(s) => { - core::mem::take(s).deinit(); - } + // `SliceWithUnderlyingString` derefs `underlying` in its own `Drop`. + Self::SliceWithUnderlyingString(_) | Self::ThreadsafeString(_) => {} // `ZigStringSlice` releases its WTF ref / owned buffer in its own // `Drop`. Self::EncodedSlice(_) => {} diff --git a/src/jsc/resolve_path_jsc.rs b/src/jsc/resolve_path_jsc.rs index 0274b536466c..11a35a9c33ae 100644 --- a/src/jsc/resolve_path_jsc.rs +++ b/src/jsc/resolve_path_jsc.rs @@ -6,10 +6,11 @@ use crate::JSGlobalObject; use bun_core::String as BunString; use bun_paths::resolve_path; +/// The C++ caller `transferToWTFString()`s the result. #[unsafe(no_mangle)] extern "C" fn ResolvePath__joinAbsStringBufCurrentPlatformBunString( global_object: &JSGlobalObject, - input: BunString, + input: &BunString, ) -> BunString { let str = input.to_utf8_without_ref(); diff --git a/src/jsc/resolver_jsc.rs b/src/jsc/resolver_jsc.rs index 1a0a7f5e7617..f86c2aa77e96 100644 --- a/src/jsc/resolver_jsc.rs +++ b/src/jsc/resolver_jsc.rs @@ -5,7 +5,7 @@ use crate::HostReturn as _; use bstr::BStr; use crate::{CallFrame, JSGlobalObject, JSValue, JsResult}; -use bun_core::{OwnedString, String as BunString, strings}; +use bun_core::{String as BunString, strings}; use bun_paths::resolve_path; use bun_paths::{Platform, SEP, SEP_STR}; @@ -18,28 +18,25 @@ fn node_module_paths_for_js(global: &JSGlobalObject, frame: &CallFrame) -> JsRes return Err(global.throw_invalid_argument_type("nodeModulePaths", "path", "string")); } - let in_str = OwnedString::new(argument.to_bun_string(global)?); - Ok(node_module_paths_js_value(in_str.get(), global, false)) + let in_str = argument.to_bun_string(global)?; + Ok(node_module_paths_js_value(&in_str, global, false)) } #[unsafe(no_mangle)] extern "C" fn Resolver__propForRequireMainPaths(global: &JSGlobalObject) -> JSValue { crate::mark_binding!(); - let in_str = BunString::static_(b"."); - node_module_paths_js_value(in_str, global, false) + node_module_paths_js_value(&BunString::static_(b"."), global, false) } -// C++ callers pass `in_str` by value without transferring a ref: -// `bun_core::String` is `Copy` with no `Drop` impl, so receiving it by value -// never releases the caller's ref. +// C++ callers pass a borrowed `const BunString*` (`Bun::toString`). #[unsafe(export_name = "Resolver__nodeModulePathsJSValue")] extern "C" fn node_module_paths_js_value( - in_str: BunString, + in_str: &BunString, global: &JSGlobalObject, use_dirname: bool, ) -> JSValue { - let mut list: Vec = Vec::new(); + let mut list: Vec = Vec::new(); let sliced = in_str.to_utf8(); let base_path: &[u8] = if use_dirname { @@ -98,12 +95,12 @@ extern "C" fn node_module_paths_js_value( None => 0, } + part.len(); - list.push(OwnedString::new(BunString::create_format(format_args!( + list.push(BunString::create_format(format_args!( "{}{}{}node_modules", BStr::new(root_path), BStr::new(&suffix[..prefix_len]), SEP_STR, - )))); + ))); } } @@ -111,34 +108,11 @@ extern "C" fn node_module_paths_js_value( root_path = &root_path[..root_path.len() - 1]; } - list.push(OwnedString::new(BunString::create_format(format_args!( + list.push(BunString::create_format(format_args!( "{}{}node_modules", BStr::new(root_path), SEP_STR, - )))); + ))); - OwnedString::as_raw_slice(&list) - .to_js_array(global) - .or_pending_exception() -} - -/// `[bun.String]::to_js_array` lives on the `StringArrayJsc` ext trait below. -trait StringArrayJsc { - fn to_js_array(&self, global: &JSGlobalObject) -> JsResult; -} -impl StringArrayJsc for [BunString] { - fn to_js_array(&self, global: &JSGlobalObject) -> JsResult { - unsafe extern "C" { - fn BunString__createArray( - global: &JSGlobalObject, - ptr: *const BunString, - len: usize, - ) -> JSValue; - } - // SAFETY: `self` is a live slice, so `self.as_ptr()` is valid for `self.len()` - // reads of `BunString` for the duration of the FFI call. - crate::host_fn::from_js_host_call(global, || unsafe { - BunString__createArray(global, self.as_ptr(), self.len()) - }) - } + crate::bun_string_jsc::to_js_array(global, &list).or_pending_exception() } diff --git a/src/jsc/web_worker.rs b/src/jsc/web_worker.rs index 1db201b529f3..c8992a60697d 100644 --- a/src/jsc/web_worker.rs +++ b/src/jsc/web_worker.rs @@ -169,7 +169,7 @@ unsafe extern "C" { safe fn WebWorker__dispatchError( global: &JSGlobalObject, proxy: *mut c_void, - message: &mut BunString, + message: BunString, err: JSValue, ); safe fn Bun__freeSharedHeaderBufferForThreadExit(); @@ -282,8 +282,8 @@ impl WebWorker { pub(crate) unsafe extern "C" fn create( proxy: *mut c_void, parent: *mut VirtualMachine, - name_str: BunString, - specifier_str: BunString, + name_str: &BunString, + specifier_str: &BunString, error_message: &mut BunString, _parent_context_id: u32, this_context_id: u32, @@ -836,12 +836,10 @@ impl WebWorker { // to `err`, which is dropped immediately after). vm_log.add_error(None, bun_ast::Loc::EMPTY, err.slice().to_vec()); } - resolve_error.deref(); self.flush_logs(vm); return self.shutdown(); } }; - resolve_error.deref(); // Terminated while resolving — exit code 0, no error. if self.has_requested_terminate() { @@ -1163,9 +1161,8 @@ impl WebWorker { return; } }; - let mut str = bun_core::OwnedString::new(str); let dispatch = jsc::host_fn::from_js_host_call_generic(global, || { - WebWorker__dispatchError(global, self.messaging_proxy, &mut str, err) + WebWorker__dispatchError(global, self.messaging_proxy, str, err) }); if let Err(e) = dispatch { let _ = crate::task::report_error_or_terminate(global, e); @@ -1242,12 +1239,12 @@ fn on_unhandled_rejection( // (declares + checks a TopExceptionScope around the FFI call, same as // `flush_logs` above) and discard any actual exception: we are already the // last-resort error handler and about to arm termination. - let mut error_message = bun_core::OwnedString::new(BunString::clone_utf8(&array)); + let error_message = BunString::clone_utf8(&array); if jsc::host_fn::from_js_host_call_generic(global_object, || { WebWorker__dispatchError( global_object, worker.messaging_proxy, - &mut error_message, + error_message, error_instance, ); }) diff --git a/src/jsc/webcore_types.rs b/src/jsc/webcore_types.rs index 5e422dcc1c26..cacf3e262a24 100644 --- a/src/jsc/webcore_types.rs +++ b/src/jsc/webcore_types.rs @@ -139,7 +139,7 @@ pub struct Blob { pub global_this: Cell<*const JSGlobalObject>, pub last_modified: Cell, /// Only used by `` / `File` (issue #10178). - pub name: bun_core::OwnedStringCell, + pub name: bun_ptr::JsCell, } // SAFETY: `Blob` holds a raw `global_this` pointer which defaults to @@ -165,7 +165,7 @@ impl Default for Blob { ref_count: bun_ptr::RawRefCount::init(0), global_this: Cell::new(core::ptr::null()), last_modified: Cell::new(0.0), - name: bun_core::OwnedStringCell::new(bun_core::String::dead()), + name: bun_ptr::JsCell::new(bun_core::String::dead()), } } } diff --git a/src/patch_jsc/testing.rs b/src/patch_jsc/testing.rs index 55bf0fd99e3d..ae0a378cbe8c 100644 --- a/src/patch_jsc/testing.rs +++ b/src/patch_jsc/testing.rs @@ -1,6 +1,6 @@ //! JS testing bindings for `bun.patch`. Keeps `src/patch/` free of JSC types. -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_jsc::{ ArgumentsSlice, CallFrame, JSGlobalObject, JSValue, JsResult, StringJsc, SysErrorJsc, }; @@ -21,13 +21,12 @@ impl TestingAPIs { let Some(old_folder_jsval) = arguments.next_eat() else { return Err(global.throw(format_args!("expected 2 strings"))); }; - // `to_bun_string` returns +1 ref; `OwnedString` derefs on drop. - let old_folder_bunstr = OwnedString::new(old_folder_jsval.to_bun_string(global)?); + let old_folder_bunstr = old_folder_jsval.to_bun_string(global)?; let Some(new_folder_jsval) = arguments.next_eat() else { return Err(global.throw(format_args!("expected 2 strings"))); }; - let new_folder_bunstr = OwnedString::new(new_folder_jsval.to_bun_string(global)?); + let new_folder_bunstr = new_folder_jsval.to_bun_string(global)?; let old_folder = old_folder_bunstr.to_utf8(); let new_folder = new_folder_bunstr.to_utf8(); @@ -82,7 +81,7 @@ impl TestingAPIs { "TestingAPIs.parse: expected at least 1 argument, got 0" ))); }; - let patchfile_src_bunstr = OwnedString::new(patchfile_src_js.to_bun_string(global)?); + let patchfile_src_bunstr = patchfile_src_js.to_bun_string(global)?; let patchfile_src = patchfile_src_bunstr.to_utf8(); let patchfile = match parse_patch_file(patchfile_src.slice()) { @@ -122,8 +121,7 @@ impl TestingAPIs { }; let dir_fd = if let Some(dir_js) = arguments.next_eat() { - // +1 ref from `to_bun_string`; release via `OwnedString` drop. - let bunstr = OwnedString::new(dir_js.to_bun_string(global)?); + let bunstr = dir_js.to_bun_string(global)?; let path = bunstr.to_owned_slice_z(); match bun_sys::open( @@ -150,10 +148,6 @@ impl TestingAPIs { return Err(e); } }; - // +1 ref from `to_bun_string`; release via `OwnedString` drop. - // `to_utf8()` takes its own ref, so - // `patchfile_src` outlives this guard. - let patchfile_bunstr = OwnedString::new(patchfile_bunstr); let patchfile_src = patchfile_bunstr.to_utf8(); // Validate the patch parses; on failure, clean up `dir_fd` and throw. diff --git a/src/ptr/js_cell.rs b/src/ptr/js_cell.rs index 4ac4b1ec563f..d7b1e772548c 100644 --- a/src/ptr/js_cell.rs +++ b/src/ptr/js_cell.rs @@ -110,6 +110,14 @@ impl JsCell { } } +impl JsCell { + /// Move the value out, leaving `T::default()` behind. + #[inline(always)] + pub fn take(&self) -> T { + self.replace(T::default()) + } +} + impl Default for JsCell { #[inline(always)] fn default() -> Self { @@ -117,6 +125,13 @@ impl Default for JsCell { } } +impl Clone for JsCell { + #[inline(always)] + fn clone(&self) -> Self { + Self::new(self.get().clone()) + } +} + impl From for JsCell { #[inline(always)] fn from(value: T) -> Self { diff --git a/src/runtime/api.rs b/src/runtime/api.rs index b79cc9825976..6700f8c81089 100644 --- a/src/runtime/api.rs +++ b/src/runtime/api.rs @@ -265,10 +265,8 @@ fn with_text_format_source_encoded( // Hold whichever input storage applies; all expose the bytes. // Conditional-init + drop-flag — only the taken branch's holder is live. let _blob_hold: BlobOrStringOrBuffer; - // `SliceWithUnderlyingString` has no `Drop`; `StringOrBuffer`'s releases - // the string's ref. let _str_hold: StringOrBuffer; - let _latin1_hold: bun_core::OwnedString; + let _latin1_hold: bun_core::String; let mut encoding = SourceEncoding::Utf8Text; let bytes: &[u8] = 'bytes: { if blob_or_buffer_input == BlobOrBufferInput::Bytes && !input_value.is_string() { @@ -278,9 +276,9 @@ fn with_text_format_source_encoded( break 'bytes _blob_hold.slice(); } } - let mut s = input_value.to_bun_string(global)?; + let s = input_value.to_bun_string(global)?; if string_input == StringInput::AsIs { - _latin1_hold = bun_core::OwnedString::new(s); + _latin1_hold = s; if _latin1_hold.is_8bit() { encoding = SourceEncoding::Latin1Text; break 'bytes _latin1_hold.latin1(); @@ -288,9 +286,7 @@ fn with_text_format_source_encoded( encoding = SourceEncoding::Utf16Text; break 'bytes bytemuck::cast_slice(_latin1_hold.utf16()); } - // `to_slice` moves the +1 ref into the returned slice's - // `.underlying`, so the temporary `BunString` drop is a no-op. - _str_hold = StringOrBuffer::String(s.to_slice()); + _str_hold = StringOrBuffer::String(s.into_slice()); _str_hold.slice() }; diff --git a/src/runtime/api/Archive.rs b/src/runtime/api/Archive.rs index 1cf12e255090..02b3802e2ec5 100644 --- a/src/runtime/api/Archive.rs +++ b/src/runtime/api/Archive.rs @@ -324,7 +324,7 @@ fn build_tarball_from_object(global: &JSGlobalObject, obj: JSValue) -> JsResult< let now_secs: isize = isize::try_from(bun_core::time::milli_timestamp() / 1000).unwrap_or(0); // Iterate over object properties and write directly to archive - let mut iter = jsc::JSPropertyIterator::init( + let iter = jsc::JSPropertyIterator::init( global, js_obj, jsc::PropertyIteratorOptions { @@ -333,8 +333,7 @@ fn build_tarball_from_object(global: &JSGlobalObject, obj: JSValue) -> JsResult< }, )?; - while let Some(key) = iter.next()? { - let value = iter.value; + while let Some((key, value)) = iter.next()? { if value == JSValue::ZERO { continue; } diff --git a/src/runtime/api/BunObject.rs b/src/runtime/api/BunObject.rs index 7ebe20f6d3c9..48f012f3d998 100644 --- a/src/runtime/api/BunObject.rs +++ b/src/runtime/api/BunObject.rs @@ -76,8 +76,8 @@ use std::io::Write as _; use bun_core::Output; use bun_jsc::{ - self as jsc, ArrayBuffer, CallFrame, ConsoleObject, ErrorableString, JSFunction, - JSGlobalObject, JSObject, JSPromise, JSValue, JsResult, + self as jsc, ArrayBuffer, CallFrame, ConsoleObject, JSFunction, JSGlobalObject, JSObject, + JSPromise, JSValue, JsResult, }; // `bun_jsc::VirtualMachine` is the *module* re-export; the struct lives one level deeper. use crate::cli::open::Editor; @@ -395,27 +395,24 @@ fn get_cron_object(global_this: &JSGlobalObject, obj: &JSObject) -> JSValue { #[bun_jsc::host_fn] fn shell_escape(global_this: &JSGlobalObject, callframe: &CallFrame) -> JsResult { - use bun_jsc::StringJsc as _; let [jsval] = callframe.arguments_as_array::<1>(); if callframe.arguments_count() < 1 { return Err(global_this.throw(format_args!("shell escape expected at least 1 argument"))); } let bunstr = jsval.to_bun_string(global_this)?; - let bunstr = scopeguard::guard(bunstr, |s| s.deref()); let mut outbuf: Vec = Vec::new(); - if bun_shell_parser::needs_escape_bunstr(*bunstr) { - let result = bun_shell_parser::escape_bun_str::(*bunstr, &mut outbuf)?; + if bun_shell_parser::needs_escape_bunstr(&bunstr) { + let result = bun_shell_parser::escape_bun_str::(&bunstr, &mut outbuf)?; if !result { return Err(global_this.throw(format_args!( "String has invalid utf-16: {}", bstr::BStr::new(bunstr.byte_slice()), ))); } - let mut str = BunString::clone_utf8(&outbuf[..]); - return str.transfer_to_js(global_this); + return bun_string_jsc::create_utf8_for_js(global_this, &outbuf); } Ok(jsval) @@ -423,7 +420,7 @@ fn shell_escape(global_this: &JSGlobalObject, callframe: &CallFrame) -> JsResult pub(crate) fn braces( global: &JSGlobalObject, - brace_str: BunString, + brace_str: &BunString, opts: r#gen::BracesOptions, ) -> JsResult { let brace_slice = brace_str.to_utf8(); @@ -478,7 +475,7 @@ pub(crate) fn braces( } if expansion_count == 0 { - return bun_string_jsc::to_js_array(global, &[brace_str]); + return bun_string_jsc::to_js_array(global, core::slice::from_ref(brace_str)); } // Hard cap before preallocation: `calculate_expanded_amount` saturates to @@ -746,11 +743,10 @@ fn get_inspect(global_object: &JSGlobalObject, _: &JSObject) -> JSValue { 2, Default::default(), ); - let mut str = bun_core::ZigString::init(b"nodejs.util.inspect.custom"); fun.put( global_object, b"custom", - JSValue::symbol_for(global_object, &mut str), + JSValue::symbol_for(global_object, b"nodejs.util.inspect.custom"), ); fun.put( global_object, @@ -1119,33 +1115,8 @@ fn do_resolve(global_this: &JSGlobalObject, arguments: &[JSValue]) -> JsResult(global_this, *specifier_str, *from_str, mode) -} - -/// Single Drop point for the three `BunString`s `do_resolve_with_args` may own. -/// Replaces three separate `scopeguard::guard(_, |s| s.deref())` closures — -/// each of which generated its own drop frame and landing pad — with one -/// contiguous cleanup. Fields default to `BunString::empty()`, whose `deref()` -/// is a single tag-compare no-op, so unused slots cost effectively nothing. -struct ResolveDerefOnDrop { - query_string: BunString, - /// Only set when the specifier had a `file://` prefix and we allocated a - /// decoded copy. On the fast path the caller's `specifier` is borrowed - /// directly and this stays empty (no refcount traffic). - decoded_specifier: BunString, - result_value: BunString, -} -impl Drop for ResolveDerefOnDrop { - #[inline] - fn drop(&mut self) { - // LIFO relative to original declaration order. - self.result_value.deref(); - self.decoded_specifier.deref(); - self.query_string.deref(); - } + do_resolve_with_args::(global_this, &specifier_str, &from_str, mode) } enum Resolved { @@ -1156,8 +1127,8 @@ enum Resolved { fn do_resolve_with_args( ctx: &JSGlobalObject, - specifier: BunString, - from: BunString, + specifier: &BunString, + from: &BunString, mode: ResolveMode, ) -> JsResult { match resolve_with_args::(ctx, specifier, from, mode)? { @@ -1168,61 +1139,44 @@ fn do_resolve_with_args( fn resolve_with_args( ctx: &JSGlobalObject, - specifier: BunString, - from: BunString, + specifier: &BunString, + from: &BunString, mode: ResolveMode, ) -> JsResult { - let mut errorable: ErrorableString = ErrorableString::ok(BunString::empty()); - let mut owned = ResolveDerefOnDrop { - query_string: BunString::empty(), - decoded_specifier: BunString::empty(), - result_value: BunString::empty(), - }; + let mut query_string = BunString::empty(); - // Fast path: no `file://` prefix → forward the caller-owned `specifier` - // by value without `dupe_ref()`/`deref()` refcount churn. Only the - // URL-decoded branch produces a string we must release. + let decoded_specifier; let specifier_for_resolve = if specifier.has_prefix_comptime(b"file://") { - owned.decoded_specifier = jsc::URL::path_from_file_url(specifier); - owned.decoded_specifier + decoded_specifier = bun_url::path_from_file_url(specifier); + &decoded_specifier } else { specifier }; - VirtualMachine::resolve_maybe_needs_trailing_slash::( - &mut errorable, + let result_value = match VirtualMachine::resolve_maybe_needs_trailing_slash::( ctx, specifier_for_resolve, from, - Some(&mut owned.query_string), + Some(&mut query_string), mode, - )?; - - if !errorable.success { - // SAFETY: !success → `err` arm of the #[repr(C)] union is active. - let err = unsafe { errorable.result.err }.value; - if err.as_class_ref::().is_some() { + )? { + Ok(path) => path, + Err(err) if err.as_class_ref::().is_some() => { return Ok(Resolved::NotFound(err)); } // e.g. an onResolve plugin returned an invalid result - return Err(ctx.throw_value(err)); - } - // SAFETY: success → `value` arm of the #[repr(C)] union is active. - owned.result_value = unsafe { errorable.result.value }; + Err(err) => return Err(ctx.throw_value(err)), + }; - if !owned.query_string.is_empty() { + if !query_string.is_empty() { let mut arraylist: Vec = Vec::with_capacity(1024); // Vec writes are infallible. - let _ = write!( - &mut arraylist, - "{}{}", - owned.result_value, owned.query_string - ); + let _ = write!(&mut arraylist, "{}{}", result_value, query_string); return Ok(Resolved::Found(ZigString::init_utf8(&arraylist).to_js(ctx))); } - Ok(Resolved::Found(owned.result_value.to_js(ctx)?)) + Ok(Resolved::Found(result_value.into_js(ctx)?)) } #[bun_jsc::host_fn] @@ -1258,7 +1212,6 @@ pub fn bun_resolve_sync( let Ok(specifier_str) = specifier.to_bun_string(global) else { return JSValue::ZERO; }; - let specifier_str = scopeguard::guard(specifier_str, |s| s.deref()); if specifier_str.length() == 0 { let _ = global @@ -1273,13 +1226,12 @@ pub fn bun_resolve_sync( let Ok(source_str) = source.to_bun_string(global) else { return JSValue::ZERO; }; - let source_str = scopeguard::guard(source_str, |s| s.deref()); jsc::to_js_host_call(global, || { do_resolve_with_args::( global, - *specifier_str, - *source_str, + &specifier_str, + &source_str, ResolveMode::from_ffi_bools(is_esm, is_user_require_resolve), ) }) @@ -1314,7 +1266,6 @@ pub fn bun_resolve_sync_with_paths( let Ok(specifier_str) = specifier.to_bun_string(global) else { return JSValue::ZERO; }; - let specifier_str = scopeguard::guard(specifier_str, |s| s.deref()); if specifier_str.length() == 0 { let _ = global @@ -1329,7 +1280,6 @@ pub fn bun_resolve_sync_with_paths( let Ok(source_str) = source.to_bun_string(global) else { return JSValue::ZERO; }; - let source_str = scopeguard::guard(source_str, |s| s.deref()); // SAFETY: bun_vm() returns the live thread-local VM for a Bun-owned global. let bun_vm = global.bun_vm().as_mut(); @@ -1345,8 +1295,8 @@ pub fn bun_resolve_sync_with_paths( jsc::to_js_host_call(global, || { do_resolve_with_args::( global, - *specifier_str, - *source_str, + &specifier_str, + &source_str, ResolveMode::from_ffi_bools(is_esm, is_user_require_resolve), ) }) @@ -1370,8 +1320,8 @@ pub fn bun_resolve_sync_with_strings( jsc::to_js_host_call(global, || { do_resolve_with_args::( global, - *specifier, - *source, + specifier, + source, ResolveMode::from_ffi_bools(is_esm, false), ) }) @@ -1391,12 +1341,11 @@ pub fn bun_resolve_sync_with_source_if_exists( let Ok(specifier_str) = specifier.to_bun_string(global) else { return JSValue::ZERO; }; - let specifier_str = scopeguard::guard(specifier_str, |s| s.deref()); jsc::to_js_host_call(global, || { resolve_with_args::( global, - *specifier_str, - *source, + &specifier_str, + source, ResolveMode::from_ffi_bools(is_esm, false), ) .map(|r| match r { @@ -1985,7 +1934,7 @@ fn get_embedded_files(global_this: &JSGlobalObject, _: &JSObject) -> JsResult( + global_object: &'a JSGlobalObject, name: &BunString, - value: &mut core::mem::MaybeUninit, - ) -> bool { + ) -> bun_core::StringView<'a> { let vm = global_object.bun_vm(); let name_slice = name.to_utf8(); - let Some(val) = vm.env_loader().get(name_slice.slice()) else { - return false; - }; - value.write(BunString::borrow_utf8(val)); - true + match vm.env_loader().get(name_slice.slice()) { + Some(val) => bun_core::StringView::borrow_utf8(val), + None => bun_core::StringView::DEAD, + } } /// Sync a process.env write back to the native env map so that native diff --git a/src/runtime/api/JSBundler.rs b/src/runtime/api/JSBundler.rs index 2160e5cee087..25c8c28a4432 100644 --- a/src/runtime/api/JSBundler.rs +++ b/src/runtime/api/JSBundler.rs @@ -11,7 +11,7 @@ use bun_bundler::options; use bun_collections::{StringMap, StringSet}; use bun_core::MutableString; use bun_core::Output; -use bun_core::{String as BunString, ZigString}; +use bun_core::String as BunString; use bun_jsc::ConcurrentTask::ConcurrentTask; use bun_jsc::{self as jsc, CallFrame, JSGlobalObject, JSValue, JsError, JsResult}; use bun_options_types::compile_target::CompileTarget; @@ -62,7 +62,7 @@ pub mod js_bundler { ); }; - let mut files_iter = jsc::JSPropertyIterator::init( + let files_iter = jsc::JSPropertyIterator::init( global_this, files_obj, jsc::JSPropertyIteratorOptions { @@ -74,9 +74,7 @@ pub mod js_bundler { this.map.reserve(files_iter.len); - while let Some(prop) = files_iter.next()? { - let property_value = files_iter.value; - + while let Some((prop, property_value)) = files_iter.next()? { // Parse the value as BlobOrStringOrBuffer using async mode for thread safety. // Async mode `protect()`s any JS-backed buffer; adopt into a // `ThreadSafe` so the guard unprotects + drops at end of iteration. @@ -297,7 +295,7 @@ pub mod js_bundler { } }; - if let Some(target) = object.get_own(global_this, &BunString::static_str("target"))? { + if let Some(target) = object.get_own(global_this, &BunString::static_("target"))? { this.compile_target = compile_target_from_js(global_this, target)?; } @@ -317,7 +315,7 @@ pub mod js_bundler { } if let Some(executable_path) = - object.get_own(global_this, &BunString::static_str("executablePath"))? + object.get_own(global_this, &BunString::static_("executablePath"))? { let slice = executable_path.to_slice(global_this)?; let path_z = bun_core::ZBox::from_bytes(slice.slice()); @@ -340,13 +338,13 @@ pub mod js_bundler { } if let Some(hide_console) = - windows.get_own(global_this, &BunString::static_str("hideConsole"))? + windows.get_own(global_this, &BunString::static_("hideConsole"))? { this.windows_hide_console = hide_console.to_boolean(); } if let Some(windows_icon_path) = - windows.get_own(global_this, &BunString::static_str("icon"))? + windows.get_own(global_this, &BunString::static_("icon"))? { let slice = windows_icon_path.to_slice(global_this)?; let path_z = bun_core::ZBox::from_bytes(slice.slice()); @@ -363,42 +361,42 @@ pub mod js_bundler { } if let Some(windows_title) = - windows.get_own(global_this, &BunString::static_str("title"))? + windows.get_own(global_this, &BunString::static_("title"))? { let slice = windows_title.to_slice(global_this)?; this.windows_title.append_slice_exact(slice.slice())?; } if let Some(windows_publisher) = - windows.get_own(global_this, &BunString::static_str("publisher"))? + windows.get_own(global_this, &BunString::static_("publisher"))? { let slice = windows_publisher.to_slice(global_this)?; this.windows_publisher.append_slice_exact(slice.slice())?; } if let Some(windows_version) = - windows.get_own(global_this, &BunString::static_str("version"))? + windows.get_own(global_this, &BunString::static_("version"))? { let slice = windows_version.to_slice(global_this)?; this.windows_version.append_slice_exact(slice.slice())?; } if let Some(windows_description) = - windows.get_own(global_this, &BunString::static_str("description"))? + windows.get_own(global_this, &BunString::static_("description"))? { let slice = windows_description.to_slice(global_this)?; this.windows_description.append_slice_exact(slice.slice())?; } if let Some(windows_copyright) = - windows.get_own(global_this, &BunString::static_str("copyright"))? + windows.get_own(global_this, &BunString::static_("copyright"))? { let slice = windows_copyright.to_slice(global_this)?; this.windows_copyright.append_slice_exact(slice.slice())?; } } - if let Some(outfile) = object.get_own(global_this, &BunString::static_str("outfile"))? { + if let Some(outfile) = object.get_own(global_this, &BunString::static_("outfile"))? { let slice = outfile.to_slice(global_this)?; this.outfile.append_slice_exact(slice.slice())?; } @@ -813,7 +811,7 @@ pub mod js_bundler { if let Some(entry_points) = entry_points_opt { 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)?; + let slice = entry_point.to_slice(global_this)?; this.entry_points.insert(slice.slice())?; drop(slice); } @@ -842,13 +840,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)?; + let slice = conditions_value.to_slice(global_this)?; 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)?; + let slice = entry_point.to_slice(global_this)?; this.conditions.insert(slice.slice())?; drop(slice); } @@ -932,14 +930,14 @@ pub mod js_bundler { if let Some(externals) = config.get_own_array(global_this, "external")? { 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)?; + let slice = entry_point.to_slice(global_this)?; this.external.insert(slice.slice())?; drop(slice); } } if let Some(allow_unresolved_val) = - config.get_own(global_this, &BunString::static_str("allowUnresolved"))? + config.get_own(global_this, &BunString::static_("allowUnresolved"))? { if !allow_unresolved_val.is_undefined() && !allow_unresolved_val.is_null() { if !(allow_unresolved_val.is_cell() @@ -953,7 +951,7 @@ pub mod js_bundler { if allow_unresolved_val.get_length(global_this)? > 0 { let mut iter = allow_unresolved_val.array_iterator(global_this)?; while let Some(entry) = iter.next()? { - let slice = entry.to_slice_or_null(global_this)?; + let slice = entry.to_slice(global_this)?; this.allow_unresolved .as_mut() .unwrap() @@ -967,7 +965,7 @@ pub mod js_bundler { if let Some(drops) = config.get_own_array(global_this, "drop")? { let mut iter = drops.array_iterator(global_this)?; while let Some(entry) = iter.next()? { - let slice = entry.to_slice_or_null(global_this)?; + let slice = entry.to_slice(global_this)?; this.drop.insert(slice.slice())?; drop(slice); } @@ -976,7 +974,7 @@ pub mod js_bundler { if let Some(features) = config.get_own_array(global_this, "features")? { let mut iter = features.array_iterator(global_this)?; while let Some(entry) = iter.next()? { - let slice = entry.to_slice_or_null(global_this)?; + let slice = entry.to_slice(global_this)?; this.features.insert(slice.slice())?; drop(slice); } @@ -985,7 +983,7 @@ pub mod js_bundler { if let Some(optimize_imports) = config.get_own_array(global_this, "optimizeImports")? { let mut iter = optimize_imports.array_iterator(global_this)?; while let Some(entry) = iter.next()? { - let slice = entry.to_slice_or_null(global_this)?; + let slice = entry.to_slice(global_this)?; this.optimize_imports.insert(slice.slice())?; drop(slice); } @@ -1052,7 +1050,7 @@ pub mod js_bundler { if let Some(define) = config.get_own_object(global_this, "define")? { // SAFETY: `get_own_object` only returns non-null live JSObject*. let define_ref = unsafe { &*define }; - let mut define_iter = jsc::JSPropertyIterator::init( + let define_iter = jsc::JSPropertyIterator::init( global_this, define_ref, jsc::JSPropertyIteratorOptions { @@ -1062,8 +1060,7 @@ pub mod js_bundler { }, )?; - while let Some(prop) = define_iter.next()? { - let property_value = define_iter.value; + while let Some((prop, property_value)) = define_iter.next()? { let value_type = property_value.js_type(); if !value_type.is_string_like() { @@ -1073,27 +1070,26 @@ pub mod js_bundler { ))); } - let mut val = ZigString::init(b""); - property_value.to_zig_string(&mut val, global_this)?; - if val.len == 0 { - val = ZigString::from_utf8(b"\"\""); - } - + let val = property_value.to_js_string_view(global_this)?; let key = prop.to_owned_slice(); - - // value is always cloned - let value = val.to_slice(); + let value = val.to_utf8(); // .insert clones the value, but not the key - this.define.insert(&key, value.slice())?; - drop(value); + this.define.insert( + &key, + if value.slice().is_empty() { + b"\"\"" + } else { + value.slice() + }, + )?; } } if let Some(loaders) = config.get_own_object(global_this, "loader")? { // SAFETY: `get_own_object` only returns non-null live JSObject*. let loaders_ref = unsafe { &*loaders }; - let mut loader_iter = jsc::JSPropertyIterator::init( + let loader_iter = jsc::JSPropertyIterator::init( global_this, loaders_ref, jsc::JSPropertyIteratorOptions { @@ -1115,7 +1111,7 @@ pub mod js_bundler { loader_names.reserve_exact(loader_iter.len); loader_values.reserve_exact(loader_iter.len); - while let Some(prop) = loader_iter.next()? { + while let Some((prop, value)) = loader_iter.next()? { let prop_slice = prop.to_utf8(); if !prop_slice.slice().starts_with(b".") || prop.length() < 2 { return Err(global_this.throw_invalid_arguments(format_args!( @@ -1124,7 +1120,7 @@ pub mod js_bundler { } drop(prop_slice); - loader_values.push(loader_iter.value.to_enum_from_map( + loader_values.push(value.to_enum_from_map( global_this, "loader", &options::LOADER_API_NAMES, @@ -1145,7 +1141,7 @@ pub mod js_bundler { // Parse metafile option: boolean | string | { json?: string, markdown?: string } if let Some(metafile_value) = - config.get_own(global_this, &BunString::static_str("metafile"))? + config.get_own(global_this, &BunString::static_("metafile"))? { if metafile_value.is_boolean() { this.metafile = metafile_value == JSValue::TRUE; @@ -1451,17 +1447,15 @@ pub mod js_bundler { resolve.value = ResolveValue::NoMatch; } else { let global = bv2_plugin(resolve.bv2).global_object(); - // `to_slice_clone` already heap-allocates; `into_vec` moves that - // buffer out instead of allocating a second copy. let path = path_value - .to_slice_clone(global) + .to_bun_string(global) .expect("Unexpected: path is not a string") - .into_vec() + .to_owned_slice() .into_boxed_slice(); let namespace = namespace_value - .to_slice_clone(global) + .to_bun_string(global) .expect("Unexpected: namespace is not a string") - .into_vec() + .to_owned_slice() .into_boxed_slice(); resolve.value = ResolveValue::Success(ResolveSuccess { path, diff --git a/src/runtime/api/JSON5Object.rs b/src/runtime/api/JSON5Object.rs index 0344526b0562..fd99ef0c6c9f 100644 --- a/src/runtime/api/JSON5Object.rs +++ b/src/runtime/api/JSON5Object.rs @@ -1,6 +1,6 @@ use bun_collections::HashMap; use bun_core::StackCheck; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_js_parser::lexer; use bun_jsc::{self as jsc, CallFrame, JSGlobalObject, JSValue, JsError, JsResult, wtf}; use bun_parsers::json5; @@ -108,7 +108,7 @@ enum Space { Minified, Number(u32), /// +1 WTF ref owned for the lifetime of the `Stringifier`. - Str(OwnedString), + Str(bun_core::String), } impl Space { @@ -125,7 +125,7 @@ impl Space { return Ok(Space::Number(if num_f > 10.0 { 10 } else { num_f as u32 })); } if space.is_string() { - let str = OwnedString::new(space.to_bun_string(global)?); + let str = space.to_bun_string(global)?; if str.length() == 0 { return Ok(Space::Minified); } @@ -192,7 +192,7 @@ impl Stringifier { } if unwrapped.is_string() { - let str = OwnedString::new(unwrapped.to_bun_string(global)?); + let str = unwrapped.to_bun_string(global)?; self.append_quoted_string(&str); return Ok(()); } @@ -276,7 +276,7 @@ impl Stringifier { } fn stringify_object(&mut self, global: &JSGlobalObject, value: JSValue) -> StringifyResult<()> { - let mut iter = jsc::JSPropertyIterator::init( + let iter = jsc::JSPropertyIterator::init( global, value.to_object(global)?, jsc::JSPropertyIteratorOptions { @@ -296,11 +296,8 @@ impl Stringifier { match self.space { Space::Minified => { let mut first = true; - while let Some(prop_name) = iter.next()? { - if iter.value.is_undefined() - || iter.value.is_symbol() - || iter.value.is_function() - { + while let Some((prop_name, value)) = iter.next()? { + if value.is_undefined() || value.is_symbol() || value.is_function() { continue; } if !first { @@ -309,17 +306,14 @@ impl Stringifier { first = false; self.append_key(&prop_name); self.builder.append_lchar(b':'); - self.stringify_value(global, iter.value)?; + self.stringify_value(global, value)?; } } Space::Number(_) | Space::Str(_) => { self.indent += 1; let mut first = true; - while let Some(prop_name) = iter.next()? { - if iter.value.is_undefined() - || iter.value.is_symbol() - || iter.value.is_function() - { + while let Some((prop_name, value)) = iter.next()? { + if value.is_undefined() || value.is_symbol() || value.is_function() { continue; } if !first { @@ -329,7 +323,7 @@ impl Stringifier { self.newline(); self.append_key(&prop_name); self.builder.append_latin1(b": "); - self.stringify_value(global, iter.value)?; + self.stringify_value(global, value)?; } self.indent -= 1; if !first { @@ -361,7 +355,7 @@ impl Stringifier { }; if is_identifier { - self.builder.append_string(*name); + self.builder.append_string(name); } else { self.append_quoted_string(name); } @@ -408,13 +402,9 @@ impl Stringifier { } Space::Str(space_str) => { self.builder.append_lchar(b'\n'); - let clamped: BunString = if space_str.length() > 10 { - space_str.substring_with_len(0, 10) - } else { - **space_str - }; + let clamped = space_str.trunc(10); for _ in 0..self.indent { - self.builder.append_string(clamped); + self.builder.append_string(&clamped); } } } diff --git a/src/runtime/api/JSTranspiler.rs b/src/runtime/api/JSTranspiler.rs index 3e92afd91414..eef0ef6efe4a 100644 --- a/src/runtime/api/JSTranspiler.rs +++ b/src/runtime/api/JSTranspiler.rs @@ -30,7 +30,7 @@ use bun_resolver::package_json::{MacroMap, PackageJSON}; use bun_resolver::tsconfig_json::TSConfigJSON; // `bun_schema::api` → schema lives in `bun_options_types::schema::api`. use bun_collections::ArrayHashMapExt; -use bun_core::{OwnedString, String as BunString, ZigString}; +use bun_core::{String as BunString, ZigString}; use bun_options_types::schema::api; // Host-fn re-entrancy: every JS-exposed method takes `&self`; per-field @@ -185,8 +185,7 @@ impl Config { // SAFETY: `define_obj` is a non-null *mut JSObject (just returned by get_object()). let define_obj_ref = unsafe { &*define_obj }; - let mut define_iter = - JSPropertyIterator::init(global, define_obj_ref, PROP_ITER_OPTS)?; + let define_iter = JSPropertyIterator::init(global, define_obj_ref, PROP_ITER_OPTS)?; // `defer define_iter.deinit()` → Drop // `define_iter.i` is the property position, not a dense index of yielded @@ -198,8 +197,7 @@ impl Config { names.reserve_exact(define_iter.len); values.reserve_exact(define_iter.len); - while let Some(prop) = define_iter.next()? { - let property_value = define_iter.value; + while let Some((prop, property_value)) = define_iter.next()? { let value_type = property_value.js_type(); if !value_type.is_string_like() { @@ -210,14 +208,12 @@ impl Config { } names.push(prop.to_owned_slice().into()); - let mut val = ZigString::init(b""); - property_value.to_zig_string(&mut val, global)?; - if val.len == 0 { - val = ZigString::init(b"\"\""); - } - let mut buf = Vec::new(); - write!(&mut buf, "{}", val).expect("unreachable"); - values.push(buf.into_boxed_slice()); + let val = property_value.to_js_string_view(global)?; + values.push(if val.is_empty() { + Box::from(&b"\"\""[..]) + } else { + val.to_owned_slice().into_boxed_slice() + }); } self.transform.define = Some(api::StringMap { @@ -235,16 +231,11 @@ impl Config { let toplevel_type = external.js_type(); if toplevel_type.is_string_like() { - let mut zig_str = ZigString::init(b""); - external.to_zig_string(&mut zig_str, global)?; - if zig_str.len == 0 { + let str = external.to_bun_string(global)?; + if str.is_empty() { break 'external; } - let mut single_external: Vec> = Vec::with_capacity(1); - let mut buf = Vec::new(); - write!(&mut buf, "{}", zig_str).expect("unreachable"); - single_external.push(buf.into_boxed_slice()); - self.transform.external = single_external; + self.transform.external = vec![str.to_owned_slice().into_boxed_slice()]; } else if toplevel_type.is_array() { let count = external.get_length(global)?; if count == 0 { @@ -260,14 +251,11 @@ impl Config { ))); } - let mut zig_str = ZigString::init(b""); - entry.to_zig_string(&mut zig_str, global)?; - if zig_str.len == 0 { + let str = entry.to_bun_string(global)?; + if str.is_empty() { continue; } - let mut buf = Vec::new(); - write!(&mut buf, "{}", zig_str).expect("unreachable"); - externals.push(buf.into_boxed_slice()); + externals.push(str.to_owned_slice().into_boxed_slice()); } self.transform.external = externals; @@ -303,7 +291,6 @@ impl Config { break 'tsconfig; } let kind = tsconfig.js_type(); - let mut out = OwnedString::new(BunString::empty()); if kind.is_array() { return Err(global.throw_invalid_arguments(format_args!( @@ -311,12 +298,12 @@ impl Config { ))); } - if !kind.is_string_like() { + let out = if !kind.is_string_like() { // Use jsonStringifyFast for SIMD-optimized serialization - tsconfig.json_stringify_fast(global, &mut out)?; + tsconfig.json_stringify_fast(global)? } else { - out = OwnedString::new(tsconfig.to_bun_string(global)?); - } + tsconfig.to_bun_string(global)? + }; if out.is_empty() { break 'tsconfig; @@ -355,14 +342,13 @@ impl Config { ); } - let mut out = OwnedString::new(BunString::empty()); // TODO: write a converter between JSC types and Bun AST types - if is_object { + let out = if is_object { // Use jsonStringifyFast for SIMD-optimized serialization - macros.json_stringify_fast(global, &mut out)?; + macros.json_stringify_fast(global)? } else { - out = OwnedString::new(macros.to_bun_string(global)?); - } + macros.to_bun_string(global)? + }; if out.is_empty() { break 'macros; @@ -508,8 +494,8 @@ impl Config { if !value.is_string() { continue; } - let str = value.get_zig_string(global)?; - if str.len == 0 { + let str = value.to_js_string_view(global)?; + if str.is_empty() { continue; } // The capacity bound is sized from UTF-16 code-unit @@ -548,7 +534,7 @@ impl Config { // SAFETY: `replace_obj` is non-null (just returned by get_object()). let replace_obj_ref = unsafe { &*replace_obj }; - let mut iter = JSPropertyIterator::init(global, replace_obj_ref, PROP_ITER_OPTS)?; + let iter = JSPropertyIterator::init(global, replace_obj_ref, PROP_ITER_OPTS)?; if iter.len > 0 { bun_core::handle_oom(replacements.ensure_unused_capacity(iter.len)); @@ -560,8 +546,7 @@ impl Config { // early return drops it — freeing the `Box<[u8]>` keys and // clearing the map. - while let Some(key_) = iter.next()? { - let value = iter.value; + while let Some((key_, value)) = iter.next()? { if value.is_empty() { continue; } @@ -593,8 +578,7 @@ impl Config { export_replacement_value(replacement_value, global, arena)? { let replacement_key = value.get_index(global, 0)?; - let slice = - OwnedString::new(replacement_key.to_bun_string(global)?); + let slice = replacement_key.to_bun_string(global)?; let replacement_name = slice.to_owned_slice(); if !JSLexer::is_identifier(&replacement_name) { @@ -886,7 +870,10 @@ impl TransformTask { } fn finish(&mut self, promise: &mut JSPromise, global: &JSGlobalObject) -> JsResult<()> { - promise.settle(global, self.output_code.transfer_to_js(global)) + promise.settle( + global, + core::mem::take(&mut self.output_code).into_js(global), + ) } } @@ -926,14 +913,13 @@ fn export_replacement_value( } if value.is_string() { - let zig_str = value.get_zig_string(global)?; - let mut buf = Vec::new(); - write!(&mut buf, "{}", zig_str).expect("unreachable"); + let str = value.to_js_string_view(global)?; + let utf8 = str.to_utf8(); // Bump-allocate so the bytes // live as long as the JSTranspiler arena that owns the resulting Expr; // `E::EString::init` erases the borrow to `'static` per the AST // crate's `Str` convention (see ast/E.rs). - let data = arena.alloc_slice_copy(&buf); + let data = arena.alloc_slice_copy(utf8.slice()); return Ok(Some(Expr::init( bun_ast::E::EString::init(data), bun_ast::Loc::EMPTY, diff --git a/src/runtime/api/TOMLObject.rs b/src/runtime/api/TOMLObject.rs index 313b0efca6d8..db0ada6bda03 100644 --- a/src/runtime/api/TOMLObject.rs +++ b/src/runtime/api/TOMLObject.rs @@ -1,6 +1,6 @@ use bun_collections::HashMap; use bun_core::StackCheck; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_jsc::{ self as jsc, CallFrame, JSGlobalObject, JSValue, JsError, JsResult, TemporalType, wtf, }; @@ -86,7 +86,6 @@ fn stringify(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { stack_check: StackCheck::init(), builder: wtf::StringBuilder::init(), visiting: HashMap::default(), - path: Vec::new(), wrote: false, }; @@ -139,19 +138,21 @@ struct Stringifier { // live on the native stack via the `stringify` recursion chain, so the // conservative GC scan keeps them alive. visiting: HashMap, - /// Header path of the table currently being emitted. Entries are - /// borrowed, not ref-counted: each is pushed and popped within the one - /// `JSPropertyIterator` loop body whose iterator keeps the name alive - /// (the iterator's strings carry no extra reference). - path: Vec, /// Whether any line has been written (controls blank lines before headers). wrote: bool, } +/// Header path of the table being emitted: a parent-linked chain of +/// iterator-borrowed keys on the `stringify_table_body` recursion stack. +struct Path<'p> { + parent: Option<&'p Path<'p>>, + key: &'p BunString, +} + impl Stringifier { fn stringify_root(&mut self, global: &JSGlobalObject, root: JSValue) -> StringifyResult<()> { self.mark_visiting(global, root)?; - self.stringify_table_body(global, root, false)?; + self.stringify_table_body(global, root, None, false)?; self.visiting.remove(&root); Ok(()) } @@ -213,6 +214,7 @@ impl Stringifier { &mut self, global: &JSGlobalObject, table: JSValue, + path: Option<&Path<'_>>, own_header: bool, ) -> StringifyResult<()> { if !self.stack_check.is_safe_to_recurse() { @@ -227,10 +229,9 @@ impl Stringifier { }; // Pass 1: keyvals. - let mut iter = - jsc::JSPropertyIterator::init(global, table.to_object(global)?, iter_options)?; - while let Some(prop_name) = iter.next()? { - let value = iter.value.unwrap_boxed_primitive(global)?; + let iter = jsc::JSPropertyIterator::init(global, table.to_object(global)?, iter_options)?; + while let Some((prop_name, prop_value)) = iter.next()? { + let value = prop_value.unwrap_boxed_primitive(global)?; if value.is_null() { return Err(self.err_null_value(global, &prop_name)); } @@ -241,7 +242,7 @@ impl Stringifier { }; if header_pending { header_pending = false; - self.append_header(false); + self.append_header(path, false); } self.append_key_segment(&prop_name); self.builder.append_latin1(b" = "); @@ -252,24 +253,28 @@ impl Stringifier { // Pass 2: sections. Values are re-read; an array-of-tables element // that is no longer a plain object during emission gets an error. - let mut iter = - jsc::JSPropertyIterator::init(global, table.to_object(global)?, iter_options)?; - while let Some(prop_name) = iter.next()? { - let value = iter.value.unwrap_boxed_primitive(global)?; + let iter = jsc::JSPropertyIterator::init(global, table.to_object(global)?, iter_options)?; + while let Some((prop_name, prop_value)) = iter.next()? { + let value = prop_value.unwrap_boxed_primitive(global)?; match self.layout_of(global, value)? { Layout::Keyval | Layout::TemporalKeyval(_) | Layout::Skip => {} Layout::Table => { header_pending = false; self.mark_visiting(global, value)?; - self.path.push(prop_name); - self.stringify_table_body(global, value, true)?; - self.path.pop(); + let child = Path { + parent: path, + key: &prop_name, + }; + self.stringify_table_body(global, value, Some(&child), true)?; self.visiting.remove(&value); } Layout::ArrayOfTables => { header_pending = false; self.mark_visiting(global, value)?; - self.path.push(prop_name); + let child = Path { + parent: path, + key: &prop_name, + }; let mut items = value.array_iterator(global)?; while let Some(item) = items.next()? { let item = item.unwrap_boxed_primitive(global)?; @@ -279,15 +284,13 @@ impl Stringifier { || item.is_function() || temporal_object_type(item).is_some() { - self.path.pop(); return Err(self.err_changed(global)); } self.mark_visiting(global, item)?; - self.append_header(true); - self.stringify_table_body(global, item, false)?; + self.append_header(Some(&child), true); + self.stringify_table_body(global, item, Some(&child), false)?; self.visiting.remove(&item); } - self.path.pop(); self.visiting.remove(&value); } } @@ -295,7 +298,7 @@ impl Stringifier { // An empty table is materialized only by its header. if header_pending { - self.append_header(false); + self.append_header(path, false); } Ok(()) @@ -335,7 +338,7 @@ impl Stringifier { } if value.is_string() { - let str = OwnedString::new(value.to_bun_string(global)?); + let str = value.to_bun_string(global)?; self.append_basic_quoted(&str); return Ok(()); } @@ -371,7 +374,7 @@ impl Stringifier { // A plain object inside an inline context becomes an inline table. self.mark_visiting(global, value)?; - let mut iter = jsc::JSPropertyIterator::init( + let iter = jsc::JSPropertyIterator::init( global, value.to_object(global)?, jsc::JSPropertyIteratorOptions { @@ -381,8 +384,8 @@ impl Stringifier { }, )?; let mut first = true; - while let Some(prop_name) = iter.next()? { - let prop_value = iter.value.unwrap_boxed_primitive(global)?; + while let Some((prop_name, value)) = iter.next()? { + let prop_value = value.unwrap_boxed_primitive(global)?; if prop_value.is_undefined() || prop_value.is_symbol() || prop_value.is_function() { continue; } @@ -404,34 +407,33 @@ impl Stringifier { // ── output pieces ────────────────────────────────────────────────────── - /// `[a.b.c]` or `[[a.b.c]]` from `self.path`, preceded by a blank line - /// when the document already has content. - fn append_header(&mut self, array_of_tables: bool) { + /// `[a.b.c]` or `[[a.b.c]]`, preceded by a blank line when the document + /// already has content. + fn append_header(&mut self, path: Option<&Path<'_>>, array_of_tables: bool) { if self.wrote { self.builder.append_lchar(b'\n'); } self.builder .append_latin1(if array_of_tables { b"[[" } else { b"[" }); - for (i, seg) in self.path.iter().enumerate() { - if i > 0 { - self.builder.append_lchar(b'.'); - } - // Inlined `append_key_segment` to avoid borrowing `self.path` - // across a `&mut self` call. - if is_bare_key(seg) { - self.builder.append_string(*seg); - } else { - append_basic_quoted_to(&mut self.builder, seg); - } + if let Some(path) = path { + self.append_path(path); } self.builder .append_latin1(if array_of_tables { b"]]\n" } else { b"]\n" }); self.wrote = true; } + fn append_path(&mut self, path: &Path<'_>) { + if let Some(parent) = path.parent { + self.append_path(parent); + self.builder.append_lchar(b'.'); + } + self.append_key_segment(path.key); + } + fn append_key_segment(&mut self, name: &BunString) { if is_bare_key(name) { - self.builder.append_string(*name); + self.builder.append_string(name); } else { append_basic_quoted_to(&mut self.builder, name); } @@ -554,11 +556,9 @@ impl Stringifier { // ── errors ───────────────────────────────────────────────────────────── fn err_null_value(&mut self, global: &JSGlobalObject, key: &BunString) -> StringifyError { - let key_utf8 = key.to_utf8_bytes(); global .throw(format_args!( - "TOML cannot represent null (key '{}'); remove the key or use a sentinel value", - bstr::BStr::new(&key_utf8) + "TOML cannot represent null (key '{key}'); remove the key or use a sentinel value", )) .into() } diff --git a/src/runtime/api/XMLObject.rs b/src/runtime/api/XMLObject.rs index f3f9e562f6aa..d8b58ba7b085 100644 --- a/src/runtime/api/XMLObject.rs +++ b/src/runtime/api/XMLObject.rs @@ -11,7 +11,7 @@ //! accepts either shape and always emits well-formed XML or throws. use bun_collections::HashMap; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_core::{StackCheck, strings}; use bun_js_parser_jsc::ExprJsc; use bun_jsc::{self as jsc, CallFrame, JSGlobalObject, JSValue, JsError, JsResult, wtf}; @@ -208,8 +208,7 @@ type StringifyResult = Result; enum Space { Minified, Number(u32), - /// +1 WTF ref owned for the lifetime of the `Stringifier`. - Str(OwnedString), + Str(bun_core::String), } impl Space { @@ -224,7 +223,7 @@ impl Space { return Ok(Space::Number(if n > 10.0 { 10 } else { n as u32 })); } if space.is_string() { - let str = OwnedString::new(space.to_bun_string(global)?); + let str = space.to_bun_string(global)?; if str.length() == 0 { return Ok(Space::Minified); } @@ -244,7 +243,7 @@ enum Scalar { Skip, /// An empty element / absent text (null). Empty, - Text(OwnedString), + Text(bun_core::String), } struct Stringifier { @@ -308,7 +307,7 @@ impl Stringifier { name: Option, ) -> StringifyResult<()> { let name = match name { - Some(name) if name.is_string() => OwnedString::new(name.to_bun_string(global)?), + Some(name) if name.is_string() => name.to_bun_string(global)?, _ => { return Err(global .throw(format_args!("XML.stringify: element children must be strings, {{ name, attributes, children }} elements, {{ comment }} or {{ target, data }}")) @@ -318,7 +317,7 @@ impl Stringifier { self.check_name(global, &name, "element")?; self.builder.append_lchar(b'<'); - self.builder.append_string(*name); + self.builder.append_string(&name); if let Some(attributes) = node.get(global, "attributes")? { if !attributes.is_null() { @@ -329,13 +328,13 @@ impl Stringifier { )) .into()); } - let mut iter = jsc::JSPropertyIterator::init( + let iter = jsc::JSPropertyIterator::init( global, attributes.to_object(global)?, iter_options(), )?; - while let Some(attr_name) = iter.next()? { - match self.scalar(global, iter.value, "an attribute value")? { + while let Some((attr_name, prop_value)) = iter.next()? { + match self.scalar(global, prop_value, "an attribute value")? { Scalar::Skip | Scalar::Empty => {} Scalar::Text(text) => self.append_attribute(global, &attr_name, &text)?, } @@ -421,7 +420,7 @@ impl Stringifier { self.indent -= 1; self.newline(); } - self.append_end_tag(*name); + self.append_end_tag(&name); Ok(()) } @@ -443,7 +442,7 @@ impl Stringifier { )) .into()); } - let text = OwnedString::new(comment.to_bun_string(global)?); + let text = comment.to_bun_string(global)?; let len = text.length(); let mut i = 0; let mut prev_dash = false; @@ -468,7 +467,7 @@ impl Stringifier { prev_dash = cp == 0x2D; } self.builder.append_latin1(b""); return Ok(true); } @@ -480,7 +479,7 @@ impl Stringifier { )) .into()); } - let target = OwnedString::new(target.to_bun_string(global)?); + let target = target.to_bun_string(global)?; self.check_name(global, &target, "processing instruction target")?; if target.length() == 3 { let lower = |i| target.char_at(i) | 0x20; @@ -492,12 +491,12 @@ impl Stringifier { } } self.builder.append_latin1(b" {} Some(data) if data.is_null() => {} Some(data) if data.is_string() => { - let data = OwnedString::new(data.to_bun_string(global)?); + let data = data.to_bun_string(global)?; let len = data.length(); if len > 0 { let mut i = 0; @@ -514,7 +513,7 @@ impl Stringifier { prev_q = cp == 0x3F; } self.builder.append_lchar(b' '); - self.builder.append_string(*data); + self.builder.append_string(&data); } } Some(_) => { @@ -550,11 +549,11 @@ impl Stringifier { global: &JSGlobalObject, document: JSValue, ) -> StringifyResult<()> { - let mut root: Option<(OwnedString, JSValue)> = None; - let mut iter = + let mut root: Option<(bun_core::StringView<'_>, JSValue)> = None; + let iter = jsc::JSPropertyIterator::init(global, document.to_object(global)?, iter_options())?; - while let Some(key) = iter.next()? { - let value = iter.value.unwrap_boxed_primitive(global)?; + while let Some((key, prop_value)) = iter.next()? { + let value = prop_value.unwrap_boxed_primitive(global)?; if skipped(value) { continue; } @@ -576,7 +575,7 @@ impl Stringifier { .throw(format_args!("XML.stringify: the root element '{}' cannot be an array (an XML document has exactly one root element)", key)) .into()); } - root = Some((OwnedString::new(key.dupe_ref()), value)); + root = Some((key, value)); } let Some((name, value)) = root else { return Err(global @@ -677,14 +676,14 @@ impl Stringifier { self.check_name(global, name, "element")?; match self.scalar(global, value, "element content")? { Scalar::Skip => {} - Scalar::Empty => self.append_empty_element(*name), - Scalar::Text(text) if text.length() == 0 => self.append_empty_element(*name), + Scalar::Empty => self.append_empty_element(name), + Scalar::Text(text) if text.length() == 0 => self.append_empty_element(name), Scalar::Text(text) => { self.builder.append_lchar(b'<'); - self.builder.append_string(*name); + self.builder.append_string(name); self.builder.append_lchar(b'>'); self.append_text(global, &text)?; - self.append_end_tag(*name); + self.append_end_tag(name); } } Ok(()) @@ -702,12 +701,11 @@ impl Stringifier { // Pass 1: the start tag with `@` attributes; note what content follows. self.builder.append_lchar(b'<'); - self.builder.append_string(*name); + self.builder.append_string(name); let mut has_elements = false; let mut has_text = false; - let mut iter = jsc::JSPropertyIterator::init(global, object, iter_options())?; - while let Some(key) = iter.next()? { - let child = iter.value; + let iter = jsc::JSPropertyIterator::init(global, object, iter_options())?; + while let Some((key, child)) = iter.next()? { if skipped(child) { continue; } @@ -744,9 +742,8 @@ impl Stringifier { if pretty { self.indent += 1; } - let mut iter = jsc::JSPropertyIterator::init(global, object, iter_options())?; - while let Some(key) = iter.next()? { - let child = iter.value; + let iter = jsc::JSPropertyIterator::init(global, object, iter_options())?; + while let Some((key, child)) = iter.next()? { if skipped(child) || key.has_prefix_comptime(b"@") { continue; } @@ -768,7 +765,7 @@ impl Stringifier { self.indent -= 1; self.newline(); } - self.append_end_tag(*name); + self.append_end_tag(name); Ok(()) } @@ -789,7 +786,7 @@ impl Stringifier { return Ok(Scalar::Empty); } if value.is_string() || value.is_number() || value.is_boolean() || value.is_big_int() { - return Ok(Scalar::Text(OwnedString::new(value.to_bun_string(global)?))); + return Ok(Scalar::Text(value.to_bun_string(global)?)); } if value.is_date() { let mut buf = [0u8; 64]; @@ -800,7 +797,7 @@ impl Stringifier { )) .into()); }; - return Ok(Scalar::Text(OwnedString::new(BunString::clone_utf8(iso)))); + return Ok(Scalar::Text(BunString::clone_utf8(iso))); } Err(global .throw(format_args!( @@ -844,13 +841,13 @@ impl Stringifier { // ── output pieces ────────────────────────────────────────────────────── - fn append_empty_element(&mut self, name: BunString) { + fn append_empty_element(&mut self, name: &BunString) { self.builder.append_lchar(b'<'); self.builder.append_string(name); self.builder.append_latin1(b"/>"); } - fn append_end_tag(&mut self, name: BunString) { + fn append_end_tag(&mut self, name: &BunString) { self.builder.append_latin1(b"'); @@ -867,7 +864,7 @@ impl Stringifier { ) -> StringifyResult<()> { self.check_name(global, name, "attribute")?; self.builder.append_lchar(b' '); - self.builder.append_string(*name); + self.builder.append_string(name); self.builder.append_latin1(b"=\""); self.append_escaped(global, value, true)?; self.builder.append_lchar(b'"'); @@ -928,13 +925,9 @@ impl Stringifier { } Space::Str(s) => { self.builder.append_lchar(b'\n'); - let clamped: BunString = if s.length() > 10 { - s.substring_with_len(0, 10) - } else { - **s - }; + let clamped = s.trunc(10); for _ in 0..self.indent { - self.builder.append_string(clamped); + self.builder.append_string(&clamped); } } } diff --git a/src/runtime/api/YAMLObject.rs b/src/runtime/api/YAMLObject.rs index 2061c6321c5d..e478735bcbd4 100644 --- a/src/runtime/api/YAMLObject.rs +++ b/src/runtime/api/YAMLObject.rs @@ -4,7 +4,7 @@ use core::ffi::c_void; use bun_ast::{Expr, expr::Data as ExprData}; use bun_collections::{HashMap, StringHashMap}; use bun_core::StackCheck; -use bun_core::{OwnedString, String as BunString}; +use bun_core::String as BunString; use bun_jsc::{ self as jsc, CallFrame, JSGlobalObject, JSPropertyIterator, JSPropertyIteratorOptions, JSValue, JsError, JsResult, MarkedArgumentBuffer, wtf, @@ -65,8 +65,7 @@ struct Stringifier { enum Space { Minified, Number(u32), - /// +1 WTF ref owned for the lifetime of the `Stringifier`. - Str(OwnedString), + Str(bun_core::String), } impl Space { @@ -84,7 +83,7 @@ impl Space { } if space.is_string() { - let str = OwnedString::new(space.to_bun_string(global)?); + let str = space.to_bun_string(global)?; if str.length() == 0 { return Ok(Space::Minified); } @@ -115,7 +114,7 @@ impl Default for AnchorAlias { } impl AnchorAlias { - fn init(origin: ValueOrigin) -> AnchorAlias { + fn init(origin: ValueOrigin<'_>) -> AnchorAlias { AnchorAlias { anchored: false, used: false, @@ -123,7 +122,7 @@ impl AnchorAlias { ValueOrigin::Root => AnchorAliasName::Root, ValueOrigin::ArrayItem => AnchorAliasName::ArrayItem(0), ValueOrigin::PropValue(prop_name) => AnchorAliasName::PropValue { - prop_name, + prop_name: (*prop_name).clone(), counter: 0, }, }, @@ -143,10 +142,10 @@ pub(crate) enum AnchorAliasName { } #[derive(Clone, Copy)] -pub(crate) enum ValueOrigin { +pub(crate) enum ValueOrigin<'a> { Root, ArrayItem, - PropValue(BunString), + PropValue(&'a BunString), } #[derive(thiserror::Error, strum::IntoStaticStr, Debug)] @@ -202,14 +201,11 @@ impl Stringifier { }) } - // deinit: all fields have Drop (`space: Space::Str` holds an - // `OwnedString`); no explicit impl needed. - fn find_anchors_and_aliases( &mut self, global: &JSGlobalObject, value: JSValue, - origin: ValueOrigin, + origin: ValueOrigin<'_>, ) -> Result<(), StringifyError> { if !self.stack_check.is_safe_to_recurse() { return Err(StringifyError::StackOverflow); @@ -296,7 +292,7 @@ impl Stringifier { } // const generics: - let mut iter = JSPropertyIterator::init( + let iter = JSPropertyIterator::init( global, unwrapped.to_object(global)?, JSPropertyIteratorOptions { @@ -306,11 +302,11 @@ impl Stringifier { }, )?; - while let Some(prop_name) = iter.next()? { - if iter.value.is_undefined() || iter.value.is_symbol() || iter.value.is_function() { + while let Some((prop_name, value)) = iter.next()? { + if value.is_undefined() || value.is_symbol() || value.is_function() { continue; } - self.find_anchors_and_aliases(global, iter.value, ValueOrigin::PropValue(prop_name))?; + self.find_anchors_and_aliases(global, value, ValueOrigin::PropValue(&prop_name))?; } Ok(()) @@ -377,7 +373,7 @@ impl Stringifier { } if unwrapped.is_string() { - let value_str = OwnedString::new(unwrapped.to_bun_string(global)?); + let value_str = unwrapped.to_bun_string(global)?; self.append_string(&value_str); return Ok(()); } @@ -413,7 +409,7 @@ impl Stringifier { self.builder.append_latin1(b"value"); self.builder.append_usize(*counter); } else { - self.builder.append_string(*prop_name); + self.builder.append_string(prop_name); if *counter != 0 { self.builder.append_usize(*counter); } @@ -493,7 +489,7 @@ impl Stringifier { } // const generics: - let mut iter = JSPropertyIterator::init( + let iter = JSPropertyIterator::init( global, unwrapped.to_object(global)?, JSPropertyIteratorOptions { @@ -512,11 +508,8 @@ impl Stringifier { Space::Minified => { self.builder.append_lchar(b'{'); let mut first = true; - while let Some(prop_name) = iter.next()? { - if iter.value.is_undefined() - || iter.value.is_symbol() - || iter.value.is_function() - { + while let Some((prop_name, value)) = iter.next()? { + if value.is_undefined() || value.is_symbol() || value.is_function() { continue; } @@ -528,7 +521,7 @@ impl Stringifier { self.append_string(&prop_name); self.builder.append_latin1(b": "); - self.stringify(global, iter.value)?; + self.stringify(global, value)?; } self.builder.append_lchar(b'}'); } @@ -536,11 +529,8 @@ impl Stringifier { self.builder.ensure_unused_capacity(iter.len * b": ".len()); let mut first = true; - while let Some(prop_name) = iter.next()? { - if iter.value.is_undefined() - || iter.value.is_symbol() - || iter.value.is_function() - { + while let Some((prop_name, value)) = iter.next()? { + if value.is_undefined() || value.is_symbol() || value.is_function() { continue; } @@ -554,7 +544,7 @@ impl Stringifier { self.indent += 1; - let prop_value = iter.value.unwrap_boxed_primitive(global)?; + let prop_value = value.unwrap_boxed_primitive(global)?; if prop_value_needs_newline(prop_value) { self.newline(); } @@ -588,16 +578,12 @@ impl Stringifier { Space::Str(space_str) => { self.builder.append_lchar(b'\n'); - let clamped: BunString = if space_str.length() > 10 { - space_str.substring_with_len(0, 10) - } else { - **space_str - }; + let clamped = space_str.trunc(10); self.builder .ensure_unused_capacity(indent_count * clamped.length()); for _ in 0..indent_count { - self.builder.append_string(clamped); + self.builder.append_string(&clamped); } } } @@ -668,7 +654,7 @@ impl Stringifier { self.append_double_quoted_string(str); return; } - self.builder.append_string(*str); + self.builder.append_string(str); } } @@ -1201,7 +1187,7 @@ impl<'a> ParserCtx<'a> { let key = self.to_js(args, key_expr)?; let value = self.to_js(args, value_expr)?; - let key_str = OwnedString::new(key.to_bun_string(self.global)?); + let key_str = key.to_bun_string(self.global)?; obj.put_may_be_index(self.global, &key_str, value)?; } diff --git a/src/runtime/api/bun/h2_frame_parser.rs b/src/runtime/api/bun/h2_frame_parser.rs index d799caf87e30..c27960a1fdd1 100644 --- a/src/runtime/api/bun/h2_frame_parser.rs +++ b/src/runtime/api/bun/h2_frame_parser.rs @@ -3689,11 +3689,9 @@ impl crate::api::h2::connection::Sink for H2FrameParser { if !self.custom_settings.get().is_empty() { let custom = JSValue::create_empty_object(&g, self.custom_settings.get().len()); for (id, value) in self.custom_settings.get().iter() { - // Custom-setting ids are numeric property keys: route through the index-aware put. - let key = bun_core::String::clone_utf8(format!("{id}").as_bytes()); // Left pending: the engine stops before the next frame // (`Sink::should_stop`) and `read()`/`on_native_read` return it. - let put = custom.put_may_be_index(&g, &key, JSValue::js_number(*value as f64)); + let put = custom.put_index(&g, u32::from(*id), JSValue::js_number(*value as f64)); let Some(()) = self.or_stop(put) else { return; }; @@ -3747,11 +3745,9 @@ impl crate::api::h2::connection::Sink for H2FrameParser { if !self.remote_custom_settings.get().is_empty() { let custom = JSValue::create_empty_object(&g, self.remote_custom_settings.get().len()); for (id, value) in self.remote_custom_settings.get().iter() { - // Custom-setting ids are numeric property keys: route through the index-aware put. - let key = bun_core::String::clone_utf8(format!("{id}").as_bytes()); // Left pending: the engine stops before the next frame // (`Sink::should_stop`) and `read()`/`on_native_read` return it. - let put = custom.put_may_be_index(&g, &key, JSValue::js_number(*value as f64)); + let put = custom.put_index(&g, u32::from(*id), JSValue::js_number(*value as f64)); let Some(()) = self.or_stop(put) else { return; }; @@ -4311,7 +4307,7 @@ impl H2FrameParser { }; let mut count: usize = 0; - let mut iter = bun_jsc::JSPropertyIterator::init( + let iter = bun_jsc::JSPropertyIterator::init( global_object, custom_settings_obj, bun_jsc::JSPropertyIteratorOptions { @@ -4321,7 +4317,7 @@ impl H2FrameParser { }, )?; - while let Some(prop_name) = iter.next()? { + while let Some((prop_name, setting_value)) = iter.next()? { count += 1; if count > MAX_CUSTOM_SETTINGS { return global_object @@ -4353,7 +4349,6 @@ impl H2FrameParser { } // Validate setting value is in range [0, 2^32-1] - let setting_value = iter.value; if setting_value.is_number() { let value = setting_value.as_number(); if value < 0.0 || value > MAX_HEADER_TABLE_SIZE_F64 { @@ -5622,7 +5617,7 @@ impl H2FrameParser { // max header name length for lshpack let mut name_buffer = [0u8; 4096]; - let mut iter = bun_jsc::JSPropertyIterator::init( + let iter = bun_jsc::JSPropertyIterator::init( global_object, headers_obj, bun_jsc::JSPropertyIteratorOptions { @@ -5635,7 +5630,7 @@ impl H2FrameParser { let mut single_value_headers = [false; SINGLE_VALUE_HEADERS_LEN]; // Encode trailer headers using HPACK - while let Some(header_name) = iter.next()? { + while let Some((header_name, js_value)) = iter.next()? { if header_name.length() == 0 { continue; } @@ -5654,7 +5649,6 @@ impl H2FrameParser { return Err(global_object.throw_value(exception)); } - let js_value = iter.value; if js_value.is_undefined_or_null() { let exception = global_object.to_type_error( bun_jsc::ErrorCode::HTTP2_INVALID_HEADER_VALUE, @@ -5759,7 +5753,7 @@ impl H2FrameParser { return Err(global_object.throw_value(exception)); } - let value_str = item.to_js_string(global_object)?; + let value_view = item.to_js_string_view(global_object)?; // All-digit names can't be passed to get_truthy (integer-index-like names // trip a debug assert in getIfPropertyExistsImpl) and can never be sensitive. @@ -5772,7 +5766,7 @@ impl H2FrameParser { } }; - let value_slice = value_str.to_slice(global_object)?; + let value_slice = value_view.to_utf8(); let value = value_slice.slice(); if let Some(ret) = handle_encode(this, value, never_index)? { @@ -5793,7 +5787,7 @@ impl H2FrameParser { } single_value_headers[idx] = true; } - let value_str = js_value.to_js_string(global_object)?; + let value_view = js_value.to_js_string_view(global_object)?; // All-digit names can't be passed to get_truthy (integer-index-like names trip // a debug assert in getIfPropertyExistsImpl) and can never be sensitive. @@ -5806,7 +5800,7 @@ impl H2FrameParser { } }; - let value_slice = value_str.to_slice(global_object)?; + let value_slice = value_view.to_utf8(); let value = value_slice.slice(); bun_output::scoped_log!( H2FrameParser, @@ -6110,7 +6104,7 @@ impl H2FrameParser { // A PUSH_PROMISE carries a REQUEST, so request pseudo-headers are valid even on the server. // Pseudo-headers must be encoded first, so iterate twice. for ignore_pseudo_headers in 0..2usize { - let mut iter = bun_jsc::JSPropertyIterator::init( + let iter = bun_jsc::JSPropertyIterator::init( global_object, headers_obj, bun_jsc::JSPropertyIteratorOptions { @@ -6119,7 +6113,7 @@ impl H2FrameParser { ..Default::default() }, )?; - while let Some(header_name) = iter.next()? { + while let Some((header_name, js_value)) = iter.next()? { if header_name.length() == 0 { continue; } @@ -6156,7 +6150,6 @@ impl H2FrameParser { } else if ignore_pseudo_headers == 0 { continue; } - let js_value = iter.value; if js_value.is_empty_or_undefined_or_null() { continue; } @@ -6171,8 +6164,8 @@ impl H2FrameParser { } }; let mut encode_value = |item: JSValue| -> JsResult> { - let value_str = item.to_js_string(global_object)?; - let value_slice = value_str.to_slice(global_object)?; + let value_view = item.to_js_string_view(global_object)?; + let value_slice = value_view.to_utf8(); let value = value_slice.slice(); if !is_valid_header_value(value) { return Err(global_object @@ -6576,8 +6569,8 @@ impl H2FrameParser { continue; } - let name_str = name_js.to_js_string(global_object)?; - let name_slice = name_str.to_slice(global_object)?; + let name_view = name_js.to_js_string_view(global_object)?; + let name_slice = name_view.to_utf8(); let name = name_slice.slice(); if name.is_empty() { continue; @@ -6636,7 +6629,7 @@ impl H2FrameParser { single_value_headers[idx] = true; } - let value_str = value_js.to_js_string(global_object)?; + let value_view = value_js.to_js_string_view(global_object)?; let never_index = if Self::is_index_like_name(validated_name) { false @@ -6647,7 +6640,7 @@ impl H2FrameParser { } }; - let value_slice = value_str.to_slice(global_object)?; + let value_slice = value_view.to_utf8(); let value = value_slice.slice(); if !is_valid_header_value(value) { return Err(global_object @@ -6701,7 +6694,7 @@ impl H2FrameParser { }) { // Note: `bun_jsc::JSPropertyIterator` (runtime-options variant) lacks `.reset()`; // re-initialize per pass instead — the observable property walk is the same. - let mut iter = bun_jsc::JSPropertyIterator::init( + let iter = bun_jsc::JSPropertyIterator::init( global_object, headers_obj, bun_jsc::JSPropertyIteratorOptions { @@ -6711,7 +6704,7 @@ impl H2FrameParser { }, )?; - while let Some(header_name) = iter.next()? { + while let Some((header_name, js_value)) = iter.next()? { if header_name.length() == 0 { continue; } @@ -6767,7 +6760,6 @@ impl H2FrameParser { continue; } - let js_value = iter.value; if js_value.is_undefined_or_null() { let exception = global_object.to_type_error( bun_jsc::ErrorCode::HTTP2_INVALID_HEADER_VALUE, @@ -6807,7 +6799,7 @@ impl H2FrameParser { .throw()); } - let value_str = item.to_js_string(global_object)?; + let value_view = item.to_js_string_view(global_object)?; let never_index = if Self::is_index_like_name(validated_name) { false @@ -6818,7 +6810,7 @@ impl H2FrameParser { } }; - let value_slice = value_str.to_slice(global_object)?; + let value_slice = value_view.to_utf8(); let value = value_slice.slice(); if !is_valid_header_value(value) { return Err(global_object @@ -6877,7 +6869,7 @@ impl H2FrameParser { } single_value_headers[idx] = true; } - let value_str = js_value.to_js_string(global_object)?; + let value_view = js_value.to_js_string_view(global_object)?; let never_index = if Self::is_index_like_name(validated_name) { false @@ -6888,7 +6880,7 @@ impl H2FrameParser { } }; - let value_slice = value_str.to_slice(global_object)?; + let value_slice = value_view.to_utf8(); let value = value_slice.slice(); if !is_valid_header_value(value) { return Err(global_object diff --git a/src/runtime/api/bun/js_bun_spawn_bindings.rs b/src/runtime/api/bun/js_bun_spawn_bindings.rs index ec036184b868..2b1337e7b58b 100644 --- a/src/runtime/api/bun/js_bun_spawn_bindings.rs +++ b/src/runtime/api/bun/js_bun_spawn_bindings.rs @@ -112,7 +112,7 @@ fn get_argv0( pretend_argv0: Option<&CStr>, first_cmd: JSValue, ) -> JsResult { - let arg0 = first_cmd.to_slice_or_null(global_this)?; + let arg0 = first_cmd.to_slice(global_this)?; // `arg0` drops at scope exit (was `defer arg0.deinit()`). // Check for null bytes in command (security: prevent null byte injection) @@ -241,7 +241,7 @@ fn get_argv( let mut arg_index: usize = 1; while let Some(value) = cmds_array.next()? { - let arg = bun_core::OwnedString::new(value.to_bun_string(global_this)?); + let arg = value.to_bun_string(global_this)?; // Check for null bytes in argument (security: prevent null byte injection) if arg.index_of_ascii_char(0).is_some() { @@ -251,7 +251,7 @@ fn get_argv( format_args!( "The argument 'args[{}]' must be a string without null bytes. Received \"{}\"", arg_index, - arg.to_zig_string() + arg ), ) .throw()); @@ -448,8 +448,8 @@ fn spawn_maybe_sync( if args.is_object() { if let Some(argv0_) = args.get_truthy(global_this, "argv0")? { - let argv0_str = argv0_.get_zig_string(global_this)?; - if argv0_str.len > 0 { + let argv0_str = argv0_.to_bun_string(global_this)?; + if !argv0_str.is_empty() { let owned = argv0_str.to_owned_slice_z(); // Check for null bytes in argv0 (security: prevent null byte injection) if strings::index_of_char(owned.as_bytes(), 0).is_some() { @@ -470,8 +470,8 @@ fn spawn_maybe_sync( // need to update `cwd` before searching for executable with `Which.which` if let Some(cwd_) = args.get_truthy(global_this, "cwd")? { - let cwd_str = cwd_.get_zig_string(global_this)?; - if cwd_str.len > 0 { + let cwd_str = cwd_.to_bun_string(global_this)?; + if !cwd_str.is_empty() { cwd_owned = cwd_str.to_owned_slice_z(); // Check for null bytes in cwd (security: prevent null byte injection) if strings::index_of_char(cwd_owned.as_bytes(), 0).is_some() { @@ -2102,11 +2102,10 @@ fn throw_command_not_found(global_this: &JSGlobalObject, command: &[u8]) -> JsEr message: BunString::create_format(format_args!( "Executable not found in $PATH: \"{}\"", bstr::BStr::new(command) - )) - .into(), - code: BunString::static_("ENOENT").into(), + )), + code: BunString::static_("ENOENT"), errno: -UV_E::NOENT, - path: BunString::clone_utf8(command).into(), + path: BunString::clone_utf8(command), ..Default::default() }; global_this.throw_value(err.to_error_instance(global_this)) @@ -2122,7 +2121,7 @@ fn append_envp_from_js( path: &mut &[u8], storage: &mut Vec, ) -> JsResult<()> { - let mut object_iter = JSPropertyIterator::init( + let object_iter = JSPropertyIterator::init( global_this, object, jsc::PropertyIteratorOptions { @@ -2140,13 +2139,12 @@ fn append_envp_from_js( .saturating_sub(envp.len()), ); storage.reserve(object_iter.len); - while let Some(key) = object_iter.next()? { - let value = object_iter.value; + while let Some((key, value)) = object_iter.next()? { if value.is_undefined() { continue; } - let value_bunstr = bun_core::OwnedString::new(value.to_bun_string(global_this)?); + let value_bunstr = value.to_bun_string(global_this)?; // Check for null bytes in env key and value (security: prevent null byte injection) if key.index_of_ascii_char(0).is_some() { @@ -2155,8 +2153,8 @@ fn append_envp_from_js( jsc::ErrorCode::INVALID_ARG_VALUE, format_args!( "The property 'options.env['{}']' must be a string without null bytes. Received \"{}\"", - key.to_zig_string(), - key.to_zig_string() + key, + key ), ) .throw()); @@ -2167,8 +2165,8 @@ fn append_envp_from_js( jsc::ErrorCode::INVALID_ARG_VALUE, format_args!( "The property 'options.env['{}']' must be a string without null bytes. Received \"{}\"", - key.to_zig_string(), - value_bunstr.to_zig_string() + key, + value_bunstr ), ) .throw()); @@ -2177,8 +2175,7 @@ fn append_envp_from_js( // PERF: per-entry allocation — profile if it shows up on a hot path. let line: ZBox = { let mut buf: Vec = Vec::new(); - write!(&mut buf, "{}={}", key, value_bunstr.to_zig_string()) - .map_err(|_| JsError::OutOfMemory)?; + write!(&mut buf, "{}={}", key, value_bunstr).map_err(|_| JsError::OutOfMemory)?; ZBox::from_vec(buf) }; diff --git a/src/runtime/api/bun/spawn/stdio.rs b/src/runtime/api/bun/spawn/stdio.rs index a6ba3fafb659..563e7f6a273a 100644 --- a/src/runtime/api/bun/spawn/stdio.rs +++ b/src/runtime/api/bun/spawn/stdio.rs @@ -428,7 +428,7 @@ impl Stdio { } if value.is_string() { - let str = value.get_zig_string(global)?; + let str = value.to_js_string_view(global)?; if str.eql_comptime(b"inherit") { *out_stdio = Stdio::Inherit; } else if str.eql_comptime(b"ignore") { diff --git a/src/runtime/api/bun/subprocess.rs b/src/runtime/api/bun/subprocess.rs index cd74a4f01e3b..9ed0a659c3c4 100644 --- a/src/runtime/api/bun/subprocess.rs +++ b/src/runtime/api/bun/subprocess.rs @@ -1639,7 +1639,7 @@ pub mod testing_apis { // SAFETY: `from_js` returned a live `*mut Subprocess` owned by the JS wrapper. // R-2: deref as shared (`&*const`) — fields are interior-mutable. let subprocess = unsafe { &*subprocess_ptr }; - let kind_str = bun_core::OwnedString::new(kind_value.to_bun_string(global_this)?); + let kind_str = kind_value.to_bun_string(global_this)?; let out: &JsCell = if kind_str.eql_comptime(b"stdout") { &subprocess.stdout diff --git a/src/runtime/api/crash_handler_jsc.rs b/src/runtime/api/crash_handler_jsc.rs index 79a6f931c22f..443543147d9e 100644 --- a/src/runtime/api/crash_handler_jsc.rs +++ b/src/runtime/api/crash_handler_jsc.rs @@ -225,8 +225,7 @@ pub(crate) mod js_bindings { crash_handler::write_u64_as_two_vlqs(buf.writer(), bits.bits() as usize) // there is definitely enough space in the bounded array .expect("unreachable"); - let mut str = BunString::clone_latin1(buf.slice()); - str.transfer_to_js(global) + BunString::clone_latin1(buf.slice()).into_js(global) } #[bun_jsc::host_fn] diff --git a/src/runtime/api/cron.rs b/src/runtime/api/cron.rs index ee760cdaa05f..09ef660d8d69 100644 --- a/src/runtime/api/cron.rs +++ b/src/runtime/api/cron.rs @@ -728,7 +728,7 @@ fn resolve_cron_tz(global: &JSGlobalObject, opts: JSValue) -> JsResult { global.throw_invalid_arguments(format_args!("Bun.cron: options.tz must be a string")) ); } - let tz_str = bun_core::OwnedString::new(tz_val.to_bun_string(global)?); + let tz_str = tz_val.to_bun_string(global)?; let tz_slice = tz_str.to_utf8(); let tz_bytes = tz_slice.slice(); // IANA names are ASCII; rejecting here keeps the Latin-1 StringView cast in @@ -777,9 +777,9 @@ pub(crate) fn cron_register(global: &JSGlobalObject, frame: &CallFrame) -> JsRes ))); } - let path_str = bun_core::OwnedString::new(args[0].to_bun_string(global)?); - let schedule_str = bun_core::OwnedString::new(args[1].to_bun_string(global)?); - let title_str = bun_core::OwnedString::new(args[2].to_bun_string(global)?); + let path_str = args[0].to_bun_string(global)?; + let schedule_str = args[1].to_bun_string(global)?; + let title_str = args[2].to_bun_string(global)?; let path_slice = path_str.to_utf8(); let schedule_slice = schedule_str.to_utf8(); @@ -1286,7 +1286,7 @@ pub(crate) fn cron_remove(global: &JSGlobalObject, frame: &CallFrame) -> JsResul .throw_invalid_arguments(format_args!("Bun.cron.remove() expects a string title"))); } - let title_str = bun_core::OwnedString::new(args[0].to_bun_string(global)?); + let title_str = args[0].to_bun_string(global)?; let title_slice = title_str.to_utf8(); if !validate_title(title_slice.slice()) { @@ -1710,7 +1710,7 @@ impl CronJob { ))); } - let schedule_str = bun_core::OwnedString::new(schedule_arg.to_bun_string(global)?); + let schedule_str = schedule_arg.to_bun_string(global)?; let schedule_slice = schedule_str.to_utf8(); let parsed = match CronExpression::parse(schedule_slice.slice()) { @@ -1864,7 +1864,7 @@ pub(crate) fn cron_parse(global: &JSGlobalObject, frame: &CallFrame) -> JsResult ))); } - let expr_str = bun_core::OwnedString::new(args[0].to_bun_string(global)?); + let expr_str = args[0].to_bun_string(global)?; let expr_slice = expr_str.to_utf8(); let parsed = match CronExpression::parse(expr_slice.slice()) { diff --git a/src/runtime/api/filesystem_router.rs b/src/runtime/api/filesystem_router.rs index 7a7f6dc45147..56d707f5844f 100644 --- a/src/runtime/api/filesystem_router.rs +++ b/src/runtime/api/filesystem_router.rs @@ -137,7 +137,10 @@ impl FileSystemRouter { let mut out_buf = [0u8; MAX_PATH_BYTES * 2]; if let Some(style_val) = argument.get(global_this, "style")? { - if !(style_val.get_zig_string(global_this)?).eql_comptime("nextjs") { + if !style_val + .to_js_string_view(global_this)? + .eql_comptime("nextjs") + { return Err(global_this.throw_invalid_arguments(format_args!( "Only 'nextjs' style is currently implemented" ))); diff --git a/src/runtime/api/glob.rs b/src/runtime/api/glob.rs index d8404a64c412..b9acf3549374 100644 --- a/src/runtime/api/glob.rs +++ b/src/runtime/api/glob.rs @@ -37,7 +37,7 @@ impl ScanOpts { absolute: bool, fn_name: &'static str, ) -> JsResult> { - let cwd_string = bun_core::OwnedString::new(BunString::from_js(cwd_val, global_this)?); + let cwd_string = BunString::from_js(cwd_val, global_this)?; if cwd_string.is_empty() { return Ok(Box::default()); } @@ -377,8 +377,8 @@ impl Glob { } let pat_str: Box<[u8]> = pat_arg - .to_slice_clone(global_this)? - .into_vec() + .to_bun_string(global_this)? + .to_owned_slice() .into_boxed_slice(); Ok(Box::new(Glob { diff --git a/src/runtime/api/html_rewriter.rs b/src/runtime/api/html_rewriter.rs index 9575866ade87..7686911487aa 100644 --- a/src/runtime/api/html_rewriter.rs +++ b/src/runtime/api/html_rewriter.rs @@ -56,8 +56,8 @@ type RawEndTag = lol_html::html_content::EndTag<'static>; /// Construct a `SystemError` with code+message and remaining fields defaulted. fn system_error(code: &'static str, message: &'static str) -> SystemError { SystemError { - code: BunString::static_(code).into(), - message: BunString::static_(message).into(), + code: BunString::static_(code), + message: BunString::static_(message), ..Default::default() } } @@ -2457,8 +2457,7 @@ fn create_lolhtml_error(global: &JSGlobalObject, message: &dyn core::fmt::Displa value } -/// lol-html error `Display` text → owned `bun.String` (a `+1` ref, consumed -/// by `to_error_instance` / `ValueError::Message`). +/// lol-html error `Display` text → owned `bun.String`. fn lol_err_string(e: impl core::fmt::Display) -> BunString { BunString::clone_utf8(e.to_string().as_bytes()) } diff --git a/src/runtime/api/js_bundle_completion_task.rs b/src/runtime/api/js_bundle_completion_task.rs index 260ce3f6152c..e8757a6935bf 100644 --- a/src/runtime/api/js_bundle_completion_task.rs +++ b/src/runtime/api/js_bundle_completion_task.rs @@ -256,7 +256,7 @@ impl JSBundleCompletionTask { bun_ast_jsc::log_to_js_aggregate_error( &self.log, global_this, - BunString::static_(b"Bundle failed"), + &BunString::static_(b"Bundle failed"), ) } else { Ok(JSValue::UNDEFINED) @@ -277,7 +277,7 @@ impl JSBundleCompletionTask { let aggregate_error = bun_ast_jsc::log_to_js_aggregate_error( &self.log, global_this, - BunString::static_(b"Bundle failed"), + &BunString::static_(b"Bundle failed"), ); return promise.reject(global_this, aggregate_error); } else { diff --git a/src/runtime/bake/BakeGlobalObject.cpp b/src/runtime/bake/BakeGlobalObject.cpp index bbebfaf03008..99955e3e20fd 100644 --- a/src/runtime/bake/BakeGlobalObject.cpp +++ b/src/runtime/bake/BakeGlobalObject.cpp @@ -8,8 +8,8 @@ #include "JavaScriptCore/Completion.h" #include "JavaScriptCore/JSSourceCode.h" -extern "C" BunString BakeProdResolve(JSC::JSGlobalObject*, BunString a, BunString b); -extern "C" BunString BakeToWindowsPath(BunString a); +extern "C" BunString BakeProdResolve(JSC::JSGlobalObject*, const BunString* a, const BunString* b); +extern "C" BunString BakeToWindowsPath(const BunString* a); namespace Bake { using namespace JSC; @@ -42,10 +42,12 @@ bakeModuleLoaderImportModule(JSC::JSGlobalObject* global, return promise; } - BunString result = BakeProdResolve(global, Bun::toString(refererString), Bun::toString(keyString)); + BunString refererBunString = Bun::toString(refererString); + BunString keyBunString = Bun::toString(keyString); + BunString result = BakeProdResolve(global, &refererBunString, &keyBunString); RETURN_IF_EXCEPTION(scope, nullptr); - return JSC::importModule(global, JSC::Identifier::fromString(vm, result.toWTFString()), + return JSC::importModule(global, JSC::Identifier::fromString(vm, result.transferToWTFString()), JSC::Identifier(), WTF::move(parameters), nullptr); } @@ -69,10 +71,12 @@ JSC::Identifier bakeModuleLoaderResolve(JSC::JSGlobalObject* jsGlobal, RETURN_IF_EXCEPTION(scope, {}); if (refererString.startsWith("bake:/"_s) || (refererString == "."_s && keyString.startsWith("bake:/"_s))) { - BunString result = BakeProdResolve(global, Bun::toString(refererString), Bun::toString(keyString)); + BunString refererBunString = Bun::toString(refererString); + BunString keyBunString = Bun::toString(keyString); + BunString result = BakeProdResolve(global, &refererBunString, &keyBunString); RETURN_IF_EXCEPTION(scope, {}); - return JSC::Identifier::fromString(vm, result.toWTFString(BunString::ZeroCopy)); + return JSC::Identifier::fromString(vm, result.transferToWTFString()); } } @@ -81,7 +85,10 @@ JSC::Identifier bakeModuleLoaderResolve(JSC::JSGlobalObject* jsGlobal, RETURN_IF_EXCEPTION(scope, {}); if (keyView.startsWith("bake:/"_s)) { - BunString result = BakeProdResolve(global, Bun::toString("bake:/"_s), Bun::toString(keyView.substringSharingImpl("bake:"_s.length()))); + WTF::String keyWithoutScheme = keyView.substringSharingImpl("bake:"_s.length()); + BunString bakePrefixBunString = { BunStringTag::StaticZigString, { .zig = { reinterpret_cast("bake:/"), 6 } } }; + BunString keyBunString = Bun::toString(keyWithoutScheme); + BunString result = BakeProdResolve(global, &bakePrefixBunString, &keyBunString); RETURN_IF_EXCEPTION(scope, {}); return JSC::Identifier::fromString(vm, result.transferToWTFString()); @@ -107,7 +114,7 @@ static JSC::JSPromise* resolvedInternalPromise(JSC::JSGlobalObject* globalObject return promise; } -extern "C" BunString BakeProdLoad(void* perThreadData, BunString a); +extern "C" BunString BakeProdLoad(void* perThreadData, const BunString* a); extern "C" bool BakeGlobalObject__isBakeGlobalObject(JSC::JSGlobalObject* global) { @@ -133,12 +140,13 @@ JSC::JSPromise* bakeModuleLoaderFetch(JSC::JSGlobalObject* globalObject, if (moduleKey.startsWith("bake:/"_s)) { if (global->m_perThreadData) [[likely]] { - BunString source = BakeProdLoad(global->m_perThreadData, Bun::toString(moduleKey)); + BunString moduleKeyBunString = Bun::toString(moduleKey); + BunString source = BakeProdLoad(global->m_perThreadData, &moduleKeyBunString); if (source.tag != BunStringTag::Dead) { JSC::SourceOrigin origin = JSC::SourceOrigin(WTF::URL(moduleKey)); JSC::SourceCode sourceCode = JSC::SourceCode(Bake::SourceProvider::create( globalObject, - source.toWTFString(), + source.transferToWTFString(), origin, WTF::move(moduleKey), WTF::TextPosition(), @@ -159,8 +167,8 @@ JSC::JSPromise* bakeModuleLoaderFetch(JSC::JSGlobalObject* globalObject, // have to worry about platform paths. Now we have to worry about // it, because `moduleLoaderFetch(...)` may read the path from disk // and so we need to give a Windows path to it. - auto temp = BakeToWindowsPath(Bun::toString(bakePrefixRemoved)); - bakePrefixRemoved = temp.toWTFString(); + BunString bakePrefixRemovedBunString = Bun::toString(bakePrefixRemoved); + bakePrefixRemoved = BakeToWindowsPath(&bakePrefixRemovedBunString).transferToWTFString(); #endif JSString* bakePrefixRemovedString = jsNontrivialString(vm, bakePrefixRemoved); JSValue bakePrefixRemovedJsvalue = bakePrefixRemovedString; diff --git a/src/runtime/bake/BakeProduction.cpp b/src/runtime/bake/BakeProduction.cpp index 321b18b0fd76..9940dd00b5bc 100644 --- a/src/runtime/bake/BakeProduction.cpp +++ b/src/runtime/bake/BakeProduction.cpp @@ -10,7 +10,7 @@ namespace Bake { extern "C" JSC::JSPromise* BakeRenderRoutesForProdStatic( JSC::JSGlobalObject* global, - BunString outBase, + const BunString* outBase, JSC::JSValue allServerFiles, JSC::JSValue renderStatic, JSC::JSValue getParams, @@ -27,7 +27,7 @@ extern "C" JSC::JSPromise* BakeRenderRoutesForProdStatic( JSC::CallData callData = JSC::getCallData(cb); JSC::MarkedArgumentBuffer args; - args.append(JSC::jsString(vm, outBase.toWTFString())); + args.append(JSC::jsString(vm, outBase->toWTFString())); args.append(allServerFiles); args.append(renderStatic); args.append(getParams); diff --git a/src/runtime/bake/BakeSourceProvider.cpp b/src/runtime/bake/BakeSourceProvider.cpp index 73c929ab59b7..75995e3a6aab 100644 --- a/src/runtime/bake/BakeSourceProvider.cpp +++ b/src/runtime/bake/BakeSourceProvider.cpp @@ -32,7 +32,7 @@ extern "C" JSC::EncodedJSValue BakeLoadInitialServerCode(JSC::JSGlobalObject* gl JSC::SourceOrigin origin = JSC::SourceOrigin(WTF::URL(string)); JSC::SourceCode sourceCode = JSC::SourceCode(SourceProvider::create( global, - source.toWTFString(), + source.transferToWTFString(), origin, WTF::move(string), WTF::TextPosition(), @@ -66,7 +66,7 @@ extern "C" JSC::EncodedJSValue BakeLoadServerHmrPatch(GlobalObject* global, BunS JSC::SourceOrigin origin = JSC::SourceOrigin(WTF::URL(string)); JSC::SourceCode sourceCode = JSC::SourceCode(SourceProvider::create( global, - source.toWTFString(), + source.transferToWTFString(), origin, WTF::move(string), WTF::TextPosition(), @@ -90,7 +90,7 @@ extern "C" JSC::EncodedJSValue BakeLoadServerHmrPatchWithSourceMap(GlobalObject* // Use DevServerSourceProvider with the source map JSON auto provider = DevServerSourceProvider::create( global, - source.toWTFString(), + source.transferToWTFString(), sourceMapJSONPtr, sourceMapJSONLength, origin, diff --git a/src/runtime/bake/BakeSourceProvider.h b/src/runtime/bake/BakeSourceProvider.h index 0da0fcaa8282..7178eb50e239 100644 --- a/src/runtime/bake/BakeSourceProvider.h +++ b/src/runtime/bake/BakeSourceProvider.h @@ -8,7 +8,7 @@ namespace Bake { class SourceProvider; -extern "C" void Bun__addBakeSourceProviderSourceMap(void* bun_vm, SourceProvider* opaque_source_provider, BunString* specifier); +extern "C" void Bun__addBakeSourceProviderSourceMap(void* bun_vm, SourceProvider* opaque_source_provider, const BunString* specifier); class SourceProvider final : public JSC::StringSourceProvider { public: diff --git a/src/runtime/bake/DevServer.rs b/src/runtime/bake/DevServer.rs index 70043ab26e82..4ed916cbc2ef 100644 --- a/src/runtime/bake/DevServer.rs +++ b/src/runtime/bake/DevServer.rs @@ -18,7 +18,7 @@ use bun_alloc::{AllocError, Arena}; use bun_ast::Log; use bun_bundler::options_impl::TargetExt as _; use bun_collections::{ArrayHashMap, DynamicBitSet, HashMap, HiveArrayFallback, StringHashMap}; -use bun_core::{self as str, OwnedString, String as BunString, ZStr, strings}; +use bun_core::{self as str, String as BunString, ZStr, strings}; use bun_core::{Environment, Output}; use bun_jsc::StringJsc as _; use bun_jsc::virtual_machine::VirtualMachine; @@ -58,14 +58,14 @@ trait LogToJsAggregateErrorExt { fn to_js_aggregate_error( &mut self, _global: &JSGlobalObject, - _msg: BunString, + _msg: &BunString, ) -> JsResult; } impl LogToJsAggregateErrorExt for Log { fn to_js_aggregate_error( &mut self, global: &JSGlobalObject, - msg: BunString, + msg: &BunString, ) -> JsResult { bun_ast_jsc::log_to_js_aggregate_error(self, global, msg) } @@ -780,7 +780,7 @@ pub(crate) fn init(options: Options) -> JsResult> { } return Err(global.throw_value(dev.log.to_js_aggregate_error( global, - BunString::static_("Framework is missing required files!"), + &BunString::static_("Framework is missing required files!"), )?)); } @@ -1206,8 +1206,11 @@ impl Drop for DevServer { impl DevServer { fn init_server_runtime(&mut self) { - let runtime = BunString::static_( - crate::bake::bake_body::get_hmr_runtime(crate::bake::bake_body::Side::Server).code, + let runtime = BunString::create_static_external( + crate::bake::bake_body::get_hmr_runtime(crate::bake::bake_body::Side::Server) + .code + .as_bytes(), + true, ); // `self.global()` returns `&'static`, decoupled from `&self` — it's @@ -2469,7 +2472,7 @@ impl DevServer { { let mut buf = paths::path_buffer_pool::get(); // SAFETY: `relative_path(&self)` only reads `self.root`; no `&mut *this` is live. - let mut route_name = BunString::clone_utf8(unsafe { + let route_name = unsafe { (*this).relative_path( &mut *buf, &keys[from_opaque_file_id::<{ bake::Side::Server }>( @@ -2477,25 +2480,29 @@ impl DevServer { ) .get() as usize], ) - }); - arr.put_index(global, 0, route_name.transfer_to_js(global)?)?; + }; + arr.put_index( + global, + 0, + bun_jsc::bun_string_jsc::create_utf8_for_js(global, route_name)?, + )?; } n = 1; loop { if let Some(layout) = route.file_layout { let mut buf = paths::path_buffer_pool::get(); // SAFETY: `relative_path(&self)` only reads `self.root`; no `&mut *this` is live. - let mut layout_name = BunString::clone_utf8(unsafe { + let layout_name = unsafe { (*this).relative_path( &mut *buf, &keys[from_opaque_file_id::<{ bake::Side::Server }>(layout) .get() as usize], ) - }); + }; arr.put_index( global, u32::try_from(n).expect("int cast"), - layout_name.transfer_to_js(global)?, + bun_jsc::bun_string_jsc::create_utf8_for_js(global, layout_name)?, )?; n += 1; } @@ -2520,10 +2527,10 @@ impl DevServer { bun_core::fmt::bytes_to_hex_lower(&generation.to_ne_bytes(), &mut hex[8..]); // SAFETY: `bytes_to_hex_lower` writes ASCII [0-9a-f] only. let hex_str = unsafe { ::core::str::from_utf8_unchecked(&hex) }; - let s = OwnedString::new(BunString::create_format(format_args!( + let js = BunString::create_format(format_args!( "{CLIENT_PREFIX}/route-{hex_str}.js", - ))); - let js = s.to_js(global)?; + )) + .into_js(global)?; framework_bundle.cached_client_bundle_url = jsc::StrongOptional::create(js, global); break 'str js; @@ -2595,16 +2602,14 @@ impl DevServer { // Extract route params by re-matching the URL let mut params: framework_router::MatchedParams = Default::default(); - let url_bunstr = OwnedString::new(match &req { + let url_bunstr = match &req { // SAFETY: r is a uws Request ptr valid for the duration of the handler callback - SavedRequestUnion::Stack(r) => BunString::borrow_utf8((**r).url()), - SavedRequestUnion::Saved(data) => 'brk: { + SavedRequestUnion::Stack(r) => bun_core::StringView::borrow_utf8((**r).url()), + SavedRequestUnion::Saved(data) => { // SAFETY: data.request is a live *mut webcore::Request (held strong by ctx) - let url = unsafe { (*data.request).url.get() }; - url.ref_(); - break 'brk url; + bun_core::StringView::new(unsafe { (*data.request).url.get() }) } - }); + }; let url = url_bunstr.to_utf8(); // Extract pathname from URL (remove protocol, host, query, hash) @@ -3135,9 +3140,6 @@ impl DevServer { trigger_files.push(BunString::clone_utf8(key)); } agent.notify_bundle_start(self.inspector_server_id, &mut trigger_files); - for s in &mut trigger_files { - s.deref(); - } } self.incremental_result.reset(); @@ -3608,11 +3610,10 @@ impl DevServer { let written = buf_len - cursor.len(); &buf[..written] }; - let s = OwnedString::new(BunString::clone_utf8(path)); arr.put_index( global, u32::try_from(i).expect("int cast"), - s.to_js(global)?, + bun_jsc::bun_string_jsc::create_utf8_for_js(global, path)?, )?; } Ok(arr) @@ -3690,13 +3691,11 @@ impl DevServer { let names = self.server_graph.bundled_files.keys(); for (i, item) in items.iter().enumerate() { let mut buf = paths::path_buffer_pool::get(); - let s = OwnedString::new(BunString::clone_utf8( - self.relative_path(&mut *buf, &names[item.get() as usize]), - )); + let s = self.relative_path(&mut *buf, &names[item.get() as usize]); arr.put_index( global, u32::try_from(i).expect("int cast"), - s.to_js(global)?, + bun_jsc::bun_string_jsc::create_utf8_for_js(global, s)?, )?; } Ok(arr) @@ -5358,8 +5357,10 @@ impl DevServer { debug_assert!(agent.is_enabled()); let failures_encoded = &buf[failures_start_buf_pos..]; // base64 output is pure ASCII so a UTF-8 borrow is safe. - let mut s = BunString::borrow_utf8(failures_encoded); - agent.notify_bundle_failed(self.inspector_server_id, &mut s); + agent.notify_bundle_failed( + self.inspector_server_id, + BunString::borrow_utf8(failures_encoded), + ); } Ok(()) } @@ -6517,7 +6518,7 @@ bun_jsc::jsc_host_abi! { pub unsafe fn Bake__bundleNewRouteJSFunctionImpl( global: &JSGlobalObject, request_ptr: *mut c_void, - url: BunString, + url: &BunString, ) -> JSValue { jsc::to_js_host_call(global, || bundle_new_route_js_function_impl(global, request_ptr, url)) } @@ -6526,7 +6527,7 @@ bun_jsc::jsc_host_abi! { fn bundle_new_route_js_function_impl( global: &JSGlobalObject, request_ptr: *mut c_void, - url_bunstr: BunString, + url_bunstr: &BunString, ) -> JsResult { let url = url_bunstr.to_utf8(); @@ -6685,7 +6686,7 @@ fn new_route_params_for_bundle_promise_for_js( u32::try_from(route_bundle_index_js.to_int32()).expect("int cast"), ); - let url = OwnedString::new(url_js.to_bun_string(global)?); + let url = url_js.to_bun_string(global)?; let url_utf8 = url.to_utf8(); new_route_params_for_bundle_promise(dev, route_bundle_index, url_utf8.slice()) diff --git a/src/runtime/bake/DevServerSourceProvider.cpp b/src/runtime/bake/DevServerSourceProvider.cpp index bbd4672310dd..d50467581037 100644 --- a/src/runtime/bake/DevServerSourceProvider.cpp +++ b/src/runtime/bake/DevServerSourceProvider.cpp @@ -3,7 +3,7 @@ #include "BunString.h" // Implemented on the Rust side to handle registration. -extern "C" void Bun__addDevServerSourceProvider(void* bun_vm, Bake::DevServerSourceProvider* opaque_source_provider, BunString* specifier); +extern "C" void Bun__addDevServerSourceProvider(void* bun_vm, Bake::DevServerSourceProvider* opaque_source_provider, const BunString* specifier); // Exported for the Rust side to access DevServerSourceProvider. extern "C" BunString DevServerSourceProvider__getSourceSlice(Bake::DevServerSourceProvider* provider) diff --git a/src/runtime/bake/DevServerSourceProvider.h b/src/runtime/bake/DevServerSourceProvider.h index 29cd4b272be1..f0ec16a4b334 100644 --- a/src/runtime/bake/DevServerSourceProvider.h +++ b/src/runtime/bake/DevServerSourceProvider.h @@ -10,8 +10,8 @@ namespace Bake { class DevServerSourceProvider; // Implemented on the Rust side to register the source provider. -extern "C" void Bun__addDevServerSourceProvider(void* bun_vm, DevServerSourceProvider* opaque_source_provider, BunString* specifier); -extern "C" void Bun__removeDevServerSourceProvider(void* bun_vm, DevServerSourceProvider* opaque_source_provider, BunString* specifier); +extern "C" void Bun__addDevServerSourceProvider(void* bun_vm, DevServerSourceProvider* opaque_source_provider, const BunString* specifier); +extern "C" void Bun__removeDevServerSourceProvider(void* bun_vm, DevServerSourceProvider* opaque_source_provider, const BunString* specifier); class DevServerSourceProvider final : public JSC::StringSourceProvider { public: diff --git a/src/runtime/bake/FrameworkRouter.rs b/src/runtime/bake/FrameworkRouter.rs index 48583ff1c802..562078bbbe35 100644 --- a/src/runtime/bake/FrameworkRouter.rs +++ b/src/runtime/bake/FrameworkRouter.rs @@ -649,7 +649,7 @@ const STYLE_ERROR_MESSAGE: &str = "'style' must be either \"nextjs-pages\", \"ne impl Style { pub fn from_js(value: JSValue, global: &JSGlobalObject) -> JsResult