Migrate all crates to the 2018 edition

Most of the CLI crates were already in the 2018 edition, and it turns
out that one of the macro crates was already in the 2018 edition so we
may as well move everything to the 2018 edition!

Always nice to remove those `extern crate` statements nowadays!

This commit also does a `cargo fmt --all` to make sure we're conforming
with style again.
This commit is contained in:
Alex Crichton 2019-03-26 08:00:16 -07:00
parent c5d2b2d1fb
commit a6fe0cefa8
53 changed files with 245 additions and 279 deletions

View File

@ -11,6 +11,7 @@ documentation = "https://docs.rs/wasm-bindgen"
description = """ description = """
Easy support for interacting between JS and Rust. Easy support for interacting between JS and Rust.
""" """
edition = "2018"
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ['serde-serialize'] features = ['serde-serialize']

View File

@ -431,7 +431,7 @@ impl Transform<'_> {
let (is_export, ty) = match &mut target.kind { let (is_export, ty) = match &mut target.kind {
walrus::FunctionKind::Import(f) => (false, &mut f.ty), walrus::FunctionKind::Import(f) => (false, &mut f.ty),
walrus::FunctionKind::Local(f) => (true, &mut f.ty), walrus::FunctionKind::Local(f) => (true, &mut f.ty),
_ => unreachable!() _ => unreachable!(),
}; };
let target_ty = types.get(*ty); let target_ty = types.get(*ty);
@ -496,7 +496,8 @@ impl Transform<'_> {
let mut builder = walrus::FunctionBuilder::new(); let mut builder = walrus::FunctionBuilder::new();
let mut before = Vec::new(); let mut before = Vec::new();
let params = types.get(shim_ty) let params = types
.get(shim_ty)
.params() .params()
.iter() .iter()
.cloned() .cloned()

View File

@ -9,6 +9,7 @@ documentation = "https://docs.rs/wasm-bindgen-backend"
description = """ description = """
Backend code generation of the wasm-bindgen tool Backend code generation of the wasm-bindgen tool
""" """
edition = "2018"
[features] [features]
spans = [] spans = []

View File

@ -1,8 +1,8 @@
use crate::Diagnostic;
use proc_macro2::{Ident, Span}; use proc_macro2::{Ident, Span};
use shared;
use syn;
use Diagnostic;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use syn;
use wasm_bindgen_shared as shared;
/// An abstract syntax tree representing a rust program. Contains /// An abstract syntax tree representing a rust program. Contains
/// extra information for joining up this rust code with javascript. /// extra information for joining up this rust code with javascript.

View File

