Run rustfmt

This commit is contained in:
Alex Crichton 2018-11-30 13:04:05 -08:00
parent 13d9e47d17
commit 29531c0abf
11 changed files with 106 additions and 103 deletions

View File

@ -53,7 +53,8 @@ pub fn rewrite(input: &mut Context) -> Result<(), Error> {
// everything. // everything.
idx + info.code_idx_to_descriptor.len() as u32 idx + info.code_idx_to_descriptor.len() as u32
} }
}).remap_module(input.module); })
.remap_module(input.module);
info.delete_function_table_entries(input); info.delete_function_table_entries(input);
info.inject_imports(input)?; info.inject_imports(input)?;
@ -263,9 +264,7 @@ impl ClosureDescriptors {
real.original = cb; real.original = cb;
return addHeapObject(real); return addHeapObject(real);
}}", }}",
closure.shim_idx, closure.shim_idx, closure.dtor_idx, js,
closure.dtor_idx,
js,
); );
input.export(&import_name, &body, None); input.export(&import_name, &body, None);

View File

@ -177,7 +177,7 @@ impl<'a> Context<'a> {
function(idx) { function(idx) {
return addHeapObject(getObject(idx)); return addHeapObject(getObject(idx));
} }
" ",
)) ))
})?; })?;
@ -424,9 +424,7 @@ impl<'a> Context<'a> {
Ok(String::from("function(idx) { throw takeObject(idx); }")) Ok(String::from("function(idx) { throw takeObject(idx); }"))
})?; })?;
closures::rewrite(self).with_context(|_| { closures::rewrite(self).with_context(|_| "failed to generate internal closure shims")?;
"failed to generate internal closure shims"
})?;
self.unexport_unused_internal_exports(); self.unexport_unused_internal_exports();
// Handle the `start` function, if one was specified. If we're in a // Handle the `start` function, if one was specified. If we're in a
@ -1405,7 +1403,7 @@ impl<'a> Context<'a> {
heap[--stack_pointer] = obj; heap[--stack_pointer] = obj;
return stack_pointer; return stack_pointer;
} }
" ",
); );
} }
@ -2067,7 +2065,9 @@ impl<'a> Context<'a> {
None => return Ok(()), None => return Ok(()),
}; };
let idx = { let idx = {
let exports = self.module.export_section() let exports = self
.module
.export_section()
.ok_or_else(|| format_err!("no export section found"))?; .ok_or_else(|| format_err!("no export section found"))?;
let entry = exports let entry = exports
.entries() .entries()
@ -2082,13 +2082,20 @@ impl<'a> Context<'a> {
if let Some(prev_start) = self.module.start_section() { if let Some(prev_start) = self.module.start_section() {
if let Some(NameSection::Function(n)) = self.module.names_section() { if let Some(NameSection::Function(n)) = self.module.names_section() {
if let Some(prev) = n.names().get(prev_start) { if let Some(prev) = n.names().get(prev_start) {
bail!("cannot flag `{}` as start function as `{}` is \ bail!(
already the start function", start, prev); "cannot flag `{}` as start function as `{}` is \
already the start function",
start,
prev
);
} }
} }
bail!("cannot flag `{}` as start function as another \ bail!(
function is already the start function", start); "cannot flag `{}` as start function as another \
function is already the start function",
start
);
} }
self.set_start_section(idx); self.set_start_section(idx);
@ -2101,21 +2108,23 @@ impl<'a> Context<'a> {
// for section ordering // for section ordering
for (i, section) in self.module.sections().iter().enumerate() { for (i, section) in self.module.sections().iter().enumerate() {
match section { match section {
Section::Type(_) | Section::Type(_)
Section::Import(_) | | Section::Import(_)
Section::Function(_) | | Section::Function(_)
Section::Table(_) | | Section::Table(_)
Section::Memory(_) | | Section::Memory(_)
Section::Global(_) | | Section::Global(_)
Section::Export(_) => continue, | Section::Export(_) => continue,
_ => { _ => {
pos = Some(i); pos = Some(i);
break break;
} }
} }
} }
let pos = pos.unwrap_or(self.module.sections().len() - 1); let pos = pos.unwrap_or(self.module.sections().len() - 1);
self.module.sections_mut().insert(pos, Section::Start(start)); self.module
.sections_mut()
.insert(pos, Section::Start(start));
} }
/// If a start function is present, it removes it from the `start` section /// If a start function is present, it removes it from the `start` section
@ -2134,11 +2143,13 @@ impl<'a> Context<'a> {
match pos { match pos {
Some(i) => { Some(i) => {
self.module.sections_mut().remove(i); self.module.sections_mut().remove(i);
let entry = ExportEntry::new( let entry =
"__wbindgen_start".to_string(), ExportEntry::new("__wbindgen_start".to_string(), Internal::Function(start));
Internal::Function(start), self.module
); .export_section_mut()
self.module.export_section_mut().unwrap().entries_mut().push(entry); .unwrap()
.entries_mut()
.push(entry);
true true
} }
None => false, None => false,
@ -2156,12 +2167,12 @@ impl<'a> Context<'a> {
}"; }";
self.export("__wbindgen_defer_start", body, None); self.export("__wbindgen_defer_start", body, None);
let imports = self.module.import_section() let imports = self
.module
.import_section()
.map(|s| s.functions() as u32) .map(|s| s.functions() as u32)
.unwrap_or(0); .unwrap_or(0);
Remap(|idx| { Remap(|idx| if idx < imports { idx } else { idx + 1 }).remap_module(self.module);
if idx < imports { idx } else { idx + 1 }
}).remap_module(self.module);
let type_idx = { let type_idx = {
let types = self.module.type_section_mut().unwrap(); let types = self.module.type_section_mut().unwrap();
@ -2207,10 +2218,7 @@ impl<'a, 'b> SubContext<'a, 'b> {
} }
for s in self.program.structs.iter() { for s in self.program.structs.iter() {
self.generate_struct(s).with_context(|_| { self.generate_struct(s).with_context(|_| {
format!( format!("failed to generate bindings for Rust struct `{}`", s.name,)
"failed to generate bindings for Rust struct `{}`",
s.name,
)
})?; })?;
} }
for s in self.program.typescript_custom_sections.iter() { for s in self.program.typescript_custom_sections.iter() {
@ -2253,8 +2261,12 @@ impl<'a, 'b> SubContext<'a, 'b> {
fn set_start_function(&mut self, start: &str) -> Result<(), Error> { fn set_start_function(&mut self, start: &str) -> Result<(), Error> {
if let Some(prev) = &self.cx.start { if let Some(prev) = &self.cx.start {
bail!("cannot flag `{}` as start function as `{}` is \ bail!(
already the start function", start, prev); "cannot flag `{}` as start function as `{}` is \
already the start function",
start,
prev
);
} }
self.cx.start = Some(start.to_string()); self.cx.start = Some(start.to_string());
Ok(()) Ok(())

View File

@ -560,12 +560,10 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
&format!("{}({}, ...{})", invoc, args.join(", "), last_arg), &format!("{}({}, ...{})", invoc, args.join(", "), last_arg),
) )
} else { } else {
ret_expr ret_expr.replace("JS", &format!("{}(...{})", invoc, last_arg))
.replace("JS", &format!("{}(...{})", invoc, last_arg))
} }
} else { } else {
ret_expr ret_expr.replace("JS", &format!("{}({})", invoc, js_arguments.join(", ")))
.replace("JS", &format!("{}({})", invoc, js_arguments.join(", ")))
}; };
Ok(ret) Ok(ret)
}; };
@ -575,9 +573,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
bail!("{} cannot be variadic", desc); bail!("{} cannot be variadic", desc);
} }
match (class, js_arguments.len()) { match (class, js_arguments.len()) {
(None, n) if n == amt + 1 => { (None, n) if n == amt + 1 => Ok((js_arguments[0].clone(), &js_arguments[1..])),
Ok((js_arguments[0].clone(), &js_arguments[1..]))
}
(None, _) => bail!("setters must have {} arguments", amt + 1), (None, _) => bail!("setters must have {} arguments", amt + 1),
(Some(class), n) if n == amt => Ok((class.clone(), &js_arguments[..])), (Some(class), n) if n == amt => Ok((class.clone(), &js_arguments[..])),
(Some(_), _) => bail!("static setters must have {} arguments", amt), (Some(_), _) => bail!("static setters must have {} arguments", amt),

View File

@ -22,8 +22,8 @@ use parity_wasm::elements::*;
mod decode; mod decode;
mod descriptor; mod descriptor;
mod js; mod js;
mod wasm_utils;
pub mod wasm2es6js; pub mod wasm2es6js;
mod wasm_utils;
pub struct Bindgen { pub struct Bindgen {
input: Input, input: Input,

View File

@ -58,20 +58,17 @@ pub fn typescript(module: &Module) -> String {
.unwrap_or(0); .unwrap_or(0);
for entry in i.entries() { for entry in i.entries() {
let idx = match *entry.internal() { let idx = match *entry.internal() {
Internal::Function(i) if i < imported_functions => { Internal::Function(i) if i < imported_functions => *module
*module.import_section() .import_section()
.unwrap() .unwrap()
.entries() .entries()
.iter() .iter()
.filter_map(|f| { .filter_map(|f| match f.external() {
match f.external() { External::Function(i) => Some(i),
External::Function(i) => Some(i), _ => None,
_ => None, })
} .nth(i as usize)
}) .unwrap(),
.nth(i as usize)
.unwrap()
}
Internal::Function(i) => { Internal::Function(i) => {
let idx = i - imported_functions; let idx = i - imported_functions;
let functions = module let functions = module
@ -96,9 +93,7 @@ pub fn typescript(module: &Module) -> String {
Internal::Global(_) => continue, Internal::Global(_) => continue,
}; };
let types = module let types = module.type_section().expect("failed to find type section");
.type_section()
.expect("failed to find type section");
let ty = match types.types()[idx as usize] { let ty = match types.types()[idx as usize] {
Type::Function(ref f) => f, Type::Function(ref f) => f,
}; };
@ -133,7 +128,7 @@ impl Output {
if self.base64 { if self.base64 {
ts.push_str("export const booted: Promise<boolean>;\n"); ts.push_str("export const booted: Promise<boolean>;\n");
} }
return ts return ts;
} }
pub fn js_and_wasm(mut self) -> Result<(String, Option<Vec<u8>>), Error> { pub fn js_and_wasm(mut self) -> Result<(String, Option<Vec<u8>>), Error> {
@ -259,7 +254,7 @@ impl Output {
fn unstart(&mut self) -> bool { fn unstart(&mut self) -> bool {
let mut start = None; let mut start = None;
for (i, section) in self.module.sections().iter().enumerate() { for (i, section) in self.module.sections().iter().enumerate() {
if let Section::Start(idx) = section { if let Section::Start(idx) = section {
start = Some((i, *idx)); start = Some((i, *idx));
break; break;
} }
@ -269,11 +264,12 @@ impl Output {
None => return false, None => return false,
}; };
self.module.sections_mut().remove(i); self.module.sections_mut().remove(i);
let entry = ExportEntry::new( let entry = ExportEntry::new("__wasm2es6js_start".to_string(), Internal::Function(idx));
"__wasm2es6js_start".to_string(), self.module
Internal::Function(idx), .export_section_mut()
); .unwrap()
self.module.export_section_mut().unwrap().entries_mut().push(entry); .entries_mut()
.push(entry);
true true
} }
} }

View File

@ -4,7 +4,10 @@ use parity_wasm::elements::*;
pub struct Remap<F>(pub F); pub struct Remap<F>(pub F);
impl<F> Remap<F> where F: FnMut(u32) -> u32 { impl<F> Remap<F>
where
F: FnMut(u32) -> u32,
{
pub fn remap_module(&mut self, module: &mut Module) { pub fn remap_module(&mut self, module: &mut Module) {
for section in module.sections_mut() { for section in module.sections_mut() {
match section { match section {

View File

@ -155,7 +155,8 @@ fn rmain() -> Result<(), Error> {
&tmpdir, &tmpdir,
&args.collect::<Vec<_>>(), &args.collect::<Vec<_>>(),
&tests, &tests,
).context("failed to spawn server")?; )
.context("failed to spawn server")?;
let addr = srv.server_addr(); let addr = srv.server_addr();
// TODO: eventually we should provide the ability to exit at some point // TODO: eventually we should provide the ability to exit at some point

View File

@ -71,7 +71,8 @@ pub fn spawn(
let (js, wasm) = output.js_and_wasm()?; let (js, wasm) = output.js_and_wasm()?;
let wasm = wasm.unwrap(); let wasm = wasm.unwrap();
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")?;
fs::write(tmpdir.join(format!("{}_bg.wasm", module)), wasm).context("failed to write wasm file")?; fs::write(tmpdir.join(format!("{}_bg.wasm", module)), wasm)
.context("failed to write wasm file")?;
// For now, always run forever on this port. We may update this later! // For now, always run forever on this port. We may update this later!
let tmpdir = tmpdir.to_path_buf(); let tmpdir = tmpdir.to_path_buf();

View File

@ -83,19 +83,16 @@ fn rmain(args: &Args) -> Result<(), Error> {
Ok(()) Ok(())
} }
fn write( fn write(args: &Args, extension: &str, contents: &[u8], print_fallback: bool) -> Result<(), Error> {
args: &Args,
extension: &str,
contents: &[u8],
print_fallback: bool,
) -> Result<(), Error> {
if let Some(p) = &args.flag_output { if let Some(p) = &args.flag_output {
let dst = p.with_extension(extension); let dst = p.with_extension(extension);
fs::write(&dst, contents).with_context(|_| format!("failed to write `{}`", dst.display()))?; fs::write(&dst, contents)
.with_context(|_| format!("failed to write `{}`", dst.display()))?;
} else if let Some(p) = &args.flag_out_dir { } else if let Some(p) = &args.flag_out_dir {
let filename = args.arg_input.file_name().unwrap(); let filename = args.arg_input.file_name().unwrap();
let dst = p.join(filename).with_extension(extension); let dst = p.join(filename).with_extension(extension);
fs::write(&dst, contents).with_context(|_| format!("failed to write `{}`", dst.display()))?; fs::write(&dst, contents)
.with_context(|_| format!("failed to write `{}`", dst.display()))?;
} else if print_fallback { } else if print_fallback {
println!("{}", String::from_utf8_lossy(contents)) println!("{}", String::from_utf8_lossy(contents))
} }

View File

@ -25,7 +25,7 @@ pub struct BindgenAttrs {
} }
macro_rules! attrgen { macro_rules! attrgen {
($mac:ident) => ( ($mac:ident) => {
$mac! { $mac! {
(catch, Catch(Span)), (catch, Catch(Span)),
(constructor, Constructor(Span)), (constructor, Constructor(Span)),
@ -49,7 +49,7 @@ macro_rules! attrgen {
(typescript_custom_section, TypescriptCustomSection(Span)), (typescript_custom_section, TypescriptCustomSection(Span)),
(start, Start(Span)), (start, Start(Span)),
} }
) };
} }
macro_rules! methods { macro_rules! methods {
@ -175,14 +175,11 @@ impl Parse for BindgenAttrs {
fn parse(input: ParseStream) -> SynResult<Self> { fn parse(input: ParseStream) -> SynResult<Self> {
let mut attrs = BindgenAttrs::default(); let mut attrs = BindgenAttrs::default();
if input.is_empty() { if input.is_empty() {
return Ok(attrs) return Ok(attrs);
} }
let opts = syn::punctuated::Punctuated::<_, syn::token::Comma>::parse_terminated(input)?; let opts = syn::punctuated::Punctuated::<_, syn::token::Comma>::parse_terminated(input)?;
attrs.attrs = opts attrs.attrs = opts.into_iter().map(|c| (Cell::new(false), c)).collect();
.into_iter()
.map(|c| (Cell::new(false), c))
.collect();
Ok(attrs) Ok(attrs)
} }
} }
@ -487,7 +484,7 @@ impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemFn
if let Some(span) = opts.final_() { if let Some(span) = opts.final_() {
if opts.structural().is_some() { if opts.structural().is_some() {
let msg = "cannot specify both `structural` and `final`"; let msg = "cannot specify both `structural` and `final`";
return Err(Diagnostic::span_error(*span, msg)) return Err(Diagnostic::span_error(*span, msg));
} }
} }
let ret = ast::ImportKind::Function(ast::ImportFunction { let ret = ast::ImportKind::Function(ast::ImportFunction {
@ -558,7 +555,11 @@ impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemSt
} }
assert_not_variadic(&opts)?; assert_not_variadic(&opts)?;
let default_name = self.ident.to_string(); let default_name = self.ident.to_string();
let js_name = opts.js_name().map(|p| p.0).unwrap_or(&default_name).to_string(); let js_name = opts
.js_name()
.map(|p| p.0)
.unwrap_or(&default_name)
.to_string();
let shim = format!( let shim = format!(
"__wbg_static_accessor_{}_{}", "__wbg_static_accessor_{}_{}",
self.ident, self.ident,
@ -733,16 +734,10 @@ impl<'a> MacroParse<(Option<BindgenAttrs>, &'a mut TokenStream)> for syn::Item {
let opts = opts.unwrap_or_default(); let opts = opts.unwrap_or_default();
if opts.start().is_some() { if opts.start().is_some() {
if f.decl.generics.params.len() > 0 { if f.decl.generics.params.len() > 0 {
bail_span!( bail_span!(&f.decl.generics, "the start function cannot have generics",);
&f.decl.generics,
"the start function cannot have generics",
);
} }
if f.decl.inputs.len() > 0 { if f.decl.inputs.len() > 0 {
bail_span!( bail_span!(&f.decl.inputs, "the start function cannot have arguments",);
&f.decl.inputs,
"the start function cannot have arguments",
);
} }
} }
program.exports.push(ast::Export { program.exports.push(ast::Export {
@ -1043,7 +1038,10 @@ impl<'a> MacroParse<&'a BindgenAttrs> for syn::ForeignItem {
}; };
BindgenAttrs::find(attrs)? BindgenAttrs::find(attrs)?
}; };
let module = item_opts.module().or(opts.module()).map(|s| s.0.to_string()); let module = item_opts
.module()
.or(opts.module())
.map(|s| s.0.to_string());
let js_namespace = item_opts.js_namespace().or(opts.js_namespace()).cloned(); let js_namespace = item_opts.js_namespace().or(opts.js_namespace()).cloned();
let kind = match self { let kind = match self {
syn::ForeignItem::Fn(f) => f.convert((item_opts, &module))?, syn::ForeignItem::Fn(f) => f.convert((item_opts, &module))?,
@ -1156,8 +1154,8 @@ fn assert_no_lifetimes(decl: &syn::FnDecl) -> Result<(), Diagnostic> {
fn assert_not_variadic(attrs: &BindgenAttrs) -> Result<(), Diagnostic> { fn assert_not_variadic(attrs: &BindgenAttrs) -> Result<(), Diagnostic> {
if let Some(span) = attrs.variadic() { if let Some(span) = attrs.variadic() {
let msg = "the `variadic` attribute can only be applied to imported \ let msg = "the `variadic` attribute can only be applied to imported \
(`extern`) functions"; (`extern`) functions";
return Err(Diagnostic::span_error(*span, msg)) return Err(Diagnostic::span_error(*span, msg));
} }
Ok(()) Ok(())
} }

View File

@ -1,8 +1,8 @@
use core::mem; use core::mem;
use convert::{FromWasmAbi, GlobalStack, IntoWasmAbi, ReturnWasmAbi, Stack};
use convert::slices::WasmSlice; use convert::slices::WasmSlice;
use describe::{inform, FUNCTION, WasmDescribe}; use convert::{FromWasmAbi, GlobalStack, IntoWasmAbi, ReturnWasmAbi, Stack};
use describe::{inform, WasmDescribe, FUNCTION};
use throw_str; use throw_str;
macro_rules! stack_closures { macro_rules! stack_closures {