Merge branch 'master' of git://github.com/rustwasm/wasm-bindgen

This commit is contained in:
Frazer McLean 2018-08-20 21:55:42 +02:00
commit 7432f5ff5c
114 changed files with 893 additions and 315 deletions

View File

@ -56,6 +56,7 @@ matrix:
- cargo test
# Run the main body of the test suite
- cargo test --target wasm32-unknown-unknown
- cargo test --target wasm32-unknown-unknown --features nightly
# Rerun the test suite but disable `--debug` in generated JS
- WASM_BINDGEN_NO_DEBUG=1 cargo test --target wasm32-unknown-unknown
# Make sure our serde tests work

View File

@ -21,6 +21,7 @@ default = ["spans", "std"]
spans = ["wasm-bindgen-macro/spans"]
std = []
serde-serialize = ["serde", "serde_json", "std"]
nightly = []
# This is only for debugging wasm-bindgen! No stability guarantees, so enable
# this at your own peril!
@ -56,6 +57,7 @@ members = [
"examples/comments",
"examples/console_log",
"examples/dom",
"examples/fetch",
"examples/guide-supported-types-examples",
"examples/hello_world",
"examples/import_js",

View File

@ -13,8 +13,6 @@
Import JavaScript things into Rust and export Rust things to JavaScript.
```rust
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -490,6 +490,39 @@ impl<'a> Context<'a> {
let mut dst = format!("class {} {{\n", name);
let mut ts_dst = format!("export {}", dst);
let (mkweakref, freeref) = if self.config.weak_refs {
// When weak refs are enabled we use them to automatically free the
// contents of an exported rust class when it's gc'd. Note that a
// manual `free` function still exists for deterministic
// destruction.
//
// This is implemented by using a `WeakRefGroup` to run finalizers
// for all `WeakRef` objects that it creates. Upon construction of
// a new wasm object we use `makeRef` with "holdings" of a thunk to
// free the wasm instance. Once the `this` (the instance we're
// creating) is gc'd then the finalizer will run with the
// `WeakRef`, and we'll pull out the `holdings`, our pointer.
//
// Note, though, that if manual finalization happens we want to
// cancel the `WeakRef`-generated finalization, so we retain the
// `WeakRef` in a global map. This global map is then used to
// `drop()` the `WeakRef` (cancel finalization) whenever it is
// finalized.
self.expose_cleanup_groups();
let mk = format!("
const cleanup_ptr = this.ptr;
const ref = CLEANUPS.makeRef(this, () => free{}(cleanup_ptr));
CLEANUPS_MAP.set(this.ptr, ref);
", name);
let free = "
CLEANUPS_MAP.get(ptr).drop();
CLEANUPS_MAP.delete(ptr);
";
(mk, free)
} else {
(String::new(), "")
};
if self.config.debug || class.constructor.is_some() {
self.expose_constructor_token();
@ -516,9 +549,11 @@ impl<'a> Context<'a> {
// This invocation of new will call this constructor with a ConstructorToken
let instance = {class}.{constructor}(...args);
this.ptr = instance.ptr;
{mkweakref}
",
class = name,
constructor = constructor
constructor = constructor,
mkweakref = mkweakref,
));
} else {
dst.push_str(
@ -537,9 +572,11 @@ impl<'a> Context<'a> {
constructor(ptr) {{
this.ptr = ptr;
{}
}}
",
name
name,
mkweakref,
));
}
@ -599,16 +636,29 @@ impl<'a> Context<'a> {
}
}
dst.push_str(&format!(
self.global(&format!(
"
free() {{
const ptr = this.ptr;
this.ptr = 0;
function free{}(ptr) {{
{}
wasm.{}(ptr);
}}
",
name,
freeref,
shared::free_function(&name)
));
dst.push_str(&format!(
"
free() {{
if (this.ptr === 0)
return;
const ptr = this.ptr;
this.ptr = 0;
free{}(this.ptr);
}}
",
name,
));
ts_dst.push_str("free(): void;\n");
dst.push_str(&class.contents);
ts_dst.push_str(&class.typescript);
@ -1594,6 +1644,18 @@ impl<'a> Context<'a> {
");
}
fn expose_cleanup_groups(&mut self) {
if !self.exposed_globals.insert("cleanup_groups") {
return
}
self.global(
"
const CLEANUPS = new WeakRefGroup(x => x.holdings());
const CLEANUPS_MAP = new Map();
"
);
}
fn gc(&mut self) -> Result<(), Error> {
let module = mem::replace(self.module, Module::default());
let module = module.parse_names().unwrap_or_else(|p| p.1);

View File

@ -10,6 +10,7 @@ extern crate failure;
use std::any::Any;
use std::collections::BTreeSet;
use std::env;
use std::fmt;
use std::fs;
use std::mem;
@ -33,6 +34,9 @@ pub struct Bindgen {
typescript: bool,
demangle: bool,
keep_debug: bool,
// Experimental support for `WeakRefGroup`, an upcoming ECMAScript feature.
// Currently only enable-able through an env var.
weak_refs: bool,
}
enum Input {
@ -55,6 +59,7 @@ impl Bindgen {
typescript: false,
demangle: true,
keep_debug: false,
weak_refs: env::var("WASM_BINDGEN_WEAKREF").is_ok(),
}
}

View File

@ -33,8 +33,6 @@
//! `Promise`.
//!
//! ```rust,no_run
//! #![feature(use_extern_macros)]
//!
//! extern crate futures;
//! extern crate js_sys;
//! extern crate wasm_bindgen;
@ -104,7 +102,6 @@
//! ```
#![deny(missing_docs)]
#![feature(use_extern_macros)]
extern crate futures;
extern crate wasm_bindgen;

View File

@ -1,4 +1,3 @@
#![feature(use_extern_macros)]
#![cfg(target_arch = "wasm32")]
extern crate futures;

View File

@ -17,7 +17,6 @@
//! bindings.
#![doc(html_root_url = "https://docs.rs/js-sys/0.2")]
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
@ -885,6 +884,7 @@ impl Function {
// Generator
#[wasm_bindgen]
extern {
#[wasm_bindgen(extends = Object)]
#[derive(Clone, Debug)]
pub type Generator;
@ -2092,7 +2092,7 @@ extern {
/// or range of allowed values.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError
#[wasm_bindgen(extends = Error)]
#[wasm_bindgen(extends = Error, extends = Object)]
#[derive(Clone, Debug)]
pub type RangeError;
@ -2111,7 +2111,7 @@ extern {
/// variable is referenced.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
#[wasm_bindgen(extends = Error)]
#[wasm_bindgen(extends = Error, extends = Object)]
#[derive(Clone, Debug)]
pub type ReferenceError;
@ -2505,7 +2505,7 @@ extern {
/// parsing code.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError
#[wasm_bindgen(extends = Error)]
#[wasm_bindgen(extends = Error, extends = Object)]
#[derive(Clone, Debug)]
pub type SyntaxError;
@ -2525,7 +2525,7 @@ extern {
/// expected type.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
#[wasm_bindgen(extends = Error)]
#[wasm_bindgen(extends = Error, extends = Object)]
#[derive(Clone, Debug)]
pub type TypeError;
@ -2758,7 +2758,7 @@ extern {
/// function was used in a wrong way.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError
#[wasm_bindgen(extends = Error, js_name = URIError)]
#[wasm_bindgen(extends = Error, extends = Object, js_name = URIError)]
#[derive(Clone, Debug)]
pub type UriError;
@ -3117,6 +3117,38 @@ extern "C" {
#[wasm_bindgen(static_method_of = JsString, js_class = "String", js_name = fromCharCode)]
pub fn from_char_code5(a: u32, b: u32, c: u32, d: u32, e: u32) -> JsString;
/// The static String.fromCodePoint() method returns a string created by
/// using the specified sequence of code points.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
///
/// # Exceptions
///
/// A RangeError is thrown if an invalid Unicode code point is given
///
/// # Notes
///
/// There are a few bindings to `from_code_point` in `js-sys`: `from_code_point1`, `from_code_point2`, etc...
/// with different arities.
#[wasm_bindgen(catch, static_method_of = JsString, js_class = "String", js_name = fromCodePoint)]
pub fn from_code_point1(a: u32) -> Result<JsString, JsValue>;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
#[wasm_bindgen(catch, static_method_of = JsString, js_class = "String", js_name = fromCodePoint)]
pub fn from_code_point2(a: u32, b: u32) -> Result<JsString, JsValue>;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
#[wasm_bindgen(catch, static_method_of = JsString, js_class = "String", js_name = fromCodePoint)]
pub fn from_code_point3(a: u32, b: u32, c: u32) -> Result<JsString, JsValue>;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
#[wasm_bindgen(catch, static_method_of = JsString, js_class = "String", js_name = fromCodePoint)]
pub fn from_code_point4(a: u32, b: u32, c: u32, d: u32) -> Result<JsString, JsValue>;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
#[wasm_bindgen(catch, static_method_of = JsString, js_class = "String", js_name = fromCodePoint)]
pub fn from_code_point5(a: u32, b: u32, c: u32, d: u32, e: u32) -> Result<JsString, JsValue>;
/// The `includes()` method determines whether one string may be found
/// within another string, returning true or false as appropriate.
///
@ -3140,6 +3172,20 @@ extern "C" {
#[wasm_bindgen(method, js_class = "String", js_name = lastIndexOf)]
pub fn last_index_of(this: &JsString, search_value: &str, from_index: i32) -> i32;
/// The localeCompare() method returns a number indicating whether
/// a reference string comes before or after or is the same as
/// the given string in sort order.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
#[wasm_bindgen(method, js_class = "String", js_name = localeCompare)]
pub fn locale_compare(this: &JsString, compare_string: &str, locales: &Array, options: &Object) -> i32;
/// The match() method retrieves the matches when matching a string against a regular expression.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
#[wasm_bindgen(method, js_class = "String", js_name = match)]
pub fn match_(this: &JsString, pattern: &RegExp) -> Option<Object>;
/// The normalize() method returns the Unicode Normalization Form
/// of a given string (if the value isn't a string, it will be converted to one first).
///
@ -3172,6 +3218,34 @@ extern "C" {
#[wasm_bindgen(method, js_class = "String")]
pub fn repeat(this: &JsString, count: i32) -> JsString;
/// The replace() method returns a new string with some or all matches of a pattern
/// replaced by a replacement. The pattern can be a string or a RegExp, and
/// the replacement can be a string or a function to be called for each match.
///
/// Note: The original string will remain unchanged.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
#[wasm_bindgen(method, js_class = "String")]
pub fn replace(this: &JsString, pattern: &str, replacement: &str) -> JsString;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
#[wasm_bindgen(method, js_class = "String", js_name = replace)]
pub fn replace_with_function(this: &JsString, pattern: &str, replacement: &Function) -> JsString;
#[wasm_bindgen(method, js_class = "String", js_name = replace)]
pub fn replace_by_pattern(this: &JsString, pattern: &RegExp, replacement: &str) -> JsString;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
#[wasm_bindgen(method, js_class = "String", js_name = replace)]
pub fn replace_by_pattern_with_function(this: &JsString, pattern: &RegExp, replacement: &Function) -> JsString;
/// The search() method executes a search for a match between
/// a regular expression and this String object.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
#[wasm_bindgen(method, js_class = "String")]
pub fn search(this: &JsString, pattern: &RegExp) -> i32;
/// The `slice()` method extracts a section of a string and returns it as a
/// new string, without modifying the original string.
///
@ -3179,6 +3253,25 @@ extern "C" {
#[wasm_bindgen(method, js_class = "String")]
pub fn slice(this: &JsString, start: u32, end: u32) -> JsString;
/// The split() method splits a String object into an array of strings by separating the string
/// into substrings, using a specified separator string to determine where to make each split.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
#[wasm_bindgen(method, js_class = "String")]
pub fn split(this: &JsString, separator: &str) -> Array;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
#[wasm_bindgen(method, js_class = "String", js_name = split)]
pub fn split_limit(this: &JsString, separator: &str, limit: u32) -> Array;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
#[wasm_bindgen(method, js_class = "String", js_name = split)]
pub fn split_by_pattern(this: &JsString, pattern: &RegExp) -> Array;
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
#[wasm_bindgen(method, js_class = "String", js_name = split)]
pub fn split_by_pattern_limit(this: &JsString, pattern: &RegExp, limit: u32) -> Array;
/// The `startsWith()` method determines whether a string begins with the
/// characters of a specified string, returning true or false as
/// appropriate.
@ -3206,14 +3299,14 @@ extern "C" {
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase
#[wasm_bindgen(method, js_class = "String", js_name = toLocaleLowerCase)]
pub fn to_locale_lower_case(this: &JsString, local: Option<&str>) -> JsString;
pub fn to_locale_lower_case(this: &JsString, locale: Option<&str>) -> JsString;
/// The toLocaleUpperCase() method returns the calling string value converted to upper case,
/// according to any locale-specific case mappings.
///
/// https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase
#[wasm_bindgen(method, js_class = "String", js_name = toLocaleUpperCase)]
pub fn to_locale_upper_case(this: &JsString, local: Option<&str>) -> JsString;
pub fn to_locale_upper_case(this: &JsString, locale: Option<&str>) -> JsString;
/// The `toLowerCase()` method returns the calling string value
/// converted to lower case.
@ -3502,7 +3595,7 @@ pub mod Intl {
/// that enable language sensitive string comparison.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator
#[wasm_bindgen(js_namespace = Intl)]
#[wasm_bindgen(extends = Object, js_namespace = Intl)]
#[derive(Clone, Debug)]
pub type Collator;
@ -3546,7 +3639,7 @@ pub mod Intl {
/// that enable language-sensitive date and time formatting.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
#[wasm_bindgen(js_namespace = Intl)]
#[wasm_bindgen(extends = Object, js_namespace = Intl)]
#[derive(Clone, Debug)]
pub type DateTimeFormat;
@ -3597,7 +3690,7 @@ pub mod Intl {
/// that enable language sensitive number formatting.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
#[wasm_bindgen(js_namespace = Intl)]
#[wasm_bindgen(extends = Object, js_namespace = Intl)]
#[derive(Clone, Debug)]
pub type NumberFormat;
@ -3647,7 +3740,7 @@ pub mod Intl {
/// that enable plural sensitive formatting and plural language rules.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/PluralRules
#[wasm_bindgen(js_namespace = Intl)]
#[wasm_bindgen(extends = Object, js_namespace = Intl)]
#[derive(Clone, Debug)]
pub type PluralRules;

View File

@ -1,4 +1,3 @@
#![feature(use_extern_macros)]
#![cfg(target_arch = "wasm32")]
extern crate wasm_bindgen_test;

View File

@ -306,4 +306,5 @@ fn array_inheritance() {
let array = Array::new();
assert!(array.is_instance_of::<Array>());
assert!(array.is_instance_of::<Object>());
let _: &Object = array.as_ref();
}

View File

@ -41,4 +41,5 @@ fn arraybuffer_inheritance() {
let buf = ArrayBuffer::new(4);
assert!(buf.is_instance_of::<ArrayBuffer>());
assert!(buf.is_instance_of::<Object>());
let _: &Object = buf.as_ref();
}

View File

@ -18,4 +18,5 @@ fn boolean_inheritance() {
let b = Boolean::new(&JsValue::from(true));
assert!(b.is_instance_of::<Boolean>());
assert!(b.is_instance_of::<Object>());
let _: &Object = b.as_ref();
}

View File

@ -1,7 +1,7 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
use wasm_bindgen::JsCast;
use js_sys::*;
#[wasm_bindgen_test]
fn test() {
@ -36,7 +36,9 @@ fn test() {
v.set_int8(0, 42);
// TODO: figure out how to do `bytes[2]`
bytes.subarray(2, 3).for_each(&mut |x, _, _| assert_eq!(x, 42));
bytes
.subarray(2, 3)
.for_each(&mut |x, _, _| assert_eq!(x, 42));
}
#[wasm_bindgen_test]
@ -50,4 +52,5 @@ fn dataview_inheritance() {
assert!(v.is_instance_of::<DataView>());
assert!(v.is_instance_of::<Object>());
let _: &Object = v.as_ref();
}

View File

@ -413,4 +413,5 @@ fn date_inheritance() {
let date = Date::new(&"August 19, 1975 23:15:30".into());
assert!(date.is_instance_of::<Date>());
assert!(date.is_instance_of::<Object>());
let _: &Object = date.as_ref();
}

View File

@ -42,4 +42,5 @@ fn error_inheritance() {
let error = Error::new("test");
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Object = error.as_ref();
}

View File

@ -52,4 +52,6 @@ fn evalerror_inheritance() {
assert!(error.is_instance_of::<EvalError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
}

View File

@ -66,4 +66,5 @@ fn to_string() {
fn function_inheritance() {
assert!(MAX.is_instance_of::<Function>());
assert!(MAX.is_instance_of::<Object>());
let _: &Object = MAX.as_ref();
}

View File

@ -1,5 +1,6 @@
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
use wasm_bindgen::JsCast;
use js_sys::*;
#[wasm_bindgen(module = "tests/wasm/Generator.js")]
@ -56,3 +57,10 @@ fn throw() {
assert!(next.value().is_undefined());
assert!(next.done());
}
#[wasm_bindgen_test]
fn generator_inheritance() {
let gen = dummy_generator();
assert!(gen.is_instance_of::<Object>());
}

View File

@ -37,6 +37,17 @@ fn collator() {
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn collator_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let c = Intl::Collator::new(&locales, &opts);
assert!(c.is_instance_of::<Intl::Collator>());
assert!(c.is_instance_of::<Object>());
let _: &Object = c.as_ref();
}
#[wasm_bindgen_test]
fn date_time_format() {
let locales = Array::of1(&JsValue::from("en-US"));
@ -52,6 +63,17 @@ fn date_time_format() {
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn date_time_format_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let c = Intl::DateTimeFormat::new(&locales, &opts);
assert!(c.is_instance_of::<Intl::DateTimeFormat>());
assert!(c.is_instance_of::<Object>());
let _: &Object = c.as_ref();
}
#[wasm_bindgen_test]
fn number_format() {
let locales = Array::of1(&JsValue::from("en-US"));
@ -66,6 +88,17 @@ fn number_format() {
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn number_format_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let n = Intl::NumberFormat::new(&locales, &opts);
assert!(n.is_instance_of::<Intl::NumberFormat>());
assert!(n.is_instance_of::<Object>());
let _: &Object = n.as_ref();
}
#[wasm_bindgen_test]
fn plural_rules() {
let locales = Array::of1(&JsValue::from("en-US"));
@ -75,6 +108,17 @@ fn plural_rules() {
assert!(r.resolved_options().is_instance_of::<Object>());
assert_eq!(r.select(1_f64), "one");
let r = Intl::PluralRules::supported_locales_of(&locales, &opts);
assert!(r.is_instance_of::<Array>());
let a = Intl::PluralRules::supported_locales_of(&locales, &opts);
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn plural_rules_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let r = Intl::PluralRules::new(&locales, &opts);
assert!(r.is_instance_of::<Intl::PluralRules>());
assert!(r.is_instance_of::<Object>());
let _: &Object = r.as_ref();
}

View File

@ -1 +1,7 @@
exports.new_string_object = () => new String("hi");
exports.new_string_object = () => new String("hi");
exports.get_replacer_function = function() {
return function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? '-' : '') + match.toLowerCase();
};
};

View File

@ -7,6 +7,7 @@ use js_sys::*;
#[wasm_bindgen(module = "tests/wasm/JsString.js")]
extern {
fn new_string_object() -> JsValue;
fn get_replacer_function() -> Function;
}
#[wasm_bindgen_test]
@ -85,6 +86,23 @@ fn from_char_code() {
assert_eq!(JsString::from_char_code4(codes[0], codes[1], codes[2], codes[3]), "½+¾=");
}
#[wasm_bindgen_test]
fn from_code_point() {
let s = "☃★♲你";
let codes : Vec<u32> = s.chars()
.map(|char| char as u32)
.collect();
assert_eq!(JsString::from_code_point1(codes[0]).unwrap(), "");
assert_eq!(JsString::from_code_point2(codes[0], codes[1]).unwrap(), "☃★");
assert_eq!(JsString::from_code_point3(codes[0], codes[1], codes[2]).unwrap(), "☃★♲");
assert_eq!(JsString::from_code_point4(codes[0], codes[1], codes[2], codes[3]).unwrap(), "☃★♲你");
assert!(!JsString::from_code_point1(0x10FFFF).is_err());
assert!(JsString::from_code_point1(0x110000).is_err());
assert!(JsString::from_code_point1(u32::max_value()).is_err());
}
#[wasm_bindgen_test]
fn includes() {
let str = JsString::from("Blue Whale");
@ -135,6 +153,95 @@ fn last_index_of() {
assert_eq!(js.last_index_of("", 2), 2);
}
#[wasm_bindgen_test]
fn locale_compare() {
let a = "résumé";
let b = "RESUME";
let js_a = JsString::from(a);
let js_b = JsString::from(b);
let locales = Array::new();
let options = Object::new();
assert_eq!(js_a.locale_compare(a, &locales, &options), 0);
assert_eq!(js_b.locale_compare(b, &locales, &options), 0);
assert!(js_a.locale_compare(b, &locales, &options) > 0);
assert!(js_b.locale_compare(a, &locales, &options) < 0);
locales.push(&"en".into());
Reflect::set(options.as_ref(), &"sensitivity".into(), &"base".into());
assert_eq!(js_a.locale_compare(a, &locales, &options), 0);
assert_eq!(js_a.locale_compare(b, &locales, &options), 0);
assert_eq!(js_b.locale_compare(a, &locales, &options), 0);
assert_eq!(js_b.locale_compare(b, &locales, &options), 0);
let a = "ä";
let z = "z";
let js_a = JsString::from(a);
let js_z = JsString::from(z);
let locales_de = Array::of1(&"de".into());
let locales_sv = Array::of1(&"sv".into());
let options = Object::new();
assert_eq!(js_a.locale_compare(a, &locales_de, &options), 0);
assert_eq!(js_z.locale_compare(z, &locales_de, &options), 0);
assert!(js_a.locale_compare(z, &locales_de, &options) < 0);
assert!(js_z.locale_compare(a, &locales_de, &options) > 0);
assert_eq!(js_a.locale_compare(a, &locales_sv, &options), 0);
assert_eq!(js_z.locale_compare(z, &locales_sv, &options), 0);
assert!(js_a.locale_compare(z, &locales_sv, &options) < 0);
assert!(js_z.locale_compare(a, &locales_sv, &options) > 0);
let two = "2";
let ten = "10";
let js_two = JsString::from(two);
let js_ten = JsString::from(ten);
let locales = Array::new();
let options = Object::new();
assert_eq!(js_two.locale_compare(two, &locales, &options), 0);
assert_eq!(js_ten.locale_compare(ten, &locales, &options), 0);
assert!(js_two.locale_compare(ten, &locales, &options) > 0);
assert!(js_ten.locale_compare(two, &locales, &options) < 0);
locales.push(&"en-u-kn-true".into());
assert!(js_two.locale_compare(ten, &locales, &options) < 0);
assert!(js_ten.locale_compare(two, &locales, &options) > 0);
let locales = Array::new();
Reflect::set(options.as_ref(), &"numeric".into(), &JsValue::TRUE);
assert!(js_two.locale_compare(ten, &locales, &options) < 0);
assert!(js_ten.locale_compare(two, &locales, &options) > 0);
}
#[wasm_bindgen_test]
fn match_() {
let s = "The quick brown fox jumped over the lazy dog. It barked.";
let re = RegExp::new("[A-Z]", "g");
let result = JsString::from(s).match_(&re);
let obj = result.unwrap();
assert_eq!(Reflect::get(obj.as_ref(), &"0".into()), "T");
assert_eq!(Reflect::get(obj.as_ref(), &"1".into()), "I");
let result = JsString::from("foo").match_(&re);
assert!(result.is_none());
let s = "For more information, see Chapter 3.4.5.1";
let re = RegExp::new("see (chapter \\d+(\\.\\d)*)", "i");
let result = JsString::from(s).match_(&re);
let obj = result.unwrap();
assert_eq!(Reflect::get(obj.as_ref(), &"0".into()), "see Chapter 3.4.5.1");
assert_eq!(Reflect::get(obj.as_ref(), &"1".into()), "Chapter 3.4.5.1");
assert_eq!(Reflect::get(obj.as_ref(), &"2".into()), ".1");
assert_eq!(Reflect::get(obj.as_ref(), &"index".into()), 22);
assert_eq!(Reflect::get(obj.as_ref(), &"input".into()), s);
}
#[wasm_bindgen_test]
fn normalize() {
let js = JsString::from("\u{1E9B}\u{0323}");
@ -178,12 +285,106 @@ fn repeat() {
assert_eq!(JsString::from("test").repeat(3), "testtesttest");
}
#[wasm_bindgen_test]
fn replace() {
let js = JsString::from("The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?");
let result = js.replace("dog", "ferret");
assert_eq!(result, "The quick brown fox jumped over the lazy ferret. If the dog reacted, was it really lazy?");
let js = JsString::from("borderTop");
let result = js.replace_with_function("T", &get_replacer_function());
assert_eq!(result, "border-top");
let js = JsString::from("The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?");
let re = RegExp::new("dog", "g");
let result = js.replace_by_pattern(&re, "ferret");
assert_eq!(result, "The quick brown fox jumped over the lazy ferret. If the ferret reacted, was it really lazy?");
let js = JsString::from("borderTop");
let re = RegExp::new("[A-Z]", "g");
let result = js.replace_by_pattern_with_function(&re, &get_replacer_function());
assert_eq!(result, "border-top");
}
#[wasm_bindgen_test]
fn search() {
let js = JsString::from("The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?");
let re = RegExp::new("[^\\w\\s]", "g");
assert_eq!(js.search(&re), 44);
let js = JsString::from("hey JudE");
let re1 = RegExp::new("[A-Z]", "g");
let re2 = RegExp::new("[.]", "g");
assert_eq!(js.search(&re1), 4);
assert_eq!(js.search(&re2), -1);
}
#[wasm_bindgen_test]
fn slice() {
let characters = JsString::from("acxn18");
assert_eq!(characters.slice(1, 3), "cx");
}
#[wasm_bindgen_test]
fn split() {
let js = JsString::from("Oh brave new world");
let result = js.split(" ");
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(v[0], "Oh");
assert_eq!(v[1], "brave");
assert_eq!(v[2], "new");
assert_eq!(v[3], "world");
let js = JsString::from("Oct,Nov,Dec");
let result = js.split(",");
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(v[0], "Oct");
assert_eq!(v[1], "Nov");
assert_eq!(v[2], "Dec");
let result = js.split_limit(",", 2);
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(result.length(), 2);
assert_eq!(v[0], "Oct");
assert_eq!(v[1], "Nov");
let js = JsString::from("Oh brave new world");
let re = RegExp::new("\\s", "g");
let result = js.split_by_pattern(&re);
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(v[0], "Oh");
assert_eq!(v[1], "brave");
assert_eq!(v[2], "new");
assert_eq!(v[3], "world");
let result = js.split_by_pattern_limit(&re, 2);
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(result.length(), 2);
assert_eq!(v[0], "Oh");
assert_eq!(v[1], "brave");
}
#[wasm_bindgen_test]
fn starts_with() {
let js = JsString::from("To be, or not to be, that is the question.");

View File

@ -93,4 +93,5 @@ fn map_inheritance() {
let map = Map::new();
assert!(map.is_instance_of::<Map>());
assert!(map.is_instance_of::<Object>());
let _: &Object = map.as_ref();
}

View File

@ -111,4 +111,5 @@ fn number_inheritance() {
let n = Number::new(&JsValue::from(42));
assert!(n.is_instance_of::<Number>());
assert!(n.is_instance_of::<Object>());
let _: &Object = n.as_ref();
}

View File

@ -9,6 +9,8 @@ fn range_error() {
assert!(error.is_instance_of::<RangeError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "out of range yo");

View File

@ -9,6 +9,8 @@ fn reference_error() {
assert!(error.is_instance_of::<ReferenceError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "bad reference, fool");

View File

@ -7,6 +7,7 @@ fn regexp_inheritance() {
let re = RegExp::new(".", "");
assert!(re.is_instance_of::<RegExp>());
assert!(re.is_instance_of::<Object>());
let _: &Object = re.as_ref();
}
#[wasm_bindgen_test]

View File

@ -87,4 +87,5 @@ fn set_inheritance() {
let set = Set::new(&JsValue::undefined());
assert!(set.is_instance_of::<Set>());
assert!(set.is_instance_of::<Object>());
let _: &Object = set.as_ref();
}

View File

@ -9,6 +9,8 @@ fn syntax_error() {
assert!(error.is_instance_of::<SyntaxError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "msg");

View File

@ -9,6 +9,8 @@ fn type_error() {
assert!(error.is_instance_of::<TypeError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "msg");

View File

@ -9,6 +9,8 @@ fn uri_error() {
assert!(error.is_instance_of::<UriError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "msg");

View File

@ -57,4 +57,5 @@ fn weakmap_inheritance() {
let map = WeakMap::new();
assert!(map.is_instance_of::<WeakMap>());
assert!(map.is_instance_of::<Object>());
let _: &Object = map.as_ref();
}

View File

@ -47,4 +47,5 @@ fn weakset_inheritance() {
let set = WeakSet::new();
assert!(set.is_instance_of::<WeakSet>());
assert!(set.is_instance_of::<Object>());
let _: &Object = set.as_ref();
}

View File

@ -1,5 +1,4 @@
#![cfg(target_arch = "wasm32")]
#![feature(use_extern_macros)]
#![allow(non_snake_case)]
extern crate futures;

View File

@ -486,7 +486,7 @@ impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemFn
ast::ImportFunctionKind::Method { class, ty, kind }
} else if opts.constructor() {
let class = match wasm.ret {
let class = match js_ret {
Some(ref ty) => ty,
_ => bail_span!(self, "constructor returns must be bare types"),
};
@ -560,10 +560,12 @@ impl ConvertToAst<BindgenAttrs> for syn::ForeignItemType {
}
}
impl ConvertToAst<BindgenAttrs> for syn::ForeignItemStatic {
impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemStatic {
type Target = ast::ImportKind;
fn convert(self, opts: BindgenAttrs) -> Result<Self::Target, Diagnostic> {
fn convert(self, (opts, module): (BindgenAttrs, &'a Option<String>))
-> Result<Self::Target, Diagnostic>
{
if self.mutability.is_some() {
bail_span!(self.mutability, "cannot import mutable globals yet")
}
@ -571,11 +573,8 @@ impl ConvertToAst<BindgenAttrs> for syn::ForeignItemStatic {
let js_name = opts.js_name().unwrap_or(&default_name);
let shim = format!(
"__wbg_static_accessor_{}_{}",
js_name
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.collect::<String>(),
self.ident
self.ident,
ShortHash((&js_name, module, &self.ident)),
);
Ok(ast::ImportKind::Static(ast::ImportStatic {
ty: *self.ty,
@ -973,7 +972,7 @@ impl<'a> MacroParse<&'a BindgenAttrs> for syn::ForeignItem {
let kind = match self {
syn::ForeignItem::Fn(f) => f.convert((item_opts, &module))?,
syn::ForeignItem::Type(t) => t.convert(item_opts)?,
syn::ForeignItem::Static(s) => s.convert(item_opts)?,
syn::ForeignItem::Static(s) => s.convert((item_opts, &module))?,
_ => panic!("only foreign functions/types allowed for now"),
};

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,7 +1,7 @@
error: error parsing #[wasm_bindgen] attribute options: failed to parse anything
--> $DIR/attribute-fails-to-parse.rs:7:16
--> $DIR/attribute-fails-to-parse.rs:5:16
|
7 | #[wasm_bindgen(nonsense)]
5 | #[wasm_bindgen(nonsense)]
| ^^^^^^^^
error: aborting due to previous error

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,19 +1,19 @@
error: cannot return a borrowed ref with #[wasm_bindgen]
--> $DIR/bad-signatures.rs:8:17
--> $DIR/bad-signatures.rs:6:17
|
8 | pub fn foo() -> &u32 {}
6 | pub fn foo() -> &u32 {}
| ^^^^
error: unsupported pattern in #[wasm_bindgen] imported function
--> $DIR/bad-signatures.rs:12:12
--> $DIR/bad-signatures.rs:10:12
|
12 | fn foo(Foo(x): Foo);
10 | fn foo(Foo(x): Foo);
| ^^^^^^
error: cannot return references in #[wasm_bindgen] imports yet
--> $DIR/bad-signatures.rs:14:17
--> $DIR/bad-signatures.rs:12:17
|
14 | fn foo() -> &u32;
12 | fn foo() -> &u32;
| ^^^^
error: aborting due to 3 previous errors

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,19 +1,19 @@
error: error parsing #[wasm_bindgen] attribute options: failed to parse anything
--> $DIR/invalid-attr.rs:7:16
--> $DIR/invalid-attr.rs:5:16
|
7 | #[wasm_bindgen(x)]
5 | #[wasm_bindgen(x)]
| ^
error: error parsing #[wasm_bindgen] attribute options: failed to parse anything
--> $DIR/invalid-attr.rs:12:20
--> $DIR/invalid-attr.rs:10:20
|
12 | #[wasm_bindgen(y)]
10 | #[wasm_bindgen(y)]
| ^
error: malformed #[wasm_bindgen] attribute
--> $DIR/invalid-attr.rs:15:5
--> $DIR/invalid-attr.rs:13:5
|
15 | #[wasm_bindgen { }]
13 | #[wasm_bindgen { }]
| ^^^^^^^^^^^^^^^^^^^^
error: aborting due to 3 previous errors

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,25 +1,25 @@
error: only public enums are allowed with #[wasm_bindgen]
--> $DIR/invalid-enums.rs:8:1
--> $DIR/invalid-enums.rs:6:1
|
8 | enum A {}
6 | enum A {}
| ^^^^^^^^^
error: only C-Style enums allowed with #[wasm_bindgen]
--> $DIR/invalid-enums.rs:12:6
--> $DIR/invalid-enums.rs:10:6
|
12 | D(u32),
10 | D(u32),
| ^^^^^
error: enums with #[wasm_bidngen] may only have number literal values
--> $DIR/invalid-enums.rs:17:9
--> $DIR/invalid-enums.rs:15:9
|
17 | X = 1 + 3,
15 | X = 1 + 3,
| ^^^^^
error: enums with #[wasm_bindgen] can only support numbers that can be represented as u32
--> $DIR/invalid-enums.rs:22:9
--> $DIR/invalid-enums.rs:20:9
|
22 | X = 4294967296,
20 | X = 4294967296,
| ^^^^^^^^^^
error: aborting due to 4 previous errors

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,91 +1,91 @@
error: it is currently not sound to use lifetimes in function signatures
--> $DIR/invalid-imports.rs:11:16
|
11 | fn f() -> &'static u32;
| ^^^^^^^
--> $DIR/invalid-imports.rs:9:16
|
9 | fn f() -> &'static u32;
| ^^^^^^^
error: imported methods must have at least one argument
--> $DIR/invalid-imports.rs:14:5
--> $DIR/invalid-imports.rs:12:5
|
14 | fn f1();
12 | fn f1();
| ^^^^^^^^
error: first argument of method must be a shared reference
--> $DIR/invalid-imports.rs:16:14
--> $DIR/invalid-imports.rs:14:14
|
16 | fn f2(x: u32);
14 | fn f2(x: u32);
| ^^^
error: first argument of method must be a path
--> $DIR/invalid-imports.rs:18:14
--> $DIR/invalid-imports.rs:16:14
|
18 | fn f3(x: &&u32);
16 | fn f3(x: &&u32);
| ^^^^^
error: multi-segment paths are not supported yet
--> $DIR/invalid-imports.rs:20:15
--> $DIR/invalid-imports.rs:18:15
|
20 | fn f4(x: &foo::Bar);
18 | fn f4(x: &foo::Bar);
| ^^^^^^^^
error: global paths are not supported yet
--> $DIR/invalid-imports.rs:20:15
|
20 | fn f4(x: &::Bar);
| ^^^^^
error: paths with type parameters are not supported yet
--> $DIR/invalid-imports.rs:22:15
|
22 | fn f4(x: &::Bar);
| ^^^^^
22 | fn f4(x: &Bar<T>);
| ^^^^^^
error: paths with type parameters are not supported yet
--> $DIR/invalid-imports.rs:24:15
|
24 | fn f4(x: &Bar<T>);
| ^^^^^^
error: paths with type parameters are not supported yet
--> $DIR/invalid-imports.rs:26:15
|
26 | fn f4(x: &Fn(T));
24 | fn f4(x: &Fn(T));
| ^^^^^
error: constructor returns must be bare types
--> $DIR/invalid-imports.rs:29:5
--> $DIR/invalid-imports.rs:27:5
|
29 | fn f();
27 | fn f();
| ^^^^^^^
error: global paths are not supported yet
--> $DIR/invalid-imports.rs:31:15
--> $DIR/invalid-imports.rs:29:15
|
31 | fn f() -> ::Bar;
29 | fn f() -> ::Bar;
| ^^^^^
error: return value of constructor must be a bare path
--> $DIR/invalid-imports.rs:33:5
--> $DIR/invalid-imports.rs:31:5
|
33 | fn f() -> &Bar;
31 | fn f() -> &Bar;
| ^^^^^^^^^^^^^^^
error: must be Result<...>
--> $DIR/invalid-imports.rs:34:15
|
34 | fn f() -> u32;
| ^^^
error: must be Result<...>
--> $DIR/invalid-imports.rs:36:15
|
36 | fn f() -> u32;
| ^^^
error: must be Result<...>
--> $DIR/invalid-imports.rs:38:15
|
38 | fn f() -> &u32;
36 | fn f() -> &u32;
| ^^^^
error: must have at least one generic parameter
--> $DIR/invalid-imports.rs:40:15
--> $DIR/invalid-imports.rs:38:15
|
40 | fn f() -> Result<>;
38 | fn f() -> Result<>;
| ^^^^^^^^
error: it is currently not sound to use lifetimes in function signatures
--> $DIR/invalid-imports.rs:42:22
--> $DIR/invalid-imports.rs:40:22
|
42 | fn f() -> Result<'a>;
40 | fn f() -> Result<'a>;
| ^^
error: aborting due to 15 previous errors

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,67 +1,67 @@
error: can only #[wasm_bindgen] public functions
--> $DIR/invalid-items.rs:8:1
--> $DIR/invalid-items.rs:6:1
|
8 | fn foo() {}
6 | fn foo() {}
| ^^^^^^^^^^^
error: can only #[wasm_bindgen] safe functions
--> $DIR/invalid-items.rs:11:5
|
11 | pub unsafe fn foo1() {}
| ^^^^^^
--> $DIR/invalid-items.rs:9:5
|
9 | pub unsafe fn foo1() {}
| ^^^^^^
error: can only #[wasm_bindgen] non-const functions
--> $DIR/invalid-items.rs:14:5
--> $DIR/invalid-items.rs:12:5
|
14 | pub const fn foo2() {}
12 | pub const fn foo2() {}
| ^^^^^
error: structs with #[wasm_bindgen] cannot have lifetime or type parameters currently
--> $DIR/invalid-items.rs:17:11
--> $DIR/invalid-items.rs:15:11
|
17 | struct Foo<T>(T);
15 | struct Foo<T>(T);
| ^^^
error: cannot import mutable globals yet
--> $DIR/invalid-items.rs:21:12
--> $DIR/invalid-items.rs:19:12
|
21 | static mut FOO: u32;
19 | static mut FOO: u32;
| ^^^
error: can't #[wasm_bindgen] variadic functions
--> $DIR/invalid-items.rs:23:25
--> $DIR/invalid-items.rs:21:25
|
23 | pub fn foo3(x: i32, ...);
21 | pub fn foo3(x: i32, ...);
| ^^^
error: only foreign mods with the `C` ABI are allowed
--> $DIR/invalid-items.rs:27:8
--> $DIR/invalid-items.rs:25:8
|
27 | extern "system" {
25 | extern "system" {
| ^^^^^^^^
error: can't #[wasm_bindgen] functions with lifetime or type parameters
--> $DIR/invalid-items.rs:29:12
|
29 | pub fn foo4<T>() {}
| ^^^
error: can't #[wasm_bindgen] functions with lifetime or type parameters
--> $DIR/invalid-items.rs:31:12
|
31 | pub fn foo4<T>() {}
| ^^^
31 | pub fn foo5<'a>() {}
| ^^^^
error: can't #[wasm_bindgen] functions with lifetime or type parameters
--> $DIR/invalid-items.rs:33:12
|
33 | pub fn foo5<'a>() {}
| ^^^^
error: can't #[wasm_bindgen] functions with lifetime or type parameters
--> $DIR/invalid-items.rs:35:12
|
35 | pub fn foo6<'a, T>() {}
33 | pub fn foo6<'a, T>() {}
| ^^^^^^^
error: #[wasm_bindgen] can only be applied to a function, struct, enum, impl, or extern block
--> $DIR/invalid-items.rs:38:1
--> $DIR/invalid-items.rs:36:1
|
38 | trait X {}
36 | trait X {}
| ^^^^^^^^^^
error: aborting due to 11 previous errors

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,61 +1,61 @@
error: #[wasm_bindgen] default impls are not supported
--> $DIR/invalid-methods.rs:11:1
|
11 | default impl A {
| ^^^^^^^
--> $DIR/invalid-methods.rs:9:1
|
9 | default impl A {
| ^^^^^^^
error: #[wasm_bindgen] unsafe impls are not supported
--> $DIR/invalid-methods.rs:15:1
--> $DIR/invalid-methods.rs:13:1
|
15 | unsafe impl A {
13 | unsafe impl A {
| ^^^^^^
error: #[wasm_bindgen] trait impls are not supported
--> $DIR/invalid-methods.rs:19:6
--> $DIR/invalid-methods.rs:17:6
|
19 | impl Clone for A {
17 | impl Clone for A {
| ^^^^^
error: #[wasm_bindgen] generic impls aren't supported
--> $DIR/invalid-methods.rs:23:5
--> $DIR/invalid-methods.rs:21:5
|
23 | impl<T> A {
21 | impl<T> A {
| ^^^
error: unsupported self type in #[wasm_bindgen] impl
--> $DIR/invalid-methods.rs:27:6
--> $DIR/invalid-methods.rs:25:6
|
27 | impl &'static A {
25 | impl &'static A {
| ^^^^^^^^^^
error: const definitions aren't supported with #[wasm_bindgen]
--> $DIR/invalid-methods.rs:34:5
--> $DIR/invalid-methods.rs:32:5
|
34 | const X: u32 = 3;
32 | const X: u32 = 3;
| ^^^^^^^^^^^^^^^^^
error: type definitions in impls aren't supported with #[wasm_bindgen]
--> $DIR/invalid-methods.rs:35:5
--> $DIR/invalid-methods.rs:33:5
|
35 | type Y = u32;
33 | type Y = u32;
| ^^^^^^^^^^^^^
error: macros in impls aren't supported
--> $DIR/invalid-methods.rs:36:5
--> $DIR/invalid-methods.rs:34:5
|
36 | x!();
34 | x!();
| ^^^^^
error: can only #[wasm_bindgen] non-const functions
--> $DIR/invalid-methods.rs:41:9
--> $DIR/invalid-methods.rs:39:9
|
41 | pub const fn foo() {}
39 | pub const fn foo() {}
| ^^^^^
error: can only bindgen safe functions
--> $DIR/invalid-methods.rs:42:9
--> $DIR/invalid-methods.rs:40:9
|
42 | pub unsafe fn foo() {}
40 | pub unsafe fn foo() {}
| ^^^^^^
error: aborting due to 10 previous errors

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,7 +1,7 @@
error: can only #[wasm_bindgen] public functions
--> $DIR/non-public-function.rs:8:1
--> $DIR/non-public-function.rs:6:1
|
8 | fn foo() {}
6 | fn foo() {}
| ^^^^^^^^^^^
error: aborting due to previous error

View File

@ -38,8 +38,6 @@ ton of documentation just yet, but a taste of how it works is:
```rust
// in tests/wasm.rs
#![feature(use_extern_macros)]
extern crate wasm_bindgen_test;
use wasm_bindgen_test::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
#[macro_use]
extern crate futures;
extern crate js_sys;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate futures;
extern crate sample;
extern crate wasm_bindgen;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate futures;
extern crate sample;
extern crate wasm_bindgen;

View File

@ -2,7 +2,6 @@
//!
//! More documentation can be found in the README for this crate!
#![feature(use_extern_macros)]
#![deny(missing_docs)]
extern crate console_error_panic_hook;

View File

@ -3,6 +3,6 @@ use web_sys::console;
#[wasm_bindgen_test]
fn test_console() {
console::time_using_label("test label");
console::time_end_using_label("test label");
console::time_with_label("test label");
console::time_end_with_label("test label");
}

View File

@ -4,7 +4,7 @@ use web_sys::{DomPoint, DomPointReadOnly};
#[wasm_bindgen_test]
fn dom_point() {
let x = DomPoint::new_using_x_and_y_and_z_and_w(1.0, 2.0, 3.0, 4.0).unwrap();
let x = DomPoint::new_with_x_and_y_and_z_and_w(1.0, 2.0, 3.0, 4.0).unwrap();
assert_eq!(x.x(), 1.0);
x.set_x(1.5);
assert_eq!(x.x(), 1.5);
@ -24,7 +24,7 @@ fn dom_point() {
#[wasm_bindgen_test]
fn dom_point_readonly() {
let x = DomPoint::new_using_x_and_y_and_z_and_w(1.0, 2.0, 3.0, 4.0).unwrap();
let x = DomPoint::new_with_x_and_y_and_z_and_w(1.0, 2.0, 3.0, 4.0).unwrap();
let x = DomPointReadOnly::from(JsValue::from(x));
assert_eq!(x.x(), 1.0);
assert_eq!(x.y(), 2.0);

View File

@ -1,4 +1,3 @@
#![feature(use_extern_macros)]
#![cfg(target_arch = "wasm32")]
extern crate futures;

View File

@ -3,7 +3,7 @@ use web_sys::HtmlOptionElement;
#[wasm_bindgen_test]
fn test_option_element() {
let option = HtmlOptionElement::new_using_text_and_value_and_default_selected_and_selected(
let option = HtmlOptionElement::new_with_text_and_value_and_default_selected_and_selected(
"option_text",
"option_value",
false,

View File

@ -99,7 +99,7 @@ fn test_table_element() {
);
table
.insert_row_using_index(0)
.insert_row_with_index(0)
.expect("Failed to insert row at index 0");
assert!(
table.rows().length() == 1,

View File

@ -43,25 +43,25 @@ interface mixin WindowOrWorkerGlobalScope {
};
// https://fetch.spec.whatwg.org/#fetch-method
partial interface WindowOrWorkerGlobalScope {
partial interface mixin WindowOrWorkerGlobalScope {
[NewObject, NeedsCallerType]
Promise<Response> fetch(RequestInfo input, optional RequestInit init);
};
// https://w3c.github.io/webappsec-secure-contexts/#monkey-patching-global-object
partial interface WindowOrWorkerGlobalScope {
partial interface mixin WindowOrWorkerGlobalScope {
readonly attribute boolean isSecureContext;
};
// http://w3c.github.io/IndexedDB/#factory-interface
partial interface WindowOrWorkerGlobalScope {
partial interface mixin WindowOrWorkerGlobalScope {
// readonly attribute IDBFactory indexedDB;
[Throws]
readonly attribute IDBFactory? indexedDB;
};
// https://w3c.github.io/ServiceWorker/#self-caches
partial interface WindowOrWorkerGlobalScope {
partial interface mixin WindowOrWorkerGlobalScope {
[Throws, Func="mozilla::dom::DOMPrefs::DOMCachesEnabled", SameObject]
readonly attribute CacheStorage caches;
};

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate js_sys;
extern crate wasm_bindgen;
extern crate wasm_bindgen_test;

View File

@ -50,7 +50,7 @@ fn static_property() {
}
#[wasm_bindgen_test]
fn one_method_using_an_undefined_import_doesnt_break_all_other_methods() {
fn one_method_with_an_undefined_import_doesnt_break_all_other_methods() {
let f = UndefinedMethod::new().unwrap();
assert!(f.ok_method());
}
@ -81,14 +81,14 @@ fn indexing() {
#[wasm_bindgen_test]
fn optional_and_union_arguments() {
let f = OptionalAndUnionArguments::new().unwrap();
assert_eq!(f.m_using_a("abc"), "string, abc, boolean, true, number, 123, number, 456");
assert_eq!(f.m_using_a_and_b("abc", false), "string, abc, boolean, false, number, 123, number, 456");
assert_eq!(f.m_using_dom_str_and_bool_and_i16("abc", false, 5), "string, abc, boolean, false, number, 5, number, 456");
assert_eq!(f.m_using_dom_str_and_bool_and_dom_str("abc", false, "5"), "string, abc, boolean, false, string, 5, number, 456");
assert_eq!(f.m_using_dom_str_and_bool_and_i16_and_opt_i64("abc", false, 5, Some(10)), "string, abc, boolean, false, number, 5, bigint, 10");
assert_eq!(f.m_using_dom_str_and_bool_and_i16_and_opt_bool("abc", false, 5, Some(true)), "string, abc, boolean, false, number, 5, boolean, true");
assert_eq!(f.m_using_dom_str_and_bool_and_dom_str_and_opt_i64("abc", false, "5", Some(10)), "string, abc, boolean, false, string, 5, bigint, 10");
assert_eq!(f.m_using_dom_str_and_bool_and_dom_str_and_opt_bool("abc", false, "5", Some(true)), "string, abc, boolean, false, string, 5, boolean, true");
assert_eq!(f.m("abc"), "string, abc, boolean, true, number, 123, number, 456");
assert_eq!(f.m_with_b("abc", false), "string, abc, boolean, false, number, 123, number, 456");
assert_eq!(f.m_with_bool_and_i16("abc", false, 5), "string, abc, boolean, false, number, 5, number, 456");
assert_eq!(f.m_with_bool_and_str("abc", false, "5"), "string, abc, boolean, false, string, 5, number, 456");
assert_eq!(f.m_with_bool_and_i16_and_opt_i64("abc", false, 5, Some(10)), "string, abc, boolean, false, number, 5, bigint, 10");
assert_eq!(f.m_with_bool_and_i16_and_opt_bool("abc", false, 5, Some(true)), "string, abc, boolean, false, number, 5, boolean, true");
assert_eq!(f.m_with_bool_and_str_and_opt_i64("abc", false, "5", Some(10)), "string, abc, boolean, false, string, 5, bigint, 10");
assert_eq!(f.m_with_bool_and_str_and_opt_bool("abc", false, "5", Some(true)), "string, abc, boolean, false, string, 5, boolean, true");
}
#[wasm_bindgen_test]

View File

@ -348,13 +348,13 @@ impl<'a> IdlType<'a> {
IdlType::UnsignedLong => dst.push_str("u32"),
IdlType::LongLong => dst.push_str("i64"),
IdlType::UnsignedLongLong => dst.push_str("u64"),
IdlType::Float => dst.push_str("f32"),
IdlType::UnrestrictedFloat => dst.push_str("unrestricted_f32"),
IdlType::Double => dst.push_str("f64"),
IdlType::UnrestrictedDouble => dst.push_str("unrestricted_f64"),
IdlType::DomString => dst.push_str("dom_str"),
IdlType::ByteString => dst.push_str("byte_str"),
IdlType::UsvString => dst.push_str("usv_str"),
IdlType::Float |
IdlType::UnrestrictedFloat => dst.push_str("f32"),
IdlType::Double |
IdlType::UnrestrictedDouble => dst.push_str("f64"),
IdlType::DomString |
IdlType::ByteString |
IdlType::UsvString => dst.push_str("str"),
IdlType::Object => dst.push_str("object"),
IdlType::Symbol => dst.push_str("symbol"),
IdlType::Error => dst.push_str("error"),

View File

@ -273,9 +273,13 @@ impl<'src> FirstPassRecord<'src> {
let rust_name = if possibilities.len() > 1 {
let mut rust_name = rust_name.clone();
let mut first = true;
for ((argument_name, _, _), idl_type) in arguments.iter().zip(idl_types) {
let iter = arguments.iter().zip(idl_types).enumerate();
for (i, ((argument_name, _, _), idl_type)) in iter {
if possibilities.iter().all(|p| p.get(i) == Some(idl_type)) {
continue
}
if first {
rust_name.push_str("_using_");
rust_name.push_str("_with_");
first = false;
} else {
rust_name.push_str("_and_");

View File

@ -10,31 +10,33 @@ when using `build.sh`!
The examples here are:
* `hello_world` - the "hello world" of `#[wasm_bindgen]`, aka throwing up a
dialog greeting you
* `console_log` - a showcase of `#[wasm_bindgen]` importing classes and how to
bind `console.log`
* `math` - like `console_log` except showing how to import Math-related
functions instead
* `dom` - an example of accessing the global `document` object and appending
HTML to it
* `smorgasboard` - a bunch of features all thrown into one, showing off the
various capabilities of the `#[wasm_bindgen]` macro and what you can do with
it from JS
* `performance` - how to import APIs like `performance.now()` and time various
operations in Rust
* `wasm-in-wasm` - how to interact with namespaced APIs like
`WebAssembly.Module` and shows off creation of a WebAssembly module from Rust
* `closures` - an example of how to invoke functions like `setInterval` or use
the `onclick` property in conjunction with closures.
* `no_modules` - an example of how to use the `--no-modules` flag to
the `wasm-bindgen` CLI tool
* `add` - an example of generating a tiny wasm binary, one that only adds two
numbers.
* `asm.js` - an example of using the `wasm2asm` tool from [binaryen] to convert
the generated WebAssembly to normal JS
* `char` - an example of passing the rust `char` type to and from the js `string` type
* `import_js` - an example of importing local JS functionality into a crate
* `closures` - an example of how to invoke functions like `setInterval` or use
the `onclick` property in conjunction with closures.
* `comments` - an example of how Rust comments are copied into js bindings
* `console_log` - a showcase of `#[wasm_bindgen]` importing classes and how to
bind `console.log`
* `dom` - an example of accessing the global `document` object and appending
HTML to it
* `fetch` -- how to use the Fetch API to make async http requests
* `hello_world` - the "hello world" of `#[wasm_bindgen]`, aka throwing up a
dialog greeting you
* `import_js` - an example of importing local JS functionality into a crate
* `math` - like `console_log` except showing how to import Math-related
functions instead
* `no_modules` - an example of how to use the `--no-modules` flag to
the `wasm-bindgen` CLI tool
* `performance` - how to import APIs like `performance.now()` and time various
operations in Rust
* `smorgasboard` - a bunch of features all thrown into one, showing off the
various capabilities of the `#[wasm_bindgen]` macro and what you can do with
it from JS
* `wasm-in-wasm` - how to interact with namespaced APIs like
`WebAssembly.Module` and shows off creation of a WebAssembly module from Rust
* `webaudio` - how to use the Web Audio APIs to generate sounds
[binaryen]: https://github.com/WebAssembly/binaryen

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate js_sys;
extern crate wasm_bindgen;
extern crate web_sys;
@ -22,7 +20,7 @@ pub fn draw() {
.unwrap();
let context = canvas
.get_context_using_context_id("2d")
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2D>()
@ -31,43 +29,43 @@ pub fn draw() {
context.begin_path();
// Draw the outer circle.
context.arc_using_x_and_y_and_radius_and_start_angle_and_end_angle(
context.arc(
75.0,
75.0,
50.0,
0.0,
f64::consts::PI * 2.0,
);
).unwrap();
// Draw the mouth.
context.move_to(110.0, 75.0);
context.arc_using_x_and_y_and_radius_and_start_angle_and_end_angle(
context.arc(
75.0,
75.0,
35.0,
0.0,
f64::consts::PI,
);
).unwrap();
// Draw the left eye.
context.move_to(65.0, 65.0);
context.arc_using_x_and_y_and_radius_and_start_angle_and_end_angle(
context.arc(
60.0,
65.0,
5.0,
0.0,
f64::consts::PI * 2.0,
);
).unwrap();
// Draw the right eye.
context.move_to(95.0, 65.0);
context.arc_using_x_and_y_and_radius_and_start_angle_and_end_angle(
context.arc(
90.0,
65.0,
5.0,
0.0,
f64::consts::PI * 2.0,
);
).unwrap();
context.stroke();
}

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -7,5 +7,5 @@ authors = ["Alex Crichton <alex@alexcrichton.com>"]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = { path = "../.." }
wasm-bindgen = { path = "../..", features = ['nightly'] }
js-sys = { path = "../../crates/js-sys" }

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
extern crate js_sys;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -8,3 +8,4 @@ crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = { path = "../.." }
web-sys = { path = "../../crates/web-sys" }

View File

@ -2,8 +2,10 @@
[View this example online](https://webassembly.studio/?f=ppd7u8k9i9)
This directory is an example of using the `#[wasm_bindgen]` macro to import the
`console.log` function and call it
This directory is an example of two ways to get access to the `console.log` function.
The first way uses the `#[wasm_bindgen]` macro to import the function and call it.
The second way uses the binding from the `web-sys` crate.
You can build the example with:

View File

@ -1,9 +1,12 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
extern crate web_sys;
use wasm_bindgen::prelude::*;
// You can use the console bindings from web-sys...
use web_sys::console;
// ... or you can manually write the bindings yourself
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
@ -19,4 +22,7 @@ pub fn run() {
log("Hello from Rust!");
log_u32(42);
log_many("Logging", "many values!");
console::log(JsValue::from("Another message from rust!"));
console::log(JsValue::from(56u32));
}

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

4
examples/fetch/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
fetch.d.ts
fetch.js
fetch_bg.wasm
package-lock.json

16
examples/fetch/Cargo.toml Normal file
View File

@ -0,0 +1,16 @@
[package]
name = "fetch"
version = "0.1.0"
authors = ["Andrew Chin <achin@eminence32.net>"]
[lib]
crate-type = ["cdylib"]
[dependencies]
futures = "0.1.20"
wasm-bindgen = { path = "../..", features = ["serde-serialize"] }
js-sys = { path = "../../crates/js-sys" }
web-sys = { path = "../../crates/web-sys" }
wasm-bindgen-futures = { path = "../../crates/futures" }
serde = "^1.0.59"
serde_derive = "^1.0.59"

2
examples/fetch/build.bat Normal file
View File

@ -0,0 +1,2 @@
cargo +nightly build --target wasm32-unknown-unknown
cargo +nightly run --manifest-path ../../crates/cli/Cargo.toml --bin wasm-bindgen -- ../../target/wasm32-unknown-unknown/debug/fetch.wasm --out-dir .

10
examples/fetch/build.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/sh
# For more coments about what's going on here, see the `hello_world` example
set -ex
cargo +nightly build --target wasm32-unknown-unknown
cargo +nightly run --manifest-path ../../crates/cli/Cargo.toml \
--bin wasm-bindgen -- \
../../target/wasm32-unknown-unknown/debug/fetch.wasm --out-dir .

10
examples/fetch/index.html Normal file
View File

@ -0,0 +1,10 @@
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
</head>
<body>
<script src='./index.js'></script>
</body>
</html>

11
examples/fetch/index.js Normal file
View File

@ -0,0 +1,11 @@
const rust = import('./fetch');
rust.then(m => {
m.run().then((data) => {
console.log(data);
console.log("The latest commit to the wasm-bindgen %s branch is:", data.name);
console.log("%s, authored by %s <%s>", data.commit.sha, data.commit.commit.author.name, data.commit.commit.author.email);
})
});

View File

@ -0,0 +1,9 @@
{
"scripts": {
"serve": "webpack-serve ./webpack.config.js"
},
"devDependencies": {
"webpack": "^4.16.5",
"webpack-serve": "^2.0.2"
}
}

83
examples/fetch/src/lib.rs Normal file
View File

@ -0,0 +1,83 @@
extern crate wasm_bindgen;
extern crate js_sys;
extern crate web_sys;
extern crate wasm_bindgen_futures;
extern crate futures;
#[macro_use]
extern crate serde_derive;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use js_sys::Promise;
use web_sys::{Request, RequestInit, RequestMode, Response, Window};
use wasm_bindgen_futures::JsFuture;
use futures::{future, Future};
use wasm_bindgen_futures::future_to_promise;
// A struct to hold some data from the github Branch API.
// Note how we don't have to define every member -- serde will ignore extra data when deserializing
#[derive(Debug, Serialize, Deserialize)]
pub struct Branch {
pub name: String,
pub commit: Commit,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Commit {
pub sha: String,
pub commit: CommitDetails,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CommitDetails {
pub author: Signature,
pub committer: Signature,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Signature {
pub name: String,
pub email: String,
}
#[wasm_bindgen]
extern "C" {
static window: Window;
}
#[wasm_bindgen]
pub fn run() -> Promise {
let mut request_options = RequestInit::new();
request_options.method("GET");
request_options.mode(RequestMode::Cors);
let req = Request::new_with_str_and_request_init("https://api.github.com/repos/rustwasm/wasm-bindgen/branches/master", &request_options).unwrap();
// the RequestInit struct will eventually support setting headers, but that's missing right now
req.headers().set("Accept", "application/vnd.github.v3+json").unwrap();
let req_promise = window.fetch_with_request(&req);
let to_return = JsFuture::from(req_promise).and_then(|resp_value| {
// resp_value is a Response object
assert!(resp_value.is_instance_of::<Response>());
let resp: Response = resp_value.dyn_into().unwrap();
resp.json()
}).and_then(|json_value: Promise| {
// convert this other promise into a rust Future
JsFuture::from(json_value)
}).and_then(|json| {
// Use serde to parse this into a struct
let branch_info: Branch = json.into_serde().unwrap();
// Send the Branch struct back to javascript as an object
future::ok(JsValue::from_serde(&branch_info).unwrap())
});
// Convert this rust future back into a javascript promise.
// Return it to javascript so that it can be driven to completion.
future_to_promise(to_return)
}

View File

@ -0,0 +1,10 @@
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
mode: 'development'
};

View File

@ -1,4 +1,3 @@
#![feature(use_extern_macros)]
#![allow(unused_variables, dead_code)]
extern crate wasm_bindgen;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate humantime;
extern crate wasm_bindgen;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -1,5 +1,3 @@
#![feature(use_extern_macros, nll)]
extern crate wasm_bindgen;
extern crate web_sys;
@ -45,13 +43,20 @@ impl FmOsc {
// TODO, how to throw from a constructor?
let ctx = web_sys::AudioContext::new().unwrap();
let base: &BaseAudioContext = ctx.as_ref();
let primary;
let fm_osc;
let gain;
let fm_gain;
// create our web audio objects
let primary = base.create_oscillator().unwrap();
let fm_osc = base.create_oscillator().unwrap();
let gain = base.create_gain().unwrap();
let fm_gain = base.create_gain().unwrap();
{
let base: &BaseAudioContext = ctx.as_ref();
// create our web audio objects
primary = base.create_oscillator().unwrap();
fm_osc = base.create_oscillator().unwrap();
gain = base.create_gain().unwrap();
fm_gain = base.create_gain().unwrap();
}
// some initial settings:
primary.set_type(OscillatorType::Sine);
@ -63,32 +68,35 @@ impl FmOsc {
// Create base class references:
let primary_node: &AudioNode = primary.as_ref();
let gain_node: &AudioNode = gain.as_ref();
let fm_osc_node: &AudioNode = fm_osc.as_ref();
let fm_gain_node: &AudioNode = fm_gain.as_ref();
let destination = base.destination();
let destination_node: &AudioNode = destination.as_ref();
{
let primary_node: &AudioNode = primary.as_ref();
let gain_node: &AudioNode = gain.as_ref();
let fm_osc_node: &AudioNode = fm_osc.as_ref();
let fm_gain_node: &AudioNode = fm_gain.as_ref();
let base: &BaseAudioContext = ctx.as_ref();
let destination = base.destination();
let destination_node: &AudioNode = destination.as_ref();
// connect them up:
// connect them up:
// The primary oscillator is routed through the gain node, so that it can control the overall output volume
primary_node.connect_with_destination_and_output_and_input_using_destination(gain.as_ref());
// Then connect the gain node to the AudioContext destination (aka your speakers)
gain_node.connect_with_destination_and_output_and_input_using_destination(destination_node);
// The primary oscillator is routed through the gain node, so that it can control the overall output volume
primary_node.connect_with_destination_and_output_and_input(gain.as_ref()).unwrap();
// Then connect the gain node to the AudioContext destination (aka your speakers)
gain_node.connect_with_destination_and_output_and_input(destination_node).unwrap();
// the FM oscillator is connected to its own gain node, so it can control the amount of modulation
fm_osc_node.connect_with_destination_and_output_and_input_using_destination(fm_gain.as_ref());
// the FM oscillator is connected to its own gain node, so it can control the amount of modulation
fm_osc_node.connect_with_destination_and_output_and_input(fm_gain.as_ref()).unwrap();
// Connect the FM oscillator to the frequency parameter of the main oscillator, so that the
// FM node can modulate its frequency
fm_gain_node.connect_with_destination_and_output_using_destination(&primary.frequency());
// Connect the FM oscillator to the frequency parameter of the main oscillator, so that the
// FM node can modulate its frequency
fm_gain_node.connect_with_destination_and_output(&primary.frequency()).unwrap();
}
// start the oscillators!
AsRef::<AudioScheduledSourceNode>::as_ref(&primary).start();
AsRef::<AudioScheduledSourceNode>::as_ref(&fm_osc).start();
AsRef::<AudioScheduledSourceNode>::as_ref(&primary).start().unwrap();
AsRef::<AudioScheduledSourceNode>::as_ref(&fm_osc).start().unwrap();
FmOsc {
ctx,
@ -144,4 +152,4 @@ impl FmOsc {
}
}
}

View File

@ -39,8 +39,6 @@ wasm-bindgen = "0.2"
Next up our actual code! We'll write this in `src/lib.rs`:
```rust,ignore
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -5,8 +5,6 @@ can also [explore this code online](https://webassembly.studio/?f=t61j18noqz):
```rust,ignore
// src/lib.rs
#![feature(use_extern_macros)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

View File

@ -7,6 +7,7 @@
#![allow(const_err)] // FIXME(rust-lang/rust#52603)
use std::cell::UnsafeCell;
#[cfg(feature = "nightly")]
use std::marker::Unsize;
use std::mem::{self, ManuallyDrop};
use std::prelude::v1::*;
@ -90,6 +91,7 @@ impl<T> Closure<T>
///
/// This is unfortunately pretty restrictive for now but hopefully some of
/// these restrictions can be lifted in the future!
#[cfg(feature = "nightly")]
pub fn new<F>(t: F) -> Closure<T>
where F: Unsize<T> + 'static
{

View File

@ -5,9 +5,9 @@
//! this crate and this crate also provides JS bindings through the `JsValue`
//! interface.
#![feature(use_extern_macros, unsize)]
#![no_std]
#![doc(html_root_url = "https://docs.rs/wasm-bindgen/0.2")]
#![cfg_attr(feature = "nightly", feature(unsize))]
#[cfg(feature = "serde-serialize")]
extern crate serde;

Some files were not shown because too many files have changed in this diff Show More