use core::fmt; use core::ptr::NonNull; use std::cell::UnsafeCell; use std::rc::{Rc, Weak}; use bun_collections::LinearFifo; use bun_core::{Output, Timespec}; use bun_jsc::{self as jsc, CallFrame, GlobalRef, JSGlobalObject, JSValue, JsResult, Strong, JsClass as _}; use bun_jsc::virtual_machine::VirtualMachine; use bun_jsc::js_promise::Status as PromiseStatus; use bun_ptr::RefPtr; use super::jest::{Jest, FileId, FileColumns as _}; use crate::timer::{EventLoopTimer, EventLoopTimerState, EventLoopTimerTag, ElTimespec}; use crate::cli::test_command::CommandLineReporter; use super::execution::TimespecExt as _; bun_core::declare_scope!(bun_test_group, hidden); // Callers use `group_log!` / `group_begin!` / `group_end!` below. /// Thin macro over `debug::group::begin()` so call sites stay `group_begin!()`. macro_rules! group_begin { () => { $crate::test_runner::debug::group::begin() }; } pub(crate) use group_begin; /// Recover this thread's `timer::All` heap (jsc/runtime crate cycle: `vm.timer` is `()` in /// the low-tier `VirtualMachine`; the real value lives in `RuntimeState`). #[inline] pub(super) fn vm_timer<'a>() -> &'a mut crate::timer::All { // SAFETY: `runtime_state()` is non-null after `bun_runtime::init()`; // single JS thread, raw-ptr-per-field re-entry pattern (jsc_hooks.rs). unsafe { &mut (*crate::jsc_hooks::runtime_state()).timer } } /// `bun.timespec.orderIgnoreEpoch` — epoch == "no timeout", treated as +∞. /// Local helper so it can compare `bun_core::Timespec` against the /// event-loop crate's distinct `Timespec` (converted by field). // ElTimespec dedup is a separate ticket. #[inline] fn order_ignore_epoch(a: &Timespec, b: &ElTimespec) -> core::cmp::Ordering { Timespec::order_ignore_epoch(*a, Timespec { sec: b.sec, nsec: b.nsec }) } /// `Strong::create` requires a `&JSGlobalObject`; recover it from the /// per-thread VM so `ExecutionEntry::create` (which has no global in scope) /// can box callbacks. #[inline] fn strong_create(value: JSValue) -> Strong { // SAFETY: `VirtualMachine::get()` is the live per-thread VM; `global` // is non-null after VM init. let global = VirtualMachine::get().global(); Strong::create(value, global) } pub(crate) fn clone_active_strong() -> Option { let runner = Jest::runner()?; runner.bun_test_root.clone_active_file() } pub(crate) use super::done_callback::DoneCallback; pub(crate) mod js_fns { use super::*; #[derive(Clone, Copy)] pub(crate) enum Signature<'a> { ScopeFunctions(&'a ScopeFunctions::ScopeFunctions), Str(&'static [u8]), } impl<'a> fmt::Display for Signature<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Signature::ScopeFunctions(sf) => write!(f, "{}", sf), Signature::Str(s) => write!(f, "{}", bstr::BStr::new(s)), } } } /// Only requires the runner: hooks are legal in preload scripts (they attach /// to the root), so the preload check lives in `clone_active_strong`. fn get_test_root( global_this: &JSGlobalObject, signature: Signature<'_>, ) -> JsResult<&'static mut BunTestRoot> { // `Jest.runner` is a process-global that outlives every caller, so the // unbounded `&'static mut` is the honest model here. let Some(runner) = Jest::runner() else { return Err(global_this.throw(format_args!( "Cannot use {} outside of the test runner. Run \"bun test\" to run tests.", signature ))); }; // The runner calls every registered callback on the main thread's VM. if global_this.bun_vm().worker_ref().is_some() { return Err(global_this.throw(format_args!("Cannot use {} in a Worker.", signature))); } Ok(&mut runner.bun_test_root) } pub(crate) fn clone_active_strong( global_this: &JSGlobalObject, signature: Signature<'_>, ) -> JsResult { let bun_test_root = get_test_root(global_this, signature)?; if global_this.bun_vm().is_in_preload { return Err(global_this.throw(format_args!( "Cannot use {} during preload.", signature ))); } let Some(bun_test) = bun_test_root.clone_active_file() else { return Err(global_this.throw(format_args!( "Cannot use {} outside of a test file.", signature ))); }; Ok(bun_test) } /// Tags accepted by `generic_hook`. Superset of `DescribeScope::HookTag` /// (adds `OnTestFinished`). // was a const-generic param (`adt_const_params` is unstable); // reshaped to runtime dispatch with per-tag thin host_fn wrappers below. #[derive(Copy, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum GenericHookTag { #[strum(serialize = "beforeAll")] BeforeAll, #[strum(serialize = "beforeEach")] BeforeEach, #[strum(serialize = "afterEach")] AfterEach, #[strum(serialize = "afterAll")] AfterAll, #[strum(serialize = "onTestFinished")] OnTestFinished, } impl GenericHookTag { const fn as_hook_tag(self) -> Option { match self { Self::BeforeAll => Some(HookTag::BeforeAll), Self::BeforeEach => Some(HookTag::BeforeEach), Self::AfterEach => Some(HookTag::AfterEach), Self::AfterAll => Some(HookTag::AfterAll), Self::OnTestFinished => None, } } /// Per-variant signature string: the tag name plus `"()"`. const fn sig(self) -> &'static [u8] { match self { Self::BeforeAll => b"beforeAll()", Self::BeforeEach => b"beforeEach()", Self::AfterEach => b"afterEach()", Self::AfterAll => b"afterAll()", Self::OnTestFinished => b"onTestFinished()", } } } // `adt_const_params` is unstable, so the body takes `tag` at runtime and // 5 thin `#[host_fn]` wrappers below supply the per-tag entry points // (one fn per JS function so JSFunction::create gets a distinct address). pub(crate) fn generic_hook_impl( tag: GenericHookTag, global_this: &JSGlobalObject, call_frame: &CallFrame, ) -> JsResult { let _g = group_begin!(); // Run the body in a closure so every error exit funnels through the // log below before the group guard closes. let result = (|| -> JsResult { let tag_name: &'static str = tag.into(); let sig_bytes: &'static [u8] = tag.sig(); let args = ScopeFunctions::parse_arguments( global_this, call_frame, Signature::Str(sig_bytes), ScopeFunctions::ParseArgumentsCfg { callback: ScopeFunctions::CallbackMode::Require, kind: ScopeFunctions::FunctionKind::Hook }, )?; let has_done_parameter = if let Some(callback) = args.callback { callback.get_length(global_this)? > 0 } else { false }; let bun_test_root = get_test_root(global_this, Signature::Str(sig_bytes))?; let cfg = ExecutionEntryCfg { has_done_parameter, timeout: args.options.timeout, ..Default::default() }; let Some(bun_test) = bun_test_root.get_active_file_unless_in_preload(global_this.bun_vm()) else { if tag == GenericHookTag::OnTestFinished { return Err(global_this.throw(format_args!( "Cannot call {}() in preload. It can only be called inside a test.", tag_name ))); } bun_core::scoped_log!(bun_test_group, "genericHook in preload"); let _ = bun_test_root.hook_scope.append_hook( tag.as_hook_tag().unwrap(), args.callback, cfg, BaseScopeCfg::default(), AddedInPhase::Preload, )?; return Ok(JSValue::UNDEFINED); }; match bun_test.phase { Phase::Collection => { if tag == GenericHookTag::OnTestFinished { return Err(global_this.throw(format_args!( "Cannot call {}() outside of a test. It can only be called inside a test.", tag_name ))); } let _ = bun_test.collection.active_scope_mut().append_hook( tag.as_hook_tag().unwrap(), args.callback, cfg, BaseScopeCfg::default(), AddedInPhase::Collection, )?; Ok(JSValue::UNDEFINED) } Phase::Execution => { let active = bun_test.get_current_state_data(); let Some((sequence, _)) = bun_test.execution.get_current_and_valid_execution_sequence(&active) else { return Err(if tag == GenericHookTag::OnTestFinished { global_this.throw(format_args!( "Cannot call {}() here. It cannot be called inside a concurrent test. Use test.serial or remove test.concurrent.", tag_name )) } else { global_this.throw(format_args!( "Cannot call {}() here. It cannot be called inside a concurrent test. Call it inside describe() instead.", tag_name )) }); }; // SAFETY: `get_current_and_valid_execution_sequence` returns a NonNull // into `execution.sequences`; deref at point-of-use only. let sequence_ref = unsafe { sequence.as_ref() }; let append_point: *mut ExecutionEntry = match tag { GenericHookTag::AfterAll | GenericHookTag::AfterEach => 'blk: { let mut iter = sequence_ref.active_entry; while let Some(entry) = iter { // SAFETY: intrusive linked-list nodes are valid while sequence is live let entry_ref = unsafe { entry.as_ref() }; if Some(entry) == sequence_ref.test_entry { break 'blk sequence_ref.test_entry.unwrap().as_ptr(); } iter = entry_ref.next.and_then(NonNull::new); } match sequence_ref.active_entry { Some(e) => break 'blk e.as_ptr(), None => { return Err(global_this.throw(format_args!( "Cannot call {}() here. Call it inside describe() instead.", tag_name ))); } } } GenericHookTag::OnTestFinished => 'blk: { // Find the last entry in the sequence let Some(mut last_entry) = sequence_ref.active_entry.map(|p| p.as_ptr()) else { return Err(global_this.throw(format_args!( "Cannot call {}() here. Call it inside a test instead.", tag_name ))); }; // SAFETY: intrusive linked-list traversal unsafe { while let Some(next_entry) = (*last_entry).next { last_entry = next_entry; } } break 'blk last_entry; } _ => { return Err(global_this.throw(format_args!( "Cannot call {}() inside a test. Call it inside describe() instead.", tag_name ))); } }; let new_item = ExecutionEntry::create( None, args.callback, cfg, None, BaseScopeCfg::default(), AddedInPhase::Execution, ); let new_item_ptr = bun_core::heap::into_raw(new_item); // SAFETY: append_point is a valid linked-list node; new_item_ptr just allocated unsafe { (*new_item_ptr).next = (*append_point).next; (*append_point).next = Some(new_item_ptr); } bun_test.extra_execution_entries.push(new_item_ptr); Ok(JSValue::UNDEFINED) } Phase::Done => Err(global_this.throw(format_args!( "Cannot call {}() after the test run has completed", tag_name ))), } })(); if result.is_err() { crate::test_runner::debug::group::log("ended in error"); } result } /// Per-tag `#[host_fn]` entry points (one fn per JS function so /// `JSFunction::create` gets a distinct address). pub(crate) mod generic_hook { use super::*; macro_rules! hook { ($name:ident, $tag:ident) => { #[bun_jsc::host_fn] pub(crate) fn $name( global_this: &JSGlobalObject, call_frame: &CallFrame, ) -> JsResult { super::generic_hook_impl(GenericHookTag::$tag, global_this, call_frame) } }; } hook!(before_all, BeforeAll); hook!(before_each, BeforeEach); hook!(after_each, AfterEach); hook!(after_all, AfterAll); hook!(on_test_finished, OnTestFinished); } } /// `Rc`: single-thread, weak-capable, interior-mutable shared handle. /// /// Code mutates through this handle pervasively (re-entrantly via JS callbacks). /// `Rc` does **not** wrap `T` in `UnsafeCell`, so the previous /// `Rc::as_ptr(&rc) as *mut T` + write was UB. The payload now lives in an /// explicit `UnsafeCell` so all writes go through interior-mutable provenance. pub(crate) type BunTestPtr = Rc; pub(crate) type BunTestPtrWeak = Weak; pub(crate) type BunTestPtrOptional = Option>; /// `UnsafeCell` newtype so `Rc` permits mutation of the shared /// `BunTest` (`UnsafeCell` is required for any write reachable through a /// shared/`*const` path). #[repr(transparent)] pub(crate) struct BunTestCell(UnsafeCell); impl BunTestCell { #[inline] pub(crate) fn new(bt: BunTest) -> Rc { Rc::new(Self(UnsafeCell::new(bt))) } /// Returns `&mut` because every call site mutates. The borrow is derived /// from `UnsafeCell::get()` so provenance is valid for writes even while /// other `Rc`/`Weak` handles exist. /// /// **Aliasing contract:** the test runner is single-threaded. Callers must not /// hold the returned `&mut` across a re-entrancy point (JS callback, /// `Collection::step`, `Execution::step`, `BunTest::run`) that itself calls /// `.get()` — re-derive afterwards instead. Prefer [`as_ptr`](Self::as_ptr) /// for long-lived handles that span re-entrant calls. #[inline] #[allow(clippy::mut_from_ref)] pub(crate) fn get(&self) -> &mut BunTest { // SAFETY: `UnsafeCell` interior; single-threaded JS VM. See contract above. unsafe { &mut *self.0.get() } } /// Raw pointer for sites that must span re-entrant `.get()` calls without /// holding a live `&mut` (Stacked-Borrows-safe: raw ptrs do not assert /// uniqueness). #[inline] pub(crate) fn as_ptr(&self) -> *mut BunTest { self.0.get() } } impl core::ops::Deref for BunTestCell { type Target = BunTest; #[inline] fn deref(&self) -> &BunTest { // SAFETY: shared read through `UnsafeCell`; single-threaded — caller // must not hold a live `&mut` from `.get()` concurrently. unsafe { &*self.0.get() } } } /// Back-compat shim for sibling modules (jest.rs) that funneled through this /// helper. Now routes through `UnsafeCell::get()` instead of the UB /// `*const T as *mut T` cast. /// /// # Safety /// Caller must uphold the aliasing contract documented on [`BunTestCell::get`]. #[inline] #[allow(clippy::mut_from_ref)] // interior mutability: routes through UnsafeCell::get() pub(crate) unsafe fn buntest_as_mut(ptr: &BunTestPtr) -> &mut BunTest { ptr.get() } pub(crate) struct BunTestRoot { // gpa dropped — global mimalloc pub(crate) active_file: BunTestPtrOptional, pub(crate) hook_scope: Box, /// `RefData` pointers handed to `Promise.then()`. Tracked here (process-lifetime) /// so a never-settled promise's `+1` stays reachable; do not free orphans — /// a queued reaction may still consume them. pub(crate) pending_then_refs: std::cell::RefCell>, /// Monotonic per-`enter_file` counter. Exposed to JS so per-file module /// state (node:test root) resets on `--rerun-each` where `Bun.main` is /// unchanged across iterations. pub(crate) file_generation: u32, } impl BunTestRoot { pub(crate) fn init() -> BunTestRoot { let hook_scope = DescribeScope::create(BaseScope { parent: None, name: None, concurrent: false, mode: ScopeMode::Normal, only: Only::No, has_callback: false, test_id_for_debugger: 0, line_no: 0, }); BunTestRoot { active_file: None, hook_scope, pending_then_refs: std::cell::RefCell::new(Vec::new()), file_generation: 0, } } /// Drop preload-level hooks registered in the previous global. The next /// file's `loadPreloads()` re-registers them against the fresh global. pub(crate) fn reset_hook_scope_for_test_isolation(&mut self) { debug_assert!(self.hook_scope.entries.is_empty()); // drop old, create fresh self.hook_scope = DescribeScope::create(BaseScope { parent: None, name: None, concurrent: false, mode: ScopeMode::Normal, only: Only::No, has_callback: false, test_id_for_debugger: 0, line_no: 0, }); } /// Tear down `bun:test` GC roots before `global_exit()` so /// `Zig__GlobalObject__destructOnExit()`'s `collectNow()` can reclaim the /// closures they pin. Releases the active file's per-test `Strong`s (the /// bail path skips its `scopeguard::defer! { exit_file() }` because /// `process::exit()` does not unwind), the preload-hook `Strong`s held in /// `hook_scope`, and the `pending_then_refs` Vec. pub(crate) fn deinit_for_exit(&mut self) { if self.active_file.is_some() { self.exit_file(); } self.reset_hook_scope_for_test_isolation(); // `pending_then_refs` holds the `+1` `RefData` ref taken at // `Promise.then()` time so a never-settled promise's box stays // reachable. The corresponding deref happens in // `bun_test_then_or_catch` when the promise settles — which it now // never will (the VM is going away). Release each orphan ourselves; // any reaction that is still queued is dropped wholesale by // `Zig__GlobalObject__destructOnExit`. for ptr in self.pending_then_refs.borrow_mut().drain(..) { // SAFETY: `ptr` was produced by `RefPtr::into_raw` in // `BunTest::run_test_callback`; it is live because the promise // never settled (the settle path removes the entry before // releasing). Single-threaded. drop(unsafe { RefPtr::from_raw(ptr.cast_mut()) }); } } pub(crate) fn enter_file( &mut self, file_id: FileId, reporter: &mut CommandLineReporter, default_concurrent: bool, first_last: FirstLast, ) { let _g = group_begin!(); debug_assert!(self.active_file.is_none()); self.file_generation = self.file_generation.wrapping_add(1); // Derive the stored backref from the TestRunner's *stable* storage // (the global `Jest::RUNNER` NonNull) rather than `self as *mut _`. // A pointer coerced from `&mut self` carries provenance bounded by this // call's reborrow; the next `Jest::runner()` hands out a fresh // an exclusive `&mut TestRunner`, invalidating that tag, so later derefs at // `BunTest::run`/`on_uncaught_exception` would be use-after-invalidation // under Stacked Borrows. // SAFETY: single-threaded; `RUNNER` outlives every BunTest. Field // projection via `addr_of_mut!` creates no intermediate `&mut TestRunner`, // and `addr_of_mut!` on a live struct field is never null. let stable_root: NonNull = Jest::runner_ptr() .map(|p| unsafe { NonNull::new_unchecked(core::ptr::addr_of_mut!((*p.as_ptr()).bun_test_root)) }) .unwrap_or_else(|| NonNull::from(&mut *self)); // BunTest stores a backref to BunTestRoot, but the backref is the // `stable_root` raw pointer above (not an `Rc`), so plain construction // works without `Rc::new_cyclic`/two-phase init. // The reporter is the global `CommandLineReporter` owned by // `test_command::exec` which outlives every `BunTest`. `exit_file()` // nulls this before the file is dropped. let reporter_ptr = NonNull::from(&mut *reporter); let bun_test = BunTestCell::new(BunTest::init( stable_root, file_id, Some(reporter_ptr), default_concurrent, first_last, )); self.active_file = Some(bun_test); } pub(crate) fn exit_file(&mut self) { let _g = group_begin!(); debug_assert!(self.active_file.is_some()); if let Some(active) = &self.active_file { // SAFETY: single-threaded; no other `&mut BunTest` is live during // teardown. Write goes through `UnsafeCell` (see `BunTestCell::get`). active.get().reporter = None; } self.active_file = None; // drops the Rc (deinit) } pub(crate) fn get_active_file_unless_in_preload(&mut self, vm: &VirtualMachine) -> Option<&mut BunTest> { if vm.is_in_preload { return None; } // SAFETY: single-threaded; caller (js_fns::generic_hook) holds the only // live `&mut` for the duration of the hook-append below. Projection goes // through `UnsafeCell` (see `BunTestCell::get`). self.active_file.as_ref().map(|rc| rc.get()) } pub(crate) fn clone_active_file(&self) -> Option { self.active_file.clone() } pub(crate) fn on_before_print(&self) { if let Some(active_file) = &self.active_file { // Do NOT go through `` here. Two of the three // callers (`on_uncaught_exception`, test_command.rs report-status) // reach this while a `&mut BunTest` to the *same* cell payload is // live and reused afterward; materialising a sibling `&BunTest` // would pop the caller's Unique tag under Stacked Borrows. Read the // reporter field via raw ptr instead — `Option>` is `Copy`. // SAFETY: single-threaded; `active_file` keeps the cell alive; raw // field read creates no intermediate `&BunTest`. let reporter = unsafe { *core::ptr::addr_of!((*active_file.as_ptr()).reporter) }; if let Some(reporter) = reporter { // SAFETY: reporter outlives every BunTest (owned by test_command::exec). // `last_printed_dot` is `Cell` so a `&` borrow suffices. let reporter = unsafe { reporter.as_ref() }; if reporter.reporters.dots && reporter.last_printed_dot.get() { bun_core::pretty_error!("\n"); Output::flush(); reporter.last_printed_dot.set(false); } // `Jest::runner()` would hand out an exclusive `&mut TestRunner` while // `self: &BunTestRoot` — a field of that same TestRunner — is // live. Project `current_file` through the raw global ptr instead. if let Some(runner_ptr) = Jest::runner_ptr() { // SAFETY: single-threaded; disjoint field from `bun_test_root`. unsafe { (*core::ptr::addr_of_mut!((*runner_ptr.as_ptr()).current_file)).print_if_needed(); } } } } } } impl Drop for BunTestRoot { fn drop(&mut self) { debug_assert!(self.hook_scope.entries.is_empty()); // entries must not be appended to the hook_scope // hook_scope: Box dropped automatically debug_assert!(self.active_file.is_none()); } } #[derive(Copy, Clone)] pub(crate) struct FirstLast { pub(crate) first: bool, pub(crate) last: bool, } #[derive(Copy, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Phase { #[strum(serialize = "collection")] Collection, #[strum(serialize = "execution")] Execution, #[strum(serialize = "done")] Done, } pub(crate) struct BunTest { pub(crate) bun_test_root: bun_ptr::BackRef, pub(crate) in_run_loop: bool, // gpa / arena_allocator / arena dropped — see §Allocators (non-AST crate) pub(crate) file_id: FileId, /// null if the runner has moved on to the next file but a strong reference to BunTest is still keeping it alive /// /// Stored as /// `NonNull` (not `&`) so callbacks (`handle_test_completed`, junit writer, /// uncaught-exception handler) can write through it without deriving `&mut` /// from `&` (UB). The reporter is owned by `test_command::exec`'s stack /// frame, which never returns; `exit_file()` nulls this before drop. pub(crate) reporter: Option>, pub(crate) timer: EventLoopTimer, pub(crate) result_queue: ResultQueue, /// Whether tests in this file should default to concurrent execution pub(crate) default_concurrent: bool, pub(crate) first_last: FirstLast, pub(crate) extra_execution_entries: Vec<*mut ExecutionEntry>, /// Heap-boxed bitwise clones of hook entries from `Order::generate_order_test`. /// Only the Box header may be freed in `Drop` — fields alias `DescribeScope` originals. pub(crate) cloned_hook_entries: Vec<*mut ExecutionEntry>, pub(crate) wants_wakeup: bool, pub(crate) phase: Phase, pub(crate) collection: Collection, pub(crate) execution: Execution::Execution, } bun_event_loop::impl_timer_owner!(BunTest; from_timer_ptr => timer); impl BunTest { /// `bun_test_root` must point at the stable global `BunTestRoot` storage /// that outlives the returned `BunTest`. pub(crate) fn init( bun_test_root: NonNull, file_id: FileId, reporter: Option>, default_concurrent: bool, first_last: FirstLast, ) -> Self { let _g = group_begin!(); BunTest { bun_test_root: bun_ptr::BackRef::from(bun_test_root), in_run_loop: false, phase: Phase::Collection, file_id, collection: Collection::init(bun_test_root.as_ptr()), execution: Execution::Execution::init(), reporter, result_queue: ResultQueue::init(), default_concurrent, first_last, extra_execution_entries: Vec::new(), cloned_hook_entries: Vec::new(), // `EventLoopTimer` has no `Default`; `init_paused` sets // `next = EPOCH, state = PENDING`. timer: EventLoopTimer::init_paused(EventLoopTimerTag::BunTest), wants_wakeup: false, } } pub(crate) fn get_current_state_data(&self) -> RefDataValue { match self.phase { Phase::Collection => RefDataValue::Collection { active_scope: self.collection.active_scope, }, Phase::Execution => 'blk: { let Some(active_group) = self.execution.active_group_ref() else { debug_assert!(false); // should have switched phase if we're calling getCurrentStateData, but it could happen with re-entry maybe break 'blk RefDataValue::Done; }; let sequences = active_group.sequences(&self.execution); if sequences.len() != 1 { break 'blk RefDataValue::Execution { group_index: self.execution.group_index, entry_data: None, // the current execution entry is not known because we are running a concurrent test }; } let active_sequence_index = 0usize; let sequence = &sequences[active_sequence_index]; let Some(active_entry) = sequence.active_entry else { break 'blk RefDataValue::Execution { group_index: self.execution.group_index, entry_data: None, // the sequence is completed. }; }; RefDataValue::Execution { group_index: self.execution.group_index, entry_data: Some(EntryData { sequence_index: active_sequence_index, entry: active_entry.as_ptr().cast::<()>(), remaining_repeat_count: sequence.remaining_repeat_count as i64, }), } } Phase::Done => RefDataValue::Done, } } pub(crate) fn ref_(this_strong: &BunTestPtr, phase: RefDataValue) -> RefPtr { let _g = group_begin!(); bun_core::scoped_log!(bun_test_group, "ref: {}", phase); RefPtr::new(RefData { buntest_weak: Rc::downgrade(this_strong), phase, ref_count: bun_ptr::RefCount::init(), }) } fn bun_test_then_or_catch( global_this: &JSGlobalObject, callframe: &CallFrame, is_catch: bool, ) -> JsResult<()> { let _g = group_begin!(); let [result, this_ptr] = callframe.arguments_as_array::<2>(); if this_ptr.is_empty_or_undefined_or_null() { return Ok(()); } let raw_ref: *mut RefData = this_ptr.as_promise_ptr::(); // SAFETY: `raw_ref` was produced by `RefPtr::into_raw` in `run_test_callback` // and round-tripped via `as_promise_ptr`; we adopt the +1 it carried. let refdata = unsafe { RefPtr::from_raw(raw_ref) }; // Remove the pending_then_refs entry first so it never holds a freed `RefData`. if let Some(runner) = Jest::runner() { let mut pending = runner.bun_test_root.pending_then_refs.borrow_mut(); if let Some(pos) = pending.iter().position(|p| *p == raw_ref.cast_const()) { pending.swap_remove(pos); } } let has_one_ref = refdata.has_one_ref(); let Some(this_strong) = refdata.buntest_weak.upgrade() else { bun_core::scoped_log!(bun_test_group, "bunTestThenOrCatch -> the BunTest is no longer active"); return Ok(()); }; // SAFETY: `&mut` derived via `UnsafeCell`; not held across `run_next_tick` // (which itself calls `.get()` for a single field write). let this = this_strong.get(); if is_catch { this.on_uncaught_exception(global_this, Some(result), true, &refdata.phase); } if !has_one_ref && !is_catch { bun_core::scoped_log!(bun_test_group, "bunTestThenOrCatch -> refdata has multiple refs; don't add result until the last ref"); return Ok(()); } this.add_result(refdata.phase); // `this` borrow ends here (NLL); `run_next_tick` re-derives via `.get()`. Self::run_next_tick(&refdata.buntest_weak, global_this, refdata.phase); Ok(()) } // `#[bun_jsc::host_fn]` proc-macro emits a free-fn wrapper that // calls the annotated item by bare name; that lookup fails for associated // fns inside `impl` blocks. The extern-"C" trampoline is wired separately // (see the gated `Bun__TestScope__Describe2__*` statics below), so the // attribute is dropped here — these are plain JsResult fns. fn bun_test_then(global_this: &JSGlobalObject, callframe: &CallFrame) -> JsResult { Self::bun_test_then_or_catch(global_this, callframe, false)?; Ok(JSValue::UNDEFINED) } fn bun_test_catch(global_this: &JSGlobalObject, callframe: &CallFrame) -> JsResult { Self::bun_test_then_or_catch(global_this, callframe, true)?; Ok(JSValue::UNDEFINED) } pub(crate) fn bun_test_done_callback( global_this: &JSGlobalObject, callframe: &CallFrame, ) -> JsResult { let _g = group_begin!(); let Some(this) = DoneCallback::from_js(callframe.this()) else { return Err(global_this.throw(format_args!("Expected callee to be DoneCallback"))); }; let [value] = callframe.arguments_as_array::<1>(); let was_error = !value.is_empty_or_undefined_or_null(); // SAFETY: `this` is the live `*mut DoneCallback` returned by `from_js`; // single-threaded JS VM, GC keeps the wrapper alive for the call frame. if unsafe { (*this).called } { // in Bun 1.2.20, this is a no-op // in Jest, this is "Expected done to be called once, but it was called multiple times." // Vitest does not support done callbacks } else { // error is only reported for the first done() call if was_error { let _ = global_this.bun_vm().as_mut().uncaught_exception(global_this, value, false); } } // SAFETY: see above — `this` is a live `*mut DoneCallback`. let ref_in = unsafe { (*this).called = true; (*this).r#ref.take() }; let Some(ref_in) = ref_in else { return Ok(JSValue::UNDEFINED); }; // dupe the ref and enqueue a task to call the done callback. // this makes it so if you do something else after calling done(), the next test doesn't start running until the next tick. let has_one_ref = ref_in.has_one_ref(); let should_run = has_one_ref || was_error; if !should_run { return Ok(JSValue::UNDEFINED); } let Some(strong): Option = ref_in.buntest_weak.upgrade() else { return Ok(JSValue::UNDEFINED); }; // SAFETY: `&mut` derived via `UnsafeCell`; borrow ends before // `run_next_tick` re-derives. strong.get().add_result(ref_in.phase); Self::run_next_tick(&ref_in.buntest_weak, global_this, ref_in.phase); Ok(JSValue::UNDEFINED) } pub(crate) fn bun_test_timeout_callback( this_strong: &BunTestPtr, _ts: &Timespec, vm: &VirtualMachine, ) { let _g = group_begin!(); // Raw `*mut` (via `UnsafeCell`) because `Self::run` below re-enters and // calls `.get()` on the same `Rc` — holding a long-lived `&mut` across // that would alias. Each `(*this).x` is a fresh short-lived reborrow. let this: *mut BunTest = this_strong.as_ptr(); let global = vm.global(); // SAFETY: `this` derived from `UnsafeCell::get`; single-threaded; each // deref is a point-use that does not span a re-entrant `.get()`. unsafe { (*this).timer.next = ElTimespec::EPOCH; (*this).timer.state = EventLoopTimerState::PENDING; match (*this).phase { Phase::Collection => {} Phase::Execution => { if let Err(e) = (*this).execution.handle_timeout(global) { (*this).on_uncaught_exception(global, Some(global.take_exception(e)), false, &RefDataValue::Done); } } Phase::Done => {} } } if let Err(e) = Self::run(this_strong, global) { // SAFETY: re-derive after `run` returned; no `&mut` was held across it. unsafe { (*this).on_uncaught_exception(global, Some(global.take_exception(e)), false, &RefDataValue::Done) }; } } pub(crate) fn run_next_tick(weak: &BunTestPtrWeak, global_this: &JSGlobalObject, phase: RefDataValue) { let vm = global_this.bun_vm().as_mut(); // Check liveness before allocating so the early return doesn't strand a Box. let Some(strong) = weak.upgrade() else { debug_assert!(false); // shouldn't be calling runNextTick after moving on to the next file return; // but just in case }; let task = jsc::Task::from_boxed(Box::new(RunTestsTask { weak: Weak::clone(weak), global_this: GlobalRef::from(global_this), phase, })); // SAFETY: single field write through `UnsafeCell`; no other `&mut` live. strong.get().wants_wakeup = true; // we need to wake up the event loop so autoTick() doesn't wait for 16-100ms because we just enqueued a task vm.enqueue_task(task); } pub(crate) fn add_result(&mut self, result: RefDataValue) { let _ = self.result_queue.write_item(result); // OOM/capacity: fire-and-forget } pub(crate) fn run(this_strong: &BunTestPtr, global_this: &JSGlobalObject) -> JsResult<()> { let _g = group_begin!(); // `Collection::step` / `Execution::step` re-enter and call `.get()` on // the same `Rc`, so we keep a raw `*mut` (via `UnsafeCell`) and reborrow // per-use instead of holding one long-lived `&mut` that would alias. let this: *mut BunTest = this_strong.as_ptr(); // SAFETY: `this` is `UnsafeCell::get()`-derived; single-threaded JS VM; // each `(*this)` deref below is a short-lived reborrow that does not // span a re-entrant `.get()` call. unsafe { if (*this).in_run_loop { return Ok(()); } (*this).in_run_loop = true; } // The guard captures the raw ptr // (not a `&mut bool`) so no `&mut` is held across the loop body. let _reset = scopeguard::guard(this, |p| { // SAFETY: `p` is the same `UnsafeCell`-derived ptr; `this_strong` // keeps the allocation alive for the whole function. unsafe { (*p).in_run_loop = false } }); let mut min_timeout = Timespec::EPOCH; // SAFETY: see block-SAFETY above. `step()` may call `.get()` internally; // no outer `&mut` overlaps because we only touch `*this` between calls. while let Some(result) = unsafe { (*this).result_queue.read_item() } { global_this.clear_termination_exception(); // SAFETY: `UnsafeCell`-derived `*mut`; short-lived field read between re-entrant calls. let step_result: StepResult = match unsafe { (*this).phase } { Phase::Collection => Collection::step(this_strong, global_this, &result)?, Phase::Execution => Execution::Execution::step(this_strong, global_this, &result)?, Phase::Done => StepResult::Complete, }; match step_result { StepResult::Waiting { timeout } => { min_timeout = min_timeout.min_ignore_epoch(timeout); } StepResult::Complete => { // SAFETY: short-lived reborrow; `advance` does not re-enter `.get()`. if unsafe { (*this).advance(global_this)? } == Advance::Exit { return Ok(()); } // SAFETY: `UnsafeCell`-derived `*mut`; sole `&mut` for this enqueue. unsafe { (*this).add_result(RefDataValue::Start) }; } } } // SAFETY: loop done; sole `&mut` for the timer update. unsafe { (*this).update_min_timeout(global_this, &min_timeout) }; Ok(()) } fn update_min_timeout(&mut self, global_this: &JSGlobalObject, min_timeout: &Timespec) { let _g = group_begin!(); let _ = global_this; // only set the timer if the new timeout is sooner than the current timeout. this unfortunately means that we can't unset an unnecessary timer. bun_core::scoped_log!( bun_test_group, "-> timeout: {:?} {}.{}, {:?}", min_timeout, self.timer.next.sec, self.timer.next.nsec, order_ignore_epoch(min_timeout, &self.timer.next) ); if order_ignore_epoch(min_timeout, &self.timer.next) == core::cmp::Ordering::Less { bun_core::scoped_log!(bun_test_group, "-> setting timer to {:?}", min_timeout); if self.timer.next != ElTimespec::EPOCH { bun_core::scoped_log!(bun_test_group, "-> removing existing timer"); vm_timer().remove(&raw mut self.timer); } // `EventLoopTimer.next` uses the event-loop crate's local // `Timespec` (distinct from `bun_core::Timespec`); convert by field. self.timer.next = ElTimespec { sec: min_timeout.sec, nsec: min_timeout.nsec }; if self.timer.next != ElTimespec::EPOCH { bun_core::scoped_log!(bun_test_group, "-> inserting timer"); vm_timer().insert(&raw mut self.timer); if debug::group::get_log_enabled() { let duration = min_timeout.since_now_force_real_time(); bun_core::scoped_log!(bun_test_group, "-> timer duration: {}", duration); } } bun_core::scoped_log!(bun_test_group, "-> timer set"); } } fn advance(&mut self, _global_this: &JSGlobalObject) -> JsResult { let _g = group_begin!(); bun_core::scoped_log!(bun_test_group, "advance from {}", <&'static str>::from(self.phase)); // capture `self.phase` by raw ptr so the deferred log doesn't // hold a `&self` borrow across the `self.phase = …` writes below. let phase_ptr: *const Phase = &raw const self.phase; scopeguard::defer! { // SAFETY: `self` outlives this guard (drops at end of this fn body). bun_core::scoped_log!(bun_test_group, "advance -> {}", <&'static str>::from(unsafe { *phase_ptr })); } match self.phase { Phase::Collection => { self.phase = Phase::Execution; debug::dump_describe(&self.collection.root_scope)?; let has_filter = if let Some(reporter) = self.reporter { // SAFETY: reporter outlives every BunTest (see field doc). unsafe { reporter.as_ref() }.jest.filter_regex.is_some() } else { false }; // Derive a per-file shuffle PRNG from (seed, file_path) so a // file's test order depends only on the path and the printed // seed — not on which worker ran it or what files preceded it // on that worker. This is what makes --parallel --randomize // reproducible via --seed=N. let mut per_file_prng: Option = if let Some(reporter) = self.reporter { 'blk: { // SAFETY: reporter outlives every BunTest (see field doc). let reporter = unsafe { reporter.as_ref() }; let Some(seed) = reporter.jest.randomize_seed else { break 'blk None }; let path = reporter.jest.files.items_source()[self.file_id as usize].path.text; // Basename only so the hash is platform-independent (path // separators and absolute prefixes differ on Windows). Some(bun_core::rand::DefaultPrng::init( bun_wyhash::hash(bun_paths::basename(path)).wrapping_add(seed as u64), )) } } else { None }; // `Order::Config.randomize` takes the PRNG itself // (`Option`), so pass it through directly. let should_randomize = per_file_prng.take(); let mut order = Order::Order::init(Order::Config { always_use_hooks: self.collection.root_scope.base.only == Only::No && !has_filter, randomize: should_randomize, }); let root = self.bun_test_root.get(); let beforeall_order: Order::AllOrderResult = if self.first_last.first { order.generate_all_order(&root.hook_scope.before_all)? } else { Order::AllOrderResult::EMPTY }; let describe_seq_start = order.sequences.len(); order.generate_order_describe(&mut self.collection.root_scope)?; let describe_seq_end = order.sequences.len(); // Collect hook-entry clones boxed by `generate_order_test` so `Drop` can // reclaim the Box headers. Must run before `extra_execution_entries` are // spliced into the same chains, or the walk would double-free `DescribeScope` // entries. debug_assert!( self.extra_execution_entries.is_empty(), "extra_execution_entries must be spliced after the cloned-hook walk" ); for seq in &order.sequences[describe_seq_start..describe_seq_end] { let Some(test_entry) = seq.test_entry else { continue }; let mut cur = seq.first_entry; while let Some(p) = cur { if p != test_entry { self.cloned_hook_entries.push(p.as_ptr()); } // SAFETY: live linked-list nodes built by `generate_order_test`. cur = unsafe { p.as_ref() }.next.and_then(NonNull::new); } } beforeall_order.set_failure_skip_to(&mut order); let afterall_order: Order::AllOrderResult = if self.first_last.last { order.generate_all_order(&root.hook_scope.after_all)? } else { Order::AllOrderResult::EMPTY }; afterall_order.set_failure_skip_to(&mut order); self.execution.load_from_order(&mut order); debug::dump_order(&self.execution)?; Ok(Advance::Cont) } Phase::Execution => { self.in_run_loop = false; self.phase = Phase::Done; Ok(Advance::Exit) } Phase::Done => Ok(Advance::Exit), } } /// if sync, the result is returned. if async, None is returned. pub(crate) fn run_test_callback( this_strong: &BunTestPtr, global_this: &JSGlobalObject, cfg_callback: JSValue, cfg_done_parameter: bool, cfg_data: RefDataValue, timeout: &Timespec, ) -> Option { let _g = group_begin!(); // Raw `*mut` (via `UnsafeCell`) — the JS event-loop call below can // re-enter `bun_test_then_or_catch` / `bun_test_done_callback` / // `on_unhandled_rejection`, each of which `.get()`s the same `BunTest`. // Hold a raw ptr and reborrow per-use so no two `&mut` overlap. let this: *mut BunTest = this_strong.as_ptr(); let vm = global_this.bun_vm(); // Don't use Option to make it harder for the conservative stack // scanner to miss it. let mut done_arg: JSValue = JSValue::ZERO; let mut done_callback: JSValue = JSValue::ZERO; if cfg_done_parameter { bun_core::scoped_log!(bun_test_group, "callTestCallback -> appending done callback param: data {}", cfg_data); done_callback = DoneCallback::create_unbound(global_this); done_arg = match DoneCallback::bind(done_callback, global_this) { Ok(v) => v, Err(e) => { // SAFETY: `UnsafeCell`-derived; sole `&mut` at this point. unsafe { (*this).on_uncaught_exception(global_this, Some(global_this.take_exception(e)), false, &cfg_data) }; JSValue::ZERO // failed to bind done callback } }; } // SAFETY: `UnsafeCell`-derived; sole `&mut` at this point (before JS re-entry). unsafe { (*this).update_min_timeout(global_this, timeout) }; let args_slice: &[JSValue] = if !done_arg.is_empty() { core::slice::from_ref(&done_arg) } else { &[] }; let result: JSValue = match vm.event_loop_mut().run_callback_with_result_and_forcefully_drain_microtasks(bun_event_loop::ContextId::NONE, cfg_callback, global_this, JSValue::UNDEFINED, args_slice, ) { Ok(v) => v, Err(_) => { global_this.clear_termination_exception(); // SAFETY: re-derive after JS callback returned; no outer `&mut` was held across it. unsafe { (*this).on_uncaught_exception(global_this, global_this.try_take_exception(), false, &cfg_data) }; bun_core::scoped_log!(bun_test_group, "callTestCallback -> error"); JSValue::ZERO } }; done_callback.ensure_still_alive(); // Drain unhandled promise rejections. loop { // Prevent the user's Promise rejection from going into the uncaught promise rejection queue. if !result.is_empty() { if let Some(promise) = result.as_promise() { // SAFETY: `as_promise` returned a non-null GC-managed JSPromise. unsafe { if (*promise).status() == PromiseStatus::Rejected { (*promise).set_handled(); } } } } let prev_unhandled_count = vm.unhandled_error_counter; let _ = global_this.handle_rejected_promises(); if vm.unhandled_error_counter == prev_unhandled_count { break; } } // `dcb_ref` is a raw observer alias, NOT a // counted handle. The single +1 from `ref()` is owned by // `dcb_data.ref`; `dcb_ref` just remembers the address so the // pending-promise branch can `dupe()` it and the tail can branch on // "wait for done callback". Holding a second `RefPtr` here would // over-count and the done-callback path would never observe // `has_one_ref()`. let mut dcb_ref: Option> = None; if !done_callback.is_empty() && !result.is_empty() { if let Some(dcb_data) = DoneCallback::from_js(done_callback) { // SAFETY: `dcb_data` is the live `*mut DoneCallback` from `from_js`; // single-threaded JS VM, GC roots `done_callback` for this frame. if unsafe { (*dcb_data).called } { // done callback already called or the callback errored; add result immediately } else { let r = Self::ref_(this_strong, cfg_data); let alias = NonNull::new(r.as_ptr()) .expect("ref_() returns a freshly-boxed RefData"); // SAFETY: see above. Move the sole +1 into the DoneCallback. unsafe { (*dcb_data).r#ref = Some(r) }; dcb_ref = Some(alias); } } else { debug_assert!(false); // this should be unreachable, we create DoneCallback above } } if !result.is_empty() { if let Some(promise) = result.as_promise() { let _keep = bun_jsc::EnsureStillAlive(result); // because sometimes we use promise without result bun_core::scoped_log!(bun_test_group, "callTestCallback -> promise: data {}", cfg_data); // S012: `JSPromise` is an `opaque_ffi!` ZST — safe `*mut → &mut` deref. match bun_jsc::JSPromise::opaque_mut(promise).status() { PromiseStatus::Pending => { // not immediately resolved; register 'then' to handle the result when it becomes available let this_ref: RefPtr = if let Some(dcb_ref_value) = dcb_ref { // SAFETY: `dcb_ref_value` aliases the live RefData // owned by `dcb_data.r#ref` (set just above; GC // roots `done_callback` for this frame). Bump the // refcount 1→2. unsafe { RefPtr::init_ref(dcb_ref_value.as_ptr()) } } else { Self::ref_(this_strong, cfg_data) }; // Track the `+1` handed to `Promise.then()` in case the promise never settles. let raw_ref: *mut RefData = RefPtr::into_raw(this_ref); this_strong .bun_test_root .get() .pending_then_refs .borrow_mut() .push(raw_ref.cast_const()); let _ = result.then( global_this, raw_ref, Bun__TestScope__Describe2__bunTestThen, Bun__TestScope__Describe2__bunTestCatch, ); // TODO: properly propagate exception upwards return None; } PromiseStatus::Fulfilled => { // Do not register a then callback when it's already fulfilled. return Some(cfg_data); } PromiseStatus::Rejected => { let value = bun_jsc::JSPromise::opaque_mut(promise).result(global_this.vm()); // SAFETY: re-derive via `UnsafeCell` after the JS/microtask // drain above; sole `&mut` at this point. unsafe { (*this).on_uncaught_exception(global_this, Some(value), true, &cfg_data) }; // We previously marked it as handled above. return Some(cfg_data); } } } } if dcb_ref.is_some() { // completed asynchronously bun_core::scoped_log!(bun_test_group, "callTestCallback -> wait for done callback"); return None; } bun_core::scoped_log!(bun_test_group, "callTestCallback -> sync"); Some(cfg_data) } /// called from the uncaught exception handler, or if a test callback rejects or throws an error pub(crate) fn on_uncaught_exception( &mut self, global_this: &JSGlobalObject, exception: Option, is_rejection: bool, user_data: &RefDataValue, ) { let _g = group_begin!(); let _ = is_rejection; let handle_status: HandleUncaughtExceptionResult = match self.phase { Phase::Collection => self.collection.handle_uncaught_exception(user_data), Phase::Done => HandleUncaughtExceptionResult::ShowUnhandledErrorBetweenTests, Phase::Execution => self.execution.handle_uncaught_exception(user_data), }; bun_core::scoped_log!(bun_test_group, "onUncaughtException -> {}", <&'static str>::from(handle_status)); if handle_status == HandleUncaughtExceptionResult::HideError { return; // do not print error, it was already consumed } let Some(exception) = exception else { return; // the exception should not be visible (eg m_terminationException) }; let failure_ctx: *mut core::ffi::c_void = 'ctx: { if handle_status != HandleUncaughtExceptionResult::ShowHandledError { break 'ctx core::ptr::null_mut(); } let Some(reporter) = self.reporter else { break 'ctx core::ptr::null_mut(); }; // SAFETY: `BunTest.reporter` carries write provenance from `enter_file`'s // `&mut`; single-threaded test runner, no other borrow live here. let reporter = unsafe { &mut *reporter.as_ptr() }; if reporter.jest.test_options.reporters.junit { core::ptr::from_mut(&mut reporter.test_failure).cast() } else { core::ptr::null_mut() } }; self.bun_test_root.on_before_print(); if matches!( handle_status, HandleUncaughtExceptionResult::ShowUnhandledErrorBetweenTests | HandleUncaughtExceptionResult::ShowUnhandledErrorInDescribe ) { // SAFETY: reporter is Some (asserted by call sites that reach here); // `NonNull` carries write provenance from // `enter_file`'s `&mut`; single-threaded, no other borrow live. unsafe { (*self.reporter.unwrap().as_ptr()).jest.unhandled_errors_between_tests += 1; } bun_core::pretty_errorln!( "\n# Unhandled error between tests\n-------------------------------\n", ); Output::flush(); } let vm = global_this.bun_vm().as_mut(); if !failure_ctx.is_null() { vm.on_print_error_zig_exception = Some(crate::cli::test_command::TestFailure::record_cb); vm.on_print_error_zig_exception_ctx = failure_ctx; } print_error(vm, global_this, exception, None); if !failure_ctx.is_null() { vm.on_print_error_zig_exception = None; vm.on_print_error_zig_exception_ctx = core::ptr::null_mut(); } if matches!( handle_status, HandleUncaughtExceptionResult::ShowUnhandledErrorBetweenTests | HandleUncaughtExceptionResult::ShowUnhandledErrorInDescribe ) { bun_core::pretty_error!("-------------------------------\n\n"); } Output::flush(); } } /// Prints `error`, then prints any exception the error's getters or `toString` threw during the print. pub(crate) fn print_error( vm: &mut VirtualMachine, global_this: &JSGlobalObject, error: JSValue, exception_list: Option<&mut bun_jsc::virtual_machine::ExceptionList>, ) { vm.run_error_handler(error, exception_list); // `BunTest::run` and `run_test_callback` clear termination exceptions. if global_this.has_pending_termination_exception() { return; } let Some(left) = global_this.try_take_exception() else { return; }; vm.run_error_handler(left, None); // Printing this one could throw again, so just print a note. if !global_this.has_pending_termination_exception() && global_this.try_take_exception().is_some() { bun_core::pretty_errorln!("note: printing the error above threw another error"); Output::flush(); } } impl Drop for BunTest { fn drop(&mut self) { let _g = group_begin!(); if self.timer.state == EventLoopTimerState::ACTIVE { // must remove an active timer to prevent UAF (if the timer were to trigger after BunTest deinit) vm_timer().remove(&raw mut self.timer); } for entry in self.extra_execution_entries.drain(..) { // SAFETY: entries were heap-allocated in generic_hook; we own them unsafe { drop(bun_core::heap::take(entry)); } } for entry in self.cloned_hook_entries.drain(..) { // Reclaim only the Box header — fields alias the `DescribeScope` originals. // SAFETY: heap-boxed by `Order::generate_order_test`; same layout as `ManuallyDrop`. let _ = unsafe { Box::from_raw(entry.cast::>()) }; } // execution, collection, result_queue: dropped automatically } } // `ZigGlobalObject::promiseHandlerID` (C++) compares the fn-ptr passed to // `JSValue::then` against `&Bun__TestScope__Describe2__bunTestThen` by // identity, so the Rust thunk MUST be the symbol itself — exporting a // `static JSHostFn = thunk` puts the name in `.data` (nm `d`), and the address // C++ sees never matches the local thunk we hand to `.then()`, tripping the // `RELEASE_ASSERT_NOT_REACHED` at the bottom of `promiseHandlerID`. bun_jsc::jsc_host_abi! { #[unsafe(no_mangle)] pub unsafe fn Bun__TestScope__Describe2__bunTestThen( global: *mut JSGlobalObject, frame: *mut CallFrame, ) -> JSValue { // SAFETY: JSC passes non-null live pointers for both. let (global, frame) = unsafe { (&*global, &*frame) }; jsc::host_fn::to_js_host_fn_result(global, BunTest::bun_test_then(global, frame)) } } bun_jsc::jsc_host_abi! { #[unsafe(no_mangle)] pub unsafe fn Bun__TestScope__Describe2__bunTestCatch( global: *mut JSGlobalObject, frame: *mut CallFrame, ) -> JSValue { // SAFETY: JSC passes non-null live pointers for both. let (global, frame) = unsafe { (&*global, &*frame) }; jsc::host_fn::to_js_host_fn_result(global, BunTest::bun_test_catch(global, frame)) } } // Clone/Copy: bitwise OK — `entry` is a non-owning erased borrow of an // `ExecutionEntry` owned by `BunTest::execution`. #[derive(Copy, Clone)] pub(crate) struct EntryData { pub(crate) sequence_index: usize, pub(crate) entry: *const (), pub(crate) remaining_repeat_count: i64, } // Clone/Copy: bitwise OK — `active_scope` is a non-owning borrow of a // `DescribeScope` whose lifetime spans the async boundary (see field note); // `EntryData.entry` likewise borrows. #[derive(Clone, Copy)] pub(crate) enum RefDataValue { Start, Collection { // A borrowed `&'a DescribeScope` cannot work here: the pointer is stored // across async boundaries (promise .then), so no thread-able lifetime // exists. The scope is kept alive by the collection tree (Box-ed entries // under root_scope, owned by BunTest) until Phase::Done. active_scope: core::ptr::NonNull, }, Execution { group_index: usize, entry_data: Option, }, Done, } impl RefDataValue { pub(crate) fn sequence<'a>(&self, buntest: &'a mut BunTest) -> Option<&'a mut Execution::ExecutionSequence> { let RefDataValue::Execution { group_index, entry_data } = self else { return None }; let entry_data = (*entry_data)?; // reshaped for borrowck — `ConcurrentGroup::sequences_mut` // borrows `&mut Execution` while `group()` already holds a borrow into // `execution.groups`. Read `(sequence_start, sequence_end)` first, then // index `execution.sequences` directly. let group = buntest.execution.groups.get(*group_index)?; let (start, end) = (group.sequence_start, group.sequence_end); Some(&mut buntest.execution.sequences[start..end][entry_data.sequence_index]) } pub(crate) fn entry<'a>(&self, buntest: &'a mut BunTest) -> Option<&'a mut ExecutionEntry> { if !matches!(self, RefDataValue::Execution { .. }) { return None; } if buntest.phase != Phase::Execution { return None; } let (the_sequence, _) = buntest.execution.get_current_and_valid_execution_sequence(self)?; // SAFETY: `the_sequence` is a NonNull into `execution.sequences`; deref // at point-of-use only. `active_entry` is a valid intrusive node while // the sequence is live. unsafe { the_sequence.as_ref().active_entry.map(|p| &mut *p.as_ptr()) } } } impl fmt::Display for RefDataValue { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { RefDataValue::Start => write!(f, "start"), RefDataValue::Collection { active_scope } => { // SAFETY: active_scope is valid for the duration of collection phase let name = unsafe { &active_scope.as_ref().base.name }; match name { Some(n) => write!(f, "collection: active_scope={}", bstr::BStr::new(n.as_ref())), None => write!(f, "collection: active_scope=null"), } } RefDataValue::Execution { group_index, entry_data } => { if let Some(ed) = entry_data { write!( f, "execution: group_index={},sequence_index={},entry_index={:x},remaining_repeat_count={}", group_index, ed.sequence_index, ed.entry as usize, ed.remaining_repeat_count ) } else { write!(f, "execution: group_index={}", group_index) } } RefDataValue::Done => write!(f, "done"), } } } // Intrusive single-thread refcount. #[derive(bun_ptr::RefCounted)] pub(crate) struct RefData { pub(crate) buntest_weak: BunTestPtrWeak, pub(crate) phase: RefDataValue, pub(crate) ref_count: bun_ptr::RefCount, } impl Drop for RefData { fn drop(&mut self) { let _g = group_begin!(); bun_core::scoped_log!(bun_test_group, "refData: {}", self.phase); } } impl RefData { pub(crate) fn has_one_ref(&self) -> bool { self.ref_count.has_one_ref() } pub(crate) fn bun_test(&self) -> Option { self.buntest_weak.upgrade() } } pub(crate) struct RunTestsTask { pub(crate) weak: BunTestPtrWeak, // `GlobalRef` (not a borrow): the JSGlobalObject is stored across the task // tick, and the VM keeps it alive until shutdown. pub global_this: GlobalRef, pub(crate) phase: RefDataValue, } impl RunTestsTask { #[allow(clippy::boxed_local, reason = "reclaim point for the boxed task")] pub(crate) fn call(self: Box) -> JsResult<()> { let this = self; // Box drops at end of scope; the Weak drops with it. let Some(strong) = this.weak.upgrade() else { return Ok(()) }; if let Err(e) = BunTest::run(&strong, &this.global_this) { // A termination is the tick's to fold, not a test failure. if this.global_this.has_pending_termination_exception() { return Err(e); } // SAFETY: `&mut` derived via `UnsafeCell` after `run` returned; sole // borrow at this point. let bt = strong.get(); bt.on_uncaught_exception( &this.global_this, Some(this.global_this.take_exception(e)), false, &this.phase, ); } Ok(()) } } impl bun_event_loop::Taskable for RunTestsTask { const TAG: bun_event_loop::TaskTag = bun_event_loop::task_tag::RunTestsTask; unsafe fn release_unrun(this: *mut Self) { // SAFETY: fn contract — boxed in `run_next_tick`. drop(unsafe { bun_core::heap::take(this) }); } /// Enters no context. unsafe fn context(_: *const Self) -> bun_event_loop::ContextId { bun_event_loop::ContextId::NONE } } #[derive(Copy, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum HandleUncaughtExceptionResult { #[strum(serialize = "hide_error")] HideError, #[strum(serialize = "show_handled_error")] ShowHandledError, #[strum(serialize = "show_unhandled_error_between_tests")] ShowUnhandledErrorBetweenTests, #[strum(serialize = "show_unhandled_error_in_describe")] ShowUnhandledErrorInDescribe, } pub(crate) type ResultQueue = LinearFifo>; // bun.LinearFifo(.Dynamic) → second generic is the buffer strategy. pub(crate) enum StepResult { Waiting { timeout: Timespec }, Complete, } impl Default for StepResult { fn default() -> Self { StepResult::Waiting { timeout: Timespec::EPOCH } } } #[derive(Copy, Clone, PartialEq, Eq)] enum Advance { Cont, Exit, } pub(crate) use super::collection::Collection; #[derive(Copy, Clone, PartialEq, Eq, Default)] pub(crate) enum ConcurrentMode { #[default] Inherit, No, Yes, } #[derive(Copy, Clone, Default)] pub(crate) struct BaseScopeCfg { pub(crate) self_concurrent: ConcurrentMode, pub(crate) self_mode: ScopeMode, pub(crate) self_only: bool, pub(crate) test_id_for_debugger: i32, pub(crate) line_no: u32, } impl BaseScopeCfg { /// returns None if the other already has the value pub(crate) fn extend(self, other: BaseScopeCfg) -> Option { let mut result = self; if other.self_concurrent != ConcurrentMode::Inherit { if result.self_concurrent != ConcurrentMode::Inherit { return None; } result.self_concurrent = other.self_concurrent; } if other.self_mode != ScopeMode::Normal { if result.self_mode != ScopeMode::Normal { return None; } result.self_mode = other.self_mode; } if other.self_only { if result.self_only { return None; } result.self_only = true; } Some(result) } } #[derive(Copy, Clone, PartialEq, Eq, Default)] pub(crate) enum ScopeMode { #[default] Normal, Skip, Todo, Failing, FilteredOut, } impl ScopeMode { /// Lowercase variant name (e.g. "skip", "filtered_out") for labels/diagnostics. pub(crate) fn tag_name(self) -> &'static str { match self { Self::Normal => "normal", Self::Skip => "skip", Self::Todo => "todo", Self::Failing => "failing", Self::FilteredOut => "filtered_out", } } } #[derive(Copy, Clone, PartialEq, Eq)] pub(crate) enum Only { No, Contains, Yes, } impl Only { /// Lowercase variant name (e.g. "yes", "contains") for labels/diagnostics. pub(crate) fn tag_name(self) -> &'static str { match self { Self::No => "no", Self::Contains => "contains", Self::Yes => "yes", } } } pub(crate) struct BaseScope { pub(crate) parent: Option<*mut DescribeScope>, pub name: Option>, pub(crate) concurrent: bool, pub(crate) mode: ScopeMode, pub(crate) only: Only, pub(crate) has_callback: bool, /// this value is 0 unless the debugger is active and the scope has a debugger id pub(crate) test_id_for_debugger: i32, /// only available if using junit reporter, otherwise 0 pub(crate) line_no: u32, } impl BaseScope { pub(crate) fn init( cfg: BaseScopeCfg, name_not_owned: Option<&[u8]>, parent: Option<*mut DescribeScope>, has_callback: bool, ) -> BaseScope { // SAFETY: `parent` is a live backref into the describe tree; single-threaded, // and the parent outlives this child during construction. let parent_base = parent.map(|p| unsafe { &(*p).base }); BaseScope { parent, name: name_not_owned.map(Box::<[u8]>::from), concurrent: match cfg.self_concurrent { ConcurrentMode::Yes => true, ConcurrentMode::No => false, ConcurrentMode::Inherit => parent_base.is_some_and(|p| p.concurrent), }, mode: if let Some(p) = parent_base { if p.mode != ScopeMode::Normal { p.mode } else { cfg.self_mode } } else { cfg.self_mode }, only: if cfg.self_only { Only::Yes } else { Only::No }, has_callback, test_id_for_debugger: cfg.test_id_for_debugger, line_no: cfg.line_no, } } pub(crate) fn propagate(&mut self, has_callback: bool) { self.has_callback = has_callback; if let Some(parent) = self.parent { // SAFETY: parent backref valid; tree is single-threaded and parent // outlives child. Borrows are scoped to each call. unsafe { if self.only != Only::No { (*parent).mark_contains_only(); } if self.has_callback { (*parent).mark_has_callback(); } } } } } // deinit: only frees `name` → Box<[u8]> drops automatically; no explicit Drop needed. pub(crate) struct DescribeScope { pub(crate) base: BaseScope, pub(crate) entries: Vec, // The `Box` is load-bearing: `Order.rs` derives `*mut ExecutionEntry` from // box interiors and stores them in the intrusive `next`/`failure_skip_past` // chains; unboxing would dangle those pointers on `Vec` realloc. #[expect(clippy::vec_box)] pub(crate) before_all: Vec>, #[expect(clippy::vec_box)] pub(crate) before_each: Vec>, #[expect(clippy::vec_box)] pub(crate) after_each: Vec>, #[expect(clippy::vec_box)] pub(crate) after_all: Vec>, /// if true, the describe callback threw an error. do not run any tests declared in this scope. pub(crate) failed: bool, } impl Drop for DescribeScope { /// Drops nested scopes iteratively. The default drop recurses once per nested `describe()`. fn drop(&mut self) { let mut pending: Vec = core::mem::take(&mut self.entries); while let Some(entry) = pending.pop() { if let TestScheduleEntry::Describe(mut scope) = entry { pending.append(&mut scope.entries); // `scope.entries` is empty, so dropping `scope` here doesn't recurse. } } } } impl DescribeScope { pub(crate) fn create(base: BaseScope) -> Box { Box::new(DescribeScope { base, entries: Vec::new(), before_each: Vec::new(), before_all: Vec::new(), after_all: Vec::new(), after_each: Vec::new(), failed: false, }) } fn mark_contains_only(&mut self) { let mut target: Option<*mut DescribeScope> = Some(std::ptr::from_mut(self)); while let Some(scope_ptr) = target { // SAFETY: walking parent backrefs; tree is single-threaded let scope = unsafe { &mut *scope_ptr }; if scope.base.only == Only::Contains { return; // already marked } // note that we overwrite '.yes' with '.contains' to support only-inside-only scope.base.only = Only::Contains; target = scope.base.parent; } } fn mark_has_callback(&mut self) { let mut target: Option<*mut DescribeScope> = Some(std::ptr::from_mut(self)); while let Some(scope_ptr) = target { // SAFETY: walking parent backrefs; tree is single-threaded let scope = unsafe { &mut *scope_ptr }; if scope.base.has_callback { return; // already marked } scope.base.has_callback = true; target = scope.base.parent; } } /// Infallible: `Vec::push` aborts on OOM. pub(crate) fn append_describe( &mut self, name_not_owned: Option<&[u8]>, base: BaseScopeCfg, ) -> &mut DescribeScope { let mut child = Self::create(BaseScope::init(base, name_not_owned, Some(std::ptr::from_mut(self)), false)); child.base.propagate(false); self.entries.push(TestScheduleEntry::Describe(child)); match self.entries.last_mut().unwrap() { TestScheduleEntry::Describe(d) => &mut **d, _ => unreachable!(), } } pub(crate) fn append_test( &mut self, name_not_owned: Option<&[u8]>, callback: Option, cfg: ExecutionEntryCfg, base: BaseScopeCfg, phase: AddedInPhase, ) -> JsResult<&mut ExecutionEntry> { let mut entry = ExecutionEntry::create(name_not_owned, callback, cfg, Some(std::ptr::from_mut(self)), base, phase); let has_cb = entry.callback.is_some(); entry.base.propagate(has_cb); self.entries.push(TestScheduleEntry::TestCallback(entry)); match self.entries.last_mut().unwrap() { TestScheduleEntry::TestCallback(e) => Ok(&mut **e), _ => unreachable!(), } } // `Box` is load-bearing: see the `before_all` field comment. #[expect(clippy::vec_box)] pub(crate) fn get_hook_entries(&mut self, tag: HookTag) -> &mut Vec> { match tag { HookTag::BeforeAll => &mut self.before_all, HookTag::BeforeEach => &mut self.before_each, HookTag::AfterEach => &mut self.after_each, HookTag::AfterAll => &mut self.after_all, } } pub(crate) fn append_hook( &mut self, tag: HookTag, callback: Option, cfg: ExecutionEntryCfg, base: BaseScopeCfg, phase: AddedInPhase, ) -> JsResult<&mut ExecutionEntry> { let entry = ExecutionEntry::create(None, callback, cfg, Some(std::ptr::from_mut(self)), base, phase); let list = self.get_hook_entries(tag); list.push(entry); Ok(&mut **list.last_mut().unwrap()) } } #[derive(Copy, Clone, PartialEq, Eq)] pub(crate) enum HookTag { BeforeAll, BeforeEach, AfterEach, AfterAll, } #[derive(Copy, Clone, Default)] pub(crate) struct ExecutionEntryCfg { /// 0 = unlimited timeout pub(crate) timeout: u32, pub(crate) has_done_parameter: bool, /// Number of times to retry a failed test (0 = no retries) pub(crate) retry_count: u32, /// Number of times to repeat a test (0 = run once, 1 = run twice, etc.) pub(crate) repeat_count: u32, } #[derive(Copy, Clone, PartialEq, Eq)] pub(crate) enum AddedInPhase { Preload, Collection, Execution, } pub(crate) struct ExecutionEntry { pub(crate) base: BaseScope, pub callback: Option, /// 0 = unlimited timeout pub(crate) timeout: u32, pub(crate) has_done_parameter: bool, /// '.epoch' = not set /// when this entry begins executing, the timespec will be set to the current time plus the timeout(ms). pub(crate) timespec: Timespec, pub(crate) added_in_phase: AddedInPhase, /// Number of times to retry a failed test (0 = no retries) pub(crate) retry_count: u32, /// Number of times to repeat a test (0 = run once, 1 = run twice, etc.) pub(crate) repeat_count: u32, pub(crate) next: Option<*mut ExecutionEntry>, /// if this entry fails, go to the entry 'failure_skip_past.next' pub(crate) failure_skip_past: Option<*mut ExecutionEntry>, } impl ExecutionEntry { fn create( name_not_owned: Option<&[u8]>, cb: Option, cfg: ExecutionEntryCfg, parent: Option<*mut DescribeScope>, base: BaseScopeCfg, phase: AddedInPhase, ) -> Box { let mut entry = Box::new(ExecutionEntry { base: BaseScope::init(base, name_not_owned, parent, cb.is_some()), callback: None, timeout: cfg.timeout, has_done_parameter: cfg.has_done_parameter, added_in_phase: phase, retry_count: cfg.retry_count, repeat_count: cfg.repeat_count, timespec: Timespec::EPOCH, next: None, failure_skip_past: None, }); if let Some(c) = cb { entry.callback = match entry.base.mode { ScopeMode::Skip => None, ScopeMode::Todo => { let run_todo = Jest::runner().is_some_and(|runner| runner.run_todo); if run_todo { Some(strong_create(c)) } else { None } } _ => Some(strong_create(c)), }; } entry } pub(crate) fn evaluate_timeout( &self, sequence: &mut Execution::ExecutionSequence, now: &Timespec, ) -> bool { if !self.timespec.eql(&Timespec::EPOCH) && self.timespec.order(now) == core::cmp::Ordering::Less { // timed out // SAFETY: pointer-identity comparison only — no deref, no provenance laundering. let is_test_entry = sequence .test_entry .is_some_and(|p| core::ptr::eq(p.as_ptr().cast_const(), self)); sequence.result = if is_test_entry { if self.has_done_parameter { Execution::Result::FailBecauseTimeoutWithDoneCallback } else { Execution::Result::FailBecauseTimeout } } else if self.has_done_parameter { Execution::Result::FailBecauseHookTimeoutWithDoneCallback } else { Execution::Result::FailBecauseHookTimeout }; sequence.maybe_skip = true; return true; } false } } // destroy → Drop: callback (Strong) and base.name (Box) drop automatically. pub(crate) enum TestScheduleEntry { Describe(Box), TestCallback(Box), } impl TestScheduleEntry { // deinit → Drop on the Box variants; nothing to write. pub(crate) fn base(&mut self) -> &mut BaseScope { match self { TestScheduleEntry::Describe(describe) => &mut describe.base, TestScheduleEntry::TestCallback(test_callback) => &mut test_callback.base, } } } // Module aliases so `Execution::ConcurrentGroup` / `Order::AllOrderResult` // resolve as module paths without per-reference rewrites. pub(crate) use super::execution as Execution; pub(crate) use super::debug; pub(crate) use super::scope_functions as ScopeFunctions; pub(crate) use super::order as Order;