@ -1,16 +1,14 @@
use crate::ast;
use crate::encode;
use crate::util::ShortHash;
use crate::Diagnostic;
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::{quote, ToTokens};
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex; use std::sync::Mutex;
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::ToTokens;
use shared;
use syn; use syn;
use wasm_bindgen_shared as shared;
use ast;
use encode;
use util::ShortHash;
use Diagnostic;
pub trait TryToTokens { pub trait TryToTokens {
fn try_to_tokens(&self, tokens: &mut TokenStream) -> Result<(), Diagnostic>; fn try_to_tokens(&self, tokens: &mut TokenStream) -> Result<(), Diagnostic>;
@ -114,12 +112,10 @@ impl TryToTokens for ast::Program {
// automatically rerun rustc which will rerun this macro. Other than // automatically rerun rustc which will rerun this macro. Other than
// this we don't actually need the results of the `include_str!`, so // this we don't actually need the results of the `include_str!`, so
// it's just shoved into an anonymous static. // it's just shoved into an anonymous static.
let file_dependencies = encoded.included_files let file_dependencies = encoded.included_files.iter().map(|file| {
.iter() let file = file.to_str().unwrap();
.map(|file| { quote! { include_str!(#file) }
let file = file.to_str().unwrap(); });
quote! { include_str!(#file) }
});
(quote! { (quote! {
#[allow(non_upper_case_globals)] #[allow(non_upper_case_globals)]
@ -1180,7 +1176,7 @@ impl ToTokens for ast::ImportStatic {
impl ToTokens for ast::Const { impl ToTokens for ast::Const {
fn to_tokens(&self, tokens: &mut TokenStream) { fn to_tokens(&self, tokens: &mut TokenStream) {
use ast::ConstValue::*; use crate::ast::ConstValue::*;
let vis = &self.vis; let vis = &self.vis;
let name = &self.name; let name = &self.name;
@ -1405,7 +1401,7 @@ impl<'a, T: ToTokens> ToTokens for Descriptor<'a, T> {
// It's up to the descriptors themselves to ensure they have unique // It's up to the descriptors themselves to ensure they have unique
// names for unique items imported, currently done via `ShortHash` and // names for unique items imported, currently done via `ShortHash` and
// hashing appropriate data into the symbol name. // hashing appropriate data into the symbol name.
lazy_static! { lazy_static::lazy_static! {
static ref DESCRIPTORS_EMITTED: Mutex<HashSet<String>> = Default::default(); static ref DESCRIPTORS_EMITTED: Mutex<HashSet<String>> = Default::default();
} }
if !DESCRIPTORS_EMITTED if !DESCRIPTORS_EMITTED

View File

@ -1,4 +1,4 @@
use ast; use crate::ast;
use proc_macro2::Ident; use proc_macro2::Ident;
use syn; use syn;
@ -355,7 +355,7 @@ impl RemoveUndefinedImports for ast::Program {
let before = num_required(dictionary); let before = num_required(dictionary);
changed = dictionary.fields.remove_undefined_imports(is_defined) || changed; changed = dictionary.fields.remove_undefined_imports(is_defined) || changed;
if before != num_required(dictionary) { if before != num_required(dictionary) {
warn!( log::warn!(
"removing {} due to a required field being removed", "removing {} due to a required field being removed",
dictionary.name dictionary.name
); );
@ -384,7 +384,7 @@ where
x.imported_type_references(&mut |id| { x.imported_type_references(&mut |id| {
if all_defined { if all_defined {
if !is_defined(id) { if !is_defined(id) {
info!("removing due to {} not being defined", id); log::info!("removing due to {} not being defined", id);
all_defined = false; all_defined = false;
} }
} }

View File

@ -1,13 +1,13 @@
use crate::util::ShortHash;
use proc_macro2::{Ident, Span}; use proc_macro2::{Ident, Span};
use std::cell::{RefCell, Cell}; use std::cell::{Cell, RefCell};
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
use util::ShortHash;
use ast; use crate::ast;
use Diagnostic; use crate::Diagnostic;
pub struct EncodeResult { pub struct EncodeResult {
pub custom_section: Vec<u8>, pub custom_section: Vec<u8>,
@ -19,8 +19,17 @@ pub fn encode(program: &ast::Program) -> Result<EncodeResult, Diagnostic> {
let i = Interner::new(); let i = Interner::new();
shared_program(program, &i)?.encode(&mut e); shared_program(program, &i)?.encode(&mut e);
let custom_section = e.finish(); let custom_section = e.finish();
let included_files = i.files.borrow().values().map(|p| &p.path).cloned().collect(); let included_files = i
Ok(EncodeResult { custom_section, included_files }) .files
.borrow()
.values()
.map(|p| &p.path)
.cloned()
.collect();
Ok(EncodeResult {
custom_section,
included_files,
})
} }
struct Interner { struct Interner {
@ -67,16 +76,16 @@ impl Interner {
fn resolve_import_module(&self, id: &str, span: Span) -> Result<&str, Diagnostic> { fn resolve_import_module(&self, id: &str, span: Span) -> Result<&str, Diagnostic> {
let mut files = self.files.borrow_mut(); let mut files = self.files.borrow_mut();
if let Some(file) = files.get(id) { if let Some(file) = files.get(id) {
return Ok(self.intern_str(&file.new_identifier)) return Ok(self.intern_str(&file.new_identifier));
} }
self.check_for_package_json(); self.check_for_package_json();
let path = if id.starts_with("/") { let path = if id.starts_with("/") {
self.root.join(&id[1..]) self.root.join(&id[1..])
} else if id.starts_with("./") || id.starts_with("../") { } else if id.starts_with("./") || id.starts_with("../") {
let msg = "relative module paths aren't supported yet"; let msg = "relative module paths aren't supported yet";
return Err(Diagnostic::span_error(span, msg)) return Err(Diagnostic::span_error(span, msg));
} else { } else {
return Ok(self.intern_str(&id)) return Ok(self.intern_str(&id));
}; };
// Generate a unique ID which is somewhat readable as well, so mix in // Generate a unique ID which is somewhat readable as well, so mix in
@ -98,7 +107,7 @@ impl Interner {
fn check_for_package_json(&self) { fn check_for_package_json(&self) {
if self.has_package_json.get() { if self.has_package_json.get() {
return return;
} }
let path = self.root.join("package.json"); let path = self.root.join("package.json");
if path.exists() { if path.exists() {
@ -139,11 +148,9 @@ fn shared_program<'a>(
.values() .values()
.map(|file| { .map(|file| {
fs::read_to_string(&file.path) fs::read_to_string(&file.path)
.map(|s| { .map(|s| LocalModule {
LocalModule { identifier: intern.intern_str(&file.new_identifier),
identifier: intern.intern_str(&file.new_identifier), contents: intern.intern_str(&s),
contents: intern.intern_str(&s),
}
}) })
.map_err(|e| { .map_err(|e| {
let msg = format!("failed to read file `{}`: {}", file.path.display(), e); let msg = format!("failed to read file `{}`: {}", file.path.display(), e);
@ -499,4 +506,4 @@ macro_rules! encode_api {
encode_api!($($rest)*); encode_api!($($rest)*);
); );
} }
shared_api!(encode_api); wasm_bindgen_shared::shared_api!(encode_api);

View File

@ -2,21 +2,8 @@
#![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")] #![doc(html_root_url = "https://docs.rs/wasm-bindgen-backend/0.2")]
extern crate bumpalo; pub use crate::codegen::TryToTokens;
#[macro_use] pub use crate::error::Diagnostic;
extern crate log;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
extern crate syn;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate wasm_bindgen_shared as shared;
pub use codegen::TryToTokens;
pub use error::Diagnostic;
#[macro_use] #[macro_use]
mod error; mod error;

View File

@ -7,7 +7,7 @@ use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize; use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst; use std::sync::atomic::Ordering::SeqCst;
use ast; use crate::ast;
use proc_macro2::{self, Ident}; use proc_macro2::{self, Ident};
use syn; use syn;

View File

@ -357,7 +357,8 @@ impl<'a, 'b> Js2Rust<'a, 'b> {
return Ok(self); return Ok(self);
} }
Descriptor::RustStruct(ref s) => { Descriptor::RustStruct(ref s) => {
self.js_arguments.push((name.clone(), format!("{} | undefined", s))); self.js_arguments
.push((name.clone(), format!("{} | undefined", s)));
self.prelude(&format!("let ptr{} = 0;", i)); self.prelude(&format!("let ptr{} = 0;", i));
self.prelude(&format!("if ({0} !== null && {0} !== undefined) {{", name)); self.prelude(&format!("if ({0} !== null && {0} !== undefined) {{", name));
self.assert_class(&name, s); self.assert_class(&name, s);
@ -659,7 +660,8 @@ impl<'a, 'b> Js2Rust<'a, 'b> {
Descriptor::RustStruct(ref name) => { Descriptor::RustStruct(ref name) => {
self.ret_ty = format!("{} | undefined", name); self.ret_ty = format!("{} | undefined", name);
self.cx.require_class_wrap(name); self.cx.require_class_wrap(name);
self.ret_expr = format!(" self.ret_expr = format!(
"
const ptr = RET; const ptr = RET;
return ptr === 0 ? undefined : {}.__wrap(ptr); return ptr === 0 ? undefined : {}.__wrap(ptr);
", ",
@ -830,7 +832,7 @@ impl<'a, 'b> Js2Rust<'a, 'b> {
fn assert_class(&mut self, arg: &str, class: &str) { fn assert_class(&mut self, arg: &str, class: &str) {
if !self.cx.config.debug { if !self.cx.config.debug {
return return;
} }
self.cx.expose_assert_class(); self.cx.expose_assert_class();
self.prelude(&format!("_assertClass({}, {});", arg, class)); self.prelude(&format!("_assertClass({}, {});", arg, class));
@ -838,7 +840,7 @@ impl<'a, 'b> Js2Rust<'a, 'b> {
fn assert_not_moved(&mut self, arg: &str) { fn assert_not_moved(&mut self, arg: &str) {
if !self.cx.config.debug { if !self.cx.config.debug {
return return;
} }
self.prelude(&format!( self.prelude(&format!(
"\ "\

View File

@ -2,7 +2,7 @@ use crate::decode;
use crate::descriptor::{Descriptor, VectorKind}; use crate::descriptor::{Descriptor, VectorKind};
use crate::{Bindgen, EncodeInto, OutputMode}; use crate::{Bindgen, EncodeInto, OutputMode};
use failure::{bail, Error, ResultExt}; use failure::{bail, Error, ResultExt};
use std::collections::{HashMap, HashSet, BTreeMap}; use std::collections::{BTreeMap, HashMap, HashSet};
use std::env; use std::env;
use std::fs; use std::fs;
use walrus::{MemoryId, Module}; use walrus::{MemoryId, Module};
@ -2998,8 +2998,10 @@ impl<'a, 'b> SubContext<'a, 'b> {
return Ok(()); return Ok(());
} }
if !self.cx.config.mode.nodejs() && !self.cx.config.mode.bundler() { if !self.cx.config.mode.nodejs() && !self.cx.config.mode.bundler() {
bail!("NPM dependencies have been specified in `{}` but \ bail!(
this is only compatible with the `bundler` and `nodejs` targets"); "NPM dependencies have been specified in `{}` but \
this is only compatible with the `bundler` and `nodejs` targets"
);
} }
let contents = fs::read_to_string(path).context(format!("failed to read `{}`", path))?; let contents = fs::read_to_string(path).context(format!("failed to read `{}`", path))?;
let json: serde_json::Value = serde_json::from_str(&contents)?; let json: serde_json::Value = serde_json::from_str(&contents)?;

View File

@ -225,7 +225,10 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
} }
Descriptor::RustStruct(ref class) => { Descriptor::RustStruct(ref class) => {
self.cx.require_class_wrap(class); self.cx.require_class_wrap(class);
let assign = format!("let c{0} = {0} === 0 ? undefined : {1}.__wrap({0});", abi, class); let assign = format!(
"let c{0} = {0} === 0 ? undefined : {1}.__wrap({0});",
abi, class
);
self.prelude(&assign); self.prelude(&assign);
self.js_arguments.push(format!("c{}", abi)); self.js_arguments.push(format!("c{}", abi));
return Ok(()); return Ok(());

View File

@ -1,7 +1,7 @@
#![doc(html_root_url = "https://docs.rs/wasm-bindgen-cli-support/0.2")] #![doc(html_root_url = "https://docs.rs/wasm-bindgen-cli-support/0.2")]
use failure::{bail, Error, ResultExt}; use failure::{bail, Error, ResultExt};
use std::collections::{BTreeSet, BTreeMap}; use std::collections::{BTreeMap, BTreeSet};
use std::env; use std::env;
use std::fs; use std::fs;
use std::mem; use std::mem;

View File

@ -59,9 +59,14 @@ fn more_package_json_fields_rejected() {
) )
.wasm_bindgen(""); .wasm_bindgen("");
cmd.assert() cmd.assert()
.stderr(str::is_match("\ .stderr(
str::is_match(
"\
error: NPM manifest found at `.*` can currently only have one key, .* error: NPM manifest found at `.*` can currently only have one key, .*
").unwrap()) ",
)
.unwrap(),
)
.failure(); .failure();
} }
@ -70,7 +75,8 @@ fn npm_conflict_rejected() {
let (mut cmd, _out_dir) = Project::new("npm_conflict_rejected") let (mut cmd, _out_dir) = Project::new("npm_conflict_rejected")
.file( .file(
"Cargo.toml", "Cargo.toml",
&format!(r#" &format!(
r#"
[package] [package]
name = "npm_conflict_rejected" name = "npm_conflict_rejected"
authors = [] authors = []
@ -87,7 +93,7 @@ fn npm_conflict_rejected() {
[workspace] [workspace]
"#, "#,
repo_root().display() repo_root().display()
) ),
) )
.file( .file(
"src/lib.rs", "src/lib.rs",
@ -116,7 +122,8 @@ fn npm_conflict_rejected() {
) )
.file( .file(
"bar/Cargo.toml", "bar/Cargo.toml",
&format!(r#" &format!(
r#"
[package] [package]
name = "bar" name = "bar"
authors = [] authors = []
@ -127,7 +134,7 @@ fn npm_conflict_rejected() {
wasm-bindgen = {{ path = '{}' }} wasm-bindgen = {{ path = '{}' }}
"#, "#,
repo_root().display() repo_root().display()
) ),
) )
.file( .file(
"bar/src/lib.rs", "bar/src/lib.rs",

View File

@ -8,6 +8,7 @@ name = "wasm-bindgen-futures"
repository = "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/futures" repository = "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/futures"
readme = "./README.md" readme = "./README.md"
version = "0.3.17" version = "0.3.17"
edition = "2018"
[dependencies] [dependencies]
futures = "0.1.20" futures = "0.1.20"

View File

@ -103,10 +103,6 @@
#![deny(missing_docs)] #![deny(missing_docs)]
extern crate futures;
extern crate js_sys;
extern crate wasm_bindgen;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;

View File

@ -12,6 +12,7 @@ Bindings for all JS global objects and functions in all JS environments like
Node.js and browsers, built on `#[wasm_bindgen]` using the `wasm-bindgen` crate. Node.js and browsers, built on `#[wasm_bindgen]` using the `wasm-bindgen` crate.
""" """
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
edition = "2018"
[lib] [lib]
test = false test = false

View File

@ -18,8 +18,6 @@
#![doc(html_root_url = "https://docs.rs/js-sys/0.2")] #![doc(html_root_url = "https://docs.rs/js-sys/0.2")]
extern crate wasm_bindgen;
use std::fmt; use std::fmt;
use std::mem; use std::mem;

View File

@ -11,9 +11,9 @@ extern crate syn;
extern crate wasm_bindgen_backend as backend; extern crate wasm_bindgen_backend as backend;
extern crate wasm_bindgen_shared as shared; extern crate wasm_bindgen_shared as shared;
use backend::{Diagnostic, TryToTokens};
pub use crate::parser::BindgenAttrs; pub use crate::parser::BindgenAttrs;
use crate::parser::MacroParse; use crate::parser::MacroParse;
use backend::{Diagnostic, TryToTokens};
use proc_macro2::TokenStream; use proc_macro2::TokenStream;
use quote::ToTokens; use quote::ToTokens;
use quote::TokenStreamExt; use quote::TokenStreamExt;

View File

@ -9,6 +9,7 @@ documentation = "https://docs.rs/wasm-bindgen"
description = """ description = """
Definition of the `#[wasm_bindgen]` attribute, an internal dependency Definition of the `#[wasm_bindgen]` attribute, an internal dependency
""" """
edition = "2018"
[lib] [lib]
proc-macro = true proc-macro = true

View File

@ -1,15 +1,13 @@
#![doc(html_root_url = "https://docs.rs/wasm-bindgen-macro/0.2")] #![doc(html_root_url = "https://docs.rs/wasm-bindgen-macro/0.2")]
extern crate proc_macro; extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate wasm_bindgen_macro_support as macro_support;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::quote;
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn wasm_bindgen(attr: TokenStream, input: TokenStream) -> TokenStream { pub fn wasm_bindgen(attr: TokenStream, input: TokenStream) -> TokenStream {
match macro_support::expand(attr.into(), input.into()) { match wasm_bindgen_macro_support::expand(attr.into(), input.into()) {
Ok(tokens) => { Ok(tokens) => {
if cfg!(feature = "xxx_debug_only_print_generated_code") { if cfg!(feature = "xxx_debug_only_print_generated_code") {
println!("{}", tokens); println!("{}", tokens);
@ -22,7 +20,7 @@ pub fn wasm_bindgen(attr: TokenStream, input: TokenStream) -> TokenStream {
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn __wasm_bindgen_class_marker(attr: TokenStream, input: TokenStream) -> TokenStream { pub fn __wasm_bindgen_class_marker(attr: TokenStream, input: TokenStream) -> TokenStream {
match macro_support::expand_class_marker(attr.into(), input.into()) { match wasm_bindgen_macro_support::expand_class_marker(attr.into(), input.into()) {
Ok(tokens) => { Ok(tokens) => {
if cfg!(feature = "xxx_debug_only_print_generated_code") { if cfg!(feature = "xxx_debug_only_print_generated_code") {
println!("{}", tokens); println!("{}", tokens);

View File

@ -10,6 +10,7 @@ description = """
Shared support between wasm-bindgen and wasm-bindgen cli, an internal Shared support between wasm-bindgen and wasm-bindgen cli, an internal
dependency. dependency.
""" """
edition = "2018"
# Because only a single `wasm_bindgen` version can be used in a dependency # Because only a single `wasm_bindgen` version can be used in a dependency
# graph, pretend we link a native library so that `cargo` will provide better # graph, pretend we link a native library so that `cargo` will provide better

View File

@ -5,6 +5,7 @@ authors = ["The wasm-bindgen Developers"]
description = "Internal testing macro for wasm-bindgen" description = "Internal testing macro for wasm-bindgen"
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
repository = "https://github.com/rustwasm/wasm-bindgen" repository = "https://github.com/rustwasm/wasm-bindgen"
edition = "2018"
[dependencies] [dependencies]
proc-macro2 = "0.4" proc-macro2 = "0.4"

View File

@ -2,11 +2,9 @@
//! going on here. //! going on here.
extern crate proc_macro; extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
use proc_macro2::*; use proc_macro2::*;
use quote::quote;
use std::sync::atomic::*; use std::sync::atomic::*;
static CNT: AtomicUsize = AtomicUsize::new(0); static CNT: AtomicUsize = AtomicUsize::new(0);
@ -17,10 +15,10 @@ pub fn wasm_bindgen_test(
body: proc_macro::TokenStream, body: proc_macro::TokenStream,
) -> proc_macro::TokenStream { ) -> proc_macro::TokenStream {
let mut attr = attr.into_iter(); let mut attr = attr.into_iter();
let mut async = false; let mut r#async = false;
while let Some(token) = attr.next() { while let Some(token) = attr.next() {
match &token { match &token {
proc_macro::TokenTree::Ident(i) if i.to_string() == "async" => async = true, proc_macro::TokenTree::Ident(i) if i.to_string() == "async" => r#async = true,
_ => panic!("malformed `#[wasm_bindgen_test]` attribute"), _ => panic!("malformed `#[wasm_bindgen_test]` attribute"),
} }
match &attr.next() { match &attr.next() {
@ -49,7 +47,7 @@ pub fn wasm_bindgen_test(
let mut tokens = Vec::<TokenTree>::new(); let mut tokens = Vec::<TokenTree>::new();
let test_body = if async { let test_body = if r#async {
quote! { cx.execute_async(test_name, #ident); } quote! { cx.execute_async(test_name, #ident); }
} else { } else {
quote! { cx.execute_sync(test_name, #ident); } quote! { cx.execute_sync(test_name, #ident); }

View File

@ -5,6 +5,7 @@ authors = ["The wasm-bindgen Developers"]
description = "Internal testing crate for wasm-bindgen" description = "Internal testing crate for wasm-bindgen"
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
repository = "https://github.com/rustwasm/wasm-bindgen" repository = "https://github.com/rustwasm/wasm-bindgen"
edition = "2018"
[dependencies] [dependencies]
console_error_panic_hook = '0.1' console_error_panic_hook = '0.1'

View File

@ -4,15 +4,6 @@
#![deny(missing_docs)] #![deny(missing_docs)]
extern crate console_error_panic_hook;
extern crate futures;
extern crate js_sys;
#[macro_use]
extern crate scoped_tls;
extern crate wasm_bindgen;
extern crate wasm_bindgen_futures;
extern crate wasm_bindgen_test_macro;
pub use wasm_bindgen_test_macro::wasm_bindgen_test; pub use wasm_bindgen_test_macro::wasm_bindgen_test;
/// Helper macro which acts like `println!` only routes to `console.log` /// Helper macro which acts like `println!` only routes to `console.log`

View File

@ -293,7 +293,7 @@ impl Context {
} }
} }
scoped_thread_local!(static CURRENT_OUTPUT: RefCell<Output>); scoped_tls::scoped_thread_local!(static CURRENT_OUTPUT: RefCell<Output>);
/// Handler for `console.log` invocations. /// Handler for `console.log` invocations.
/// ///

View File

@ -1,8 +1,7 @@
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
#[wasm_bindgen] #[wasm_bindgen]
pub struct A { pub struct A {}
}
#[wasm_bindgen] #[wasm_bindgen]
impl A { impl A {

View File

@ -10,6 +10,7 @@ description = """
Bindings for all Web APIs, a procedurally generated crate from WebIDL Bindings for all Web APIs, a procedurally generated crate from WebIDL
""" """
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
edition = "2018"
[package.metadata.docs.rs] [package.metadata.docs.rs]
all-features = true all-features = true

View File

@ -14,9 +14,6 @@
#![doc(html_root_url = "https://docs.rs/web-sys/0.2")] #![doc(html_root_url = "https://docs.rs/web-sys/0.2")]
#![allow(deprecated)] #![allow(deprecated)]
extern crate js_sys;
extern crate wasm_bindgen;
#[allow(unused_imports)] #[allow(unused_imports)]
use js_sys::Object; use js_sys::Object;

View File

@ -12,7 +12,7 @@
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*; use wasm_bindgen_test::*;
use web_sys::{WebGlRenderingContext, WebGl2RenderingContext}; use web_sys::{WebGl2RenderingContext, WebGlRenderingContext};
#[wasm_bindgen(module = "/tests/wasm/element.js")] #[wasm_bindgen(module = "/tests/wasm/element.js")]
extern "C" { extern "C" {

View File

@ -2,6 +2,7 @@
name = "webidl-tests" name = "webidl-tests"
version = "0.1.0" version = "0.1.0"
authors = ["The wasm-bindgen Developers"] authors = ["The wasm-bindgen Developers"]
edition = "2018"
[lib] [lib]
test = false test = false

View File

@ -10,6 +10,7 @@ documentation = "https://docs.rs/wasm-bindgen"
description = """ description = """
Support for parsing WebIDL specific to wasm-bindgen Support for parsing WebIDL specific to wasm-bindgen
""" """
edition = "2018"
[dependencies] [dependencies]
failure = "0.1.2" failure = "0.1.2"

View File

@ -20,8 +20,8 @@ use weedle::CallbackInterfaceDefinition;
use weedle::{DictionaryDefinition, PartialDictionaryDefinition}; use weedle::{DictionaryDefinition, PartialDictionaryDefinition};
use super::Result; use super::Result;
use util; use crate::util;
use util::camel_case_ident; use crate::util::camel_case_ident;
/// Collection of constructs that may use partial. /// Collection of constructs that may use partial.
#[derive(Default)] #[derive(Default)]
@ -191,7 +191,7 @@ impl<'src> FirstPass<'src, ()> for weedle::EnumDefinition<'src> {
} }
if record.enums.insert(self.identifier.0, self).is_some() { if record.enums.insert(self.identifier.0, self).is_some() {
info!( log::info!(
"Encountered multiple enum declarations: {}", "Encountered multiple enum declarations: {}",
self.identifier.0 self.identifier.0
); );
@ -304,7 +304,7 @@ impl<'src> FirstPass<'src, ()> for weedle::InterfaceDefinition<'src> {
} }
if util::is_no_interface_object(&self.attributes) { if util::is_no_interface_object(&self.attributes) {
info!( log::info!(
"Skipping because of `NoInterfaceObject` attribute: {:?}", "Skipping because of `NoInterfaceObject` attribute: {:?}",
self.identifier.0 self.identifier.0
); );
@ -431,23 +431,23 @@ impl<'src> FirstPass<'src, &'src str> for weedle::interface::InterfaceMember<'sr
Ok(()) Ok(())
} }
InterfaceMember::Iterable(_iterable) => { InterfaceMember::Iterable(_iterable) => {
warn!("Unsupported WebIDL iterable interface member: {:?}", self); log::warn!("Unsupported WebIDL iterable interface member: {:?}", self);
Ok(()) Ok(())
} }
// TODO // TODO
InterfaceMember::Maplike(_) => { InterfaceMember::Maplike(_) => {
warn!("Unsupported WebIDL Maplike interface member: {:?}", self); log::warn!("Unsupported WebIDL Maplike interface member: {:?}", self);
Ok(()) Ok(())
} }
InterfaceMember::Stringifier(_) => { InterfaceMember::Stringifier(_) => {
warn!( log::warn!(
"Unsupported WebIDL Stringifier interface member: {:?}", "Unsupported WebIDL Stringifier interface member: {:?}",
self self
); );
Ok(()) Ok(())
} }
InterfaceMember::Setlike(_) => { InterfaceMember::Setlike(_) => {
warn!("Unsupported WebIDL Setlike interface member: {:?}", self); log::warn!("Unsupported WebIDL Setlike interface member: {:?}", self);
Ok(()) Ok(())
} }
} }
@ -462,7 +462,7 @@ impl<'src> FirstPass<'src, &'src str> for weedle::interface::OperationInterfaceM
) -> Result<()> { ) -> Result<()> {
let is_static = match self.modifier { let is_static = match self.modifier {
Some(StringifierOrStatic::Stringifier(_)) => { Some(StringifierOrStatic::Stringifier(_)) => {
warn!("Unsupported webidl stringifier: {:?}", self); log::warn!("Unsupported webidl stringifier: {:?}", self);
return Ok(()); return Ok(());
} }
Some(StringifierOrStatic::Static(_)) => true, Some(StringifierOrStatic::Static(_)) => true,
@ -571,7 +571,7 @@ impl<'src> FirstPass<'src, &'src str> for weedle::mixin::MixinMember<'src> {
Ok(()) Ok(())
} }
MixinMember::Stringifier(_) => { MixinMember::Stringifier(_) => {
warn!("Unsupported WebIDL stringifier mixin member: {:?}", self); log::warn!("Unsupported WebIDL stringifier mixin member: {:?}", self);
Ok(()) Ok(())
} }
} }
@ -585,7 +585,7 @@ impl<'src> FirstPass<'src, &'src str> for weedle::mixin::OperationMixinMember<'s
self_name: &'src str, self_name: &'src str,
) -> Result<()> { ) -> Result<()> {
if self.stringifier.is_some() { if self.stringifier.is_some() {
warn!("Unsupported webidl stringifier: {:?}", self); log::warn!("Unsupported webidl stringifier: {:?}", self);
return Ok(()); return Ok(());
} }
@ -633,7 +633,7 @@ impl<'src> FirstPass<'src, ()> for weedle::TypedefDefinition<'src> {
.insert(self.identifier.0, &self.type_.type_) .insert(self.identifier.0, &self.type_.type_)
.is_some() .is_some()
{ {
info!( log::info!(
"Encountered multiple typedef declarations: {}", "Encountered multiple typedef declarations: {}",
self.identifier.0 self.identifier.0
); );
@ -721,7 +721,7 @@ impl<'src> FirstPass<'src, ()> for weedle::CallbackInterfaceDefinition<'src> {
return Ok(()); return Ok(());
} }
if self.inheritance.is_some() { if self.inheritance.is_some() {
warn!( log::warn!(
"skipping callback interface with inheritance: {}", "skipping callback interface with inheritance: {}",
self.identifier.0 self.identifier.0
); );

View File

@ -1,12 +1,12 @@
use backend::util::{ident_ty, leading_colon_path_ty, raw_ident, rust_ident};
use proc_macro2::{Ident, Span}; use proc_macro2::{Ident, Span};
use syn; use syn;
use wasm_bindgen_backend::util::{ident_ty, leading_colon_path_ty, raw_ident, rust_ident};
use weedle::common::Identifier; use weedle::common::Identifier;
use weedle::term; use weedle::term;
use weedle::types::*; use weedle::types::*;
use first_pass::FirstPassRecord; use crate::first_pass::FirstPassRecord;
use util::{array, camel_case_ident, option_ty, shared_ref, snake_case_ident, TypePosition}; use crate::util::{array, camel_case_ident, option_ty, shared_ref, snake_case_ident, TypePosition};
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub(crate) enum IdlType<'a> { pub(crate) enum IdlType<'a> {
@ -329,7 +329,7 @@ impl<'a> ToIdlType<'a> for Identifier<'a> {
// let's translate it as such. // let's translate it as such.
IdlType::Interface("Window") IdlType::Interface("Window")
} else { } else {
warn!("Unrecognized type: {}", self.0); log::warn!("Unrecognized type: {}", self.0);
IdlType::UnknownInterface(self.0) IdlType::UnknownInterface(self.0)
} }
} }

View File

@ -9,53 +9,39 @@ emitted for the types and methods described in the WebIDL.
#![deny(missing_debug_implementations)] #![deny(missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/wasm-bindgen-webidl/0.2")] #![doc(html_root_url = "https://docs.rs/wasm-bindgen-webidl/0.2")]
#[macro_use]
extern crate failure;
extern crate heck;
#[macro_use]
extern crate log;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
#[macro_use]
extern crate syn;
extern crate wasm_bindgen_backend as backend;
extern crate weedle;
mod error; mod error;
mod first_pass; mod first_pass;
mod idl_type; mod idl_type;
mod util; mod util;
use crate::first_pass::{CallbackInterfaceData, OperationData};
use crate::first_pass::{FirstPass, FirstPassRecord, InterfaceData, OperationId};
use crate::idl_type::ToIdlType;
use crate::util::{
camel_case_ident, mdn_doc, public, shouty_snake_case_ident, snake_case_ident,
webidl_const_v_to_backend_const_v, TypePosition,
};
use failure::format_err;
use proc_macro2::{Ident, Span};
use quote::{quote, ToTokens};
use std::collections::{BTreeSet, HashSet}; use std::collections::{BTreeSet, HashSet};
use std::env; use std::env;
use std::fs; use std::fs;
use std::iter::FromIterator; use std::iter::FromIterator;
use wasm_bindgen_backend::ast;
use backend::ast; use wasm_bindgen_backend::defined::ImportedTypeReferences;
use backend::defined::ImportedTypeReferences; use wasm_bindgen_backend::defined::{ImportedTypeDefinitions, RemoveUndefinedImports};
use backend::defined::{ImportedTypeDefinitions, RemoveUndefinedImports}; use wasm_bindgen_backend::util::{ident_ty, raw_ident, rust_ident, wrap_import_function};
use backend::util::{ident_ty, raw_ident, rust_ident, wrap_import_function}; use wasm_bindgen_backend::TryToTokens;
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::dictionary::DictionaryMember;
use weedle::interface::InterfaceMember; use weedle::interface::InterfaceMember;
use first_pass::{CallbackInterfaceData, OperationData}; pub use crate::error::{Error, ErrorKind, Result};
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};
struct Program { struct Program {
main: backend::ast::Program, main: ast::Program,
submodules: Vec<(String, backend::ast::Program)>, submodules: Vec<(String, ast::Program)>,
} }
/// Parse a string of WebIDL source text into a wasm-bindgen AST. /// Parse a string of WebIDL source text into a wasm-bindgen AST.
@ -132,7 +118,7 @@ fn parse(webidl_source: &str, allowed_types: Option<&[&str]>) -> Result<Program>
// prevent the type from being usable entirely. They're just there for // prevent the type from being usable entirely. They're just there for
// `AsRef` and such implementations. // `AsRef` and such implementations.
for import in program.imports.iter_mut() { for import in program.imports.iter_mut() {
if let backend::ast::ImportKind::Type(t) = &mut import.kind { if let ast::ImportKind::Type(t) = &mut import.kind {
t.extends.retain(|n| { t.extends.retain(|n| {
let ident = &n.segments.last().unwrap().value().ident; let ident = &n.segments.last().unwrap().value().ident;
first_pass_record.builtin_idents.contains(ident) || filter(&ident.to_string()) first_pass_record.builtin_idents.contains(ident) || filter(&ident.to_string())
@ -280,16 +266,12 @@ fn compile_ast(mut ast: Program) -> String {
} }
impl<'src> FirstPassRecord<'src> { impl<'src> FirstPassRecord<'src> {
fn append_enum( fn append_enum(&self, program: &mut ast::Program, enum_: &'src weedle::EnumDefinition<'src>) {
&self,
program: &mut backend::ast::Program,
enum_: &'src weedle::EnumDefinition<'src>,
) {
let variants = &enum_.values.body.list; let variants = &enum_.values.body.list;
program.imports.push(backend::ast::Import { program.imports.push(ast::Import {
module: backend::ast::ImportModule::None, module: ast::ImportModule::None,
js_namespace: None, js_namespace: None,
kind: backend::ast::ImportKind::Enum(backend::ast::ImportEnum { kind: ast::ImportKind::Enum(ast::ImportEnum {
vis: public(), vis: public(),
name: rust_ident(camel_case_ident(enum_.identifier.0).as_str()), name: rust_ident(camel_case_ident(enum_.identifier.0).as_str()),
variants: variants variants: variants
@ -303,7 +285,7 @@ impl<'src> FirstPassRecord<'src> {
}) })
.collect(), .collect(),
variant_values: variants.iter().map(|v| v.0.to_string()).collect(), variant_values: variants.iter().map(|v| v.0.to_string()).collect(),
rust_attrs: vec![parse_quote!(#[derive(Copy, Clone, PartialEq, Debug)])], rust_attrs: vec![syn::parse_quote!(#[derive(Copy, Clone, PartialEq, Debug)])],
}), }),
}); });
} }
@ -312,7 +294,7 @@ impl<'src> FirstPassRecord<'src> {
// https://www.w3.org/TR/WebIDL-1/#idl-dictionaries // https://www.w3.org/TR/WebIDL-1/#idl-dictionaries
fn append_dictionary( fn append_dictionary(
&self, &self,
program: &mut backend::ast::Program, program: &mut ast::Program,
data: &first_pass::DictionaryData<'src>, data: &first_pass::DictionaryData<'src>,
) { ) {
let def = match data.definition { let def = match data.definition {
@ -358,7 +340,7 @@ impl<'src> FirstPassRecord<'src> {
match self.dictionary_field(member) { match self.dictionary_field(member) {
Some(f) => dst.push(f), Some(f) => dst.push(f),
None => { None => {
warn!( log::warn!(
"unsupported dictionary field {:?}", "unsupported dictionary field {:?}",
(dict, member.identifier.0), (dict, member.identifier.0),
); );
@ -435,7 +417,7 @@ impl<'src> FirstPassRecord<'src> {
&'src self, &'src self,
name: &'src str, name: &'src str,
ns: &'src first_pass::NamespaceData<'src>, ns: &'src first_pass::NamespaceData<'src>,
) -> backend::ast::Program { ) -> ast::Program {
let mut ret = Default::default(); let mut ret = Default::default();
for (id, data) in ns.operations.iter() { for (id, data) in ns.operations.iter() {
@ -447,7 +429,7 @@ impl<'src> FirstPassRecord<'src> {
fn append_ns_member( fn append_ns_member(
&self, &self,
module: &mut backend::ast::Program, module: &mut ast::Program,
self_name: &'src str, self_name: &'src str,
id: &OperationId<'src>, id: &OperationId<'src>,
data: &OperationData<'src>, data: &OperationData<'src>,
@ -459,7 +441,7 @@ impl<'src> FirstPassRecord<'src> {
| OperationId::IndexingGetter | OperationId::IndexingGetter
| OperationId::IndexingSetter | OperationId::IndexingSetter
| OperationId::IndexingDeleter => { | OperationId::IndexingDeleter => {
warn!("Unsupported unnamed operation: on {:?}", self_name); log::warn!("Unsupported unnamed operation: on {:?}", self_name);
return; return;
} }
}; };
@ -470,24 +452,24 @@ impl<'src> FirstPassRecord<'src> {
mdn_doc(self_name, Some(&name)) mdn_doc(self_name, Some(&name))
); );
let kind = backend::ast::ImportFunctionKind::Normal; let kind = ast::ImportFunctionKind::Normal;
let extra = snake_case_ident(self_name); let extra = snake_case_ident(self_name);
let extra = &[&extra[..]]; let extra = &[&extra[..]];
for mut import_function in self.create_imports(None, kind, id, data) { for mut import_function in self.create_imports(None, kind, id, data) {
let mut doc = Some(doc_comment.clone()); let mut doc = Some(doc_comment.clone());
self.append_required_features_doc(&import_function, &mut doc, extra); self.append_required_features_doc(&import_function, &mut doc, extra);
import_function.doc_comment = doc; import_function.doc_comment = doc;
module.imports.push(backend::ast::Import { module.imports.push(ast::Import {
module: backend::ast::ImportModule::None, module: ast::ImportModule::None,
js_namespace: Some(raw_ident(self_name)), js_namespace: Some(raw_ident(self_name)),
kind: backend::ast::ImportKind::Function(import_function), kind: ast::ImportKind::Function(import_function),
}); });
} }
} }
fn append_const( fn append_const(
&self, &self,
program: &mut backend::ast::Program, program: &mut ast::Program,
self_name: &'src str, self_name: &'src str,
member: &'src weedle::interface::ConstMember<'src>, member: &'src weedle::interface::ConstMember<'src>,
) { ) {
@ -495,15 +477,17 @@ impl<'src> FirstPassRecord<'src> {
let ty = match idl_type.to_syn_type(TypePosition::Return) { let ty = match idl_type.to_syn_type(TypePosition::Return) {
Some(ty) => ty, Some(ty) => ty,
None => { None => {
warn!( log::warn!(
"Cannot convert const type to syn type: {:?} in {:?} on {:?}", "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 { program.consts.push(ast::Const {
vis: public(), vis: public(),
name: rust_ident(shouty_snake_case_ident(member.identifier.0).as_str()), name: rust_ident(shouty_snake_case_ident(member.identifier.0).as_str()),
class: Some(rust_ident(camel_case_ident(&self_name).as_str())), class: Some(rust_ident(camel_case_ident(&self_name).as_str())),
@ -514,16 +498,16 @@ impl<'src> FirstPassRecord<'src> {
fn append_interface( fn append_interface(
&self, &self,
program: &mut backend::ast::Program, program: &mut ast::Program,
name: &'src str, name: &'src str,
data: &InterfaceData<'src>, 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 mut attrs = Vec::new(); let mut attrs = Vec::new();
attrs.push(parse_quote!( #[derive(Debug, Clone)] )); attrs.push(syn::parse_quote!( #[derive(Debug, Clone)] ));
self.add_deprecated(data, &mut attrs); self.add_deprecated(data, &mut attrs);
let mut import_type = backend::ast::ImportType { let mut import_type = ast::ImportType {
vis: public(), vis: public(),
rust_name: rust_ident(camel_case_ident(name).as_str()), rust_name: rust_ident(camel_case_ident(name).as_str()),
js_name: name.to_string(), js_name: name.to_string(),
@ -553,10 +537,10 @@ impl<'src> FirstPassRecord<'src> {
.collect(); .collect();
import_type.doc_comment = doc_comment; import_type.doc_comment = doc_comment;
program.imports.push(backend::ast::Import { program.imports.push(ast::Import {
module: backend::ast::ImportModule::None, module: ast::ImportModule::None,
js_namespace: None, js_namespace: None,
kind: backend::ast::ImportKind::Type(import_type), kind: ast::ImportKind::Type(import_type),
}); });
for (id, op_data) in data.operations.iter() { for (id, op_data) in data.operations.iter() {
@ -608,7 +592,7 @@ impl<'src> FirstPassRecord<'src> {
fn member_attribute( fn member_attribute(
&self, &self,
program: &mut backend::ast::Program, program: &mut ast::Program,
self_name: &'src str, self_name: &'src str,
data: &InterfaceData<'src>, data: &InterfaceData<'src>,
modifier: Option<weedle::interface::StringifierOrInheritOrStatic>, modifier: Option<weedle::interface::StringifierOrInheritOrStatic>,
@ -661,7 +645,7 @@ impl<'src> FirstPassRecord<'src> {
fn member_operation( fn member_operation(
&self, &self,
program: &mut backend::ast::Program, program: &mut ast::Program,
self_name: &str, self_name: &str,
data: &InterfaceData<'src>, data: &InterfaceData<'src>,
id: &OperationId<'src>, id: &OperationId<'src>,
@ -672,21 +656,17 @@ impl<'src> FirstPassRecord<'src> {
let kind = match id { let kind = match id {
OperationId::Constructor(ctor_name) => { OperationId::Constructor(ctor_name) => {
let self_ty = ident_ty(rust_ident(&camel_case_ident(self_name))); let self_ty = ident_ty(rust_ident(&camel_case_ident(self_name)));
backend::ast::ImportFunctionKind::Method { ast::ImportFunctionKind::Method {
class: ctor_name.0.to_string(), class: ctor_name.0.to_string(),
ty: self_ty.clone(), ty: self_ty.clone(),
kind: backend::ast::MethodKind::Constructor, kind: ast::MethodKind::Constructor,
} }
} }
OperationId::Operation(_) => import_function_kind(backend::ast::OperationKind::Regular), OperationId::Operation(_) => import_function_kind(ast::OperationKind::Regular),
OperationId::IndexingGetter => { OperationId::IndexingGetter => import_function_kind(ast::OperationKind::IndexingGetter),
import_function_kind(backend::ast::OperationKind::IndexingGetter) OperationId::IndexingSetter => import_function_kind(ast::OperationKind::IndexingSetter),
}
OperationId::IndexingSetter => {
import_function_kind(backend::ast::OperationKind::IndexingSetter)
}
OperationId::IndexingDeleter => { OperationId::IndexingDeleter => {
import_function_kind(backend::ast::OperationKind::IndexingDeleter) import_function_kind(ast::OperationKind::IndexingDeleter)
} }
}; };
let doc = match id { let doc = match id {
@ -721,7 +701,7 @@ impl<'src> FirstPassRecord<'src> {
Some(s) => s, Some(s) => s,
None => return, None => return,
}; };
dst.push(parse_quote!( #[deprecated(note = #msg)] )); dst.push(syn::parse_quote!( #[deprecated(note = #msg)] ));
} }
fn append_required_features_doc( fn append_required_features_doc(
@ -760,7 +740,7 @@ impl<'src> FirstPassRecord<'src> {
fn append_callback_interface( fn append_callback_interface(
&self, &self,
program: &mut backend::ast::Program, program: &mut ast::Program,
item: &CallbackInterfaceData<'src>, item: &CallbackInterfaceData<'src>,
) { ) {
let mut fields = Vec::new(); let mut fields = Vec::new();
@ -780,7 +760,7 @@ impl<'src> FirstPassRecord<'src> {
}); });
} }
_ => { _ => {
warn!( log::warn!(
"skipping callback interface member on {}", "skipping callback interface member on {}",
item.definition.identifier.0 item.definition.identifier.0
); );

View File

@ -1,17 +1,17 @@
use std::iter::FromIterator; use std::iter::FromIterator;
use std::ptr; use std::ptr;
use backend;
use backend::util::{ident_ty, leading_colon_path_ty, raw_ident, rust_ident};
use heck::{CamelCase, ShoutySnakeCase, SnakeCase}; use heck::{CamelCase, ShoutySnakeCase, SnakeCase};
use proc_macro2::{Ident, Span}; use proc_macro2::{Ident, Span};
use syn; use syn;
use wasm_bindgen_backend::ast;
use wasm_bindgen_backend::util::{ident_ty, leading_colon_path_ty, raw_ident, rust_ident};
use weedle; use weedle;
use weedle::attribute::{ExtendedAttribute, ExtendedAttributeList, IdentifierOrString}; use weedle::attribute::{ExtendedAttribute, ExtendedAttributeList, IdentifierOrString};
use weedle::literal::{ConstValue, FloatLit, IntegerLit}; use weedle::literal::{ConstValue, FloatLit, IntegerLit};
use first_pass::{FirstPassRecord, OperationData, OperationId, Signature}; use crate::first_pass::{FirstPassRecord, OperationData, OperationId, Signature};
use idl_type::{IdlType, ToIdlType}; use crate::idl_type::{IdlType, ToIdlType};
/// For variadic operations an overload with a `js_sys::Array` argument is generated alongside with /// For variadic operations an overload with a `js_sys::Array` argument is generated alongside with
/// `operation_name_0`, `operation_name_1`, `operation_name_2`, ..., `operation_name_n` overloads /// `operation_name_0`, `operation_name_1`, `operation_name_2`, ..., `operation_name_n` overloads
@ -81,8 +81,7 @@ pub(crate) fn array(base_ty: &str, pos: TypePosition, immutable: bool) -> syn::T
} }
/// Map a webidl const value to the correct wasm-bindgen const value /// 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 { pub fn webidl_const_v_to_backend_const_v(v: &ConstValue) -> ast::ConstValue {
use backend::ast;
use std::f64::{INFINITY, NAN, NEG_INFINITY}; use std::f64::{INFINITY, NAN, NEG_INFINITY};
match *v { match *v {
@ -225,12 +224,12 @@ impl<'src> FirstPassRecord<'src> {
rust_name: &str, rust_name: &str,
idl_arguments: impl Iterator<Item = (&'a str, &'a IdlType<'src>)>, idl_arguments: impl Iterator<Item = (&'a str, &'a IdlType<'src>)>,
ret: &IdlType<'src>, ret: &IdlType<'src>,
kind: backend::ast::ImportFunctionKind, kind: ast::ImportFunctionKind,
structural: bool, structural: bool,
catch: bool, catch: bool,
variadic: bool, variadic: bool,
doc_comment: Option<String>, doc_comment: Option<String>,
) -> Option<backend::ast::ImportFunction> ) -> Option<ast::ImportFunction>
where where
'src: 'a, 'src: 'a,
{ {
@ -239,10 +238,10 @@ impl<'src> FirstPassRecord<'src> {
// //
// Note that for non-static methods we add a `&self` type placeholder, // Note that for non-static methods we add a `&self` type placeholder,
// but this type isn't actually used so it's just here for show mostly. // but this type isn't actually used so it's just here for show mostly.
let mut arguments = if let &backend::ast::ImportFunctionKind::Method { let mut arguments = if let &ast::ImportFunctionKind::Method {
ref ty, ref ty,
kind: kind:
backend::ast::MethodKind::Operation(backend::ast::Operation { ast::MethodKind::Operation(ast::Operation {
is_static: false, .. is_static: false, ..
}), }),
.. ..
@ -263,9 +262,10 @@ impl<'src> FirstPassRecord<'src> {
let syn_type = match idl_type.to_syn_type(TypePosition::Argument) { let syn_type = match idl_type.to_syn_type(TypePosition::Argument) {
Some(t) => t, Some(t) => t,
None => { None => {
warn!( log::warn!(
"Unsupported argument type: {:?} on {:?}", "Unsupported argument type: {:?} on {:?}",
idl_type, rust_name idl_type,
rust_name
); );
return None; return None;
} }
@ -287,7 +287,7 @@ impl<'src> FirstPassRecord<'src> {
ret @ _ => match ret.to_syn_type(TypePosition::Return) { ret @ _ => match ret.to_syn_type(TypePosition::Return) {
Some(ret) => Some(ret), Some(ret) => Some(ret),
None => { None => {
warn!("Unsupported return type: {:?} on {:?}", ret, rust_name); log::warn!("Unsupported return type: {:?} on {:?}", ret, rust_name);
return None; return None;
} }
}, },
@ -299,8 +299,8 @@ impl<'src> FirstPassRecord<'src> {
ret ret
}; };
Some(backend::ast::ImportFunction { Some(ast::ImportFunction {
function: backend::ast::Function { function: ast::Function {
name: js_name.to_string(), name: js_name.to_string(),
name_span: Span::call_site(), name_span: Span::call_site(),
renamed_via_js_name: false, renamed_via_js_name: false,
@ -316,8 +316,8 @@ impl<'src> FirstPassRecord<'src> {
structural, structural,
shim: { shim: {
let ns = match kind { let ns = match kind {
backend::ast::ImportFunctionKind::Normal => "", ast::ImportFunctionKind::Normal => "",
backend::ast::ImportFunctionKind::Method { ref class, .. } => class, ast::ImportFunctionKind::Method { ref class, .. } => class,
}; };
raw_ident(&format!("__widl_f_{}_{}", rust_name, ns)) raw_ident(&format!("__widl_f_{}_{}", rust_name, ns))
}, },
@ -335,8 +335,8 @@ impl<'src> FirstPassRecord<'src> {
is_static: bool, is_static: bool,
attrs: &Option<ExtendedAttributeList>, attrs: &Option<ExtendedAttributeList>,
container_attrs: Option<&ExtendedAttributeList>, container_attrs: Option<&ExtendedAttributeList>,
) -> Option<backend::ast::ImportFunction> { ) -> Option<ast::ImportFunction> {
let kind = backend::ast::OperationKind::Getter(Some(raw_ident(name))); let kind = ast::OperationKind::Getter(Some(raw_ident(name)));
let kind = self.import_function_kind(self_name, is_static, kind); let kind = self.import_function_kind(self_name, is_static, kind);
let ret = ty.to_idl_type(self); let ret = ty.to_idl_type(self);
self.create_one_function( self.create_one_function(
@ -365,8 +365,8 @@ impl<'src> FirstPassRecord<'src> {
is_static: bool, is_static: bool,
attrs: &Option<ExtendedAttributeList>, attrs: &Option<ExtendedAttributeList>,
container_attrs: Option<&ExtendedAttributeList>, container_attrs: Option<&ExtendedAttributeList>,
) -> Option<backend::ast::ImportFunction> { ) -> Option<ast::ImportFunction> {
let kind = backend::ast::OperationKind::Setter(Some(raw_ident(name))); let kind = ast::OperationKind::Setter(Some(raw_ident(name)));
let kind = self.import_function_kind(self_name, is_static, kind); let kind = self.import_function_kind(self_name, is_static, kind);
let field_ty = field_ty.to_idl_type(self); let field_ty = field_ty.to_idl_type(self);
self.create_one_function( self.create_one_function(
@ -390,27 +390,27 @@ impl<'src> FirstPassRecord<'src> {
&self, &self,
self_name: &str, self_name: &str,
is_static: bool, is_static: bool,
operation_kind: backend::ast::OperationKind, operation_kind: ast::OperationKind,
) -> backend::ast::ImportFunctionKind { ) -> ast::ImportFunctionKind {
let operation = backend::ast::Operation { let operation = ast::Operation {
is_static, is_static,
kind: operation_kind, kind: operation_kind,
}; };
let ty = ident_ty(rust_ident(camel_case_ident(&self_name).as_str())); let ty = ident_ty(rust_ident(camel_case_ident(&self_name).as_str()));
backend::ast::ImportFunctionKind::Method { ast::ImportFunctionKind::Method {
class: self_name.to_string(), class: self_name.to_string(),
ty, ty,
kind: backend::ast::MethodKind::Operation(operation), kind: ast::MethodKind::Operation(operation),
} }
} }
pub fn create_imports( pub fn create_imports(
&self, &self,
container_attrs: Option<&ExtendedAttributeList<'src>>, container_attrs: Option<&ExtendedAttributeList<'src>>,
kind: backend::ast::ImportFunctionKind, kind: ast::ImportFunctionKind,
id: &OperationId<'src>, id: &OperationId<'src>,
data: &OperationData<'src>, data: &OperationData<'src>,
) -> Vec<backend::ast::ImportFunction> { ) -> Vec<ast::ImportFunction> {
// First up, prune all signatures that reference unsupported arguments. // First up, prune all signatures that reference unsupported arguments.
// We won't consider these until said arguments are implemented. // We won't consider these until said arguments are implemented.
// //
@ -434,7 +434,7 @@ impl<'src> FirstPassRecord<'src> {
signatures.push((signature, idl_args.clone())); signatures.push((signature, idl_args.clone()));
} }
let mut idl_type = arg.ty.to_idl_type(self); let idl_type = arg.ty.to_idl_type(self);
let idl_type = self.maybe_adjust(idl_type, id); let idl_type = self.maybe_adjust(idl_type, id);
idl_args.push(idl_type); idl_args.push(idl_type);
} }
@ -452,7 +452,7 @@ impl<'src> FirstPassRecord<'src> {
let mut actual_signatures = Vec::new(); let mut actual_signatures = Vec::new();
for (signature, idl_args) in signatures.iter() { for (signature, idl_args) in signatures.iter() {
let mut start = actual_signatures.len(); let start = actual_signatures.len();
// Start off with an empty signature, this'll handle zero-argument // Start off with an empty signature, this'll handle zero-argument
// cases and otherwise the loop below will continue to add on to this. // cases and otherwise the loop below will continue to add on to this.
@ -504,7 +504,7 @@ impl<'src> FirstPassRecord<'src> {
OperationId::Constructor(_) => ("new", false, true), OperationId::Constructor(_) => ("new", false, true),
OperationId::Operation(Some(s)) => (*s, false, false), OperationId::Operation(Some(s)) => (*s, false, false),
OperationId::Operation(None) => { OperationId::Operation(None) => {
warn!("unsupported unnamed operation"); log::warn!("unsupported unnamed operation");
return Vec::new(); return Vec::new();
} }
OperationId::IndexingGetter => ("get", true, false), OperationId::IndexingGetter => ("get", true, false),

View File

@ -4,7 +4,7 @@ use std::ptr;
use std::alloc::{self, Layout}; use std::alloc::{self, Layout};
use std::mem; use std::mem;
use JsValue; use crate::JsValue;
externs! { externs! {
#[link(wasm_import_module = "__wbindgen_anyref_xform__")] #[link(wasm_import_module = "__wbindgen_anyref_xform__")]

View File

@ -1,4 +1,4 @@
use JsValue; use crate::JsValue;
/// A trait for checked and unchecked casting between JS types. /// A trait for checked and unchecked casting between JS types.
/// ///

View File

@ -9,11 +9,11 @@ use std::marker::Unsize;
use std::mem::{self, ManuallyDrop}; use std::mem::{self, ManuallyDrop};
use std::prelude::v1::*; use std::prelude::v1::*;
use convert::*; use crate::convert::*;
use describe::*; use crate::describe::*;
use throw_str; use crate::throw_str;
use JsValue; use crate::JsValue;
use UnwrapThrowExt; use crate::UnwrapThrowExt;
/// A handle to both a closure in Rust as well as JS closure which will invoke /// A handle to both a closure in Rust as well as JS closure which will invoke
/// the Rust closure. /// the Rust closure.
@ -642,7 +642,7 @@ macro_rules! doit {
fn into_js_function(self) -> JsValue { fn into_js_function(self) -> JsValue {
use std::rc::Rc; use std::rc::Rc;
use __rt::WasmRefCell; use crate::__rt::WasmRefCell;
let mut me = Some(self); let mut me = Some(self);

View File

@ -1,9 +1,9 @@
use core::mem; use core::mem;
use convert::slices::WasmSlice; use crate::convert::slices::WasmSlice;
use convert::{FromWasmAbi, GlobalStack, IntoWasmAbi, ReturnWasmAbi, Stack}; use crate::convert::{FromWasmAbi, GlobalStack, IntoWasmAbi, ReturnWasmAbi, Stack};
use describe::{inform, WasmDescribe, FUNCTION}; use crate::describe::{inform, WasmDescribe, FUNCTION};
use throw_str; use crate::throw_str;
macro_rules! stack_closures { macro_rules! stack_closures {
($( ($cnt:tt $invoke:ident $invoke_mut:ident $($var:ident)*) )*) => ($( ($( ($cnt:tt $invoke:ident $invoke_mut:ident $($var:ident)*) )*) => ($(

View File

@ -1,10 +1,10 @@
use core::char; use core::char;
use core::mem::{self, ManuallyDrop}; use core::mem::{self, ManuallyDrop};
use convert::traits::WasmAbi; use crate::convert::traits::WasmAbi;
use convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi, Stack}; use crate::convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi, Stack};
use convert::{OptionFromWasmAbi, OptionIntoWasmAbi, ReturnWasmAbi}; use crate::convert::{OptionFromWasmAbi, OptionIntoWasmAbi, ReturnWasmAbi};
use {Clamped, JsValue}; use crate::{Clamped, JsValue};
unsafe impl WasmAbi for () {} unsafe impl WasmAbi for () {}
@ -414,7 +414,7 @@ impl<T: IntoWasmAbi> ReturnWasmAbi for Result<T, JsValue> {
fn return_abi(self, extra: &mut Stack) -> Self::Abi { fn return_abi(self, extra: &mut Stack) -> Self::Abi {
match self { match self {
Ok(v) => v.into_abi(extra), Ok(v) => v.into_abi(extra),
Err(e) => ::throw_val(e), Err(e) => crate::throw_val(e),
} }
} }
} }

View File

@ -23,7 +23,7 @@ impl GlobalStack {
impl Stack for GlobalStack { impl Stack for GlobalStack {
#[inline] #[inline]
fn push(&mut self, val: u32) { fn push(&mut self, val: u32) {
use __rt::{__wbindgen_global_argument_ptr as global_ptr, GLOBAL_STACK_CAP}; use crate::__rt::{__wbindgen_global_argument_ptr as global_ptr, GLOBAL_STACK_CAP};
unsafe { unsafe {
assert!(self.next < GLOBAL_STACK_CAP); assert!(self.next < GLOBAL_STACK_CAP);
*global_ptr().offset(self.next as isize) = val; *global_ptr().offset(self.next as isize) = val;

View File

@ -4,12 +4,12 @@ use std::prelude::v1::*;
use core::slice; use core::slice;
use core::str; use core::str;
use convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi, RefMutFromWasmAbi, WasmAbi}; use crate::convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi, RefMutFromWasmAbi, WasmAbi};
use convert::{OptionIntoWasmAbi, Stack}; use crate::convert::{OptionIntoWasmAbi, Stack};
if_std! { if_std! {
use core::mem; use core::mem;
use convert::OptionFromWasmAbi; use crate::convert::OptionFromWasmAbi;
} }
#[repr(C)] #[repr(C)]
@ -204,7 +204,7 @@ impl RefFromWasmAbi for str {
} }
if_std! { if_std! {
use JsValue; use crate::JsValue;
impl IntoWasmAbi for Box<[JsValue]> { impl IntoWasmAbi for Box<[JsValue]> {
type Abi = WasmSlice; type Abi = WasmSlice;

View File

@ -1,6 +1,6 @@
use core::ops::{Deref, DerefMut}; use core::ops::{Deref, DerefMut};
use describe::*; use crate::describe::*;
/// A trait for anything that can be converted into a type that can cross the /// A trait for anything that can be converted into a type that can cross the
/// wasm ABI directly, eg `u32` or `f64`. /// wasm ABI directly, eg `u32` or `f64`.

View File

@ -3,7 +3,7 @@
#![doc(hidden)] #![doc(hidden)]
use {Clamped, JsValue}; use crate::{Clamped, JsValue};
macro_rules! tys { macro_rules! tys {
($($a:ident)*) => (tys! { @ ($($a)*) 0 }); ($($a:ident)*) => (tys! { @ ($($a)*) 0 });

View File

@ -9,20 +9,13 @@
#![doc(html_root_url = "https://docs.rs/wasm-bindgen/0.2")] #![doc(html_root_url = "https://docs.rs/wasm-bindgen/0.2")]
#![cfg_attr(feature = "nightly", feature(unsize))] #![cfg_attr(feature = "nightly", feature(unsize))]
#[cfg(feature = "serde-serialize")]
extern crate serde;
#[cfg(feature = "serde-serialize")]
extern crate serde_json;
extern crate wasm_bindgen_macro;
use core::fmt; use core::fmt;
use core::marker; use core::marker;
use core::mem; use core::mem;
use core::ops::{Deref, DerefMut}; use core::ops::{Deref, DerefMut};
use core::ptr; use core::ptr;
use convert::FromWasmAbi; use crate::convert::FromWasmAbi;
macro_rules! if_std { macro_rules! if_std {
($($i:item)*) => ($( ($($i:item)*) => ($(
@ -54,14 +47,14 @@ macro_rules! externs {
/// use wasm_bindgen::prelude::*; /// use wasm_bindgen::prelude::*;
/// ``` /// ```
pub mod prelude { pub mod prelude {
pub use crate::JsValue;
pub use crate::UnwrapThrowExt;
#[doc(hidden)] #[doc(hidden)]
pub use wasm_bindgen_macro::__wasm_bindgen_class_marker; pub use wasm_bindgen_macro::__wasm_bindgen_class_marker;
pub use wasm_bindgen_macro::wasm_bindgen; pub use wasm_bindgen_macro::wasm_bindgen;
pub use JsValue;
pub use UnwrapThrowExt;
if_std! { if_std! {
pub use closure::Closure; pub use crate::closure::Closure;
} }
} }
@ -69,7 +62,7 @@ pub mod convert;
pub mod describe; pub mod describe;
mod cast; mod cast;
pub use cast::JsCast; pub use crate::cast::JsCast;
if_std! { if_std! {
extern crate std; extern crate std;
@ -1002,7 +995,7 @@ pub mod __rt {
/// ///
/// Ideas for how to improve this are most welcome! /// Ideas for how to improve this are most welcome!
pub fn link_mem_intrinsics() { pub fn link_mem_intrinsics() {
::anyref::link_intrinsics(); crate::anyref::link_intrinsics();
} }
} }

View File

@ -2,14 +2,14 @@ use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*; use wasm_bindgen_test::*;
#[wasm_bindgen(module = "/tests/headless/snippets1.js")] #[wasm_bindgen(module = "/tests/headless/snippets1.js")]
extern { extern "C" {
fn get_two() -> u32; fn get_two() -> u32;
#[wasm_bindgen(js_name = get_stateful)] #[wasm_bindgen(js_name = get_stateful)]
fn get_stateful1() -> u32; fn get_stateful1() -> u32;
} }
#[wasm_bindgen(module = "/tests/headless/snippets1.js")] #[wasm_bindgen(module = "/tests/headless/snippets1.js")]
extern { extern "C" {
#[wasm_bindgen(js_name = get_stateful)] #[wasm_bindgen(js_name = get_stateful)]
fn get_stateful2() -> u32; fn get_stateful2() -> u32;
} }
@ -28,7 +28,7 @@ fn stateful_deduplicated() {
} }
#[wasm_bindgen(inline_js = "export function get_three() { return 3; }")] #[wasm_bindgen(inline_js = "export function get_three() { return 3; }")]
extern { extern "C" {
fn get_three() -> u32; fn get_three() -> u32;
} }
@ -38,13 +38,13 @@ fn test_get_three() {
} }
#[wasm_bindgen(inline_js = "let a = 0; export function get() { a += 1; return a; }")] #[wasm_bindgen(inline_js = "let a = 0; export function get() { a += 1; return a; }")]
extern { extern "C" {
#[wasm_bindgen(js_name = get)] #[wasm_bindgen(js_name = get)]
fn duplicate1() -> u32; fn duplicate1() -> u32;
} }
#[wasm_bindgen(inline_js = "let a = 0; export function get() { a += 1; return a; }")] #[wasm_bindgen(inline_js = "let a = 0; export function get() { a += 1; return a; }")]
extern { extern "C" {
#[wasm_bindgen(js_name = get)] #[wasm_bindgen(js_name = get)]
fn duplicate2() -> u32; fn duplicate2() -> u32;
} }

View File

@ -19,7 +19,7 @@ extern "C" {
#[wasm_bindgen(constructor)] #[wasm_bindgen(constructor)]
fn new() -> JsCast3; fn new() -> JsCast3;
#[wasm_bindgen(extends = ::jscast::JsCast1, extends = JsCast3)] #[wasm_bindgen(extends = crate::jscast::JsCast1, extends = JsCast3)]
type JsCast4; type JsCast4;
#[wasm_bindgen(constructor)] #[wasm_bindgen(constructor)]
fn new() -> JsCast4; fn new() -> JsCast4;