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.
idx + info.code_idx_to_descriptor.len() as u32
}
}).remap_module(input.module);
})
.remap_module(input.module);
info.delete_function_table_entries(input);
info.inject_imports(input)?;
@ -263,9 +264,7 @@ impl ClosureDescriptors {
real.original = cb;
return addHeapObject(real);
}}",
closure.shim_idx,
closure.dtor_idx,
js,
closure.shim_idx, closure.dtor_idx, js,
);
input.export(&import_name, &body, None);

View File

@ -177,7 +177,7 @@ impl<'a> Context<'a> {
function(idx) {
return addHeapObject(getObject(idx));
}
"
",
))
})?;
@ -424,9 +424,7 @@ impl<'a> Context<'a> {
Ok(String::from("function(idx) { throw takeObject(idx); }"))
})?;
closures::rewrite(self).with_context(|_| {
"failed to generate internal closure shims"
})?;
closures::rewrite(self).with_context(|_| "failed to generate internal closure shims")?;
self.unexport_unused_internal_exports();
// 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;
return stack_pointer;
}
"
",
);
}
@ -2067,7 +2065,9 @@ impl<'a> Context<'a> {
None => return Ok(()),
};
let idx = {
let exports = self.module.export_section()
let exports = self
.module
.export_section()
.ok_or_else(|| format_err!("no export section found"))?;
let entry = exports
.entries()
@ -2082,13 +2082,20 @@ impl<'a> Context<'a> {
if let Some(prev_start) = self.module.start_section() {
if let Some(NameSection::Function(n)) = self.module.names_section() {
if let Some(prev) = n.names().get(prev_start) {
bail!("cannot flag `{}` as start function as `{}` is \
already the start function", start, prev);
bail!(
"cannot flag `{}` as start function as `{}` is \
already the start function",
start,
prev
);
}
}
bail!("cannot flag `{}` as start function as another \
function is already the start function", start);
bail!(
"cannot flag `{}` as start function as another \
function is already the start function",
start
);
}
self.set_start_section(idx);
@ -2101,21 +2108,23 @@ impl<'a> Context<'a> {
// for section ordering
for (i, section) in self.module.sections().iter().enumerate() {
match section {
Section::Type(_) |
Section::Import(_) |
Section::Function(_) |
Section::Table(_) |
Section::Memory(_) |
Section::Global(_) |
Section::Export(_) => continue,
Section::Type(_)
| Section::Import(_)
| Section::Function(_)
| Section::Table(_)
| Section::Memory(_)
| Section::Global(_)
| Section::Export(_) => continue,
_ => {
pos = Some(i);
break
break;
}
}
}
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
@ -2134,11 +2143,13 @@ impl<'a> Context<'a> {
match pos {
Some(i) => {
self.module.sections_mut().remove(i);
let entry = ExportEntry::new(
"__wbindgen_start".to_string(),
Internal::Function(start),
);
self.module.export_section_mut().unwrap().entries_mut().push(entry);
let entry =
ExportEntry::new("__wbindgen_start".to_string(), Internal::Function(start));
self.module
.export_section_mut()
.unwrap()
.entries_mut()
.push(entry);
true
}
None => false,
@ -2156,12 +2167,12 @@ impl<'a> Context<'a> {
}";
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)
.unwrap_or(0);
Remap(|idx| {
if idx < imports { idx } else { idx + 1 }
}).remap_module(self.module);
Remap(|idx| if idx < imports { idx } else { idx + 1 }).remap_module(self.module);
let type_idx = {
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() {
self.generate_struct(s).with_context(|_| {
format!(
"failed to generate bindings for Rust struct `{}`",
s.name,
)
format!("failed to generate bindings for Rust struct `{}`", s.name,)
})?;
}
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> {
if let Some(prev) = &self.cx.start {
bail!("cannot flag `{}` as start function as `{}` is \
already the start function", start, prev);
bail!(
"cannot flag `{}` as start function as `{}` is \
already the start function",
start,
prev
);
}
self.cx.start = Some(start.to_string());
Ok(())

View File

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

View File

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

View File

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

View File

@ -4,7 +4,10 @@ use parity_wasm::elements::*;
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) {
for section in module.sections_mut() {
match section {

View File

@ -155,7 +155,8 @@ fn rmain() -> Result<(), Error> {
&tmpdir,
&args.collect::<Vec<_>>(),
&tests,
).context("failed to spawn server")?;
)
.context("failed to spawn server")?;
let addr = srv.server_addr();
// 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 wasm = wasm.unwrap();
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!
let tmpdir = tmpdir.to_path_buf();

View File

@ -83,19 +83,16 @@ fn rmain(args: &Args) -> Result<(), Error> {
Ok(())
}
fn write(
args: &Args,
extension: &str,
contents: &[u8],
print_fallback: bool,
) -> Result<(), Error> {
fn write(args: &Args, extension: &str, contents: &[u8], print_fallback: bool) -> Result<(), Error> {
if let Some(p) = &args.flag_output {
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 {
let filename = args.arg_input.file_name().unwrap();
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 {
println!("{}", String::from_utf8_lossy(contents))
}

View File

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

View File

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