From 7ecf4aae87489c4224adf01cd8494b470fd0c73a Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 26 Sep 2018 08:26:00 -0700 Subject: [PATCH] cargo +nightly fmt --all Rustfmt all the things! --- crates/backend/src/ast.rs | 16 +- crates/backend/src/codegen.rs | 94 ++--- crates/backend/src/defined.rs | 20 +- crates/backend/src/error.rs | 12 +- crates/backend/src/lib.rs | 5 +- crates/backend/src/util.rs | 3 +- crates/cli-support/src/descriptor.rs | 20 +- crates/cli-support/src/js/closures.rs | 72 ++-- crates/cli-support/src/js/js2rust.rs | 74 ++-- crates/cli-support/src/js/mod.rs | 109 +++--- crates/cli-support/src/js/rust2js.rs | 76 ++-- crates/cli-support/src/lib.rs | 35 +- .../bin/wasm-bindgen-test-runner/headless.rs | 89 ++--- .../src/bin/wasm-bindgen-test-runner/main.rs | 39 +- .../src/bin/wasm-bindgen-test-runner/node.rs | 29 +- .../bin/wasm-bindgen-test-runner/server.rs | 26 +- .../src/bin/wasm-bindgen-test-runner/shell.rs | 9 +- crates/cli/src/bin/wasm2es6js.rs | 6 +- crates/futures/src/lib.rs | 17 +- crates/js-sys/tests/headless.rs | 14 +- crates/js-sys/tests/wasm/Array.rs | 75 ++-- crates/js-sys/tests/wasm/ArrayBuffer.rs | 4 +- crates/js-sys/tests/wasm/ArrayIterator.rs | 2 +- crates/js-sys/tests/wasm/Boolean.rs | 4 +- crates/js-sys/tests/wasm/Date.rs | 9 +- crates/js-sys/tests/wasm/Error.rs | 9 +- crates/js-sys/tests/wasm/EvalError.rs | 15 +- crates/js-sys/tests/wasm/Function.rs | 10 +- crates/js-sys/tests/wasm/Generator.rs | 10 +- crates/js-sys/tests/wasm/Intl.rs | 2 +- crates/js-sys/tests/wasm/Iterator.rs | 18 +- crates/js-sys/tests/wasm/JSON.rs | 12 +- crates/js-sys/tests/wasm/JsString.rs | 91 +++-- crates/js-sys/tests/wasm/Map.rs | 4 +- crates/js-sys/tests/wasm/MapIterator.rs | 2 +- crates/js-sys/tests/wasm/Math.rs | 20 +- crates/js-sys/tests/wasm/Number.rs | 14 +- crates/js-sys/tests/wasm/Promise.rs | 4 +- crates/js-sys/tests/wasm/Proxy.rs | 5 +- crates/js-sys/tests/wasm/RangeError.rs | 4 +- crates/js-sys/tests/wasm/ReferenceError.rs | 4 +- crates/js-sys/tests/wasm/Reflect.rs | 27 +- crates/js-sys/tests/wasm/RegExp.rs | 9 +- crates/js-sys/tests/wasm/Set.rs | 20 +- crates/js-sys/tests/wasm/SetIterator.rs | 2 +- crates/js-sys/tests/wasm/Symbol.rs | 11 +- crates/js-sys/tests/wasm/SyntaxError.rs | 4 +- crates/js-sys/tests/wasm/TypeError.rs | 4 +- crates/js-sys/tests/wasm/TypedArray.rs | 32 +- crates/js-sys/tests/wasm/UriError.rs | 4 +- crates/js-sys/tests/wasm/WeakMap.rs | 8 +- crates/js-sys/tests/wasm/WeakSet.rs | 8 +- crates/js-sys/tests/wasm/WebAssembly.rs | 22 +- crates/js-sys/tests/wasm/global_fns.rs | 4 +- crates/js-sys/tests/wasm/main.rs | 4 +- crates/macro-support/src/lib.rs | 2 +- crates/macro-support/src/parser.rs | 127 ++++--- crates/test-macro/src/lib.rs | 30 +- crates/test/sample/src/lib.rs | 5 +- crates/test/sample/tests/common/mod.rs | 29 +- crates/test/src/rt/browser.rs | 11 +- crates/test/src/rt/detect.rs | 4 +- crates/test/src/rt/mod.rs | 39 +- crates/test/src/rt/node.rs | 9 +- crates/typescript/src/parser.rs | 3 +- crates/wasm-interpreter/src/lib.rs | 53 ++- crates/wasm-interpreter/tests/smoke.rs | 3 +- crates/web-sys/build.rs | 37 +- crates/web-sys/src/lib.rs | 2 +- crates/web-sys/tests/wasm/anchor_element.rs | 16 +- crates/web-sys/tests/wasm/body_element.rs | 4 +- crates/web-sys/tests/wasm/br_element.rs | 4 +- crates/web-sys/tests/wasm/button_element.rs | 54 ++- crates/web-sys/tests/wasm/div_element.rs | 4 +- crates/web-sys/tests/wasm/element.rs | 137 +++++-- crates/web-sys/tests/wasm/event.rs | 32 +- crates/web-sys/tests/wasm/head_element.rs | 4 +- crates/web-sys/tests/wasm/headers.rs | 4 +- crates/web-sys/tests/wasm/heading_element.rs | 4 +- crates/web-sys/tests/wasm/history.rs | 22 +- crates/web-sys/tests/wasm/hr_element.rs | 6 +- crates/web-sys/tests/wasm/html_element.rs | 38 +- .../web-sys/tests/wasm/html_html_element.rs | 4 +- crates/web-sys/tests/wasm/input_element.rs | 73 ++-- crates/web-sys/tests/wasm/main.rs | 10 +- crates/web-sys/tests/wasm/meta_element.rs | 30 +- crates/web-sys/tests/wasm/meter_element.rs | 41 ++- crates/web-sys/tests/wasm/mod_elements.rs | 30 +- crates/web-sys/tests/wasm/olist_element.rs | 48 ++- crates/web-sys/tests/wasm/optgroup_element.rs | 24 +- crates/web-sys/tests/wasm/option_element.rs | 73 +++- .../web-sys/tests/wasm/options_collection.rs | 38 +- crates/web-sys/tests/wasm/output_element.rs | 54 ++- .../web-sys/tests/wasm/paragraph_element.rs | 12 +- crates/web-sys/tests/wasm/param_element.rs | 24 +- crates/web-sys/tests/wasm/performance.rs | 2 +- crates/web-sys/tests/wasm/pre_element.rs | 6 +- crates/web-sys/tests/wasm/progress_element.rs | 23 +- crates/web-sys/tests/wasm/quote_element.rs | 11 +- crates/web-sys/tests/wasm/response.rs | 4 +- crates/web-sys/tests/wasm/script_element.rs | 38 +- crates/web-sys/tests/wasm/select_element.rs | 148 ++++++-- crates/web-sys/tests/wasm/slot_element.rs | 6 +- crates/web-sys/tests/wasm/span_element.rs | 4 +- crates/web-sys/tests/wasm/style_element.rs | 4 +- crates/web-sys/tests/wasm/table_element.rs | 286 +++++++-------- crates/web-sys/tests/wasm/title_element.rs | 4 +- crates/web-sys/tests/wasm/xpath_result.rs | 19 +- crates/webidl-tests/build.rs | 17 +- crates/webidl-tests/callbacks.rs | 2 +- crates/webidl-tests/dictionary.rs | 7 +- crates/webidl-tests/global.rs | 2 +- crates/webidl-tests/main.rs | 6 +- crates/webidl-tests/simple.rs | 85 +++-- crates/webidl/src/error.rs | 14 +- crates/webidl/src/first_pass.rs | 238 +++++++------ crates/webidl/src/idl_type.rs | 165 ++++----- crates/webidl/src/lib.rs | 244 ++++++------- crates/webidl/src/util.rs | 192 +++++----- examples/canvas/src/lib.rs | 38 +- examples/closures/src/lib.rs | 37 +- examples/duck-typed-interfaces/src/lib.rs | 2 +- examples/fetch/src/lib.rs | 3 +- .../src/imported_types.rs | 14 +- .../guide-supported-types-examples/src/lib.rs | 18 +- examples/julia_set/src/lib.rs | 6 +- examples/performance/src/lib.rs | 4 +- src/convert/closures.rs | 3 +- src/convert/impls.rs | 14 +- src/convert/mod.rs | 9 +- src/convert/slices.rs | 8 +- src/describe.rs | 34 +- src/lib.rs | 34 +- tests/crates/a/src/lib.rs | 2 +- tests/crates/b/src/lib.rs | 2 +- tests/headless.rs | 8 +- tests/no-std/test.rs | 4 +- tests/non_wasm.rs | 5 +- tests/std-crate-no-std-dep.rs | 2 +- tests/wasm/api.rs | 22 +- tests/wasm/char.rs | 28 +- tests/wasm/classes.rs | 12 +- tests/wasm/closures.rs | 35 +- tests/wasm/comments.rs | 6 +- tests/wasm/duplicate_deps.rs | 2 +- tests/wasm/duplicates.rs | 8 +- tests/wasm/enums.rs | 6 +- tests/wasm/import_class.rs | 10 +- tests/wasm/imports.rs | 7 +- tests/wasm/js_objects.rs | 19 +- tests/wasm/jscast.rs | 4 +- tests/wasm/main.rs | 2 +- tests/wasm/math.rs | 106 +++--- tests/wasm/node.rs | 106 +++--- tests/wasm/option.rs | 4 +- tests/wasm/optional_primitives.rs | 336 +++++++++++++----- tests/wasm/rethrow.rs | 4 +- tests/wasm/simple.rs | 17 +- tests/wasm/slice.rs | 6 +- tests/wasm/structural.rs | 6 +- tests/wasm/u64.rs | 48 ++- tests/wasm/validate_prt.rs | 4 +- tests/wasm/variadic.rs | 15 +- 163 files changed, 2975 insertions(+), 1998 deletions(-) diff --git a/crates/backend/src/ast.rs b/crates/backend/src/ast.rs index 3a72b056b..e8333429a 100644 --- a/crates/backend/src/ast.rs +++ b/crates/backend/src/ast.rs @@ -396,7 +396,7 @@ impl ImportFunction { // if `#[wasm_bindgen(js_name = "...")]` is used then that explicitly // because it was hand-written anyway. if self.function.renamed_via_js_name { - return Ok(name) + return Ok(name); } // Otherwise we infer names based on the Rust function name. @@ -417,18 +417,14 @@ impl ImportFunction { OperationKind::Regular => shared::OperationKind::Regular, OperationKind::Getter(g) => { let g = g.as_ref().map(|g| g.to_string()); - shared::OperationKind::Getter( - g.unwrap_or_else(|| self.infer_getter_property()), - ) + shared::OperationKind::Getter(g.unwrap_or_else(|| self.infer_getter_property())) } OperationKind::Setter(s) => { let s = s.as_ref().map(|s| s.to_string()); - shared::OperationKind::Setter( - match s { - Some(s) => s, - None => self.infer_setter_property()?, - } - ) + shared::OperationKind::Setter(match s { + Some(s) => s, + None => self.infer_setter_property()?, + }) } OperationKind::IndexingGetter => shared::OperationKind::IndexingGetter, OperationKind::IndexingSetter => shared::OperationKind::IndexingSetter, diff --git a/crates/backend/src/codegen.rs b/crates/backend/src/codegen.rs index 782d953bf..85c0f8814 100644 --- a/crates/backend/src/codegen.rs +++ b/crates/backend/src/codegen.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::sync::Mutex; use proc_macro2::{Ident, Literal, Span, TokenStream}; use quote::ToTokens; @@ -9,8 +9,8 @@ use shared; use syn; use ast; -use Diagnostic; use util::ShortHash; +use Diagnostic; pub trait TryToTokens { fn try_to_tokens(&self, tokens: &mut TokenStream) -> Result<(), Diagnostic>; @@ -51,7 +51,7 @@ impl TryToTokens for ast::Program { Ok(kind) => kind, Err(e) => { errors.push(e); - continue + continue; } }; (quote! { impl #ns { #kind } }).to_tokens(tokens); @@ -275,9 +275,12 @@ impl ToTokens for ast::StructField { } }).to_tokens(tokens); - Descriptor(&getter, quote! { - <#ty as WasmDescribe>::describe(); - }).to_tokens(tokens); + Descriptor( + &getter, + quote! { + <#ty as WasmDescribe>::describe(); + }, + ).to_tokens(tokens); if self.readonly { return; @@ -307,9 +310,7 @@ impl ToTokens for ast::StructField { } impl TryToTokens for ast::Export { - fn try_to_tokens(self: &ast::Export, into: &mut TokenStream) - -> Result<(), Diagnostic> - { + fn try_to_tokens(self: &ast::Export, into: &mut TokenStream) -> Result<(), Diagnostic> { let generated_name = self.rust_symbol(); let export_name = self.export_name(); let mut args = vec![]; @@ -424,10 +425,7 @@ impl TryToTokens for ast::Export { }); let syn_ret = self.function.ret.as_ref().unwrap_or(&syn_unit); if let syn::Type::Reference(_) = syn_ret { - bail_span!( - syn_ret, - "cannot return a borrowed ref with #[wasm_bindgen]", - ) + bail_span!(syn_ret, "cannot return a borrowed ref with #[wasm_bindgen]",) } let ret_ty = quote! { -> <#syn_ret as ::wasm_bindgen::convert::ReturnWasmAbi>::Abi @@ -482,12 +480,15 @@ impl TryToTokens for ast::Export { // this, but the tl;dr; is that this is stripped from the final wasm // binary along with anything it references. let export = Ident::new(&export_name, Span::call_site()); - Descriptor(&export, quote! { - inform(FUNCTION); - inform(#nargs); - #(<#argtys as WasmDescribe>::describe();)* - #describe_ret - }).to_tokens(into); + Descriptor( + &export, + quote! { + inform(FUNCTION); + inform(#nargs); + #(<#argtys as WasmDescribe>::describe();)* + #describe_ret + }, + ).to_tokens(into); Ok(()) } @@ -680,8 +681,7 @@ impl ToTokens for ast::ImportEnum { let this_index = current_idx; current_idx += 1; Literal::usize_unsuffixed(this_index) - }) - .collect(); + }).collect(); // Borrow variant_indexes because we need to use it multiple times inside the quote! macro let variant_indexes_ref = &variant_indexes; @@ -792,12 +792,10 @@ impl TryToTokens for ast::ImportFunction { .. }) => ident.clone(), syn::Pat::Wild(_) => syn::Ident::new(&format!("__genarg_{}", i), Span::call_site()), - _ => { - bail_span!( - pat, - "unsupported pattern in #[wasm_bindgen] imported function", - ) - } + _ => bail_span!( + pat, + "unsupported pattern in #[wasm_bindgen] imported function", + ), }; abi_argument_names.push(name.clone()); @@ -819,7 +817,10 @@ impl TryToTokens for ast::ImportFunction { let mut convert_ret; match &self.js_ret { Some(syn::Type::Reference(_)) => { - bail_span!(self.js_ret, "cannot return references in #[wasm_bindgen] imports yet"); + bail_span!( + self.js_ret, + "cannot return references in #[wasm_bindgen] imports yet" + ); } Some(ref ty) => { abi_ret = quote! { @@ -943,12 +944,15 @@ impl<'a> ToTokens for DescribeImport<'a> { None => quote! { <() as WasmDescribe>::describe(); }, }; - Descriptor(&f.shim, quote! { - inform(FUNCTION); - inform(#nargs); - #(<#argtys as WasmDescribe>::describe();)* - #inform_ret - }).to_tokens(tokens); + Descriptor( + &f.shim, + quote! { + inform(FUNCTION); + inform(#nargs); + #(<#argtys as WasmDescribe>::describe();)* + #inform_ret + }, + ).to_tokens(tokens); } } @@ -1055,15 +1059,15 @@ impl ToTokens for ast::Const { FloatLiteral(f) => { let f = Literal::f64_suffixed(f); quote!(#f) - }, + } SignedIntegerLiteral(i) => { let i = Literal::i64_suffixed(i); quote!(#i) - }, + } UnsignedIntegerLiteral(i) => { let i = Literal::u64_suffixed(i); quote!(#i) - }, + } Null => unimplemented!(), }; @@ -1088,11 +1092,15 @@ impl ToTokens for ast::Dictionary { for field in self.fields.iter() { field.to_tokens(&mut methods); } - let required_names = &self.fields.iter() + let required_names = &self + .fields + .iter() .filter(|f| f.required) .map(|f| &f.name) .collect::>(); - let required_types = &self.fields.iter() + let required_types = &self + .fields + .iter() .filter(|f| f.required) .map(|f| &f.ty) .collect::>(); @@ -1240,8 +1248,12 @@ impl<'a, T: ToTokens> ToTokens for Descriptor<'a, T> { lazy_static! { static ref DESCRIPTORS_EMITTED: Mutex> = Default::default(); } - if !DESCRIPTORS_EMITTED.lock().unwrap().insert(self.0.to_string()) { - return + if !DESCRIPTORS_EMITTED + .lock() + .unwrap() + .insert(self.0.to_string()) + { + return; } let name = Ident::new(&format!("__wbindgen_describe_{}", self.0), self.0.span()); diff --git a/crates/backend/src/defined.rs b/crates/backend/src/defined.rs index 35ebae370..b1a1442cb 100644 --- a/crates/backend/src/defined.rs +++ b/crates/backend/src/defined.rs @@ -210,7 +210,7 @@ impl ImportedTypes for syn::PathArguments { arg.imported_types(f); } } -//TOCHECK + //TOCHECK syn::PathArguments::Parenthesized(data) => { for input in data.inputs.iter() { input.imported_types(f); @@ -231,14 +231,13 @@ impl ImportedTypes for syn::GenericArgument { match self { syn::GenericArgument::Lifetime(_) => {} syn::GenericArgument::Type(ty) => ty.imported_types(f), - syn::GenericArgument::Binding(_) => {}, // TODO - syn::GenericArgument::Const(_) => {}, // TODO - syn::GenericArgument::Constraint(_) => {}, // TODO + syn::GenericArgument::Binding(_) => {} // TODO + syn::GenericArgument::Const(_) => {} // TODO + syn::GenericArgument::Constraint(_) => {} // TODO } } } - impl ImportedTypes for ast::ImportFunction { fn imported_types(&self, f: &mut F) where @@ -351,14 +350,15 @@ impl RemoveUndefinedImports for ast::Program { let mut dictionaries_to_remove = Vec::new(); for (i, dictionary) in self.dictionaries.iter_mut().enumerate() { - let num_required = |dict: &ast::Dictionary| { - dict.fields.iter().filter(|f| f.required).count() - }; + let num_required = + |dict: &ast::Dictionary| dict.fields.iter().filter(|f| f.required).count(); let before = num_required(dictionary); changed = dictionary.fields.remove_undefined_imports(is_defined) || changed; if before != num_required(dictionary) { - warn!("removing {} due to a required field being removed", - dictionary.name); + warn!( + "removing {} due to a required field being removed", + dictionary.name + ); dictionaries_to_remove.push(i); } } diff --git a/crates/backend/src/error.rs b/crates/backend/src/error.rs index 733c4c782..654c6093d 100644 --- a/crates/backend/src/error.rs +++ b/crates/backend/src/error.rs @@ -30,7 +30,7 @@ enum Repr { SynError(Error), Multi { diagnostics: Vec, - } + }, } impl Diagnostic { @@ -39,7 +39,7 @@ impl Diagnostic { inner: Repr::Single { text: text.into(), span: None, - } + }, } } @@ -48,7 +48,7 @@ impl Diagnostic { inner: Repr::Single { text: text.into(), span: extract_spans(node), - } + }, } } @@ -56,7 +56,9 @@ impl Diagnostic { if diagnostics.len() == 0 { Ok(()) } else { - Err(Diagnostic { inner: Repr::Multi { diagnostics } }) + Err(Diagnostic { + inner: Repr::Multi { diagnostics }, + }) } } @@ -72,7 +74,7 @@ impl Diagnostic { impl From for Diagnostic { fn from(err: Error) -> Diagnostic { - Diagnostic { + Diagnostic { inner: Repr::SynError(err), } } diff --git a/crates/backend/src/lib.rs b/crates/backend/src/lib.rs index 50a308e4f..bcc9d51e1 100755 --- a/crates/backend/src/lib.rs +++ b/crates/backend/src/lib.rs @@ -1,5 +1,8 @@ #![recursion_limit = "256"] -#![cfg_attr(feature = "extra-traits", deny(missing_debug_implementations))] +#![cfg_attr( + feature = "extra-traits", + deny(missing_debug_implementations) +)] #![doc(html_root_url = "https://docs.rs/wasm-bindgen-backend/0.2")] #[macro_use] diff --git a/crates/backend/src/util.rs b/crates/backend/src/util.rs index fcfb9e9ce..0495f4c90 100644 --- a/crates/backend/src/util.rs +++ b/crates/backend/src/util.rs @@ -71,8 +71,7 @@ where .map(|i| syn::PathSegment { ident: i, arguments: syn::PathArguments::None, - }) - .collect(); + }).collect(); syn::TypePath { qself: None, diff --git a/crates/cli-support/src/descriptor.rs b/crates/cli-support/src/descriptor.rs index 3b8d2f01a..5c116cc1c 100644 --- a/crates/cli-support/src/descriptor.rs +++ b/crates/cli-support/src/descriptor.rs @@ -163,20 +163,14 @@ impl Descriptor { pub fn is_wasm_native(&self) -> bool { match *self { - Descriptor::I32 - | Descriptor::U32 - | Descriptor::F32 - | Descriptor::F64 => true, + Descriptor::I32 | Descriptor::U32 | Descriptor::F32 | Descriptor::F64 => true, _ => return false, } } pub fn is_abi_as_u32(&self) -> bool { match *self { - Descriptor::I8 - | Descriptor::U8 - | Descriptor::I16 - | Descriptor::U16 => true, + Descriptor::I8 | Descriptor::U8 | Descriptor::I16 | Descriptor::U16 => true, _ => return false, } } @@ -223,12 +217,10 @@ impl Descriptor { Descriptor::Slice(ref d) => &**d, _ => return None, }, - Descriptor::Clamped(ref d) => { - match d.vector_kind()? { - VectorKind::U8 => return Some(VectorKind::ClampedU8), - _ => return None, - } - } + Descriptor::Clamped(ref d) => match d.vector_kind()? { + VectorKind::U8 => return Some(VectorKind::ClampedU8), + _ => return None, + }, _ => return None, }; match *inner { diff --git a/crates/cli-support/src/js/closures.rs b/crates/cli-support/src/js/closures.rs index 54a354061..77103c165 100644 --- a/crates/cli-support/src/js/closures.rs +++ b/crates/cli-support/src/js/closures.rs @@ -16,8 +16,8 @@ use failure::Error; use parity_wasm::elements::*; use descriptor::Descriptor; -use js::Context; use js::js2rust::Js2Rust; +use js::Context; pub fn rewrite(input: &mut Context) -> Result<(), Error> { let info = ClosureDescriptors::new(input); @@ -29,7 +29,7 @@ pub fn rewrite(input: &mut Context) -> Result<(), Error> { info.code_idx_to_descriptor.len(), ); if info.element_removal_list.len() == 0 { - return Ok(()) + return Ok(()); } // Make sure the names section is available in the wasm module because we'll @@ -39,7 +39,8 @@ pub fn rewrite(input: &mut Context) -> Result<(), Error> { input.parse_wasm_names(); Remap { code_idx_to_descriptor: &info.code_idx_to_descriptor, - old_num_imports: input.module + old_num_imports: input + .module .import_section() .map(|s| s.functions()) .unwrap_or(0) as u32, @@ -90,7 +91,9 @@ impl ClosureDescriptors { Some(i) => i, None => return Default::default(), }; - let imports = input.module.import_section() + let imports = input + .module + .import_section() .map(|s| s.functions()) .unwrap_or(0); let mut ret = ClosureDescriptors::default(); @@ -100,24 +103,18 @@ impl ClosureDescriptors { None => return Default::default(), }; for (i, function) in code.bodies().iter().enumerate() { - let call_pos = function.code() - .elements() - .iter() - .position(|i| { - match i { - Instruction::Call(i) => *i == wbindgen_describe_closure, - _ => false, - } - }); + let call_pos = function.code().elements().iter().position(|i| match i { + Instruction::Call(i) => *i == wbindgen_describe_closure, + _ => false, + }); let call_pos = match call_pos { Some(i) => i, None => continue, }; - let descriptor = input.interpreter.interpret_closure_descriptor( - i, - input.module, - &mut ret.element_removal_list, - ).unwrap(); + let descriptor = input + .interpreter + .interpret_closure_descriptor(i, input.module, &mut ret.element_removal_list) + .unwrap(); // `new_idx` is the function-space index of the function that we'll // be injecting. Calls to the code function `i` will instead be // rewritten to calls to `new_idx`, which is an import that we'll @@ -132,7 +129,7 @@ impl ClosureDescriptors { }, ); } - return ret + return ret; } /// Here we remove elements from the function table. All our descriptor @@ -165,7 +162,7 @@ impl ClosureDescriptors { // If we keep this entry, then keep going if !to_remove.contains(&j) { current.push(*idx); - continue + continue; } // If we have members of `current` then we save off a section @@ -173,10 +170,8 @@ impl ClosureDescriptors { let next_offset = offset + (current.len() as i32) + 1; if current.len() > 0 { let members = mem::replace(&mut current, Vec::new()); - let offset = InitExpr::new(vec![ - Instruction::I32Const(offset), - Instruction::End, - ]); + let offset = + InitExpr::new(vec![Instruction::I32Const(offset), Instruction::End]); let new_entry = ElementSegment::new(0, offset, members); elements.entries_mut().push(new_entry); } @@ -184,10 +179,7 @@ impl ClosureDescriptors { } // Any remaining function table entries get pushed at the end. if current.len() > 0 { - let offset = InitExpr::new(vec![ - Instruction::I32Const(offset), - Instruction::End, - ]); + let offset = InitExpr::new(vec![Instruction::I32Const(offset), Instruction::End]); let new_entry = ElementSegment::new(0, offset, current); elements.entries_mut().push(new_entry); } @@ -211,9 +203,8 @@ impl ClosureDescriptors { // signature of our `#[inline(never)]` functions. Find the type // signature index so we can assign it below. let type_idx = { - let kind = input.module.import_section() - .unwrap() - .entries()[wbindgen_describe_closure as usize] + let kind = input.module.import_section().unwrap().entries() + [wbindgen_describe_closure as usize] .external(); match kind { External::Function(i) => *i, @@ -268,7 +259,9 @@ impl ClosureDescriptors { import_name, External::Function(type_idx as u32), ); - input.module.import_section_mut() + input + .module + .import_section_mut() .unwrap() .entries_mut() .push(new_import); @@ -313,7 +306,9 @@ impl<'a> Remap<'a> { Section::Export(e) => self.remap_export_section(e), Section::Element(e) => self.remap_element_section(e), Section::Code(e) => self.remap_code_section(e), - Section::Start(i) => { self.remap_idx(i); } + Section::Start(i) => { + self.remap_idx(i); + } Section::Name(n) => self.remap_name_section(n), _ => {} } @@ -328,10 +323,11 @@ impl<'a> Remap<'a> { fn remap_export_entry(&self, entry: &mut ExportEntry) { match entry.internal_mut() { - Internal::Function(i) => { self.remap_idx(i); } + Internal::Function(i) => { + self.remap_idx(i); + } _ => {} } - } fn remap_element_section(&self, section: &mut ElementSection) { @@ -364,7 +360,9 @@ impl<'a> Remap<'a> { fn remap_instruction(&self, instr: &mut Instruction) { match instr { - Instruction::Call(i) => { self.remap_idx(i); } + Instruction::Call(i) => { + self.remap_idx(i); + } _ => {} } } @@ -403,7 +401,7 @@ impl<'a> Remap<'a> { // If this was an imported function we didn't reorder those, so nothing // to do. if *idx < self.old_num_imports { - return false + return false; } // ... otherwise we're injecting a number of new imports, so offset // everything. diff --git a/crates/cli-support/src/js/js2rust.rs b/crates/cli-support/src/js/js2rust.rs index e5153cd52..d04ffe928 100644 --- a/crates/cli-support/src/js/js2rust.rs +++ b/crates/cli-support/src/js/js2rust.rs @@ -197,10 +197,8 @@ impl<'a, 'b> Js2Rust<'a, 'b> { self.cx.expose_add_heap_object(); if optional { self.cx.expose_is_like_none(); - self.rust_arguments.push(format!( - "isLikeNone({0}) ? 0 : addHeapObject({0})", - name, - )); + self.rust_arguments + .push(format!("isLikeNone({0}) ? 0 : addHeapObject({0})", name,)); } else { self.rust_arguments.push(format!("addHeapObject({})", name)); } @@ -225,7 +223,8 @@ impl<'a, 'b> Js2Rust<'a, 'b> { } self.rust_arguments.push(format!("!isLikeNone({0})", name)); - self.rust_arguments.push(format!("isLikeNone({0}) ? 0 : {0}", name)); + self.rust_arguments + .push(format!("isLikeNone({0}) ? 0 : {0}", name)); return Ok(self); } @@ -245,7 +244,8 @@ impl<'a, 'b> Js2Rust<'a, 'b> { )); } - self.rust_arguments.push(format!("isLikeNone({0}) ? 0xFFFFFF : {0}", name)); + self.rust_arguments + .push(format!("isLikeNone({0}) ? 0xFFFFFF : {0}", name)); return Ok(self); } @@ -278,7 +278,8 @@ impl<'a, 'b> Js2Rust<'a, 'b> { match *arg { Descriptor::Boolean => { self.cx.expose_is_like_none(); - self.js_arguments.push((name.clone(), "boolean".to_string())); + self.js_arguments + .push((name.clone(), "boolean".to_string())); if self.cx.config.debug { self.cx.expose_assert_bool(); self.prelude(&format!( @@ -290,17 +291,22 @@ impl<'a, 'b> Js2Rust<'a, 'b> { name, )); } - self.rust_arguments.push(format!("isLikeNone({0}) ? 0xFFFFFF : {0} ? 1 : 0", name)); + self.rust_arguments + .push(format!("isLikeNone({0}) ? 0xFFFFFF : {0} ? 1 : 0", name)); return Ok(self); - }, + } Descriptor::Char => { self.cx.expose_is_like_none(); self.js_arguments.push((name.clone(), "string".to_string())); self.rust_arguments.push(format!("!isLikeNone({0})", name)); - self.rust_arguments.push(format!("isLikeNone({0}) ? 0 : {0}.codePointAt(0)", name)); + self.rust_arguments + .push(format!("isLikeNone({0}) ? 0 : {0}.codePointAt(0)", name)); return Ok(self); - }, - _ => bail!("unsupported optional argument type for calling Rust function from JS: {:?}", arg), + } + _ => bail!( + "unsupported optional argument type for calling Rust function from JS: {:?}", + arg + ), }; } @@ -401,7 +407,10 @@ impl<'a, 'b> Js2Rust<'a, 'b> { self.js_arguments.push((name.clone(), "string".to_string())); self.rust_arguments.push(format!("{}.codePointAt(0)", name)) } - _ => bail!("unsupported argument type for calling Rust function from JS: {:?}", arg), + _ => bail!( + "unsupported argument type for calling Rust function from JS: {:?}", + arg + ), } Ok(self) } @@ -412,14 +421,15 @@ impl<'a, 'b> Js2Rust<'a, 'b> { Some(class) if class == name => { self.ret_expr = format!("this.ptr = RET;"); if self.cx.config.weak_refs { - self.ret_expr.push_str(&format!("\ + self.ret_expr.push_str(&format!( + "\ addCleanup(this, this.ptr, free{}); - ", name)); + ", + name + )); } } - Some(class) => { - bail!("constructor for `{}` cannot return `{}`", class, name) - } + Some(class) => bail!("constructor for `{}` cannot return `{}`", class, name), None => { self.ret_ty = name.to_string(); self.cx.require_class_wrap(name); @@ -465,7 +475,11 @@ impl<'a, 'b> Js2Rust<'a, 'b> { ", f, ty.size(), - guard = if optional { "if (rustptr === 0) return;" } else { "" }, + guard = if optional { + "if (rustptr === 0) return;" + } else { + "" + }, ); return Ok(self); } @@ -559,7 +573,7 @@ impl<'a, 'b> Js2Rust<'a, 'b> { return ret === 0xFFFFFF ? undefined : ret !== 0; ".to_string(); return Ok(self); - }, + } Descriptor::Char => { self.ret_ty = "string".to_string(); self.cx.expose_global_argument_ptr()?; @@ -573,8 +587,11 @@ impl<'a, 'b> Js2Rust<'a, 'b> { return present === 0 ? undefined : String.fromCodePoint(value); ".to_string(); return Ok(self); - }, - _ => bail!("unsupported optional return type for calling Rust function from JS: {:?}", ty), + } + _ => bail!( + "unsupported optional return type for calling Rust function from JS: {:?}", + ty + ), }; } @@ -633,15 +650,20 @@ impl<'a, 'b> Js2Rust<'a, 'b> { self.ret_ty = "string".to_string(); self.ret_expr = format!("return String.fromCodePoint(RET);") } - _ => bail!("unsupported return type for calling Rust function from JS: {:?}", ty), + _ => bail!( + "unsupported return type for calling Rust function from JS: {:?}", + ty + ), } Ok(self) } pub fn js_doc_comments(&self) -> String { - let mut ret: String = self.js_arguments.iter().map(|a| { - format!("@param {{{}}} {}\n", a.1, a.0) - }).collect(); + let mut ret: String = self + .js_arguments + .iter() + .map(|a| format!("@param {{{}}} {}\n", a.1, a.0)) + .collect(); ret.push_str(&format!("@returns {{{}}}", self.ret_ty)); ret } diff --git a/crates/cli-support/src/js/mod.rs b/crates/cli-support/src/js/mod.rs index fcbb53781..0b4fedd07 100644 --- a/crates/cli-support/src/js/mod.rs +++ b/crates/cli-support/src/js/mod.rs @@ -390,7 +390,8 @@ impl<'a> Context<'a> { function() {{ return addHeapObject({}); }} - ", mem + ", + mem )) })?; @@ -549,7 +550,7 @@ impl<'a> Context<'a> { constructor() { throw new Error('cannot invoke `new` directly'); } - " + ", ); } @@ -705,8 +706,7 @@ impl<'a> Context<'a> { .filter_map(|s| match *s { Section::Import(ref mut s) => Some(s), _ => None, - }) - .flat_map(|s| s.entries_mut()); + }).flat_map(|s| s.entries_mut()); for import in imports { if import.module() == "__wbindgen_placeholder__" { @@ -726,7 +726,7 @@ impl<'a> Context<'a> { import.module_mut().truncate(0); import.module_mut().push_str("./"); import.module_mut().push_str(module_name); - continue + continue; } let renamed_import = format!("__wbindgen_{}", import.field()); @@ -817,7 +817,9 @@ impl<'a> Context<'a> { slab_next = idx; }} ", - validate_owned, INITIAL_SLAB_VALUES.len(), dec_ref + validate_owned, + INITIAL_SLAB_VALUES.len(), + dec_ref )); } @@ -848,7 +850,8 @@ impl<'a> Context<'a> { if !self.exposed_globals.insert("slab") { return; } - let initial_values = INITIAL_SLAB_VALUES.iter() + let initial_values = INITIAL_SLAB_VALUES + .iter() .map(|s| format!("{{ obj: {} }}", s)) .collect::>(); self.global(&format!("const slab = [{}];", initial_values.join(", "))); @@ -1013,7 +1016,8 @@ impl<'a> Context<'a> { self.require_internal_export("__wbindgen_malloc")?; self.expose_uint32_memory(); self.expose_add_heap_object(); - self.global(" + self.global( + " function passArrayJsValueToWasm(array) { const ptr = wasm.__wbindgen_malloc(array.length * 4); const mem = getUint32Memory(); @@ -1023,7 +1027,8 @@ impl<'a> Context<'a> { return [ptr, array.length]; } - "); + ", + ); Ok(()) } @@ -1126,7 +1131,8 @@ impl<'a> Context<'a> { // non-shared mode there's no need to copy the data except for the // string itself. self.memory(); // set self.memory_init - let is_shared = self.module + let is_shared = self + .module .memory_section() .map(|s| s.entries()[0].limits().shared()) .unwrap_or(match &self.memory_init { @@ -1135,11 +1141,14 @@ impl<'a> Context<'a> { }); let method = if is_shared { "slice" } else { "subarray" }; - self.global(&format!(" + self.global(&format!( + " function getStringFromWasm(ptr, len) {{ return cachedDecoder.decode(getUint8Memory().{}(ptr, ptr + len)); }} - ", method)); + ", + method + )); } fn expose_get_array_js_value_from_wasm(&mut self) { @@ -1646,18 +1655,20 @@ impl<'a> Context<'a> { fn expose_is_like_none(&mut self) { if !self.exposed_globals.insert("is_like_none") { - return + return; } - self.global(" + self.global( + " function isLikeNone(x) { return x === undefined || x === null; } - "); + ", + ); } fn expose_cleanup_groups(&mut self) { if !self.exposed_globals.insert("cleanup_groups") { - return + return; } self.global( " @@ -1668,7 +1679,7 @@ impl<'a> Context<'a> { const ref = CLEANUPS.makeRef(obj, () => free(ptr)); CLEANUPS_MAP.set(ptr, ref); } - " + ", ); } @@ -1719,17 +1730,16 @@ impl<'a> Context<'a> { return "wasm.memory"; } - let (entry, mem) = self.module.import_section() + let (entry, mem) = self + .module + .import_section() .expect("must import memory") .entries() .iter() - .filter_map(|i| { - match i.external() { - External::Memory(m) => Some((i, m)), - _ => None, - } - }) - .next() + .filter_map(|i| match i.external() { + External::Memory(m) => Some((i, m)), + _ => None, + }).next() .expect("must import memory"); assert_eq!(entry.module(), "env"); assert_eq!(entry.field(), "memory"); @@ -1822,8 +1832,11 @@ impl<'a, 'b> SubContext<'a, 'b> { }; let (js, ts, js_doc) = Js2Rust::new(function_name, self.cx) .method(export.method, export.consumed) - .constructor(if export.is_constructor { Some(class_name) } else { None }) - .process(descriptor.unwrap_function())? + .constructor(if export.is_constructor { + Some(class_name) + } else { + None + }).process(descriptor.unwrap_function())? .finish("", &format!("wasm.{}", wasm_name)); let class = self @@ -1837,8 +1850,7 @@ impl<'a, 'b> SubContext<'a, 'b> { if export.is_constructor { if class.has_constructor { - bail!("found duplicate constructor `{}`", - export.function.name); + bail!("found duplicate constructor `{}`", export.function.name); } class.has_constructor = true; } else if !export.method { @@ -1871,10 +1883,7 @@ impl<'a, 'b> SubContext<'a, 'b> { } shared::ImportKind::Type(ref ty) => { self.generate_import_type(import, ty).with_context(|_| { - format!( - "failed to generate bindings for JS import `{}`", - ty.name, - ) + format!("failed to generate bindings for JS import `{}`", ty.name,) })?; } shared::ImportKind::Enum(_) => {} @@ -1890,7 +1899,7 @@ impl<'a, 'b> SubContext<'a, 'b> { // The same static can be imported in multiple locations, so only // generate bindings once for it. if !self.cx.imported_statics.insert(import.shim.clone()) { - return Ok(()) + return Ok(()); } // TODO: should support more types to import here @@ -1962,7 +1971,7 @@ impl<'a, 'b> SubContext<'a, 'b> { format!("{}_target", import.shim) } else { name - }) + }); } }; @@ -2052,9 +2061,15 @@ impl<'a, 'b> SubContext<'a, 'b> { class, location, s, binding, ) } - shared::OperationKind::IndexingGetter => panic!("indexing getter should be structural"), - shared::OperationKind::IndexingSetter => panic!("indexing setter should be structural"), - shared::OperationKind::IndexingDeleter => panic!("indexing deleter should be structural"), + shared::OperationKind::IndexingGetter => { + panic!("indexing getter should be structural") + } + shared::OperationKind::IndexingSetter => { + panic!("indexing setter should be structural") + } + shared::OperationKind::IndexingDeleter => { + panic!("indexing deleter should be structural") + } } }; @@ -2090,7 +2105,8 @@ impl<'a, 'b> SubContext<'a, 'b> { } let name = self.import_name(info, &import.name)?; self.cx.expose_get_object(); - let body = format!(" + let body = format!( + " function(idx) {{ return getObject(idx) instanceof {} ? 1 : 0; }} @@ -2139,10 +2155,7 @@ impl<'a, 'b> SubContext<'a, 'b> { // Figure out what identifier we're importing from the module. If we've // got a namespace we use that, otherwise it's the name specified above. - let name_to_import = import.js_namespace - .as_ref() - .map(|s| &**s) - .unwrap_or(item); + let name_to_import = import.js_namespace.as_ref().map(|s| &**s).unwrap_or(item); // Here's where it's a bit tricky. We need to make sure that importing // the same identifier from two different modules works, and they're @@ -2158,7 +2171,10 @@ impl<'a, 'b> SubContext<'a, 'b> { let use_node_require = self.cx.use_node_require(); let imported_identifiers = &mut self.cx.imported_identifiers; let imports = &mut self.cx.imports; - let identifier = self.cx.imported_names.entry(import.module.clone()) + let identifier = self + .cx + .imported_names + .entry(import.module.clone()) .or_insert_with(Default::default) .entry(name_to_import.to_string()) .or_insert_with(|| { @@ -2170,10 +2186,7 @@ impl<'a, 'b> SubContext<'a, 'b> { name, module, name_to_import )); } else if name_to_import == name { - imports.push_str(&format!( - "import {{ {} }} from '{}';\n", - name, module - )); + imports.push_str(&format!("import {{ {} }} from '{}';\n", name, module)); } else { imports.push_str(&format!( "import {{ {} as {} }} from '{}';\n", diff --git a/crates/cli-support/src/js/rust2js.rs b/crates/cli-support/src/js/rust2js.rs index 0f839725d..668b31e10 100644 --- a/crates/cli-support/src/js/rust2js.rs +++ b/crates/cli-support/src/js/rust2js.rs @@ -109,7 +109,11 @@ impl<'a, 'b> Rust2Js<'a, 'b> { abi, abi2, func = f, - prefix = if optional { format!("{} == 0 ? undefined : ", abi) } else { String::new() }, + prefix = if optional { + format!("{} == 0 ? undefined : ", abi) + } else { + String::new() + }, )); if !arg.is_by_ref() && !arg.is_clamped_by_ref() { @@ -123,9 +127,12 @@ impl<'a, 'b> Rust2Js<'a, 'b> { abi, abi2, size = ty.size(), - start = if optional { format!("if ({} !== 0) {{", abi) } else { String::new() }, + start = if optional { + format!("if ({} !== 0) {{", abi) + } else { + String::new() + }, end = if optional { "}" } else { "" }, - )); self.cx.require_internal_export("__wbindgen_free")?; } @@ -138,11 +145,11 @@ impl<'a, 'b> Rust2Js<'a, 'b> { if arg.is_anyref() { self.cx.expose_take_object(); self.js_arguments.push(format!("takeObject({})", abi)); - return Ok(()) + return Ok(()); } else if arg.is_ref_anyref() { self.cx.expose_get_object(); self.js_arguments.push(format!("getObject({})", abi)); - return Ok(()) + return Ok(()); } if optional { @@ -153,12 +160,13 @@ impl<'a, 'b> Rust2Js<'a, 'b> { value = value, present = abi, )); - return Ok(()) + return Ok(()); } if arg.is_abi_as_u32() { - self.js_arguments.push(format!("{0} === 0xFFFFFF ? undefined : {0}", abi)); - return Ok(()) + self.js_arguments + .push(format!("{0} === 0xFFFFFF ? undefined : {0}", abi)); + return Ok(()); } if let Some(signed) = arg.get_64() { @@ -189,9 +197,10 @@ impl<'a, 'b> Rust2Js<'a, 'b> { match *arg { Descriptor::Boolean => { - self.js_arguments.push(format!("{0} === 0xFFFFFF ? undefined : {0} !== 0", abi)); - return Ok(()) - }, + self.js_arguments + .push(format!("{0} === 0xFFFFFF ? undefined : {0} !== 0", abi)); + return Ok(()); + } Descriptor::Char => { let value = self.shim_argument(); self.js_arguments.push(format!( @@ -199,9 +208,12 @@ impl<'a, 'b> Rust2Js<'a, 'b> { value = value, present = abi, )); - return Ok(()) - }, - _ => bail!("unsupported optional argument type for calling JS function from Rust: {:?}", arg), + return Ok(()); + } + _ => bail!( + "unsupported optional argument type for calling JS function from Rust: {:?}", + arg + ), }; } @@ -280,7 +292,10 @@ impl<'a, 'b> Rust2Js<'a, 'b> { ref d if d.is_number() => abi, Descriptor::Boolean => format!("{} !== 0", abi), Descriptor::Char => format!("String.fromCodePoint({})", abi), - _ => bail!("unsupported argument type for calling JS function from Rust: {:?}", arg), + _ => bail!( + "unsupported argument type for calling JS function from Rust: {:?}", + arg + ), }; self.js_arguments.push(invoc_arg); Ok(()) @@ -318,8 +333,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> { mem[ret / 4] = retptr; mem[ret / 4 + 1] = retlen; ", - prelude, - expr + prelude, expr ); return Ok(()); } @@ -334,7 +348,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> { } else { self.ret_expr = "return addHeapObject(JS);".to_string() } - return Ok(()) + return Ok(()); } if optional { if ty.is_wasm_native() { @@ -411,7 +425,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> { return isLikeNone(val) ? 0xFFFFFF : val ? 1 : 0; ".to_string(); return Ok(()); - }, + } Descriptor::Char => { self.cx.expose_is_like_none(); self.cx.expose_uint32_memory(); @@ -422,8 +436,11 @@ impl<'a, 'b> Rust2Js<'a, 'b> { getUint32Memory()[ret / 4 + 1] = isLikeNone(val) ? 0 : val.codePointAt(0); ".to_string(); return Ok(()); - }, - _ => bail!("unsupported optional return type for calling JS function from Rust: {:?}", ty), + } + _ => bail!( + "unsupported optional return type for calling JS function from Rust: {:?}", + ty + ), }; } if ty.is_number() { @@ -474,7 +491,10 @@ impl<'a, 'b> Rust2Js<'a, 'b> { self.ret_expr = match *ty { Descriptor::Boolean => "return JS ? 1 : 0;".to_string(), Descriptor::Char => "return JS.codePointAt(0);".to_string(), - _ => bail!("unsupported return type for calling JS function from Rust: {:?}", ty), + _ => bail!( + "unsupported return type for calling JS function from Rust: {:?}", + ty + ), }; Ok(()) } @@ -494,7 +514,9 @@ impl<'a, 'b> Rust2Js<'a, 'b> { let mut invoc = if self.variadic { if self.js_arguments.is_empty() { - return Err(failure::err_msg("a function with no arguments cannot be variadic")); + return Err(failure::err_msg( + "a function with no arguments cannot be variadic", + )); } let last_arg = self.js_arguments.len() - 1; // check implies >= 0 if self.js_arguments.len() != 1 { @@ -505,16 +527,12 @@ impl<'a, 'b> Rust2Js<'a, 'b> { invoc, self.js_arguments[..last_arg].join(", "), self.js_arguments[last_arg], - ) + ), ) } else { self.ret_expr.replace( "JS", - &format!( - "{}(...{})", - invoc, - self.js_arguments[last_arg], - ) + &format!("{}(...{})", invoc, self.js_arguments[last_arg],), ) } } else { diff --git a/crates/cli-support/src/lib.rs b/crates/cli-support/src/lib.rs index 75b3291cb..a5441f260 100644 --- a/crates/cli-support/src/lib.rs +++ b/crates/cli-support/src/lib.rs @@ -1,8 +1,8 @@ #![doc(html_root_url = "https://docs.rs/wasm-bindgen-cli-support/0.2")] extern crate parity_wasm; -extern crate wasm_bindgen_shared as shared; extern crate serde_json; +extern crate wasm_bindgen_shared as shared; extern crate wasm_gc; #[macro_use] extern crate failure; @@ -90,7 +90,7 @@ impl Bindgen { if let Some(module) = (&mut module as &mut Any).downcast_mut::() { let blank = Module::new(Vec::new()); self.input = Input::Module(mem::replace(module, blank), name); - return self + return self; } self.input = Input::Bytes(into_bytes(module), name); @@ -213,7 +213,11 @@ impl Bindgen { cx.finalize(stem)? }; - let extension = if self.nodejs_experimental_modules { "mjs" } else { "js" }; + let extension = if self.nodejs_experimental_modules { + "mjs" + } else { + "js" + }; let js_path = out_dir.join(stem).with_extension(extension); fs::write(&js_path, reset_indentation(&js)) .with_context(|_| format!("failed to write `{}`", js_path.display()))?; @@ -251,12 +255,12 @@ impl Bindgen { if self.nodejs_experimental_modules { for (i, module) in imports.iter().enumerate() { - shim.push_str(&format!("import * as import{} from '{}';\n", - i, module)); + 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!(" + shim.push_str(&format!( + " import * as path from 'path'; import * as fs from 'fs'; import * as url from 'url'; @@ -267,12 +271,17 @@ impl Bindgen { file = file.substring(1); }} const bytes = fs.readFileSync(path.join(file, '{}')); - ", path.file_name().unwrap().to_str().unwrap())); + ", + path.file_name().unwrap().to_str().unwrap() + )); } else { - shim.push_str(&format!(" + shim.push_str(&format!( + " const path = require('path').join(__dirname, '{}'); const bytes = require('fs').readFileSync(path); - ", path.file_name().unwrap().to_str().unwrap())); + ", + path.file_name().unwrap().to_str().unwrap() + )); } shim.push_str("let imports = {};\n"); for (i, module) in imports.iter().enumerate() { @@ -387,7 +396,11 @@ fn reset_indentation(s: &str) -> String { if line.starts_with('}') || (line.ends_with('}') && !line.starts_with('*')) { indent = indent.saturating_sub(1); } - let extra = if line.starts_with(':') || line.starts_with('?') { 1 } else { 0 }; + let extra = if line.starts_with(':') || line.starts_with('?') { + 1 + } else { + 0 + }; if !line.is_empty() { for _ in 0..indent + extra { dst.push_str(" "); @@ -399,5 +412,5 @@ fn reset_indentation(s: &str) -> String { indent += 1; } } - return dst + return dst; } diff --git a/crates/cli/src/bin/wasm-bindgen-test-runner/headless.rs b/crates/cli/src/bin/wasm-bindgen-test-runner/headless.rs index ea826c369..4648e7174 100644 --- a/crates/cli/src/bin/wasm-bindgen-test-runner/headless.rs +++ b/crates/cli/src/bin/wasm-bindgen-test-runner/headless.rs @@ -1,14 +1,14 @@ use std::env; use std::io::{self, Read}; use std::net::{SocketAddr, TcpListener, TcpStream}; -use std::path::{PathBuf, Path}; +use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::thread; -use std::time::{Instant, Duration}; +use std::time::{Duration, Instant}; use curl::easy::Easy; -use failure::{ResultExt, Error}; -use serde::{Serialize, Deserialize}; +use failure::{Error, ResultExt}; +use serde::{Deserialize, Serialize}; use serde_json; use shell::Shell; @@ -22,9 +22,11 @@ use shell::Shell; /// will return an error if some tests failed. pub fn run(server: &SocketAddr, shell: &Shell) -> Result<(), Error> { let (driver, args) = Driver::find()?; - println!("Running headless tests in {} with `{}`", - driver.browser(), - driver.path().display()); + println!( + "Running headless tests in {} with `{}`", + driver.browser(), + driver.path().display() + ); // Allow tests to run in parallel (in theory) by finding any open port // available for our driver. We can't bind the port for the driver, but @@ -47,7 +49,7 @@ pub fn run(server: &SocketAddr, shell: &Shell) -> Result<(), Error> { while start.elapsed() < max { if TcpStream::connect(&driver_addr).is_ok() { bound = true; - break + break; } thread::sleep(Duration::from_millis(100)); } @@ -94,7 +96,7 @@ pub fn run(server: &SocketAddr, shell: &Shell) -> Result<(), Error> { let max = Duration::new(20, 0); while start.elapsed() < max { if client.text(&id, &output)?.contains("test result: ") { - break + break; } thread::sleep(Duration::from_millis(100)); } @@ -174,30 +176,29 @@ impl Driver { Some(path) => path, None => continue, }; - return Ok((ctor(path.into()), env_args(driver))) + return Ok((ctor(path.into()), env_args(driver))); } // Next, check PATH. If we can find any supported driver, use that by // default. for path in env::split_paths(&env::var_os("PATH").unwrap_or_default()) { - let found = drivers - .iter() - .find(|(name, _)| { - path.join(name) - .with_extension(env::consts::EXE_EXTENSION) - .exists() - }); + let found = drivers.iter().find(|(name, _)| { + path.join(name) + .with_extension(env::consts::EXE_EXTENSION) + .exists() + }); let (name, ctor) = match found { Some(p) => p, None => continue, }; - return Ok((ctor(name.into()), env_args(name))) + return Ok((ctor(name.into()), env_args(name))); } // TODO: download an appropriate driver? How to know which one to // download? - bail!("\ + bail!( + "\ failed to find a suitable WebDriver binary to drive headless testing; to configure the location of the webdriver binary you can use environment variables like `GECKODRIVER=/path/to/geckodriver` or make sure that the binary @@ -217,7 +218,8 @@ visit in a web browser, and headless testing should not be used. If you're still having difficulty resolving this error, please feel free to open an issue against rustwasm/wasm-bindgen! - ") + " + ) } fn path(&self) -> &Path { @@ -320,8 +322,7 @@ impl Client { fn close_window(&mut self, id: &str) -> Result<(), Error> { #[derive(Deserialize)] - struct Response { - } + struct Response {} let x: Response = self.delete(&format!("/session/{}/window", id))?; drop(x); Ok(()) @@ -333,8 +334,7 @@ impl Client { url: String, } #[derive(Deserialize)] - struct Response { - } + struct Response {} let request = Request { url: url.to_string(), @@ -367,10 +367,10 @@ impl Client { value: selector.to_string(), }; let x: Response = self.post(&format!("/session/{}/element", id), &request)?; - Ok(x.value.gecko_reference - .or(x.value.safari_reference) - .ok_or(format_err!("failed to find element reference in response"))?) - + Ok(x.value + .gecko_reference + .or(x.value.safari_reference) + .ok_or(format_err!("failed to find element reference in response"))?) } fn text(&mut self, id: &str, element: &str) -> Result { @@ -383,7 +383,8 @@ impl Client { } fn get(&mut self, path: &str) -> Result - where U: for<'a> Deserialize<'a>, + where + U: for<'a> Deserialize<'a>, { debug!("GET {}", path); let result = self.doit(path, Method::Get)?; @@ -391,8 +392,9 @@ impl Client { } fn post(&mut self, path: &str, data: &T) -> Result - where T: Serialize, - U: for<'a> Deserialize<'a>, + where + T: Serialize, + U: for<'a> Deserialize<'a>, { let input = serde_json::to_string(data)?; debug!("POST {} {}", path, input); @@ -401,7 +403,8 @@ impl Client { } fn delete(&mut self, path: &str) -> Result - where U: for<'a> Deserialize<'a>, + where + U: for<'a> Deserialize<'a>, { debug!("DELETE {}", path); let result = self.doit(path, Method::Delete)?; @@ -431,7 +434,11 @@ impl Client { } let result = String::from_utf8_lossy(&result); if self.handle.response_code()? != 200 { - bail!("non-200 response code: {}\n{}", self.handle.response_code()?, result); + bail!( + "non-200 response code: {}\n{}", + self.handle.response_code()?, + result + ); } debug!("got: {}", result); Ok(result.into_owned()) @@ -475,14 +482,16 @@ struct BackgroundChild<'a> { } impl<'a> BackgroundChild<'a> { - fn spawn(path: &Path, cmd: &mut Command, shell: &'a Shell) - -> Result, Error> - { - cmd - .stdout(Stdio::piped()) + fn spawn( + path: &Path, + cmd: &mut Command, + shell: &'a Shell, + ) -> Result, Error> { + cmd.stdout(Stdio::piped()) .stderr(Stdio::piped()) .stdin(Stdio::null()); - let mut child = cmd.spawn() + let mut child = cmd + .spawn() .context(format!("failed to spawn {:?} binary", path))?; let mut stdout = child.stdout.take().unwrap(); let mut stderr = child.stderr.take().unwrap(); @@ -503,7 +512,7 @@ impl<'a> Drop for BackgroundChild<'a> { self.child.kill().unwrap(); let status = self.child.wait().unwrap(); if !self.print_stdio_on_drop { - return + return; } self.shell.clear(); diff --git a/crates/cli/src/bin/wasm-bindgen-test-runner/main.rs b/crates/cli/src/bin/wasm-bindgen-test-runner/main.rs index e03dc8d7d..bf1eaea61 100644 --- a/crates/cli/src/bin/wasm-bindgen-test-runner/main.rs +++ b/crates/cli/src/bin/wasm-bindgen-test-runner/main.rs @@ -32,8 +32,8 @@ use std::path::PathBuf; use std::process; use std::thread; -use failure::{ResultExt, Error}; -use parity_wasm::elements::{Module, Deserialize, Section}; +use failure::{Error, ResultExt}; +use parity_wasm::elements::{Deserialize, Module, Section}; use wasm_bindgen_cli_support::Bindgen; mod headless; @@ -67,33 +67,29 @@ fn rmain() -> Result<(), Error> { // Assume a cargo-like directory layout and generate output at // `target/wasm32-unknown-unknown/wbg-tmp/...` - let tmpdir = wasm_file_to_test.parent() // chop off file name - .and_then(|p| p.parent()) // chop off `deps` - .and_then(|p| p.parent()) // chop off `debug` + let tmpdir = wasm_file_to_test + .parent() // chop off file name + .and_then(|p| p.parent()) // chop off `deps` + .and_then(|p| p.parent()) // chop off `debug` .map(|p| p.join("wbg-tmp")) - .ok_or_else(|| { - format_err!("file to test doesn't follow the expected Cargo conventions") - })?; + .ok_or_else(|| format_err!("file to test doesn't follow the expected Cargo conventions"))?; // Make sure there's no stale state from before drop(fs::remove_dir_all(&tmpdir)); - fs::create_dir(&tmpdir) - .context("creating temporary directory")?; + fs::create_dir(&tmpdir).context("creating temporary directory")?; let module = "wasm-bindgen-test"; // Collect all tests that the test harness is supposed to run. We assume // that any exported function with the prefix `__wbg_test` is a test we need // to execute. - let wasm = fs::read(&wasm_file_to_test) - .context("failed to read wasm file")?; - let wasm = Module::deserialize(&mut &wasm[..]) - .context("failed to deserialize wasm module")?; + let wasm = fs::read(&wasm_file_to_test).context("failed to read wasm file")?; + let wasm = Module::deserialize(&mut &wasm[..]).context("failed to deserialize wasm module")?; let mut tests = Vec::new(); if let Some(exports) = wasm.export_section() { for export in exports.entries() { if !export.field().starts_with("__wbg_test") { - continue + continue; } tests.push(export.field().to_string()); } @@ -104,7 +100,7 @@ fn rmain() -> Result<(), Error> { // early saying everything is ok. if tests.len() == 0 { println!("no tests to run!"); - return Ok(()) + return Ok(()); } // Figure out if this tests is supposed to execute in node.js or a browser. @@ -118,7 +114,7 @@ fn rmain() -> Result<(), Error> { _ => continue, }; if custom.name() != "__wasm_bindgen_test_unstable" { - continue + continue; } node = !custom.payload().contains(&0x01); } @@ -138,7 +134,7 @@ fn rmain() -> Result<(), Error> { // If we're executing in node.js, that module will take it from here. if node { - return node::execute(&module, &tmpdir, &args.collect::>(), &tests) + return node::execute(&module, &tmpdir, &args.collect::>(), &tests); } // Otherwise we're executing in a browser. Spawn a server which serves up @@ -160,13 +156,16 @@ fn rmain() -> Result<(), Error> { // TODO: eventually we should provide the ability to exit at some point // (gracefully) here, but for now this just runs forever. if !headless { - println!("Interactive browsers tests are now available at http://{}", addr); + println!( + "Interactive browsers tests are now available at http://{}", + addr + ); println!(""); println!("Note that interactive mode is enabled because `NO_HEADLESS`"); println!("is specified in the environment of this process. Once you're"); println!("done with testing you'll need to kill this server with"); println!("Ctrl-C."); - return Ok(srv.run()) + return Ok(srv.run()); } thread::spawn(|| srv.run()); diff --git a/crates/cli/src/bin/wasm-bindgen-test-runner/node.rs b/crates/cli/src/bin/wasm-bindgen-test-runner/node.rs index cd0b3ce57..f9837fcea 100644 --- a/crates/cli/src/bin/wasm-bindgen-test-runner/node.rs +++ b/crates/cli/src/bin/wasm-bindgen-test-runner/node.rs @@ -4,12 +4,16 @@ use std::fs; use std::path::Path; use std::process::Command; -use failure::{ResultExt, Error}; +use failure::{Error, ResultExt}; -pub fn execute(module: &str, tmpdir: &Path, args: &[OsString], tests: &[String]) - -> Result<(), Error> -{ - let mut js_to_execute = format!(r#" +pub fn execute( + module: &str, + tmpdir: &Path, + args: &[OsString], + tests: &[String], +) -> Result<(), Error> { + let mut js_to_execute = format!( + r#" const {{ exit }} = require('process'); let console_log_redirect = null; @@ -68,17 +72,18 @@ pub fn execute(module: &str, tmpdir: &Path, args: &[OsString], tests: &[String]) js_to_execute.push_str(&format!("tests.push('{}')\n", test)); } // And as a final addendum, exit with a nonzero code if any tests fail. - js_to_execute.push_str(" + js_to_execute.push_str( + " main(tests) .catch(e => { console.error(e); exit(1); }); - "); + ", + ); let js_path = tmpdir.join("run.js"); - fs::write(&js_path, js_to_execute) - .context("failed to write JS file")?; + fs::write(&js_path, js_to_execute).context("failed to write JS file")?; // Augment `NODE_PATH` so things like `require("tests/my-custom.js")` work // and Rust code can import from custom JS shims. This is a bit of a hack @@ -91,14 +96,16 @@ pub fn execute(module: &str, tmpdir: &Path, args: &[OsString], tests: &[String]) Command::new("node") .env("NODE_PATH", env::join_paths(&path).unwrap()) .arg(&js_path) - .args(args) + .args(args), ) } #[cfg(unix)] fn exec(cmd: &mut Command) -> Result<(), Error> { use std::os::unix::prelude::*; - Err(Error::from(cmd.exec()).context("failed to execute `node`").into()) + Err(Error::from(cmd.exec()) + .context("failed to execute `node`") + .into()) } #[cfg(windows)] diff --git a/crates/cli/src/bin/wasm-bindgen-test-runner/server.rs b/crates/cli/src/bin/wasm-bindgen-test-runner/server.rs index ea441bcec..ab548cfbf 100644 --- a/crates/cli/src/bin/wasm-bindgen-test-runner/server.rs +++ b/crates/cli/src/bin/wasm-bindgen-test-runner/server.rs @@ -1,10 +1,10 @@ use std::ffi::OsString; -use std::path::Path; use std::fs; use std::net::SocketAddr; +use std::path::Path; -use failure::{ResultExt, Error}; -use rouille::{self, Response, Request, Server}; +use failure::{Error, ResultExt}; +use rouille::{self, Request, Response, Server}; use wasm_bindgen_cli_support::wasm2es6js::Config; pub fn spawn( @@ -15,7 +15,8 @@ pub fn spawn( args: &[OsString], tests: &[String], ) -> Result Response + Send + Sync>, Error> { - let mut js_to_execute = format!(r#" + let mut js_to_execute = format!( + r#" import {{ Context, __wbgtest_console_log, __wbgtest_console_error }} from './{0}'; import * as wasm from './{0}_bg'; @@ -52,8 +53,7 @@ pub fn spawn( js_to_execute.push_str("main(tests);\n"); let js_path = tmpdir.join("run.js"); - fs::write(&js_path, js_to_execute) - .context("failed to write JS file")?; + fs::write(&js_path, js_to_execute).context("failed to write JS file")?; // No browser today supports a wasm file as ES modules natively, so we need // to shim it. Use `wasm2es6js` here to fetch an appropriate URL and look @@ -69,8 +69,7 @@ pub fn spawn( .fetch(Some(format!("/{}", wasm_name))) .generate(&wasm)?; let js = output.js()?; - fs::write(tmpdir.join(format!("{}_bg.js", module)), js) - .context("failed to write JS file")?; + fs::write(tmpdir.join(format!("{}_bg.js", module)), js).context("failed to write JS file")?; // For now, always run forever on this port. We may update this later! let tmpdir = tmpdir.to_path_buf(); @@ -85,7 +84,7 @@ pub fn spawn( } else { include_str!("index.html") }; - return Response::from_data("text/html", s) + return Response::from_data("text/html", s); } // Otherwise we need to find the asset here. It may either be in our @@ -98,14 +97,14 @@ pub fn spawn( // Make sure browsers don't cache anything (Chrome appeared to with this // header?) response.headers.retain(|(k, _)| k != "Cache-Control"); - return response + return response; }).map_err(|e| format_err!("{}", e))?; return Ok(srv); fn try_asset(request: &Request, dir: &Path) -> Response { let response = rouille::match_assets(request, dir); if response.is_success() { - return response + return response; } // When a browser is doing ES imports it's using the directives we @@ -117,14 +116,15 @@ pub fn spawn( let new_request = Request::fake_http( request.method(), format!("{}.js", request.url()), - request.headers() + request + .headers() .map(|(a, b)| (a.to_string(), b.to_string())) .collect(), Vec::new(), ); let response = rouille::match_assets(&new_request, dir); if response.is_success() { - return response + return response; } } } diff --git a/crates/cli/src/bin/wasm-bindgen-test-runner/shell.rs b/crates/cli/src/bin/wasm-bindgen-test-runner/shell.rs index 6f1d0f770..f6893fb76 100644 --- a/crates/cli/src/bin/wasm-bindgen-test-runner/shell.rs +++ b/crates/cli/src/bin/wasm-bindgen-test-runner/shell.rs @@ -2,8 +2,7 @@ const WIDTH: usize = 50; use std::io::{self, Write}; -pub struct Shell { -} +pub struct Shell {} impl Shell { pub fn new() -> Shell { @@ -11,11 +10,7 @@ impl Shell { } pub fn status(&self, s: &str) { - let s = if s.len() > WIDTH { - &s[..WIDTH] - } else { - s - }; + let s = if s.len() > WIDTH { &s[..WIDTH] } else { s }; print!("{:<1$}\r", s, WIDTH); io::stdout().flush().unwrap(); } diff --git a/crates/cli/src/bin/wasm2es6js.rs b/crates/cli/src/bin/wasm2es6js.rs index 7991cc962..8cf1f86c8 100644 --- a/crates/cli/src/bin/wasm2es6js.rs +++ b/crates/cli/src/bin/wasm2es6js.rs @@ -67,8 +67,7 @@ fn rmain(args: &Args) -> Result<(), Error> { if let Some(ref p) = args.flag_output { let dst = p.with_extension("d.ts"); let ts = object.typescript(); - fs::write(&dst, ts) - .with_context(|_| format!("failed to write `{}`", dst.display()))?; + fs::write(&dst, ts).with_context(|_| format!("failed to write `{}`", dst.display()))?; } } @@ -76,8 +75,7 @@ fn rmain(args: &Args) -> Result<(), Error> { match args.flag_output { Some(ref p) => { - fs::write(p, js) - .with_context(|_| format!("failed to write `{}`", p.display()))?; + fs::write(p, js).with_context(|_| format!("failed to write `{}`", p.display()))?; } None => { println!("{}", js); diff --git a/crates/futures/src/lib.rs b/crates/futures/src/lib.rs index d8c672be3..4c6418f64 100644 --- a/crates/futures/src/lib.rs +++ b/crates/futures/src/lib.rs @@ -104,13 +104,13 @@ #![deny(missing_docs)] extern crate futures; -extern crate wasm_bindgen; extern crate js_sys; +extern crate wasm_bindgen; +use std::cell::{Cell, RefCell}; use std::sync::Arc; -use std::cell::{RefCell, Cell}; -use futures::executor::{self, Spawn, Notify}; +use futures::executor::{self, Notify, Spawn}; use futures::prelude::*; use futures::sync::oneshot; use js_sys::{Function, Promise}; @@ -170,11 +170,11 @@ impl Future for JsFuture { // till we're done, so we dont need to handle that. if let Ok(Async::Ready(val)) = self.resolved.poll() { drop(self.callbacks.take()); - return Ok(val.into()) + return Ok(val.into()); } if let Ok(Async::Ready(val)) = self.rejected.poll() { drop(self.callbacks.take()); - return Err(val) + return Err(val); } Ok(Async::NotReady) } @@ -201,7 +201,8 @@ impl Future for JsFuture { /// resolve**. Instead it will be a leaked promise. This is an unfortunate /// limitation of wasm currently that's hoped to be fixed one day! pub fn future_to_promise(future: F) -> Promise - where F: Future + 'static, +where + F: Future + 'static, { _future_to_promise(Box::new(future)) } @@ -310,7 +311,7 @@ fn _future_to_promise(future: Box>) -> P // our `Waiting` state, and resume the polling process State::Polling => { me.notified.set(State::Waiting(me.clone())); - break + break; } State::Waiting(_) => panic!("shouldn't see waiting state!"), @@ -328,7 +329,7 @@ fn _future_to_promise(future: Box>) -> P }; drop(f.call1(&JsValue::undefined(), &val)); - break + break; } } } diff --git a/crates/js-sys/tests/headless.rs b/crates/js-sys/tests/headless.rs index 1b45ea7b6..2cb86953c 100755 --- a/crates/js-sys/tests/headless.rs +++ b/crates/js-sys/tests/headless.rs @@ -1,22 +1,22 @@ #![cfg(target_arch = "wasm32")] -extern crate wasm_bindgen_test; -extern crate wasm_bindgen; extern crate js_sys; +extern crate wasm_bindgen; +extern crate wasm_bindgen_test; +use js_sys::Array; use wasm_bindgen::prelude::*; use wasm_bindgen_test::*; -use js_sys::Array; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen(module = "./tests/headless.js")] -extern { - fn is_array_values_supported()-> bool; +extern "C" { + fn is_array_values_supported() -> bool; } #[wasm_bindgen] -extern { +extern "C" { type ValuesIterator; #[wasm_bindgen(method, structural)] fn next(this: &ValuesIterator) -> IterNext; @@ -32,7 +32,7 @@ extern { #[wasm_bindgen_test] fn array_iterator_values() { if !is_array_values_supported() { - return + return; } let array = Array::new(); array.push(&8.into()); diff --git a/crates/js-sys/tests/wasm/Array.rs b/crates/js-sys/tests/wasm/Array.rs index fe6d8867a..829694805 100644 --- a/crates/js-sys/tests/wasm/Array.rs +++ b/crates/js-sys/tests/wasm/Array.rs @@ -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::*; macro_rules! js_array { ($($e:expr),*) => ({ @@ -31,10 +31,16 @@ fn filter() { assert!(array.filter(&mut |x, _, _| x.as_f64().is_some()).length() == 0); let array = js_array![1, 2, 3, 4]; - assert_eq!(array.filter(&mut |x, _, _| x.as_f64().is_some()).length(), 4); + assert_eq!( + array.filter(&mut |x, _, _| x.as_f64().is_some()).length(), + 4 + ); let array = js_array!["a", 1, "b", 2]; - assert_eq!(array.filter(&mut |x, _, _| x.as_f64().is_some()).length(), 2); + assert_eq!( + array.filter(&mut |x, _, _| x.as_f64().is_some()).length(), + 2 + ); } #[wasm_bindgen_test] @@ -223,14 +229,20 @@ fn every() { #[wasm_bindgen_test] fn find() { let even = js_array![2, 4, 6, 8]; - assert_eq!(even.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0), 2); + assert_eq!( + even.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0), + 2 + ); let odd = js_array![1, 3, 5, 7]; assert_eq!( odd.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0), JsValue::undefined(), ); let mixed = js_array![3, 5, 7, 10]; - assert_eq!(mixed.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0), 10); + assert_eq!( + mixed.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0), + 10 + ); } #[wasm_bindgen_test] @@ -242,38 +254,43 @@ fn map() { #[wasm_bindgen_test] fn reduce() { - let arr = js_array!["0", "1", "2", "3", "4"] - .reduce( - &mut |ac, cr, _, _| { - format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap()) - .into() - }, - &"".into(), - ); + let arr = js_array!["0", "1", "2", "3", "4"].reduce( + &mut |ac, cr, _, _| { + format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap()).into() + }, + &"".into(), + ); assert_eq!(arr, "01234"); } #[wasm_bindgen_test] fn reduce_right() { - let arr = js_array!["0", "1", "2", "3", "4"] - .reduce_right( - &mut |ac, cr, _, _| { - format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap()) - .into() - }, - &"".into(), - ); + let arr = js_array!["0", "1", "2", "3", "4"].reduce_right( + &mut |ac, cr, _, _| { + format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap()).into() + }, + &"".into(), + ); assert_eq!(arr, "43210"); } #[wasm_bindgen_test] fn find_index() { let even = js_array![2, 4, 6, 8]; - assert_eq!(even.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.), 0); + assert_eq!( + even.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.), + 0 + ); let odd = js_array![1, 3, 5, 7]; - assert_eq!(odd.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.), -1); + assert_eq!( + odd.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.), + -1 + ); let mixed = js_array![3, 5, 7, 10]; - assert_eq!(mixed.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.), 3); + assert_eq!( + mixed.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.), + 3 + ); } #[wasm_bindgen_test] @@ -287,11 +304,9 @@ fn to_locale_string() { fn for_each() { fn sum_indices_of_evens(array: &Array) -> u32 { let mut res = 0; - array.for_each(&mut |elem: JsValue, i, _| { - match elem.as_f64() { - Some(val) if val % 2. == 0. => res += i, - _ => { } - } + array.for_each(&mut |elem: JsValue, i, _| match elem.as_f64() { + Some(val) if val % 2. == 0. => res += i, + _ => {} }); res } diff --git a/crates/js-sys/tests/wasm/ArrayBuffer.rs b/crates/js-sys/tests/wasm/ArrayBuffer.rs index a4a082a43..4bd3b664f 100644 --- a/crates/js-sys/tests/wasm/ArrayBuffer.rs +++ b/crates/js-sys/tests/wasm/ArrayBuffer.rs @@ -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 new() { diff --git a/crates/js-sys/tests/wasm/ArrayIterator.rs b/crates/js-sys/tests/wasm/ArrayIterator.rs index 0554e1561..87e67fd2c 100644 --- a/crates/js-sys/tests/wasm/ArrayIterator.rs +++ b/crates/js-sys/tests/wasm/ArrayIterator.rs @@ -1,6 +1,6 @@ +use js_sys::*; use wasm_bindgen::JsValue; use wasm_bindgen_test::*; -use js_sys::*; #[wasm_bindgen_test] fn keys() { diff --git a/crates/js-sys/tests/wasm/Boolean.rs b/crates/js-sys/tests/wasm/Boolean.rs index c7aa93774..62a381674 100644 --- a/crates/js-sys/tests/wasm/Boolean.rs +++ b/crates/js-sys/tests/wasm/Boolean.rs @@ -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 new_undefined() { diff --git a/crates/js-sys/tests/wasm/Date.rs b/crates/js-sys/tests/wasm/Date.rs index d0496fa49..fd63674c9 100644 --- a/crates/js-sys/tests/wasm/Date.rs +++ b/crates/js-sys/tests/wasm/Date.rs @@ -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 get_date() { @@ -343,7 +343,10 @@ fn to_date_string() { #[wasm_bindgen_test] fn to_iso_string() { let date = Date::new(&"05 October 2011 14:48 UTC".into()); - assert_eq!(JsValue::from(date.to_iso_string()), "2011-10-05T14:48:00.000Z"); + assert_eq!( + JsValue::from(date.to_iso_string()), + "2011-10-05T14:48:00.000Z" + ); } #[wasm_bindgen_test] diff --git a/crates/js-sys/tests/wasm/Error.rs b/crates/js-sys/tests/wasm/Error.rs index e05ed23c8..b6414bf75 100644 --- a/crates/js-sys/tests/wasm/Error.rs +++ b/crates/js-sys/tests/wasm/Error.rs @@ -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 new() { @@ -34,7 +34,10 @@ fn to_string() { let error = Error::new("error message 1"); assert_eq!(JsValue::from(error.to_string()), "Error: error message 1"); error.set_name("error_name_1"); - assert_eq!(JsValue::from(error.to_string()), "error_name_1: error message 1"); + assert_eq!( + JsValue::from(error.to_string()), + "error_name_1: error message 1" + ); } #[wasm_bindgen_test] diff --git a/crates/js-sys/tests/wasm/EvalError.rs b/crates/js-sys/tests/wasm/EvalError.rs index e23a25b20..52abe06ca 100644 --- a/crates/js-sys/tests/wasm/EvalError.rs +++ b/crates/js-sys/tests/wasm/EvalError.rs @@ -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::*; // Note: This error is not thrown any more, so there are no tests that will generate this error. // Instead we just have to manually construct it @@ -40,12 +40,17 @@ fn set_name() { fn to_string() { let error = EvalError::new("error message 1"); let base_error: &Error = error.dyn_ref().unwrap(); - assert_eq!(JsValue::from(base_error.to_string()), "EvalError: error message 1"); + assert_eq!( + JsValue::from(base_error.to_string()), + "EvalError: error message 1" + ); base_error.set_name("error_name_1"); - assert_eq!(JsValue::from(base_error.to_string()), "error_name_1: error message 1"); + assert_eq!( + JsValue::from(base_error.to_string()), + "error_name_1: error message 1" + ); } - #[wasm_bindgen_test] fn evalerror_inheritance() { let error = EvalError::new("some message"); diff --git a/crates/js-sys/tests/wasm/Function.rs b/crates/js-sys/tests/wasm/Function.rs index 86bfa9196..b3ad413ba 100644 --- a/crates/js-sys/tests/wasm/Function.rs +++ b/crates/js-sys/tests/wasm/Function.rs @@ -1,10 +1,10 @@ -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = max, js_namespace = Math)] static MAX: Function; @@ -31,7 +31,7 @@ fn apply() { } #[wasm_bindgen(module = "tests/wasm/Function.js")] -extern { +extern "C" { fn get_function_to_bind() -> Function; fn get_value_to_bind_to() -> JsValue; fn call_function(f: Function) -> JsValue; diff --git a/crates/js-sys/tests/wasm/Generator.rs b/crates/js-sys/tests/wasm/Generator.rs index 3395ced2b..690bb2260 100644 --- a/crates/js-sys/tests/wasm/Generator.rs +++ b/crates/js-sys/tests/wasm/Generator.rs @@ -1,10 +1,10 @@ -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/Generator.js")] -extern { +extern "C" { fn one_two_generator() -> Generator; fn dummy_generator() -> Generator; fn broken_generator() -> Generator; @@ -61,6 +61,6 @@ fn throw() { #[wasm_bindgen_test] fn generator_inheritance() { let gen = dummy_generator(); - + assert!(gen.is_instance_of::()); } diff --git a/crates/js-sys/tests/wasm/Intl.rs b/crates/js-sys/tests/wasm/Intl.rs index 74c57ecdc..427ea00a5 100644 --- a/crates/js-sys/tests/wasm/Intl.rs +++ b/crates/js-sys/tests/wasm/Intl.rs @@ -1,6 +1,6 @@ +use js_sys::*; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_test::*; -use js_sys::*; #[wasm_bindgen_test] fn get_canonical_locales() { diff --git a/crates/js-sys/tests/wasm/Iterator.rs b/crates/js-sys/tests/wasm/Iterator.rs index 7c5408376..94fe14c56 100644 --- a/crates/js-sys/tests/wasm/Iterator.rs +++ b/crates/js-sys/tests/wasm/Iterator.rs @@ -30,7 +30,19 @@ fn try_iter_handles_iteration_protocol() { assert!(try_iter(&get_not_iterable()).unwrap().is_none()); assert!(try_iter(&get_symbol_iterator_throws()).is_err()); - assert!(try_iter(&get_symbol_iterator_not_function()).unwrap().is_none()); - assert!(try_iter(&get_symbol_iterator_returns_not_object()).unwrap().is_none()); - assert!(try_iter(&get_symbol_iterator_returns_object_without_next()).unwrap().is_none()); + assert!( + try_iter(&get_symbol_iterator_not_function()) + .unwrap() + .is_none() + ); + assert!( + try_iter(&get_symbol_iterator_returns_not_object()) + .unwrap() + .is_none() + ); + assert!( + try_iter(&get_symbol_iterator_returns_object_without_next()) + .unwrap() + .is_none() + ); } diff --git a/crates/js-sys/tests/wasm/JSON.rs b/crates/js-sys/tests/wasm/JSON.rs index affbf3f78..bc7a1c287 100644 --- a/crates/js-sys/tests/wasm/JSON.rs +++ b/crates/js-sys/tests/wasm/JSON.rs @@ -1,11 +1,10 @@ -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen_test] fn parse_array() { - let js_array = JSON::parse("[1, 2, 3]").unwrap();; assert!(Array::is_array(&js_array)); @@ -14,12 +13,10 @@ fn parse_array() { assert_eq!(array.pop(), 3); assert_eq!(array.pop(), 2); assert_eq!(array.pop(), 1); - } #[wasm_bindgen_test] fn parse_object() { - let js_object = JSON::parse("{\"x\": 5, \"y\": true, \"z\": [\"foo\", \"bar\"]}").unwrap(); assert!(js_object.is_object()); @@ -45,7 +42,6 @@ fn parse_object() { assert!(Number::is_integer(&x)); let x_num = Number::new(&x); assert_eq!(x_num.value_of(), 5.0); - } #[wasm_bindgen_test] @@ -86,7 +82,7 @@ fn stringify_error() { #[wasm_bindgen_test] fn json_extends() { #[wasm_bindgen] - extern { + extern "C" { #[wasm_bindgen(js_name = JSON)] static json: JSON; } diff --git a/crates/js-sys/tests/wasm/JsString.rs b/crates/js-sys/tests/wasm/JsString.rs index 0240dbdf0..bb4a6ac05 100644 --- a/crates/js-sys/tests/wasm/JsString.rs +++ b/crates/js-sys/tests/wasm/JsString.rs @@ -1,11 +1,11 @@ -use wasm_bindgen::JsValue; +use js_sys::*; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; +use wasm_bindgen::JsValue; use wasm_bindgen_test::*; -use js_sys::*; #[wasm_bindgen(module = "tests/wasm/JsString.js")] -extern { +extern "C" { fn new_string_object() -> JsValue; fn get_replacer_function() -> Function; } @@ -55,7 +55,10 @@ fn concat() { let s = JsString::from("Hello ").concat(&"World".into()); assert_eq!(JsValue::from(s), "Hello World"); let foo = JsString::from("foo"); - assert_eq!(JsValue::from(foo.concat(&Object::new().into())), "foo[object Object]"); + assert_eq!( + JsValue::from(foo.concat(&Object::new().into())), + "foo[object Object]" + ); assert_eq!(JsValue::from(foo.concat(&Array::new().into())), "foo"); assert_eq!(JsValue::from(foo.concat(&JsValue::null())), "foonull"); assert_eq!(JsValue::from(foo.concat(&true.into())), "footrue"); @@ -76,27 +79,38 @@ fn ends_with() { #[wasm_bindgen_test] fn from_char_code() { let s = "½+¾="; - let codes : Vec = s.chars() - .map(|char| char as u32) - .collect(); + let codes: Vec = s.chars().map(|char| char as u32).collect(); assert_eq!(JsString::from_char_code1(codes[0]), "½"); assert_eq!(JsString::from_char_code2(codes[0], codes[1]), "½+"); - assert_eq!(JsString::from_char_code3(codes[0], codes[1], codes[2]), "½+¾"); - assert_eq!(JsString::from_char_code4(codes[0], codes[1], codes[2], codes[3]), "½+¾="); + assert_eq!( + JsString::from_char_code3(codes[0], codes[1], codes[2]), + "½+¾" + ); + 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 = s.chars() - .map(|char| char as u32) - .collect(); + let codes: Vec = 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_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()); @@ -235,8 +249,14 @@ fn match_() { let result = JsString::from(s).match_(&re); let obj = result.unwrap(); - assert_eq!(Reflect::get(obj.as_ref(), &"0".into()).unwrap(), "see Chapter 3.4.5.1"); - assert_eq!(Reflect::get(obj.as_ref(), &"1".into()).unwrap(), "Chapter 3.4.5.1"); + assert_eq!( + Reflect::get(obj.as_ref(), &"0".into()).unwrap(), + "see Chapter 3.4.5.1" + ); + assert_eq!( + Reflect::get(obj.as_ref(), &"1".into()).unwrap(), + "Chapter 3.4.5.1" + ); assert_eq!(Reflect::get(obj.as_ref(), &"2".into()).unwrap(), ".1"); assert_eq!(Reflect::get(obj.as_ref(), &"index".into()).unwrap(), 22); assert_eq!(Reflect::get(obj.as_ref(), &"input".into()).unwrap(), s); @@ -248,9 +268,15 @@ fn normalize() { // TODO: Handle undefined assert_eq!(JsValue::from(js.normalize("NFC")), "\u{1E9B}\u{0323}"); - assert_eq!(JsValue::from(js.normalize("NFD")), "\u{017F}\u{0323}\u{0307}"); + assert_eq!( + JsValue::from(js.normalize("NFD")), + "\u{017F}\u{0323}\u{0307}" + ); assert_eq!(JsValue::from(js.normalize("NFKC")), "\u{1E69}"); - assert_eq!(JsValue::from(js.normalize("NFKD")), "\u{0073}\u{0323}\u{0307}"); + assert_eq!( + JsValue::from(js.normalize("NFKD")), + "\u{0073}\u{0323}\u{0307}" + ); } #[wasm_bindgen_test] @@ -287,17 +313,24 @@ fn repeat() { #[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 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?"); + 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 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"); @@ -312,7 +345,9 @@ fn replace() { #[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 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); @@ -495,8 +530,14 @@ fn raw() { let call_site = Object::new(); let raw = Array::of3(&"foo".into(), &"bar".into(), &"123".into()); Reflect::set(&call_site.as_ref(), &"raw".into(), &raw.into()).unwrap(); - assert_eq!(JsString::raw_2(&call_site, "5", "JavaScript").unwrap(), "foo5barJavaScript123"); + assert_eq!( + JsString::raw_2(&call_site, "5", "JavaScript").unwrap(), + "foo5barJavaScript123" + ); let substitutions = Array::of2(&"5".into(), &"JavaScript".into()); - assert_eq!(JsString::raw(&call_site, &substitutions).unwrap(), "foo5barJavaScript123"); + assert_eq!( + JsString::raw(&call_site, &substitutions).unwrap(), + "foo5barJavaScript123" + ); assert!(JsString::raw_0(&JsValue::null().unchecked_into()).is_err()); } diff --git a/crates/js-sys/tests/wasm/Map.rs b/crates/js-sys/tests/wasm/Map.rs index 912822824..8223c6e70 100644 --- a/crates/js-sys/tests/wasm/Map.rs +++ b/crates/js-sys/tests/wasm/Map.rs @@ -1,6 +1,6 @@ -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen_test] fn clear() { diff --git a/crates/js-sys/tests/wasm/MapIterator.rs b/crates/js-sys/tests/wasm/MapIterator.rs index 3e28a2044..6a6eec391 100644 --- a/crates/js-sys/tests/wasm/MapIterator.rs +++ b/crates/js-sys/tests/wasm/MapIterator.rs @@ -1,5 +1,5 @@ -use wasm_bindgen_test::*; use js_sys::*; +use wasm_bindgen_test::*; #[wasm_bindgen_test] fn entries() { diff --git a/crates/js-sys/tests/wasm/Math.rs b/crates/js-sys/tests/wasm/Math.rs index c6047fca6..3fc88c191 100644 --- a/crates/js-sys/tests/wasm/Math.rs +++ b/crates/js-sys/tests/wasm/Math.rs @@ -1,14 +1,14 @@ use std::f64::consts::PI; -use std::f64::{NEG_INFINITY, NAN}; +use std::f64::{NAN, NEG_INFINITY}; -use wasm_bindgen::{JsCast, prelude::*}; -use wasm_bindgen_test::*; use js_sys::*; +use wasm_bindgen::{prelude::*, JsCast}; +use wasm_bindgen_test::*; #[wasm_bindgen_test] fn math_extends() { #[wasm_bindgen] - extern { + extern "C" { #[wasm_bindgen(js_name = Math)] static math: Math; } @@ -18,15 +18,19 @@ fn math_extends() { } macro_rules! assert_eq { - ($a:expr, $b:expr) => ({ + ($a:expr, $b:expr) => {{ let (a, b) = (&$a, &$b); if f64::is_infinite(*a) && f64::is_infinite(*b) { assert!(a == b); } else { - assert!((*a - *b).abs() < 1.0e-6, - "not approximately equal {:?} ?= {:?}", a, b); + assert!( + (*a - *b).abs() < 1.0e-6, + "not approximately equal {:?} ?= {:?}", + a, + b + ); } - }) + }}; } #[wasm_bindgen_test] diff --git a/crates/js-sys/tests/wasm/Number.rs b/crates/js-sys/tests/wasm/Number.rs index b3fae6b12..37e141eb5 100644 --- a/crates/js-sys/tests/wasm/Number.rs +++ b/crates/js-sys/tests/wasm/Number.rs @@ -1,9 +1,9 @@ use std::f64::{INFINITY, NAN}; +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 is_finite() { @@ -41,7 +41,10 @@ fn is_nan() { #[wasm_bindgen_test] fn is_safe_integer() { assert_eq!(Number::is_safe_integer(&42.into()), true); - assert_eq!(Number::is_safe_integer(&(Math::pow(2., 53.) - 1.).into()), true); + assert_eq!( + Number::is_safe_integer(&(Math::pow(2., 53.) - 1.).into()), + true + ); assert_eq!(Number::is_safe_integer(&Math::pow(2., 53.).into()), false); assert_eq!(Number::is_safe_integer(&"42".into()), false); assert_eq!(Number::is_safe_integer(&42.1.into()), false); @@ -102,7 +105,10 @@ fn to_fixed() { #[wasm_bindgen_test] fn to_exponential() { - assert_eq!(Number::new(&123456.into()).to_exponential(2).unwrap(), "1.23e+5"); + assert_eq!( + Number::new(&123456.into()).to_exponential(2).unwrap(), + "1.23e+5" + ); assert!(Number::new(&10.into()).to_exponential(101).is_err()); } diff --git a/crates/js-sys/tests/wasm/Promise.rs b/crates/js-sys/tests/wasm/Promise.rs index a070b784e..5502a6156 100644 --- a/crates/js-sys/tests/wasm/Promise.rs +++ b/crates/js-sys/tests/wasm/Promise.rs @@ -1,6 +1,6 @@ -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen_test] fn promise_inheritance() { diff --git a/crates/js-sys/tests/wasm/Proxy.rs b/crates/js-sys/tests/wasm/Proxy.rs index 30b23418f..3aca98084 100644 --- a/crates/js-sys/tests/wasm/Proxy.rs +++ b/crates/js-sys/tests/wasm/Proxy.rs @@ -1,9 +1,9 @@ +use js_sys::*; use wasm_bindgen::prelude::*; use wasm_bindgen_test::*; -use js_sys::*; #[wasm_bindgen(module = "tests/wasm/Proxy.js")] -extern { +extern "C" { fn proxy_target() -> JsValue; fn proxy_handler() -> Object; @@ -13,7 +13,6 @@ extern { #[wasm_bindgen(method, getter, structural, catch)] fn b(this: &Custom) -> Result; - type RevocableResult; #[wasm_bindgen(method, getter, structural)] fn proxy(this: &RevocableResult) -> JsValue; diff --git a/crates/js-sys/tests/wasm/RangeError.rs b/crates/js-sys/tests/wasm/RangeError.rs index 93b42b995..97cd08b2b 100644 --- a/crates/js-sys/tests/wasm/RangeError.rs +++ b/crates/js-sys/tests/wasm/RangeError.rs @@ -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 range_error() { diff --git a/crates/js-sys/tests/wasm/ReferenceError.rs b/crates/js-sys/tests/wasm/ReferenceError.rs index 82d6e6925..a40f5b165 100644 --- a/crates/js-sys/tests/wasm/ReferenceError.rs +++ b/crates/js-sys/tests/wasm/ReferenceError.rs @@ -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 reference_error() { diff --git a/crates/js-sys/tests/wasm/Reflect.rs b/crates/js-sys/tests/wasm/Reflect.rs index 47b5ac4ab..b20411365 100644 --- a/crates/js-sys/tests/wasm/Reflect.rs +++ b/crates/js-sys/tests/wasm/Reflect.rs @@ -1,9 +1,9 @@ -use wasm_bindgen::{JsCast, prelude::*}; -use wasm_bindgen_test::*; use js_sys::*; +use wasm_bindgen::{prelude::*, JsCast}; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/Reflect.js")] -extern { +extern "C" { fn get_char_at() -> Function; #[wasm_bindgen(js_name = Rectangle)] @@ -26,7 +26,7 @@ extern { } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = prototype, js_namespace = Object)] static OBJECT_PROTOTYPE: JsValue; #[wasm_bindgen(js_name = prototype, js_namespace = Array)] @@ -45,7 +45,10 @@ extern { fn apply() { let args = Array::new(); args.push(&3.into()); - assert_eq!(Reflect::apply(&get_char_at(), &"ponies".into(), &args).unwrap(), "i"); + assert_eq!( + Reflect::apply(&get_char_at(), &"ponies".into(), &args).unwrap(), + "i" + ); } #[wasm_bindgen_test] @@ -62,11 +65,8 @@ fn construct_with_new_target() { let args = Array::new(); args.push(&10.into()); args.push(&10.into()); - let instance = Reflect::construct_with_new_target( - &RECTANGLE_CLASS, - &args, - &RECTANGLE2_CLASS, - ).unwrap(); + let instance = + Reflect::construct_with_new_target(&RECTANGLE_CLASS, &args, &RECTANGLE2_CLASS).unwrap(); assert_eq!(Rectangle::from(instance).x(), 10); } @@ -180,13 +180,16 @@ fn set_prototype_of() { let obj = Object::new(); assert!(Reflect::set_prototype_of(&obj, &JsValue::null()).unwrap()); let obj = JsValue::from(obj); - assert_eq!(JsValue::from(Reflect::get_prototype_of(&obj).unwrap()), JsValue::null()); + assert_eq!( + JsValue::from(Reflect::get_prototype_of(&obj).unwrap()), + JsValue::null() + ); } #[wasm_bindgen_test] fn reflect_extends() { #[wasm_bindgen] - extern { + extern "C" { #[wasm_bindgen(js_name = Reflect)] static reflect: Reflect; } diff --git a/crates/js-sys/tests/wasm/RegExp.rs b/crates/js-sys/tests/wasm/RegExp.rs index eedbaafca..6351a9a3f 100644 --- a/crates/js-sys/tests/wasm/RegExp.rs +++ b/crates/js-sys/tests/wasm/RegExp.rs @@ -1,6 +1,6 @@ -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen_test] fn regexp_inheritance() { @@ -95,7 +95,10 @@ fn multiline() { #[wasm_bindgen_test] fn n1_to_n9() { - let re = RegExp::new(r"(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)", ""); + let re = RegExp::new( + r"(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)", + "", + ); re.test("The Quick Brown Fox Jumps Over The Lazy Dog"); assert_eq!(RegExp::n1(), "The"); assert_eq!(RegExp::n2(), "Quick"); diff --git a/crates/js-sys/tests/wasm/Set.rs b/crates/js-sys/tests/wasm/Set.rs index 6b70d1b6d..045e192e6 100644 --- a/crates/js-sys/tests/wasm/Set.rs +++ b/crates/js-sys/tests/wasm/Set.rs @@ -1,12 +1,12 @@ -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; fn set2vec(s: &Set) -> Vec { let mut result = Vec::new(); s.for_each(&mut |x, _, _| result.push(x)); - return result + return result; } #[wasm_bindgen_test] @@ -97,7 +97,11 @@ fn keys() { set.add(&2.into()); set.add(&3.into()); - let list = set.keys().into_iter().map(|e| e.unwrap()).collect::>(); + let list = set + .keys() + .into_iter() + .map(|e| e.unwrap()) + .collect::>(); assert_eq!(list.len(), 3); assert!(list.iter().any(|l| *l == 1)); assert!(list.iter().any(|l| *l == 2)); @@ -111,7 +115,11 @@ fn values() { set.add(&2.into()); set.add(&3.into()); - let list = set.values().into_iter().map(|e| e.unwrap()).collect::>(); + let list = set + .values() + .into_iter() + .map(|e| e.unwrap()) + .collect::>(); assert_eq!(list.len(), 3); assert!(list.iter().any(|l| *l == 1)); assert!(list.iter().any(|l| *l == 2)); diff --git a/crates/js-sys/tests/wasm/SetIterator.rs b/crates/js-sys/tests/wasm/SetIterator.rs index 45e253192..ff853825b 100644 --- a/crates/js-sys/tests/wasm/SetIterator.rs +++ b/crates/js-sys/tests/wasm/SetIterator.rs @@ -1,6 +1,6 @@ +use js_sys::*; use wasm_bindgen::prelude::*; use wasm_bindgen_test::*; -use js_sys::*; #[wasm_bindgen_test] fn entries() { diff --git a/crates/js-sys/tests/wasm/Symbol.rs b/crates/js-sys/tests/wasm/Symbol.rs index 876e1d88a..c48d5ddca 100644 --- a/crates/js-sys/tests/wasm/Symbol.rs +++ b/crates/js-sys/tests/wasm/Symbol.rs @@ -1,9 +1,9 @@ +use js_sys::*; use wasm_bindgen::prelude::*; use wasm_bindgen_test::*; -use js_sys::*; #[wasm_bindgen(module = "tests/wasm/Symbol.js")] -extern { +extern "C" { fn test_has_instance(sym: &Symbol); fn test_is_concat_spreadable(sym: &Symbol); fn test_iterator(sym: &Symbol); @@ -17,7 +17,7 @@ extern { } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = Symbol)] fn gensym(val: JsValue) -> Symbol; } @@ -101,7 +101,10 @@ fn to_string() { #[wasm_bindgen_test] fn unscopables() { - assert_eq!(Symbol::unscopables().to_string(), "Symbol(Symbol.unscopables)"); + assert_eq!( + Symbol::unscopables().to_string(), + "Symbol(Symbol.unscopables)" + ); } #[wasm_bindgen_test] diff --git a/crates/js-sys/tests/wasm/SyntaxError.rs b/crates/js-sys/tests/wasm/SyntaxError.rs index 136746af5..b76b71ca6 100644 --- a/crates/js-sys/tests/wasm/SyntaxError.rs +++ b/crates/js-sys/tests/wasm/SyntaxError.rs @@ -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 syntax_error() { diff --git a/crates/js-sys/tests/wasm/TypeError.rs b/crates/js-sys/tests/wasm/TypeError.rs index e9a9957ad..0fdbde1d3 100644 --- a/crates/js-sys/tests/wasm/TypeError.rs +++ b/crates/js-sys/tests/wasm/TypeError.rs @@ -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 type_error() { diff --git a/crates/js-sys/tests/wasm/TypedArray.rs b/crates/js-sys/tests/wasm/TypedArray.rs index 5c1e88fca..a4a3af344 100644 --- a/crates/js-sys/tests/wasm/TypedArray.rs +++ b/crates/js-sys/tests/wasm/TypedArray.rs @@ -1,10 +1,10 @@ -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; macro_rules! each { - ($m:ident) => ( + ($m:ident) => { $m!(Uint8Array); $m!(Uint8ClampedArray); $m!(Uint16Array); @@ -14,16 +14,16 @@ macro_rules! each { $m!(Int32Array); $m!(Float32Array); $m!(Float64Array); - ) + }; } macro_rules! test_inheritence { - ($arr:ident) => ({ + ($arr:ident) => {{ let arr = $arr::new(&JsValue::undefined()); assert!(arr.is_instance_of::<$arr>()); let _: &Object = arr.as_ref(); - assert!(arr.is_instance_of::()); - }) + assert!(arr.is_instance_of::()); + }}; } #[wasm_bindgen_test] fn inheritence() { @@ -31,13 +31,13 @@ fn inheritence() { } macro_rules! test_undefined { - ($arr:ident) => ({ + ($arr:ident) => {{ let arr = $arr::new(&JsValue::undefined()); assert_eq!(arr.length(), 0); assert_eq!(arr.byte_length(), 0); assert_eq!(arr.byte_offset(), 0); assert!(JsValue::from(arr.buffer()).is_object()); - }) + }}; } #[wasm_bindgen_test] fn new_undefined() { @@ -45,13 +45,13 @@ fn new_undefined() { } macro_rules! test_length { - ($arr:ident) => ({ + ($arr:ident) => {{ let arr = $arr::new(&4.into()); assert_eq!(arr.length(), 4); assert!(arr.byte_length() != 0); assert_eq!(arr.byte_offset(), 0); assert!(JsValue::from(arr.buffer()).is_object()); - }) + }}; } #[wasm_bindgen_test] fn new_length() { @@ -59,9 +59,9 @@ fn new_length() { } macro_rules! test_subarray { - ($arr:ident) => ({ + ($arr:ident) => {{ assert_eq!($arr::new(&4.into()).subarray(0, 1).length(), 1); - }) + }}; } #[wasm_bindgen_test] fn new_subarray() { @@ -69,7 +69,7 @@ fn new_subarray() { } macro_rules! test_fill { - ($arr:ident) => ({ + ($arr:ident) => {{ let arr = $arr::new(&4.into()); arr.for_each(&mut |x, _, _| { assert_eq!(x as f64, 0.0); @@ -82,7 +82,7 @@ macro_rules! test_fill { assert_eq!(x as f64, 0.0); } }); - }) + }}; } #[wasm_bindgen_test] fn new_fill() { diff --git a/crates/js-sys/tests/wasm/UriError.rs b/crates/js-sys/tests/wasm/UriError.rs index df939e5d8..0e5720c51 100644 --- a/crates/js-sys/tests/wasm/UriError.rs +++ b/crates/js-sys/tests/wasm/UriError.rs @@ -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 uri_error() { diff --git a/crates/js-sys/tests/wasm/WeakMap.rs b/crates/js-sys/tests/wasm/WeakMap.rs index 9b3f0d78b..1eab1cb9d 100644 --- a/crates/js-sys/tests/wasm/WeakMap.rs +++ b/crates/js-sys/tests/wasm/WeakMap.rs @@ -1,10 +1,10 @@ -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen] -extern { +extern "C" { type SomeKey; #[wasm_bindgen(method, setter, structural)] fn set_some(this: &SomeKey, val: JsValue); diff --git a/crates/js-sys/tests/wasm/WeakSet.rs b/crates/js-sys/tests/wasm/WeakSet.rs index 541bd4486..094038b5f 100644 --- a/crates/js-sys/tests/wasm/WeakSet.rs +++ b/crates/js-sys/tests/wasm/WeakSet.rs @@ -1,10 +1,10 @@ -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; -use wasm_bindgen::JsCast; use js_sys::*; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen] -extern { +extern "C" { type SomeValue; #[wasm_bindgen(method, setter, structural)] fn set_some(this: &SomeValue, val: JsValue); diff --git a/crates/js-sys/tests/wasm/WebAssembly.rs b/crates/js-sys/tests/wasm/WebAssembly.rs index f67c742b7..301ba164e 100644 --- a/crates/js-sys/tests/wasm/WebAssembly.rs +++ b/crates/js-sys/tests/wasm/WebAssembly.rs @@ -186,10 +186,9 @@ fn instantiate_module() -> impl Future { let module = WebAssembly::Module::new(&get_valid_wasm()).unwrap(); let imports = get_imports(); let p = WebAssembly::instantiate_module(&module, &imports); - JsFuture::from(p) - .map(|inst| { - assert!(inst.is_instance_of::()); - }) + JsFuture::from(p).map(|inst| { + assert!(inst.is_instance_of::()); + }) } #[wasm_bindgen_test(async)] @@ -197,14 +196,13 @@ fn instantiate_streaming() -> impl Future { let response = Promise::resolve(&get_valid_wasm()); let imports = get_imports(); let p = WebAssembly::instantiate_streaming(&response, &imports); - JsFuture::from(p) - .map(|obj| { - assert!( - Reflect::get(obj.as_ref(), &"instance".into()) - .unwrap() - .is_instance_of::() - ); - }) + JsFuture::from(p).map(|obj| { + assert!( + Reflect::get(obj.as_ref(), &"instance".into()) + .unwrap() + .is_instance_of::() + ); + }) } #[wasm_bindgen_test] diff --git a/crates/js-sys/tests/wasm/global_fns.rs b/crates/js-sys/tests/wasm/global_fns.rs index ec0e2a673..1a2c5e1c5 100644 --- a/crates/js-sys/tests/wasm/global_fns.rs +++ b/crates/js-sys/tests/wasm/global_fns.rs @@ -1,7 +1,7 @@ -use std::f64::{NAN, INFINITY}; +use std::f64::{INFINITY, NAN}; -use wasm_bindgen_test::*; use js_sys::*; +use wasm_bindgen_test::*; #[wasm_bindgen_test] fn test_decode_uri() { diff --git a/crates/js-sys/tests/wasm/main.rs b/crates/js-sys/tests/wasm/main.rs index 3dd249c39..05d298747 100755 --- a/crates/js-sys/tests/wasm/main.rs +++ b/crates/js-sys/tests/wasm/main.rs @@ -7,7 +7,6 @@ extern crate wasm_bindgen; extern crate wasm_bindgen_futures; extern crate wasm_bindgen_test; -pub mod global_fns; pub mod Array; pub mod ArrayBuffer; pub mod ArrayIterator; @@ -20,8 +19,8 @@ pub mod Function; pub mod Generator; pub mod Intl; pub mod Iterator; -pub mod JsString; pub mod JSON; +pub mod JsString; pub mod Map; pub mod MapIterator; pub mod Math; @@ -43,3 +42,4 @@ pub mod UriError; pub mod WeakMap; pub mod WeakSet; pub mod WebAssembly; +pub mod global_fns; diff --git a/crates/macro-support/src/lib.rs b/crates/macro-support/src/lib.rs index 361d60461..e702e6a3c 100644 --- a/crates/macro-support/src/lib.rs +++ b/crates/macro-support/src/lib.rs @@ -11,9 +11,9 @@ extern crate syn; extern crate wasm_bindgen_backend as backend; extern crate wasm_bindgen_shared as shared; +use backend::{Diagnostic, TryToTokens}; pub use parser::BindgenAttrs; use parser::MacroParse; -use backend::{Diagnostic, TryToTokens}; use proc_macro2::TokenStream; mod parser; diff --git a/crates/macro-support/src/parser.rs b/crates/macro-support/src/parser.rs index 7a870a731..96cf82c7b 100644 --- a/crates/macro-support/src/parser.rs +++ b/crates/macro-support/src/parser.rs @@ -197,11 +197,13 @@ impl BindgenAttrs { impl Parse for BindgenAttrs { fn parse(input: ParseStream) -> SynResult { if input.is_empty() { - return Ok(BindgenAttrs { attrs: Vec::new() }) + return Ok(BindgenAttrs { attrs: Vec::new() }); } let opts = syn::punctuated::Punctuated::<_, syn::token::Comma>::parse_terminated(input)?; - Ok(BindgenAttrs { attrs: opts.into_iter().collect() }) + Ok(BindgenAttrs { + attrs: opts.into_iter().collect(), + }) } } @@ -232,65 +234,65 @@ impl Parse for BindgenAttr { let original = input.fork(); let attr: Ident = input.parse()?; if attr == "catch" { - return Ok(BindgenAttr::Catch) + return Ok(BindgenAttr::Catch); } if attr == "constructor" { - return Ok(BindgenAttr::Constructor) + return Ok(BindgenAttr::Constructor); } if attr == "method" { - return Ok(BindgenAttr::Method) + return Ok(BindgenAttr::Method); } if attr == "indexing_getter" { - return Ok(BindgenAttr::IndexingGetter) + return Ok(BindgenAttr::IndexingGetter); } if attr == "indexing_setter" { - return Ok(BindgenAttr::IndexingSetter) + return Ok(BindgenAttr::IndexingSetter); } if attr == "indexing_deleter" { - return Ok(BindgenAttr::IndexingDeleter) + return Ok(BindgenAttr::IndexingDeleter); } if attr == "structural" { - return Ok(BindgenAttr::Structural) + return Ok(BindgenAttr::Structural); } if attr == "readonly" { - return Ok(BindgenAttr::Readonly) + return Ok(BindgenAttr::Readonly); } if attr == "variadic" { - return Ok(BindgenAttr::Variadic) + return Ok(BindgenAttr::Variadic); } if attr == "static_method_of" { input.parse::()?; - return Ok(BindgenAttr::StaticMethodOf(input.parse::()?.0)) + return Ok(BindgenAttr::StaticMethodOf(input.parse::()?.0)); } if attr == "getter" { if input.parse::().is_ok() { - return Ok(BindgenAttr::Getter(Some(input.parse::()?.0))) + return Ok(BindgenAttr::Getter(Some(input.parse::()?.0))); } else { - return Ok(BindgenAttr::Getter(None)) + return Ok(BindgenAttr::Getter(None)); } } if attr == "setter" { if input.parse::().is_ok() { - return Ok(BindgenAttr::Setter(Some(input.parse::()?.0))) + return Ok(BindgenAttr::Setter(Some(input.parse::()?.0))); } else { - return Ok(BindgenAttr::Setter(None)) + return Ok(BindgenAttr::Setter(None)); } } if attr == "js_namespace" { input.parse::()?; - return Ok(BindgenAttr::JsNamespace(input.parse::()?.0)) + return Ok(BindgenAttr::JsNamespace(input.parse::()?.0)); } if attr == "extends" { input.parse::()?; - return Ok(BindgenAttr::Extends(input.parse::()?.0)) + return Ok(BindgenAttr::Extends(input.parse::()?.0)); } if attr == "module" { input.parse::()?; - return Ok(BindgenAttr::Module(input.parse::()?.value())) + return Ok(BindgenAttr::Module(input.parse::()?.value())); } if attr == "js_class" { input.parse::()?; - return Ok(BindgenAttr::JsClass(input.parse::()?.value())) + return Ok(BindgenAttr::JsClass(input.parse::()?.value())); } if attr == "js_name" { input.parse::()?; @@ -301,7 +303,7 @@ impl Parse for BindgenAttr { (ident.to_string(), ident.span()) } }; - return Ok(BindgenAttr::JsName(val, span)) + return Ok(BindgenAttr::JsName(val, span)); } Err(original.error("unknown attribute")) @@ -312,11 +314,9 @@ struct AnyIdent(Ident); impl Parse for AnyIdent { fn parse(input: ParseStream) -> SynResult { - input.step(|cursor| { - match cursor.ident() { - Some((ident, remaining)) => Ok((AnyIdent(ident), remaining)), - None => Err(cursor.error("expected an identifier")), - } + input.step(|cursor| match cursor.ident() { + Some((ident, remaining)) => Ok((AnyIdent(ident), remaining)), + None => Err(cursor.error("expected an identifier")), }) } } @@ -563,9 +563,10 @@ impl ConvertToAst for syn::ForeignItemType { impl<'a> ConvertToAst<(BindgenAttrs, &'a Option)> for syn::ForeignItemStatic { type Target = ast::ImportKind; - fn convert(self, (opts, module): (BindgenAttrs, &'a Option)) - -> Result - { + fn convert( + self, + (opts, module): (BindgenAttrs, &'a Option), + ) -> Result { if self.mutability.is_some() { bail_span!(self.mutability, "cannot import mutable globals yet") } @@ -606,7 +607,15 @@ impl ConvertToAst for syn::ItemFn { } assert_not_variadic(&attrs, &self)?; - Ok(function_from_decl(&self.ident, &attrs, self.decl, self.attrs, self.vis, false, None)?.0) + Ok(function_from_decl( + &self.ident, + &attrs, + self.decl, + self.attrs, + self.vis, + false, + None, + )?.0) } } @@ -687,7 +696,9 @@ fn function_from_decl( let js_name = opts.js_name(); Ok(( ast::Function { - name: js_name.map(|s| s.0.to_string()).unwrap_or(decl_name.to_string()), + name: js_name + .map(|s| s.0.to_string()) + .unwrap_or(decl_name.to_string()), name_span: js_name.map(|s| s.1).unwrap_or(decl_name.span()), renamed_via_js_name: js_name.is_some(), arguments, @@ -1031,28 +1042,31 @@ fn extract_first_ty_param(ty: Option<&syn::Type>) -> Result, D /// Extract the documentation comments from a Vec of attributes fn extract_doc_comments(attrs: &[syn::Attribute]) -> Vec { attrs - .iter() - .filter_map(|a| { - // if the path segments include an ident of "doc" we know this - // this is a doc comment - if a.path.segments.iter().any(|s| s.ident.to_string() == "doc") { - Some( - // We want to filter out any Puncts so just grab the Literals - a.tts.clone().into_iter().filter_map(|t| match t { - TokenTree::Literal(lit) => { - // this will always return the quoted string, we deal with - // that in the cli when we read in the comments - Some(lit.to_string()) - }, - _ => None, - }) - ) - } else { - None - } - }) - //Fold up the [[String]] iter we created into Vec - .fold(vec![], |mut acc, a| {acc.extend(a); acc}) + .iter() + .filter_map(|a| { + // if the path segments include an ident of "doc" we know this + // this is a doc comment + if a.path.segments.iter().any(|s| s.ident.to_string() == "doc") { + Some( + // We want to filter out any Puncts so just grab the Literals + a.tts.clone().into_iter().filter_map(|t| match t { + TokenTree::Literal(lit) => { + // this will always return the quoted string, we deal with + // that in the cli when we read in the comments + Some(lit.to_string()) + } + _ => None, + }), + ) + } else { + None + } + }) + //Fold up the [[String]] iter we created into Vec + .fold(vec![], |mut acc, a| { + acc.extend(a); + acc + }) } /// Check there are no lifetimes on the function. @@ -1080,8 +1094,11 @@ fn assert_no_lifetimes(decl: &syn::FnDecl) -> Result<(), Diagnostic> { /// This method always fails if the BindgenAttrs contain variadic fn assert_not_variadic(attrs: &BindgenAttrs, span: &dyn ToTokens) -> Result<(), Diagnostic> { if attrs.variadic() { - bail_span!(span, "the `variadic` attribute can only be applied to imported \ - (`extern`) functions") + bail_span!( + span, + "the `variadic` attribute can only be applied to imported \ + (`extern`) functions" + ) } Ok(()) } diff --git a/crates/test-macro/src/lib.rs b/crates/test-macro/src/lib.rs index 19b775902..9f64413a2 100644 --- a/crates/test-macro/src/lib.rs +++ b/crates/test-macro/src/lib.rs @@ -6,8 +6,8 @@ extern crate proc_macro2; #[macro_use] extern crate quote; -use std::sync::atomic::*; use proc_macro2::*; +use std::sync::atomic::*; static CNT: AtomicUsize = ATOMIC_USIZE_INIT; @@ -38,7 +38,7 @@ pub fn wasm_bindgen_test( leading_tokens.push(token.clone()); if let TokenTree::Ident(token) = token { if token == "fn" { - break + break; } } } @@ -58,18 +58,24 @@ pub fn wasm_bindgen_test( // We generate a `#[no_mangle]` with a known prefix so the test harness can // later slurp up all of these functions and pass them as arguments to the // main test harness. This is the entry point for all tests. - let name = format!("__wbg_test_{}_{}", ident, CNT.fetch_add(1, Ordering::SeqCst)); + let name = format!( + "__wbg_test_{}_{}", + ident, + CNT.fetch_add(1, Ordering::SeqCst) + ); let name = Ident::new(&name, Span::call_site()); - tokens.extend((quote! { - #[no_mangle] - pub extern fn #name(cx: *const ::wasm_bindgen_test::__rt::Context) { - unsafe { - let cx = &*cx; - let test_name = concat!(module_path!(), "::", stringify!(#ident)); - #test_body + tokens.extend( + (quote! { + #[no_mangle] + pub extern fn #name(cx: *const ::wasm_bindgen_test::__rt::Context) { + unsafe { + let cx = &*cx; + let test_name = concat!(module_path!(), "::", stringify!(#ident)); + #test_body + } } - } - }).into_iter()); + }).into_iter(), + ); tokens.extend(leading_tokens); tokens.push(ident.into()); diff --git a/crates/test/sample/src/lib.rs b/crates/test/sample/src/lib.rs index 02b0a2e3f..23852f99a 100644 --- a/crates/test/sample/src/lib.rs +++ b/crates/test/sample/src/lib.rs @@ -17,7 +17,7 @@ pub struct Timeout { } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = setTimeout)] fn set_timeout(closure: JsValue, millis: f64) -> u32; @@ -27,7 +27,8 @@ extern { impl Timeout { pub fn new(dur: Duration) -> Timeout { - let millis = dur.as_secs() + let millis = dur + .as_secs() .checked_mul(1000) .unwrap() .checked_add(dur.subsec_millis() as u64) diff --git a/crates/test/sample/tests/common/mod.rs b/crates/test/sample/tests/common/mod.rs index f8679a8c8..cde7d6deb 100644 --- a/crates/test/sample/tests/common/mod.rs +++ b/crates/test/sample/tests/common/mod.rs @@ -1,9 +1,9 @@ use std::time::Duration; use futures::prelude::*; +use sample::Timeout; use wasm_bindgen::prelude::*; use wasm_bindgen_test::*; -use sample::Timeout; #[wasm_bindgen_test] fn pass() { @@ -13,13 +13,12 @@ fn pass() { #[wasm_bindgen_test(async)] fn pass_after_2s() -> impl Future { console_log!("immediate log"); - Timeout::new(Duration::new(1, 0)) - .and_then(|()| { - console_log!("log after 1s"); - Timeout::new(Duration::new(1, 0)).map(|()| { - console_log!("log at end"); - }) + Timeout::new(Duration::new(1, 0)).and_then(|()| { + console_log!("log after 1s"); + Timeout::new(Duration::new(1, 0)).map(|()| { + console_log!("log at end"); }) + }) } #[wasm_bindgen_test] @@ -31,15 +30,13 @@ fn fail() { #[wasm_bindgen_test(async)] fn fail_after_3s() -> impl Future { console_log!("immediate log"); - Timeout::new(Duration::new(1, 0)) - .and_then(|()| { - console_log!("log after 1s"); - Timeout::new(Duration::new(1, 0)).and_then(|()| { - console_log!("log after 2s"); - Timeout::new(Duration::new(1, 0)).map(|()| { - panic!("end"); - }) + Timeout::new(Duration::new(1, 0)).and_then(|()| { + console_log!("log after 1s"); + Timeout::new(Duration::new(1, 0)).and_then(|()| { + console_log!("log after 2s"); + Timeout::new(Duration::new(1, 0)).map(|()| { + panic!("end"); }) }) + }) } - diff --git a/crates/test/src/rt/browser.rs b/crates/test/src/rt/browser.rs index 2fab7e229..fc97d5adb 100644 --- a/crates/test/src/rt/browser.rs +++ b/crates/test/src/rt/browser.rs @@ -3,8 +3,8 @@ //! Currently this is quite simple, rendering the same as the console tests in //! node.js. Output here is rendered in a `pre`, however. -use wasm_bindgen::prelude::*; use js_sys::Error; +use wasm_bindgen::prelude::*; /// Implementation of `Formatter` for browsers. /// @@ -15,7 +15,7 @@ pub struct Browser { } #[wasm_bindgen] -extern { +extern "C" { type HTMLDocument; static document: HTMLDocument; #[wasm_bindgen(method, structural)] @@ -38,9 +38,7 @@ impl Browser { pub fn new() -> Browser { let pre = document.getElementById("output"); pre.set_inner_html(""); - Browser { - pre, - } + Browser { pre } } } @@ -75,11 +73,10 @@ impl super::Formatter for Browser { // probably a chome-like error which is already rendered well, so just // return this info if stack.contains(&header) { - return stack + return stack; } // Fallback to make sure we don't lose any info format!("{}\n{}", header, stack) } } - diff --git a/crates/test/src/rt/detect.rs b/crates/test/src/rt/detect.rs index ab5a23004..295e7c53d 100644 --- a/crates/test/src/rt/detect.rs +++ b/crates/test/src/rt/detect.rs @@ -1,11 +1,11 @@ //! Runtime detection of whether we're in node.js or a browser. +use js_sys; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; -use js_sys; #[wasm_bindgen] -extern { +extern "C" { type This; #[wasm_bindgen(method, getter, structural, js_name = self)] fn self_(me: &This) -> JsValue; diff --git a/crates/test/src/rt/mod.rs b/crates/test/src/rt/mod.rs index 83e80facd..7722095af 100644 --- a/crates/test/src/rt/mod.rs +++ b/crates/test/src/rt/mod.rs @@ -87,8 +87,7 @@ // Overall this is all somewhat in flux as it's pretty new, and feedback is // always of course welcome! - -use std::cell::{RefCell, Cell}; +use std::cell::{Cell, RefCell}; use std::fmt; use std::rc::Rc; @@ -107,9 +106,9 @@ use wasm_bindgen_futures::future_to_promise; // conccurrently doing things by default would likely end up in a bad situation. const CONCURRENCY: usize = 1; -pub mod node; pub mod browser; pub mod detect; +pub mod node; /// Runtime test harness support instantiated in JS. /// @@ -182,7 +181,7 @@ trait Formatter { } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_namespace = console, js_name = log)] #[doc(hidden)] pub fn js_console_log(s: &str); @@ -259,7 +258,9 @@ impl Context { /// `false` if at least one test failed. pub fn run(&self, tests: Vec) -> Promise { let noun = if tests.len() == 1 { "test" } else { "tests" }; - self.state.formatter.writeln(&format!("running {} {}", tests.len(), noun)); + self.state + .formatter + .writeln(&format!("running {} {}", tests.len(), noun)); self.state.formatter.writeln(""); // Execute all our test functions through their wasm shims (unclear how @@ -271,8 +272,10 @@ impl Context { match Function::from(test).call1(&JsValue::null(), &cx_arg) { Ok(_) => {} Err(e) => { - panic!("exception thrown while creating a test: {}", - self.state.formatter.stringify_error(&e)); + panic!( + "exception thrown while creating a test: {}", + self.state.formatter.stringify_error(&e) + ); } } } @@ -280,7 +283,8 @@ impl Context { // Now that we've collected all our tests we wrap everything up in a // future to actually do all the processing, and pass it out to JS as a // `Promise`. - let future = ExecuteTests(self.state.clone()).map(JsValue::from) + let future = ExecuteTests(self.state.clone()) + .map(JsValue::from) .map_err(|e| match e {}); future_to_promise(future) } @@ -316,7 +320,7 @@ pub fn __wbgtest_console_error(original: &Function, args: &Array) { fn record(orig: &Function, args: &Array, dst: impl FnOnce(&mut Output) -> &mut String) { if !CURRENT_OUTPUT.is_set() { drop(orig.apply(&JsValue::null(), args)); - return + return; } CURRENT_OUTPUT.with(|output| { @@ -343,16 +347,13 @@ impl Context { /// `#[wasm_bindgen_test(async)]` macro generates invocations of this /// method. pub fn execute_async(&self, name: &str, f: impl FnOnce() -> F + 'static) - where F: Future + 'static, + where + F: Future + 'static, { self.execute(name, future::lazy(f)) } - fn execute( - &self, - name: &str, - test: impl Future + 'static, - ) { + fn execute(&self, name: &str, test: impl Future + 'static) { // If our test is filtered out, record that it was filtered and move // on, nothing to do here. let filter = self.state.filter.borrow(); @@ -360,7 +361,7 @@ impl Context { if !name.contains(filter) { let ignored = self.state.ignored.get(); self.state.ignored.set(ignored + 1); - return + return; } } @@ -416,7 +417,7 @@ impl Future for ExecuteTests { Ok(Async::Ready(())) => Ok(()), Ok(Async::NotReady) => { running.push(test); - continue + continue; } Err(e) => Err(e), }; @@ -426,7 +427,7 @@ impl Future for ExecuteTests { // Tests are still executing, we're registered to get a notification, // keep going. if running.len() != 0 { - return Ok(Async::NotReady) + return Ok(Async::NotReady); } // If there are no tests running then we must have finished everything, @@ -532,7 +533,7 @@ struct TestFuture { } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(catch)] fn __wbg_test_invoke(f: &mut FnMut()) -> Result<(), JsValue>; } diff --git a/crates/test/src/rt/node.rs b/crates/test/src/rt/node.rs index 94da15011..ecfa4bd4f 100644 --- a/crates/test/src/rt/node.rs +++ b/crates/test/src/rt/node.rs @@ -6,11 +6,10 @@ use wasm_bindgen::prelude::*; /// Implementation of the `Formatter` trait for node.js -pub struct Node { -} +pub struct Node {} #[wasm_bindgen] -extern { +extern "C" { // Not using `js_sys::Error` because node's errors specifically have a // `stack` attribute. type NodeError; @@ -23,9 +22,9 @@ impl Node { /// is executing in a browser and Node won't work. pub fn new() -> Option { if super::detect::is_browser() { - return None + return None; } - Some(Node { }) + Some(Node {}) } } diff --git a/crates/typescript/src/parser.rs b/crates/typescript/src/parser.rs index 0421e5519..24fc38343 100644 --- a/crates/typescript/src/parser.rs +++ b/crates/typescript/src/parser.rs @@ -93,8 +93,7 @@ fn build_function( segments, }, }) - }) - .collect::>(); + }).collect::>(); let mut ret_segments = syn::punctuated::Punctuated::new(); ret_segments.push(syn::PathSegment { diff --git a/crates/wasm-interpreter/src/lib.rs b/crates/wasm-interpreter/src/lib.rs index aa28314a7..80ffe6291 100644 --- a/crates/wasm-interpreter/src/lib.rs +++ b/crates/wasm-interpreter/src/lib.rs @@ -119,7 +119,7 @@ impl Interpreter { _ => continue, } if entry.module() != "__wbindgen_placeholder__" { - continue + continue; } if entry.field() == "__wbindgen_describe" { ret.describe_idx = Some(idx - 1 as u32); @@ -140,7 +140,7 @@ impl Interpreter { } } - return ret + return ret; } /// Interprets the execution of the descriptor function `func`. @@ -163,22 +163,14 @@ impl Interpreter { /// /// Returns `Some` if `func` was found in the `module` and `None` if it was /// not found in the `module`. - pub fn interpret_descriptor( - &mut self, - func: &str, - module: &Module, - ) -> Option<&[u32]> { + pub fn interpret_descriptor(&mut self, func: &str, module: &Module) -> Option<&[u32]> { let idx = *self.name_map.get(func)?; self.with_sections(module, |me, sections| { me.interpret_descriptor_idx(idx, sections) }) } - fn interpret_descriptor_idx( - &mut self, - idx: u32, - sections: &Sections, - ) -> Option<&[u32]> { + fn interpret_descriptor_idx(&mut self, idx: u32, sections: &Sections) -> Option<&[u32]> { self.descriptor.truncate(0); // We should have a blank wasm and LLVM stack at both the start and end @@ -250,27 +242,27 @@ impl Interpreter { // After we've got the table index of the descriptor function we're // interested go take a look in the function table to find what the // actual index of the function is. - let (entry_idx, offset, entry) = sections.elements.entries() + let (entry_idx, offset, entry) = sections + .elements + .entries() .iter() .enumerate() .filter_map(|(i, entry)| { let code = entry.offset().code(); if code.len() != 2 { - return None + return None; } if code[1] != Instruction::End { - return None + return None; } match code[0] { Instruction::I32Const(x) => Some((i, x as u32, entry)), _ => None, } - }) - .find(|(_i, offset, entry)| { - *offset <= descriptor_table_idx && - descriptor_table_idx < (*offset + entry.members().len() as u32) - }) - .expect("failed to find index in table elements"); + }).find(|(_i, offset, entry)| { + *offset <= descriptor_table_idx + && descriptor_table_idx < (*offset + entry.members().len() as u32) + }).expect("failed to find index in table elements"); let idx = (descriptor_table_idx - offset) as usize; let descriptor_idx = entry.members()[idx]; @@ -299,13 +291,13 @@ impl Interpreter { // Allocate space for our call frame's local variables. All local // variables should be of the `i32` type. assert!(body.locals().len() <= 1, "too many local types"); - let nlocals = body.locals() + let nlocals = body + .locals() .get(0) .map(|i| { assert_eq!(i.value_type(), ValueType::I32); i.count() - }) - .unwrap_or(0); + }).unwrap_or(0); let code_sig = sections.functions.entries()[code_idx].type_ref(); let function_ty = match §ions.types.types()[code_sig as usize] { @@ -352,8 +344,7 @@ impl Interpreter { if Some(*idx) == self.describe_idx { self.descriptor.push(self.stack.pop().unwrap() as u32); } else if Some(*idx) == self.describe_closure_idx { - self.descriptor_table_idx = - Some(self.stack.pop().unwrap() as u32); + self.descriptor_table_idx = Some(self.stack.pop().unwrap() as u32); self.stack.pop(); self.stack.pop(); self.stack.push(0); @@ -428,6 +419,14 @@ impl Interpreter { let functions = module.sections[self.functions_idx] (Function); let elements = module.sections[self.elements_idx] (Element); } - f(self, &Sections { code, types, functions, elements }) + f( + self, + &Sections { + code, + types, + functions, + elements, + }, + ) } } diff --git a/crates/wasm-interpreter/tests/smoke.rs b/crates/wasm-interpreter/tests/smoke.rs index f2fe894d5..184d6f368 100644 --- a/crates/wasm-interpreter/tests/smoke.rs +++ b/crates/wasm-interpreter/tests/smoke.rs @@ -13,7 +13,8 @@ fn interpret(wat: &str, name: &str, result: Option<&[u32]>) { fs::write(input.path(), wat).unwrap(); let status = Command::new("wat2wasm") .arg(input.path()) - .arg("-o").arg(output.path()) + .arg("-o") + .arg(output.path()) .status() .unwrap(); println!("status: {}", status); diff --git a/crates/web-sys/build.rs b/crates/web-sys/build.rs index f71acc47c..82b4138fe 100644 --- a/crates/web-sys/build.rs +++ b/crates/web-sys/build.rs @@ -1,8 +1,8 @@ extern crate env_logger; #[macro_use] extern crate failure; -extern crate wasm_bindgen_webidl; extern crate sourcefile; +extern crate wasm_bindgen_webidl; use failure::{Fail, ResultExt}; use sourcefile::SourceFile; @@ -35,10 +35,11 @@ fn try_main() -> Result<(), failure::Error> { let entry = entry.context("getting webidls/enabled/*.webidl entry")?; let path = entry.path(); if path.extension() != Some(OsStr::new("webidl")) { - continue + continue; } println!("cargo:rerun-if-changed={}", path.display()); - source = source.add_file(&path) + source = source + .add_file(&path) .with_context(|_| format!("reading contents of file \"{}\"", path.display()))?; } @@ -48,7 +49,9 @@ fn try_main() -> Result<(), failure::Error> { // the webidl compiler. let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); let manifest = fs::read_to_string(manifest_dir.join("Cargo.toml"))?; - let features = manifest.lines().skip_while(|f| !f.starts_with("[features]")); + let features = manifest + .lines() + .skip_while(|f| !f.starts_with("[features]")); let enabled_features = env::vars() .map(|p| p.0) @@ -56,8 +59,7 @@ fn try_main() -> Result<(), failure::Error> { .map(|mut p| { p.drain(0.."CARGO_FEATURE_".len()); p - }) - .collect::>(); + }).collect::>(); let mut allowed = Vec::new(); for feature in features.filter(|f| !f.starts_with("#") && !f.starts_with("[")) { @@ -81,23 +83,31 @@ fn try_main() -> Result<(), failure::Error> { Err(e) => match e.kind() { wasm_bindgen_webidl::ErrorKind::ParsingWebIDLSourcePos(pos) => { if let Some(pos) = source.resolve_offset(pos) { - let ctx = format!("compiling WebIDL into wasm-bindgen bindings in file \ - \"{}\", line {} column {}", pos.filename, pos.line + 1, pos.col + 1); + let ctx = format!( + "compiling WebIDL into wasm-bindgen bindings in file \ + \"{}\", line {} column {}", + pos.filename, + pos.line + 1, + pos.col + 1 + ); return Err(e.context(ctx).into()); } else { - return Err(e.context("compiling WebIDL into wasm-bindgen bindings").into()); + return Err(e + .context("compiling WebIDL into wasm-bindgen bindings") + .into()); } } _ => { - return Err(e.context("compiling WebIDL into wasm-bindgen bindings").into()); + return Err(e + .context("compiling WebIDL into wasm-bindgen bindings") + .into()); } - } + }, }; let out_dir = env::var("OUT_DIR").context("reading OUT_DIR environment variable")?; let out_file_path = path::Path::new(&out_dir).join("bindings.rs"); - fs::write(&out_file_path, bindings) - .context("writing bindings to output file")?; + fs::write(&out_file_path, bindings).context("writing bindings to output file")?; // run rustfmt on the generated file - really handy for debugging println!("cargo:rerun-if-env-changed=WEBIDL_RUSTFMT_BINDINGS"); @@ -113,4 +123,3 @@ fn try_main() -> Result<(), failure::Error> { Ok(()) } - diff --git a/crates/web-sys/src/lib.rs b/crates/web-sys/src/lib.rs index 4ec678634..724b72711 100755 --- a/crates/web-sys/src/lib.rs +++ b/crates/web-sys/src/lib.rs @@ -13,8 +13,8 @@ #![doc(html_root_url = "https://docs.rs/web-sys/0.2")] -extern crate wasm_bindgen; extern crate js_sys; +extern crate wasm_bindgen; use js_sys::Object; diff --git a/crates/web-sys/tests/wasm/anchor_element.rs b/crates/web-sys/tests/wasm/anchor_element.rs index 367c6fc54..9585d1a97 100644 --- a/crates/web-sys/tests/wasm/anchor_element.rs +++ b/crates/web-sys/tests/wasm/anchor_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlAnchorElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_a() -> HtmlAnchorElement; } @@ -26,9 +26,17 @@ fn test_anchor_element() { element.set_rel("boop"); assert_eq!(element.rel(), "boop", "Should have a rel"); - assert_eq!(element.referrer_policy(), "", "Shouldn't have a referrer_policy"); + assert_eq!( + element.referrer_policy(), + "", + "Shouldn't have a referrer_policy" + ); element.set_referrer_policy("origin"); - assert_eq!(element.referrer_policy(), "origin", "Should have a referrer_policy"); + assert_eq!( + element.referrer_policy(), + "origin", + "Should have a referrer_policy" + ); assert_eq!(element.hreflang(), "", "Shouldn't have a hreflang"); element.set_hreflang("en-us"); diff --git a/crates/web-sys/tests/wasm/body_element.rs b/crates/web-sys/tests/wasm/body_element.rs index abdb7487b..8e6639449 100644 --- a/crates/web-sys/tests/wasm/body_element.rs +++ b/crates/web-sys/tests/wasm/body_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlBodyElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_body() -> HtmlBodyElement; } diff --git a/crates/web-sys/tests/wasm/br_element.rs b/crates/web-sys/tests/wasm/br_element.rs index d21d93193..103559990 100644 --- a/crates/web-sys/tests/wasm/br_element.rs +++ b/crates/web-sys/tests/wasm/br_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlBrElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_br() -> HtmlBrElement; } diff --git a/crates/web-sys/tests/wasm/button_element.rs b/crates/web-sys/tests/wasm/button_element.rs index f32a38503..3d74f67d6 100644 --- a/crates/web-sys/tests/wasm/button_element.rs +++ b/crates/web-sys/tests/wasm/button_element.rs @@ -1,15 +1,15 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::{HtmlButtonElement, HtmlFormElement, Node}; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_button() -> HtmlButtonElement; fn new_form() -> HtmlFormElement; } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = location, js_namespace = document)] static LOCATION: Location; @@ -37,13 +37,25 @@ fn test_button_element() { _ => assert!(false, "Shouldn't have a form"), }; - assert_eq!(element.form_action(), location, "Should have the pages location"); + assert_eq!( + element.form_action(), + location, + "Should have the pages location" + ); element.set_form_action("http://boop.com/"); - assert_eq!(element.form_action(), "http://boop.com/", "Should have a form_action"); + assert_eq!( + element.form_action(), + "http://boop.com/", + "Should have a form_action" + ); assert_eq!(element.form_enctype(), "", "Should have no enctype"); element.set_form_enctype("text/plain"); - assert_eq!(element.form_enctype(), "text/plain", "Should have a plain text enctype"); + assert_eq!( + element.form_enctype(), + "text/plain", + "Should have a plain text enctype" + ); assert_eq!(element.form_method(), "", "Should have no method"); element.set_form_method("POST"); @@ -55,7 +67,11 @@ fn test_button_element() { assert_eq!(element.form_target(), "", "Should have no target"); element.set_form_target("_blank"); - assert_eq!(element.form_target(), "_blank", "Should have a _blank target"); + assert_eq!( + element.form_target(), + "_blank", + "Should have a _blank target" + ); assert_eq!(element.name(), "", "Shouldn't have a name"); element.set_name("button-name"); @@ -70,14 +86,22 @@ fn test_button_element() { assert_eq!(element.value(), "value1", "Should have a value"); assert_eq!(element.will_validate(), false, "Shouldn't validate"); - assert_eq!(element.validation_message().unwrap(), "", "Shouldn't have a value"); + assert_eq!( + element.validation_message().unwrap(), + "", + "Shouldn't have a value" + ); assert_eq!(element.check_validity(), true, "Should be valid"); assert_eq!(element.report_validity(), true, "Should be valid"); element.set_custom_validity("Boop"); // Method exists but doesn't impact validity assert_eq!(element.check_validity(), true, "Should be valid"); assert_eq!(element.report_validity(), true, "Should be valid"); - assert_eq!(element.labels().length(), 0, "Should return a node list with no elements"); + assert_eq!( + element.labels().length(), + 0, + "Should return a node list with no elements" + ); } #[wasm_bindgen_test] @@ -90,15 +114,21 @@ fn test_button_element_in_form() { // TODO: implement `Clone` for types in `web_sys` to make this easier. let button = JsValue::from(button); let as_node = Node::from(button.clone()); - Node::from(JsValue::from(form)).append_child(&as_node).unwrap(); + Node::from(JsValue::from(form)) + .append_child(&as_node) + .unwrap(); let element = HtmlButtonElement::from(button); match element.form() { None => assert!(false, "Should have a form"), Some(form) => { assert!(true, "Should have a form"); - assert_eq!(form.name(), "test-form", "Form should have a name of test-form"); - }, + assert_eq!( + form.name(), + "test-form", + "Form should have a name of test-form" + ); + } }; assert_eq!(element.type_(), "reset", "Should have a type"); } diff --git a/crates/web-sys/tests/wasm/div_element.rs b/crates/web-sys/tests/wasm/div_element.rs index 7f58cc39f..e4a612f62 100644 --- a/crates/web-sys/tests/wasm/div_element.rs +++ b/crates/web-sys/tests/wasm/div_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlDivElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_div() -> HtmlDivElement; } diff --git a/crates/web-sys/tests/wasm/element.rs b/crates/web-sys/tests/wasm/element.rs index 162e74e84..041d9d0c4 100644 --- a/crates/web-sys/tests/wasm/element.rs +++ b/crates/web-sys/tests/wasm/element.rs @@ -1,15 +1,15 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::Element; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_div() -> Element; } #[wasm_bindgen_test] fn element() { -/* Tests needed for: + /* Tests needed for: namespace_uri */ let element = new_div(); @@ -22,20 +22,40 @@ fn element() { assert_eq!(element.id(), "beep", "Should have an id of 'beep'"); // must_use is set on this result? - assert_eq!(element.set_attribute("id", "beep").unwrap(), (), "Should set id"); + assert_eq!( + element.set_attribute("id", "beep").unwrap(), + (), + "Should set id" + ); assert!(element.has_attribute("id"), "Should now have an id"); - assert_eq!(element.remove_attribute("id").unwrap(), (), "Should return nothing if removed"); + assert_eq!( + element.remove_attribute("id").unwrap(), + (), + "Should return nothing if removed" + ); assert_eq!(element.class_name(), "", "Shouldn't have a class name"); element.set_class_name("test thing"); - assert_eq!(element.class_name(), "test thing", "Should have a class name"); - assert_eq!(element.get_attribute("class").unwrap(), "test thing", "Should have a class name"); - assert_eq!(element.remove_attribute("class").unwrap(), (), "Should return nothing if removed"); -/* Tests needed for: + assert_eq!( + element.class_name(), + "test thing", + "Should have a class name" + ); + assert_eq!( + element.get_attribute("class").unwrap(), + "test thing", + "Should have a class name" + ); + assert_eq!( + element.remove_attribute("class").unwrap(), + (), + "Should return nothing if removed" + ); + /* Tests needed for: get_attribute_ns */ -/*TODO should we enable toggle_attribute tests? (Firefox Nightly + Chrome canary only) + /*TODO should we enable toggle_attribute tests? (Firefox Nightly + Chrome canary only) // TODO toggle_attribute should permit a single argument when optional arguments are supported assert!(!element.has_attribute("disabled"), "Should not be disabled"); assert!(element.toggle_attribute("disabled", true).unwrap(), "Should return true when attribute is set"); @@ -45,35 +65,71 @@ get_attribute_ns */ assert!(!element.has_attribute("title"), "Should not have a title"); - assert_eq!(element.set_attribute("title", "boop").unwrap(), (), "Should return nothing if set correctly"); + assert_eq!( + element.set_attribute("title", "boop").unwrap(), + (), + "Should return nothing if set correctly" + ); assert!(element.has_attribute("title"), "Should have a title"); // TODO check get_attribute here when supported - assert_eq!(element.remove_attribute("title").unwrap(), (), "Should return nothing if removed"); + assert_eq!( + element.remove_attribute("title").unwrap(), + (), + "Should return nothing if removed" + ); assert!(!element.has_attribute("title"), "Should not have a title"); -/* Tests needed for: + /* Tests needed for: set_attribute_ns */ assert!(!element.has_attributes(), "Should not have any attributes"); - assert_eq!(element.set_attribute("title", "boop").unwrap(), (), "Should return nothing if set correctly"); + assert_eq!( + element.set_attribute("title", "boop").unwrap(), + (), + "Should return nothing if set correctly" + ); assert!(element.has_attributes(), "Should have attributes"); - assert_eq!(element.remove_attribute("title").unwrap(), (), "Should return nothing if removed"); -/* Tests needed for: + assert_eq!( + element.remove_attribute("title").unwrap(), + (), + "Should return nothing if removed" + ); + /* Tests needed for: remove_attribute_ns has_attribure_ns closest */ - assert_eq!(element.matches(".this-is-a-thing").unwrap(), false, "Should not match selector"); - assert_eq!(element.webkit_matches_selector(".this-is-a-thing").unwrap(), false, "Should not match selector"); + assert_eq!( + element.matches(".this-is-a-thing").unwrap(), + false, + "Should not match selector" + ); + assert_eq!( + element.webkit_matches_selector(".this-is-a-thing").unwrap(), + false, + "Should not match selector" + ); element.set_class_name("this-is-a-thing"); - assert_eq!(element.matches(".this-is-a-thing").unwrap(), true, "Should match selector"); - assert_eq!(element.webkit_matches_selector(".this-is-a-thing").unwrap(), true, "Should match selector"); - assert_eq!(element.remove_attribute("class").unwrap(), (), "Should return nothing if removed"); + assert_eq!( + element.matches(".this-is-a-thing").unwrap(), + true, + "Should match selector" + ); + assert_eq!( + element.webkit_matches_selector(".this-is-a-thing").unwrap(), + true, + "Should match selector" + ); + assert_eq!( + element.remove_attribute("class").unwrap(), + (), + "Should return nothing if removed" + ); -// TODO non standard moz_matches_selector should we even support? + // TODO non standard moz_matches_selector should we even support? -/* Tests needed for: + /* Tests needed for: insert_adjacent_element insert_adjacent_text set_pointer_capture @@ -99,21 +155,42 @@ scroll_left_max */ assert_eq!(element.inner_html(), "", "Should return no content"); element.set_inner_html("Hey!Web!"); - assert_eq!(element.inner_html(), "Hey!Web!", "Should return HTML conent"); - assert_eq!(element.query_selector_all("strong").unwrap().length(), 1, "Should return one element"); - assert!(element.query_selector("strong").unwrap().is_some(), "Should return an element"); + assert_eq!( + element.inner_html(), + "Hey!Web!", + "Should return HTML conent" + ); + assert_eq!( + element.query_selector_all("strong").unwrap().length(), + 1, + "Should return one element" + ); + assert!( + element.query_selector("strong").unwrap().is_some(), + "Should return an element" + ); element.set_inner_html(""); assert_eq!(element.inner_html(), "", "Should return no content"); -/* Tests needed for: + /* Tests needed for: outer_html set_outer_html insert_adjacent_html */ - assert!(element.query_selector(".none-existant").unwrap().is_none(), "Should return no results"); - assert_eq!(element.query_selector_all(".none-existant").unwrap().length(), 0, "Should return no results"); -/* Tests needed for: + assert!( + element.query_selector(".none-existant").unwrap().is_none(), + "Should return no results" + ); + assert_eq!( + element + .query_selector_all(".none-existant") + .unwrap() + .length(), + 0, + "Should return no results" + ); + /* Tests needed for: slot set_slot request_fullscreen diff --git a/crates/web-sys/tests/wasm/event.rs b/crates/web-sys/tests/wasm/event.rs index 4192e5bb1..66d55a3d5 100644 --- a/crates/web-sys/tests/wasm/event.rs +++ b/crates/web-sys/tests/wasm/event.rs @@ -7,28 +7,26 @@ use wasm_bindgen_test::*; use web_sys::Event; #[wasm_bindgen(module = "./tests/wasm/event.js")] -extern { +extern "C" { fn new_event() -> Promise; } #[wasm_bindgen_test(async)] fn event() -> impl Future { - JsFuture::from(new_event()) - .map(Event::from) - .map(|event| { - // All DOM interfaces should inherit from `Object`. - assert!(event.is_instance_of::()); - let _: &Object = event.as_ref(); + JsFuture::from(new_event()).map(Event::from).map(|event| { + // All DOM interfaces should inherit from `Object`. + assert!(event.is_instance_of::()); + let _: &Object = event.as_ref(); - // These should match `new Event`. - assert!(event.bubbles()); - assert!(event.cancelable()); - assert!(event.composed()); + // These should match `new Event`. + assert!(event.bubbles()); + assert!(event.cancelable()); + assert!(event.composed()); - // The default behavior not initially prevented, but after - // we call `prevent_default` it better be. - assert!(!event.default_prevented()); - event.prevent_default(); - assert!(event.default_prevented()); - }) + // The default behavior not initially prevented, but after + // we call `prevent_default` it better be. + assert!(!event.default_prevented()); + event.prevent_default(); + assert!(event.default_prevented()); + }) } diff --git a/crates/web-sys/tests/wasm/head_element.rs b/crates/web-sys/tests/wasm/head_element.rs index e3e5b9e49..a459a6687 100644 --- a/crates/web-sys/tests/wasm/head_element.rs +++ b/crates/web-sys/tests/wasm/head_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlHeadElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_head() -> HtmlHeadElement; } diff --git a/crates/web-sys/tests/wasm/headers.rs b/crates/web-sys/tests/wasm/headers.rs index 6f08554c9..ca801e0a3 100644 --- a/crates/web-sys/tests/wasm/headers.rs +++ b/crates/web-sys/tests/wasm/headers.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::Headers; #[wasm_bindgen(module = "./tests/wasm/headers.js")] -extern { +extern "C" { fn new_headers() -> Headers; } diff --git a/crates/web-sys/tests/wasm/heading_element.rs b/crates/web-sys/tests/wasm/heading_element.rs index 22951cde7..795ba7175 100644 --- a/crates/web-sys/tests/wasm/heading_element.rs +++ b/crates/web-sys/tests/wasm/heading_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlHeadingElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_heading() -> HtmlHeadingElement; } diff --git a/crates/web-sys/tests/wasm/history.rs b/crates/web-sys/tests/wasm/history.rs index 234c3125a..f3ecdc42e 100644 --- a/crates/web-sys/tests/wasm/history.rs +++ b/crates/web-sys/tests/wasm/history.rs @@ -1,18 +1,28 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::{History, ScrollRestoration}; #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = history, js_namespace = window)] static HISTORY: History; } #[wasm_bindgen_test] fn history() { - HISTORY.set_scroll_restoration(ScrollRestoration::Manual).expect("failure to set scroll restoration"); - assert_eq!(HISTORY.scroll_restoration().unwrap(), ScrollRestoration::Manual); + HISTORY + .set_scroll_restoration(ScrollRestoration::Manual) + .expect("failure to set scroll restoration"); + assert_eq!( + HISTORY.scroll_restoration().unwrap(), + ScrollRestoration::Manual + ); - HISTORY.set_scroll_restoration(ScrollRestoration::Auto).expect("failure to set scroll restoration"); - assert_eq!(HISTORY.scroll_restoration().unwrap(), ScrollRestoration::Auto); + HISTORY + .set_scroll_restoration(ScrollRestoration::Auto) + .expect("failure to set scroll restoration"); + assert_eq!( + HISTORY.scroll_restoration().unwrap(), + ScrollRestoration::Auto + ); } diff --git a/crates/web-sys/tests/wasm/hr_element.rs b/crates/web-sys/tests/wasm/hr_element.rs index e994bca28..ba92efdfd 100644 --- a/crates/web-sys/tests/wasm/hr_element.rs +++ b/crates/web-sys/tests/wasm/hr_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlHrElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_hr() -> HtmlHrElement; } @@ -21,4 +21,4 @@ fn test_hr_element() { hr.set_no_shade(true); assert_eq!(hr.no_shade(), true); -} \ No newline at end of file +} diff --git a/crates/web-sys/tests/wasm/html_element.rs b/crates/web-sys/tests/wasm/html_element.rs index 9d6d6d61f..004907501 100644 --- a/crates/web-sys/tests/wasm/html_element.rs +++ b/crates/web-sys/tests/wasm/html_element.rs @@ -1,10 +1,10 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; use web_sys::HtmlElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_html() -> HtmlElement; } @@ -56,12 +56,20 @@ fn test_html_element() { element.set_draggable(true); assert!(element.draggable(), "Should be draggable"); - assert_eq!(element.content_editable(), "inherit", "Shouldn't have a content_editable"); + assert_eq!( + element.content_editable(), + "inherit", + "Shouldn't have a content_editable" + ); element.set_content_editable("true"); - assert_eq!(element.content_editable(), "true", "Should be content_editable"); + assert_eq!( + element.content_editable(), + "true", + "Should be content_editable" + ); assert!(element.is_content_editable(), "Should be content_editable"); -/*TODO doesn't work in Chrome + /*TODO doesn't work in Chrome // TODO verify case where menu is passed match element.context_menu() { None => assert!(true, "Shouldn't have a custom menu set"), @@ -77,12 +85,24 @@ fn test_html_element() { // TODO verify case where we have an offset_parent match element.offset_parent() { None => assert!(true, "Shouldn't have an offset_parent set"), - _ => assert!(false, "Shouldn't have a offset_parent set") + _ => assert!(false, "Shouldn't have a offset_parent set"), }; // TODO verify when we have offsets assert_eq!(element.offset_top(), 0, "Shouldn't have an offset_top yet"); - assert_eq!(element.offset_left(), 0, "Shouldn't have an offset_left yet"); - assert_eq!(element.offset_width(), 0, "Shouldn't have an offset_width yet"); - assert_eq!(element.offset_height(), 0, "Shouldn't have an offset_height yet"); + assert_eq!( + element.offset_left(), + 0, + "Shouldn't have an offset_left yet" + ); + assert_eq!( + element.offset_width(), + 0, + "Shouldn't have an offset_width yet" + ); + assert_eq!( + element.offset_height(), + 0, + "Shouldn't have an offset_height yet" + ); } diff --git a/crates/web-sys/tests/wasm/html_html_element.rs b/crates/web-sys/tests/wasm/html_html_element.rs index fc5631347..75de8f6b8 100644 --- a/crates/web-sys/tests/wasm/html_html_element.rs +++ b/crates/web-sys/tests/wasm/html_html_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlHtmlElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_html() -> HtmlHtmlElement; } diff --git a/crates/web-sys/tests/wasm/input_element.rs b/crates/web-sys/tests/wasm/input_element.rs index 9ce7743d7..21583f99a 100644 --- a/crates/web-sys/tests/wasm/input_element.rs +++ b/crates/web-sys/tests/wasm/input_element.rs @@ -1,14 +1,14 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlInputElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_input() -> HtmlInputElement; } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = location, js_namespace = document)] static LOCATION: Location; @@ -34,18 +34,25 @@ fn test_input_element() { element.set_type("text"); assert_eq!(element.autocomplete(), "", "Shouldn't have an autocomplete"); element.set_autocomplete("on"); - assert_eq!(element.autocomplete(), "on", "Shouldn't have an autocomplete"); + assert_eq!( + element.autocomplete(), + "on", + "Shouldn't have an autocomplete" + ); assert!(!element.autofocus(), "Shouldn't have an autofocus"); element.set_autofocus(true); assert!(element.autofocus(), "Should have an autofocus"); element.set_type("checkbox"); - assert!(!element.default_checked(), "Shouldn't have an default_checked"); + assert!( + !element.default_checked(), + "Shouldn't have an default_checked" + ); element.set_default_checked(true); assert!(element.default_checked(), "Should have an default_checked"); -/*TODO fix + /*TODO fix assert!(!element.checked(), "Shouldn't be checked"); element.set_checked(true); assert!(element.checked(), "Should be checked"); @@ -60,13 +67,25 @@ fn test_input_element() { _ => assert!(false, "Shouldn't have a form"), }; - assert_eq!(element.form_action(), location, "Should have the pages location"); + assert_eq!( + element.form_action(), + location, + "Should have the pages location" + ); element.set_form_action("http://boop.com/"); - assert_eq!(element.form_action(), "http://boop.com/", "Should have a form_action"); + assert_eq!( + element.form_action(), + "http://boop.com/", + "Should have a form_action" + ); assert_eq!(element.form_enctype(), "", "Should have no enctype"); element.set_form_enctype("text/plain"); - assert_eq!(element.form_enctype(), "text/plain", "Should have a plain text enctype"); + assert_eq!( + element.form_enctype(), + "text/plain", + "Should have a plain text enctype" + ); assert_eq!(element.form_method(), "", "Should have no method"); element.set_form_method("POST"); @@ -78,19 +97,23 @@ fn test_input_element() { assert_eq!(element.form_target(), "", "Should have no target"); element.set_form_target("_blank"); - assert_eq!(element.form_target(), "_blank", "Should have a _blank target"); + assert_eq!( + element.form_target(), + "_blank", + "Should have a _blank target" + ); assert_eq!(element.height(), 0, "Should have no height"); element.set_height(12); assert_eq!(element.height(), 0, "Should have no height"); // Doesn't change, TODO check with get_attribute("height")=="12" -/*TODO fails in chrome + /*TODO fails in chrome element.set_type("checkbox"); assert!(element.indeterminate(), "Should be indeterminate"); element.set_checked(true); assert!(!element.indeterminate(), "Shouldn't be indeterminate"); */ -/*TODO add tests + /*TODO add tests pub fn indeterminate(&self) -> bool pub fn set_indeterminate(&self, indeterminate: bool) pub fn input_mode(&self) -> String @@ -110,13 +133,17 @@ pub fn set_multiple(&self, multiple: bool) assert_eq!(element.name(), "", "Should not have a name"); element.set_name("namey"); assert_eq!(element.name(), "namey", "Should have a name"); -/*TODO add tests + /*TODO add tests pub fn pattern(&self) -> String pub fn set_pattern(&self, pattern: &str) */ assert_eq!(element.placeholder(), "", "Should not have a placeholder"); element.set_placeholder("some text"); - assert_eq!(element.placeholder(), "some text", "Should have a placeholder"); + assert_eq!( + element.placeholder(), + "some text", + "Should have a placeholder" + ); assert!(!element.read_only(), "Should have not be readonly"); element.set_read_only(true); @@ -125,17 +152,17 @@ pub fn set_pattern(&self, pattern: &str) assert!(!element.required(), "Should have not be required"); element.set_required(true); assert!(element.required(), "Should be required"); -/*TODO add tests + /*TODO add tests pub fn size(&self) -> u32 pub fn set_size(&self, size: u32) */ -/*TODO fails in chrome + /*TODO fails in chrome element.set_type("image"); assert_eq!(element.src(), "", "Should have no src"); element.set_value("hey.png"); assert_eq!(element.src(), "hey.png", "Should have a src"); */ -/*TODO add tests + /*TODO add tests pub fn src(&self) -> String pub fn set_src(&self, src: &str) pub fn step(&self) -> String @@ -145,7 +172,7 @@ pub fn set_type(&self, type_: &str) pub fn default_value(&self) -> String pub fn set_default_value(&self, default_value: &str) */ -/*TODO fails in chrome + /*TODO fails in chrome assert_eq!(element.value(), "", "Should have no value"); element.set_value("hey!"); assert_eq!(element.value(), "hey!", "Should have a value"); @@ -161,13 +188,17 @@ pub fn set_default_value(&self, default_value: &str) assert_eq!(element.width(), 0, "Should have no width"); // Doesn't change, TODO check with get_attribute("width")=="12" assert_eq!(element.will_validate(), false, "Shouldn't validate"); - assert_eq!(element.validation_message().unwrap(), "", "Shouldn't have a value"); + assert_eq!( + element.validation_message().unwrap(), + "", + "Shouldn't have a value" + ); assert_eq!(element.check_validity(), true, "Should be valid"); assert_eq!(element.report_validity(), true, "Should be valid"); element.set_custom_validity("Boop"); // Method exists but doesn't impact validity ?!??! TODO look into assert_eq!(element.check_validity(), true, "Should be valid"); assert_eq!(element.report_validity(), true, "Should be valid"); -/*TODO add tests + /*TODO add tests pub fn labels(&self) -> Option pub fn select(&self) pub fn selection_direction(&self) -> Result, JsValue> @@ -187,7 +218,7 @@ pub fn set_selection_range( assert_eq!(element.align(), "", "Should have no align"); element.set_align("left"); assert_eq!(element.align(), "left", "Should have an align"); -/*TODO add tests + /*TODO add tests pub fn use_map(&self) -> String pub fn set_use_map(&self, use_map: &str) pub fn text_length(&self) -> i32 diff --git a/crates/web-sys/tests/wasm/main.rs b/crates/web-sys/tests/wasm/main.rs index efeebaf8f..ce221e16a 100644 --- a/crates/web-sys/tests/wasm/main.rs +++ b/crates/web-sys/tests/wasm/main.rs @@ -20,8 +20,8 @@ pub mod div_element; pub mod element; pub mod event; pub mod head_element; -pub mod heading_element; pub mod headers; +pub mod heading_element; pub mod history; pub mod hr_element; pub mod html_element; @@ -30,6 +30,8 @@ pub mod input_element; //TODO: Both menu-related tests completely break in Chrome, but run fine in Firefox. //pub mod menu_element; //pub mod menu_item_element; +pub mod dom_point; +pub mod location; pub mod meta_element; pub mod meter_element; pub mod mod_elements; @@ -40,18 +42,16 @@ pub mod options_collection; pub mod output_element; pub mod paragraph_element; pub mod param_element; +pub mod performance; pub mod pre_element; pub mod progress_element; pub mod quote_element; pub mod response; -pub mod select_element; pub mod script_element; +pub mod select_element; pub mod slot_element; pub mod span_element; pub mod style_element; pub mod table_element; pub mod title_element; pub mod xpath_result; -pub mod dom_point; -pub mod performance; -pub mod location; diff --git a/crates/web-sys/tests/wasm/meta_element.rs b/crates/web-sys/tests/wasm/meta_element.rs index 9b2d355eb..f94444cc5 100644 --- a/crates/web-sys/tests/wasm/meta_element.rs +++ b/crates/web-sys/tests/wasm/meta_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlMetaElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_meta() -> HtmlMetaElement; } @@ -12,14 +12,30 @@ fn test_meter_element() { let meta = new_meta(); meta.set_name("keywords"); - assert_eq!(meta.name(), "keywords", "Meta should have the name value we gave it."); + assert_eq!( + meta.name(), + "keywords", + "Meta should have the name value we gave it." + ); meta.set_http_equiv("content-type"); - assert_eq!(meta.http_equiv(), "content-type", "Meta should have the http_equiv value we gave it."); + assert_eq!( + meta.http_equiv(), + "content-type", + "Meta should have the http_equiv value we gave it." + ); meta.set_content("HTML, CSS, XML, JavaScript"); - assert_eq!(meta.content(), "HTML, CSS, XML, JavaScript", "Meta should have the content value we gave it."); + assert_eq!( + meta.content(), + "HTML, CSS, XML, JavaScript", + "Meta should have the content value we gave it." + ); meta.set_scheme("text"); - assert_eq!(meta.scheme(), "text", "Meta should have the scheme value we gave it."); -} \ No newline at end of file + assert_eq!( + meta.scheme(), + "text", + "Meta should have the scheme value we gave it." + ); +} diff --git a/crates/web-sys/tests/wasm/meter_element.rs b/crates/web-sys/tests/wasm/meter_element.rs index 8a8ad405a..cd26432d1 100644 --- a/crates/web-sys/tests/wasm/meter_element.rs +++ b/crates/web-sys/tests/wasm/meter_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlMeterElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_meter() -> HtmlMeterElement; } @@ -12,22 +12,45 @@ fn test_meter_element() { let meter = new_meter(); meter.set_min(-5.); - assert_eq!(meter.min(), -5., "Meter should have the min value we gave it."); + assert_eq!( + meter.min(), + -5., + "Meter should have the min value we gave it." + ); meter.set_max(5.); - assert_eq!(meter.max(), 5., "Meter should have the max value we gave it."); + assert_eq!( + meter.max(), + 5., + "Meter should have the max value we gave it." + ); meter.set_value(2.); assert_eq!(meter.value(), 2., "Meter should have the value we gave it."); meter.set_low(-1.); - assert_eq!(meter.low(), -1., "Meter should have the low value we gave it."); + assert_eq!( + meter.low(), + -1., + "Meter should have the low value we gave it." + ); meter.set_high(1.); - assert_eq!(meter.high(), 1., "Meter should have the high value we gave it."); + assert_eq!( + meter.high(), + 1., + "Meter should have the high value we gave it." + ); meter.set_optimum(3.); - assert_eq!(meter.optimum(), 3., "Meter should have the optimum value we gave it."); + assert_eq!( + meter.optimum(), + 3., + "Meter should have the optimum value we gave it." + ); - assert!(meter.labels().length() == 0, "Our meter shouldn't have any labels associated with it."); -} \ No newline at end of file + assert!( + meter.labels().length() == 0, + "Our meter shouldn't have any labels associated with it." + ); +} diff --git a/crates/web-sys/tests/wasm/mod_elements.rs b/crates/web-sys/tests/wasm/mod_elements.rs index f7dacdff4..5edae5703 100644 --- a/crates/web-sys/tests/wasm/mod_elements.rs +++ b/crates/web-sys/tests/wasm/mod_elements.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlModElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_del() -> HtmlModElement; fn new_ins() -> HtmlModElement; } @@ -13,16 +13,32 @@ fn test_mod_elements() { let del = new_del(); del.set_cite("https://www.rust-lang.org/en-US/"); - assert_eq!(del.cite(), "https://www.rust-lang.org/en-US/", "Option should have the cite URI we gave it."); + assert_eq!( + del.cite(), + "https://www.rust-lang.org/en-US/", + "Option should have the cite URI we gave it." + ); del.set_date_time("Thu Aug 02 2018 18:02:56 GMT-0500 (Central Daylight Time)"); - assert_eq!(del.date_time(), "Thu Aug 02 2018 18:02:56 GMT-0500 (Central Daylight Time)", "Option should have the date_time we gave it."); + assert_eq!( + del.date_time(), + "Thu Aug 02 2018 18:02:56 GMT-0500 (Central Daylight Time)", + "Option should have the date_time we gave it." + ); let ins = new_ins(); ins.set_cite("https://www.rust-lang.org/en-US/"); - assert_eq!(ins.cite(), "https://www.rust-lang.org/en-US/", "Option should have the cite URI we gave it."); + assert_eq!( + ins.cite(), + "https://www.rust-lang.org/en-US/", + "Option should have the cite URI we gave it." + ); ins.set_date_time("Thu Aug 02 2018 18:02:56 GMT-0500 (Central Daylight Time)"); - assert_eq!(ins.date_time(), "Thu Aug 02 2018 18:02:56 GMT-0500 (Central Daylight Time)", "Option should have the date_time we gave it."); -} \ No newline at end of file + assert_eq!( + ins.date_time(), + "Thu Aug 02 2018 18:02:56 GMT-0500 (Central Daylight Time)", + "Option should have the date_time we gave it." + ); +} diff --git a/crates/web-sys/tests/wasm/olist_element.rs b/crates/web-sys/tests/wasm/olist_element.rs index 411b73cfc..ffc1a406b 100644 --- a/crates/web-sys/tests/wasm/olist_element.rs +++ b/crates/web-sys/tests/wasm/olist_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlOListElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_olist() -> HtmlOListElement; } @@ -12,23 +12,51 @@ fn test_olist_element() { let olist = new_olist(); olist.set_reversed(true); - assert_eq!(olist.reversed(), true, "Olist should be reversed after we set it to be reversed."); + assert_eq!( + olist.reversed(), + true, + "Olist should be reversed after we set it to be reversed." + ); olist.set_reversed(false); - assert_eq!(olist.reversed(), false, "Olist should not be reversed after we set it to be not reversed."); + assert_eq!( + olist.reversed(), + false, + "Olist should not be reversed after we set it to be not reversed." + ); olist.set_start(23); - assert_eq!(olist.start(), 23, "Olist should have the start value we gave it."); + assert_eq!( + olist.start(), + 23, + "Olist should have the start value we gave it." + ); olist.set_type("A"); - assert_eq!(olist.type_(), "A", "Olist should be type 'A' after we set it to be type 'A'."); + assert_eq!( + olist.type_(), + "A", + "Olist should be type 'A' after we set it to be type 'A'." + ); olist.set_type("I"); - assert_eq!(olist.type_(), "I", "Olist should be type 'I' after we set it to be type 'I'."); + assert_eq!( + olist.type_(), + "I", + "Olist should be type 'I' after we set it to be type 'I'." + ); olist.set_compact(true); - assert_eq!(olist.compact(), true, "Olist should be compact after we set it to be compact."); + assert_eq!( + olist.compact(), + true, + "Olist should be compact after we set it to be compact." + ); olist.set_compact(false); - assert_eq!(olist.compact(), false, "Olist should not be compact after we set it to be not compact."); -} \ No newline at end of file + assert_eq!( + olist.compact(), + false, + "Olist should not be compact after we set it to be not compact." + ); +} diff --git a/crates/web-sys/tests/wasm/optgroup_element.rs b/crates/web-sys/tests/wasm/optgroup_element.rs index 1a7dccfca..e786e39b6 100644 --- a/crates/web-sys/tests/wasm/optgroup_element.rs +++ b/crates/web-sys/tests/wasm/optgroup_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlOptGroupElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_optgroup() -> HtmlOptGroupElement; } @@ -12,11 +12,23 @@ fn test_optgroup_element() { let optgroup = new_optgroup(); optgroup.set_disabled(true); - assert_eq!(optgroup.disabled(), true, "Optgroup should be disabled after we set it to be disabled."); + assert_eq!( + optgroup.disabled(), + true, + "Optgroup should be disabled after we set it to be disabled." + ); optgroup.set_disabled(false); - assert_eq!(optgroup.disabled(), false, "Optgroup should not be disabled after we set it to be not-disabled."); + assert_eq!( + optgroup.disabled(), + false, + "Optgroup should not be disabled after we set it to be not-disabled." + ); optgroup.set_label("Group of options below"); - assert_eq!(optgroup.label(), "Group of options below", "Optgroup should have the label we gave it."); -} \ No newline at end of file + assert_eq!( + optgroup.label(), + "Group of options below", + "Optgroup should have the label we gave it." + ); +} diff --git a/crates/web-sys/tests/wasm/option_element.rs b/crates/web-sys/tests/wasm/option_element.rs index 1cb2d2626..826375b76 100644 --- a/crates/web-sys/tests/wasm/option_element.rs +++ b/crates/web-sys/tests/wasm/option_element.rs @@ -4,40 +4,83 @@ use web_sys::HtmlOptionElement; #[wasm_bindgen_test] fn test_option_element() { let option = HtmlOptionElement::new_with_text_and_value_and_default_selected_and_selected( - "option_text", - "option_value", - false, - true + "option_text", + "option_value", + false, + true, ).unwrap(); option.set_disabled(true); - assert_eq!(option.disabled(), true, "Option should be disabled after we set it to be disabled."); + assert_eq!( + option.disabled(), + true, + "Option should be disabled after we set it to be disabled." + ); option.set_disabled(false); - assert_eq!(option.disabled(), false, "Option should not be disabled after we set it to be not-disabled."); + assert_eq!( + option.disabled(), + false, + "Option should not be disabled after we set it to be not-disabled." + ); - assert!(option.form().is_none(), "Our option should not be associated with a form."); + assert!( + option.form().is_none(), + "Our option should not be associated with a form." + ); option.set_label("Well this truly is a neat option"); - assert_eq!(option.label(), "Well this truly is a neat option", "Option should have the label we gave it."); + assert_eq!( + option.label(), + "Well this truly is a neat option", + "Option should have the label we gave it." + ); option.set_default_selected(true); - assert_eq!(option.default_selected(), true, "Option should be default_selected after we set it to be default_selected."); + assert_eq!( + option.default_selected(), + true, + "Option should be default_selected after we set it to be default_selected." + ); option.set_default_selected(false); - assert_eq!(option.default_selected(), false, "Option should not be default_selected after we set it to be not default_selected."); + assert_eq!( + option.default_selected(), + false, + "Option should not be default_selected after we set it to be not default_selected." + ); option.set_selected(true); - assert_eq!(option.selected(), true, "Option should be selected after we set it to be selected."); + assert_eq!( + option.selected(), + true, + "Option should be selected after we set it to be selected." + ); option.set_selected(false); - assert_eq!(option.selected(), false, "Option should not be selected after we set it to be not selected."); + assert_eq!( + option.selected(), + false, + "Option should not be selected after we set it to be not selected." + ); option.set_value("tomato"); - assert_eq!(option.value(), "tomato", "Option should have the value we gave it."); + assert_eq!( + option.value(), + "tomato", + "Option should have the value we gave it." + ); option.set_text("potato"); - assert_eq!(option.text(), "potato", "Option should have the text we gave it."); + assert_eq!( + option.text(), + "potato", + "Option should have the text we gave it." + ); - assert_eq!(option.index(), 0, "This should be the first option, since there are no other known options."); + assert_eq!( + option.index(), + 0, + "This should be the first option, since there are no other known options." + ); } diff --git a/crates/web-sys/tests/wasm/options_collection.rs b/crates/web-sys/tests/wasm/options_collection.rs index b62432991..254cedd79 100644 --- a/crates/web-sys/tests/wasm/options_collection.rs +++ b/crates/web-sys/tests/wasm/options_collection.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlOptionsCollection; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_food_options_collection() -> HtmlOptionsCollection; } @@ -11,13 +11,33 @@ extern { fn test_options_collection() { let opt_collection = new_food_options_collection(); - assert!(opt_collection.length() == 4, "Our option collection should have four options."); - assert!(opt_collection.remove(0).is_ok(), "We should be able to successfully remove an element from an option collection."); - assert!(opt_collection.length() == 3, "Our option collection should have three options after removing one."); + assert!( + opt_collection.length() == 4, + "Our option collection should have four options." + ); + assert!( + opt_collection.remove(0).is_ok(), + "We should be able to successfully remove an element from an option collection." + ); + assert!( + opt_collection.length() == 3, + "Our option collection should have three options after removing one." + ); - assert!(opt_collection.set_selected_index(1).is_ok(), "Should be able to set the selected index of an option collection if it is valid."); - assert_eq!(opt_collection.selected_index().unwrap(), 1, "The second option should be selected in our option collection."); + assert!( + opt_collection.set_selected_index(1).is_ok(), + "Should be able to set the selected index of an option collection if it is valid." + ); + assert_eq!( + opt_collection.selected_index().unwrap(), + 1, + "The second option should be selected in our option collection." + ); opt_collection.set_length(1234); - assert_eq!(opt_collection.length(), 1234, "Our option collections length should update after being set to 1234."); -} \ No newline at end of file + assert_eq!( + opt_collection.length(), + 1234, + "Our option collections length should update after being set to 1234." + ); +} diff --git a/crates/web-sys/tests/wasm/output_element.rs b/crates/web-sys/tests/wasm/output_element.rs index 53668c5e8..9c3582152 100644 --- a/crates/web-sys/tests/wasm/output_element.rs +++ b/crates/web-sys/tests/wasm/output_element.rs @@ -1,25 +1,43 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlOutputElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_output() -> HtmlOutputElement; } #[wasm_bindgen_test] fn test_output_element() { let output = new_output(); - assert!(output.html_for().length() == 0, "Our basic should have no html associated with it."); - assert!(output.form().is_none(), "Our basic should have no form associated with it."); + assert!( + output.html_for().length() == 0, + "Our basic should have no html associated with it." + ); + assert!( + output.form().is_none(), + "Our basic should have no form associated with it." + ); output.set_name("Calculation result"); - assert_eq!(output.name(), "Calculation result", "Output name should be 'Calculation result'."); + assert_eq!( + output.name(), + "Calculation result", + "Output name should be 'Calculation result'." + ); - assert_eq!(output.type_(), "output", "Our basic should have an type of 'output'."); + assert_eq!( + output.type_(), + "output", + "Our basic should have an type of 'output'." + ); output.set_default_value("27"); - assert_eq!(output.default_value(), "27", "Default output value should be '27'."); + assert_eq!( + output.default_value(), + "27", + "Default output value should be '27'." + ); output.set_value("49"); assert_eq!(output.value(), "49", "Output value should be '49'."); @@ -27,15 +45,27 @@ fn test_output_element() { // TODO: Fails in Chrome, but not in Firefox. //assert!(output.will_validate(), "Output should validate by default (maybe browser dependent?)"); - assert!(output.validity().valid(), "Our s validity should be true."); + assert!( + output.validity().valid(), + "Our s validity should be true." + ); - assert!(output.validation_message().is_ok(), "We should be able to retrieve some validation message from our ."); + assert!( + output.validation_message().is_ok(), + "We should be able to retrieve some validation message from our ." + ); assert!(output.check_validity(), "Our should be valid."); - assert!(output.report_validity(), "Our should report valid."); + assert!( + output.report_validity(), + "Our should report valid." + ); output.set_custom_validity("Some scary error message."); - assert!(output.labels().length() == 0, "Our basic shouldn't have any labels associated with it."); -} \ No newline at end of file + assert!( + output.labels().length() == 0, + "Our basic shouldn't have any labels associated with it." + ); +} diff --git a/crates/web-sys/tests/wasm/paragraph_element.rs b/crates/web-sys/tests/wasm/paragraph_element.rs index b4a8b3e32..681eff8f6 100644 --- a/crates/web-sys/tests/wasm/paragraph_element.rs +++ b/crates/web-sys/tests/wasm/paragraph_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlParagraphElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_paragraph() -> HtmlParagraphElement; } @@ -11,5 +11,9 @@ extern { fn test_paragraph_element() { let paragraph = new_paragraph(); paragraph.set_align("right"); - assert_eq!(paragraph.align(), "right", "Paragraph should be aligned 'right'."); -} \ No newline at end of file + assert_eq!( + paragraph.align(), + "right", + "Paragraph should be aligned 'right'." + ); +} diff --git a/crates/web-sys/tests/wasm/param_element.rs b/crates/web-sys/tests/wasm/param_element.rs index a87d3bdb7..8cc90b677 100644 --- a/crates/web-sys/tests/wasm/param_element.rs +++ b/crates/web-sys/tests/wasm/param_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlParamElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_param() -> HtmlParamElement; } @@ -14,11 +14,23 @@ fn test_param_element() { assert_eq!(param.name(), "color", "Name of param should be 'color'."); param.set_value("purple"); - assert_eq!(param.value(), "purple", "Value of param should be 'purple'."); + assert_eq!( + param.value(), + "purple", + "Value of param should be 'purple'." + ); param.set_value_type("ref"); - assert_eq!(param.value_type(), "ref", "Value type of param should be 'ref'."); + assert_eq!( + param.value_type(), + "ref", + "Value type of param should be 'ref'." + ); param.set_type("text/plain"); - assert_eq!(param.type_(), "text/plain", "Value of param should be 'text/plain'."); -} \ No newline at end of file + assert_eq!( + param.type_(), + "text/plain", + "Value of param should be 'text/plain'." + ); +} diff --git a/crates/web-sys/tests/wasm/performance.rs b/crates/web-sys/tests/wasm/performance.rs index 1ddef6838..84931a627 100644 --- a/crates/web-sys/tests/wasm/performance.rs +++ b/crates/web-sys/tests/wasm/performance.rs @@ -3,7 +3,7 @@ use wasm_bindgen_test::*; use web_sys::Performance; #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_name = performance)] static PERFORMANCE: Performance; } diff --git a/crates/web-sys/tests/wasm/pre_element.rs b/crates/web-sys/tests/wasm/pre_element.rs index 1d0c7618c..b6f2b8ca0 100644 --- a/crates/web-sys/tests/wasm/pre_element.rs +++ b/crates/web-sys/tests/wasm/pre_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlPreElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_pre() -> HtmlPreElement; } @@ -12,4 +12,4 @@ fn test_pre_element() { let pre = new_pre(); pre.set_width(150); assert_eq!(pre.width(), 150, "Pre width should be 150."); -} \ No newline at end of file +} diff --git a/crates/web-sys/tests/wasm/progress_element.rs b/crates/web-sys/tests/wasm/progress_element.rs index f94d094d3..9363ab243 100644 --- a/crates/web-sys/tests/wasm/progress_element.rs +++ b/crates/web-sys/tests/wasm/progress_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlProgressElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_progress() -> HtmlProgressElement; } @@ -11,11 +11,22 @@ extern { fn test_progress_element() { let progress = new_progress(); progress.set_max(150.5); - assert_eq!(progress.max(), 150.5, "Maximum progress value should be 150.5."); + assert_eq!( + progress.max(), + 150.5, + "Maximum progress value should be 150.5." + ); progress.set_value(22.); assert_eq!(progress.value(), 22., "Progress value should be 22 units."); - assert_eq!(progress.position(), (22. / 150.5), "Progress position should be 22 divided by the max possible value."); + assert_eq!( + progress.position(), + (22. / 150.5), + "Progress position should be 22 divided by the max possible value." + ); - assert!(progress.labels().length() == 0, "Our simple progress bar shouldn't be associated with any labels."); -} \ No newline at end of file + assert!( + progress.labels().length() == 0, + "Our simple progress bar shouldn't be associated with any labels." + ); +} diff --git a/crates/web-sys/tests/wasm/quote_element.rs b/crates/web-sys/tests/wasm/quote_element.rs index a016db4a4..935ac0e62 100644 --- a/crates/web-sys/tests/wasm/quote_element.rs +++ b/crates/web-sys/tests/wasm/quote_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlQuoteElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_quote() -> HtmlQuoteElement; } @@ -11,5 +11,8 @@ extern { fn test_quote_element() { let quote = new_quote(); quote.set_cite("https://en.wikipedia.org/wiki/Rust_(programming_language)"); - assert_eq!(quote.cite(), "https://en.wikipedia.org/wiki/Rust_(programming_language)"); -} \ No newline at end of file + assert_eq!( + quote.cite(), + "https://en.wikipedia.org/wiki/Rust_(programming_language)" + ); +} diff --git a/crates/web-sys/tests/wasm/response.rs b/crates/web-sys/tests/wasm/response.rs index 9413db27b..40c893f56 100644 --- a/crates/web-sys/tests/wasm/response.rs +++ b/crates/web-sys/tests/wasm/response.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::Response; #[wasm_bindgen(module = "./tests/wasm/response.js")] -extern { +extern "C" { fn new_response() -> Response; } diff --git a/crates/web-sys/tests/wasm/script_element.rs b/crates/web-sys/tests/wasm/script_element.rs index dd9abd2b0..35eb3b185 100644 --- a/crates/web-sys/tests/wasm/script_element.rs +++ b/crates/web-sys/tests/wasm/script_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlScriptElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_script() -> HtmlScriptElement; } @@ -12,11 +12,19 @@ fn test_script_element() { let element = new_script(); assert_eq!(element.src(), "", "Shouldn't have a src"); element.set_src("https://example.com/script.js"); - assert_eq!(element.src(), "https://example.com/script.js", "Should have a src"); + assert_eq!( + element.src(), + "https://example.com/script.js", + "Should have a src" + ); assert_eq!(element.type_(), "", "Shouldn't have a type"); element.set_type("application/javascript"); - assert_eq!(element.type_(), "application/javascript", "Should have a type"); + assert_eq!( + element.type_(), + "application/javascript", + "Should have a type" + ); assert!(!element.no_module(), "Shouldn't be a nomodule"); element.set_no_module(true); @@ -34,11 +42,21 @@ fn test_script_element() { element.set_defer(true); assert!(element.defer(), "Should be a defer"); - assert!(element.cross_origin().is_none(), "Shouldn't have a crossorigin"); + assert!( + element.cross_origin().is_none(), + "Shouldn't have a crossorigin" + ); element.set_cross_origin(Some("anonymous")); - assert_eq!(element.cross_origin().unwrap(), "anonymous", "Should have a crossorigin"); + assert_eq!( + element.cross_origin().unwrap(), + "anonymous", + "Should have a crossorigin" + ); element.set_cross_origin(None); - assert!(element.cross_origin().is_none(), "Shouldn't have a crossorigin"); + assert!( + element.cross_origin().is_none(), + "Shouldn't have a crossorigin" + ); assert_eq!(element.text().unwrap(), "", "Shouldn't have text"); assert_eq!(element.set_text("text").unwrap(), ()); @@ -54,5 +72,9 @@ fn test_script_element() { assert_eq!(element.integrity(), "", "Shouldn't have an integrity"); element.set_integrity("integrity-val"); - assert_eq!(element.integrity(), "integrity-val", "Should have an integrity"); + assert_eq!( + element.integrity(), + "integrity-val", + "Should have an integrity" + ); } diff --git a/crates/web-sys/tests/wasm/select_element.rs b/crates/web-sys/tests/wasm/select_element.rs index a7abe143a..aec91ac72 100644 --- a/crates/web-sys/tests/wasm/select_element.rs +++ b/crates/web-sys/tests/wasm/select_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlSelectElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_select_with_food_opts() -> HtmlSelectElement; } @@ -13,81 +13,169 @@ fn test_select_element() { // the string is the .value and .text of each option. let select = new_select_with_food_opts(); select.set_autofocus(true); - assert_eq!(select.autofocus(), true, "Select element should have a true autofocus property."); + assert_eq!( + select.autofocus(), + true, + "Select element should have a true autofocus property." + ); select.set_autofocus(false); - assert_eq!(select.autofocus(), false, "Select element should have a false autofocus property."); + assert_eq!( + select.autofocus(), + false, + "Select element should have a false autofocus property." + ); -// TODO: This test currently fails on Firefox, but not Chrome. In Firefox, even though we select.set_autocomplete(), select.autocomplete() yields an empty String. -// select.set_autocomplete("tomato"); -// assert_eq!(select.autocomplete(), "tomato", "Select element should have a 'tomato' autocomplete property."); + // TODO: This test currently fails on Firefox, but not Chrome. In Firefox, even though we select.set_autocomplete(), select.autocomplete() yields an empty String. + // select.set_autocomplete("tomato"); + // assert_eq!(select.autocomplete(), "tomato", "Select element should have a 'tomato' autocomplete property."); select.set_disabled(true); - assert_eq!(select.disabled(), true, "Select element should be disabled."); + assert_eq!( + select.disabled(), + true, + "Select element should be disabled." + ); select.set_disabled(false); - assert_eq!(select.disabled(), false, "Select element should not be disabled."); + assert_eq!( + select.disabled(), + false, + "Select element should not be disabled." + ); - assert!(select.form().is_none(), "Select should not be associated with a form."); + assert!( + select.form().is_none(), + "Select should not be associated with a form." + ); select.set_multiple(false); - assert_eq!(select.multiple(), false, "Select element should have a false multiple property."); + assert_eq!( + select.multiple(), + false, + "Select element should have a false multiple property." + ); select.set_multiple(true); - assert_eq!(select.multiple(), true, "Select element should have a true multiple property."); + assert_eq!( + select.multiple(), + true, + "Select element should have a true multiple property." + ); select.set_name("potato"); - assert_eq!(select.name(), "potato", "Select element should have a name property of 'potato'."); + assert_eq!( + select.name(), + "potato", + "Select element should have a name property of 'potato'." + ); select.set_required(true); - assert_eq!(select.required(), true, "Select element should be required."); + assert_eq!( + select.required(), + true, + "Select element should be required." + ); select.set_required(false); - assert_eq!(select.required(), false, "Select element should not be required."); + assert_eq!( + select.required(), + false, + "Select element should not be required." + ); select.set_size(432); - assert_eq!(select.size(), 432, "Select element should have a size property of 432."); + assert_eq!( + select.size(), + 432, + "Select element should have a size property of 432." + ); // Default type seems to be "select-multiple" for the browsers I tested, but there's no guarantee // on this, so let's just make sure we get back something here. - assert!(select.type_().len() > 0, "Select element should have some type."); + assert!( + select.type_().len() > 0, + "Select element should have some type." + ); - assert!(select.options().length() == 4, "Select element should have four options."); + assert!( + select.options().length() == 4, + "Select element should have four options." + ); select.set_length(12); - assert_eq!(select.length(), 12, "Select element should have a length of 12."); + assert_eq!( + select.length(), + 12, + "Select element should have a length of 12." + ); // Reset the length to four, as that's how many options we actually have. select.set_length(4); - assert!(select.named_item("this should definitely find nothing").is_none(), "Shouldn't be able to find a named item with the given string."); + assert!( + select + .named_item("this should definitely find nothing") + .is_none(), + "Shouldn't be able to find a named item with the given string." + ); - assert!(select.selected_options().length() == 1, "One option should be selected by default, just by way of having items."); + assert!( + select.selected_options().length() == 1, + "One option should be selected by default, just by way of having items." + ); select.set_selected_index(2); - assert_eq!(select.selected_index(), 2, "Select element should have a selected index of 2."); + assert_eq!( + select.selected_index(), + 2, + "Select element should have a selected index of 2." + ); // Quote from docs: The value property sets or returns the value of the selected option in a drop-down list. select.set_value("tomato"); // Select the "tomato" option - assert_eq!(select.value(), "tomato", "Select element should have no selected value."); + assert_eq!( + select.value(), + "tomato", + "Select element should have no selected value." + ); // This might be browser dependent, potentially rendering this test useless? Worked fine in Chrome and Firefox for now. - assert_eq!(select.will_validate(), true, "Select element should not validate by default."); + assert_eq!( + select.will_validate(), + true, + "Select element should not validate by default." + ); - assert!(select.validation_message().is_ok(), "Select element should retrieve a validation message."); + assert!( + select.validation_message().is_ok(), + "Select element should retrieve a validation message." + ); - assert!(select.validity().valid(), "Our basic select should be valid."); + assert!( + select.validity().valid(), + "Our basic select should be valid." + ); - assert!(select.check_validity(), "Our basic select should check out as valid."); + assert!( + select.check_validity(), + "Our basic select should check out as valid." + ); - assert!(select.report_validity(), "Our basic select should report valid."); + assert!( + select.report_validity(), + "Our basic select should report valid." + ); select.set_custom_validity("Some custom validity error."); - assert!(select.labels().length() == 0, "There should be no labels associated with our select element."); + assert!( + select.labels().length() == 0, + "There should be no labels associated with our select element." + ); // TODO: This test won't work until this bug is fixed: https://www.w3.org/Bugs/Public/show_bug.cgi?id=20720. Sometime in the future, either remove this test or uncomment after bug is fixed. // assert!(select.named_item("tomato").is_some(), "Should be able to find the 'tomato' option before removing it."); // select.remove(0); // assert!(select.named_item("tomato").is_none(), "Shouldn't be able to find the 'tomato' option after removing it.") // TODO: As a result, we are missing a test for the remove() method. -} \ No newline at end of file +} diff --git a/crates/web-sys/tests/wasm/slot_element.rs b/crates/web-sys/tests/wasm/slot_element.rs index c97fec290..8ed02ff9c 100644 --- a/crates/web-sys/tests/wasm/slot_element.rs +++ b/crates/web-sys/tests/wasm/slot_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlSlotElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_slot() -> HtmlSlotElement; } @@ -13,4 +13,4 @@ fn test_slot_element() { // TODO: Test fails in Firefox, but not in Chrome. Error in Firefox is 'ReferenceError: HTMLSlotElement is not defined'. https://w3c-test.org/shadow-dom/HTMLSlotElement-interface.html // slot.set_name("root_separator"); // assert_eq!(slot.name(), "root_separator", "Slot name should 'root_separator'."); -} \ No newline at end of file +} diff --git a/crates/web-sys/tests/wasm/span_element.rs b/crates/web-sys/tests/wasm/span_element.rs index fc50e0e85..235fe23df 100644 --- a/crates/web-sys/tests/wasm/span_element.rs +++ b/crates/web-sys/tests/wasm/span_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlSpanElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_span() -> HtmlSpanElement; } diff --git a/crates/web-sys/tests/wasm/style_element.rs b/crates/web-sys/tests/wasm/style_element.rs index 289305f56..14299c8c4 100644 --- a/crates/web-sys/tests/wasm/style_element.rs +++ b/crates/web-sys/tests/wasm/style_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlStyleElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_style() -> HtmlStyleElement; } diff --git a/crates/web-sys/tests/wasm/table_element.rs b/crates/web-sys/tests/wasm/table_element.rs index 0ed436cd2..a1ad4fdf5 100644 --- a/crates/web-sys/tests/wasm/table_element.rs +++ b/crates/web-sys/tests/wasm/table_element.rs @@ -4,176 +4,176 @@ use web_sys::{HtmlTableCaptionElement, HtmlTableElement, HtmlTableSectionElement #[wasm_bindgen(module = "./tests/wasm/element.js")] extern "C" { - fn new_table() -> HtmlTableElement; - fn new_caption() -> HtmlTableCaptionElement; - fn new_thead() -> HtmlTableSectionElement; - fn new_tfoot() -> HtmlTableSectionElement; + fn new_table() -> HtmlTableElement; + fn new_caption() -> HtmlTableCaptionElement; + fn new_thead() -> HtmlTableSectionElement; + fn new_tfoot() -> HtmlTableSectionElement; } #[wasm_bindgen_test] fn test_table_element() { - let table = new_table(); - assert!( - table.caption().is_none(), - "New table element should have no caption element." - ); + let table = new_table(); + assert!( + table.caption().is_none(), + "New table element should have no caption element." + ); - table.create_caption(); - assert!( - table.caption().is_some(), - "Table element should have caption element after create caption." - ); + table.create_caption(); + assert!( + table.caption().is_some(), + "Table element should have caption element after create caption." + ); - table.delete_caption(); - assert!( - table.caption().is_none(), - "Table element should have no caption element after delete caption." - ); + table.delete_caption(); + assert!( + table.caption().is_none(), + "Table element should have no caption element after delete caption." + ); - table.set_caption(Some(&new_caption())); - assert!( - table.caption().is_some(), - "Table element should have caption element after set." - ); + table.set_caption(Some(&new_caption())); + assert!( + table.caption().is_some(), + "Table element should have caption element after set." + ); - assert!( - table.t_head().is_none(), - "New table element should have no thead element." - ); + assert!( + table.t_head().is_none(), + "New table element should have no thead element." + ); - table.create_t_head(); - assert!( - table.t_head().is_some(), - "Table element should have thead element after create thead." - ); + table.create_t_head(); + assert!( + table.t_head().is_some(), + "Table element should have thead element after create thead." + ); - table.delete_t_head(); - assert!( - table.t_head().is_none(), - "Table element should have no thead element after delete thead." - ); + table.delete_t_head(); + assert!( + table.t_head().is_none(), + "Table element should have no thead element after delete thead." + ); - table.set_t_head(Some(&new_thead())); - assert!( - table.t_head().is_some(), - "Table element should have thead element after set." - ); + table.set_t_head(Some(&new_thead())); + assert!( + table.t_head().is_some(), + "Table element should have thead element after set." + ); - assert!( - table.t_foot().is_none(), - "New table element should have no tfoot element." - ); + assert!( + table.t_foot().is_none(), + "New table element should have no tfoot element." + ); - table.create_t_foot(); - assert!( - table.t_foot().is_some(), - "Table element should have tfoot element after create tfoot." - ); + table.create_t_foot(); + assert!( + table.t_foot().is_some(), + "Table element should have tfoot element after create tfoot." + ); - table.delete_t_foot(); - assert!( - table.t_foot().is_none(), - "Table element should have no tfoot element after delete tfoot." - ); + table.delete_t_foot(); + assert!( + table.t_foot().is_none(), + "Table element should have no tfoot element after delete tfoot." + ); - table.set_t_foot(Some(&new_tfoot())); - assert!( - table.t_foot().is_some(), - "Table element should have tfoot element after set." - ); + table.set_t_foot(Some(&new_tfoot())); + assert!( + table.t_foot().is_some(), + "Table element should have tfoot element after set." + ); - assert!( - table.t_bodies().length() == 0, - "New table element should have no tbody element." - ); + assert!( + table.t_bodies().length() == 0, + "New table element should have no tbody element." + ); - table.create_t_body(); - assert!( - table.t_bodies().length() == 1, - "Table element should have tbody element after create tbody." - ); + table.create_t_body(); + assert!( + table.t_bodies().length() == 1, + "Table element should have tbody element after create tbody." + ); - assert!( - table.rows().length() == 0, - "New table element should have no rows." - ); + assert!( + table.rows().length() == 0, + "New table element should have no rows." + ); - table - .insert_row_with_index(0) - .expect("Failed to insert row at index 0"); - assert!( - table.rows().length() == 1, - "Table element should have rows after insert row." - ); + table + .insert_row_with_index(0) + .expect("Failed to insert row at index 0"); + assert!( + table.rows().length() == 1, + "Table element should have rows after insert row." + ); - table - .delete_row(0) - .expect("Failed to delete row at index 0"); - assert!( - table.rows().length() == 0, - "Table element should have no rows after delete row." - ); + table + .delete_row(0) + .expect("Failed to delete row at index 0"); + assert!( + table.rows().length() == 0, + "Table element should have no rows after delete row." + ); - table.set_align("left"); - assert_eq!( - table.align(), - "left", - "Table element should have an align property of 'left'" - ); + table.set_align("left"); + assert_eq!( + table.align(), + "left", + "Table element should have an align property of 'left'" + ); - table.set_border("10"); - assert_eq!( - table.border(), - "10", - "Table element should have a border property of '10'" - ); + table.set_border("10"); + assert_eq!( + table.border(), + "10", + "Table element should have a border property of '10'" + ); - table.set_frame("above"); - assert_eq!( - table.frame(), - "above", - "Table element should have an frame property of 'above'" - ); + table.set_frame("above"); + assert_eq!( + table.frame(), + "above", + "Table element should have an frame property of 'above'" + ); - table.set_rules("none"); - assert_eq!( - table.rules(), - "none", - "Table element should have an rules property of 'none'" - ); + table.set_rules("none"); + assert_eq!( + table.rules(), + "none", + "Table element should have an rules property of 'none'" + ); - table.set_summary("summary"); - assert_eq!( - table.summary(), - "summary", - "Table element should have an summary property of 'summary'" - ); + table.set_summary("summary"); + assert_eq!( + table.summary(), + "summary", + "Table element should have an summary property of 'summary'" + ); - table.set_width("1000"); - assert_eq!( - table.width(), - "1000", - "Table element should have a width property of '1000'" - ); + table.set_width("1000"); + assert_eq!( + table.width(), + "1000", + "Table element should have a width property of '1000'" + ); - table.set_bg_color("#ffffff"); - assert_eq!( - table.bg_color(), - "#ffffff", - "Table element should have an bgColor property of '#ffffff'" - ); + table.set_bg_color("#ffffff"); + assert_eq!( + table.bg_color(), + "#ffffff", + "Table element should have an bgColor property of '#ffffff'" + ); - table.set_cell_padding("1"); - assert_eq!( - table.cell_padding(), - "1", - "Table element should have an cellPadding property of '1'" - ); + table.set_cell_padding("1"); + assert_eq!( + table.cell_padding(), + "1", + "Table element should have an cellPadding property of '1'" + ); - table.set_cell_spacing("1"); - assert_eq!( - table.cell_spacing(), - "1", - "Table element should have an cellSpacing property of '1'" - ); + table.set_cell_spacing("1"); + assert_eq!( + table.cell_spacing(), + "1", + "Table element should have an cellSpacing property of '1'" + ); } diff --git a/crates/web-sys/tests/wasm/title_element.rs b/crates/web-sys/tests/wasm/title_element.rs index 82f231100..b3de7ae76 100644 --- a/crates/web-sys/tests/wasm/title_element.rs +++ b/crates/web-sys/tests/wasm/title_element.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::HtmlTitleElement; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_title() -> HtmlTitleElement; } diff --git a/crates/web-sys/tests/wasm/xpath_result.rs b/crates/web-sys/tests/wasm/xpath_result.rs index c69965de6..4260dcb1b 100644 --- a/crates/web-sys/tests/wasm/xpath_result.rs +++ b/crates/web-sys/tests/wasm/xpath_result.rs @@ -1,16 +1,27 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; use web_sys::XPathResult; #[wasm_bindgen(module = "./tests/wasm/element.js")] -extern { +extern "C" { fn new_xpath_result() -> XPathResult; } #[wasm_bindgen_test] fn test_xpath_result() { let xpath_result = new_xpath_result(); - assert_eq!(xpath_result.result_type(), XPathResult::UNORDERED_NODE_ITERATOR_TYPE); + assert_eq!( + xpath_result.result_type(), + XPathResult::UNORDERED_NODE_ITERATOR_TYPE + ); assert_eq!(xpath_result.invalid_iterator_state(), false); - assert_eq!(xpath_result.iterate_next().unwrap().unwrap().text_content().unwrap(), "tomato"); + assert_eq!( + xpath_result + .iterate_next() + .unwrap() + .unwrap() + .text_content() + .unwrap(), + "tomato" + ); } diff --git a/crates/webidl-tests/build.rs b/crates/webidl-tests/build.rs index d90426130..1dbf71f81 100644 --- a/crates/webidl-tests/build.rs +++ b/crates/webidl-tests/build.rs @@ -1,5 +1,5 @@ -extern crate wasm_bindgen_webidl; extern crate env_logger; +extern crate wasm_bindgen_webidl; use std::env; use std::fs; @@ -19,13 +19,11 @@ fn main() { println!("processing {:?}", path); let mut generated_rust = wasm_bindgen_webidl::compile(&idl, None).unwrap(); - let out_file = out_dir.join(path.file_name().unwrap()) - .with_extension("rs"); + let out_file = out_dir.join(path.file_name().unwrap()).with_extension("rs"); - let js_file = path.with_extension("js") - .canonicalize() - .unwrap(); - generated_rust.push_str(&format!(r#" + let js_file = path.with_extension("js").canonicalize().unwrap(); + generated_rust.push_str(&format!( + r#" pub mod import_script {{ use wasm_bindgen::prelude::*; use wasm_bindgen_test::*; @@ -42,7 +40,10 @@ fn main() { }} }} }} - "#, js_file.display(), i)); + "#, + js_file.display(), + i + )); fs::write(&out_file, generated_rust).unwrap(); diff --git a/crates/webidl-tests/callbacks.rs b/crates/webidl-tests/callbacks.rs index 9fd83181a..bdb4858eb 100644 --- a/crates/webidl-tests/callbacks.rs +++ b/crates/webidl-tests/callbacks.rs @@ -1,5 +1,5 @@ -use wasm_bindgen_test::*; use js_sys::{Function, Object}; +use wasm_bindgen_test::*; include!(concat!(env!("OUT_DIR"), "/callbacks.rs")); diff --git a/crates/webidl-tests/dictionary.rs b/crates/webidl-tests/dictionary.rs index cf26d5eaf..d769b9e9a 100644 --- a/crates/webidl-tests/dictionary.rs +++ b/crates/webidl-tests/dictionary.rs @@ -1,10 +1,10 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; include!(concat!(env!("OUT_DIR"), "/dictionary.rs")); #[wasm_bindgen] -extern { +extern "C" { fn assert_dict_c(c: &C); #[wasm_bindgen(js_name = assert_dict_c)] fn assert_dict_c2(c: C); @@ -44,8 +44,7 @@ fn casing() { #[wasm_bindgen_test] fn many_types() { - ManyTypes::new() - .a("a"); + ManyTypes::new().a("a"); } #[wasm_bindgen_test] diff --git a/crates/webidl-tests/global.rs b/crates/webidl-tests/global.rs index 2a9846909..15e1c5088 100644 --- a/crates/webidl-tests/global.rs +++ b/crates/webidl-tests/global.rs @@ -5,7 +5,7 @@ use wasm_bindgen_test::*; include!(concat!(env!("OUT_DIR"), "/global.rs")); #[wasm_bindgen] -extern { +extern "C" { fn get_global() -> Global; } diff --git a/crates/webidl-tests/main.rs b/crates/webidl-tests/main.rs index 2e20392a8..0dffef7ff 100644 --- a/crates/webidl-tests/main.rs +++ b/crates/webidl-tests/main.rs @@ -4,11 +4,11 @@ extern crate wasm_bindgen_test; pub mod array; pub mod array_buffer; +pub mod callbacks; pub mod consts; +pub mod dictionary; pub mod enums; +pub mod global; pub mod namespace; pub mod simple; pub mod throws; -pub mod dictionary; -pub mod global; -pub mod callbacks; diff --git a/crates/webidl-tests/simple.rs b/crates/webidl-tests/simple.rs index 21a710e41..a3d295153 100644 --- a/crates/webidl-tests/simple.rs +++ b/crates/webidl-tests/simple.rs @@ -1,7 +1,7 @@ use js_sys::Object; -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; include!(concat!(env!("OUT_DIR"), "/simple.rs")); @@ -73,11 +73,10 @@ fn nullable_method() { } #[wasm_bindgen] -extern { +extern "C" { fn get_global_method() -> GlobalMethod; } - #[wasm_bindgen_test] fn global_method() { let x = get_global_method(); @@ -97,16 +96,46 @@ fn indexing() { #[wasm_bindgen_test] fn optional_and_union_arguments() { let f = OptionalAndUnionArguments::new().unwrap(); - 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_b_and_i16("abc", false, 5), "string, abc, boolean, false, number, 5, number, 456"); - assert_eq!(f.m_with_b_and_str("abc", false, "5"), "string, abc, boolean, false, string, 5, number, 456"); - assert_eq!(f.m_with_b_and_i16_and_opt_i32("abc", false, 5, Some(10)), "string, abc, boolean, false, number, 5, number, 10"); - assert_eq!(f.m_with_b_and_i16_and_opt_f64("abc", false, 5, Some(10.0)), "string, abc, boolean, false, number, 5, number, 10"); - assert_eq!(f.m_with_b_and_i16_and_opt_bool("abc", false, 5, Some(true)), "string, abc, boolean, false, number, 5, boolean, true"); - assert_eq!(f.m_with_b_and_str_and_opt_i32("abc", false, "5", Some(10)), "string, abc, boolean, false, string, 5, number, 10"); - assert_eq!(f.m_with_b_and_str_and_opt_f64("abc", false, "5", Some(12.0)), "string, abc, boolean, false, string, 5, number, 12"); - assert_eq!(f.m_with_b_and_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_b_and_i16("abc", false, 5), + "string, abc, boolean, false, number, 5, number, 456" + ); + assert_eq!( + f.m_with_b_and_str("abc", false, "5"), + "string, abc, boolean, false, string, 5, number, 456" + ); + assert_eq!( + f.m_with_b_and_i16_and_opt_i32("abc", false, 5, Some(10)), + "string, abc, boolean, false, number, 5, number, 10" + ); + assert_eq!( + f.m_with_b_and_i16_and_opt_f64("abc", false, 5, Some(10.0)), + "string, abc, boolean, false, number, 5, number, 10" + ); + assert_eq!( + f.m_with_b_and_i16_and_opt_bool("abc", false, 5, Some(true)), + "string, abc, boolean, false, number, 5, boolean, true" + ); + assert_eq!( + f.m_with_b_and_str_and_opt_i32("abc", false, "5", Some(10)), + "string, abc, boolean, false, string, 5, number, 10" + ); + assert_eq!( + f.m_with_b_and_str_and_opt_f64("abc", false, "5", Some(12.0)), + "string, abc, boolean, false, string, 5, number, 12" + ); + assert_eq!( + f.m_with_b_and_str_and_opt_bool("abc", false, "5", Some(true)), + "string, abc, boolean, false, string, 5, boolean, true" + ); } #[wasm_bindgen_test] @@ -114,15 +143,13 @@ fn variadic() { let f = Variadic::new().unwrap(); assert_eq!(f.sum_5(1, 2, 3, 4, 5), 15); assert_eq!( - f.sum( - &::js_sys::Array::of5( - &JsValue::from_f64(1f64), - &JsValue::from_f64(2f64), - &JsValue::from_f64(3f64), - &JsValue::from_f64(4f64), - &JsValue::from_f64(5f64), - ) - ), + f.sum(&::js_sys::Array::of5( + &JsValue::from_f64(1f64), + &JsValue::from_f64(2f64), + &JsValue::from_f64(3f64), + &JsValue::from_f64(4f64), + &JsValue::from_f64(5f64), + )), 15 ); } @@ -167,20 +194,18 @@ fn callback() { let o = InvokeCallback::new().unwrap(); { static mut HIT: bool = false; - let cb = Closure::wrap(Box::new(move || { - unsafe { HIT = true; } + let cb = Closure::wrap(Box::new(move || unsafe { + HIT = true; }) as Box); o.invoke(cb.as_ref().unchecked_ref()); assert!(unsafe { HIT }); } - let cb = Closure::wrap(Box::new(move |a, b| { - a + b - }) as Box u32>); + let cb = Closure::wrap(Box::new(move |a, b| a + b) as Box u32>); assert_eq!(o.call_add(cb.as_ref().unchecked_ref()), 3); - let cb = Closure::wrap(Box::new(move |a: String, b| { - a.repeat(b) - }) as Box String>); + let cb = Closure::wrap( + Box::new(move |a: String, b| a.repeat(b)) as Box String> + ); assert_eq!(o.call_repeat(cb.as_ref().unchecked_ref()), "abababab"); } diff --git a/crates/webidl/src/error.rs b/crates/webidl/src/error.rs index cdf2519df..0984359f0 100644 --- a/crates/webidl/src/error.rs +++ b/crates/webidl/src/error.rs @@ -8,16 +8,16 @@ pub type Result = ::std::result::Result; #[derive(Debug, Fail, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum ErrorKind { /// Failed to open a WebIDL file. - #[fail(display="opening WebIDL file")] + #[fail(display = "opening WebIDL file")] OpeningWebIDLFile, /// Failed to read a WebIDL file. - #[fail(display="reading WebIDL file")] + #[fail(display = "reading WebIDL file")] ReadingWebIDLFile, /// Failed to parse a WebIDL file. - #[fail(display="parsing WebIDL source text at {}", _0)] + #[fail(display = "parsing WebIDL source text at {}", _0)] ParsingWebIDLSourcePos(usize), /// Failed to parse a WebIDL file. - #[fail(display="parsing WebIDL source text")] + #[fail(display = "parsing WebIDL source text")] ParsingWebIDLSource, } @@ -52,7 +52,9 @@ impl Error { impl From for Error { fn from(kind: ErrorKind) -> Error { - Error { inner: Context::new(kind) } + Error { + inner: Context::new(kind), + } } } @@ -61,5 +63,3 @@ impl From> for Error { Error { inner: inner } } } - - diff --git a/crates/webidl/src/first_pass.rs b/crates/webidl/src/first_pass.rs index c149e1902..37ce61c28 100644 --- a/crates/webidl/src/first_pass.rs +++ b/crates/webidl/src/first_pass.rs @@ -11,17 +11,17 @@ use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet}; use proc_macro2::Ident; -use weedle::{DictionaryDefinition, PartialDictionaryDefinition}; -use weedle::CallbackInterfaceDefinition; +use weedle; use weedle::argument::Argument; use weedle::attribute::*; use weedle::interface::*; use weedle::mixin::*; -use weedle; +use weedle::CallbackInterfaceDefinition; +use weedle::{DictionaryDefinition, PartialDictionaryDefinition}; use super::Result; -use util::camel_case_ident; use util; +use util::camel_case_ident; /// Collection of constructs that may use partial. #[derive(Default)] @@ -154,7 +154,9 @@ impl<'src> FirstPass<'src, ()> for weedle::DictionaryDefinition<'src> { return Ok(()); } - record.dictionaries.entry(self.identifier.0) + record + .dictionaries + .entry(self.identifier.0) .or_default() .definition = Some(self); Ok(()) @@ -167,7 +169,9 @@ impl<'src> FirstPass<'src, ()> for weedle::PartialDictionaryDefinition<'src> { return Ok(()); } - record.dictionaries.entry(self.identifier.0) + record + .dictionaries + .entry(self.identifier.0) .or_default() .partials .push(self); @@ -182,7 +186,10 @@ impl<'src> FirstPass<'src, ()> for weedle::EnumDefinition<'src> { } if record.enums.insert(self.identifier.0, self).is_some() { - info!("Encountered multiple enum declarations: {}", self.identifier.0); + info!( + "Encountered multiple enum declarations: {}", + self.identifier.0 + ); } Ok(()) @@ -223,7 +230,7 @@ fn first_pass_operation<'src>( is_static: bool, ) { if util::is_chrome_only(attrs) { - return + return; } let mut names = Vec::with_capacity(arguments.len()); @@ -240,29 +247,32 @@ fn first_pass_operation<'src>( .get_mut(self_name) .expect(&format!("not found {} interface", self_name)); &mut x.operations - }, + } FirstPassOperationType::Mixin => { let x = record .mixins .get_mut(self_name) .expect(&format!("not found {} mixin", self_name)); &mut x.operations - }, + } FirstPassOperationType::Namespace => { let x = record .namespaces .get_mut(self_name) .expect(&format!("not found {} namespace", self_name)); &mut x.operations - }, + } }; let mut args = Vec::with_capacity(arguments.len()); for argument in arguments { let (name, ty, optional, variadic) = match argument { - Argument::Single(single) => - (single.identifier.0, &single.type_.type_, single.optional.is_some(), false), - Argument::Variadic(variadic) => - (variadic.identifier.0, &variadic.type_, false, true), + Argument::Single(single) => ( + single.identifier.0, + &single.type_.type_, + single.optional.is_some(), + false, + ), + Argument::Variadic(variadic) => (variadic.identifier.0, &variadic.type_, false, true), }; args.push(Arg { name, @@ -289,26 +299,22 @@ impl<'src> FirstPass<'src, ()> for weedle::InterfaceDefinition<'src> { } if util::is_no_interface_object(&self.attributes) { - info!("Skipping because of `NoInterfaceObject` attribute: {:?}", self.identifier.0); + info!( + "Skipping because of `NoInterfaceObject` attribute: {:?}", + self.identifier.0 + ); return Ok(()); } { - let interface_data = record - .interfaces - .entry(self.identifier.0) - .or_default(); + let interface_data = record.interfaces.entry(self.identifier.0).or_default(); interface_data.partial = false; interface_data.superclass = self.inheritance.map(|s| s.identifier.0); interface_data.definition_attributes = self.attributes.as_ref(); } if let Some(attrs) = &self.attributes { for attr in attrs.body.list.iter() { - process_interface_attribute( - record, - self.identifier.0, - attr, - ); + process_interface_attribute(record, self.identifier.0, attr); } } @@ -323,18 +329,19 @@ impl<'src> FirstPass<'src, ()> for weedle::InterfaceDefinition<'src> { fn process_interface_attribute<'src>( record: &mut FirstPassRecord<'src>, self_name: &'src str, - attr: &'src ExtendedAttribute<'src> + attr: &'src ExtendedAttribute<'src>, ) { let ident = weedle::common::Identifier(self_name); - let non_null = weedle::types::MayBeNull { type_: ident, q_mark: None }; + let non_null = weedle::types::MayBeNull { + type_: ident, + q_mark: None, + }; let non_any = weedle::types::NonAnyType::Identifier(non_null); let single = weedle::types::SingleType::NonAny(non_any); let ty = weedle::types::Type::Single(single); let return_ty = weedle::types::ReturnType::Type(ty); match attr { - ExtendedAttribute::ArgList(list) - if list.identifier.0 == "Constructor" => - { + ExtendedAttribute::ArgList(list) if list.identifier.0 == "Constructor" => { first_pass_operation( record, FirstPassOperationType::Interface, @@ -358,14 +365,14 @@ fn process_interface_attribute<'src>( false, ); } - ExtendedAttribute::NamedArgList(list) - if list.lhs_identifier.0 == "NamedConstructor" => - { + ExtendedAttribute::NamedArgList(list) if list.lhs_identifier.0 == "NamedConstructor" => { first_pass_operation( record, FirstPassOperationType::Interface, self_name, - &[OperationId::Constructor(IgnoreTraits(list.rhs_identifier.0))], + &[OperationId::Constructor(IgnoreTraits( + list.rhs_identifier.0, + ))], &list.args.body.list, &return_ty, &None, @@ -384,12 +391,10 @@ impl<'src> FirstPass<'src, ()> for weedle::PartialInterfaceDefinition<'src> { record .interfaces .entry(self.identifier.0) - .or_insert_with(|| - InterfaceData { - partial: true, - ..Default::default() - }, - ); + .or_insert_with(|| InterfaceData { + partial: true, + ..Default::default() + }); for member in &self.members.body { member.first_pass(record, self.identifier.0)?; } @@ -398,19 +403,20 @@ impl<'src> FirstPass<'src, ()> for weedle::PartialInterfaceDefinition<'src> { } impl<'src> FirstPass<'src, &'src str> for weedle::interface::InterfaceMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { match self { - InterfaceMember::Attribute(attr) => { - attr.first_pass(record, self_name) - } - InterfaceMember::Operation(op) => { - op.first_pass(record, self_name) - } + InterfaceMember::Attribute(attr) => attr.first_pass(record, self_name), + InterfaceMember::Operation(op) => op.first_pass(record, self_name), InterfaceMember::Const(const_) => { if util::is_chrome_only(&const_.attributes) { return Ok(()); } - record.interfaces + record + .interfaces .get_mut(self_name) .unwrap() .consts @@ -427,7 +433,10 @@ impl<'src> FirstPass<'src, &'src str> for weedle::interface::InterfaceMember<'sr Ok(()) } InterfaceMember::Stringifier(_) => { - warn!("Unsupported WebIDL Stringifier interface member: {:?}", self); + warn!( + "Unsupported WebIDL Stringifier interface member: {:?}", + self + ); Ok(()) } InterfaceMember::Setlike(_) => { @@ -439,11 +448,15 @@ impl<'src> FirstPass<'src, &'src str> for weedle::interface::InterfaceMember<'sr } impl<'src> FirstPass<'src, &'src str> for weedle::interface::OperationInterfaceMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { let is_static = match self.modifier { Some(StringifierOrStatic::Stringifier(_)) => { warn!("Unsupported webidl stringifier: {:?}", self); - return Ok(()) + return Ok(()); } Some(StringifierOrStatic::Static(_)) => true, None => false, @@ -455,7 +468,7 @@ impl<'src> FirstPass<'src, &'src str> for weedle::interface::OperationInterfaceM Special::Getter(_) => ids.push(OperationId::IndexingGetter), Special::Setter(_) => ids.push(OperationId::IndexingSetter), Special::Deleter(_) => ids.push(OperationId::IndexingDeleter), - Special::LegacyCaller(_) => {}, + Special::LegacyCaller(_) => {} }; } first_pass_operation( @@ -473,12 +486,17 @@ impl<'src> FirstPass<'src, &'src str> for weedle::interface::OperationInterfaceM } impl<'src> FirstPass<'src, &'src str> for weedle::interface::AttributeInterfaceMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { if util::is_chrome_only(&self.attributes) { return Ok(()); } - record.interfaces + record + .interfaces .get_mut(self_name) .unwrap() .attributes @@ -487,17 +505,14 @@ impl<'src> FirstPass<'src, &'src str> for weedle::interface::AttributeInterfaceM } } -impl<'src> FirstPass<'src, ()> for weedle::InterfaceMixinDefinition<'src>{ +impl<'src> FirstPass<'src, ()> for weedle::InterfaceMixinDefinition<'src> { fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, (): ()) -> Result<()> { if util::is_chrome_only(&self.attributes) { return Ok(()); } { - let mixin_data = record - .mixins - .entry(self.identifier.0) - .or_default(); + let mixin_data = record.mixins.entry(self.identifier.0).or_default(); mixin_data.partial = false; mixin_data.definition_attributes = self.attributes.as_ref(); } @@ -519,12 +534,10 @@ impl<'src> FirstPass<'src, ()> for weedle::PartialInterfaceMixinDefinition<'src> record .mixins .entry(self.identifier.0) - .or_insert_with(|| - MixinData { - partial: true, - ..Default::default() - }, - ); + .or_insert_with(|| MixinData { + partial: true, + ..Default::default() + }); for member in &self.members.body { member.first_pass(record, self.identifier.0)?; @@ -535,7 +548,11 @@ impl<'src> FirstPass<'src, ()> for weedle::PartialInterfaceMixinDefinition<'src> } impl<'src> FirstPass<'src, &'src str> for weedle::mixin::MixinMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { match self { MixinMember::Operation(op) => op.first_pass(record, self_name), MixinMember::Attribute(a) => a.first_pass(record, self_name), @@ -543,11 +560,7 @@ impl<'src> FirstPass<'src, &'src str> for weedle::mixin::MixinMember<'src> { if util::is_chrome_only(&a.attributes) { return Ok(()); } - record.mixins - .get_mut(self_name) - .unwrap() - .consts - .push(a); + record.mixins.get_mut(self_name).unwrap().consts.push(a); Ok(()) } MixinMember::Stringifier(_) => { @@ -559,10 +572,14 @@ impl<'src> FirstPass<'src, &'src str> for weedle::mixin::MixinMember<'src> { } impl<'src> FirstPass<'src, &'src str> for weedle::mixin::OperationMixinMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { if self.stringifier.is_some() { warn!("Unsupported webidl stringifier: {:?}", self); - return Ok(()) + return Ok(()); } first_pass_operation( @@ -580,11 +597,16 @@ impl<'src> FirstPass<'src, &'src str> for weedle::mixin::OperationMixinMember<'s } impl<'src> FirstPass<'src, &'src str> for weedle::mixin::AttributeMixinMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { if util::is_chrome_only(&self.attributes) { return Ok(()); } - record.mixins + record + .mixins .get_mut(self_name) .unwrap() .attributes @@ -599,8 +621,15 @@ impl<'src> FirstPass<'src, ()> for weedle::TypedefDefinition<'src> { return Ok(()); } - if record.typedefs.insert(self.identifier.0, &self.type_.type_).is_some() { - info!("Encountered multiple typedef declarations: {}", self.identifier.0); + if record + .typedefs + .insert(self.identifier.0, &self.type_.type_) + .is_some() + { + info!( + "Encountered multiple typedef declarations: {}", + self.identifier.0 + ); } Ok(()) @@ -610,13 +639,10 @@ impl<'src> FirstPass<'src, ()> for weedle::TypedefDefinition<'src> { impl<'src> FirstPass<'src, ()> for weedle::NamespaceDefinition<'src> { fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, (): ()) -> Result<()> { if util::is_chrome_only(&self.attributes) { - return Ok(()) + return Ok(()); } - record - .namespaces - .entry(self.identifier.0) - .or_default(); + record.namespaces.entry(self.identifier.0).or_default(); for member in &self.members.body { member.first_pass(record, self.identifier.0)?; @@ -629,13 +655,10 @@ impl<'src> FirstPass<'src, ()> for weedle::NamespaceDefinition<'src> { impl<'src> FirstPass<'src, ()> for weedle::PartialNamespaceDefinition<'src> { fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, (): ()) -> Result<()> { if util::is_chrome_only(&self.attributes) { - return Ok(()) + return Ok(()); } - record - .namespaces - .entry(self.identifier.0) - .or_default(); + record.namespaces.entry(self.identifier.0).or_default(); for member in &self.members.body { member.first_pass(record, self.identifier.0)?; @@ -646,18 +669,24 @@ impl<'src> FirstPass<'src, ()> for weedle::PartialNamespaceDefinition<'src> { } impl<'src> FirstPass<'src, &'src str> for weedle::namespace::NamespaceMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { match self { - weedle::namespace::NamespaceMember::Operation(op) => { - op.first_pass(record, self_name) - } + weedle::namespace::NamespaceMember::Operation(op) => op.first_pass(record, self_name), _ => Ok(()), } } } impl<'src> FirstPass<'src, &'src str> for weedle::namespace::OperationNamespaceMember<'src> { - fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, self_name: &'src str) -> Result<()> { + fn first_pass( + &'src self, + record: &mut FirstPassRecord<'src>, + self_name: &'src str, + ) -> Result<()> { first_pass_operation( record, FirstPassOperationType::Namespace, @@ -682,12 +711,14 @@ impl<'src> FirstPass<'src, ()> for weedle::CallbackDefinition<'src> { impl<'src> FirstPass<'src, ()> for weedle::CallbackInterfaceDefinition<'src> { fn first_pass(&'src self, record: &mut FirstPassRecord<'src>, _: ()) -> Result<()> { if util::is_chrome_only(&self.attributes) { - return Ok(()) + return Ok(()); } if self.inheritance.is_some() { - warn!("skipping callback interface with inheritance: {}", - self.identifier.0); - return Ok(()) + warn!( + "skipping callback interface with inheritance: {}", + self.identifier.0 + ); + return Ok(()); } let data = CallbackInterfaceData { definition: self, @@ -699,9 +730,7 @@ impl<'src> FirstPass<'src, ()> for weedle::CallbackInterfaceDefinition<'src> { } impl<'a> FirstPassRecord<'a> { - pub fn all_superclasses<'me>(&'me self, interface: &str) - -> impl Iterator + 'me - { + pub fn all_superclasses<'me>(&'me self, interface: &str) -> impl Iterator + 'me { let mut set = BTreeSet::new(); self.fill_superclasses(interface, &mut set); set.into_iter() @@ -723,9 +752,10 @@ impl<'a> FirstPassRecord<'a> { } } - pub fn all_mixins<'me>(&'me self, interface: &str) - -> impl Iterator> + 'me - { + pub fn all_mixins<'me>( + &'me self, + interface: &str, + ) -> impl Iterator> + 'me { let mut set = Vec::new(); self.fill_mixins(interface, interface, &mut set); set.into_iter() @@ -752,7 +782,9 @@ impl<'a> FirstPassRecord<'a> { pub struct IgnoreTraits(pub T); impl PartialEq for IgnoreTraits { - fn eq(&self, _other: &IgnoreTraits) -> bool { true } + fn eq(&self, _other: &IgnoreTraits) -> bool { + true + } } impl Eq for IgnoreTraits {} diff --git a/crates/webidl/src/idl_type.rs b/crates/webidl/src/idl_type.rs index 33dfc9dfd..8d20eb13a 100644 --- a/crates/webidl/src/idl_type.rs +++ b/crates/webidl/src/idl_type.rs @@ -6,7 +6,7 @@ use weedle::term; use weedle::types::*; use first_pass::FirstPassRecord; -use util::{TypePosition, camel_case_ident, snake_case_ident, shared_ref, option_ty, array}; +use util::{array, camel_case_ident, option_ty, shared_ref, snake_case_ident, TypePosition}; #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] pub(crate) enum IdlType<'a> { @@ -49,7 +49,10 @@ pub(crate) enum IdlType<'a> { Interface(&'a str), Dictionary(&'a str), Enum(&'a str), - CallbackInterface { name: &'a str, single_function: bool }, + CallbackInterface { + name: &'a str, + single_function: bool, + }, Nullable(Box>), FrozenArray(Box>), @@ -132,13 +135,17 @@ impl<'a> ToIdlType<'a> for NonAnyType<'a> { impl<'a> ToIdlType<'a> for SequenceType<'a> { fn to_idl_type(&self, record: &FirstPassRecord<'a>) -> Option> { - Some(IdlType::Sequence(Box::new(self.generics.body.to_idl_type(record)?))) + Some(IdlType::Sequence(Box::new( + self.generics.body.to_idl_type(record)?, + ))) } } impl<'a> ToIdlType<'a> for FrozenArrayType<'a> { fn to_idl_type(&self, record: &FirstPassRecord<'a>) -> Option> { - Some(IdlType::FrozenArray(Box::new(self.generics.body.to_idl_type(record)?))) + Some(IdlType::FrozenArray(Box::new( + self.generics.body.to_idl_type(record)?, + ))) } } @@ -155,7 +162,9 @@ impl<'a, T: ToIdlType<'a>> ToIdlType<'a> for MayBeNull { impl<'a> ToIdlType<'a> for PromiseType<'a> { fn to_idl_type(&self, record: &FirstPassRecord<'a>) -> Option> { - Some(IdlType::Promise(Box::new(self.generics.body.to_idl_type(record)?))) + Some(IdlType::Promise(Box::new( + self.generics.body.to_idl_type(record)?, + ))) } } @@ -230,12 +239,10 @@ impl<'a> ToIdlType<'a> for DoubleType { impl<'a> ToIdlType<'a> for RecordType<'a> { fn to_idl_type(&self, record: &FirstPassRecord<'a>) -> Option> { - Some( - IdlType::Record( - Box::new(self.generics.body.0.to_idl_type(record)?), - Box::new(self.generics.body.2.to_idl_type(record)?) - ) - ) + Some(IdlType::Record( + Box::new(self.generics.body.0.to_idl_type(record)?), + Box::new(self.generics.body.2.to_idl_type(record)?), + )) } } @@ -375,13 +382,9 @@ impl<'a> IdlType<'a> { IdlType::UnsignedLong => dst.push_str("u32"), IdlType::LongLong => dst.push_str("i64"), IdlType::UnsignedLongLong => dst.push_str("u64"), - | 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::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"), @@ -405,32 +408,30 @@ impl<'a> IdlType<'a> { IdlType::Interface(name) => dst.push_str(&snake_case_ident(name)), IdlType::Dictionary(name) => dst.push_str(&snake_case_ident(name)), IdlType::Enum(name) => dst.push_str(&snake_case_ident(name)), - IdlType::CallbackInterface { name, .. } => { - dst.push_str(&snake_case_ident(name)) - } + IdlType::CallbackInterface { name, .. } => dst.push_str(&snake_case_ident(name)), IdlType::Nullable(idl_type) => { dst.push_str("opt_"); idl_type.push_snake_case_name(dst); - }, + } IdlType::FrozenArray(idl_type) => { idl_type.push_snake_case_name(dst); dst.push_str("_frozen_array"); - }, + } IdlType::Sequence(idl_type) => { idl_type.push_snake_case_name(dst); dst.push_str("_sequence"); - }, + } IdlType::Promise(idl_type) => { idl_type.push_snake_case_name(dst); dst.push_str("_promise"); - }, + } IdlType::Record(idl_type_from, idl_type_to) => { dst.push_str("record_from_"); idl_type_from.push_snake_case_name(dst); dst.push_str("_to_"); idl_type_to.push_snake_case_name(dst); - }, + } IdlType::Union(idl_types) => { dst.push_str("union_of_"); let mut first = true; @@ -442,7 +443,7 @@ impl<'a> IdlType<'a> { } idl_type.push_snake_case_name(dst); } - }, + } IdlType::Any => dst.push_str("any"), IdlType::Void => dst.push_str("void"), @@ -483,16 +484,13 @@ impl<'a> IdlType<'a> { // // Perhaps one day we'll bind to u64/i64 here, but we need `BigInt` // to see more usage! - IdlType::LongLong | - IdlType::UnsignedLongLong => Some(ident_ty(raw_ident("f64"))), + IdlType::LongLong | IdlType::UnsignedLongLong => Some(ident_ty(raw_ident("f64"))), IdlType::Float => Some(ident_ty(raw_ident("f32"))), IdlType::UnrestrictedFloat => Some(ident_ty(raw_ident("f32"))), IdlType::Double => Some(ident_ty(raw_ident("f64"))), IdlType::UnrestrictedDouble => Some(ident_ty(raw_ident("f64"))), - | IdlType::DomString - | IdlType::ByteString - | IdlType::UsvString => match pos { + IdlType::DomString | IdlType::ByteString | IdlType::UsvString => match pos { TypePosition::Argument => Some(shared_ref(ident_ty(raw_ident("str")), false)), TypePosition::Return => Some(ident_ty(raw_ident("String"))), }, @@ -519,7 +517,7 @@ impl<'a> IdlType<'a> { | IdlType::CallbackInterface { name, .. } => { let ty = ident_ty(rust_ident(camel_case_ident(name).as_str())); anyref(ty) - }, + } IdlType::Enum(name) => Some(ident_ty(rust_ident(camel_case_ident(name).as_str()))), IdlType::Nullable(idl_type) => { @@ -532,11 +530,14 @@ impl<'a> IdlType<'a> { // it's up to users to dispatch and/or create instances // appropriately. if let syn::Type::Path(path) = &inner { - if path.qself.is_none() && - path.path.segments.last().map(|p| p.value().ident == "JsValue") - .unwrap_or(false) + if path.qself.is_none() && path + .path + .segments + .last() + .map(|p| p.value().ident == "JsValue") + .unwrap_or(false) { - return Some(inner.clone()) + return Some(inner.clone()); } } @@ -570,24 +571,20 @@ impl<'a> IdlType<'a> { // Such an enum, however, might have a relatively high // overhead in creating it from a JS value, but would be // cheap to convert from a variant back to a JS value. - if idl_types - .iter() - .all(|idl_type| - match idl_type { - IdlType::Interface(..) => true, - _ => false, - } - ) { + if idl_types.iter().all(|idl_type| match idl_type { + IdlType::Interface(..) => true, + _ => false, + }) { IdlType::Object.to_syn_type(pos) } else { IdlType::Any.to_syn_type(pos) } - }, + } IdlType::Any => { let path = vec![rust_ident("wasm_bindgen"), rust_ident("JsValue")]; anyref(leading_colon_path_ty(path)) - }, + } IdlType::Void => None, IdlType::Callback => js_sys("Function"), } @@ -629,33 +626,26 @@ impl<'a> IdlType<'a> { let mut idl_types = Vec::new(); for idl_type_from in idl_type_from.flatten() { for idl_type_to in idl_type_to.flatten() { - idl_types.push( - IdlType::Record( - Box::new(idl_type_from.clone()), - Box::new(idl_type_to.clone()) - ) - ); + idl_types.push(IdlType::Record( + Box::new(idl_type_from.clone()), + Box::new(idl_type_to.clone()), + )); } } idl_types - }, + } IdlType::Union(idl_types) => idl_types .iter() .flat_map(|idl_type| idl_type.flatten()) .collect(), - IdlType::ArrayBufferView => { - vec![IdlType::ArrayBufferView, IdlType::Uint8ArrayMut] - } - IdlType::BufferSource => { - vec![IdlType::BufferSource, IdlType::Uint8ArrayMut] - } - IdlType::LongLong => { - vec![IdlType::Long, IdlType::Double] - } - IdlType::UnsignedLongLong => { - vec![IdlType::UnsignedLong, IdlType::Double] - } - IdlType::CallbackInterface { name, single_function: true } => { + IdlType::ArrayBufferView => vec![IdlType::ArrayBufferView, IdlType::Uint8ArrayMut], + IdlType::BufferSource => vec![IdlType::BufferSource, IdlType::Uint8ArrayMut], + IdlType::LongLong => vec![IdlType::Long, IdlType::Double], + IdlType::UnsignedLongLong => vec![IdlType::UnsignedLong, IdlType::Double], + IdlType::CallbackInterface { + name, + single_function: true, + } => { // According to the webidl spec [1] single-function callback // interfaces can also be replaced in arguments with simply a // single callable function, which we map to a `Callback`. @@ -663,7 +653,10 @@ impl<'a> IdlType<'a> { // [1]: https://heycam.github.io/webidl/#es-user-objects vec![ IdlType::Callback, - IdlType::CallbackInterface { name, single_function: false }, + IdlType::CallbackInterface { + name, + single_function: false, + }, ] } idl_type @ _ => vec![idl_type.clone()], @@ -678,26 +671,15 @@ fn idl_type_flatten_test() { assert_eq!( Union(vec![ Interface("Node"), - Union(vec![ - Sequence( - Box::new(Long), - ), - Interface("Event"), - ]), - Nullable( - Box::new(Union(vec![ - Interface("XMLHttpRequest"), - DomString, - ])), - ), - Sequence( - Box::new(Union(vec![ - Sequence( - Box::new(Double), - ), - Interface("NodeList"), - ])), - ), + Union(vec![Sequence(Box::new(Long),), Interface("Event"),]), + Nullable(Box::new(Union(vec![ + Interface("XMLHttpRequest"), + DomString, + ])),), + Sequence(Box::new(Union(vec![ + Sequence(Box::new(Double),), + Interface("NodeList"), + ])),), ]).flatten(), vec![ Interface("Node"), @@ -726,10 +708,9 @@ fn clamped(t: syn::Type) -> syn::Type { qself: None, path: syn::Path { leading_colon: Some(Default::default()), - segments: vec![ - Ident::new("wasm_bindgen", Span::call_site()).into(), - seg, - ].into_iter().collect(), + segments: vec![Ident::new("wasm_bindgen", Span::call_site()).into(), seg] + .into_iter() + .collect(), }, }.into() } diff --git a/crates/webidl/src/lib.rs b/crates/webidl/src/lib.rs index c14e6e7e0..6a6d13184 100644 --- a/crates/webidl/src/lib.rs +++ b/crates/webidl/src/lib.rs @@ -24,31 +24,34 @@ extern crate syn; extern crate wasm_bindgen_backend as backend; extern crate weedle; +mod error; mod first_pass; mod idl_type; mod util; -mod error; use std::collections::{BTreeSet, HashSet}; use std::env; use std::fs; use std::iter::FromIterator; -use backend::TryToTokens; use backend::ast; use backend::defined::ImportedTypeReferences; use backend::defined::{ImportedTypeDefinitions, RemoveUndefinedImports}; -use backend::util::{ident_ty, rust_ident, raw_ident, wrap_import_function}; +use backend::util::{ident_ty, raw_ident, rust_ident, wrap_import_function}; +use backend::TryToTokens; use proc_macro2::{Ident, Span}; use quote::ToTokens; -use weedle::attribute::{ExtendedAttributeList}; +use weedle::attribute::ExtendedAttributeList; use weedle::dictionary::DictionaryMember; use weedle::interface::InterfaceMember; -use first_pass::{FirstPass, FirstPassRecord, OperationId, InterfaceData}; -use first_pass::{OperationData, CallbackInterfaceData}; -use util::{public, webidl_const_v_to_backend_const_v, TypePosition, camel_case_ident, shouty_snake_case_ident, snake_case_ident, mdn_doc}; +use first_pass::{CallbackInterfaceData, OperationData}; +use first_pass::{FirstPass, FirstPassRecord, InterfaceData, OperationId}; use idl_type::ToIdlType; +use util::{ + camel_case_ident, mdn_doc, public, shouty_snake_case_ident, snake_case_ident, + webidl_const_v_to_backend_const_v, TypePosition, +}; pub use error::{Error, ErrorKind, Result}; @@ -58,25 +61,22 @@ struct Program { } /// Parse a string of WebIDL source text into a wasm-bindgen AST. -fn parse(webidl_source: &str, allowed_types: Option<&[&str]>) - -> Result -{ +fn parse(webidl_source: &str, allowed_types: Option<&[&str]>) -> Result { let definitions = match weedle::parse(webidl_source) { Ok(def) => def, Err(e) => { return Err(match &e { - weedle::Err::Incomplete(needed) => { - format_err!("needed {:?} more bytes", needed) - .context(ErrorKind::ParsingWebIDLSource).into() - } - weedle::Err::Error(cx) | - weedle::Err::Failure(cx) => { + weedle::Err::Incomplete(needed) => format_err!("needed {:?} more bytes", needed) + .context(ErrorKind::ParsingWebIDLSource) + .into(), + weedle::Err::Error(cx) | weedle::Err::Failure(cx) => { let remaining = match cx { weedle::Context::Code(remaining, _) => remaining, }; let pos = webidl_source.len() - remaining.len(); format_err!("failed to parse WebIDL") - .context(ErrorKind::ParsingWebIDLSourcePos(pos)).into() + .context(ErrorKind::ParsingWebIDLSourcePos(pos)) + .into() } }); } @@ -88,14 +88,10 @@ fn parse(webidl_source: &str, allowed_types: Option<&[&str]>) let mut program = Default::default(); let mut submodules = Vec::new(); - let allowed_types = allowed_types.map(|list| { - list.iter().cloned().collect::>() - }); - let filter = |name: &str| { - match &allowed_types { - Some(set) => set.contains(name), - None => true, - } + let allowed_types = allowed_types.map(|list| list.iter().cloned().collect::>()); + let filter = |name: &str| match &allowed_types { + Some(set) => set.contains(name), + None => true, }; for (name, e) in first_pass_record.enums.iter() { @@ -130,10 +126,8 @@ fn parse(webidl_source: &str, allowed_types: Option<&[&str]>) // `AsRef` and such implementations. for import in program.imports.iter_mut() { if let backend::ast::ImportKind::Type(t) = &mut import.kind { - t.extends.retain(|n| { - first_pass_record.builtin_idents.contains(n) || - filter(&n.to_string()) - }); + t.extends + .retain(|n| first_pass_record.builtin_idents.contains(n) || filter(&n.to_string())); } } @@ -145,10 +139,7 @@ fn parse(webidl_source: &str, allowed_types: Option<&[&str]>) /// Compile the given WebIDL source text into Rust source text containing /// `wasm-bindgen` bindings to the things described in the WebIDL. -pub fn compile( - webidl_source: &str, - allowed_types: Option<&[&str]>, -) -> Result { +pub fn compile(webidl_source: &str, allowed_types: Option<&[&str]>) -> Result { let ast = parse(webidl_source, allowed_types)?; Ok(compile_ast(ast)) } @@ -156,11 +147,34 @@ pub fn compile( fn builtin_idents() -> BTreeSet { BTreeSet::from_iter( vec![ - "str", "char", "bool", "JsValue", "u8", "i8", "u16", "i16", "u32", "i32", "u64", "i64", - "usize", "isize", "f32", "f64", "Result", "String", "Vec", "Option", - "Array", "ArrayBuffer", "Object", "Promise", "Function", "Clamped", + "str", + "char", + "bool", + "JsValue", + "u8", + "i8", + "u16", + "i16", + "u32", + "i32", + "u64", + "i64", + "usize", + "isize", + "f32", + "f64", + "Result", + "String", + "Vec", + "Option", + "Array", + "ArrayBuffer", + "Object", + "Promise", + "Function", + "Clamped", ].into_iter() - .map(|id| proc_macro2::Ident::new(id, proc_macro2::Span::call_site())), + .map(|id| proc_macro2::Ident::new(id, proc_macro2::Span::call_site())), ) } @@ -188,17 +202,20 @@ fn compile_ast(mut ast: Program) -> String { m.imported_type_references(&mut cb); } } - let changed = - ast.main.remove_undefined_imports(&|id| defined.contains(id)) || - ast.submodules.iter_mut().any(|(_, m)| { - m.remove_undefined_imports(&|id| defined.contains(id)) - }); + let changed = ast + .main + .remove_undefined_imports(&|id| defined.contains(id)) + || ast + .submodules + .iter_mut() + .any(|(_, m)| m.remove_undefined_imports(&|id| defined.contains(id))); if !changed { - break + break; } } if let Some(path) = track { - let contents = all_definitions.into_iter() + let contents = all_definitions + .into_iter() .filter(|def| !builtin.contains(def)) .map(|s| format!("{} = []", s)) .collect::>() @@ -229,7 +246,7 @@ impl<'src> FirstPassRecord<'src> { fn append_enum( &self, program: &mut backend::ast::Program, - enum_: &'src weedle::EnumDefinition<'src> + enum_: &'src weedle::EnumDefinition<'src>, ) { let variants = &enum_.values.body.list; program.imports.push(backend::ast::Import { @@ -246,8 +263,7 @@ impl<'src> FirstPassRecord<'src> { } else { rust_ident("None") } - }) - .collect(), + }).collect(), variant_values: variants.iter().map(|v| v.0.to_string()).collect(), rust_attrs: vec![parse_quote!(#[derive(Copy, Clone, PartialEq, Debug)])], }), @@ -267,7 +283,7 @@ impl<'src> FirstPassRecord<'src> { }; let mut fields = Vec::new(); if !self.append_dictionary_members(def.identifier.0, &mut fields) { - return + return; } program.dictionaries.push(ast::Dictionary { @@ -289,7 +305,7 @@ impl<'src> FirstPassRecord<'src> { // > non-inherited members ... if let Some(parent) = &definition.inheritance { if !self.append_dictionary_members(parent.identifier.0, dst) { - return false + return false; } } @@ -313,7 +329,7 @@ impl<'src> FirstPassRecord<'src> { // avoid generating bindings for the field and keep // going otherwise. if member.required.is_some() { - return false + return false; } } } @@ -324,7 +340,7 @@ impl<'src> FirstPassRecord<'src> { // now! dst[start..].sort_by_key(|f| f.name.clone()); - return true + return true; } fn dictionary_field( @@ -332,31 +348,35 @@ impl<'src> FirstPassRecord<'src> { field: &'src DictionaryMember<'src>, ) -> Option { // use argument position now as we're just binding setters - let ty = field.type_.to_idl_type(self)?.to_syn_type(TypePosition::Argument)?; + let ty = field + .type_ + .to_idl_type(self)? + .to_syn_type(TypePosition::Argument)?; // Slice types aren't supported because they don't implement // `Into` match ty { - syn::Type::Reference(ref i) => - match &*i.elem { - syn::Type::Slice(_) => return None, - _ => () - } + syn::Type::Reference(ref i) => match &*i.elem { + syn::Type::Slice(_) => return None, + _ => (), + }, syn::Type::Path(ref path, ..) => - // check that our inner don't contains slices either + // check that our inner don't contains slices either + { for seg in path.path.segments.iter() { if let syn::PathArguments::AngleBracketed(ref arg) = seg.arguments { for elem in &arg.args { if let syn::GenericArgument::Type(syn::Type::Reference(ref i)) = elem { match &*i.elem { syn::Type::Slice(_) => return None, - _ => () + _ => (), } } } } } - _ => () + } + _ => (), }; // Similarly i64/u64 aren't supported because they don't @@ -366,7 +386,7 @@ impl<'src> FirstPassRecord<'src> { any_64bit = any_64bit || i == "u64" || i == "i64"; }); if any_64bit { - return None + return None; } Some(ast::DictionaryField { @@ -387,7 +407,7 @@ impl<'src> FirstPassRecord<'src> { self.append_ns_member(&mut ret, name, id, data); } - return ret + return ret; } fn append_ns_member( @@ -399,13 +419,13 @@ impl<'src> FirstPassRecord<'src> { ) { let name = match id { OperationId::Operation(Some(name)) => name, - OperationId::Constructor(_) | - OperationId::Operation(None) | - OperationId::IndexingGetter | - OperationId::IndexingSetter | - OperationId::IndexingDeleter => { + OperationId::Constructor(_) + | OperationId::Operation(None) + | OperationId::IndexingGetter + | OperationId::IndexingSetter + | OperationId::IndexingDeleter => { warn!("Unsupported unnamed operation: on {:?}", self_name); - return + return; } }; let doc_comment = format!( @@ -422,13 +442,11 @@ impl<'src> FirstPassRecord<'src> { let mut doc = Some(doc_comment.clone()); self.append_required_features_doc(&import_function, &mut doc, extra); import_function.doc_comment = doc; - module.imports.push( - backend::ast::Import { - module: None, - js_namespace: Some(raw_ident(self_name)), - kind: backend::ast::ImportKind::Function(import_function), - } - ); + module.imports.push(backend::ast::Import { + module: None, + js_namespace: Some(raw_ident(self_name)), + kind: backend::ast::ImportKind::Function(import_function), + }); } } @@ -448,12 +466,10 @@ impl<'src> FirstPassRecord<'src> { None => { warn!( "Cannot convert const type to syn type: {:?} in {:?} on {:?}", - idl_type, - member, - self_name + idl_type, member, self_name ); - return - }, + return; + } }; program.consts.push(backend::ast::Const { @@ -471,11 +487,7 @@ impl<'src> FirstPassRecord<'src> { name: &'src str, data: &InterfaceData<'src>, ) { - let mut doc_comment = Some(format!( - "The `{}` object\n\n{}", - name, - mdn_doc(name, None), - )); + let mut doc_comment = Some(format!("The `{}` object\n\n{}", name, mdn_doc(name, None),)); let derive = syn::Attribute { pound_token: Default::default(), style: syn::AttrStyle::Outer, @@ -495,10 +507,11 @@ impl<'src> FirstPassRecord<'src> { let extra = camel_case_ident(name); let extra = &[&extra[..]]; self.append_required_features_doc(&import_type, &mut doc_comment, extra); - import_type.extends = self.all_superclasses(name) - .map(|name| Ident::new(&name, Span::call_site())) - .chain(Some(Ident::new("Object", Span::call_site()))) - .collect(); + import_type.extends = self + .all_superclasses(name) + .map(|name| Ident::new(&name, Span::call_site())) + .chain(Some(Ident::new("Object", Span::call_site()))) + .collect(); import_type.doc_comment = doc_comment; program.imports.push(backend::ast::Import { @@ -611,9 +624,8 @@ impl<'src> FirstPassRecord<'src> { id: &OperationId<'src>, op_data: &OperationData<'src>, ) { - let import_function_kind = |opkind| { - self.import_function_kind(self_name, op_data.is_static, opkind) - }; + let import_function_kind = + |opkind| self.import_function_kind(self_name, op_data.is_static, opkind); let kind = match id { OperationId::Constructor(ctor_name) => { let self_ty = ident_ty(rust_ident(&camel_case_ident(self_name))); @@ -623,9 +635,7 @@ impl<'src> FirstPassRecord<'src> { kind: backend::ast::MethodKind::Constructor, } } - OperationId::Operation(_) => { - import_function_kind(backend::ast::OperationKind::Regular) - } + OperationId::Operation(_) => import_function_kind(backend::ast::OperationKind::Regular), OperationId::IndexingGetter => { import_function_kind(backend::ast::OperationKind::IndexingGetter) } @@ -637,24 +647,15 @@ impl<'src> FirstPassRecord<'src> { } }; let doc = match id { - OperationId::Constructor(_) | - OperationId::Operation(None) => Some(String::new()), - OperationId::Operation(Some(name)) => { - Some(format!( - "The `{}()` method\n\n{}", - name, - mdn_doc(self_name, Some(name)) - )) - } - OperationId::IndexingGetter => { - Some(format!("The indexing getter\n\n")) - } - OperationId::IndexingSetter => { - Some(format!("The indexing setter\n\n")) - } - OperationId::IndexingDeleter => { - Some(format!("The indexing deleter\n\n")) - } + OperationId::Constructor(_) | OperationId::Operation(None) => Some(String::new()), + OperationId::Operation(Some(name)) => Some(format!( + "The `{}()` method\n\n{}", + name, + mdn_doc(self_name, Some(name)) + )), + OperationId::IndexingGetter => Some(format!("The indexing getter\n\n")), + OperationId::IndexingSetter => Some(format!("The indexing setter\n\n")), + OperationId::IndexingDeleter => Some(format!("The indexing deleter\n\n")), }; let attrs = data.definition_attributes; for mut method in self.create_imports(attrs, kind, id, op_data) { @@ -675,7 +676,8 @@ impl<'src> FirstPassRecord<'src> { Some(doc) => doc, None => return, }; - let mut required = extra.iter() + let mut required = extra + .iter() .map(|s| Ident::new(s, Span::call_site())) .collect::>(); item.imported_type_references(&mut |f| { @@ -684,9 +686,10 @@ impl<'src> FirstPassRecord<'src> { } }); if required.len() == 0 { - return + return; } - let list = required.iter() + let list = required + .iter() .map(|ident| format!("`{}`", ident)) .collect::>() .join(", "); @@ -714,13 +717,14 @@ impl<'src> FirstPassRecord<'src> { fields.push(ast::DictionaryField { required: false, name: rust_ident(&snake_case_ident(identifier)), - ty: idl_type::IdlType::Callback.to_syn_type(pos) - .unwrap(), + ty: idl_type::IdlType::Callback.to_syn_type(pos).unwrap(), }); } _ => { - warn!("skipping callback interface member on {}", - item.definition.identifier.0); + warn!( + "skipping callback interface member on {}", + item.definition.identifier.0 + ); } } } diff --git a/crates/webidl/src/util.rs b/crates/webidl/src/util.rs index 3043d3117..a67ef2560 100644 --- a/crates/webidl/src/util.rs +++ b/crates/webidl/src/util.rs @@ -7,10 +7,10 @@ use heck::{CamelCase, ShoutySnakeCase, SnakeCase}; use proc_macro2::{Ident, Span}; use syn; use weedle; -use weedle::attribute::{ExtendedAttributeList, ExtendedAttribute}; +use weedle::attribute::{ExtendedAttribute, ExtendedAttributeList}; use weedle::literal::{ConstValue, FloatLit, IntegerLit}; -use first_pass::{FirstPassRecord, OperationId, OperationData, Signature}; +use first_pass::{FirstPassRecord, OperationData, OperationId, Signature}; use idl_type::{IdlType, ToIdlType}; /// For variadic operations an overload with a `js_sys::Array` argument is generated alongside with @@ -24,7 +24,11 @@ pub(crate) fn shared_ref(ty: syn::Type, mutable: bool) -> syn::Type { syn::TypeReference { and_token: Default::default(), lifetime: None, - mutability: if mutable { Some(syn::token::Mut::default()) } else { None }, + mutability: if mutable { + Some(syn::token::Mut::default()) + } else { + None + }, elem: Box::new(ty), }.into() } @@ -66,30 +70,25 @@ pub fn mdn_doc(class: &str, method: Option<&str>) -> String { pub(crate) fn array(base_ty: &str, pos: TypePosition) -> syn::Type { match pos { TypePosition::Argument => { - shared_ref(slice_ty(ident_ty(raw_ident(base_ty))), /*mutable =*/ true) - } - TypePosition::Return => { - vec_ty(ident_ty(raw_ident(base_ty))) + shared_ref( + slice_ty(ident_ty(raw_ident(base_ty))), + /*mutable =*/ true, + ) } + TypePosition::Return => vec_ty(ident_ty(raw_ident(base_ty))), } } /// Map a webidl const value to the correct wasm-bindgen const value pub fn webidl_const_v_to_backend_const_v(v: &ConstValue) -> backend::ast::ConstValue { - use std::f64::{NEG_INFINITY, INFINITY, NAN}; use backend::ast; + use std::f64::{INFINITY, NAN, NEG_INFINITY}; match *v { ConstValue::Boolean(b) => ast::ConstValue::BooleanLiteral(b.0), - ConstValue::Float(FloatLit::NegInfinity(_)) => { - ast::ConstValue::FloatLiteral(NEG_INFINITY) - } - ConstValue::Float(FloatLit::Infinity(_)) => { - ast::ConstValue::FloatLiteral(INFINITY) - } - ConstValue::Float(FloatLit::NaN(_)) => { - ast::ConstValue::FloatLiteral(NAN) - } + ConstValue::Float(FloatLit::NegInfinity(_)) => ast::ConstValue::FloatLiteral(NEG_INFINITY), + ConstValue::Float(FloatLit::Infinity(_)) => ast::ConstValue::FloatLiteral(INFINITY), + ConstValue::Float(FloatLit::NaN(_)) => ast::ConstValue::FloatLiteral(NAN), ConstValue::Float(FloatLit::Value(s)) => { ast::ConstValue::FloatLiteral(s.0.parse().unwrap()) } @@ -101,7 +100,7 @@ pub fn webidl_const_v_to_backend_const_v(v: &ConstValue) -> backend::ast::ConstV (false, orig_text) }; if text == "0" { - return ast::ConstValue::SignedIntegerLiteral(0) + return ast::ConstValue::SignedIntegerLiteral(0); } let text = &text[offset..]; let n = u64::from_str_radix(text, base) @@ -119,7 +118,7 @@ pub fn webidl_const_v_to_backend_const_v(v: &ConstValue) -> backend::ast::ConstV }; match lit { IntegerLit::Hex(h) => mklit(h.0, 16, 2), // leading 0x - IntegerLit::Oct(h) => mklit(h.0, 8, 1), // leading 0 + IntegerLit::Oct(h) => mklit(h.0, 8, 1), // leading 0 IntegerLit::Dec(h) => mklit(h.0, 10, 0), } } @@ -183,9 +182,7 @@ pub(crate) fn vec_ty(t: syn::Type) -> syn::Type { let arguments = syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { colon2_token: None, lt_token: Default::default(), - args: FromIterator::from_iter(vec![ - syn::GenericArgument::Type(t), - ]), + args: FromIterator::from_iter(vec![syn::GenericArgument::Type(t)]), gt_token: Default::default(), }); @@ -231,7 +228,10 @@ impl<'src> FirstPassRecord<'src> { catch: bool, variadic: bool, doc_comment: Option, - ) -> Option where 'src: 'a { + ) -> Option + where + 'src: 'a, + { // Convert all of the arguments from their IDL type to a `syn` type, // ready to pass to the backend. // @@ -239,15 +239,18 @@ impl<'src> FirstPassRecord<'src> { // but this type isn't actually used so it's just here for show mostly. let mut arguments = if let &backend::ast::ImportFunctionKind::Method { ref ty, - kind: backend::ast::MethodKind::Operation( - backend::ast::Operation { + kind: + backend::ast::MethodKind::Operation(backend::ast::Operation { is_static: false, .. - } - ), + }), .. - } = &kind { + } = &kind + { let mut res = Vec::with_capacity(idl_arguments.size_hint().0 + 1); - res.push(simple_fn_arg(raw_ident("self_"), shared_ref(ty.clone(), false))); + res.push(simple_fn_arg( + raw_ident("self_"), + shared_ref(ty.clone(), false), + )); res } else { Vec::with_capacity(idl_arguments.size_hint().0) @@ -260,10 +263,9 @@ impl<'src> FirstPassRecord<'src> { None => { warn!( "Unsupported argument type: {:?} on {:?}", - idl_type, - rust_name + idl_type, rust_name ); - return None + return None; } }; let syn_type = if variadic && i == arguments_count - 1 { @@ -280,17 +282,11 @@ impl<'src> FirstPassRecord<'src> { // attribute here to use a `Result` in Rust. let ret = match ret { IdlType::Void => None, - ret @ _ => { - match ret.to_syn_type(TypePosition::Return) { - Some(ret) => Some(ret), - None => { - warn!( - "Unsupported return type: {:?} on {:?}", - ret, - rust_name - ); - return None - } + ret @ _ => match ret.to_syn_type(TypePosition::Return) { + Some(ret) => Some(ret), + None => { + warn!("Unsupported return type: {:?} on {:?}", ret, rust_name); + return None; } }, }; @@ -350,7 +346,11 @@ impl<'src> FirstPassRecord<'src> { is_structural(attrs.as_ref(), container_attrs), throws(attrs), false, - Some(format!("The `{}` getter\n\n{}", name, mdn_doc(self_name, Some(name)))), + Some(format!( + "The `{}` getter\n\n{}", + name, + mdn_doc(self_name, Some(name)) + )), ) } @@ -376,7 +376,11 @@ impl<'src> FirstPassRecord<'src> { is_structural(attrs.as_ref(), container_attrs), throws(attrs), false, - Some(format!("The `{}` setter\n\n{}", name, mdn_doc(self_name, Some(name)))), + Some(format!( + "The `{}` setter\n\n{}", + name, + mdn_doc(self_name, Some(name)) + )), ) } @@ -404,9 +408,7 @@ impl<'src> FirstPassRecord<'src> { kind: backend::ast::ImportFunctionKind, id: &OperationId<'src>, data: &OperationData<'src>, - ) - -> Vec - { + ) -> Vec { // First up, prune all signatures that reference unsupported arguments. // We won't consider these until said arguments are implemented. // @@ -416,14 +418,12 @@ impl<'src> FirstPassRecord<'src> { // signature where that and all remaining optional arguments are // undefined. let mut signatures = Vec::new(); - 'outer: - for signature in data.signatures.iter() { + 'outer: for signature in data.signatures.iter() { let mut idl_args = Vec::with_capacity(signature.args.len()); for (i, arg) in signature.args.iter().enumerate() { if arg.optional { assert!( - signature - .args[i..] + signature.args[i..] .iter() .all(|arg| arg.optional || arg.variadic), "Not optional or variadic argument after optional argument: {:?}", @@ -503,7 +503,7 @@ impl<'src> FirstPassRecord<'src> { OperationId::Operation(Some(s)) => (*s, false, false), OperationId::Operation(None) => { warn!("unsupported unnamed operation"); - return Vec::new() + return Vec::new(); } OperationId::IndexingGetter => ("get", true, false), OperationId::IndexingSetter => ("set", true, false), @@ -551,7 +551,7 @@ impl<'src> FirstPassRecord<'src> { // then there's nothing to disambiguate so we don't modify the // name. if !any_different { - continue + continue; } if first { rust_name.push_str("_with_"); @@ -574,46 +574,58 @@ impl<'src> FirstPassRecord<'src> { rust_name.push_str(&snake_case_ident(arg_name)); } } - let structural = force_structural || is_structural(signature.orig.attrs.as_ref(), container_attrs); + let structural = + force_structural || is_structural(signature.orig.attrs.as_ref(), container_attrs); let catch = force_throws || throws(&signature.orig.attrs); - let variadic = signature.args.len() == signature.orig.args.len() - && signature.orig.args.last().map(|arg| arg.variadic).unwrap_or(false); - ret.extend(self.create_one_function( - name, - &rust_name, - signature.args.iter() - .zip(&signature.orig.args) - .map(|(idl_type, orig_arg)| (orig_arg.name, idl_type)), - &ret_ty, - kind.clone(), - structural, - catch, - variadic, - None, - )); + let variadic = signature.args.len() == signature.orig.args.len() && signature + .orig + .args + .last() + .map(|arg| arg.variadic) + .unwrap_or(false); + ret.extend( + self.create_one_function( + name, + &rust_name, + signature + .args + .iter() + .zip(&signature.orig.args) + .map(|(idl_type, orig_arg)| (orig_arg.name, idl_type)), + &ret_ty, + kind.clone(), + structural, + catch, + variadic, + None, + ), + ); if !variadic { continue; } let last_idl_type = &signature.args[signature.args.len() - 1]; let last_name = signature.orig.args[signature.args.len() - 1].name; for i in 0..=MAX_VARIADIC_ARGUMENTS_COUNT { - ret.extend(self.create_one_function( - name, - &format!("{}_{}", rust_name, i), - signature.args[..signature.args.len() - 1].iter() - .zip(&signature.orig.args) - .map(|(idl_type, orig_arg)| (orig_arg.name.to_string(), idl_type)) - .chain((1..=i).map(|j| (format!("{}_{}", last_name, j), last_idl_type))) - .collect::>() - .iter() - .map(|(name, idl_type)| (&name[..], idl_type.clone())), - &ret_ty, - kind.clone(), - structural, - catch, - false, - None, - )); + ret.extend( + self.create_one_function( + name, + &format!("{}_{}", rust_name, i), + signature.args[..signature.args.len() - 1] + .iter() + .zip(&signature.orig.args) + .map(|(idl_type, orig_arg)| (orig_arg.name.to_string(), idl_type)) + .chain((1..=i).map(|j| (format!("{}_{}", last_name, j), last_idl_type))) + .collect::>() + .iter() + .map(|(name, idl_type)| (&name[..], idl_type.clone())), + &ret_ty, + kind.clone(), + structural, + catch, + false, + None, + ), + ); } } return ret; @@ -659,9 +671,9 @@ pub fn is_structural( item_attrs: Option<&ExtendedAttributeList>, container_attrs: Option<&ExtendedAttributeList>, ) -> bool { - has_named_attribute(item_attrs, "Unforgeable") || - has_named_attribute(container_attrs, "Unforgeable") || - has_ident_attribute(container_attrs, "Global") + has_named_attribute(item_attrs, "Unforgeable") + || has_named_attribute(container_attrs, "Unforgeable") + || has_ident_attribute(container_attrs, "Global") } /// Whether a webidl object is marked as throwing. diff --git a/examples/canvas/src/lib.rs b/examples/canvas/src/lib.rs index 5396975c0..3e31f1baa 100755 --- a/examples/canvas/src/lib.rs +++ b/examples/canvas/src/lib.rs @@ -25,43 +25,25 @@ pub fn draw() { context.begin_path(); // Draw the outer circle. - context.arc( - 75.0, - 75.0, - 50.0, - 0.0, - f64::consts::PI * 2.0, - ).unwrap(); + 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( - 75.0, - 75.0, - 35.0, - 0.0, - f64::consts::PI, - ).unwrap(); + 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( - 60.0, - 65.0, - 5.0, - 0.0, - f64::consts::PI * 2.0, - ).unwrap(); + 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( - 90.0, - 65.0, - 5.0, - 0.0, - f64::consts::PI * 2.0, - ).unwrap(); + context + .arc(90.0, 65.0, 5.0, 0.0, f64::consts::PI * 2.0) + .unwrap(); context.stroke(); } diff --git a/examples/closures/src/lib.rs b/examples/closures/src/lib.rs index 09d0db80d..a12d7b523 100755 --- a/examples/closures/src/lib.rs +++ b/examples/closures/src/lib.rs @@ -1,10 +1,10 @@ -extern crate wasm_bindgen; extern crate js_sys; +extern crate wasm_bindgen; extern crate web_sys; -use js_sys::{Date, Array}; -use wasm_bindgen::JsCast; +use js_sys::{Array, Date}; use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; use web_sys::{Document, Element, HtmlElement, Window}; #[wasm_bindgen] @@ -18,15 +18,13 @@ pub fn run() -> Result<(), JsValue> { array.push(&"Hello".into()); array.push(&1.into()); let mut first_item = None; - array.for_each(&mut |obj, idx, _arr| { - match idx { - 0 => { - assert_eq!(obj, "Hello"); - first_item = obj.as_string(); - } - 1 => assert_eq!(obj, 1), - _ => panic!("unknown index: {}", idx) + array.for_each(&mut |obj, idx, _arr| match idx { + 0 => { + assert_eq!(obj, "Hello"); + first_item = obj.as_string(); } + 1 => assert_eq!(obj, 1), + _ => panic!("unknown index: {}", idx), }); assert_eq!(first_item, Some("Hello".to_string())); @@ -69,18 +67,13 @@ fn setup_clock(window: &Window, document: &Document) -> Result<(), JsValue> { .get_element_by_id("current-time") .expect("should have #current-time on the page"); update_time(¤t_time); - let a = Closure::wrap(Box::new(move || { - update_time(¤t_time) - }) as Box); - window.set_interval_with_callback_and_timeout_and_arguments_0( - a.as_ref().unchecked_ref(), - 1000, - )?; + let a = Closure::wrap(Box::new(move || update_time(¤t_time)) as Box); + window + .set_interval_with_callback_and_timeout_and_arguments_0(a.as_ref().unchecked_ref(), 1000)?; fn update_time(current_time: &Element) { - current_time - .set_inner_html(&String::from( - Date::new_0().to_locale_string("en-GB", &JsValue::undefined()), - )); + current_time.set_inner_html(&String::from( + Date::new_0().to_locale_string("en-GB", &JsValue::undefined()), + )); } // The instances of `Closure` that we created will invalidate their diff --git a/examples/duck-typed-interfaces/src/lib.rs b/examples/duck-typed-interfaces/src/lib.rs index dfb6adb82..0e1140f67 100755 --- a/examples/duck-typed-interfaces/src/lib.rs +++ b/examples/duck-typed-interfaces/src/lib.rs @@ -8,7 +8,7 @@ use wasm_bindgen::prelude::*; /// `JsCast::is_instance_of` (i.e. the `instanceof` operator) will fail because /// there is no JS class named `Quacks`. #[wasm_bindgen] -extern { +extern "C" { pub type Quacks; #[wasm_bindgen(structural, method)] diff --git a/examples/fetch/src/lib.rs b/examples/fetch/src/lib.rs index 02d851b16..eb16781d5 100644 --- a/examples/fetch/src/lib.rs +++ b/examples/fetch/src/lib.rs @@ -53,7 +53,8 @@ pub fn run() -> Promise { &opts, ).unwrap(); - request.headers() + request + .headers() .set("Accept", "application/vnd.github.v3+json") .unwrap(); diff --git a/examples/guide-supported-types-examples/src/imported_types.rs b/examples/guide-supported-types-examples/src/imported_types.rs index 22578ca50..ed5674a67 100644 --- a/examples/guide-supported-types-examples/src/imported_types.rs +++ b/examples/guide-supported-types-examples/src/imported_types.rs @@ -1,15 +1,19 @@ use wasm_bindgen::prelude::*; #[wasm_bindgen] -extern { +extern "C" { pub type SomeJsType; } #[wasm_bindgen] -pub fn imported_type_by_value(x: SomeJsType) { /* ... */ } +pub fn imported_type_by_value(x: SomeJsType) { + /* ... */ +} #[wasm_bindgen] -pub fn imported_type_by_shared_ref(x: &SomeJsType) { /* ... */ } +pub fn imported_type_by_shared_ref(x: &SomeJsType) { + /* ... */ +} #[wasm_bindgen] pub fn return_imported_type() -> SomeJsType { @@ -17,7 +21,9 @@ pub fn return_imported_type() -> SomeJsType { } #[wasm_bindgen] -pub fn take_option_imported_type(x: Option) { /* ... */ } +pub fn take_option_imported_type(x: Option) { + /* ... */ +} #[wasm_bindgen] pub fn return_option_imported_type() -> Option { diff --git a/examples/guide-supported-types-examples/src/lib.rs b/examples/guide-supported-types-examples/src/lib.rs index 13984c231..cd79099eb 100755 --- a/examples/guide-supported-types-examples/src/lib.rs +++ b/examples/guide-supported-types-examples/src/lib.rs @@ -2,15 +2,15 @@ extern crate wasm_bindgen; -pub mod imported_types; +pub mod bool; +pub mod boxed_js_value_slice; +pub mod boxed_number_slices; +pub mod char; pub mod exported_types; +pub mod imported_types; +pub mod js_value; +pub mod number_slices; +pub mod numbers; +pub mod pointers; pub mod str; pub mod string; -pub mod char; -pub mod bool; -pub mod js_value; -pub mod boxed_js_value_slice; -pub mod pointers; -pub mod numbers; -pub mod boxed_number_slices; -pub mod number_slices; diff --git a/examples/julia_set/src/lib.rs b/examples/julia_set/src/lib.rs index d5b833c9d..e0884da73 100644 --- a/examples/julia_set/src/lib.rs +++ b/examples/julia_set/src/lib.rs @@ -2,8 +2,8 @@ extern crate wasm_bindgen; extern crate web_sys; use std::ops::Add; -use wasm_bindgen::Clamped; use wasm_bindgen::prelude::*; +use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; #[wasm_bindgen] @@ -15,7 +15,7 @@ pub fn draw( imaginary: f64, ) -> Result<(), JsValue> { // The real workhorse of this algorithm, generating pixel data - let c = Complex { real, imaginary, }; + let c = Complex { real, imaginary }; let mut data = get_julia_set(width, height, c); let data = ImageData::new_with_u8_clamped_array_and_sh(Clamped(&mut data), width, height)?; ctx.put_image_data(&data, 0.0, 0.0) @@ -50,7 +50,7 @@ fn get_iter_index(z: Complex, c: Complex) -> u32 { let mut z = z; while iter_index < 900 { if z.norm() > 2.0 { - break + break; } z = z.square() + c; iter_index += 1; diff --git a/examples/performance/src/lib.rs b/examples/performance/src/lib.rs index cd3c289f1..0dad2a6b0 100644 --- a/examples/performance/src/lib.rs +++ b/examples/performance/src/lib.rs @@ -21,7 +21,9 @@ macro_rules! console_log { #[wasm_bindgen] pub fn run() { let window = web_sys::window().expect("should have a window in this context"); - let performance = window.performance().expect("performance should be available"); + let performance = window + .performance() + .expect("performance should be available"); console_log!("the current time (in ms) is {}", performance.now()); diff --git a/src/convert/closures.rs b/src/convert/closures.rs index 3cc0ef1cb..7a2a0636a 100644 --- a/src/convert/closures.rs +++ b/src/convert/closures.rs @@ -1,6 +1,6 @@ use core::mem; -use convert::{FromWasmAbi, IntoWasmAbi, GlobalStack, Stack, ReturnWasmAbi}; +use convert::{FromWasmAbi, GlobalStack, IntoWasmAbi, ReturnWasmAbi, Stack}; use throw_str; macro_rules! stack_closures { @@ -91,4 +91,3 @@ stack_closures! { (A B C D E F) (A B C D E F G) } - diff --git a/src/convert/impls.rs b/src/convert/impls.rs index 539b6a897..2267a9f58 100644 --- a/src/convert/impls.rs +++ b/src/convert/impls.rs @@ -1,10 +1,10 @@ use core::char; use core::mem::{self, ManuallyDrop}; -use convert::{Stack, FromWasmAbi, IntoWasmAbi, RefFromWasmAbi}; -use convert::{OptionIntoWasmAbi, OptionFromWasmAbi, ReturnWasmAbi}; use convert::traits::WasmAbi; -use {JsValue, Clamped}; +use convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi, Stack}; +use convert::{OptionFromWasmAbi, OptionIntoWasmAbi, ReturnWasmAbi}; +use {Clamped, JsValue}; unsafe impl WasmAbi for () {} @@ -224,12 +224,16 @@ impl FromWasmAbi for bool { impl OptionIntoWasmAbi for bool { #[inline] - fn none() -> u32 { 0xFFFFFFu32 } + fn none() -> u32 { + 0xFFFFFFu32 + } } impl OptionFromWasmAbi for bool { #[inline] - fn is_none(js: &u32) -> bool { *js == 0xFFFFFFu32 } + fn is_none(js: &u32) -> bool { + *js == 0xFFFFFFu32 + } } impl IntoWasmAbi for char { diff --git a/src/convert/mod.rs b/src/convert/mod.rs index 0163293c9..60df8c581 100644 --- a/src/convert/mod.rs +++ b/src/convert/mod.rs @@ -1,10 +1,10 @@ //! This is mostly an internal module, no stability guarantees are provided. Use //! at your own risk. -mod traits; +mod closures; mod impls; mod slices; -mod closures; +mod traits; pub use self::slices::WasmSlice; pub use self::traits::*; @@ -23,10 +23,7 @@ impl GlobalStack { impl Stack for GlobalStack { #[inline] fn push(&mut self, val: u32) { - use __rt::{ - __wbindgen_global_argument_ptr as global_ptr, - GLOBAL_STACK_CAP, - }; + use __rt::{__wbindgen_global_argument_ptr as global_ptr, GLOBAL_STACK_CAP}; unsafe { assert!(self.next < GLOBAL_STACK_CAP); *global_ptr().offset(self.next as isize) = val; diff --git a/src/convert/slices.rs b/src/convert/slices.rs index 59276ae6e..0dcf94026 100644 --- a/src/convert/slices.rs +++ b/src/convert/slices.rs @@ -4,8 +4,8 @@ use std::prelude::v1::*; use core::slice; use core::str; -use convert::{WasmAbi, IntoWasmAbi, FromWasmAbi, RefFromWasmAbi, RefMutFromWasmAbi}; -use convert::{Stack, OptionIntoWasmAbi}; +use convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi, RefMutFromWasmAbi, WasmAbi}; +use convert::{OptionIntoWasmAbi, Stack}; if_std! { use core::mem; @@ -188,7 +188,9 @@ impl<'a> IntoWasmAbi for &'a str { } impl<'a> OptionIntoWasmAbi for &'a str { - fn none() -> WasmSlice { null_slice() } + fn none() -> WasmSlice { + null_slice() + } } impl RefFromWasmAbi for str { diff --git a/src/describe.rs b/src/describe.rs index 7b2e64737..d4c53f87a 100644 --- a/src/describe.rs +++ b/src/describe.rs @@ -3,7 +3,7 @@ #![doc(hidden)] -use {JsValue, Clamped}; +use {Clamped, JsValue}; macro_rules! tys { ($($a:ident)*) => (tys! { @ ($($a)*) 0 }); @@ -134,14 +134,30 @@ if_std! { } macro_rules! cnt { - () => (0); - (A) => (1); - (A B) => (2); - (A B C) => (3); - (A B C D) => (4); - (A B C D E) => (5); - (A B C D E F) => (6); - (A B C D E F G) => (7); + () => { + 0 + }; + (A) => { + 1 + }; + (A B) => { + 2 + }; + (A B C) => { + 3 + }; + (A B C D) => { + 4 + }; + (A B C D E) => { + 5 + }; + (A B C D E F) => { + 6 + }; + (A B C D E F G) => { + 7 + }; } macro_rules! doit { diff --git a/src/lib.rs b/src/lib.rs index 324f4edcc..3b938dfa1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -351,13 +351,19 @@ impl From for JsValue { } } -impl<'a, T> From<&'a T> for JsValue where T: JsCast { +impl<'a, T> From<&'a T> for JsValue +where + T: JsCast, +{ fn from(s: &'a T) -> JsValue { s.as_ref().clone() } } -impl From> for JsValue where JsValue: From { +impl From> for JsValue +where + JsValue: From, +{ fn from(s: Option) -> JsValue { match s { Some(s) => s.into(), @@ -368,13 +374,21 @@ impl From> for JsValue where JsValue: From { impl JsCast for JsValue { // everything is a `JsValue`! - fn instanceof(_val: &JsValue) -> bool { true } - fn unchecked_from_js(val: JsValue) -> Self { val } - fn unchecked_from_js_ref(val: &JsValue) -> &Self { val } + fn instanceof(_val: &JsValue) -> bool { + true + } + fn unchecked_from_js(val: JsValue) -> Self { + val + } + fn unchecked_from_js_ref(val: &JsValue) -> &Self { + val + } } impl AsRef for JsValue { - fn as_ref(&self) -> &JsValue { self } + fn as_ref(&self) -> &JsValue { + self + } } macro_rules! numbers { @@ -562,7 +576,6 @@ pub fn throw(s: &str) -> ! { throw_str(s) } - /// Throws a JS exception. /// /// This function will throw a JS exception with the message provided. The @@ -604,7 +617,9 @@ pub fn throw_val(s: JsValue) -> ! { /// Returns a handle to this wasm instance's `WebAssembly.Memory` pub fn memory() -> JsValue { unsafe { - JsValue { idx: __wbindgen_memory() } + JsValue { + idx: __wbindgen_memory(), + } } } @@ -847,8 +862,7 @@ pub mod __rt { /// in the object file and link the intrinsics. /// /// Ideas for how to improve this are most welcome! - pub fn link_mem_intrinsics() { - } + pub fn link_mem_intrinsics() {} } /// A wrapper type around slices and vectors for binding the `Uint8ClampedArray` diff --git a/tests/crates/a/src/lib.rs b/tests/crates/a/src/lib.rs index d39f7eeec..55e6417d7 100644 --- a/tests/crates/a/src/lib.rs +++ b/tests/crates/a/src/lib.rs @@ -3,7 +3,7 @@ extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "tests/wasm/duplicate_deps.js")] -extern { +extern "C" { fn foo(); } diff --git a/tests/crates/b/src/lib.rs b/tests/crates/b/src/lib.rs index c7876ed4e..f6c993815 100644 --- a/tests/crates/b/src/lib.rs +++ b/tests/crates/b/src/lib.rs @@ -3,7 +3,7 @@ extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "tests/wasm/duplicate_deps.js")] -extern { +extern "C" { fn foo(x: u32); } diff --git a/tests/headless.rs b/tests/headless.rs index 6cb1449a2..2fcf66ce9 100644 --- a/tests/headless.rs +++ b/tests/headless.rs @@ -1,10 +1,10 @@ #![cfg(target_arch = "wasm32")] -extern crate wasm_bindgen_test; extern crate wasm_bindgen; +extern crate wasm_bindgen_test; -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); @@ -17,7 +17,9 @@ impl ConsumeRetString { // // This used to cause two `const ptr = ...` declarations, which is invalid // JS. - pub fn consume(self) -> String { String::new() } + pub fn consume(self) -> String { + String::new() + } } #[wasm_bindgen_test] diff --git a/tests/no-std/test.rs b/tests/no-std/test.rs index a8e04ac88..c548f9ee8 100644 --- a/tests/no-std/test.rs +++ b/tests/no-std/test.rs @@ -7,8 +7,8 @@ #![no_std] #![allow(dead_code)] -extern crate wasm_bindgen; extern crate std as _some_other_name; +extern crate wasm_bindgen; use wasm_bindgen::prelude::*; @@ -16,7 +16,7 @@ use wasm_bindgen::prelude::*; pub fn foo(_a: u32) {} #[wasm_bindgen] -extern { +extern "C" { fn test(a: &str); type Js; diff --git a/tests/non_wasm.rs b/tests/non_wasm.rs index 947dcf192..00c2a3961 100644 --- a/tests/non_wasm.rs +++ b/tests/non_wasm.rs @@ -29,7 +29,7 @@ pub fn foo(x: bool) { } #[wasm_bindgen] -extern { +extern "C" { fn some_import(); static A: JsValue; } @@ -41,8 +41,7 @@ pub fn bar(_: &str) -> JsValue { } #[wasm_bindgen] -pub fn baz(_: JsValue) { -} +pub fn baz(_: JsValue) {} #[test] fn test_foo() { diff --git a/tests/std-crate-no-std-dep.rs b/tests/std-crate-no-std-dep.rs index e2b25037b..bc09e4a63 100644 --- a/tests/std-crate-no-std-dep.rs +++ b/tests/std-crate-no-std-dep.rs @@ -9,7 +9,7 @@ extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] -extern { +extern "C" { fn test(a: &str); type Js; diff --git a/tests/wasm/api.rs b/tests/wasm/api.rs index 6b28d40d1..e7d951333 100644 --- a/tests/wasm/api.rs +++ b/tests/wasm/api.rs @@ -1,10 +1,10 @@ +use js_sys::{Uint8Array, WebAssembly}; +use wasm_bindgen::prelude::*; use wasm_bindgen::{self, JsCast}; use wasm_bindgen_test::*; -use wasm_bindgen::prelude::*; -use js_sys::{WebAssembly, Uint8Array}; #[wasm_bindgen(module = "tests/wasm/api.js")] -extern { +extern "C" { fn js_works(); fn js_eq_works(); fn assert_null(v: JsValue); @@ -47,11 +47,7 @@ pub fn api_js_undefined() -> JsValue { } #[wasm_bindgen] -pub fn api_test_is_null_undefined( - a: &JsValue, - b: &JsValue, - c: &JsValue, -) { +pub fn api_test_is_null_undefined(a: &JsValue, b: &JsValue, c: &JsValue) { assert!(a.is_null()); assert!(!a.is_undefined()); @@ -73,11 +69,7 @@ pub fn api_get_false() -> JsValue { } #[wasm_bindgen] -pub fn api_test_bool( - a: &JsValue, - b: &JsValue, - c: &JsValue, -) { +pub fn api_test_bool(a: &JsValue, b: &JsValue, c: &JsValue) { assert_eq!(a.as_bool(), Some(true)); assert_eq!(format!("{:?}", a), "true"); assert_eq!(b.as_bool(), Some(false)); @@ -148,6 +140,8 @@ fn memory_accessor_appears_to_work() { let buf = mem.buffer(); let slice = Uint8Array::new(&buf); let mut v = Vec::new(); - slice.subarray(ptr, ptr + 4).for_each(&mut |val, _, _| v.push(val)); + slice + .subarray(ptr, ptr + 4) + .for_each(&mut |val, _, _| v.push(val)); assert_eq!(v, [3, 0, 0, 0]); } diff --git a/tests/wasm/char.rs b/tests/wasm/char.rs index 6d2ef325d..f852b8d81 100644 --- a/tests/wasm/char.rs +++ b/tests/wasm/char.rs @@ -1,29 +1,41 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/char.js")] -extern { +extern "C" { fn js_identity(c: char) -> char; fn js_works(); } #[wasm_bindgen] -pub fn rust_identity(c: char) -> char { c } +pub fn rust_identity(c: char) -> char { + c +} #[wasm_bindgen] -pub fn rust_js_identity(c: char) -> char { js_identity(c) } +pub fn rust_js_identity(c: char) -> char { + js_identity(c) +} #[wasm_bindgen] -pub fn letter() -> char { 'a' } +pub fn letter() -> char { + 'a' +} #[wasm_bindgen] -pub fn face() -> char { '😀' } +pub fn face() -> char { + '😀' +} #[wasm_bindgen] -pub fn rust_letter(a: char) { assert_eq!(a, 'a'); } +pub fn rust_letter(a: char) { + assert_eq!(a, 'a'); +} #[wasm_bindgen] -pub fn rust_face(p: char) { assert_eq!(p, '😀'); } +pub fn rust_face(p: char) { + assert_eq!(p, '😀'); +} #[wasm_bindgen_test] fn works() { diff --git a/tests/wasm/classes.rs b/tests/wasm/classes.rs index 2c58c6095..b61fb30a3 100644 --- a/tests/wasm/classes.rs +++ b/tests/wasm/classes.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/classes.js")] -extern { +extern "C" { fn js_simple(); fn js_strings(); fn js_exceptions(); @@ -76,7 +76,9 @@ impl ClassesStrings1 { } pub fn bar(&self, mix: &str) -> ClassesStrings2 { - ClassesStrings2 { contents: format!("foo-{}-{}", mix, self.name) } + ClassesStrings2 { + contents: format!("foo-{}-{}", mix, self.name), + } } } @@ -242,7 +244,9 @@ pub struct OtherEmpty {} #[wasm_bindgen] impl OtherEmpty { - pub fn return_a_value() -> MissingClass { MissingClass {} } + pub fn return_a_value() -> MissingClass { + MissingClass {} + } } #[wasm_bindgen_test] diff --git a/tests/wasm/closures.rs b/tests/wasm/closures.rs index 0b896a7ed..fd62baf89 100644 --- a/tests/wasm/closures.rs +++ b/tests/wasm/closures.rs @@ -1,12 +1,12 @@ #![cfg(feature = "nightly")] -use wasm_bindgen_test::*; -use wasm_bindgen::prelude::*; use std::cell::Cell; use std::rc::Rc; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/closures.js")] -extern { +extern "C" { fn works_call(a: &Fn()); fn works_thread(a: &Fn(u32) -> u32) -> u32; @@ -121,18 +121,12 @@ fn many_arity() { many_arity_stack2(&(|a| assert_eq!(a, 1))); many_arity_stack3(&(|a, b| assert_eq!((a, b), (1, 2)))); many_arity_stack4(&(|a, b, c| assert_eq!((a, b, c), (1, 2, 3)))); - many_arity_stack5(&(|a, b, c, d| { - assert_eq!((a, b, c, d), (1, 2, 3, 4)) - })); - many_arity_stack6(&(|a, b, c, d, e| { - assert_eq!((a, b, c, d, e), (1, 2, 3, 4, 5)) - })); - many_arity_stack7(&(|a, b, c, d, e, f| { - assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6)) - })); - many_arity_stack8(&(|a, b, c, d, e, f, g| { - assert_eq!((a, b, c, d, e, f, g), (1, 2, 3, 4, 5, 6, 7)) - })); + many_arity_stack5(&(|a, b, c, d| assert_eq!((a, b, c, d), (1, 2, 3, 4)))); + many_arity_stack6(&(|a, b, c, d, e| assert_eq!((a, b, c, d, e), (1, 2, 3, 4, 5)))); + many_arity_stack7(&(|a, b, c, d, e, f| assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6)))); + many_arity_stack8( + &(|a, b, c, d, e, f, g| assert_eq!((a, b, c, d, e, f, g), (1, 2, 3, 4, 5, 6, 7))), + ); } #[wasm_bindgen_test] @@ -164,10 +158,13 @@ fn fnmut() { assert!(a); let mut x = false; - assert_eq!(fnmut_thread(&mut |a| { - x = true; - a + 1 - }), 3); + assert_eq!( + fnmut_thread(&mut |a| { + x = true; + a + 1 + }), + 3 + ); assert!(x); } diff --git a/tests/wasm/comments.rs b/tests/wasm/comments.rs index d592ad51c..65b9d7d43 100644 --- a/tests/wasm/comments.rs +++ b/tests/wasm/comments.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/comments.js")] -extern { +extern "C" { fn assert_comments_exist(); } @@ -17,7 +17,7 @@ pub fn annotated() -> String { pub struct Annotated { a: String, /// annotated struct field - pub b: u32 + pub b: u32, } #[wasm_bindgen] diff --git a/tests/wasm/duplicate_deps.rs b/tests/wasm/duplicate_deps.rs index 0a4513017..4d3506b90 100644 --- a/tests/wasm/duplicate_deps.rs +++ b/tests/wasm/duplicate_deps.rs @@ -4,7 +4,7 @@ use wasm_bindgen_test_crate_a as a; use wasm_bindgen_test_crate_b as b; #[wasm_bindgen(module = "tests/wasm/duplicate_deps.js")] -extern { +extern "C" { fn assert_next_undefined(); fn assert_next_ten(); } diff --git a/tests/wasm/duplicates.rs b/tests/wasm/duplicates.rs index 60b17c823..206fede71 100644 --- a/tests/wasm/duplicates.rs +++ b/tests/wasm/duplicates.rs @@ -4,7 +4,7 @@ pub mod same_function_different_locations_a { use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "tests/wasm/duplicates_a.js")] - extern { + extern "C" { pub fn foo(); pub static bar: JsValue; } @@ -14,7 +14,7 @@ pub mod same_function_different_locations_b { use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "tests/wasm/duplicates_a.js")] - extern { + extern "C" { pub fn foo(); pub static bar: JsValue; } @@ -32,7 +32,7 @@ pub mod same_function_different_modules_a { use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "tests/wasm/duplicates_b.js")] - extern { + extern "C" { pub fn foo() -> bool; pub static bar: JsValue; } @@ -42,7 +42,7 @@ pub mod same_function_different_modules_b { use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "tests/wasm/duplicates_c.js")] - extern { + extern "C" { pub fn foo() -> bool; pub static bar: JsValue; } diff --git a/tests/wasm/enums.rs b/tests/wasm/enums.rs index 4c1ad2dcd..c51d60b5f 100644 --- a/tests/wasm/enums.rs +++ b/tests/wasm/enums.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; -use wasm_bindgen::prelude::*; use self::inner::ColorWithCustomValues; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/enums.js")] -extern { +extern "C" { fn js_c_style_enum(); fn js_c_style_enum_with_custom_values(); } diff --git a/tests/wasm/import_class.rs b/tests/wasm/import_class.rs index d0ae1f21e..60b5181ca 100644 --- a/tests/wasm/import_class.rs +++ b/tests/wasm/import_class.rs @@ -2,11 +2,11 @@ #![deny(missing_docs)] // test that documenting public bindings is enough -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/import_class.js")] -extern { +extern "C" { fn math_log(f: f64) -> f64; #[wasm_bindgen(js_namespace = StaticFunction)] @@ -87,7 +87,7 @@ extern { } #[wasm_bindgen] -extern { +extern "C" { #[wasm_bindgen(js_namespace = Math)] fn random() -> f64; #[wasm_bindgen(js_namespace = Math)] @@ -172,9 +172,7 @@ pub struct AssertDenyDocsWorks { /// dox #[wasm_bindgen] -pub fn assert_deny_docs_works() { -} - +pub fn assert_deny_docs_works() {} #[wasm_bindgen_test] fn options() { diff --git a/tests/wasm/imports.rs b/tests/wasm/imports.rs index 1ad9208e9..fec062812 100644 --- a/tests/wasm/imports.rs +++ b/tests/wasm/imports.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/imports.js")] -extern { +extern "C" { fn test_simple(); fn simple_foo(s: &str); @@ -53,7 +53,7 @@ extern { } #[wasm_bindgen] -extern { +extern "C" { fn parseInt(a: &str) -> u32; } @@ -161,7 +161,6 @@ impl CustomType { } } - #[wasm_bindgen_test] fn rename_with_string() { renamed_with_dollar_sign(); diff --git a/tests/wasm/js_objects.rs b/tests/wasm/js_objects.rs index 70b3518e4..7cf8c162a 100644 --- a/tests/wasm/js_objects.rs +++ b/tests/wasm/js_objects.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/js_objects.js")] -extern { +extern "C" { fn simple_foo(s: &JsValue); fn js_simple(); @@ -123,16 +123,17 @@ fn serde() { a: u32, } - let js = JsValue::from_serde("foo").unwrap(); assert_eq!(js.as_string(), Some("foo".to_string())); - let ret = verify_serde(JsValue::from_serde(&Foo { - a: 0, - b: "foo".to_string(), - c: None, - d: Bar { a: 1 }, - }).unwrap()); + let ret = verify_serde( + JsValue::from_serde(&Foo { + a: 0, + b: "foo".to_string(), + c: None, + d: Bar { a: 1 }, + }).unwrap(), + ); let foo = ret.into_serde::().unwrap(); assert_eq!(foo.a, 2); diff --git a/tests/wasm/jscast.rs b/tests/wasm/jscast.rs index f87199d53..e62c5deee 100644 --- a/tests/wasm/jscast.rs +++ b/tests/wasm/jscast.rs @@ -1,9 +1,9 @@ -use wasm_bindgen::JsCast; use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/jscast.js")] -extern { +extern "C" { type JsCast1; #[wasm_bindgen(constructor)] fn new() -> JsCast1; diff --git a/tests/wasm/main.rs b/tests/wasm/main.rs index 5321bf870..fcf9e3e16 100644 --- a/tests/wasm/main.rs +++ b/tests/wasm/main.rs @@ -1,8 +1,8 @@ #![cfg(target_arch = "wasm32")] extern crate js_sys; -extern crate wasm_bindgen_test; extern crate wasm_bindgen; +extern crate wasm_bindgen_test; extern crate wasm_bindgen_test_crate_a; extern crate wasm_bindgen_test_crate_b; diff --git a/tests/wasm/math.rs b/tests/wasm/math.rs index 413e8f2f5..90d3fa85e 100644 --- a/tests/wasm/math.rs +++ b/tests/wasm/math.rs @@ -1,64 +1,64 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/math.js")] -extern { +extern "C" { fn js_auto_bind_math(); } #[wasm_bindgen] pub fn math(a: f32, b: f64) -> f64 { - b.acos() + - b.asin() + - b.atan() + - b.atan2(b) + - b.cbrt() + - b.cosh() + - b.exp_m1() + - b.ln_1p() + - b.sinh() + - b.tan() + - b.tanh() + - b.hypot(b) + - b.cos() + - b.exp() + - b.exp2() + - b.mul_add(b, b) + - b.ln() + - b.log(b) + - b.log10() + - b.log2() + - b.powi(8) + - b.powf(b) + - b.round() + - b.sin() + - b.abs() + - b.signum() + - b.floor() + - b.ceil() + - b.trunc() + - b.sqrt() + - (b % (a as f64)) + - ((a.cos() + - a.exp() + - a.exp2() + - a.mul_add(a, a) + - a.ln() + - a.log(a) + - a.log10() + - a.log2() + - a.powi(8) + - a.powf(a) + - a.round() + - a.sin() + - a.abs() + - a.signum() + - a.floor() + - a.ceil() + - a.trunc() + - a.sqrt() + - (a % (b as f32))) as f64) + - (b + 2.0f64.powf(a as f64)) + b.acos() + + b.asin() + + b.atan() + + b.atan2(b) + + b.cbrt() + + b.cosh() + + b.exp_m1() + + b.ln_1p() + + b.sinh() + + b.tan() + + b.tanh() + + b.hypot(b) + + b.cos() + + b.exp() + + b.exp2() + + b.mul_add(b, b) + + b.ln() + + b.log(b) + + b.log10() + + b.log2() + + b.powi(8) + + b.powf(b) + + b.round() + + b.sin() + + b.abs() + + b.signum() + + b.floor() + + b.ceil() + + b.trunc() + + b.sqrt() + + (b % (a as f64)) + + ((a.cos() + + a.exp() + + a.exp2() + + a.mul_add(a, a) + + a.ln() + + a.log(a) + + a.log10() + + a.log2() + + a.powi(8) + + a.powf(a) + + a.round() + + a.sin() + + a.abs() + + a.signum() + + a.floor() + + a.ceil() + + a.trunc() + + a.sqrt() + + (a % (b as f32))) as f64) + + (b + 2.0f64.powf(a as f64)) } #[wasm_bindgen_test] diff --git a/tests/wasm/node.rs b/tests/wasm/node.rs index 741febfcc..742dbcfb5 100644 --- a/tests/wasm/node.rs +++ b/tests/wasm/node.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/node.js")] -extern { +extern "C" { fn test_works(); static FOO: JsValue; fn hit(); @@ -51,55 +51,55 @@ pub fn cycle(color: Color) -> Color { #[wasm_bindgen] pub fn node_math(a: f32, b: f64) -> f64 { - b.acos() + - b.asin() + - b.atan() + - b.atan2(b) + - b.cbrt() + - b.cosh() + - b.exp_m1() + - b.ln_1p() + - b.sinh() + - b.tan() + - b.tanh() + - b.hypot(b) + - b.cos() + - b.exp() + - b.exp2() + - b.mul_add(b, b) + - b.ln() + - b.log(b) + - b.log10() + - b.log2() + - b.powi(8) + - b.powf(b) + - b.round() + - b.sin() + - b.abs() + - b.signum() + - b.floor() + - b.ceil() + - b.trunc() + - b.sqrt() + - (b % (a as f64)) + - ((a.cos() + - a.exp() + - a.exp2() + - a.mul_add(a, a) + - a.ln() + - a.log(a) + - a.log10() + - a.log2() + - a.powi(8) + - a.powf(a) + - a.round() + - a.sin() + - a.abs() + - a.signum() + - a.floor() + - a.ceil() + - a.trunc() + - a.sqrt() + - (a % (b as f32))) as f64) + - (b + 2.0f64.powf(a as f64)) + b.acos() + + b.asin() + + b.atan() + + b.atan2(b) + + b.cbrt() + + b.cosh() + + b.exp_m1() + + b.ln_1p() + + b.sinh() + + b.tan() + + b.tanh() + + b.hypot(b) + + b.cos() + + b.exp() + + b.exp2() + + b.mul_add(b, b) + + b.ln() + + b.log(b) + + b.log10() + + b.log2() + + b.powi(8) + + b.powf(b) + + b.round() + + b.sin() + + b.abs() + + b.signum() + + b.floor() + + b.ceil() + + b.trunc() + + b.sqrt() + + (b % (a as f64)) + + ((a.cos() + + a.exp() + + a.exp2() + + a.mul_add(a, a) + + a.ln() + + a.log(a) + + a.log10() + + a.log2() + + a.powi(8) + + a.powf(a) + + a.round() + + a.sin() + + a.abs() + + a.signum() + + a.floor() + + a.ceil() + + a.trunc() + + a.sqrt() + + (a % (b as f32))) as f64) + + (b + 2.0f64.powf(a as f64)) } diff --git a/tests/wasm/option.rs b/tests/wasm/option.rs index 8da01e3b9..4b4cc4379 100644 --- a/tests/wasm/option.rs +++ b/tests/wasm/option.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/option.js")] -extern { +extern "C" { pub type MyType; #[wasm_bindgen(constructor)] fn new() -> MyType; diff --git a/tests/wasm/optional_primitives.rs b/tests/wasm/optional_primitives.rs index 3543a4e2f..b314ae5ce 100644 --- a/tests/wasm/optional_primitives.rs +++ b/tests/wasm/optional_primitives.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/optional_primitives.js")] -extern { +extern "C" { fn optional_i32_js_identity(a: Option) -> Option; fn optional_u32_js_identity(a: Option) -> Option; fn optional_isize_js_identity(a: Option) -> Option; @@ -22,253 +22,419 @@ extern { } #[wasm_bindgen] -pub fn optional_i32_none() -> Option { None } +pub fn optional_i32_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_i32_zero() -> Option { Some(0) } +pub fn optional_i32_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_i32_one() -> Option { Some(1) } +pub fn optional_i32_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_i32_neg_one() -> Option { Some(-1) } +pub fn optional_i32_neg_one() -> Option { + Some(-1) +} #[wasm_bindgen] -pub fn optional_i32_min() -> Option { Some(i32::min_value()) } +pub fn optional_i32_min() -> Option { + Some(i32::min_value()) +} #[wasm_bindgen] -pub fn optional_i32_max() -> Option { Some(i32::max_value()) } +pub fn optional_i32_max() -> Option { + Some(i32::max_value()) +} #[wasm_bindgen] -pub fn optional_i32_identity(a: Option) -> Option { optional_i32_js_identity(a) } +pub fn optional_i32_identity(a: Option) -> Option { + optional_i32_js_identity(a) +} #[wasm_bindgen] -pub fn optional_u32_none() -> Option { None } +pub fn optional_u32_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_u32_zero() -> Option { Some(0) } +pub fn optional_u32_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_u32_one() -> Option { Some(1) } +pub fn optional_u32_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_u32_min() -> Option { Some(u32::min_value()) } +pub fn optional_u32_min() -> Option { + Some(u32::min_value()) +} #[wasm_bindgen] -pub fn optional_u32_max() -> Option { Some(u32::max_value()) } +pub fn optional_u32_max() -> Option { + Some(u32::max_value()) +} #[wasm_bindgen] -pub fn optional_u32_identity(a: Option) -> Option { optional_u32_js_identity(a) } +pub fn optional_u32_identity(a: Option) -> Option { + optional_u32_js_identity(a) +} #[wasm_bindgen] -pub fn optional_isize_none() -> Option { None } +pub fn optional_isize_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_isize_zero() -> Option { Some(0) } +pub fn optional_isize_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_isize_one() -> Option { Some(1) } +pub fn optional_isize_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_isize_neg_one() -> Option { Some(-1) } +pub fn optional_isize_neg_one() -> Option { + Some(-1) +} #[wasm_bindgen] -pub fn optional_isize_min() -> Option { Some(isize::min_value()) } +pub fn optional_isize_min() -> Option { + Some(isize::min_value()) +} #[wasm_bindgen] -pub fn optional_isize_max() -> Option { Some(isize::max_value()) } +pub fn optional_isize_max() -> Option { + Some(isize::max_value()) +} #[wasm_bindgen] -pub fn optional_isize_identity(a: Option) -> Option { optional_isize_js_identity(a) } +pub fn optional_isize_identity(a: Option) -> Option { + optional_isize_js_identity(a) +} #[wasm_bindgen] -pub fn optional_usize_none() -> Option { None } +pub fn optional_usize_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_usize_zero() -> Option { Some(0) } +pub fn optional_usize_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_usize_one() -> Option { Some(1) } +pub fn optional_usize_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_usize_min() -> Option { Some(usize::min_value()) } +pub fn optional_usize_min() -> Option { + Some(usize::min_value()) +} #[wasm_bindgen] -pub fn optional_usize_max() -> Option { Some(usize::max_value()) } +pub fn optional_usize_max() -> Option { + Some(usize::max_value()) +} #[wasm_bindgen] -pub fn optional_usize_identity(a: Option) -> Option { optional_usize_js_identity(a) } +pub fn optional_usize_identity(a: Option) -> Option { + optional_usize_js_identity(a) +} #[wasm_bindgen] -pub fn optional_f32_none() -> Option { None } +pub fn optional_f32_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_f32_zero() -> Option { Some(0f32) } +pub fn optional_f32_zero() -> Option { + Some(0f32) +} #[wasm_bindgen] -pub fn optional_f32_one() -> Option { Some(1f32) } +pub fn optional_f32_one() -> Option { + Some(1f32) +} #[wasm_bindgen] -pub fn optional_f32_neg_one() -> Option { Some(-1f32) } +pub fn optional_f32_neg_one() -> Option { + Some(-1f32) +} #[wasm_bindgen] -pub fn optional_f32_identity(a: Option) -> Option { optional_f32_js_identity(a) } +pub fn optional_f32_identity(a: Option) -> Option { + optional_f32_js_identity(a) +} #[wasm_bindgen] -pub fn optional_f64_none() -> Option { None } +pub fn optional_f64_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_f64_zero() -> Option { Some(0f64) } +pub fn optional_f64_zero() -> Option { + Some(0f64) +} #[wasm_bindgen] -pub fn optional_f64_one() -> Option { Some(1f64) } +pub fn optional_f64_one() -> Option { + Some(1f64) +} #[wasm_bindgen] -pub fn optional_f64_neg_one() -> Option { Some(-1f64) } +pub fn optional_f64_neg_one() -> Option { + Some(-1f64) +} #[wasm_bindgen] -pub fn optional_f64_identity(a: Option) -> Option { optional_f64_js_identity(a) } +pub fn optional_f64_identity(a: Option) -> Option { + optional_f64_js_identity(a) +} #[wasm_bindgen] -pub fn optional_i8_none() -> Option { None } +pub fn optional_i8_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_i8_zero() -> Option { Some(0) } +pub fn optional_i8_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_i8_one() -> Option { Some(1) } +pub fn optional_i8_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_i8_neg_one() -> Option { Some(-1) } +pub fn optional_i8_neg_one() -> Option { + Some(-1) +} #[wasm_bindgen] -pub fn optional_i8_min() -> Option { Some(i8::min_value()) } +pub fn optional_i8_min() -> Option { + Some(i8::min_value()) +} #[wasm_bindgen] -pub fn optional_i8_max() -> Option { Some(i8::max_value()) } +pub fn optional_i8_max() -> Option { + Some(i8::max_value()) +} #[wasm_bindgen] -pub fn optional_i8_identity(a: Option) -> Option { optional_i8_js_identity(a) } +pub fn optional_i8_identity(a: Option) -> Option { + optional_i8_js_identity(a) +} #[wasm_bindgen] -pub fn optional_u8_none() -> Option { None } +pub fn optional_u8_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_u8_zero() -> Option { Some(0) } +pub fn optional_u8_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_u8_one() -> Option { Some(1) } +pub fn optional_u8_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_u8_min() -> Option { Some(u8::min_value()) } +pub fn optional_u8_min() -> Option { + Some(u8::min_value()) +} #[wasm_bindgen] -pub fn optional_u8_max() -> Option { Some(u8::max_value()) } +pub fn optional_u8_max() -> Option { + Some(u8::max_value()) +} #[wasm_bindgen] -pub fn optional_u8_identity(a: Option) -> Option { optional_u8_js_identity(a) } +pub fn optional_u8_identity(a: Option) -> Option { + optional_u8_js_identity(a) +} #[wasm_bindgen] -pub fn optional_i16_none() -> Option { None } +pub fn optional_i16_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_i16_zero() -> Option { Some(0) } +pub fn optional_i16_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_i16_one() -> Option { Some(1) } +pub fn optional_i16_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_i16_neg_one() -> Option { Some(-1) } +pub fn optional_i16_neg_one() -> Option { + Some(-1) +} #[wasm_bindgen] -pub fn optional_i16_min() -> Option { Some(i16::min_value()) } +pub fn optional_i16_min() -> Option { + Some(i16::min_value()) +} #[wasm_bindgen] -pub fn optional_i16_max() -> Option { Some(i16::max_value()) } +pub fn optional_i16_max() -> Option { + Some(i16::max_value()) +} #[wasm_bindgen] -pub fn optional_i16_identity(a: Option) -> Option { optional_i16_js_identity(a) } +pub fn optional_i16_identity(a: Option) -> Option { + optional_i16_js_identity(a) +} #[wasm_bindgen] -pub fn optional_u16_none() -> Option { None } +pub fn optional_u16_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_u16_zero() -> Option { Some(0) } +pub fn optional_u16_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_u16_one() -> Option { Some(1) } +pub fn optional_u16_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_u16_min() -> Option { Some(u16::min_value()) } +pub fn optional_u16_min() -> Option { + Some(u16::min_value()) +} #[wasm_bindgen] -pub fn optional_u16_max() -> Option { Some(u16::max_value()) } +pub fn optional_u16_max() -> Option { + Some(u16::max_value()) +} #[wasm_bindgen] -pub fn optional_u16_identity(a: Option) -> Option { optional_u16_js_identity(a) } +pub fn optional_u16_identity(a: Option) -> Option { + optional_u16_js_identity(a) +} #[wasm_bindgen] -pub fn optional_i64_none() -> Option { None } +pub fn optional_i64_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_i64_zero() -> Option { Some(0) } +pub fn optional_i64_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_i64_one() -> Option { Some(1) } +pub fn optional_i64_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_i64_neg_one() -> Option { Some(-1) } +pub fn optional_i64_neg_one() -> Option { + Some(-1) +} #[wasm_bindgen] -pub fn optional_i64_min() -> Option { Some(i64::min_value()) } +pub fn optional_i64_min() -> Option { + Some(i64::min_value()) +} #[wasm_bindgen] -pub fn optional_i64_max() -> Option { Some(i64::max_value()) } +pub fn optional_i64_max() -> Option { + Some(i64::max_value()) +} #[wasm_bindgen] -pub fn optional_i64_identity(a: Option) -> Option { optional_i64_js_identity(a) } +pub fn optional_i64_identity(a: Option) -> Option { + optional_i64_js_identity(a) +} #[wasm_bindgen] -pub fn optional_u64_none() -> Option { None } +pub fn optional_u64_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_u64_zero() -> Option { Some(0) } +pub fn optional_u64_zero() -> Option { + Some(0) +} #[wasm_bindgen] -pub fn optional_u64_one() -> Option { Some(1) } +pub fn optional_u64_one() -> Option { + Some(1) +} #[wasm_bindgen] -pub fn optional_u64_min() -> Option { Some(u64::min_value()) } +pub fn optional_u64_min() -> Option { + Some(u64::min_value()) +} #[wasm_bindgen] -pub fn optional_u64_max() -> Option { Some(u64::max_value()) } +pub fn optional_u64_max() -> Option { + Some(u64::max_value()) +} #[wasm_bindgen] -pub fn optional_u64_identity(a: Option) -> Option { optional_u64_js_identity(a) } +pub fn optional_u64_identity(a: Option) -> Option { + optional_u64_js_identity(a) +} #[wasm_bindgen] -pub fn optional_bool_none() -> Option { None } +pub fn optional_bool_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_bool_false() -> Option { Some(false) } +pub fn optional_bool_false() -> Option { + Some(false) +} #[wasm_bindgen] -pub fn optional_bool_true() -> Option { Some(true) } +pub fn optional_bool_true() -> Option { + Some(true) +} #[wasm_bindgen] -pub fn optional_bool_identity(a: Option) -> Option { optional_bool_js_identity(a) } +pub fn optional_bool_identity(a: Option) -> Option { + optional_bool_js_identity(a) +} #[wasm_bindgen] -pub fn optional_char_none() -> Option { None } +pub fn optional_char_none() -> Option { + None +} #[wasm_bindgen] -pub fn optional_char_letter() -> Option { Some('a') } +pub fn optional_char_letter() -> Option { + Some('a') +} #[wasm_bindgen] -pub fn optional_char_face() -> Option { Some('😀') } +pub fn optional_char_face() -> Option { + Some('😀') +} #[wasm_bindgen] -pub fn optional_char_identity(a: Option) -> Option { optional_char_js_identity(a) } +pub fn optional_char_identity(a: Option) -> Option { + optional_char_js_identity(a) +} #[wasm_bindgen_test] fn works() { diff --git a/tests/wasm/rethrow.rs b/tests/wasm/rethrow.rs index 7cee77191..d2a0ffafd 100644 --- a/tests/wasm/rethrow.rs +++ b/tests/wasm/rethrow.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/rethrow.js")] -extern { +extern "C" { fn call_throw_one(); fn call_ok(); } diff --git a/tests/wasm/simple.rs b/tests/wasm/simple.rs index 930c1fced..84f74abd5 100644 --- a/tests/wasm/simple.rs +++ b/tests/wasm/simple.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/simple.js")] -extern { +extern "C" { fn test_add(); fn test_string_arguments(); fn test_return_a_string(); @@ -56,7 +56,7 @@ pub fn simple_return_and_take_bool(a: bool, b: bool) -> bool { pub fn simple_raw_pointers_work(a: *mut u32, b: *const u8) -> *const u32 { unsafe { (*a) = (*b) as u32; - return a + return a; } } @@ -108,8 +108,7 @@ fn other_exports() { } #[no_mangle] -pub extern fn foo(_a: u32) { -} +pub extern "C" fn foo(_a: u32) {} #[wasm_bindgen_test] fn jsvalue_typeof() { @@ -132,14 +131,15 @@ pub fn is_string(val: &JsValue) -> bool { } #[wasm_bindgen] -extern { +extern "C" { #[derive(Clone)] type Array; #[wasm_bindgen(constructor)] fn new() -> Array; #[wasm_bindgen(method, catch)] - fn standardized_method_this_js_runtime_doesnt_implement_yet(this: &Array) - -> Result<(), JsValue>; + fn standardized_method_this_js_runtime_doesnt_implement_yet( + this: &Array, + ) -> Result<(), JsValue>; } #[wasm_bindgen_test] @@ -167,7 +167,6 @@ fn optional_slices() { #[wasm_bindgen] pub fn take_optional_str_none(x: Option) { assert!(x.is_none()) - } #[wasm_bindgen] pub fn take_optional_str_some(x: Option) { diff --git a/tests/wasm/slice.rs b/tests/wasm/slice.rs index b3e9486a5..f50ac7aaa 100644 --- a/tests/wasm/slice.rs +++ b/tests/wasm/slice.rs @@ -1,9 +1,9 @@ -use wasm_bindgen_test::*; -use wasm_bindgen::Clamped; use wasm_bindgen::prelude::*; +use wasm_bindgen::Clamped; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/slice.js")] -extern { +extern "C" { fn js_export(); fn js_import(); diff --git a/tests/wasm/structural.rs b/tests/wasm/structural.rs index 4729620c7..024aad9ef 100644 --- a/tests/wasm/structural.rs +++ b/tests/wasm/structural.rs @@ -1,13 +1,13 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/structural.js")] -extern { +extern "C" { fn js_works(); } #[wasm_bindgen] -extern { +extern "C" { pub type Foo; #[wasm_bindgen(method, structural)] diff --git a/tests/wasm/u64.rs b/tests/wasm/u64.rs index 1900d3cdb..0165c6a20 100644 --- a/tests/wasm/u64.rs +++ b/tests/wasm/u64.rs @@ -1,45 +1,67 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/u64.js")] -extern { +extern "C" { fn i64_js_identity(a: i64) -> i64; fn u64_js_identity(a: u64) -> u64; fn js_works(); } #[wasm_bindgen] -pub fn zero() -> u64 { 0 } +pub fn zero() -> u64 { + 0 +} #[wasm_bindgen] -pub fn one() -> u64 { 1 } +pub fn one() -> u64 { + 1 +} #[wasm_bindgen] -pub fn neg_one() -> i64 { -1 } +pub fn neg_one() -> i64 { + -1 +} #[wasm_bindgen] -pub fn i32_min() -> i64 { i32::min_value() as i64 } +pub fn i32_min() -> i64 { + i32::min_value() as i64 +} #[wasm_bindgen] -pub fn u32_max() -> u64 { u32::max_value() as u64 } +pub fn u32_max() -> u64 { + u32::max_value() as u64 +} #[wasm_bindgen] -pub fn i64_min() -> i64 { i64::min_value() } +pub fn i64_min() -> i64 { + i64::min_value() +} #[wasm_bindgen] -pub fn u64_max() -> u64 { u64::max_value() } +pub fn u64_max() -> u64 { + u64::max_value() +} #[wasm_bindgen] -pub fn i64_rust_identity(a: i64) -> i64 { i64_js_identity(a) } +pub fn i64_rust_identity(a: i64) -> i64 { + i64_js_identity(a) +} #[wasm_bindgen] -pub fn u64_rust_identity(a: u64) -> u64 { u64_js_identity(a) } +pub fn u64_rust_identity(a: u64) -> u64 { + u64_js_identity(a) +} #[wasm_bindgen] -pub fn i64_slice(a: &[i64]) -> Vec { a.to_vec() } +pub fn i64_slice(a: &[i64]) -> Vec { + a.to_vec() +} #[wasm_bindgen] -pub fn u64_slice(a: &[u64]) -> Vec { a.to_vec() } +pub fn u64_slice(a: &[u64]) -> Vec { + a.to_vec() +} #[wasm_bindgen_test] fn works() { diff --git a/tests/wasm/validate_prt.rs b/tests/wasm/validate_prt.rs index c04f3353c..efae98305 100644 --- a/tests/wasm/validate_prt.rs +++ b/tests/wasm/validate_prt.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/validate_prt.js")] -extern { +extern "C" { fn js_works(); } diff --git a/tests/wasm/variadic.rs b/tests/wasm/variadic.rs index cb7394be3..d558f74e4 100644 --- a/tests/wasm/variadic.rs +++ b/tests/wasm/variadic.rs @@ -1,8 +1,8 @@ -use wasm_bindgen_test::*; use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/variadic.js")] -extern { +extern "C" { #[wasm_bindgen(variadic)] fn variadic_sum_u8(first: u8, second: u8, rest: &[u8]) -> u8; #[wasm_bindgen(variadic)] @@ -37,9 +37,9 @@ extern { // rest: Vec) -> String; #[wasm_bindgen(variadic)] fn variadic_sum_rest_vec(first: u8, second: u8, rest: Vec) -> u8; - //#[wasm_bindgen(variadic)] - //fn variadic_compare_pairs(first: JsValue, second: JsValue, rest: &[JsValue]); - //TODO imported type +//#[wasm_bindgen(variadic)] +//fn variadic_compare_pairs(first: JsValue, second: JsValue, rest: &[JsValue]); +//TODO imported type } // ints @@ -52,7 +52,7 @@ macro_rules! variadic_test_int { assert_eq!($extern_name(1, 2, &[3]), 6); assert_eq!($extern_name(1, 2, &[3, 4]), 10); } - } + }; } // The 64 tests throw js `Cannot mix BigInt and other types, use explicit conversions` @@ -77,7 +77,7 @@ macro_rules! variadic_test_float { assert_eq!($extern_name(1., 2., &[3.]), 6.); assert_eq!($extern_name(1., 2., &[3., 4.]), 10.); } - } + }; } variadic_test_float!(f32, variadic_sum_f32); @@ -132,4 +132,3 @@ fn rest_vec() { // variadic_compare_pairs_jsvalue(true, true, vec![]); // variadic_compare_pairs_jsvalue(false, false, vec![3, 3]); //} -