wasm-bindgen/tests/closures.rs
Alex Crichton c0cad447c1 Initial support for closures
This commit starts wasm-bindgen down the path of supporting closures. We
discussed this at the recent Rust All-Hands but I ended up needing to pretty
significantly scale back the ambitions of what closures are supported. This
commit is just the initial support and provides only a small amount of support
but will hopefully provide a good basis for future implementations.

Specifically this commit adds support for passing `&Fn(...)` to an *imported
function*, but nothing elese. The `&Fn` type can have any lifetime and the JS
object is invalidated as soon as the import returns. The arguments and return
value of `Fn` must currently implement the `WasmAbi` trait, aka they can't
require any conversions like strings/types/etc.

I'd like to soon expand this to `&mut FnMut` as well as `'static` closures that
can be passed around for a long time in JS, but for now I'm putting that off
until later. I'm not currently sure how to implement richer argument types, but
hopefully that can be figured out at some point!
2018-04-09 14:34:21 -07:00

91 lines
2.1 KiB
Rust

extern crate test_support;
#[test]
fn works() {
test_support::project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
extern crate wasm_bindgen;
use std::cell::Cell;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(module = "./test")]
extern {
fn call(a: &Fn());
fn thread(a: &Fn(u32) -> u32) -> u32;
}
#[wasm_bindgen]
pub fn run() {
let a = Cell::new(false);
call(&|| a.set(true));
assert!(a.get());
assert_eq!(thread(&|a| a + 1), 3);
}
"#)
.file("test.ts", r#"
import { run } from "./out";
export function call(a: any) {
a();
}
export function thread(a: any) {
return a(2);
}
export function test() {
run();
}
"#)
.test();
}
#[test]
fn cannot_reuse() {
test_support::project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
extern crate wasm_bindgen;
use std::cell::Cell;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(module = "./test")]
extern {
fn call(a: &Fn());
#[wasm_bindgen(catch)]
fn call_again() -> Result<(), JsValue>;
}
#[wasm_bindgen]
pub fn run() {
call(&|| {});
assert!(call_again().is_err());
}
"#)
.file("test.ts", r#"
import { run } from "./out";
let CACHE: any = null;
export function call(a: any) {
CACHE = a;
}
export function call_again() {
CACHE();
}
export function test() {
run();
}
"#)
.test();
}