merge master

This commit is contained in:
Jannik Keye
2018-07-06 09:31:58 +02:00
56 changed files with 4646 additions and 11610 deletions

View File

@ -6,6 +6,7 @@ module.exports = {
node: true
},
extends: 'eslint:recommended',
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
@ -24,8 +25,10 @@ module.exports = {
'always'
],
'no-console': 0,
'no-undef':
'warn',
'no-unused-vars': 'warn'
'no-undef': 'warn'
},
globals: {
BigInt64Array: true,
BigUint64Array: true
}
};

View File

@ -1,20 +1,38 @@
language: rust
sudo: false
matrix:
include:
# CLI builds on stable
- rust: stable
install: true
script: cargo build --manifest-path crates/cli/Cargo.toml
# Tests pass on nightly
- rust: nightly
before_install:
INSTALL_NODE_VIA_NVM: &INSTALL_NODE_VIA_NVM
- rustup target add wasm32-unknown-unknown
- curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
- curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
- source ~/.nvm/nvm.sh
- nvm install v10.5
DEPLOY_TO_GITHUB: &DEPLOY_TO_GITHUB
before_deploy:
|
name="wasm-bindgen-$TRAVIS_TAG-$TARGET"
mkdir "$name"
cp "target/$TARGET/release/{wasm-bindgen,wasm2es6js}" "$name/"
cp README.md LICENSE-MIT LICENSE-APACHE "$name/"
tar czvf "$name.tar.gz" "$name"
deploy:
api_key:
secure: "qCiELnEnvyKpWHDttgTNf+ElZGbWlvthu5aOIj5nYfov+h6g1+mkWnDFP6at/WPlE78zE/f/z/dL2KB2I7w/cxH/T4P1nWh0A9DvrpY6hqWkK2pgN5dPeWE/a4flI7AdH0A6wMRw7m00uMgDjlzN78v7XueccpJCxSO5allQN5jweAQvMX2QA07TbLRJc7Lq6lfVwSf8OfrcO8qCbcIzJTsC4vtbh6jkUYg1OAaU2tAYlskBy9ZYmHWCExIAu/zxzcJY9OpApPD9Ea4CyrsfjniAyRBJ87Weh/sP4XhiWeRPVmvA4HAzv4Pps9ps+Ar5QmsX53rhKQ3id7/VPR8ggaAHxrYUiJPvJRtbP6cKKOlDiK0ooP+vI4vjxWeNVj9ibEolSYOlT0ENIvPK1BppA6VgAoJOjwPr0Q16Ma4AmvLkIkowJiXCm2Jlje/5c0vPEAGJVgUtkj3jFQzgXwyEMpzxUlhHmYpmnfeaM0tK/Kiiwe1monL/ydMlyfV55kNylylCg+XoTnf420AFChKbD4DM5Z7ZsjU9g8fF3LUoN0sKpmLDp+GvwjLi9YtGogWB71Q2MFp43MSL0YLshkyYYoZKrVMiy5J9hKNUxhT2jNEq53Z69syIHHMCxHL9GoAcuHxIKOA7uTMW0aCoyy2I+dfAKKsrUGwGYaNC5LZdUQI="
file_glob: true
file:
- wasm-bindgen-$TRAVIS_TAG-$TARGET.tar.gz
on:
tags: true
provider: releases
skip_cleanup: true
matrix:
include:
# Tests pass on nightly
- rust: nightly
env: JOB=test-bindgen
before_install: *INSTALL_NODE_VIA_NVM
install:
# dirties git repository, there doesn't seem to be a way to resolve this other than
# to run `npm install` twice or by using `npm ci` (which is currently broken)
@ -22,82 +40,70 @@ matrix:
script:
- cargo test
# Check JS output from all tests against eslint
- ./node_modules/.bin/eslint ./target/generated-tests/*/out*.js
env: RUST_BACKTRACE=1
- ./node_modules/.bin/eslint ./target/generated-tests/*/out*js
addons:
firefox: latest
# All examples work
- rust: nightly
env: JOB=examples-build
install: *INSTALL_NODE_VIA_NVM
script:
- mkdir node_modules
- |
for dir in `ls examples | grep -v README | grep -v asm.js | grep -v no_modules`; do
(cd examples/$dir &&
sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json &&
ln -s ../../node_modules . &&
./build.sh) || exit 1;
done
# Tests pass on nightly using yarn
- rust: nightly
before_install:
- rustup target add wasm32-unknown-unknown
- curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
- source ~/.nvm/nvm.sh
- nvm install v10.5
env: JOB=test-yarn-smoke
before_install: *INSTALL_NODE_VIA_NVM
install:
- curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.7.0
- export PATH=$HOME/.yarn/bin:$PATH
install:
- yarn install --freeze-lockfile
script:
- cargo test
# Check JS output from all tests against eslint
- ./node_modules/.bin/eslint ./target/generated-tests/*/out*.js
env: RUST_BACKTRACE=1
script: cargo test api::works
# WebIDL tests pass on nightly
- rust: nightly
env: JOB=test-webidl
before_install: rustup component add rustfmt-preview --toolchain nightly
script: (cd crates/webidl && cargo test)
env: RUST_BACKTRACE=1 RUST_LOG=wasm_bindgen_webidl
script: cargo test --manifest-path crates/webidl/Cargo.toml
# Dist linux binary
- env: TARGET=x86_64-unknown-linux-musl DEPLOY=1
rust: nightly
- rust: nightly
env: JOB=dist-linux TARGET=x86_64-unknown-linux-musl
before_script: rustup target add $TARGET
script: cargo build --manifest-path crates/cli/Cargo.toml --release --target $TARGET
addons:
apt:
packages:
- musl-tools
<<: *DEPLOY_TO_GITHUB
# Dist OSX binary
- os: osx
rust: nightly
env: MACOSX_DEPLOYMENT_TARGET=10.7 DEPLOY=1 TARGET=x86_64-apple-darwin
- rust: nightly
os: osx
env: JOB=dist-osx MACOSX_DEPLOYMENT_TARGET=10.7 TARGET=x86_64-apple-darwin
script: cargo build --manifest-path crates/cli/Cargo.toml --release --target $TARGET
install: true
<<: *DEPLOY_TO_GITHUB
# We can build the tool on nightly
# CLI builds on stable
- rust: stable
env: JOB=check-stable-cli
script: cargo check --manifest-path crates/cli/Cargo.toml
# CLI builds on nightly
- rust: nightly
script: cargo install --debug --path crates/cli
# All examples work
- rust: nightly
before_install:
- rustup target add wasm32-unknown-unknown
- curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
- source ~/.nvm/nvm.sh
- nvm install v10.5
script:
- |
(cd examples/hello_world && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/smorgasboard && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/console_log && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/math && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/dom && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/wasm-in-wasm && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/char && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/closures && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/comments && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
env: JOB=check-nightly-cli
script: cargo check --manifest-path crates/cli/Cargo.toml
# Build the guide.
- rust: stable
env: JOB=guide-build-and-deploy
cache:
- cargo
before_script:
@ -119,25 +125,3 @@ matrix:
notifications:
email:
on_success: never
before_deploy:
|
if [[ "$DEPLOY" == "1" ]]; then
name="wasm-bindgen-$TRAVIS_TAG-$TARGET"
mkdir "$name"
cp "target/$TARGET/release/{wasm-bindgen,wasm2es6js}" "$name/"
cp README.md LICENSE-MIT LICENSE-APACHE "$name/"
tar czvf "$name.tar.gz" "$name"
fi
deploy:
api_key:
secure: "qCiELnEnvyKpWHDttgTNf+ElZGbWlvthu5aOIj5nYfov+h6g1+mkWnDFP6at/WPlE78zE/f/z/dL2KB2I7w/cxH/T4P1nWh0A9DvrpY6hqWkK2pgN5dPeWE/a4flI7AdH0A6wMRw7m00uMgDjlzN78v7XueccpJCxSO5allQN5jweAQvMX2QA07TbLRJc7Lq6lfVwSf8OfrcO8qCbcIzJTsC4vtbh6jkUYg1OAaU2tAYlskBy9ZYmHWCExIAu/zxzcJY9OpApPD9Ea4CyrsfjniAyRBJ87Weh/sP4XhiWeRPVmvA4HAzv4Pps9ps+Ar5QmsX53rhKQ3id7/VPR8ggaAHxrYUiJPvJRtbP6cKKOlDiK0ooP+vI4vjxWeNVj9ibEolSYOlT0ENIvPK1BppA6VgAoJOjwPr0Q16Ma4AmvLkIkowJiXCm2Jlje/5c0vPEAGJVgUtkj3jFQzgXwyEMpzxUlhHmYpmnfeaM0tK/Kiiwe1monL/ydMlyfV55kNylylCg+XoTnf420AFChKbD4DM5Z7ZsjU9g8fF3LUoN0sKpmLDp+GvwjLi9YtGogWB71Q2MFp43MSL0YLshkyYYoZKrVMiy5J9hKNUxhT2jNEq53Z69syIHHMCxHL9GoAcuHxIKOA7uTMW0aCoyy2I+dfAKKsrUGwGYaNC5LZdUQI="
file_glob: true
file:
- wasm-bindgen-$TRAVIS_TAG-$TARGET.tar.gz
on:
condition: $DEPLOY = 1
tags: true
provider: releases
skip_cleanup: true

View File

@ -33,7 +33,7 @@ serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }
[dev-dependencies]
wasm-bindgen-cli-support = { path = "crates/cli-support", version = '=0.2.11' }
wasm-bindgen-test-project-builder = { path = "crates/test-project-builder", version = '=0.2.11' }
[workspace]
members = [

View File

@ -84,6 +84,7 @@ pub struct ImportStatic {
pub struct ImportType {
pub vis: syn::Visibility,
pub name: Ident,
pub attrs: Vec<syn::Attribute>,
}
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
@ -469,6 +470,7 @@ impl Program {
ImportKind::Type(ImportType {
vis: f.vis,
name: f.ident,
attrs: f.attrs,
})
}

View File

@ -505,8 +505,10 @@ impl ToTokens for ast::ImportType {
fn to_tokens(&self, tokens: &mut TokenStream) {
let vis = &self.vis;
let name = &self.name;
let attrs = &self.attrs;
(quote! {
#[allow(bad_style)]
#(#attrs)*
#vis struct #name {
obj: ::wasm_bindgen::JsValue,
}

View File

@ -60,7 +60,7 @@ impl<'a> Context<'a> {
if let Some(ref c) = comments {
self.globals.push_str(c);
}
let global = if self.config.nodejs {
let global = if self.use_node_require() {
if contents.starts_with("class") {
format!("{1}\nmodule.exports.{0} = {0};\n", name, contents)
} else {
@ -410,12 +410,14 @@ impl<'a> Context<'a> {
.unwrap_or("wasm_bindgen"),
)
} else {
let import_wasm = if self.config.nodejs {
let import_wasm = if self.globals.len() == 0 {
String::new()
} else if self.use_node_require() {
self.footer
.push_str(&format!("wasm = require('./{}_bg');", module_name));
format!("var wasm;")
} else {
format!("import * as wasm from './{}_bg.wasm';", module_name)
format!("import * as wasm from './{}_bg';", module_name)
};
format!(
@ -956,7 +958,6 @@ impl<'a> Context<'a> {
return Ok(());
}
self.require_internal_export("__wbindgen_malloc")?;
self.expose_uint64_memory();
self.global(&format!(
"
function {}(arg) {{
@ -976,7 +977,9 @@ impl<'a> Context<'a> {
if !self.exposed_globals.insert("text_encoder") {
return;
}
if self.config.nodejs {
if self.config.nodejs_experimental_modules {
self.imports.push_str("import { TextEncoder } from 'util';\n");
} else if self.config.nodejs {
self.global(
"
const TextEncoder = require('util').TextEncoder;
@ -1002,7 +1005,9 @@ impl<'a> Context<'a> {
if !self.exposed_globals.insert("text_decoder") {
return;
}
if self.config.nodejs {
if self.config.nodejs_experimental_modules {
self.imports.push_str("import { TextDecoder } from 'util';\n");
} else if self.config.nodejs {
self.global(
"
const TextDecoder = require('util').TextDecoder;
@ -1059,7 +1064,7 @@ impl<'a> Context<'a> {
if !self.exposed_globals.insert("get_array_js_value_from_wasm") {
return;
}
self.expose_get_array_u32_from_wasm();
self.expose_uint32_memory();
self.expose_take_object();
self.global(
"
@ -1584,6 +1589,10 @@ impl<'a> Context<'a> {
*section.payload_mut() = contents.into_bytes();
self.module.sections_mut().push(Section::Custom(section));
}
fn use_node_require(&self) -> bool {
self.config.nodejs && !self.config.nodejs_experimental_modules
}
}
impl<'a, 'b> SubContext<'a, 'b> {
@ -1807,9 +1816,10 @@ impl<'a, 'b> SubContext<'a, 'b> {
let target = if let Some(g) = getter {
if import.structural {
format!(
"function(y) {{
return this.{};
"function() {{
return {}.{};
}}",
if is_static { &class } else { "this" },
g
)
} else {
@ -1826,8 +1836,9 @@ impl<'a, 'b> SubContext<'a, 'b> {
if import.structural {
format!(
"function(y) {{
this.{} = y;
{}.{} = y;
}}",
if is_static { &class } else { "this" },
s
)
} else {
@ -1943,7 +1954,7 @@ impl<'a, 'b> SubContext<'a, 'b> {
let name = import.js_namespace.as_ref().map(|s| &**s).unwrap_or(item);
if self.cx.imported_names.insert(name.to_string()) {
if self.cx.config.nodejs {
if self.cx.use_node_require() {
self.cx.imports.push_str(&format!(
"\
const {} = require('{}').{};\n\

View File

@ -24,6 +24,7 @@ pub mod wasm2es6js;
pub struct Bindgen {
path: Option<PathBuf>,
nodejs: bool,
nodejs_experimental_modules: bool,
browser: bool,
no_modules: bool,
no_modules_global: Option<String>,
@ -37,6 +38,7 @@ impl Bindgen {
Bindgen {
path: None,
nodejs: false,
nodejs_experimental_modules: false,
browser: false,
no_modules: false,
no_modules_global: None,
@ -56,6 +58,11 @@ impl Bindgen {
self
}
pub fn nodejs_experimental_modules(&mut self, node: bool) -> &mut Bindgen {
self.nodejs_experimental_modules = node;
self
}
pub fn browser(&mut self, browser: bool) -> &mut Bindgen {
self.browser = browser;
self
@ -162,7 +169,8 @@ impl Bindgen {
cx.finalize(stem)?
};
let js_path = out_dir.join(stem).with_extension("js");
let extension = if self.nodejs_experimental_modules { "mjs" } else { "js" };
let js_path = out_dir.join(stem).with_extension(extension);
File::create(&js_path)
.and_then(|mut f| f.write_all(reset_indentation(&js).as_bytes()))
.with_context(|_| format!("failed to write `{}`", js_path.display()))?;
@ -177,7 +185,7 @@ impl Bindgen {
let wasm_path = out_dir.join(format!("{}_bg", stem)).with_extension("wasm");
if self.nodejs {
let js_path = wasm_path.with_extension("js");
let js_path = wasm_path.with_extension(extension);
let shim = self.generate_node_wasm_import(&module, &wasm_path);
File::create(&js_path)
.and_then(|mut f| f.write_all(shim.as_bytes()))
@ -200,22 +208,62 @@ impl Bindgen {
}
let mut shim = String::new();
if self.nodejs_experimental_modules {
for (i, module) in imports.iter().enumerate() {
shim.push_str(&format!("import * as import{} from '{}';\n",
i, module));
}
// On windows skip the leading `/` which comes out when we parse a
// url to use `C:\...` instead of `\C:\...`
shim.push_str(&format!("
import * as path from 'path';
import * as fs from 'fs';
import * as url from 'url';
import * as process from 'process';
let file = path.dirname(url.parse(import.meta.url).pathname);
if (process.platform === 'win32') {{
file = file.substring(1);
}}
const bytes = fs.readFileSync(path.join(file, '{}'));
", path.file_name().unwrap().to_str().unwrap()));
} else {
shim.push_str(&format!("
const path = require('path').join(__dirname, '{}');
const bytes = require('fs').readFileSync(path);
", path.file_name().unwrap().to_str().unwrap()));
}
shim.push_str("let imports = {};\n");
for module in imports {
for (i, module) in imports.iter().enumerate() {
if self.nodejs_experimental_modules {
shim.push_str(&format!("imports['{}'] = import{};\n", module, i));
} else {
shim.push_str(&format!("imports['{0}'] = require('{0}');\n", module));
}
}
shim.push_str(&format!(
"
const join = require('path').join;
const bytes = require('fs').readFileSync(join(__dirname, '{}'));
const wasmModule = new WebAssembly.Module(bytes);
const wasmInstance = new WebAssembly.Instance(wasmModule, imports);
module.exports = wasmInstance.exports;
",
path.file_name().unwrap().to_str().unwrap()
));
if self.nodejs_experimental_modules {
if let Some(e) = m.export_section() {
for name in e.entries().iter().map(|e| e.field()) {
shim.push_str("export const ");
shim.push_str(name);
shim.push_str(" = wasmInstance.exports.");
shim.push_str(name);
shim.push_str(";\n");
}
}
} else {
shim.push_str("module.exports = wasmInstance.exports;\n");
}
reset_indentation(&shim)
}
}

View File

@ -0,0 +1,8 @@
[package]
name = "wasm-bindgen-test-project-builder"
version = "0.2.11"
authors = ["Nick Fitzgerald <fitzgen@gmail.com>"]
[dependencies]
lazy_static = "1"
wasm-bindgen-cli-support = { path = "../cli-support", version = '=0.2.11' }

View File

@ -0,0 +1,830 @@
#[macro_use]
extern crate lazy_static;
extern crate wasm_bindgen_cli_support as cli;
use std::env;
use std::fs::{self, File};
use std::thread;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio, Child, ChildStdin};
use std::net::TcpStream;
use std::sync::atomic::*;
use std::sync::{Once, ONCE_INIT, Mutex};
use std::time::{Duration, Instant};
static CNT: AtomicUsize = ATOMIC_USIZE_INIT;
thread_local!(static IDX: usize = CNT.fetch_add(1, Ordering::SeqCst));
pub struct Project {
files: Vec<(String, String)>,
debug: bool,
node: bool,
nodejs_experimental_modules: bool,
no_std: bool,
serde: bool,
rlib: bool,
webpack: bool,
node_args: Vec<String>,
deps: Vec<String>,
headless: bool,
}
pub fn project() -> Project {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let mut lockfile = String::new();
fs::File::open(&dir.join("Cargo.lock"))
.unwrap()
.read_to_string(&mut lockfile)
.unwrap();
Project {
debug: true,
no_std: false,
node: true,
nodejs_experimental_modules: true,
webpack: false,
serde: false,
rlib: false,
headless: false,
deps: Vec::new(),
node_args: Vec::new(),
files: vec![
("Cargo.lock".to_string(), lockfile),
],
}
}
fn root() -> PathBuf {
let idx = IDX.with(|x| *x);
let mut me = env::current_exe().unwrap();
me.pop(); // chop off exe name
me.pop(); // chop off `deps`
me.pop(); // chop off `debug` / `release`
me.push("generated-tests");
me.push(&format!("test{}", idx));
return me;
}
fn assert_bigint_support() -> Option<&'static str> {
static BIGINT_SUPPORED: AtomicUsize = ATOMIC_USIZE_INIT;
static INIT: Once = ONCE_INIT;
INIT.call_once(|| {
let mut cmd = Command::new("node");
cmd.arg("-e").arg("BigInt");
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
if cmd.status().unwrap().success() {
BIGINT_SUPPORED.store(1, Ordering::SeqCst);
return;
}
cmd.arg("--harmony-bigint");
if cmd.status().unwrap().success() {
BIGINT_SUPPORED.store(2, Ordering::SeqCst);
return;
}
});
match BIGINT_SUPPORED.load(Ordering::SeqCst) {
1 => return None,
2 => return Some("--harmony-bigint"),
_ => panic!(
"the version of node.js that is installed for these tests \
does not support `BigInt`, you may wish to try installing \
node 10 to fix this"
),
}
}
impl Project {
/// Add a new file with the specified contents to this project, the `name`
/// can have slahes for files in subdirectories.
pub fn file(&mut self, name: &str, contents: &str) -> &mut Project {
self.files.push((name.to_string(), contents.to_string()));
self
}
/// Enable debug mode in wasm-bindgen for this test
pub fn debug(&mut self, debug: bool) -> &mut Project {
self.debug = debug;
self
}
/// Depend on `wasm-bindgen` without the `std` feature enabled.
pub fn no_std(&mut self, no_std: bool) -> &mut Project {
self.no_std = no_std;
self
}
/// Depend on the `serde` feature of `wasm-bindgen`
pub fn serde(&mut self, serde: bool) -> &mut Project {
self.serde = serde;
self
}
/// Generate an rlib instead of a cdylib in the generated Cargo project
pub fn rlib(&mut self, rlib: bool) -> &mut Project {
self.rlib = rlib;
self
}
/// Depend on a crate from crates.io, like serde.
pub fn depend(&mut self, dep: &str) -> &mut Project {
self.deps.push(dep.to_string());
self
}
/// Enables or disables node.js experimental modules output
pub fn nodejs_experimental_modules(&mut self, node: bool) -> &mut Project {
self.nodejs_experimental_modules = node;
self
}
/// Enables or disables the usage of webpack for this project
pub fn webpack(&mut self, webpack: bool) -> &mut Project {
self.webpack = webpack;
self
}
/// Add a path dependency to the generated project
pub fn add_local_dependency(&mut self, name: &str, path: &str) -> &mut Project {
self.deps
.push(format!("{} = {{ path = '{}' }}", name, path));
self
}
/// Returns the crate name that will be used for the generated crate, this
/// name changes between test runs and is generated at runtime.
pub fn crate_name(&self) -> String {
format!("test{}", IDX.with(|x| *x))
}
/// Flag this project as requiring bigint support in Node
pub fn requires_bigint(&mut self) -> &mut Project {
if let Some(arg) = assert_bigint_support() {
self.node_args.push(arg.to_string());
}
self
}
/// This test requires a headless web browser
pub fn headless(&mut self, headless: bool) -> &mut Project {
self.headless = headless;
self
}
/// Write this project to the filesystem, ensuring all files are ready to
/// go.
pub fn build(&mut self) -> (PathBuf, PathBuf) {
if self.headless {
self.webpack = true;
}
if self.webpack {
self.node = false;
self.nodejs_experimental_modules = false;
}
self.ensure_webpack_config();
self.ensure_test_entry();
if self.headless {
self.ensure_index_html();
self.ensure_run_headless_js();
}
let webidl_modules = self.generate_webidl_bindings();
self.generate_js_entry(webidl_modules);
let mut manifest = format!(
r#"
[package]
name = "test{}"
version = "0.0.1"
authors = []
[workspace]
[lib]
"#,
IDX.with(|x| *x)
);
if !self.rlib {
manifest.push_str("crate-type = [\"cdylib\"]\n");
}
manifest.push_str("[build-dependencies]\n");
manifest.push_str("wasm-bindgen-webidl = { path = '");
manifest.push_str(env!("CARGO_MANIFEST_DIR"));
manifest.push_str("/../webidl' }\n");
manifest.push_str("[dependencies]\n");
for dep in self.deps.iter() {
manifest.push_str(dep);
manifest.push_str("\n");
}
manifest.push_str("wasm-bindgen = { path = '");
manifest.push_str(env!("CARGO_MANIFEST_DIR"));
manifest.push_str("/../..'");
if self.no_std {
manifest.push_str(", default-features = false");
}
if self.serde {
manifest.push_str(", features = ['serde-serialize']");
}
manifest.push_str(" }\n");
self.files.push(("Cargo.toml".to_string(), manifest));
let root = root();
drop(fs::remove_dir_all(&root));
for &(ref file, ref contents) in self.files.iter() {
let mut dst = root.join(file);
if self.nodejs_experimental_modules &&
dst.extension().and_then(|s| s.to_str()) == Some("js")
{
dst = dst.with_extension("mjs");
}
if dst.extension().and_then(|s| s.to_str()) == Some("ts") &&
!self.webpack
{
panic!("webpack needs to be enabled to use typescript");
}
fs::create_dir_all(dst.parent().unwrap()).unwrap();
fs::File::create(&dst)
.unwrap()
.write_all(contents.as_ref())
.unwrap();
}
let target_dir = root.parent().unwrap() // chop off test name
.parent().unwrap(); // chop off `generated-tests`
(root.clone(), target_dir.to_path_buf())
}
fn ensure_webpack_config(&mut self) {
if !self.webpack {
return
}
let needs_typescript = self.files.iter().any(|t| t.0.ends_with(".ts"));
let mut rules = String::new();
let mut extensions = format!("'.js', '.wasm'");
if needs_typescript {
rules.push_str("
{
test: /.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
}
");
extensions.push_str(", '.ts'");
}
let target = if self.headless { "web" } else { "node" };
self.files.push((
"webpack.config.js".to_string(),
format!(r#"
const path = require('path');
const fs = require('fs');
let nodeModules = {{}};
// Webpack bundles the modules from node_modules.
// For node target, we will not have `fs` module
// inside the `node_modules` folder.
// This reads the directories in `node_modules`
// and give that to externals and webpack ignores
// to bundle the modules listed as external.
if ('{2}' == 'node') {{
fs.readdirSync('node_modules')
.filter(module => module !== '.bin')
.forEach(mod => {{
// External however,expects browser environment.
// To make it work in `node` target we
// prefix commonjs here.
nodeModules[mod] = 'commonjs ' + mod;
}});
}}
module.exports = {{
entry: './run.js',
mode: "development",
devtool: "source-map",
module: {{
rules: [{}]
}},
resolve: {{
extensions: [{}]
}},
output: {{
filename: 'bundle.js',
path: path.resolve(__dirname, '.')
}},
target: '{}',
externals: nodeModules
}};
"#, rules, extensions, target)
));
if needs_typescript {
self.files.push((
"tsconfig.json".to_string(),
r#"
{
"compilerOptions": {
"noEmitOnError": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"noImplicitReturns": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"alwaysStrict": true,
"strict": true,
"target": "es5",
"lib": ["es2015"]
}
}
"#.to_string(),
));
}
}
fn ensure_test_entry(&mut self) {
if !self
.files
.iter()
.any(|(path, _)| path == "test.ts" || path == "test.js")
{
self.files.push((
"test.js".to_string(),
r#"export {test} from './out';"#.to_string(),
));
}
}
fn ensure_index_html(&mut self) {
self.file(
"index.html",
r#"
<!DOCTYPE html>
<html>
<body>
<div id="error"></div>
<div id="logs"></div>
<div id="status"></div>
<script src="bundle.js"></script>
</body>
</html>
"#,
);
}
fn ensure_run_headless_js(&mut self) {
self.file("run-headless.js", include_str!("run-headless.js"));
}
fn generate_webidl_bindings(&mut self) -> Vec<PathBuf> {
let mut res = Vec::new();
let mut origpaths = Vec::new();
for (path, _) in &self.files {
let path = Path::new(&path);
let extension = path.extension().map(|x| x.to_str().unwrap());
if extension != Some("webidl") {
continue;
}
res.push(path.with_extension("rs"));
origpaths.push(path.to_owned());
}
if res.is_empty() {
return res;
}
let mut buildrs = r#"
extern crate wasm_bindgen_webidl;
use wasm_bindgen_webidl::compile_file;
use std::env;
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
fn main() {
let dest = env::var("OUT_DIR").unwrap();
"#.to_string();
for (path, origpath) in res.iter().zip(origpaths.iter()) {
buildrs.push_str(&format!(
r#"
fs::create_dir_all("{}").unwrap();
File::create(&Path::new(&dest).join("{}"))
.unwrap()
.write_all(
compile_file(Path::new("{}"))
.unwrap()
.as_bytes()
)
.unwrap();
"#,
path.parent().unwrap().to_str().unwrap(),
path.to_str().unwrap(),
origpath.to_str().unwrap(),
));
self.files.push((
Path::new("src").join(path).to_str().unwrap().to_string(),
format!(
r#"include!(concat!(env!("OUT_DIR"), "/{}"));"#,
path.display()
),
));
}
buildrs.push('}');
self.files.push(("build.rs".to_string(), buildrs));
res
}
fn generate_js_entry(&mut self, modules: Vec<PathBuf>) {
let mut runjs = String::new();
let esm_imports = self.webpack || !self.node || self.nodejs_experimental_modules;
if self.headless {
runjs.push_str(
r#"
window.document.body.innerHTML += "\nTEST_START\n";
console.log = function(...args) {
const logs = document.getElementById('logs');
for (let msg of args) {
logs.innerHTML += `${msg}<br/>\n`;
}
};
"#,
);
} else if esm_imports {
runjs.push_str("import * as process from 'process';\n");
} else {
runjs.push_str("const process = require('process');\n");
}
runjs.push_str("
function run(test, wasm) {
test.test();
if (wasm.assertStackEmpty)
wasm.assertStackEmpty();
if (wasm.assertSlabEmpty)
wasm.assertSlabEmpty();
}
");
if self.headless {
runjs.push_str("
function onerror(error) {
const errors = document.getElementById('error');
let content = `exception: ${e.message}\\nstack: ${e.stack}`;
errors.innerHTML = `<pre>${content}</pre>`;
}
");
} else {
runjs.push_str("
function onerror(error) {
console.error(error);
process.exit(1);
}
");
}
if esm_imports {
runjs.push_str("console.log('importing modules...');\n");
runjs.push_str("const modules = [];\n");
for module in modules.iter() {
runjs.push_str(&format!("modules.push(import('./{}'))",
module.with_extension("").display()));
}
let import_wasm = if self.debug {
"import('./out')"
} else {
"new Promise((a, b) => a({}))"
};
runjs.push_str(&format!("
Promise.all(modules)
.then(results => {{
results.map(module => Object.assign(global, module));
return Promise.all([import('./test'), {}])
}})
.then(result => run(result[0], result[1]))
", import_wasm));
if self.headless {
runjs.push_str(".then(() => {
document.getElementById('status').innerHTML = 'good';
})");
}
runjs.push_str(".catch(onerror)\n");
if self.headless {
runjs.push_str("
.finally(() => {
window.document.body.innerHTML += \"\\nTEST_DONE\";
})
");
}
} else {
assert!(!self.debug);
assert!(modules.is_empty());
runjs.push_str("
const test = require('./test');
try {
run(test, {});
} catch (e) {
onerror(e);
}
");
}
self.files.push(("run.js".to_string(), runjs));
}
/// Build the Cargo project for the wasm target, returning the root of the
/// project and the target directory where output is located.
pub fn cargo_build(&mut self) -> (PathBuf, PathBuf) {
let (root, target_dir) = self.build();
let mut cmd = Command::new("cargo");
cmd.arg("build")
.arg("--target")
.arg("wasm32-unknown-unknown")
.current_dir(&root)
.env("CARGO_TARGET_DIR", &target_dir)
// Catch any warnings in generated code because we don't want any
.env("RUSTFLAGS", "-Dwarnings");
run(&mut cmd, "cargo");
(root, target_dir)
}
/// Generate wasm-bindgen bindings for the compiled artifacts of this
/// project, returning the root of the project as well as the target
/// directory where output was generated.
pub fn gen_bindings(&mut self) -> (PathBuf, PathBuf) {
let (root, target_dir) = self.cargo_build();
let idx = IDX.with(|x| *x);
let out = target_dir.join(&format!("wasm32-unknown-unknown/debug/test{}.wasm", idx));
let as_a_module = root.join("out.wasm");
fs::hard_link(&out, &as_a_module).unwrap();
let _x = wrap_step("running wasm-bindgen");
let res = cli::Bindgen::new()
.input_path(&as_a_module)
.typescript(self.webpack)
.debug(self.debug)
.nodejs(self.node)
.nodejs_experimental_modules(self.nodejs_experimental_modules)
.generate(&root);
if let Err(e) = res {
for e in e.causes() {
println!("- {}", e);
}
panic!("failed");
}
(root, target_dir)
}
/// Execute this project's `run.js`, ensuring that everything runs through
/// node or a browser correctly
pub fn test(&mut self) {
let (root, _target_dir) = self.gen_bindings();
if !self.webpack {
let mut cmd = Command::new("node");
cmd.args(&self.node_args);
if self.nodejs_experimental_modules {
cmd.arg("--experimental-modules").arg("run.mjs");
} else {
cmd.arg("run.js");
}
cmd.current_dir(&root);
run(&mut cmd, "node");
return
}
// Generate typescript bindings for the wasm module
{
let _x = wrap_step("running wasm2es6js");
let mut wasm = Vec::new();
File::open(root.join("out_bg.wasm"))
.unwrap()
.read_to_end(&mut wasm)
.unwrap();
let obj = cli::wasm2es6js::Config::new()
.base64(true)
.generate(&wasm)
.expect("failed to convert wasm to js");
File::create(root.join("out_bg.d.ts"))
.unwrap()
.write_all(obj.typescript().as_bytes())
.unwrap();
}
// move files from the root into each test, it looks like this may be
// needed for webpack to work well when invoked concurrently.
fs::hard_link("package.json", root.join("package.json")).unwrap();
if !Path::new("node_modules").exists() {
panic!("\n\nfailed to find `node_modules`, have you run `npm install` yet?\n\n");
}
let cwd = env::current_dir().unwrap();
symlink_dir(&cwd.join("node_modules"), &root.join("node_modules")).unwrap();
if self.headless {
return self.test_headless(&root)
}
// Execute webpack to generate a bundle
let mut cmd = self.npm();
cmd.arg("run").arg("run-webpack").current_dir(&root);
run(&mut cmd, "npm");
let mut cmd = Command::new("node");
cmd.args(&self.node_args);
cmd.arg(root.join("bundle.js")).current_dir(&root);
run(&mut cmd, "node");
}
fn npm(&self) -> Command {
if cfg!(windows) {
let mut c = Command::new("cmd");
c.arg("/c");
c.arg("npm");
c
} else {
Command::new("npm")
}
}
fn test_headless(&mut self, root: &Path) {
// Serialize all headless tests since they require starting
// webpack-dev-server on the same port.
lazy_static! {
static ref MUTEX: Mutex<()> = Mutex::new(());
}
let _lock = MUTEX.lock().unwrap();
let mut cmd = self.npm();
cmd.arg("run")
.arg("run-webpack-dev-server")
.arg("--")
.arg("--quiet")
.arg("--watch-stdin")
.current_dir(&root);
let _server = run_in_background(&mut cmd, "webpack-dev-server".into());
// wait for webpack-dev-server to come online and bind its port
loop {
if TcpStream::connect("127.0.0.1:8080").is_ok() {
break;
}
thread::sleep(Duration::from_millis(100));
}
let path = env::var_os("PATH").unwrap_or_default();
let mut path = env::split_paths(&path).collect::<Vec<_>>();
path.push(root.join("node_modules/geckodriver"));
let mut cmd = Command::new("node");
cmd.args(&self.node_args)
.arg(root.join("run-headless.js"))
.current_dir(&root)
.env("PATH", env::join_paths(&path).unwrap());
run(&mut cmd, "node");
}
/// Reads JS generated by `wasm-bindgen` to a string.
pub fn read_js(&self) -> String {
let path = root().join(if self.nodejs_experimental_modules {
"out.mjs"
} else {
"out.js"
});
println!("js, {:?}", &path);
fs::read_to_string(path).expect("Unable to read js")
}
}
#[cfg(unix)]
fn symlink_dir(a: &Path, b: &Path) -> io::Result<()> {
use std::os::unix::fs::symlink;
symlink(a, b)
}
#[cfg(windows)]
fn symlink_dir(a: &Path, b: &Path) -> io::Result<()> {
use std::os::windows::fs::symlink_dir;
symlink_dir(a, b)
}
fn wrap_step(desc: &str) -> WrapStep {
println!("···················································");
println!("{}", desc);
WrapStep { start: Instant::now() }
}
struct WrapStep { start: Instant }
impl Drop for WrapStep {
fn drop(&mut self) {
let dur = self.start.elapsed();
println!(
"dur: {}.{:03}s",
dur.as_secs(),
dur.subsec_nanos() / 1_000_000
);
}
}
pub fn run(cmd: &mut Command, program: &str) {
let _x = wrap_step(&format!("running {:?}", cmd));
let output = match cmd.output() {
Ok(output) => output,
Err(err) => panic!("failed to spawn `{}`: {}", program, err),
};
println!("exit: {}", output.status);
if output.stdout.len() > 0 {
println!("stdout ---\n{}", String::from_utf8_lossy(&output.stdout));
}
if output.stderr.len() > 0 {
println!("stderr ---\n{}", String::from_utf8_lossy(&output.stderr));
}
assert!(output.status.success());
}
struct BackgroundChild {
name: String,
child: Child,
stdin: Option<ChildStdin>,
stdout: Option<thread::JoinHandle<io::Result<String>>>,
stderr: Option<thread::JoinHandle<io::Result<String>>>,
}
impl Drop for BackgroundChild {
fn drop(&mut self) {
drop(self.stdin.take());
let status = self.child.wait().expect("failed to wait on child");
let stdout = self
.stdout
.take()
.unwrap()
.join()
.unwrap()
.expect("failed to read stdout");
let stderr = self
.stderr
.take()
.unwrap()
.join()
.unwrap()
.expect("failed to read stderr");
println!("···················································");
println!("background {}", self.name);
println!("status: {}", status);
println!("stdout ---\n{}", stdout);
println!("stderr ---\n{}", stderr);
}
}
fn run_in_background(cmd: &mut Command, name: String) -> BackgroundChild {
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
cmd.stdin(Stdio::piped());
let mut child = cmd.spawn().expect(&format!("should spawn {} OK", name));
let mut stdout = child.stdout.take().unwrap();
let mut stderr = child.stderr.take().unwrap();
let stdin = child.stdin.take().unwrap();
let stdout = thread::spawn(move || {
let mut t = String::new();
stdout.read_to_string(&mut t)?;
Ok(t)
});
let stderr = thread::spawn(move || {
let mut t = String::new();
stderr.read_to_string(&mut t)?;
Ok(t)
});
BackgroundChild {
name,
child,
stdout: Some(stdout),
stderr: Some(stderr),
stdin: Some(stdin),
}
}

View File

@ -0,0 +1,128 @@
const process = require("process");
const { promisify } = require("util");
const { Builder, By, Key, logging, promise, until } = require("selenium-webdriver");
const firefox = require("selenium-webdriver/firefox");
promise.USE_PROMISE_MANAGER = false;
const prefs = new logging.Preferences();
prefs.setLevel(logging.Type.BROWSER, logging.Level.DEBUG);
const opts = new firefox.Options();
opts.headless();
if (process.env.WASM_BINDGEN_FIREFOX_BIN_PATH) {
console.log("Using custom firefox-bin: $WASM_BINDGEN_FIREFOX_BIN_PATH =",
process.env.WASM_BINDGEN_FIREFOX_BIN_PATH);
opts.setBinary(process.env.WASM_BINDGEN_FIREFOX_BIN_PATH);
}
console.log("Using Firefox options:", opts);
const driver = new Builder()
.forBrowser("firefox")
.setFirefoxOptions(opts)
.build();
const SECONDS = 1000;
const MINUTES = 60 * SECONDS;
const start = Date.now();
const timeSinceStart = () => {
const elapsed = Date.now() - start;
const minutes = Math.floor(elapsed / MINUTES);
const seconds = elapsed % MINUTES / SECONDS;
return `${minutes}m${seconds.toFixed(3)}s`;
};
async function logged(msg, promise) {
console.log(`${timeSinceStart()}: START: ${msg}`);
try {
const value = await promise;
console.log(`${timeSinceStart()}: END: ${msg}`);
return value;
} catch (e) {
console.log(`${timeSinceStart()}: ERROR: ${msg}: ${e}\n\n${e.stack}`);
throw e;
}
}
async function main() {
let body;
try {
await logged(
"load http://localhost:8080/index.html",
driver.get("http://localhost:8080/index.html")
);
body = driver.findElement(By.tagName("body"));
await logged(
"Waiting for <body> to include text 'TEST_START'",
driver.wait(
until.elementTextContains(body, "TEST_START"),
1 * MINUTES
)
);
await logged(
"Waiting for <body> to include text 'TEST_DONE'",
driver.wait(
until.elementTextContains(body, "TEST_DONE"),
1 * MINUTES
)
);
const status = await logged(
"get #status text",
body.findElement(By.id("status")).getText()
);
console.log(`Test status is: "${status}"`);
if (status != "good") {
throw new Error(`test failed with status = ${status}`);
}
} finally {
const logs = await logged(
"getting browser logs",
body.findElement(By.id("logs")).getText()
);
if (logs.length > 0) {
console.log("logs:");
logs.split("\n").forEach(line => {
console.log(` ${line}`);
});
}
const errors = await logged(
"getting browser errors",
body.findElement(By.id("error")).getText()
);
if (errors.length > 0) {
console.log("errors:");
errors.split("\n").forEach(line => {
console.log(` ${line}`);
});
}
const bodyText = await logged(
"getting browser body",
body.getText()
);
if (bodyText.length > 0) {
console.log("body:");
bodyText.split("\n").forEach(line => {
console.log(` ${line}`);
});
}
}
}
main()
.finally(() => driver.quit())
.catch(e => {
console.error(`Got an error: ${e}\n\nStack: ${e.stack}`);
process.exit(1);
});

View File

@ -171,6 +171,7 @@ impl WebidlParse<()> for webidl::ast::NonPartialInterface {
pub_token: Default::default(),
}),
name: rust_ident(&self.name),
attrs: Vec::new(),
}),
});

View File

@ -42,3 +42,16 @@ Finally, you can run the tests with `cargo`:
```shell
cargo test
```
### Headless Browser Tests
Some tests are configured to run in a headless Firefox instance. To run these
tests, you must have Firefox installed. If you have Firefox installed in a
non-default, custom location you can set the `WASM_BINDGEN_FIREFOX_BIN_PATH`
environment variable to the path to your `firefox-bin`.
For example:
```shell
WASM_BINDGEN_FIREFOX_BIN_PATH=/home/fitzgen/firefox/firefox-bin cargo test
```

View File

@ -40,7 +40,7 @@ Rust arguments of JS functions imported to Rust.
### From JS to Rust
Unfortunately the opposite direction from above, going from JS to Rust, is a bit
mroe complicated. Here we've got three traits:
more complicated. Here we've got three traits:
```rust
pub trait FromWasmAbi: WasmDescribe {

8091
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,20 @@
{
"license": "MIT",
"scripts": {
"run-webpack": "webpack"
"run-webpack": "webpack",
"run-webpack-dev-server": "webpack-dev-server",
"run-geckodriver": "geckodriver"
},
"devDependencies": {
"@types/node": "^9.4.6",
"eslint": "^5.0.1",
"geckodriver": "^1.11.0",
"selenium-webdriver": "^4.0.0-alpha.1",
"ts-loader": "^4.0.1",
"typescript": "^2.7.2",
"webpack": "^4.11.1",
"webpack-cli": "^2.0.10",
"eslint": "^4.19.1"
"webpack-dev-server": "^3.1.4",
"babel-eslint": "^8.2.5"
}
}

179
src/js.rs
View File

@ -141,6 +141,13 @@ extern "C" {
#[wasm_bindgen(method)]
pub fn filter(this: &Array, predicate: &mut FnMut(JsValue, u32, Array) -> bool) -> Array;
/// The `find()` method returns the value of the first element in the array that satisfies
/// the provided testing function. Otherwise `undefined` is returned.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
#[wasm_bindgen(method)]
pub fn find(this: &Array, predicate: &mut FnMut(JsValue, u32, Array) -> bool) -> JsValue;
/// The includes() method determines whether an array includes a certain
/// element, returning true or false as appropriate.
///
@ -254,6 +261,45 @@ extern "C" {
pub fn unshift(this: &Array, value: JsValue) -> u32;
}
// ArrayBuffer
#[wasm_bindgen]
extern "C" {
pub type ArrayBuffer;
/// The `ArrayBuffer` object is used to represent a generic,
/// fixed-length raw binary data buffer. You cannot directly
/// manipulate the contents of an `ArrayBuffer`; instead, you
/// create one of the typed array objects or a `DataView` object
/// which represents the buffer in a specific format, and use that
/// to read and write the contents of the buffer.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
#[wasm_bindgen(constructor)]
pub fn new(length: u32) -> ArrayBuffer;
/// The `slice()` method returns a new `ArrayBuffer` whose contents
/// are a copy of this `ArrayBuffer`'s bytes from begin, inclusive,
/// up to end, exclusive.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView
#[wasm_bindgen(static_method_of = ArrayBuffer, js_name = isView)]
pub fn is_view(value: JsValue) -> bool;
/// The `slice()` method returns a new `ArrayBuffer` whose contents
/// are a copy of this `ArrayBuffer`'s bytes from begin, inclusive,
/// up to end, exclusive.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice
#[wasm_bindgen(method)]
pub fn slice(this: &ArrayBuffer, begin: u32) -> ArrayBuffer;
/// Like `slice()` but with the `end` argument.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice
#[wasm_bindgen(method, js_name = slice)]
pub fn slice_with_end(this: &ArrayBuffer, begin: u32, end: u32) -> ArrayBuffer;
}
// Array Iterator
#[wasm_bindgen]
extern "C" {
@ -445,7 +491,7 @@ extern {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
#[wasm_bindgen(method, getter, structural)]
pub fn size(this: &Map) -> Number;
pub fn size(this: &Map) -> u32;
}
// Map Iterator
@ -480,12 +526,13 @@ extern {
#[wasm_bindgen]
extern "C" {
pub type Math;
/// The Math.abs() function returns the absolute value of a number, that is
/// Math.abs(x) = |x|
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs
#[wasm_bindgen(static_method_of = Math)]
pub fn abs(x: f64) -> Number;
pub fn abs(x: f64) -> f64;
/// The Math.acos() function returns the arccosine (in radians) of a
/// number, that is ∀x∊[-1;1]
@ -493,7 +540,7 @@ extern "C" {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos
#[wasm_bindgen(static_method_of = Math)]
pub fn acos(x: f64) -> Number;
pub fn acos(x: f64) -> f64;
/// The Math.acosh() function returns the hyperbolic arc-cosine of a
/// number, that is ∀x ≥ 1
@ -501,7 +548,7 @@ extern "C" {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acosh
#[wasm_bindgen(static_method_of = Math)]
pub fn acosh(x: f64) -> Number;
pub fn acosh(x: f64) -> f64;
/// The Math.asin() function returns the arcsine (in radians) of a
/// number, that is ∀x ∊ [-1;1]
@ -509,27 +556,27 @@ extern "C" {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin
#[wasm_bindgen(static_method_of = Math)]
pub fn asin(x: f64) -> Number;
pub fn asin(x: f64) -> f64;
/// The Math.asinh() function returns the hyperbolic arcsine of a
/// number, that is Math.asinh(x) = arsinh(x) = the unique y such that sinh(y) = x
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asinh
#[wasm_bindgen(static_method_of = Math)]
pub fn asinh(x: f64) -> Number;
pub fn asinh(x: f64) -> f64;
/// The Math.atan() function returns the arctangent (in radians) of a
/// number, that is Math.atan(x) = arctan(x) = the unique y ∊ [-π2;π2]such that
/// tan(y) = x
#[wasm_bindgen(static_method_of = Math)]
pub fn atan(x: f64) -> Number;
pub fn atan(x: f64) -> f64;
/// The Math.atan2() function returns the arctangent of the quotient of
/// its arguments.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2
#[wasm_bindgen(static_method_of = Math)]
pub fn atan2(y: f64, x: f64) -> Number;
pub fn atan2(y: f64, x: f64) -> f64;
/// The Math.atanh() function returns the hyperbolic arctangent of a number,
/// that is ∀x ∊ (-1,1), Math.atanh(x) = arctanh(x) = the unique y such that
@ -537,35 +584,35 @@ extern "C" {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atanh
#[wasm_bindgen(static_method_of = Math)]
pub fn atanh(x: f64) -> Number;
pub fn atanh(x: f64) -> f64;
/// The Math.cbrt() function returns the cube root of a number, that is
/// Math.cbrt(x) = x^3 = the unique y such that y^3 = x
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cbrt
#[wasm_bindgen(static_method_of = Math)]
pub fn cbrt(x: f64) -> Number;
pub fn cbrt(x: f64) -> f64;
/// The Math.ceil() function returns the smallest integer greater than
/// or equal to a given number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil
#[wasm_bindgen(static_method_of = Math)]
pub fn ceil(x: f64) -> Number;
pub fn ceil(x: f64) -> i32;
/// The Math.clz32() function returns the number of leading zero bits in
/// the 32-bit binary representation of a number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
#[wasm_bindgen(static_method_of = Math)]
pub fn clz32(x: i32) -> Number;
pub fn clz32(x: i32) -> u32;
/// The Math.cos() static function returns the cosine of the specified angle,
/// which must be specified in radians. This value is length(adjacent)/length(hypotenuse).
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos
#[wasm_bindgen(static_method_of = Math)]
pub fn cos(x: f64) -> Number;
pub fn cos(x: f64) -> f64;
/// The Math.cosh() function returns the hyperbolic cosine of a number,
@ -573,125 +620,125 @@ extern "C" {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cosh
#[wasm_bindgen(static_method_of = Math)]
pub fn cosh(x: f64) -> Number;
pub fn cosh(x: f64) -> f64;
/// The Math.exp() function returns e^x, where x is the argument, and e is Euler's number
/// (also known as Napier's constant), the base of the natural logarithms.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp
#[wasm_bindgen(static_method_of = Math)]
pub fn exp(x: f64) -> Number;
pub fn exp(x: f64) -> f64;
/// The Math.expm1() function returns e^x - 1, where x is the argument, and e the base of the
/// natural logarithms.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1
#[wasm_bindgen(static_method_of = Math)]
pub fn expm1(x: f64) -> Number;
pub fn expm1(x: f64) -> f64;
/// The Math.floor() function returns the largest integer less than or
/// equal to a given number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
#[wasm_bindgen(static_method_of = Math)]
pub fn floor(x: f64) -> Number;
pub fn floor(x: f64) -> i32;
/// The Math.fround() function returns the nearest 32-bit single precision float representation
/// of a Number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
#[wasm_bindgen(static_method_of = Math)]
pub fn fround(x: f64) -> Number;
pub fn fround(x: f64) -> f32;
/// The Math.imul() function returns the result of the C-like 32-bit multiplication of the
/// two parameters.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
#[wasm_bindgen(static_method_of = Math)]
pub fn imul(x: i32, y: i32) -> Number;
pub fn imul(x: i32, y: i32) -> i32;
/// The Math.log() function returns the natural logarithm (base e) of a number.
/// The JavaScript Math.log() function is equivalent to ln(x) in mathematics.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log
#[wasm_bindgen(static_method_of = Math)]
pub fn log(x: f64) -> Number;
pub fn log(x: f64) -> f64;
/// The Math.log10() function returns the base 10 logarithm of a number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10
#[wasm_bindgen(static_method_of = Math)]
pub fn log10(x: f64) -> Number;
pub fn log10(x: f64) -> f64;
/// The Math.log1p() function returns the natural logarithm (base e) of 1 + a number.
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log1p
#[wasm_bindgen(static_method_of = Math)]
pub fn log1p(x: f64) -> Number;
pub fn log1p(x: f64) -> f64;
/// The Math.log2() function returns the base 2 logarithm of a number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2
#[wasm_bindgen(static_method_of = Math)]
pub fn log2(x: f64) -> Number;
pub fn log2(x: f64) -> f64;
/// The Math.pow() function returns the base to the exponent power, that is, base^exponent.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow
#[wasm_bindgen(static_method_of = Math)]
pub fn pow(base: f64, exponent: f64) -> Number;
pub fn pow(base: f64, exponent: f64) -> f64;
/// The Math.round() function returns the value of a number rounded to the nearest integer.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
#[wasm_bindgen(static_method_of = Math)]
pub fn round(x: f64) -> Number;
pub fn round(x: f64) -> i32;
/// The Math.sign() function returns the sign of a number, indicating whether the number is
/// positive, negative or zero.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
#[wasm_bindgen(static_method_of = Math)]
pub fn sign(x: f64) -> Number;
pub fn sign(x: f64) -> f64;
/// The Math.sin() function returns the sine of a number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin
#[wasm_bindgen(static_method_of = Math)]
pub fn sin(x: f64) -> Number;
pub fn sin(x: f64) -> f64;
/// The Math.sinh() function returns the hyperbolic sine of a number, that can be expressed
/// using the constant e: Math.sinh(x) = (e^x - e^-x)/2
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sinh
#[wasm_bindgen(static_method_of = Math)]
pub fn sinh(x: f64) -> Number;
pub fn sinh(x: f64) -> f64;
/// The Math.sqrt() function returns the square root of a number, that is
/// ∀x ≥ 0, Math.sqrt(x) = √x = the unique y ≥ 0 such that y^2 = x
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt
#[wasm_bindgen(static_method_of = Math)]
pub fn sqrt(x: f64) -> Number;
pub fn sqrt(x: f64) -> f64;
/// The Math.tan() function returns the tangent of a number.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan
#[wasm_bindgen(static_method_of = Math)]
pub fn tan(x: f64) -> Number;
pub fn tan(x: f64) -> f64;
/// The Math.tanh() function returns the hyperbolic tangent of a number, that is
/// tanh x = sinh x / cosh x = (e^x - e^-x)/(e^x + e^-x) = (e^2x - 1)/(e^2x + 1)
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tanh
#[wasm_bindgen(static_method_of = Math)]
pub fn tanh(x: f64) -> Number;
pub fn tanh(x: f64) -> f64;
/// The Math.trunc() function returns the integer part of a number by removing any fractional
/// digits.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
#[wasm_bindgen(static_method_of = Math)]
pub fn trunc(x: f64) -> Number;
pub fn trunc(x: f64) -> i32;
}
// Number.
@ -699,6 +746,12 @@ extern "C" {
extern "C" {
pub type Number;
/// The Number.isInteger() method determines whether the passed value is an integer.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
#[wasm_bindgen(static_method_of = Number, js_name = isInteger)]
pub fn is_integer(object: &Object) -> bool;
/// The `Number` JavaScript object is a wrapper object allowing
/// you to work with numerical values. A `Number` object is
/// created using the `Number()` constructor.
@ -747,7 +800,7 @@ extern "C" {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/valueOf
#[wasm_bindgen(method, js_name = valueOf)]
pub fn value_of(this: &Number) -> Number;
pub fn value_of(this: &Number) -> f64;
}
// Date.
@ -755,6 +808,26 @@ extern "C" {
extern "C" {
pub type Date;
/// The getDate() method returns the day of the month for the
/// specified date according to local time.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate
#[wasm_bindgen(method, js_name = getDate)]
pub fn get_date(this: &Date) -> u32;
/// The getDay() method returns the day of the week for the specified date according to local time,
/// where 0 represents Sunday. For the day of the month see getDate().
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
#[wasm_bindgen(method, js_name = getDay)]
pub fn get_day(this: &Date) -> u32;
/// The getFullYear() method returns the year of the specified date according to local time.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear
#[wasm_bindgen(method, js_name = getFullYear)]
pub fn get_full_year(this: &Date) -> u32;
/// Creates a JavaScript Date instance that represents
/// a single moment in time. Date objects are based on a time value that is
/// the number of milliseconds since 1 January 1970 UTC.
@ -978,6 +1051,26 @@ extern "C" {
pub fn values(object: &Object) -> Array;
}
// Proxy
#[wasm_bindgen]
extern {
pub type Proxy;
/// The Proxy object is used to define custom behavior for fundamental
/// operations (e.g. property lookup, assignment, enumeration, function
/// invocation, etc).
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
#[wasm_bindgen(constructor)]
pub fn new(target: &JsValue, handler: &Object) -> Proxy;
/// The Proxy.revocable() method is used to create a revocable Proxy object.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/revocable
#[wasm_bindgen(static_method_of = Proxy)]
pub fn revocable(target: &JsValue, handler: &Object) -> Object;
}
// Reflect
#[wasm_bindgen]
extern "C" {
@ -1128,7 +1221,7 @@ extern {
///
/// https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Set/size
#[wasm_bindgen(method, getter, structural)]
pub fn size(this: &Set) -> Number;
pub fn size(this: &Set) -> u32;
}
// SetIterator
@ -1259,9 +1352,11 @@ extern "C" {
/// code points not representable in a single UTF-16 code unit, e.g. Unicode code points > 0x10000).
/// If you want the entire code point value, use codePointAt().
///
/// Returns `NaN` if index is out of range.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt
#[wasm_bindgen(method, js_class = "String", js_name = charCodeAt)]
pub fn char_code_at(this: &JsString, index: u32) -> Number;
pub fn char_code_at(this: &JsString, index: u32) -> f64;
/// The codePointAt() method returns a non-negative integer that is the Unicode code point value.
///
@ -1408,3 +1503,17 @@ if_std! {
}
}
}
// Symbol
#[wasm_bindgen]
extern "C" {
pub type Symbol;
/// The Symbol.hasInstance well-known symbol is used to determine
/// if a constructor object recognizes an object as its instance.
/// The instanceof operator's behavior can be customized by this symbol.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
#[wasm_bindgen(static_method_of = Symbol, getter, structural, js_name = hasInstance)]
pub fn has_instance() -> Symbol;
}

View File

@ -113,7 +113,7 @@ fn works() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -135,10 +135,10 @@ fn works() {
assert.strictEqual(typeof(wasm.mk_symbol()), 'symbol');
assert.strictEqual(typeof(wasm.mk_symbol2('a')), 'symbol');
assert.strictEqual((Symbol as any).keyFor(wasm.mk_symbol()), undefined);
assert.strictEqual((Symbol as any).keyFor(wasm.mk_symbol2('b')), undefined);
assert.strictEqual(Symbol.keyFor(wasm.mk_symbol()), undefined);
assert.strictEqual(Symbol.keyFor(wasm.mk_symbol2('b')), undefined);
wasm.assert_symbols((Symbol as any)(), 'a');
wasm.assert_symbols(Symbol(), 'a');
wasm.acquire_string('foo', null)
assert.strictEqual(wasm.acquire_string2(''), '');
assert.strictEqual(wasm.acquire_string2('a'), 'a');
@ -172,7 +172,7 @@ fn eq_works() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -40,7 +40,7 @@ fn simple() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import { Foo } from "./out";
@ -115,7 +115,7 @@ fn strings() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import { Foo } from "./out";
@ -198,12 +198,6 @@ fn exceptions() {
};
"#,
)
.file(
"test.d.ts",
r#"
export function test(): void;
"#,
)
.test();
}
@ -247,7 +241,7 @@ fn pass_one_to_another() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { A, B } from "./out";
@ -297,12 +291,12 @@ fn pass_into_js() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run, Foo } from "./out";
import * as assert from "assert";
export function take_foo(foo: Foo) {
export function take_foo(foo) {
assert.strictEqual(foo.inner(), 13);
foo.free();
assert.throws(() => foo.free(), /null pointer passed to rust/);
@ -353,7 +347,7 @@ fn issue_27() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { context } from "./out";
@ -399,13 +393,13 @@ fn pass_into_js_as_js_class() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run, Foo } from "./out";
import * as assert from "assert";
export function take_foo(foo: any) {
assert(foo instanceof Foo);
export function take_foo(foo) {
assert.ok(foo instanceof Foo);
assert.strictEqual(foo.inner(), 13);
foo.free();
}
@ -472,7 +466,7 @@ fn constructors() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import { Foo, Bar, cross_item_construction } from "./out";
@ -525,7 +519,7 @@ fn empty_structs() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { Other } from "./out";
@ -568,7 +562,7 @@ fn public_fields() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { Foo } from "./out";
import * as assert from "assert";
@ -622,7 +616,7 @@ fn using_self() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { Foo } from "./out";
@ -663,7 +657,7 @@ fn readonly_fields() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { Foo } from "./out";
import * as assert from "assert";
@ -671,7 +665,7 @@ fn readonly_fields() {
export function test() {
const a = Foo.new();
assert.strictEqual(a.a, 0);
assert.throws(() => (a as any).a = 3, /has only a getter/);
assert.throws(() => a.a = 3, /has only a getter/);
a.free();
}
"#,
@ -704,7 +698,7 @@ fn double_consume() {
}
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import { Foo } from "./out";

View File

@ -30,15 +30,15 @@ fn works() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
export function call(a: any) {
export function call(a) {
a();
}
export function thread(a: any) {
export function thread(a) {
return a(2);
}
@ -77,13 +77,13 @@ fn cannot_reuse() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
let CACHE: any = null;
let CACHE = null;
export function call(a: any) {
export function call(a) {
CACHE = a;
}
@ -142,15 +142,15 @@ fn long_lived() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
export function call1(a: any) {
export function call1(a) {
a();
}
export function call2(a: any) {
export function call2(a) {
return a(2);
}
@ -242,18 +242,18 @@ fn many_arity() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
export function call1(a: any) { a() }
export function call2(a: any) { a(1) }
export function call3(a: any) { a(1, 2) }
export function call4(a: any) { a(1, 2, 3) }
export function call5(a: any) { a(1, 2, 3, 4) }
export function call6(a: any) { a(1, 2, 3, 4, 5) }
export function call7(a: any) { a(1, 2, 3, 4, 5, 6) }
export function call8(a: any) { a(1, 2, 3, 4, 5, 6, 7) }
export function call1(a) { a() }
export function call2(a) { a(1) }
export function call3(a) { a(1, 2) }
export function call4(a) { a(1, 2, 3) }
export function call5(a) { a(1, 2, 3, 4) }
export function call6(a) { a(1, 2, 3, 4, 5) }
export function call7(a) { a(1, 2, 3, 4, 5, 6) }
export function call8(a) { a(1, 2, 3, 4, 5, 6, 7) }
export function test() {
run();
@ -299,13 +299,13 @@ fn long_lived_dropping() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
let CACHE: any = null;
let CACHE = null;
export function cache(a: any) { CACHE = a; }
export function cache(a) { CACHE = a; }
export function call() { CACHE() }
export function test() {
@ -346,13 +346,13 @@ fn long_fnmut_recursive() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
let CACHE: any = null;
let CACHE = null;
export function cache(a: any) { CACHE = a; }
export function cache(a) { CACHE = a; }
export function call() { CACHE() }
export function test() {
@ -397,15 +397,15 @@ fn fnmut() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
export function call(a: any) {
export function call(a) {
a();
}
export function thread(a: any) {
export function thread(a) {
return a(2);
}
@ -455,18 +455,18 @@ fn fnmut_bad() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
let F: any = null;
let F = null;
export function call(a: any) {
export function call(a) {
F = a;
a();
}
export function again(x: boolean) {
export function again(x) {
if (x) F();
}
@ -507,11 +507,11 @@ fn string_arguments() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
export function call(a: any) {
export function call(a) {
a("foo")
}
@ -554,12 +554,12 @@ fn string_ret() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
import * as assert from "assert";
export function call(a: any) {
export function call(a) {
const s = a("foo");
assert.strictEqual(s, "foobar");
}

View File

@ -38,12 +38,12 @@ fn works() {
"#,
);
let (root, target) = p.cargo_build();
p.gen_bindings(&root, &target);
p.gen_bindings();
let js = p.read_js();
let comments = extract_doc_comments(&js);
assert!(comments.iter().all(|c| c == "This comment should exist"));
}
/// Pull out all lines in a js string that start with
/// '* ', all other lines will either be comment start, comment
/// end or actual js lines.

View File

@ -66,7 +66,7 @@ fn dependencies_work() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -84,7 +84,7 @@ fn dependencies_work() {
const z = wasm.takes_own_dep_ty(foo);
assert.strictEqual(z, y);
assert.strictEqual((foo as any).ptr, 0);
assert.strictEqual(foo.ptr, 0);
}
"#,
)

View File

@ -30,7 +30,7 @@ fn c_style_enum() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -84,7 +84,7 @@ fn c_style_enum_with_custom_values() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -32,7 +32,7 @@ fn simple() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
@ -71,7 +71,7 @@ fn import_class() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { baz } from "./out";
import { called } from "./another";
@ -84,7 +84,7 @@ fn import_class() {
"#,
)
.file(
"another.ts",
"another.js",
r#"
export let called = false;
@ -112,6 +112,7 @@ fn construct() {
#[wasm_bindgen(module = "./another")]
extern {
#[derive(Clone)]
type Foo;
#[wasm_bindgen(js_namespace = Foo)]
fn create() -> Foo;
@ -127,13 +128,14 @@ fn construct() {
pub fn run() {
let f = Foo::create();
assert_eq!(f.get_internal_string(), "this");
assert_eq!(f.clone().get_internal_string(), "this");
f.append_to_internal_string(" foo");
f.assert_internal_string("this foo");
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
import { called } from "./another";
@ -146,15 +148,13 @@ fn construct() {
"#,
)
.file(
"another.ts",
"another.js",
r#"
import * as assert from "assert";
export let called = false;
export class Foo {
private internal_string: string = '';
static create() {
const ret = new Foo();
ret.internal_string = 'this';
@ -165,15 +165,17 @@ fn construct() {
return this.internal_string;
}
append_to_internal_string(s: string) {
append_to_internal_string(s) {
this.internal_string += s;
}
assert_internal_string(s: string) {
assert_internal_string(s) {
assert.strictEqual(this.internal_string, s);
called = true;
}
}
Foo.internal_string = '';
"#,
)
.test();
@ -208,7 +210,7 @@ fn new_constructors() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
@ -218,10 +220,11 @@ fn new_constructors() {
"#,
)
.file(
"another.ts",
"another.js",
r#"
export class Foo {
constructor(private field: number) {
constructor(field) {
this.field = field;
}
get() {
@ -271,7 +274,7 @@ fn switch_methods() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { a, b } from "./out";
import { Foo, called } from "./another";
@ -300,7 +303,7 @@ fn switch_methods() {
"#,
)
.file(
"another.ts",
"another.js",
r#"
export let called = { a: false };
@ -357,7 +360,7 @@ fn properties() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
@ -367,10 +370,10 @@ fn properties() {
"#,
)
.file(
"another.ts",
"another.js",
r#"
export class Foo {
constructor(private num: number) {
constructor() {
this.num = 1;
}
@ -423,7 +426,7 @@ fn rename_setter_getter() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
@ -433,10 +436,10 @@ fn rename_setter_getter() {
"#,
)
.file(
"another.ts",
"another.js",
r#"
export class Foo {
constructor(private num: number) {
constructor() {
this.num = 1;
}

View File

@ -42,30 +42,30 @@ fn simple() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
let ARG: string | null = null;
let ANOTHER_ARG: number | null = null;
let SYM = (Symbol as any)('a');
let ARG = null;
let ANOTHER_ARG = null;
let SYM = Symbol('a');
export function foo(s: string): void {
export function foo(s) {
assert.strictEqual(ARG, null);
assert.strictEqual(s, "foo");
ARG = s;
}
export function another(s: number): number {
export function another(s) {
assert.strictEqual(ANOTHER_ARG, null);
assert.strictEqual(s, 21);
ANOTHER_ARG = s;
return 35;
}
export function take_and_return_bool(s: boolean): boolean {
export function take_and_return_bool(s) {
return s;
}
export function return_object(): any {
export function return_object() {
return SYM;
}
@ -111,7 +111,7 @@ fn unused() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
@ -149,11 +149,11 @@ fn string_ret() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
export function foo(): string {
export function foo() {
return 'bar';
}
@ -194,12 +194,12 @@ fn strings() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
export function foo(a: string): string {
export function foo(a) {
return a + 'b';
}
@ -246,7 +246,7 @@ fn exceptions() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run, run2 } from "./out";
import * as assert from "assert";
@ -301,7 +301,7 @@ fn exn_caught() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
import * as assert from "assert";
@ -344,7 +344,7 @@ fn free_imports() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
@ -381,7 +381,7 @@ fn import_a_field() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
@ -420,7 +420,7 @@ fn rename() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
@ -443,6 +443,7 @@ fn rename() {
#[test]
fn versions() {
project()
.debug(false)
.file(
"src/lib.rs",
r#"
@ -466,10 +467,10 @@ fn versions() {
.file(
"test.js",
r#"
const fs = require("fs");
const assert = require("assert");
import * as fs from 'fs';
import * as assert from 'assert';
exports.test = function() {
export function test() {
const bytes = fs.readFileSync('out_bg.wasm');
const m = new WebAssembly.Module(bytes);
const name = '__wasm_pack_unstable';
@ -511,10 +512,10 @@ fn underscore_pattern() {
foo(1);
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import { run } from "./out";
export function foo(_a: number) {
export function foo(_a) {
}
export function test() {
@ -549,7 +550,7 @@ fn rust_keyword() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
@ -592,7 +593,7 @@ fn rust_keyword2() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run } from "./out";
@ -645,18 +646,18 @@ fn custom_type() {
bad2();
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import { run, Foo, bad } from "./out";
let VAL: any = null;
let VAL = null;
export function foo(f: Foo): Foo {
export function foo(f) {
VAL = f;
return f;
}
export function bad2(): number {
export function bad2() {
return 2;
}
@ -691,7 +692,7 @@ fn unused_imports_not_generated() {
pub fn run() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import { run } from "./out";
export function test() {

View File

@ -22,7 +22,7 @@ fn filter() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -61,7 +61,7 @@ fn index_of() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -104,27 +104,27 @@ fn is_array() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert(wasm.is_array([]));
assert(wasm.is_array([1]));
assert(wasm.is_array(new Array()));
assert(wasm.is_array(new Array('a', 'b', 'c', 'd')));
assert(wasm.is_array(new Array(3)));
assert(wasm.is_array(Array.prototype));
assert.ok(wasm.is_array([]));
assert.ok(wasm.is_array([1]));
assert.ok(wasm.is_array(new Array()));
assert.ok(wasm.is_array(new Array('a', 'b', 'c', 'd')));
assert.ok(wasm.is_array(new Array(3)));
assert.ok(wasm.is_array(Array.prototype));
assert(!wasm.is_array({}));
assert(!wasm.is_array(null));
assert(!wasm.is_array(undefined));
assert(!wasm.is_array(17));
assert(!wasm.is_array('Array'));
assert(!wasm.is_array(true));
assert(!wasm.is_array(false));
assert(!wasm.is_array({ __proto__: Array.prototype }));
assert.ok(!wasm.is_array({}));
assert.ok(!wasm.is_array(null));
assert.ok(!wasm.is_array(undefined));
assert.ok(!wasm.is_array(17));
assert.ok(!wasm.is_array('Array'));
assert.ok(!wasm.is_array(true));
assert.ok(!wasm.is_array(false));
assert.ok(!wasm.is_array({ __proto__: Array.prototype }));
}
"#,
)
@ -151,7 +151,7 @@ fn sort() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -183,7 +183,7 @@ fn some() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -218,7 +218,7 @@ fn last_index_of() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -262,7 +262,7 @@ fn join() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -299,7 +299,7 @@ fn slice() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -335,7 +335,7 @@ fn fill() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -368,7 +368,7 @@ fn copy_within() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -406,7 +406,7 @@ fn pop() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -442,7 +442,7 @@ fn push() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -478,7 +478,7 @@ fn reverse() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -514,7 +514,7 @@ fn shift() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -551,7 +551,7 @@ fn unshift() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -588,7 +588,7 @@ fn to_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -624,7 +624,7 @@ fn includes() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -665,7 +665,7 @@ fn concat() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -702,7 +702,7 @@ fn length() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -712,7 +712,7 @@ fn length() {
let charactersLength = wasm.array_length(characters);
assert.equal(charactersLength, 6);
var empty : number[] = [];
var empty = [];
let emptyLength = wasm.array_length(empty);
assert.equal(emptyLength, 0);
}
@ -740,7 +740,7 @@ fn every() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -750,9 +750,47 @@ fn every() {
const arrayOdd = [1, 3, 5, 7];
const arrayMixed = [2, 3, 4, 5];
assert(wasm.array_every_number_is_even(arrayEven));
assert(!wasm.array_every_number_is_even(arrayOdd));
assert(!wasm.array_every_number_is_even(arrayMixed));
assert.ok(wasm.array_every_number_is_even(arrayEven));
assert.ok(!wasm.array_every_number_is_even(arrayOdd));
assert.ok(!wasm.array_every_number_is_even(arrayMixed));
}
"#,
)
.test()
}
#[test]
fn find() {
project()
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn array_find_first_even_number(array: &js::Array) -> JsValue {
array.find(&mut |el, _, _| el.as_f64().unwrap() % 2f64 == 0f64)
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const arrayEven = [2, 4, 6, 8];
const arrayOdd = [1, 3, 5, 7];
const arrayMixed = [3, 5, 7, 10];
assert.equal(wasm.array_find_first_even_number(arrayEven), 2);
assert.equal(wasm.array_find_first_even_number(arrayOdd), undefined);
assert.equal(wasm.array_find_first_even_number(arrayMixed), 10);
}
"#,
)

View File

@ -0,0 +1,110 @@
#![allow(non_snake_case)]
use super::project;
#[test]
fn new() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js::ArrayBuffer;
#[wasm_bindgen]
pub fn new_arraybuffer() -> ArrayBuffer {
ArrayBuffer::new(42)
}
"#)
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert.equal(typeof wasm.new_arraybuffer(), "object");
}
"#)
.test()
}
#[test]
fn is_view() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use JsValue;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js::ArrayBuffer;
#[wasm_bindgen]
pub fn is_view(value: JsValue) -> bool {
ArrayBuffer::is_view(value)
}
"#)
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert.equal(wasm.is_view(new Uint8Array(42)), true);
}
"#)
.test()
}
#[test]
fn slice() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js::ArrayBuffer;
#[wasm_bindgen]
pub fn slice(arraybuffer: &ArrayBuffer, begin: u32) -> ArrayBuffer {
arraybuffer.slice(begin)
}
"#)
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const arraybuffer = new ArrayBuffer(4);
assert.equal(typeof wasm.slice(arraybuffer, 2), "object");
}
"#)
.test()
}
#[test]
fn slice_with_end() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js::ArrayBuffer;
#[wasm_bindgen]
pub fn slice_with_end(arraybuffer: &ArrayBuffer, begin: u32, end: u32) -> ArrayBuffer {
arraybuffer.slice_with_end(begin, end)
}
"#)
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const arraybuffer = new ArrayBuffer(4);
assert.equal(typeof wasm.slice_with_end(arraybuffer, 1, 2), "object");
}
"#)
.test()
}

View File

@ -22,7 +22,7 @@ fn keys() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -60,7 +60,7 @@ fn entries() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -21,7 +21,7 @@ fn new_undefined() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -53,7 +53,7 @@ fn new_truely() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

138
tests/all/js_globals/Date.rs Normal file → Executable file
View File

@ -2,6 +2,110 @@
use super::project;
#[test]
fn get_date() {
project()
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js::Date;
#[wasm_bindgen]
pub fn get_date(this: &Date) -> u32 {
this.get_date()
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
let date = new Date(1993, 6, 28, 14, 39, 7);
assert.equal(wasm.get_date(date), 28);
}
"#,
)
.test()
}
#[test]
fn get_day() {
project()
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js::Date;
#[wasm_bindgen]
pub fn get_day(this: &Date) -> u32 {
this.get_day()
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
let date = new Date('August 19, 1975 23:15:30');
assert.equal(wasm.get_day(date), 2);
}
"#,
)
.test()
}
#[test]
fn get_full_year() {
project()
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js::Date;
#[wasm_bindgen]
pub fn get_full_year(this: &Date) -> u32 {
this.get_full_year()
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
let date = new Date('July 20, 1969 00:20:18');
let abbrDate = new Date('Thu, 06 Sep 12 00:00:00');
assert.equal(wasm.get_full_year(date), 1969);
assert.equal(wasm.get_full_year(abbrDate), 2012);
}
"#,
)
.test()
}
#[test]
fn new() {
project()
@ -21,7 +125,7 @@ fn new() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -49,7 +153,7 @@ fn now() {
Date::now()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -79,7 +183,7 @@ fn to_date_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -113,7 +217,7 @@ fn to_iso_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -147,7 +251,7 @@ fn to_json() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -178,7 +282,7 @@ fn to_locale_date_string() {
this.to_locale_date_string(locale, options)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -186,7 +290,9 @@ fn to_locale_date_string() {
let date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
assert.equal(wasm.to_locale_date_string(date, 'de-DE', options), 'Thursday, December 20, 2012');
let output = wasm.to_locale_date_string(date, 'de-DE', options)
assert.equal(typeof output, 'string');
assert.ok(output.length > 0);
}
"#)
.test()
@ -208,13 +314,15 @@ fn to_locale_string() {
this.to_locale_string(locale, options)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
let date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
assert.equal(wasm.to_locale_string(date, 'en-GB', { timeZone: 'UTC' }), "12/20/2012, 3:00:00 AM");
let output = wasm.to_locale_string(date, 'en-GB', { timeZone: 'UTC' });
assert.equal(typeof output, 'string');
assert.ok(output.length > 0);
}
"#)
.test()
@ -239,7 +347,7 @@ fn to_locale_time_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -272,7 +380,7 @@ fn to_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -305,7 +413,7 @@ fn to_time_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -338,7 +446,7 @@ fn to_utc_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -367,7 +475,7 @@ fn utc() {
Date::utc(2018f64, 6f64)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -397,7 +505,7 @@ fn value_of() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -18,7 +18,7 @@ fn new() {
Error::new(message)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -48,7 +48,7 @@ fn message() {
this.message()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -78,7 +78,7 @@ fn set_message() {
this.set_message(message);
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -109,7 +109,7 @@ fn name() {
this.name()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -140,7 +140,7 @@ fn set_name() {
this.set_name(name);
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -171,7 +171,7 @@ fn to_string() {
this.to_string()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -180,13 +180,13 @@ fn to_string() {
assert.equal(wasm.error_to_string(error), 'Error: error message 1');
(error.name as any) = undefined;
error.name = undefined;
assert.equal(wasm.error_to_string(error), 'Error: error message 1');
error.name = 'error_name_1';
assert.equal(wasm.error_to_string(error), 'error_name_1: error message 1');
(error.message as any) = undefined;
error.message = undefined;
assert.equal(wasm.error_to_string(error), 'error_name_1');
error.name = 'error_name_2';

View File

@ -21,7 +21,7 @@ fn apply() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -57,7 +57,7 @@ fn bind() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -97,21 +97,21 @@ fn length() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert.equal(wasm.fn_length(() => {}), 0);
assert.equal(wasm.fn_length((a: string) => console.log(a)), 1);
assert.equal(wasm.fn_length((a: string, b: string) => console.log({ a, b })), 2);
assert.equal(wasm.fn_length(a => console.log(a)), 1);
assert.equal(wasm.fn_length((a, b) => console.log({ a, b })), 2);
function fn0() {}
function fn1(a: string) {
function fn1(a) {
console.log(a);
}
function fn2(a: string, b: string) {
function fn2(a, b) {
console.log({ a, b });
}
@ -143,7 +143,7 @@ fn name() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -190,17 +190,17 @@ fn to_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
function fn1(a: any, b: any) { return a + b }
const fn2 = (a: number) => console.log(a);
function fn1(a, b) { return a + b; }
const fn2 = a => console.log(a);
assert.equal(wasm.get_source_code(fn1), 'function fn1(a, b) { return a + b; }');
assert.equal(wasm.get_source_code(fn2), 'function (a) { return console.log(a); }');
assert.equal(wasm.get_source_code(fn2), 'a => console.log(a)');
}
"#,
)

View File

@ -21,7 +21,7 @@ fn return_() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -72,7 +72,7 @@ fn next() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -97,7 +97,7 @@ fn next() {
yield 1;
}
assert(wasm.next_throws_error(brokenGenerator(), undefined));
assert.ok(wasm.next_throws_error(brokenGenerator(), undefined));
}
"#,
)
@ -123,7 +123,7 @@ fn throw() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -137,7 +137,7 @@ fn throw() {
const gen = generator();
gen.next();
assert(wasm.gen_throws_error(gen, new Error('Something went wrong')));
assert.ok(wasm.gen_throws_error(gen, new Error('Something went wrong')));
assert.deepEqual(gen.next(), { value: undefined, done: true });
}
"#,

48
tests/all/js_globals/JsString.rs Normal file → Executable file
View File

@ -22,7 +22,7 @@ fn length() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -58,7 +58,7 @@ fn char_at() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -87,13 +87,13 @@ fn char_code_at() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn string_char_code_at(this: &js::JsString, index: u32) -> js::Number {
pub fn string_char_code_at(this: &js::JsString, index: u32) -> f64 {
this.char_code_at(index)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -101,8 +101,14 @@ fn char_code_at() {
var anyString = 'Brave new world';
export function test() {
assert.equal(wasm.string_char_code_at(anyString, 0), 66);
assert.ok(isNaN(wasm.string_char_code_at(anyString, 999)));
for (let i = 0; i < anyString.length; i++) {
assert.equal(wasm.string_char_code_at(anyString, i),
anyString.charCodeAt(i),
`charCodeAt(${i})`);
}
const outOfBounds = wasm.string_char_code_at(anyString, 999);
assert.ok(Number.isNaN(outOfBounds));
}
"#,
)
@ -128,7 +134,7 @@ fn code_point_at() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -162,7 +168,7 @@ fn concat() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -196,7 +202,7 @@ fn includes() {
this.includes(search_value, position)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -231,7 +237,7 @@ fn index_of() {
this.index_of(search_value, from_index)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -274,7 +280,7 @@ fn slice() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -305,7 +311,7 @@ fn starts_with() {
this.starts_with(search_string, position)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -336,7 +342,7 @@ fn substring() {
this.substring(index_start, index_end)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -375,7 +381,7 @@ fn substr() {
this.substr(start, length)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -411,7 +417,7 @@ fn to_lower_case() {
this.to_lower_case()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -441,7 +447,7 @@ fn to_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -470,7 +476,7 @@ fn to_upper_case() {
this.to_upper_case()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -500,7 +506,7 @@ fn trim() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -539,7 +545,7 @@ fn trim_end_and_trim_right() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -579,7 +585,7 @@ fn trim_start_and_trim_left() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -614,7 +620,7 @@ fn value_of() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

16
tests/all/js_globals/Map.rs Normal file → Executable file
View File

@ -17,7 +17,7 @@ fn clear() {
this.clear();
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -49,7 +49,7 @@ fn delete() {
this.delete(key)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -81,7 +81,7 @@ fn get() {
this.get(key)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -112,7 +112,7 @@ fn has() {
this.has(key)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -141,7 +141,7 @@ fn new() {
js::Map::new()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -169,7 +169,7 @@ fn set() {
this.set(key, value)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -194,11 +194,11 @@ fn size() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn map_size(this: &js::Map) -> js::Number {
pub fn map_size(this: &js::Map) -> u32 {
this.size()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -18,7 +18,7 @@ fn entries() {
this.entries()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -50,7 +50,7 @@ fn keys() {
this.keys()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -82,7 +82,7 @@ fn values() {
this.values()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";

140
tests/all/js_globals/Math.rs Normal file → Executable file
View File

@ -15,13 +15,13 @@ fn abs() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn abs(x: f64) -> js::Number {
pub fn abs(x: f64) -> f64 {
js::Math::abs(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -49,13 +49,13 @@ fn acos() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn acos(x: f64) -> js::Number {
pub fn acos(x: f64) -> f64 {
js::Math::acos(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -63,7 +63,7 @@ fn acos() {
export function test() {
assert.equal(wasm.acos(-1), Math.PI);
assert.equal(wasm.acos(0.5), 1.0471975511965979);
assert(Number.isNaN(wasm.acos(2)));
assert.ok(Number.isNaN(wasm.acos(2)));
}
"#,
)
@ -83,13 +83,13 @@ fn acosh() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn acosh(x: f64) -> js::Number {
pub fn acosh(x: f64) -> f64 {
js::Math::acosh(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -97,7 +97,7 @@ fn acosh() {
export function test() {
assert.equal(wasm.acosh(1), 0);
assert.equal(wasm.acosh(2), Math.acosh(2));
assert(Number.isNaN(wasm.acosh(0.5)));
assert.ok(Number.isNaN(wasm.acosh(0.5)));
}
"#,
)
@ -117,13 +117,13 @@ fn asin() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn asin(x: f64) -> js::Number {
pub fn asin(x: f64) -> f64 {
js::Math::asin(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -131,7 +131,7 @@ fn asin() {
export function test() {
assert.equal(wasm.asin(1), Math.asin(1));
assert.equal(wasm.asin(0.5), Math.asin(0.5));
assert(Number.isNaN(wasm.asin(2)));
assert.ok(Number.isNaN(wasm.asin(2)));
}
"#,
)
@ -151,13 +151,13 @@ fn asinh() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn asinh(x: f64) -> js::Number {
pub fn asinh(x: f64) -> f64 {
js::Math::asinh(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -184,13 +184,13 @@ fn atan() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn atan(x: f64) -> js::Number {
pub fn atan(x: f64) -> f64 {
js::Math::atan(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -217,13 +217,13 @@ fn atan2() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn atan2(y: f64, x: f64) -> js::Number {
pub fn atan2(y: f64, x: f64) -> f64 {
js::Math::atan2(y, x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -250,13 +250,13 @@ fn atanh() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn atanh(x: f64) -> js::Number {
pub fn atanh(x: f64) -> f64 {
js::Math::atanh(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -264,7 +264,7 @@ fn atanh() {
export function test() {
assert.equal(wasm.atanh(1), Math.atanh(1));
assert.equal(wasm.atanh(0.5), Math.atanh(0.5));
assert(Number.isNaN(wasm.atanh(2)));
assert.ok(Number.isNaN(wasm.atanh(2)));
}
"#,
)
@ -284,13 +284,13 @@ fn cbrt() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn cbrt(x: f64) -> js::Number {
pub fn cbrt(x: f64) -> f64 {
js::Math::cbrt(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -317,13 +317,13 @@ fn ceil() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn ceil(x: f64) -> js::Number {
pub fn ceil(x: f64) -> i32 {
js::Math::ceil(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -350,13 +350,13 @@ fn clz32() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn clz32(x: i32) -> js::Number {
pub fn clz32(x: i32) -> u32 {
js::Math::clz32(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -381,11 +381,11 @@ fn cos() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn cos(x: f64) -> js::Number {
pub fn cos(x: f64) -> f64 {
js::Math::cos(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -408,11 +408,11 @@ fn cosh() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn cosh(x: f64) -> js::Number {
pub fn cosh(x: f64) -> f64 {
js::Math::cosh(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -435,11 +435,11 @@ fn exp() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn exp(x: f64) -> js::Number {
pub fn exp(x: f64) -> f64 {
js::Math::exp(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -463,11 +463,11 @@ fn expm1() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn expm1(x: f64) -> js::Number {
pub fn expm1(x: f64) -> f64 {
js::Math::expm1(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -494,13 +494,13 @@ fn floor() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn floor(x: f64) -> js::Number {
pub fn floor(x: f64) -> i32 {
js::Math::floor(x)
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -525,11 +525,11 @@ fn fround() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn fround(x: f64) -> js::Number {
pub fn fround(x: f64) -> f32 {
js::Math::fround(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -554,11 +554,11 @@ fn imul() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn imul(x: i32, y:i32) -> js::Number {
pub fn imul(x: i32, y:i32) -> i32 {
js::Math::imul(x, y)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -582,11 +582,11 @@ fn log() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn log(x: f64) -> js::Number {
pub fn log(x: f64) -> f64 {
js::Math::log(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -609,11 +609,11 @@ fn log10() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn log10(x: f64) -> js::Number {
pub fn log10(x: f64) -> f64 {
js::Math::log10(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -637,11 +637,11 @@ fn log1p() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn log1p(x: f64) -> js::Number {
pub fn log1p(x: f64) -> f64 {
js::Math::log1p(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -649,7 +649,7 @@ fn log1p() {
assert.equal(wasm.log1p(1), 0.6931471805599453);
assert.equal(wasm.log1p(0), 0);
assert.equal(wasm.log1p(-1), -Infinity);
assert(isNaN(wasm.log1p(-2)));
assert.ok(isNaN(wasm.log1p(-2)));
}
"#)
.test()
@ -666,11 +666,11 @@ fn log2() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn log2(x: f64) -> js::Number {
pub fn log2(x: f64) -> f64 {
js::Math::log2(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -695,18 +695,18 @@ fn pow() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn pow(base: f64, exponent: f64) -> js::Number {
pub fn pow(base: f64, exponent: f64) -> f64 {
js::Math::pow(base, exponent)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert.equal(wasm.pow(7, 2), 49);
assert.equal(wasm.pow(3.8, 0.5), Math.pow(3.8, 0.5));
assert(Number.isNaN(wasm.pow(-2, 0.5)));
assert.ok(Number.isNaN(wasm.pow(-2, 0.5)));
}
"#)
.test()
@ -723,11 +723,11 @@ fn round() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn round(x: f64) -> js::Number {
pub fn round(x: f64) -> i32 {
js::Math::round(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -753,11 +753,11 @@ fn sign() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn sign(x: f64) -> js::Number {
pub fn sign(x: f64) -> f64 {
js::Math::sign(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -766,7 +766,7 @@ fn sign() {
assert.equal(wasm.sign(-3), -1);
assert.equal(wasm.sign(2.3), 1);
assert.equal(wasm.sign(0), 0);
assert(Number.isNaN(wasm.sign(NaN)));
assert.ok(Number.isNaN(wasm.sign(NaN)));
}
"#)
.test()
@ -783,11 +783,11 @@ fn sin() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn sin(x: f64) -> js::Number {
pub fn sin(x: f64) -> f64 {
js::Math::sin(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -811,11 +811,11 @@ fn sinh() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn sinh(x: f64) -> js::Number {
pub fn sinh(x: f64) -> f64 {
js::Math::sinh(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -839,11 +839,11 @@ fn sqrt() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn sqrt(x: f64) -> js::Number {
pub fn sqrt(x: f64) -> f64 {
js::Math::sqrt(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -852,7 +852,7 @@ fn sqrt() {
assert.equal(wasm.sqrt(2), Math.sqrt(2));
assert.equal(wasm.sqrt(42.42), Math.sqrt(42.42));
assert.equal(wasm.sqrt(1), 1);
assert(Number.isNaN(wasm.sqrt(-1)));
assert.ok(Number.isNaN(wasm.sqrt(-1)));
}
"#)
.test()
@ -869,11 +869,11 @@ fn tan() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn tan(x: f64) -> js::Number {
pub fn tan(x: f64) -> f64 {
js::Math::tan(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -897,11 +897,11 @@ fn tanh() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn tanh(x: f64) -> js::Number {
pub fn tanh(x: f64) -> f64 {
js::Math::tanh(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -925,11 +925,11 @@ fn trunc() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn trunc(x: f64) -> js::Number {
pub fn trunc(x: f64) -> i32 {
js::Math::trunc(x)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";

43
tests/all/js_globals/Number.rs Normal file → Executable file
View File

@ -2,6 +2,33 @@
use super::project;
#[test]
fn is_integer() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn is_integer(obj: &js::Object) -> bool {
js::Number::is_integer(&obj)
}
"#)
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert.ok(wasm.is_integer(123));
assert.ok(!wasm.is_integer(123.45));
}
"#)
.test()
}
#[test]
fn new() {
project()
@ -17,7 +44,7 @@ fn new() {
Number::new(JsValue::from(42))
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -44,7 +71,7 @@ fn to_locale_string() {
this.to_locale_string(locale)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -83,7 +110,7 @@ fn to_precision() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -121,7 +148,7 @@ fn to_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -150,13 +177,13 @@ fn value_of() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn js_value_of(this: &js::Number) -> js::Number {
pub fn js_value_of(this: &js::Number) -> f64 {
this.value_of()
}
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -195,7 +222,7 @@ fn to_fixed() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -233,7 +260,7 @@ fn to_exponential() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -21,7 +21,7 @@ fn new() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -53,18 +53,18 @@ fn has_own_property() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert(wasm.has_own_foo_property({ foo: 42 }, "foo"));
assert(wasm.has_own_foo_property({ 42: "foo" }, 42));
assert(!wasm.has_own_foo_property({ foo: 42 }, "bar"));
assert.ok(wasm.has_own_foo_property({ foo: 42 }, "foo"));
assert.ok(wasm.has_own_foo_property({ 42: "foo" }, 42));
assert.ok(!wasm.has_own_foo_property({ foo: 42 }, "bar"));
const s = Symbol();
assert(wasm.has_own_foo_property({ [s]: "foo" }, s));
assert.ok(wasm.has_own_foo_property({ [s]: "foo" }, s));
}
"#,
)
@ -96,7 +96,7 @@ fn to_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -125,16 +125,16 @@ fn is_extensible() {
js::Object::is_extensible(&obj)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const object = {};
assert(wasm.is_extensible(object));
assert.ok(wasm.is_extensible(object));
Object.preventExtensions(object);
assert(!wasm.is_extensible(object));
assert.ok(!wasm.is_extensible(object));
}
"#)
.test()
@ -155,16 +155,16 @@ fn is_frozen() {
js::Object::is_frozen(&obj)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const object = {};
assert(!wasm.is_frozen(object));
assert.ok(!wasm.is_frozen(object));
Object.freeze(object);
assert(wasm.is_frozen(object));
assert.ok(wasm.is_frozen(object));
}
"#)
.test()
@ -185,16 +185,16 @@ fn is_sealed() {
js::Object::is_sealed(&obj)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const object = {};
assert(!wasm.is_sealed(object));
assert.ok(!wasm.is_sealed(object));
Object.seal(object);
assert(wasm.is_sealed(object));
assert.ok(wasm.is_sealed(object));
}
"#)
.test()
@ -219,7 +219,7 @@ fn is_prototype_of() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -229,8 +229,8 @@ fn is_prototype_of() {
export function test() {
const foo = new Foo();
assert(wasm.obj_is_prototype_of_value(Foo.prototype, foo));
assert(!wasm.obj_is_prototype_of_value(Bar.prototype, foo));
assert.ok(wasm.obj_is_prototype_of_value(Foo.prototype, foo));
assert.ok(!wasm.obj_is_prototype_of_value(Bar.prototype, foo));
}
"#,
)
@ -256,7 +256,7 @@ fn keys() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -285,7 +285,7 @@ fn prevent_extensions() {
js::Object::prevent_extensions(obj);
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -293,7 +293,7 @@ fn prevent_extensions() {
const object = {};
wasm.prevent_extensions(object);
assert(!Object.isExtensible(object));
assert.ok(!Object.isExtensible(object));
assert.throws(() => {
'use strict';
Object.defineProperty(object, 'foo', { value: 42 });
@ -322,19 +322,19 @@ fn property_is_enumerable() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert(wasm.property_is_enumerable({ foo: 42 }, "foo"));
assert(wasm.property_is_enumerable({ 42: "foo" }, 42));
assert(!wasm.property_is_enumerable({}, 42));
assert.ok(wasm.property_is_enumerable({ foo: 42 }, "foo"));
assert.ok(wasm.property_is_enumerable({ 42: "foo" }, 42));
assert.ok(!wasm.property_is_enumerable({}, 42));
const obj = {};
Object.defineProperty(obj, "foo", { enumerable: false });
assert(!wasm.property_is_enumerable(obj, "foo"));
assert.ok(!wasm.property_is_enumerable(obj, "foo"));
const s = Symbol();
assert.ok(wasm.property_is_enumerable({ [s]: true }, s));
@ -359,12 +359,12 @@ fn seal() {
js::Object::seal(&value)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const object: any = { foo: 'bar' };
const object = { foo: 'bar' };
const sealedObject = wasm.seal(object);
assert.strictEqual(object, sealedObject);
assert.throws(() => {
@ -410,7 +410,7 @@ fn set_prototype_of() {
js::Object::set_prototype_of(&object, &prototype)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -419,7 +419,7 @@ fn set_prototype_of() {
const newPrototype = { bar: 'baz' };
const modifiedObject = wasm.set_prototype_of(object, newPrototype);
assert(newPrototype.isPrototypeOf(modifiedObject));
assert.ok(newPrototype.isPrototypeOf(modifiedObject));
}
"#)
.test()
@ -445,7 +445,7 @@ fn to_locale_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -477,7 +477,7 @@ fn value_of() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -507,7 +507,7 @@ fn values() {
js::Object::values(&obj)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -0,0 +1,76 @@
#![allow(non_snake_case)]
use project;
#[test]
fn new() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn new_proxy(target: JsValue, handler: js::Object) -> js::Proxy {
js::Proxy::new(&target, &handler)
}
"#)
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const target = { a: 100 };
const handler = {
get: function(obj, prop) {
return prop in obj ? obj[prop] : 37;
}
};
const proxy = wasm.new_proxy(target, handler);
assert.equal(proxy.a, 100);
assert.equal(proxy.b, 37);
}
"#)
.test()
}
#[test]
fn revocable() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn new_revocable_proxy(target: JsValue, handler: js::Object) -> js::Object {
js::Proxy::revocable(&target, &handler)
}
"#)
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const target = { a: 100 };
const handler = {
get: function(obj, prop) {
return prop in obj ? obj[prop] : 37;
}
};
const { proxy, revoke } =
wasm.new_revocable_proxy(target, handler);
assert.equal(proxy.a, 100);
assert.equal(proxy.b, 37);
revoke();
assert.throws(() => { proxy.a }, TypeError);
assert.throws(() => { proxy.b }, TypeError);
assert.equal(typeof proxy, "object");
}
"#)
.test()
}

14
tests/all/js_globals/Set.rs Normal file → Executable file
View File

@ -18,7 +18,7 @@ fn add() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -51,7 +51,7 @@ fn clear() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -81,7 +81,7 @@ fn delete() {
this.delete(value)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -110,7 +110,7 @@ fn has() {
this.has(value)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -139,7 +139,7 @@ fn new() {
js::Set::new()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -163,12 +163,12 @@ fn size() {
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn size(this: &js::Set) -> js::Number {
pub fn size(this: &js::Set) -> u32 {
this.size()
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -18,7 +18,7 @@ fn entries() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -50,7 +50,7 @@ fn keys() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -81,7 +81,7 @@ fn values() {
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -0,0 +1,42 @@
#![allow(non_snake_case)]
use project;
#[test]
fn has_instance() {
project()
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js;
#[wasm_bindgen]
pub fn symbol_has_instance() -> js::Symbol {
js::Symbol::has_instance()
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
class Array1 {
static [wasm.symbol_has_instance()](instance) {
return Array.isArray(instance);
}
}
export function test() {
assert.equal(typeof wasm.symbol_has_instance(), "symbol");
assert.ok([] instanceof Array1);
}
"#,
)
.test()
}

View File

@ -21,7 +21,7 @@ fn new_undefined() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -53,7 +53,7 @@ fn new_length() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -81,7 +81,7 @@ fn fill() {
this.fill(value, start, end)
}
"#)
.file("test.ts", r#"
.file("test.js", r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -21,7 +21,7 @@ fn new() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -53,7 +53,7 @@ fn get() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -91,7 +91,7 @@ fn set() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -126,7 +126,7 @@ fn has() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -164,7 +164,7 @@ fn delete() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -21,7 +21,7 @@ fn new() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -53,7 +53,7 @@ fn has() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -91,7 +91,7 @@ fn add() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -132,7 +132,7 @@ fn delete() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -3,6 +3,7 @@
use super::project;
mod Array;
mod ArrayBuffer;
mod ArrayIterator;
mod Boolean;
mod Date;
@ -15,9 +16,11 @@ mod MapIterator;
mod Math;
mod Number;
mod Object;
mod Proxy;
mod Reflect;
mod Set;
mod SetIterator;
mod Symbol;
mod TypedArray;
mod WeakMap;
mod WeakSet;

View File

@ -24,21 +24,21 @@ fn simple() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
let ARG: string | null = null;
let ARG = null;
export function foo(s: any): void {
export function foo(s) {
assert.strictEqual(ARG, null);
ARG = s;
}
export function test() {
assert.strictEqual(ARG, null);
let sym = (Symbol as any)('test');
let sym = Symbol('test');
wasm.bar(sym);
assert.strictEqual(ARG, sym);
}
@ -71,21 +71,21 @@ fn owned() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
let ARG: any = null;
let ARG = null;
export function foo(s: any): void {
export function foo(s) {
assert.strictEqual(ARG, null);
ARG = s;
}
export function test() {
assert.strictEqual(ARG, null);
let sym = (Symbol as any)('test');
let sym = Symbol('test');
wasm.bar(sym);
assert.strictEqual(ARG, sym);
}
@ -126,18 +126,18 @@ fn clone() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
let ARG = (Symbol as any)('test');
let ARG = Symbol('test');
export function foo1(s: any): void { assert.strictEqual(s, ARG); }
export function foo2(s: any): void { assert.strictEqual(s, ARG); }
export function foo3(s: any): void { assert.strictEqual(s, ARG); }
export function foo4(s: any): void { assert.strictEqual(s, ARG); }
export function foo5(s: any): void { assert.strictEqual(s, ARG); }
export function foo1(s) { assert.strictEqual(s, ARG); }
export function foo2(s) { assert.strictEqual(s, ARG); }
export function foo3(s) { assert.strictEqual(s, ARG); }
export function foo4(s) { assert.strictEqual(s, ARG); }
export function foo5(s) { assert.strictEqual(s, ARG); }
export function test() {
wasm.bar(ARG);
@ -177,17 +177,17 @@ fn promote() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
let ARG = (Symbol as any)('test');
let ARG = Symbol('test');
export function foo1(s: any): void { assert.strictEqual(s, ARG); }
export function foo2(s: any): void { assert.strictEqual(s, ARG); }
export function foo3(s: any): void { assert.strictEqual(s, ARG); }
export function foo4(s: any): void { assert.strictEqual(s, ARG); }
export function foo1(s) { assert.strictEqual(s, ARG); }
export function foo2(s) { assert.strictEqual(s, ARG); }
export function foo3(s) { assert.strictEqual(s, ARG); }
export function foo4(s) { assert.strictEqual(s, ARG); }
export function test() {
wasm.bar(ARG);
@ -225,12 +225,12 @@ fn returning_vector() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
import * as assert from "assert";
export function foo(): any { return { "foo": "bar" }; }
export function foo() { return { "foo": "bar" }; }
export function test() {
const result = wasm.bar();
@ -268,7 +268,7 @@ fn another_vector_return() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { get_array } from "./out";
import * as assert from "assert";
@ -344,12 +344,12 @@ fn serde() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { run, parse } from "./out";
import * as assert from "assert";
export function verify(a: any) {
export function verify(a) {
assert.deepStrictEqual(a, {
a: 0,
b: 'foo',

View File

@ -1,544 +1,6 @@
extern crate wasm_bindgen_cli_support as cli;
extern crate wasm_bindgen_test_project_builder as project_builder;
use std::env;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::*;
use std::sync::{Once, ONCE_INIT};
use std::time::Instant;
static CNT: AtomicUsize = ATOMIC_USIZE_INIT;
thread_local!(static IDX: usize = CNT.fetch_add(1, Ordering::SeqCst));
struct Project {
files: Vec<(String, String)>,
debug: bool,
node: bool,
no_std: bool,
serde: bool,
rlib: bool,
node_args: Vec<String>,
deps: Vec<String>,
}
fn project() -> Project {
let dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let mut lockfile = String::new();
fs::File::open(&dir.join("Cargo.lock"))
.unwrap()
.read_to_string(&mut lockfile)
.unwrap();
Project {
debug: true,
node: false,
no_std: false,
serde: false,
rlib: false,
deps: Vec::new(),
node_args: Vec::new(),
files: vec![
("Cargo.lock".to_string(), lockfile),
(
"run-node.js".to_string(),
r#"require("./test").test();"#.to_string(),
),
(
"webpack.config.js".to_string(),
r#"
const path = require('path');
const fs = require('fs');
let nodeModules = {};
// Webpack bundles the modules from node_modules.
// For node target, we will not have `fs` module
// inside the `node_modules` folder.
// This reads the directories in `node_modules`
// and give that to externals and webpack ignores
// to bundle the modules listed as external.
fs.readdirSync('node_modules')
.filter(module => module !== '.bin')
.forEach(mod => {
// External however,expects browser environment.
// To make it work in `node` target we
// prefix commonjs here.
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './run.js',
mode: "development",
devtool: "source-map",
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.ts', '.js', '.wasm' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '.')
},
target: 'node',
externals: nodeModules
};
"#.to_string(),
),
(
"tsconfig.json".to_string(),
r#"
{
"compilerOptions": {
"noEmitOnError": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"noImplicitReturns": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"alwaysStrict": true,
"strict": true,
"target": "es5",
"lib": ["es2015"]
}
}
"#.to_string(),
),
],
}
}
fn root() -> PathBuf {
let idx = IDX.with(|x| *x);
let mut me = env::current_exe().unwrap();
me.pop(); // chop off exe name
me.pop(); // chop off `deps`
me.pop(); // chop off `debug` / `release`
me.push("generated-tests");
me.push(&format!("test{}", idx));
return me;
}
fn assert_bigint_support() -> Option<&'static str> {
static BIGINT_SUPPORED: AtomicUsize = ATOMIC_USIZE_INIT;
static INIT: Once = ONCE_INIT;
INIT.call_once(|| {
let mut cmd = Command::new("node");
cmd.arg("-e").arg("BigInt");
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
if cmd.status().unwrap().success() {
BIGINT_SUPPORED.store(1, Ordering::SeqCst);
return;
}
cmd.arg("--harmony-bigint");
if cmd.status().unwrap().success() {
BIGINT_SUPPORED.store(2, Ordering::SeqCst);
return;
}
});
match BIGINT_SUPPORED.load(Ordering::SeqCst) {
1 => return None,
2 => return Some("--harmony-bigint"),
_ => panic!(
"the version of node.js that is installed for these tests \
does not support `BigInt`, you may wish to try installing \
node 10 to fix this"
),
}
}
impl Project {
fn file(&mut self, name: &str, contents: &str) -> &mut Project {
self.files.push((name.to_string(), contents.to_string()));
self
}
fn debug(&mut self, debug: bool) -> &mut Project {
self.debug = debug;
self
}
fn node(&mut self, node: bool) -> &mut Project {
self.node = node;
self
}
fn no_std(&mut self, no_std: bool) -> &mut Project {
self.no_std = no_std;
self
}
fn serde(&mut self, serde: bool) -> &mut Project {
self.serde = serde;
self
}
fn rlib(&mut self, rlib: bool) -> &mut Project {
self.rlib = rlib;
self
}
fn depend(&mut self, dep: &str) -> &mut Project {
self.deps.push(dep.to_string());
self
}
fn add_local_dependency(&mut self, name: &str, path: &str) -> &mut Project {
self.deps
.push(format!("{} = {{ path = '{}' }}", name, path));
self
}
fn crate_name(&self) -> String {
format!("test{}", IDX.with(|x| *x))
}
fn requires_bigint(&mut self) -> &mut Project {
if let Some(arg) = assert_bigint_support() {
self.node_args.push(arg.to_string());
}
self
}
fn generate_webidl_bindings(&mut self) -> Vec<PathBuf> {
let mut res = Vec::new();
let mut origpaths = Vec::new();
for (path, _) in &self.files {
let path = Path::new(&path);
let extension = path.extension().map(|x| x.to_str().unwrap());
if extension != Some("webidl") {
continue;
}
res.push(path.with_extension("rs"));
origpaths.push(path.to_owned());
}
if res.is_empty() {
return res;
}
let mut buildrs = r#"
extern crate wasm_bindgen_webidl;
use wasm_bindgen_webidl::compile_file;
use std::env;
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
fn main() {
let dest = env::var("OUT_DIR").unwrap();
"#.to_string();
for (path, origpath) in res.iter().zip(origpaths.iter()) {
buildrs.push_str(&format!(
r#"
fs::create_dir_all("{}").unwrap();
File::create(&Path::new(&dest).join("{}"))
.unwrap()
.write_all(
compile_file(Path::new("{}"))
.unwrap()
.as_bytes()
)
.unwrap();
"#,
path.parent().unwrap().to_str().unwrap(),
path.to_str().unwrap(),
origpath.to_str().unwrap(),
));
self.files.push((
Path::new("src").join(path).to_str().unwrap().to_string(),
format!(
r#"include!(concat!(env!("OUT_DIR"), "/{}"));"#,
path.display()
),
));
}
buildrs.push('}');
self.files.push(("build.rs".to_string(), buildrs));
res
}
fn generate_js_entry(&mut self, modules: Vec<PathBuf>) {
let mut runjs = r#"
import * as process from "process";
"#.to_string();
if !modules.is_empty() {
runjs.push_str(r#"Promise.all(["#);
for module in &modules {
runjs.push_str(&format!(
r#"import('./{}'),"#,
module.with_extension("").to_str().unwrap()
));
}
runjs.push_str(
r#"]).then(results => { results.map(module => Object.assign(global, module));"#,
);
}
runjs.push_str(
r#"
let wasm = import('./out');
const test = import('./test');
"#,
);
if !modules.is_empty() {
runjs.push_str("return ");
}
runjs.push_str(r#"Promise.all([test, wasm])"#);
if !modules.is_empty() {
runjs.push_str("})");
}
runjs.push_str(
r#"
.then(results => {
let [test, wasm] = results;
test.test();
if (wasm.assertStackEmpty)
wasm.assertStackEmpty();
if (wasm.assertSlabEmpty)
wasm.assertSlabEmpty();
})
.catch(error => {
console.error(error);
process.exit(1);
});
"#,
);
self.files.push(("run.js".to_string(), runjs));
}
fn ensure_test_entry(&mut self) {
if !self
.files
.iter()
.any(|(path, _)| path == "test.ts" || path == "test.js")
{
self.files.push((
"test.ts".to_string(),
r#"export {test} from './out';"#.to_string(),
));
}
}
/// build + cargo cmd execution
fn cargo_build(&mut self) -> (PathBuf, PathBuf) {
let (root, target_dir) = self.build();
let mut cmd = Command::new("cargo");
cmd.arg("build")
.arg("--target")
.arg("wasm32-unknown-unknown")
.current_dir(&root)
.env("CARGO_TARGET_DIR", &target_dir)
// Catch any warnings in generated code because we don't want any
.env("RUSTFLAGS", "-Dwarnings");
run(&mut cmd, "cargo");
(root, target_dir)
}
fn build(&mut self) -> (PathBuf, PathBuf) {
self.ensure_test_entry();
let webidl_modules = self.generate_webidl_bindings();
self.generate_js_entry(webidl_modules);
let mut manifest = format!(
r#"
[package]
name = "test{}"
version = "0.0.1"
authors = []
[workspace]
[lib]
"#,
IDX.with(|x| *x)
);
if !self.rlib {
manifest.push_str("crate-type = [\"cdylib\"]\n");
}
manifest.push_str("[build-dependencies]\n");
manifest.push_str("wasm-bindgen-webidl = { path = '");
manifest.push_str(env!("CARGO_MANIFEST_DIR"));
manifest.push_str("/crates/webidl' }\n");
manifest.push_str("[dependencies]\n");
for dep in self.deps.iter() {
manifest.push_str(dep);
manifest.push_str("\n");
}
manifest.push_str("wasm-bindgen = { path = '");
manifest.push_str(env!("CARGO_MANIFEST_DIR"));
manifest.push_str("'");
if self.no_std {
manifest.push_str(", default-features = false");
}
if self.serde {
manifest.push_str(", features = ['serde-serialize']");
}
manifest.push_str(" }\n");
self.files.push(("Cargo.toml".to_string(), manifest));
let root = root();
drop(fs::remove_dir_all(&root));
for &(ref file, ref contents) in self.files.iter() {
let dst = root.join(file);
fs::create_dir_all(dst.parent().unwrap()).unwrap();
fs::File::create(&dst)
.unwrap()
.write_all(contents.as_ref())
.unwrap();
}
let target_dir = root.parent().unwrap() // chop off test name
.parent().unwrap(); // chop off `generated-tests`
(root.clone(), target_dir.to_path_buf())
}
fn test(&mut self) {
let (root, target_dir) = self.cargo_build();
self.gen_bindings(&root, &target_dir);
let mut wasm = Vec::new();
File::open(root.join("out_bg.wasm"))
.unwrap()
.read_to_end(&mut wasm)
.unwrap();
let obj = cli::wasm2es6js::Config::new()
.base64(true)
.generate(&wasm)
.expect("failed to convert wasm to js");
File::create(root.join("out_bg.d.ts"))
.unwrap()
.write_all(obj.typescript().as_bytes())
.unwrap();
// move files from the root into each test, it looks like this may be
// needed for webpack to work well when invoked concurrently.
fs::hard_link("package.json", root.join("package.json")).unwrap();
if !Path::new("node_modules").exists() {
panic!("\n\nfailed to find `node_modules`, have you run `npm install` yet?\n\n");
}
let cwd = env::current_dir().unwrap();
symlink_dir(&cwd.join("node_modules"), &root.join("node_modules")).unwrap();
if self.node {
let mut cmd = Command::new("node");
cmd.args(&self.node_args);
cmd.arg(root.join("run-node.js")).current_dir(&root);
run(&mut cmd, "node");
} else {
let mut cmd = if cfg!(windows) {
let mut c = Command::new("cmd");
c.arg("/c");
c.arg("npm");
c
} else {
Command::new("npm")
};
cmd.arg("run").arg("run-webpack").current_dir(&root);
run(&mut cmd, "npm");
let mut cmd = Command::new("node");
cmd.args(&self.node_args);
cmd.arg(root.join("bundle.js")).current_dir(&root);
run(&mut cmd, "node");
}
}
/// execute the cli against the current test .wasm
fn gen_bindings(&self, root: &PathBuf, target_dir: &PathBuf) {
let idx = IDX.with(|x| *x);
let out = target_dir.join(&format!("wasm32-unknown-unknown/debug/test{}.wasm", idx));
let as_a_module = root.join("out.wasm");
fs::copy(&out, &as_a_module).unwrap();
let res = cli::Bindgen::new()
.input_path(&as_a_module)
.typescript(true)
.nodejs(self.node)
.debug(self.debug)
.generate(&root);
if let Err(e) = res {
for e in e.causes() {
println!("- {}", e);
}
panic!("failed");
}
}
fn read_js(&self) -> String {
let path = root().join("out.js");
println!("js, {:?}", &path);
fs::read_to_string(path).expect("Unable to read js")
}
}
#[cfg(unix)]
fn symlink_dir(a: &Path, b: &Path) -> io::Result<()> {
use std::os::unix::fs::symlink;
symlink(a, b)
}
#[cfg(windows)]
fn symlink_dir(a: &Path, b: &Path) -> io::Result<()> {
use std::os::windows::fs::symlink_dir;
symlink_dir(a, b)
}
fn run(cmd: &mut Command, program: &str) {
println!("···················································");
println!("running {:?}", cmd);
let start = Instant::now();
let output = match cmd.output() {
Ok(output) => output,
Err(err) => panic!("failed to spawn `{}`: {}", program, err),
};
println!("exit: {}", output.status);
let dur = start.elapsed();
println!(
"dur: {}.{:03}ms",
dur.as_secs(),
dur.subsec_nanos() / 1_000_000
);
if output.stdout.len() > 0 {
println!("stdout ---\n{}", String::from_utf8_lossy(&output.stdout));
}
if output.stderr.len() > 0 {
println!("stderr ---\n{}", String::from_utf8_lossy(&output.stderr));
}
assert!(output.status.success());
}
use project_builder::{project, run};
mod api;
mod char;
@ -559,6 +21,7 @@ mod non_wasm;
mod simple;
mod slice;
mod structural;
mod typescript;
mod u64;
mod validate_prt;
mod webidl;

View File

@ -69,7 +69,7 @@ fn auto_bind_math() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import { math } from "./out";

View File

@ -3,7 +3,8 @@ use super::project;
#[test]
fn works() {
project()
.node(true)
.debug(false)
.nodejs_experimental_modules(false)
.file(
"src/lib.rs",
r#"
@ -125,6 +126,7 @@ fn works() {
module.exports.hit = function() {
called = true;
};
module.exports.FOO = 1.0;
const { math, run, Foo, Color, cycle } = require('./out');
@ -153,7 +155,6 @@ fn works() {
math(1.0, 2.0);
};
"#,
)
.test();

View File

@ -31,13 +31,13 @@ fn works() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
let sym = (Symbol as any)('a');
let sym = Symbol('a');
assert.strictEqual(wasm.clone(sym), sym);
let a = wasm.A.new();
a.free();

View File

@ -42,7 +42,7 @@ fn add() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -59,6 +59,39 @@ fn add() {
.test();
}
#[test]
fn add_headless() {
project()
.headless(true)
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: u32, b: u32) -> u32 {
a + b
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
console.log("start `add_headless` test");
assert.strictEqual(wasm.add(1, 2), 3);
console.log("end `add_headless` test");
}
"#,
)
.test();
}
#[test]
fn string_arguments() {
project()
@ -84,7 +117,7 @@ fn string_arguments() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out";
@ -121,7 +154,7 @@ fn return_a_string() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
@ -168,12 +201,6 @@ fn exceptions() {
}
"#,
)
.file(
"test.d.ts",
r#"
export function test(): void;
"#,
)
.test();
}
@ -197,7 +224,7 @@ fn exceptions() {
// }
// }
// "#)
// .file("test.ts", r#"
// .file("test.js", r#"
// import * as assert from "assert";
// import * as wasm from "./out";
//
@ -223,7 +250,7 @@ fn other_exports() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out_bg";
@ -267,7 +294,7 @@ fn no_std() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out_bg";
@ -329,7 +356,7 @@ fn no_std_class() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as wasm from "./out_bg";

View File

@ -29,12 +29,12 @@ fn export() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
function assert_arrays_equal(a: any, b: any) {
function assert_arrays_equal(a, b) {
console.log(a, b);
assert.strictEqual(a.length, b.length);
assert.strictEqual(a.byteLength, b.byteLength);
@ -129,68 +129,68 @@ fn import() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function js_i8(a: any): any {
export function js_i8(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
export function js_u8(a: any): any {
export function js_u8(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
export function js_i16(a: any): any {
export function js_i16(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
export function js_u16(a: any): any {
export function js_u16(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
export function js_i32(a: any): any {
export function js_i32(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
export function js_u32(a: any): any {
export function js_u32(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
export function js_f32(a: any): any {
export function js_f32(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
export function js_f64(a: any): any {
export function js_f64(a) {
assert.strictEqual(a.length, 2);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
return a;
}
function assert_arrays_equal(a: any, b: any) {
function assert_arrays_equal(a, b) {
console.log(a, b);
assert.strictEqual(a.length, b.length);
assert.strictEqual(a.byteLength, b.byteLength);
@ -280,9 +280,9 @@ fn pass_array_works() {
.file(
"test.js",
r#"
const wasm = require("./out");
import * as wasm from "./out";
module.exports.test = function() {
export function test() {
wasm.rust_i8([1, 2]);
wasm.rust_u8([1, 2]);
wasm.rust_i16([1, 2]);
@ -291,7 +291,7 @@ fn pass_array_works() {
wasm.rust_u32([1, 2]);
wasm.rust_f32([1, 2]);
wasm.rust_f64([1, 2]);
};
}
"#,
)
.test();
@ -351,12 +351,12 @@ fn import_mut() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
function foo(a: any) {
function foo(a) {
assert.strictEqual(a.length, 3);
assert.strictEqual(a[0], 1);
assert.strictEqual(a[1], 2);
@ -412,12 +412,12 @@ fn export_mut() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
function run(a: any, rust: any) {
function run(a, rust) {
assert.strictEqual(a.length, 3);
a[0] = 1;
a[1] = 2;
@ -496,7 +496,7 @@ fn return_vec_ok() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

View File

@ -33,7 +33,7 @@ fn works() {
"#,
)
.file(
"test.ts",
"test.js",
r#"
import * as assert from "assert";
import { run } from "./out";

79
tests/all/typescript.rs Normal file
View File

@ -0,0 +1,79 @@
use super::project;
#[test]
fn works() {
project()
.webpack(true)
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn foo() {}
#[wasm_bindgen]
pub fn bar(a: &str, b: u32) -> String {
format!("{} {}", a, b)
}
#[wasm_bindgen]
pub fn thunk(a: &JsValue) {
drop(a);
}
#[wasm_bindgen]
pub struct A {
}
#[wasm_bindgen]
impl A {
#[wasm_bindgen(constructor)]
pub fn new() -> A {
A {}
}
pub fn new2() -> A {
A {}
}
pub fn foo(&self) {}
pub fn bar(&self, _a: u32) {}
pub fn baz(&self, _d: &A) {}
}
"#,
)
.file(
"test.ts",
r#"
import * as assert from 'assert';
import { foo, bar, A, thunk } from './out';
import { memory } from './out_bg';
export function test() {
foo();
assert.strictEqual(bar('a', 3), 'a 3');
const x = new A();
x.foo();
x.free();
const y = A.new2();
y.foo();
y.bar(2);
y.baz(y);
y.free();
thunk(memory);
};
"#,
)
.test();
}

View File

@ -14,13 +14,13 @@ fn method() {
"#,
)
.file(
"foo.ts",
"foo.js",
r#"
export class Foo {
constructor(private value: number) {
constructor(value) {
this.value = value;
}
myCmp(other: Foo): boolean {
myCmp(other) {
return this.value === other.value;
}
}
@ -73,19 +73,19 @@ fn property() {
"#,
)
.file(
"foo.ts",
"foo.js",
r#"
export class Foo {
constructor(private _value: number) {
this._value = _value;
constructor(value) {
this._value = value;
}
get value(): number {
get value() {
return this._value;
}
set value(_value: number) {
this._value = _value;
set value(value) {
this._value = value;
}
}
"#,
@ -132,17 +132,20 @@ fn named_constructor() {
)
.file(
// Not a perfect test, but it gets the job done.
"foo.ts",
"foo.js",
r#"
export class Foo {
protected _value: number = 0;
get value(): number {
constructor() {
this._value = 0;
}
get value(){
return this._value;
}
}
export class Bar extends Foo {
constructor(_value: number) {
constructor(_value) {
super();
this._value = _value;
}
@ -185,16 +188,17 @@ fn static_method() {
"#,
)
.file(
"foo.ts",
"foo.js",
r#"
export class Foo {
private static value: number = 0;
static swap(value: number): number {
static swap(value) {
const res = Foo.value;
Foo.value = value;
return res;
}
}
Foo.value = 0;
"#,
)
.file(
@ -235,19 +239,19 @@ fn static_property() {
"#,
)
.file(
"foo.ts",
"foo.js",
r#"
export class Foo {
private static _value: number = 0;
static get value(): number {
static get value(){
return Foo._value;
}
static set value(_value: number) {
Foo._value = _value;
static set value(value) {
Foo._value = value;
}
}
Foo._value = 0;
"#,
)
.file(