Default all async support to std::future (#1741)

This commit defaults all crates in-tree to use `std::future` by default
and none of them support the crates.io `futures` 0.1 crate any more.
This is a breaking change for `wasm-bindgen-futures` and
`wasm-bindgen-test` so they've both received a major version bump to
reflect the new defaults. Historical versions of these crates should
continue to work if necessary, but they won't receive any more
maintenance after this is merged.

The movement here liberally uses `async`/`await` to remove the need for
using any combinators on the `Future` trait. As a result many of the
crates now rely on a much more recent version of the compiler,
especially to run tests.

The `wasm-bindgen-futures` crate was updated to remove all of its
futures-related dependencies and purely use `std::future`, hopefully
improving its compatibility by not having any version compat
considerations over time. The implementations of the executors here are
relatively simple and only delve slightly into the `RawWaker` business
since there are no other stable APIs in `std::task` for wrapping these.

This commit also adds support for:

    #[wasm_bindgen_test]
    async fn foo() {
        // ...
    }

where previously you needed to pass `(async)` now that's inferred
because it's an `async fn`.

Closes #1558
Closes #1695
This commit is contained in:
Alex Crichton
2019-09-05 11:18:36 -05:00
committed by GitHub
parent ba85275d7d
commit 3c887c40b7
33 changed files with 643 additions and 1120 deletions

View File

@ -1,6 +1,6 @@
[package]
name = "wasm-bindgen-test"
version = "0.2.50"
version = "0.3.0"
authors = ["The wasm-bindgen Developers"]
description = "Internal testing crate for wasm-bindgen"
license = "MIT/Apache-2.0"
@ -9,12 +9,11 @@ edition = "2018"
[dependencies]
console_error_panic_hook = '0.1'
futures = "0.1"
js-sys = { path = '../js-sys', version = '0.3.27' }
scoped-tls = "1.0"
wasm-bindgen = { path = '../..', version = '0.2.50' }
wasm-bindgen-futures = { path = '../futures', version = '0.3.27' }
wasm-bindgen-test-macro = { path = '../test-macro', version = '=0.2.50' }
wasm-bindgen-futures = { path = '../futures', version = '0.4.0' }
wasm-bindgen-test-macro = { path = '../test-macro', version = '=0.3.0' }
[lib]
test = false

View File

@ -2,12 +2,12 @@
name = "sample"
version = "0.1.0"
authors = ["The wasm-bindgen Developers"]
edition = "2018"
[lib]
test = false
[dependencies]
futures = "0.1"
js-sys = { path = '../../js-sys' }
wasm-bindgen = { path = '../../..' }
wasm-bindgen-futures = { path = '../../futures' }

View File

@ -1,28 +1,23 @@
#[macro_use]
extern crate futures;
extern crate js_sys;
extern crate wasm_bindgen;
extern crate wasm_bindgen_futures;
use std::time::Duration;
use futures::prelude::*;
use js_sys::Promise;
use std::task::{Poll, Context};
use std::pin::Pin;
use std::time::Duration;
use wasm_bindgen::prelude::*;
use std::future::Future;
use wasm_bindgen_futures::JsFuture;
pub struct Timeout {
id: u32,
id: JsValue,
inner: JsFuture,
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = setTimeout)]
fn set_timeout(closure: JsValue, millis: f64) -> u32;
fn set_timeout(closure: JsValue, millis: f64) -> JsValue;
#[wasm_bindgen(js_name = clearTimeout)]
fn clear_timeout(id: u32);
fn clear_timeout(id: &JsValue);
}
impl Timeout {
@ -47,17 +42,15 @@ impl Timeout {
}
impl Future for Timeout {
type Item = ();
type Error = JsValue;
type Output = ();
fn poll(&mut self) -> Poll<(), JsValue> {
let _obj = try_ready!(self.inner.poll());
Ok(().into())
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
Pin::new(&mut self.inner).poll(cx).map(|_| ())
}
}
impl Drop for Timeout {
fn drop(&mut self) {
clear_timeout(self.id);
clear_timeout(&self.id);
}
}

View File

@ -1,8 +1,3 @@
extern crate futures;
extern crate sample;
extern crate wasm_bindgen;
extern crate wasm_bindgen_test;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
pub mod common;

View File

@ -1,8 +1,5 @@
use std::time::Duration;
use futures::prelude::*;
use sample::Timeout;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
@ -10,15 +7,13 @@ fn pass() {
console_log!("DO NOT SEE ME");
}
#[wasm_bindgen_test(async)]
fn pass_after_2s() -> impl Future<Item = (), Error = JsValue> {
#[wasm_bindgen_test]
async fn pass_after_2s() {
console_log!("immediate log");
Timeout::new(Duration::new(1, 0)).and_then(|()| {
console_log!("log after 1s");
Timeout::new(Duration::new(1, 0)).map(|()| {
console_log!("log at end");
})
})
Timeout::new(Duration::new(1, 0)).await;
console_log!("log after 1s");
Timeout::new(Duration::new(1, 0)).await;
console_log!("log at end");
}
#[wasm_bindgen_test]
@ -27,16 +22,13 @@ fn fail() {
panic!("this is a failing test");
}
#[wasm_bindgen_test(async)]
fn fail_after_3s() -> impl Future<Item = (), Error = JsValue> {
#[wasm_bindgen_test]
async fn fail_after_3s() {
console_log!("immediate log");
Timeout::new(Duration::new(1, 0)).and_then(|()| {
console_log!("log after 1s");
Timeout::new(Duration::new(1, 0)).and_then(|()| {
console_log!("log after 2s");
Timeout::new(Duration::new(1, 0)).map(|()| {
panic!("end");
})
})
})
Timeout::new(Duration::new(1, 0)).await;
console_log!("log after 1s");
Timeout::new(Duration::new(1, 0)).await;
console_log!("log after 2s");
Timeout::new(Duration::new(1, 0)).await;
panic!("end");
}

View File

@ -1,6 +1 @@
extern crate futures;
extern crate sample;
extern crate wasm_bindgen;
extern crate wasm_bindgen_test;
pub mod common;

View File

@ -87,14 +87,14 @@
// Overall this is all somewhat in flux as it's pretty new, and feedback is
// always of course welcome!
use console_error_panic_hook;
use js_sys::{Array, Function, Promise};
use std::cell::{Cell, RefCell};
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use console_error_panic_hook;
use futures::future;
use futures::prelude::*;
use js_sys::{Array, Function, Promise};
use std::task::{self, Poll};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::future_to_promise;
@ -157,7 +157,7 @@ struct State {
/// future is polled.
struct Test {
name: String,
future: Box<dyn Future<Item = (), Error = JsValue>>,
future: Pin<Box<dyn Future<Output = Result<(), JsValue>>>>,
output: Rc<RefCell<Output>>,
}
@ -286,10 +286,11 @@ impl Context {
// Now that we've collected all our tests we wrap everything up in a
// future to actually do all the processing, and pass it out to JS as a
// `Promise`.
let future = ExecuteTests(self.state.clone())
.map(JsValue::from)
.map_err(|e| match e {});
future_to_promise(future)
let state = self.state.clone();
future_to_promise(async {
let passed = ExecuteTests(state).await;
Ok(JsValue::from(passed))
})
}
}
@ -358,7 +359,7 @@ impl Context {
/// Entry point for a synchronous test in wasm. The `#[wasm_bindgen_test]`
/// macro generates invocations of this method.
pub fn execute_sync(&self, name: &str, f: impl FnOnce() + 'static) {
self.execute(name, future::lazy(|| Ok(f())));
self.execute(name, async { f() });
}
/// Entry point for an asynchronous in wasm. The
@ -366,12 +367,12 @@ impl Context {
/// method.
pub fn execute_async<F>(&self, name: &str, f: impl FnOnce() -> F + 'static)
where
F: Future<Item = (), Error = JsValue> + 'static,
F: Future<Output = ()> + 'static,
{
self.execute(name, future::lazy(f))
self.execute(name, async { f().await })
}
fn execute(&self, name: &str, test: impl Future<Item = (), Error = JsValue> + 'static) {
fn execute(&self, name: &str, test: impl Future<Output = ()> + 'static) {
// If our test is filtered out, record that it was filtered and move
// on, nothing to do here.
let filter = self.state.filter.borrow();
@ -392,7 +393,7 @@ impl Context {
};
self.state.remaining.borrow_mut().push(Test {
name: name.to_string(),
future: Box::new(future),
future: Pin::from(Box::new(future)),
output,
});
}
@ -400,23 +401,19 @@ impl Context {
struct ExecuteTests(Rc<State>);
enum Never {}
impl Future for ExecuteTests {
type Item = bool;
type Error = Never;
type Output = bool;
fn poll(&mut self) -> Poll<bool, Never> {
fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<bool> {
let mut running = self.0.running.borrow_mut();
let mut remaining = self.0.remaining.borrow_mut();
// First up, try to make progress on all active tests. Remove any
// finished tests.
for i in (0..running.len()).rev() {
let result = match running[i].future.poll() {
Ok(Async::Ready(_jsavl)) => Ok(()),
Ok(Async::NotReady) => continue,
Err(e) => Err(e),
let result = match running[i].future.as_mut().poll(cx) {
Poll::Ready(result) => result,
Poll::Pending => continue,
};
let test = running.remove(i);
self.0.log_test_result(test, result);
@ -431,13 +428,12 @@ impl Future for ExecuteTests {
Some(test) => test,
None => break,
};
let result = match test.future.poll() {
Ok(Async::Ready(())) => Ok(()),
Ok(Async::NotReady) => {
let result = match test.future.as_mut().poll(cx) {
Poll::Ready(result) => result,
Poll::Pending => {
running.push(test);
continue;
}
Err(e) => Err(e),
};
self.0.log_test_result(test, result);
}
@ -445,7 +441,7 @@ impl Future for ExecuteTests {
// Tests are still executing, we're registered to get a notification,
// keep going.
if running.len() != 0 {
return Ok(Async::NotReady);
return Poll::Pending;
}
// If there are no tests running then we must have finished everything,
@ -454,7 +450,7 @@ impl Future for ExecuteTests {
self.0.print_results();
let all_passed = self.0.failures.borrow().len() == 0;
Ok(Async::Ready(all_passed))
Poll::Ready(all_passed)
}
}
@ -561,17 +557,28 @@ extern "C" {
fn __wbg_test_invoke(f: &mut dyn FnMut()) -> Result<(), JsValue>;
}
impl<F: Future<Error = JsValue>> Future for TestFuture<F> {
type Item = F::Item;
type Error = F::Error;
impl<F: Future> Future for TestFuture<F> {
type Output = Result<F::Output, JsValue>;
fn poll(&mut self) -> Poll<F::Item, F::Error> {
let test = &mut self.test;
fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Self::Output> {
let output = self.output.clone();
// Use `new_unchecked` here to project our own pin, and we never
// move `test` so this should be safe
let test = unsafe { Pin::map_unchecked_mut(self, |me| &mut me.test) };
let mut future_output = None;
CURRENT_OUTPUT.set(&self.output, || {
__wbg_test_invoke(&mut || future_output = Some(test.poll()))
})?;
future_output.unwrap()
let result = CURRENT_OUTPUT.set(&output, || {
let mut test = Some(test);
__wbg_test_invoke(&mut || {
let test = test.take().unwrap_throw();
future_output = Some(test.poll(cx))
})
});
match (result, future_output) {
(_, Some(Poll::Ready(e))) => Poll::Ready(Ok(e)),
(_, Some(Poll::Pending)) => Poll::Pending,
(Err(e), _) => Poll::Ready(Err(e)),
(Ok(_), None) => wasm_bindgen::throw_str("invalid poll state"),
}
}
}