Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+3384
View File
File diff suppressed because it is too large Load Diff
+230
View File
@@ -0,0 +1,230 @@
//! Internal JSPI (JS Promise Integration) machinery.
//!
//! The public surface is a single function, `futures::jspi_block_on_promise`:
//! suspend the current promising execution until a JS `Promise` settles. The
//! executor side has no API at all — `spawn_local` (and everything built on
//! it, like `future_to_promise` and async exports) checks the ambient JSPI
//! context at spawn time and enters the task's polls through a
//! `WebAssembly.promising` boundary when spawned from within one, so sync
//! code reached from such a task may itself suspend. The capability is
//! inherited transitively: a task spawned from a promising-entered poll is
//! itself promising-entered.
//!
//! The runtime state is minimal by construction. The suspend bridge,
//! `__wbindgen_jspi_suspend`, is a plain `#[wasm_bindgen(catch, suspending)]`
//! import whose JS body is an identity function: JSPI itself awaits the
//! returned `Promise` and resumes with the settled value, while a rejection
//! is thrown into wasm as a `WebAssembly.JSTag` exception and marshalled to
//! `Err` by the standard `catch + suspending` machinery (see
//! `cli-support/src/transforms/jspi.rs`). The ambient context probe,
//! `__wbindgen_jspi_in_context`, is rewritten in-wasm by the CLI: it reads
//! the `__jspi_stack_base` global when JSPI instrumentation is active and is
//! a constant `0` otherwise, so modules that never use JSPI attributes carry
//! no JSPI machinery and keep running on engines without exnref/JSPI.
// The `suspending` attribute on the internal bridge import generates an
// experimental-status deprecation warning; this module is itself part of the
// experimental JSPI surface, so silence it here.
#![allow(deprecated)]
use crate::Promise;
use alloc::boxed::Box;
use alloc::rc::Rc;
use core::cell::{Cell, RefCell};
use core::future::Future;
use core::mem::ManuallyDrop;
use core::pin::Pin;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use wasm_bindgen::prelude::*;
#[wasm_bindgen(raw_module = "__wbindgen_placeholder__")]
extern "C" {
#[wasm_bindgen(catch, suspending)]
fn __wbindgen_jspi_suspend(promise: &Promise) -> Result<JsValue, JsValue>;
/// Whether a JSPI context is on the stack: a `#[wasm_bindgen(jspi)]`
/// export or a promising-entered poll. Rewritten in-wasm by the CLI to
/// read the `__jspi_stack_base` global (constant `0` in modules without
/// JSPI instrumentation); no JS shim is ever emitted.
fn __wbindgen_jspi_in_context() -> u32;
/// Schedules a task poll on the microtask queue, entered through the
/// promising-wrapped `__wbg_jspi_task_poll` export so the poll runs
/// on a fresh suspendable stack. Consumes one strong `Rc<SpawnedTask>`
/// reference, reclaimed by the trampoline.
fn __wbindgen_jspi_spawn_poll(task: u32);
/// The same operation, called only from the initial schedule in
/// [`spawn_promising`].
fn __wbindgen_jspi_spawn_first(task: u32);
}
/// Whether the caller is executing within a JSPI context, i.e. whether a
/// spawned task's polls should be promising-entered.
pub(crate) fn in_context() -> bool {
__wbindgen_jspi_in_context() != 0
}
/// Suspend the current promising execution until `promise` settles.
/// Backs `futures::jspi_block_on_promise`.
///
/// On return the shadow stack is guaranteed to hold the correct contents
/// for this execution, regardless of what else ran while it was suspended:
/// the wasm-bindgen CLI instruments every `#[wasm_bindgen(suspending)]`
/// import with an in-wasm wrapper that evacuates the live shadow-stack
/// region to a heap buffer before suspending and copies it back as the very
/// first instructions after resume (see `cli-support/src/transforms/jspi.rs`).
/// The `catch` marshalling (rejections as `Err` data) rides the same wrapper.
#[inline(never)]
pub(crate) fn suspend(promise: &Promise) -> Result<JsValue, JsValue> {
__wbindgen_jspi_suspend(promise)
}
// ─── Promising-entered task polls ────────────────────────────────────────────
/// Poll-in-flight discipline for a spawned task.
#[derive(Clone, Copy, PartialEq)]
enum State {
/// Not scheduled and not being polled.
Idle,
/// A poll is queued on the microtask queue but has not started.
Scheduled,
/// A poll is in flight — executing, or suspended mid-frame.
Running,
/// A wake arrived during the in-flight poll: re-poll before going idle.
RunningWoken,
}
struct SpawnedTask {
/// `None` once the future has completed (late wakes are no-ops).
future: RefCell<Option<Pin<Box<dyn Future<Output = ()>>>>>,
state: Cell<State>,
}
impl SpawnedTask {
/// Schedule a poll, consuming one strong reference into the intrinsic.
fn schedule(this: Rc<SpawnedTask>) {
this.state.set(State::Scheduled);
__wbindgen_jspi_spawn_poll(Rc::into_raw(this) as u32);
}
fn wake(this: &Rc<SpawnedTask>) {
match this.state.get() {
// In flight (possibly suspended): flag a re-poll. The poll loop
// consumes the flag when the in-flight poll returns, so the
// future is never entered reentrantly.
State::Running => this.state.set(State::RunningWoken),
State::RunningWoken | State::Scheduled => {}
State::Idle => {
if this.future.borrow().is_some() {
SpawnedTask::schedule(Rc::clone(this));
}
}
}
}
fn poll(this: &Rc<SpawnedTask>) {
loop {
this.state.set(State::Running);
let waker = task_waker(Rc::clone(this));
let mut cx = Context::from_waker(&waker);
let done = {
let mut slot = this.future.borrow_mut();
let Some(future) = slot.as_mut() else { return };
// The poll may suspend; `slot` stays mutably borrowed across
// the suspension, which is sound because every other path to
// the future first checks `state` (`Running`) and never
// touches the `RefCell`.
match future.as_mut().poll(&mut cx) {
Poll::Ready(()) => {
*slot = None;
true
}
Poll::Pending => false,
}
};
if done {
this.state.set(State::Idle);
return;
}
match this.state.replace(State::Idle) {
// Woken while the poll was in flight: re-poll.
State::RunningWoken => continue,
_ => return,
}
}
}
}
/// A `Waker` over `Rc<SpawnedTask>`. As in `task::singlethread`, `Waker`'s
/// nominal `Send + Sync` demand is safely ignored: JSPI is single-threaded
/// (rejected under the `atomics` feature), so the lie is confined to the
/// vtable.
fn task_waker(task: Rc<SpawnedTask>) -> Waker {
unsafe fn raw_clone(ptr: *const ()) -> RawWaker {
let rc = ManuallyDrop::new(Rc::from_raw(ptr as *const SpawnedTask));
RawWaker::new(Rc::into_raw(Rc::clone(&rc)) as *const (), &VTABLE)
}
unsafe fn raw_wake(ptr: *const ()) {
let rc = Rc::from_raw(ptr as *const SpawnedTask);
SpawnedTask::wake(&rc);
}
unsafe fn raw_wake_by_ref(ptr: *const ()) {
let rc = ManuallyDrop::new(Rc::from_raw(ptr as *const SpawnedTask));
SpawnedTask::wake(&rc);
}
unsafe fn raw_drop(ptr: *const ()) {
drop(Rc::from_raw(ptr as *const SpawnedTask));
}
static VTABLE: RawWakerVTable =
RawWakerVTable::new(raw_clone, raw_wake, raw_wake_by_ref, raw_drop);
unsafe { Waker::from_raw(RawWaker::new(Rc::into_raw(task) as *const (), &VTABLE)) }
}
/// The promising-entered poll trampoline. Each call runs one task's poll
/// loop on a fresh suspendable stack. Not public API.
///
/// A raw wasm export rather than a `#[wasm_bindgen(jspi)]` one: the CLI
/// special-cases it by name — in a module with `#[wasm_bindgen(jspi)]`
/// exports it receives the same in-wasm wrapper as a jspi export and is
/// invoked through `WebAssembly.promising` by the spawn intrinsics' JS
/// shims; in a module without them the ambient context is constant-false,
/// so the export is deleted and the spawn intrinsics are stubbed out,
/// leaving no JSPI machinery at all.
///
/// `extern "C-unwind"`: an unwind must be able to escape the poll — a panic
/// under panic=unwind, or a rethrown rejection of a non-`catch` suspending
/// import — to reject the promising call's promise. Plain `extern "C"` is
/// nounwind, whose `panic_cannot_unwind` guard would abort the whole
/// instance instead of abandoning the one task.
#[no_mangle]
pub extern "C-unwind" fn __wbg_jspi_task_poll(task: u32) {
let task = unsafe { Rc::from_raw(task as *const SpawnedTask) };
SpawnedTask::poll(&task);
}
/// Runs a `Future<Output = ()>` with every poll entered through a
/// `WebAssembly.promising` boundary, so the task's whole call tree may
/// suspend. Backs `spawn_local` when called within a JSPI context —
/// including the rooted activation of a `#[wasm_bindgen(jspi)] async fn`
/// export.
///
/// A suspension parks only this task's poll; the microtask queue, other
/// tasks, and the event loop continue. A wake arriving while the poll is
/// suspended re-polls after the suspended poll returns. The task is leaked
/// if its future never completes, exactly like `spawn_local`.
pub(crate) fn spawn_promising<F>(future: F)
where
F: Future<Output = ()> + 'static,
{
let task = Rc::new(SpawnedTask {
future: RefCell::new(Some(Box::pin(future))),
state: Cell::new(State::Scheduled),
});
__wbindgen_jspi_spawn_first(Rc::into_raw(task) as u32);
}
+415
View File
@@ -0,0 +1,415 @@
//! Converting between JavaScript `Promise`s to Rust `Future`s.
//!
//! This module provides a bridge for working with JavaScript `Promise` types as
//! a Rust `Future`, and similarly contains utilities to turn a rust `Future`
//! into a JavaScript `Promise`. This can be useful when working with
//! asynchronous or otherwise blocking work in Rust (wasm), and provides the
//! ability to interoperate with JavaScript events and JavaScript I/O
//! primitives.
//!
//! There are three main interfaces in this module currently:
//!
//! 1. [**`JsFuture`**](./struct.JsFuture.html)
//!
//! A type that is constructed with a `Promise` and can then be used as a
//! `Future<Output = Result<JsValue, JsValue>>`. This Rust future will resolve
//! or reject with the value coming out of the `Promise`.
//!
//! 2. [**`future_to_promise`**](./fn.future_to_promise.html)
//!
//! Converts a Rust `Future<Output = Result<JsValue, JsValue>>` into a
//! JavaScript `Promise`. The future's result will translate to either a
//! resolved or rejected `Promise` in JavaScript.
//!
//! 3. [**`spawn_local`**](./fn.spawn_local.html)
//!
//! Spawns a `Future<Output = ()>` on the current thread. This is the
//! best way to run a `Future` in Rust without sending it to JavaScript.
//!
//! These three items should provide enough of a bridge to interoperate the two
//! systems and make sure that Rust/JavaScript can work together with
//! asynchronous and I/O work.
extern crate alloc;
#[cfg(not(target_feature = "atomics"))]
mod jspi;
use crate::Promise;
use alloc::rc::Rc;
use core::cell::RefCell;
use core::fmt;
use core::future::{Future, IntoFuture};
use core::panic::AssertUnwindSafe;
use core::pin::Pin;
use core::task::{Context, Poll, Waker};
#[cfg(all(
all(target_family = "wasm", not(target_os = "wasi")),
feature = "std",
panic = "unwind"
))]
use futures_util::FutureExt;
use wasm_bindgen::__rt::marker::ErasableGeneric;
#[cfg(all(
all(target_family = "wasm", not(target_os = "wasi")),
feature = "std",
panic = "unwind"
))]
use wasm_bindgen::__rt::panic_to_panic_error;
use wasm_bindgen::convert::{FromWasmAbi, Upcast};
use wasm_bindgen::sys::Promising;
use wasm_bindgen::{prelude::*, JsError, JsGeneric};
#[cfg_attr(docsrs, doc(cfg(feature = "futures-core-03-stream")))]
#[cfg(feature = "futures-core-03-stream")]
pub mod stream;
mod queue;
mod task {
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(target_feature = "atomics")] {
mod wait_async_polyfill;
mod multithread;
pub(crate) use multithread::*;
} else {
mod singlethread;
pub(crate) use singlethread::*;
}
}
}
/// Runs a Rust `Future` on the current thread.
///
/// The `future` must be `'static` because it will be scheduled
/// to run in the background and cannot contain any stack references.
///
/// The `future` will always be run on the next microtask tick even if it
/// immediately returns `Poll::Ready`.
///
/// # JSPI
///
/// When called from within a JSPI context — a `#[wasm_bindgen(jspi)]` export
/// or a task itself spawned from one — the task's polls are entered through
/// a `WebAssembly.promising` boundary, so sync code reached from the future
/// may suspend via [`jspi_block_on_promise`]. The capability is inherited
/// transitively down the spawn tree; a suspension parks only that task's
/// poll. In modules that never use JSPI attributes this branch compiles to a
/// constant and no JSPI machinery is emitted.
///
/// # Panics
///
/// This function has the same panic behavior as `future_to_promise`.
#[inline]
pub fn spawn_local<F>(future: F)
where
F: Future<Output = ()> + 'static,
{
#[cfg(not(target_feature = "atomics"))]
if jspi::in_context() {
jspi::spawn_promising(future);
return;
}
task::Task::spawn(future);
}
/// Suspend the current JSPI execution until `promise` settles, returning the
/// resolved value as `Ok` or the rejection reason as `Err` — without
/// blocking the event loop, and without an `async` call chain.
///
/// May only be called where a `WebAssembly.promising` frame is on the stack:
/// within a `#[wasm_bindgen(jspi)]` export, or a task spawned (transitively)
/// from a JSPI context. Calling it elsewhere throws a `SuspendError` at
/// runtime.
///
/// Promises are eager, so concurrency composes at the promise level: start
/// several JS calls, then suspend on each or on a `Promise::all` /
/// `Promise::race` combination. A Rust `Future` is awaited by suspending on
/// its completion promise: `jspi_block_on_promise(&future_to_promise(fut))`.
#[cfg(not(target_feature = "atomics"))]
#[deprecated(note = "JSPI support is experimental and subject to change; \
`jspi_block_on_promise` requires a runtime with WebAssembly \
JS Promise Integration enabled")]
pub fn jspi_block_on_promise(promise: &Promise) -> Result<JsValue, JsValue> {
jspi::suspend(promise)
}
struct Inner<T = JsValue> {
result: Option<Result<T, JsValue>>,
task: Option<Waker>,
callbacks: Option<(
Closure<dyn FnMut(T) -> Result<(), JsError>>,
Closure<dyn FnMut(JsValue) -> Result<(), JsError>>,
)>,
}
/// A Rust `Future` backed by a JavaScript `Promise`.
///
/// This type is constructed with a JavaScript `Promise` object and translates
/// it to a Rust `Future`. This type implements the `Future` trait from the
/// `futures` crate and will either succeed or fail depending on what happens
/// with the JavaScript `Promise`.
///
/// Currently this type is constructed with `JsFuture::from`.
pub struct JsFuture<T = JsValue> {
inner: Rc<RefCell<Inner<T>>>,
}
impl core::panic::UnwindSafe for JsFuture {}
unsafe impl<T> ErasableGeneric for JsFuture<T> {
type Repr = JsFuture<JsValue>;
}
// Upcast for JsFuture is covariant in T (the success type)
// JsFuture<T> can upcast to JsFuture<Target> if T: Upcast<Target>
impl<T, Target> Upcast<JsFuture<Target>> for JsFuture<T> where T: Upcast<Target> {}
impl<T> fmt::Debug for JsFuture<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "JsFuture {{ ... }}")
}
}
// `FromWasmAbi` is what the closure shim invokes on the resolved value;
// no layout equivalence with `JsValue` is required at this seam — the
// per-type `from_abi` does the conversion (e.g. for dynamic unions it
// runs the variant dispatcher).
impl<T: FromWasmAbi + 'static> From<Promise<T>> for JsFuture<T> {
fn from(js: Promise<T>) -> JsFuture<T> {
// Use the `then` method to schedule two callbacks, one for the
// resolved value and one for the rejected value. We're currently
// assuming that JS engines will unconditionally invoke precisely one of
// these callbacks, no matter what.
//
// Ideally we'd have a way to cancel the callbacks getting invoked and
// free up state ourselves when this `JsFuture` is dropped. We don't
// have that, though, and one of the callbacks is likely always going to
// be invoked.
//
// As a result we need to make sure that no matter when the callbacks
// are invoked they are valid to be called at any time, which means they
// have to be self-contained. Through the `Closure::once` and some
// `Rc`-trickery we can arrange for both instances of `Closure`, and the
// `Rc`, to all be destroyed once the first one is called.
let state = Rc::new(RefCell::new(Inner::<T> {
result: None,
task: None,
callbacks: None,
}));
fn finish<T>(state: &RefCell<Inner<T>>, val: Result<T, JsValue>) {
let task = {
let mut state = state.borrow_mut();
assert!(
state.callbacks.is_some(),
"finish: callbacks should be Some"
);
assert!(state.result.is_none(), "finish: result should be None");
// First up drop our closures as they'll never be invoked again and
// this is our chance to clean up their state.
drop(state.callbacks.take());
// Next, store the value into the internal state.
state.result = Some(val);
state.task.take()
};
// And then finally if any task was waiting on the value wake it up and
// let them know it's there.
if let Some(task) = task {
task.wake()
}
}
let resolve = {
let state = AssertUnwindSafe(state.clone());
Closure::once(move |val: T| {
finish(&*state, Ok(val));
Ok(())
})
};
let reject = {
let state = AssertUnwindSafe(state.clone());
Closure::once(move |val| {
finish(&*state, Err(val));
Ok(())
})
};
let _ = js.then_with_reject(&resolve, &reject);
state.borrow_mut().callbacks = Some((resolve, reject));
JsFuture { inner: state }
}
}
impl<T> Future for JsFuture<T> {
type Output = Result<T, JsValue>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut inner = self.inner.borrow_mut();
// If our value has come in then we return it...
if let Some(val) = inner.result.take() {
return Poll::Ready(val);
}
// ... otherwise we arrange ourselves to get woken up once the value
// does come in
inner.task = Some(cx.waker().clone());
Poll::Pending
}
}
impl<T: FromWasmAbi + 'static> IntoFuture for Promise<T> {
type Output = Result<T, JsValue>;
type IntoFuture = JsFuture<T>;
fn into_future(self) -> JsFuture<T> {
JsFuture::from(self)
}
}
/// Converts a Rust `Future` into a JavaScript `Promise`.
///
/// This function will take any future in Rust and schedule it to be executed,
/// returning a JavaScript `Promise` which can then be passed to JavaScript.
///
/// The `future` must be `'static` because it will be scheduled to run in the
/// background and cannot contain any stack references.
///
/// The returned `Promise` will be resolved or rejected when the future
/// completes, depending on whether it finishes with `Ok` or `Err`.
///
/// # Panics
///
/// Note that in Wasm panics are currently translated to aborts, but "abort" in
/// this case means that a JavaScript exception is thrown. The Wasm module is
/// still usable (likely erroneously) after Rust panics.
#[cfg(not(all(
all(target_family = "wasm", not(target_os = "wasi")),
feature = "std",
panic = "unwind"
)))]
pub fn future_to_promise<F>(future: F) -> Promise
where
F: Future<Output = Result<JsValue, JsValue>> + 'static,
{
let mut future = Some(future);
Promise::new_typed(&mut move |resolve, reject| {
let future = future.take().unwrap_throw();
spawn_local(async move {
match future.await {
Ok(val) => {
resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
}
Err(val) => {
reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
}
}
});
})
}
/// Converts a Rust `Future` into a JavaScript `Promise`.
///
/// This function will take any future in Rust and schedule it to be executed,
/// returning a JavaScript `Promise` which can then be passed to JavaScript.
///
/// The `future` must be `'static` because it will be scheduled to run in the
/// background and cannot contain any stack references.
///
/// The returned `Promise` will be resolved or rejected when the future
/// completes, depending on whether it finishes with `Ok` or `Err`.
///
/// # Panics
///
/// If the `future` provided panics then the returned `Promise` will be rejected
/// with a PanicError.
#[cfg(all(
all(target_family = "wasm", not(target_os = "wasi")),
feature = "std",
panic = "unwind"
))]
pub fn future_to_promise<F>(future: F) -> Promise
where
F: Future<Output = Result<JsValue, JsValue>> + 'static + std::panic::UnwindSafe,
{
// Wrap `future` in AssertUnwindSafe and move it into the closure so the closure
// satisfies MaybeUnwindSafe (required when panic=unwind). Using `move` avoids
// capturing a `&mut` reference, which is never UnwindSafe. The Promise executor
// is not called inside a panic-catching context, so this is always safe.
let mut future = core::panic::AssertUnwindSafe(Some(future));
Promise::new(&mut move |resolve, reject| {
let future = future.take().unwrap_throw();
spawn_local(async move {
let res = future.catch_unwind().await;
match res {
Ok(Ok(val)) => {
resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
}
Ok(Err(val)) => {
reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
}
Err(val) => {
reject
.call(&JsValue::UNDEFINED, (&panic_to_panic_error(val),))
.unwrap_throw();
}
}
});
})
}
// Note: Once we bump MSRV, we can type future_to_promise with backwards compatible inference.
/// Converts a Rust `Future` into a corresponding typed JavaScript `Promise<T>`.
///
/// This function will take any future in Rust and schedule it to be executed,
/// returning a JavaScript `Promise` which can then be passed to JavaScript.
///
/// The `future` must be `'static` because it will be scheduled to run in the
/// background and cannot contain any stack references.
///
/// The returned `Promise` will be resolved or rejected when the future completes,
/// depending on whether it finishes with `Ok` or `Err`.
///
/// # Panics
///
/// Note that in Wasm panics are currently translated to aborts, but "abort" in
/// this case means that a JavaScript exception is thrown. The Wasm module is
/// still usable (likely erroneously) after Rust panics.
///
/// If the `future` provided panics then the returned `Promise` **will not
/// resolve**. Instead it will be a leaked promise. This is an unfortunate
/// limitation of Wasm currently that's hoped to be fixed one day!
pub fn future_to_promise_typed<T, F>(future: F) -> Promise<<T as Promising>::Resolution>
where
F: Future<Output = Result<T, JsValue>> + 'static,
T: Promising + FromWasmAbi + JsGeneric,
<T as Promising>::Resolution: JsGeneric,
{
let mut future = Some(future);
Promise::new_typed(&mut move |resolve, reject| {
let future = future.take().unwrap_throw();
spawn_local(async move {
match future.await {
Ok(val) => {
resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
}
Err(val) => {
reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
}
}
});
})
}
+123
View File
@@ -0,0 +1,123 @@
use crate::Promise;
use alloc::collections::VecDeque;
use alloc::rc::Rc;
use core::cell::{Cell, RefCell};
use core::panic::AssertUnwindSafe;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsError;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen]
fn queueMicrotask(closure: &Closure<dyn FnMut(JsValue) -> Result<(), JsError>>);
type Global;
#[wasm_bindgen(method, getter, js_name = queueMicrotask)]
fn hasQueueMicrotask(this: &Global) -> JsValue;
}
struct QueueState {
// The queue of Tasks which are to be run in order. In practice this is all the
// synchronous work of futures, and each `Task` represents calling `poll` on
// a future "at the right time".
tasks: RefCell<VecDeque<Rc<crate::futures::task::Task>>>,
// This flag indicates whether we've scheduled `run_all` to run in the future.
// This is used to ensure that it's only scheduled once.
is_scheduled: Cell<bool>,
}
impl QueueState {
fn run_all(&self) {
// "consume" the schedule
let _was_scheduled = self.is_scheduled.replace(false);
debug_assert!(_was_scheduled);
// Stop when all tasks that have been scheduled before this tick have been run.
// Tasks that are scheduled while running tasks will run on the next tick.
let mut task_count_left = self.tasks.borrow().len();
while task_count_left > 0 {
task_count_left -= 1;
let task = match self.tasks.borrow_mut().pop_front() {
Some(task) => task,
None => break,
};
task.run();
}
// All of the Tasks have been run, so it's now possible to schedule the
// next tick again
}
}
pub(crate) struct Queue {
state: Rc<QueueState>,
promise: Promise,
closure: Closure<dyn FnMut(JsValue) -> Result<(), JsError>>,
has_queue_microtask: bool,
}
impl Queue {
// Schedule a task to run on the next tick
pub(crate) fn schedule_task(&self, task: Rc<crate::futures::task::Task>) {
self.state.tasks.borrow_mut().push_back(task);
// Use queueMicrotask to execute as soon as possible. If it does not exist
// fall back to the promise resolution
if !self.state.is_scheduled.replace(true) {
if self.has_queue_microtask {
queueMicrotask(&self.closure);
} else {
let _ = self.promise.then_map(&self.closure);
}
}
}
// Append a task to the currently running queue, or schedule it
#[cfg(not(target_feature = "atomics"))]
pub(crate) fn push_task(&self, task: Rc<crate::futures::task::Task>) {
// It would make sense to run this task on the same tick. For now, we
// make the simplifying choice of always scheduling tasks for a future tick.
self.schedule_task(task)
}
}
impl Queue {
fn new() -> Self {
let state = Rc::new(QueueState {
is_scheduled: Cell::new(false),
tasks: RefCell::new(VecDeque::new()),
});
let has_queue_microtask = crate::global()
.unchecked_into::<Global>()
.hasQueueMicrotask()
.is_function();
Self {
promise: Promise::resolve(&JsValue::undefined()),
closure: {
let state = AssertUnwindSafe(Rc::clone(&state));
// This closure will only be called on the next microtask event
// tick
Closure::new(move |_| {
state.run_all();
Ok(())
})
},
state,
has_queue_microtask,
}
}
pub(crate) fn with<R>(f: impl FnOnce(&Self) -> R) -> R {
use wasm_bindgen::__rt::LazyCell;
#[cfg_attr(target_feature = "atomics", thread_local)]
static QUEUE: LazyCell<Queue> = LazyCell::new(Queue::new);
f(&QUEUE)
}
}
+81
View File
@@ -0,0 +1,81 @@
//! Converting JavaScript `AsyncIterator`s to Rust `Stream`s.
//!
//! Analogous to the promise to future conversion, this module allows
//! turning objects implementing the async iterator protocol into `Stream`s
//! that produce values that can be awaited from.
//!
use super::JsFuture;
use crate::{AsyncIterator, IteratorNext};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use futures_core::stream::Stream;
use wasm_bindgen::convert::FromWasmAbi;
use wasm_bindgen::{prelude::*, JsGeneric};
/// A `Stream` that yields values from an underlying `AsyncIterator`.
pub struct JsStream<T = JsValue> {
iter: AsyncIterator<T>,
next: Option<JsFuture<IteratorNext<T>>>,
done: bool,
}
impl<T: JsGeneric + FromWasmAbi> JsStream<T> {
fn next_future(&self) -> Result<JsFuture<IteratorNext<T>>, JsValue> {
self.iter.next_iterator().map(JsFuture::from)
}
}
impl<T> From<AsyncIterator<T>> for JsStream<T> {
fn from(iter: AsyncIterator<T>) -> Self {
JsStream {
iter,
next: None,
done: false,
}
}
}
impl<T: JsGeneric + FromWasmAbi + Unpin> Stream for JsStream<T> {
type Item = Result<T, JsValue>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
if self.done {
return Poll::Ready(None);
}
let future = match self.next.as_mut() {
Some(val) => val,
None => match self.next_future() {
Ok(val) => {
self.next = Some(val);
self.next.as_mut().unwrap()
}
Err(e) => {
self.done = true;
return Poll::Ready(Some(Err(e)));
}
},
};
match Pin::new(future).poll(cx) {
Poll::Ready(res) => match res {
Ok(next) => {
if next.done() {
self.done = true;
Poll::Ready(None)
} else {
self.next.take();
Poll::Ready(Some(Ok(next.value())))
}
}
Err(e) => {
self.done = true;
Poll::Ready(Some(Err(e)))
}
},
Poll::Pending => Poll::Pending,
}
}
}
+13
View File
@@ -0,0 +1,13 @@
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(target_feature = "atomics")] {
mod wait_async_polyfill;
mod multithread;
pub(crate) use multithread::*;
} else {
mod singlethread;
pub(crate) use singlethread::*;
}
}
+240
View File
@@ -0,0 +1,240 @@
#![allow(clippy::incompatible_msrv)]
use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::sync::Arc;
use core::cell::RefCell;
use core::future::Future;
use core::mem::ManuallyDrop;
use core::pin::Pin;
use core::sync::atomic::AtomicI32;
use core::sync::atomic::Ordering::SeqCst;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
use core::arch::wasm32 as wasm;
#[cfg(target_arch = "wasm64")]
use core::arch::wasm64 as wasm;
const SLEEPING: i32 = 0;
const AWAKE: i32 = 1;
struct AtomicWaker {
state: AtomicI32,
}
impl AtomicWaker {
fn new() -> Arc<Self> {
Arc::new(Self {
state: AtomicI32::new(AWAKE),
})
}
fn wake_by_ref(&self) {
// If we're already AWAKE then we previously notified and there's
// nothing to do...
match self.state.swap(AWAKE, SeqCst) {
AWAKE => return,
other => debug_assert_eq!(other, SLEEPING),
}
// ... otherwise we execute the native `notify` instruction to wake up
// the corresponding `waitAsync` that was waiting for the transition
// from SLEEPING to AWAKE.
unsafe {
wasm::memory_atomic_notify(
self.state.as_ptr(),
1, // Number of threads to notify
);
}
}
/// Same as the singlethread module, this creates a standard library
/// `RawWaker`. We could use `futures_util::task::ArcWake` but it's small
/// enough that we just inline it for now.
unsafe fn into_raw_waker(this: Arc<Self>) -> RawWaker {
unsafe fn raw_clone(ptr: *const ()) -> RawWaker {
let ptr = ManuallyDrop::new(Arc::from_raw(ptr as *const AtomicWaker));
AtomicWaker::into_raw_waker((*ptr).clone())
}
unsafe fn raw_wake(ptr: *const ()) {
let ptr = Arc::from_raw(ptr as *const AtomicWaker);
AtomicWaker::wake_by_ref(&ptr);
}
unsafe fn raw_wake_by_ref(ptr: *const ()) {
let ptr = ManuallyDrop::new(Arc::from_raw(ptr as *const AtomicWaker));
AtomicWaker::wake_by_ref(&ptr);
}
unsafe fn raw_drop(ptr: *const ()) {
drop(Arc::from_raw(ptr as *const AtomicWaker));
}
const VTABLE: RawWakerVTable =
RawWakerVTable::new(raw_clone, raw_wake, raw_wake_by_ref, raw_drop);
RawWaker::new(Arc::into_raw(this) as *const (), &VTABLE)
}
}
struct Inner {
future: Pin<Box<dyn Future<Output = ()> + 'static>>,
closure: Closure<dyn FnMut(JsValue)>,
}
pub(crate) struct Task {
atomic: Arc<AtomicWaker>,
waker: Waker,
// See `singlethread.rs` for why this is an internal `Option`.
inner: RefCell<Option<Inner>>,
}
impl Task {
pub(crate) fn spawn(future: impl Future<Output = ()> + 'static) {
let atomic = AtomicWaker::new();
let waker = unsafe { Waker::from_raw(AtomicWaker::into_raw_waker(atomic.clone())) };
let this = Rc::new(Task {
atomic,
waker,
inner: RefCell::new(None),
});
let closure = {
let this = Rc::clone(&this);
// `own_assert_unwind_safe` is required because the closure captures
// `Rc<Task>`, which isn't `UnwindSafe`. A poll unwinding out of
// `run` frees the `Task` via a drop guard to avoid a leak.
Closure::own_assert_unwind_safe(move |_| {
// The promise resolution acts like a wake, so ensure the state
// transitions to AWAKE before entering `run`.
this.atomic.wake_by_ref();
this.run();
})
};
*this.inner.borrow_mut() = Some(Inner {
future: Box::pin(future),
closure,
});
// Queue up the Future's work to happen on the next microtask tick.
crate::futures::queue::Queue::with(move |queue| queue.schedule_task(this));
}
pub(crate) fn run(&self) {
// A poll can unwind via either a Rust panic or a JS
// exception. `catch_unwind` only catches the former, but both run
// drops, so a drop guard covers both: if a poll unwinds we drop
// `Inner`, releasing the future and breaking the
// `Inner -> closure -> Rc<Task>` cycle that would otherwise leak the
// `Task`. The guard is forgotten on a normal return.
struct ClearOnUnwind<'a>(&'a RefCell<Option<Inner>>);
impl Drop for ClearOnUnwind<'_> {
fn drop(&mut self) {
*self.0.borrow_mut() = None;
}
}
let clear_on_unwind = ClearOnUnwind(&self.inner);
let mut borrow = self.inner.borrow_mut();
// Same as `singlethread.rs`, handle spurious wakeups happening after we
// finished.
let inner = match borrow.as_mut() {
Some(inner) => inner,
None => {
core::mem::forget(clear_on_unwind);
return;
}
};
loop {
// Also the same as `singlethread.rs`, flag ourselves as ready to
// receive a notification.
let prev = self.atomic.state.swap(SLEEPING, SeqCst);
debug_assert_eq!(prev, AWAKE);
let poll = {
let mut cx = Context::from_waker(&self.waker);
inner.future.as_mut().poll(&mut cx)
};
match poll {
// Same as `singlethread.rs` (noticing a pattern?) clean up
// resources associated with the future ASAP.
Poll::Ready(()) => {
*borrow = None;
}
// Unlike `singlethread.rs` we are responsible for ensuring there's
// a closure to handle the notification that a Future is ready. In
// the single-threaded case the notification itself enqueues work,
// but in the multithreaded case we don't know what thread a
// notification comes from so we need to ensure the current running
// thread is the one that enqueues the work. To do that we execute
// `Atomics.waitAsync`, creating a local Promise on our own thread
// which will resolve once `Atomics.notify` is called.
//
// We could be in one of two states as we execute this:
//
// * `SLEEPING` - we'll get notified via `Atomics.notify`
// and then this Promise will resolve.
//
// * `AWAKE` - the Promise will immediately be resolved and
// we'll execute the work on the next microtask queue.
Poll::Pending => {
match wait_async(&self.atomic.state, SLEEPING) {
Some(promise) => drop(promise.then(&inner.closure)),
// our state has already changed so we can just do the work
// again inline.
None => continue,
}
}
}
break;
}
core::mem::forget(clear_on_unwind);
}
}
fn wait_async(ptr: &AtomicI32, current_value: i32) -> Option<crate::Promise> {
// If `Atomics.waitAsync` isn't defined then we use our fallback, otherwise
// we use the native function.
return if Atomics::get_wait_async().is_undefined() {
Some(crate::futures::task::wait_async_polyfill::wait_async(
ptr,
current_value,
))
} else {
let mem = wasm_bindgen::memory().unchecked_into::<crate::WebAssembly::Memory>();
let array = crate::Int32Array::new(&mem.buffer());
let result = Atomics::wait_async(&array, ptr.as_ptr() as u32 / 4, current_value);
if result.async_() {
Some(result.value())
} else {
None
}
};
#[wasm_bindgen]
extern "C" {
type Atomics;
type WaitAsyncResult;
#[wasm_bindgen(static_method_of = Atomics, js_name = waitAsync)]
fn wait_async(buf: &crate::Int32Array, index: u32, value: i32) -> WaitAsyncResult;
#[wasm_bindgen(static_method_of = Atomics, js_name = waitAsync, getter)]
fn get_wait_async() -> JsValue;
#[wasm_bindgen(method, getter, structural, js_name = async)]
fn async_(this: &WaitAsyncResult) -> bool;
#[wasm_bindgen(method, getter, structural)]
fn value(this: &WaitAsyncResult) -> crate::Promise;
}
}
+204
View File
@@ -0,0 +1,204 @@
use alloc::boxed::Box;
use alloc::rc::Rc;
use core::cell::{Cell, RefCell};
use core::future::Future;
use core::mem::ManuallyDrop;
use core::pin::Pin;
use core::task::{Context, RawWaker, RawWakerVTable, Waker};
struct Inner {
future: Pin<Box<dyn Future<Output = ()> + 'static>>,
waker: Waker,
}
impl Inner {
fn is_ready(&mut self) -> bool {
let mut cx = Context::from_waker(&self.waker);
self.future.as_mut().poll(&mut cx).is_ready()
}
}
#[cfg(debug_assertions)]
#[wasm_bindgen::prelude::wasm_bindgen]
extern "C" {
type ConsoleTask;
#[wasm_bindgen(thread_local_v2, js_namespace = console, js_name = createTask)]
static CREATE_TASK: Option<crate::Function<fn(crate::JsString) -> ConsoleTask>>;
#[wasm_bindgen(method)]
fn run(this: &ConsoleTask, poll: &mut dyn FnMut() -> bool) -> bool;
}
#[cfg(debug_assertions)]
fn try_create_task(name: &str) -> Option<ConsoleTask> {
CREATE_TASK.with(|create_task| {
create_task.as_ref().and_then(|f| {
f.call(&wasm_bindgen::JsValue::UNDEFINED, (&name.into(),))
.ok()
})
})
}
pub(crate) struct Task {
// Console tracking for this task to avoid deeply nested stacks from individual `poll()` calls.
// See [Linked Stack Traces](https://developer.chrome.com/blog/devtools-modern-web-debugging#linked_stack_traces).
#[cfg(debug_assertions)]
console: Option<ConsoleTask>,
// The actual Future that we're executing as part of this task.
//
// This is an Option so that the Future can be immediately dropped when it's
// finished
inner: RefCell<Option<Inner>>,
// This is used to ensure that the Task will only be queued once
is_queued: Cell<bool>,
}
impl Task {
pub(crate) fn spawn<F: Future<Output = ()> + 'static>(future: F) {
let this = Rc::new(Self {
#[cfg(debug_assertions)]
console: try_create_task(core::any::type_name::<F>()),
inner: RefCell::new(None),
is_queued: Cell::new(true),
});
let waker = unsafe { Waker::from_raw(Task::into_raw_waker(Rc::clone(&this))) };
*this.inner.borrow_mut() = Some(Inner {
future: Box::pin(future),
waker,
});
crate::futures::queue::Queue::with(|queue| queue.schedule_task(this));
}
fn force_wake(this: Rc<Self>) {
crate::futures::queue::Queue::with(|queue| {
queue.push_task(this);
});
}
fn wake(this: Rc<Self>) {
// If we've already been placed on the run queue then there's no need to
// requeue ourselves since we're going to run at some point in the
// future anyway.
if this.is_queued.replace(true) {
return;
}
Self::force_wake(this);
}
fn wake_by_ref(this: &Rc<Self>) {
// If we've already been placed on the run queue then there's no need to
// requeue ourselves since we're going to run at some point in the
// future anyway.
if this.is_queued.replace(true) {
return;
}
Self::force_wake(Rc::clone(this));
}
/// Creates a standard library `RawWaker` from an `Rc` of ourselves.
///
/// Note that in general this is wildly unsafe because everything with
/// Futures requires `Sync` + `Send` with regard to Wakers. For wasm,
/// however, everything is guaranteed to be singlethreaded (since we're
/// compiled without the `atomics` feature) so we "safely lie" and say our
/// `Rc` pointer is good enough.
///
/// The implementation is based off of futures::task::ArcWake
unsafe fn into_raw_waker(this: Rc<Self>) -> RawWaker {
unsafe fn raw_clone(ptr: *const ()) -> RawWaker {
let ptr = ManuallyDrop::new(Rc::from_raw(ptr as *const Task));
Task::into_raw_waker(Rc::clone(&ptr))
}
unsafe fn raw_wake(ptr: *const ()) {
let ptr = Rc::from_raw(ptr as *const Task);
Task::wake(ptr);
}
unsafe fn raw_wake_by_ref(ptr: *const ()) {
let ptr = ManuallyDrop::new(Rc::from_raw(ptr as *const Task));
Task::wake_by_ref(&ptr);
}
unsafe fn raw_drop(ptr: *const ()) {
drop(Rc::from_raw(ptr as *const Task));
}
static VTABLE: RawWakerVTable =
RawWakerVTable::new(raw_clone, raw_wake, raw_wake_by_ref, raw_drop);
RawWaker::new(Rc::into_raw(this) as *const (), &VTABLE)
}
pub(crate) fn run(&self) {
// A poll can unwind via either a Rust panic or a foreign (JS)
// exception. `catch_unwind` only catches the former, but both run
// drops, so a drop guard covers both: if a poll unwinds we drop
// `Inner`, releasing the future and breaking the
// `Inner -> Waker -> Rc<Task>` cycle that would otherwise leak the
// `Task`. The guard is disarmed (forgotten) on a normal return.
struct ClearOnUnwind<'a>(&'a RefCell<Option<Inner>>);
impl Drop for ClearOnUnwind<'_> {
fn drop(&mut self) {
*self.0.borrow_mut() = None;
}
}
let clear_on_unwind = ClearOnUnwind(&self.inner);
let mut borrow = self.inner.borrow_mut();
// Wakeups can come in after a Future has finished and been destroyed,
// so handle this gracefully by just ignoring the request to run.
let inner = match borrow.as_mut() {
Some(inner) => inner,
None => {
core::mem::forget(clear_on_unwind);
return;
}
};
// Ensure that if poll calls `waker.wake()` we can get enqueued back on
// the run queue.
self.is_queued.set(false);
// In debug mode we want to avoid deeply nested stacks from individual
// `poll()` calls, so we use `task.run` on a task created per future.
#[cfg(debug_assertions)]
let is_ready = match self.console.as_ref() {
// Wrap `inner` in AssertUnwindSafe before capturing it, so the closure
// satisfies MaybeUnwindSafe (required when panic=unwind). This is safe:
// a panic from `is_ready` propagates as usual and is handled by the
// `ClearOnUnwind` guard above.
Some(console) => {
let mut inner = core::panic::AssertUnwindSafe(inner);
console.run(&mut move || inner.is_ready())
}
None => inner.is_ready(),
};
// In release mode we prefer to avoid the overhead of the JS wrapper
// and just poll directly.
#[cfg(not(debug_assertions))]
let is_ready = inner.is_ready();
// If a future has finished (`Ready`) then clean up resources associated
// with the future ASAP. This ensures that we don't keep anything extra
// alive in-memory by accident. Our own struct, `Rc<Task>` won't
// actually go away until all wakers referencing us go away, which may
// take quite some time, so ensure that the heaviest of resources are
// released early.
if is_ready {
*borrow = None;
}
core::mem::forget(clear_on_unwind);
}
}
+77
View File
@@ -0,0 +1,77 @@
//! Polyfill for `Atomics.waitAsync` using a dedicated `Worker` per wait.
//! Workers are pooled and reused. The worker communicates the result back via
//! `postMessage`, which resolves a `Promise` on the calling thread.
#![allow(clippy::incompatible_msrv)]
use crate::{Array, Function, Promise};
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;
use core::sync::atomic::AtomicI32;
use wasm_bindgen::prelude::*;
// Inline bindings for the web Worker and MessageEvent APIs.
// These replace the web-sys dependency, which would create a circular
// dependency since web-sys depends on js-sys.
#[wasm_bindgen]
extern "C" {
#[derive(Clone)]
type Worker;
type MessageEvent;
#[wasm_bindgen(constructor)]
fn new_worker(url: &str) -> Worker;
#[wasm_bindgen(method, js_name = postMessage, catch)]
fn post_message(this: &Worker, msg: &JsValue) -> Result<(), JsValue>;
#[wasm_bindgen(method, setter, js_name = onmessage)]
fn set_onmessage(this: &Worker, cb: Option<&Function>);
#[wasm_bindgen(method, getter)]
fn data(this: &MessageEvent) -> JsValue;
}
#[thread_local]
static HELPERS: RefCell<Vec<Worker>> = RefCell::new(vec![]);
fn alloc_helper() -> Worker {
if let Some(helper) = HELPERS.borrow_mut().pop() {
return helper;
}
let worker_url = wasm_bindgen::link_to!(module = "/src/futures/task/worker.js");
Worker::new_worker(&worker_url)
}
fn free_helper(helper: Worker) {
let mut helpers = HELPERS.borrow_mut();
helpers.push(helper.clone());
helpers.truncate(10); // random arbitrary limit chosen here
}
pub fn wait_async(ptr: &AtomicI32, value: i32) -> Promise {
Promise::new(&mut |resolve, _reject| {
let helper = alloc_helper();
let helper_ref = helper.clone();
let onmessage_callback = Closure::once_into_js(move |e: MessageEvent| {
// Our helper is done waiting so it's available to wait on a
// different location, so return it to the free list.
free_helper(helper_ref);
drop(resolve.call1(&JsValue::NULL, &e.data()));
});
helper.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
let data = Array::of3(
&wasm_bindgen::memory(),
&JsValue::from(ptr.as_ptr() as u32 / 4),
&JsValue::from(value),
);
helper
.post_message(&data)
.unwrap_or_else(|js| wasm_bindgen::throw_val(js));
})
}
+6
View File
@@ -0,0 +1,6 @@
onmessage = function (ev) {
let [ia, index, value] = ev.data;
ia = new Int32Array(ia.buffer);
let result = Atomics.wait(ia, index, value);
postMessage(result);
};
+14245
View File
File diff suppressed because it is too large Load Diff