cargo fmt

This commit is contained in:
Bo Yao
2021-04-21 15:42:47 -07:00
parent 2eac442646
commit 24bcc9349e
224 changed files with 2778 additions and 7749 deletions

View File

@@ -83,9 +83,7 @@ pub trait Compiler: Send + MemoryUsage {
deterministic_only: false,
};
validator.wasm_features(wasm_features);
validator
.validate_all(data)
.map_err(|e| CompileError::Validate(format!("{}", e)))?;
validator.validate_all(data).map_err(|e| CompileError::Validate(format!("{}", e)))?;
Ok(())
}

View File

@@ -62,10 +62,7 @@ pub struct MiddlewareError {
impl MiddlewareError {
/// Create a new `MiddlewareError`
pub fn new<A: Into<String>, B: Into<String>>(name: A, message: B) -> Self {
Self {
name: name.into(),
message: message.into(),
}
Self { name: name.into(), message: message.into() }
}
}

View File

@@ -242,9 +242,7 @@ impl<'a> IntoIterator for &'a Compilation {
type Item = <Self::IntoIter as Iterator>::Item;
fn into_iter(self) -> Self::IntoIter {
Iter {
iterator: self.functions.iter(),
}
Iter { iterator: self.functions.iter() }
}
}

View File

@@ -15,10 +15,7 @@ use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle};
/// or the `MemoryStyle` and `TableStyle`).
#[derive(Debug, MemoryUsage, PartialEq, Eq)]
#[cfg_attr(feature = "enable-serde", derive(Deserialize, Serialize))]
#[cfg_attr(
feature = "enable-rkyv",
derive(RkyvSerialize, RkyvDeserialize, Archive)
)]
#[cfg_attr(feature = "enable-rkyv", derive(RkyvSerialize, RkyvDeserialize, Archive))]
pub struct CompileModuleInfo {
/// The features used for compiling the module
pub features: Features,

View File

@@ -116,9 +116,7 @@ impl Relocation {
RelocationKind::Abs8 => {
let reloc_address = start + self.offset as usize;
let reloc_addend = self.addend as isize;
let reloc_abs = target_func_address
.checked_add(reloc_addend as u64)
.unwrap();
let reloc_abs = target_func_address.checked_add(reloc_addend as u64).unwrap();
(reloc_address, reloc_abs)
}
RelocationKind::X86PCRel4 => {

View File

@@ -16,11 +16,7 @@ use serde::{Deserialize, Serialize};
///
/// The default source location uses the all-ones bit pattern `!0`. It is used for instructions
/// that can't be given a real source location.
#[cfg_attr(
feature = "enable-serde",
derive(Serialize, Deserialize),
serde(transparent)
)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize), serde(transparent))]
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, MemoryUsage)]
pub struct SourceLoc(u32);

View File

@@ -172,10 +172,7 @@ pub struct Target {
impl Target {
/// Creates a new target given a triple
pub fn new(triple: Triple, cpu_features: EnumSet<CpuFeature>) -> Self {
Self {
triple,
cpu_features,
}
Self { triple, cpu_features }
}
/// The triple associated for the target.
@@ -192,9 +189,6 @@ impl Target {
/// The default for the Target will use the HOST as the triple
impl Default for Target {
fn default() -> Self {
Self {
triple: Triple::host(),
cpu_features: CpuFeature::for_host(),
}
Self { triple: Triple::host(), cpu_features: CpuFeature::for_host() }
}
}

View File

@@ -78,10 +78,7 @@ impl<'data> ModuleEnvironment<'data> {
}
pub(crate) fn declare_export(&mut self, export: ExportIndex, name: &str) -> WasmResult<()> {
self.result
.module
.exports
.insert(String::from(name), export);
self.result.module.exports.insert(String::from(name), export);
Ok(())
}
@@ -91,18 +88,15 @@ impl<'data> ModuleEnvironment<'data> {
module: &str,
field: &str,
) -> WasmResult<()> {
self.result.module.imports.insert(
(String::from(module), String::from(field), self.imports),
import,
);
self.result
.module
.imports
.insert((String::from(module), String::from(field), self.imports), import);
Ok(())
}
pub(crate) fn reserve_signatures(&mut self, num: u32) -> WasmResult<()> {
self.result
.module
.signatures
.reserve_exact(usize::try_from(num).unwrap());
self.result.module.signatures.reserve_exact(usize::try_from(num).unwrap());
Ok(())
}
@@ -148,9 +142,7 @@ impl<'data> ModuleEnvironment<'data> {
"Imported tables must be declared first"
);
self.declare_import(
ImportIndex::Table(TableIndex::from_u32(
self.result.module.num_imported_tables as _,
)),
ImportIndex::Table(TableIndex::from_u32(self.result.module.num_imported_tables as _)),
module,
field,
)?;
@@ -213,13 +205,8 @@ impl<'data> ModuleEnvironment<'data> {
}
pub(crate) fn reserve_func_types(&mut self, num: u32) -> WasmResult<()> {
self.result
.module
.functions
.reserve_exact(usize::try_from(num).unwrap());
self.result
.function_body_inputs
.reserve_exact(usize::try_from(num).unwrap());
self.result.module.functions.reserve_exact(usize::try_from(num).unwrap());
self.result.function_body_inputs.reserve_exact(usize::try_from(num).unwrap());
Ok(())
}
@@ -229,10 +216,7 @@ impl<'data> ModuleEnvironment<'data> {
}
pub(crate) fn reserve_tables(&mut self, num: u32) -> WasmResult<()> {
self.result
.module
.tables
.reserve_exact(usize::try_from(num).unwrap());
self.result.module.tables.reserve_exact(usize::try_from(num).unwrap());
Ok(())
}
@@ -242,28 +226,20 @@ impl<'data> ModuleEnvironment<'data> {
}
pub(crate) fn reserve_memories(&mut self, num: u32) -> WasmResult<()> {
self.result
.module
.memories
.reserve_exact(usize::try_from(num).unwrap());
self.result.module.memories.reserve_exact(usize::try_from(num).unwrap());
Ok(())
}
pub(crate) fn declare_memory(&mut self, memory: MemoryType) -> WasmResult<()> {
if memory.shared {
return Err(WasmError::Unsupported(
"shared memories are not supported yet".to_owned(),
));
return Err(WasmError::Unsupported("shared memories are not supported yet".to_owned()));
}
self.result.module.memories.push(memory);
Ok(())
}
pub(crate) fn reserve_globals(&mut self, num: u32) -> WasmResult<()> {
self.result
.module
.globals
.reserve_exact(usize::try_from(num).unwrap());
self.result.module.globals.reserve_exact(usize::try_from(num).unwrap());
Ok(())
}
@@ -278,10 +254,7 @@ impl<'data> ModuleEnvironment<'data> {
}
pub(crate) fn reserve_exports(&mut self, num: u32) -> WasmResult<()> {
self.result
.module
.exports
.reserve(usize::try_from(num).unwrap());
self.result.module.exports.reserve(usize::try_from(num).unwrap());
Ok(())
}
@@ -324,10 +297,7 @@ impl<'data> ModuleEnvironment<'data> {
}
pub(crate) fn reserve_table_initializers(&mut self, num: u32) -> WasmResult<()> {
self.result
.module
.table_initializers
.reserve_exact(usize::try_from(num).unwrap());
self.result.module.table_initializers.reserve_exact(usize::try_from(num).unwrap());
Ok(())
}
@@ -338,15 +308,12 @@ impl<'data> ModuleEnvironment<'data> {
offset: usize,
elements: Box<[FunctionIndex]>,
) -> WasmResult<()> {
self.result
.module
.table_initializers
.push(TableInitializer {
table_index,
base,
offset,
elements,
});
self.result.module.table_initializers.push(TableInitializer {
table_index,
base,
offset,
elements,
});
Ok(())
}
@@ -355,11 +322,7 @@ impl<'data> ModuleEnvironment<'data> {
elem_index: ElemIndex,
segments: Box<[FunctionIndex]>,
) -> WasmResult<()> {
let old = self
.result
.module
.passive_elements
.insert(elem_index, segments);
let old = self.result.module.passive_elements.insert(elem_index, segments);
debug_assert!(
old.is_none(),
"should never get duplicate element indices, that would be a bug in `wasmer_compiler`'s \
@@ -374,17 +337,14 @@ impl<'data> ModuleEnvironment<'data> {
body_bytes: &'data [u8],
body_offset: usize,
) -> WasmResult<()> {
self.result.function_body_inputs.push(FunctionBodyData {
data: body_bytes,
module_offset: body_offset,
});
self.result
.function_body_inputs
.push(FunctionBodyData { data: body_bytes, module_offset: body_offset });
Ok(())
}
pub(crate) fn reserve_data_initializers(&mut self, num: u32) -> WasmResult<()> {
self.result
.data_initializers
.reserve_exact(usize::try_from(num).unwrap());
self.result.data_initializers.reserve_exact(usize::try_from(num).unwrap());
Ok(())
}
@@ -396,11 +356,7 @@ impl<'data> ModuleEnvironment<'data> {
data: &'data [u8],
) -> WasmResult<()> {
self.result.data_initializers.push(DataInitializer {
location: DataInitializerLocation {
memory_index,
base,
offset,
},
location: DataInitializerLocation { memory_index, base, offset },
data,
});
Ok(())
@@ -417,11 +373,7 @@ impl<'data> ModuleEnvironment<'data> {
data_index: DataIndex,
data: &'data [u8],
) -> WasmResult<()> {
let old = self
.result
.module
.passive_data
.insert(data_index, Arc::from(data));
let old = self.result.module.passive_data.insert(data_index, Arc::from(data));
debug_assert!(
old.is_none(),
"a module can't have duplicate indices, this would be a wasmer-compiler bug"
@@ -439,10 +391,7 @@ impl<'data> ModuleEnvironment<'data> {
func_index: FunctionIndex,
name: &'data str,
) -> WasmResult<()> {
self.result
.module
.function_names
.insert(func_index, name.to_string());
self.result.module.function_names.insert(func_index, name.to_string());
Ok(())
}
@@ -460,21 +409,10 @@ impl<'data> ModuleEnvironment<'data> {
/// Indicates that a custom section has been found in the wasm file
pub(crate) fn custom_section(&mut self, name: &'data str, data: &'data [u8]) -> WasmResult<()> {
let custom_section = CustomSectionIndex::from_u32(
self.result
.module
.custom_sections_data
.len()
.try_into()
.unwrap(),
self.result.module.custom_sections_data.len().try_into().unwrap(),
);
self.result
.module
.custom_sections
.insert(String::from(name), custom_section);
self.result
.module
.custom_sections_data
.push(Arc::from(data));
self.result.module.custom_sections.insert(String::from(name), custom_section);
self.result.module.custom_sections_data.push(Arc::from(data));
Ok(())
}
}

View File

@@ -10,10 +10,7 @@ macro_rules! wasm_unsupported {
impl From<BinaryReaderError> for WasmError {
fn from(original: BinaryReaderError) -> Self {
Self::InvalidWebAssembly {
message: original.message().into(),
offset: original.offset(),
}
Self::InvalidWebAssembly { message: original.message().into(), offset: original.offset() }
}
}

View File

@@ -79,9 +79,7 @@ impl<T: Deref<Target = dyn ModuleMiddleware>> ModuleMiddlewareChain for [T] {
&self,
local_function_index: LocalFunctionIndex,
) -> Vec<Box<dyn FunctionMiddleware>> {
self.iter()
.map(|x| x.generate_function_middleware(local_function_index))
.collect()
self.iter().map(|x| x.generate_function_middleware(local_function_index)).collect()
}
/// Applies the chain on a `ModuleInfo` struct.
@@ -116,10 +114,7 @@ impl<'a> MiddlewareBinaryReader<'a> {
pub fn new_with_offset(data: &'a [u8], original_offset: usize) -> Self {
let inner = BinaryReader::new_with_offset(data, original_offset);
Self {
state: MiddlewareReaderState {
inner,
pending_operations: VecDeque::new(),
},
state: MiddlewareReaderState { inner, pending_operations: VecDeque::new() },
chain: vec![],
}
}

View File

@@ -89,11 +89,9 @@ pub fn translate_module<'data>(
unimplemented!("module linking not implemented yet")
}
Payload::CustomSection {
name: "name",
data,
data_offset,
} => parse_name_section(NameSectionReader::new(data, data_offset)?, environ)?,
Payload::CustomSection { name: "name", data, data_offset } => {
parse_name_section(NameSectionReader::new(data, data_offset)?, environ)?
}
Payload::CustomSection { name, data, .. } => environ.custom_section(name, data)?,

View File

@@ -42,10 +42,7 @@ pub fn wptype_to_type(ty: wasmparser::Type) -> WasmResult<Type> {
wasmparser::Type::V128 => Ok(Type::V128),
wasmparser::Type::ExternRef => Ok(Type::ExternRef),
wasmparser::Type::FuncRef => Ok(Type::FuncRef),
ty => Err(wasm_unsupported!(
"wptype_to_type: wasmparser type {:?}",
ty
)),
ty => Err(wasm_unsupported!("wptype_to_type: wasmparser type {:?}", ty)),
}
}
@@ -110,10 +107,7 @@ pub fn parse_import_section<'data>(
| ImportSectionEntryType::Event(_) => {
unimplemented!("module linking not implemented yet")
}
ImportSectionEntryType::Memory(WPMemoryType::M32 {
limits: ref memlimits,
shared,
}) => {
ImportSectionEntryType::Memory(WPMemoryType::M32 { limits: ref memlimits, shared }) => {
environ.declare_memory_import(
MemoryType {
minimum: Pages(memlimits.initial),
@@ -227,13 +221,7 @@ pub fn parse_global_section(
environ.reserve_globals(globals.get_count())?;
for entry in globals {
let wasmparser::Global {
ty: WPGlobalType {
content_type,
mutable,
},
init_expr,
} = entry?;
let wasmparser::Global { ty: WPGlobalType { content_type, mutable }, init_expr } = entry?;
let mut init_expr_reader = init_expr.get_binary_reader();
let initializer = match init_expr_reader.read_operator()? {
Operator::I32Const { value } => GlobalInit::I32Const(value),
@@ -249,16 +237,11 @@ pub fn parse_global_section(
GlobalInit::GetGlobal(GlobalIndex::from_u32(global_index))
}
ref s => {
return Err(wasm_unsupported!(
"unsupported init expr in global section: {:?}",
s
));
return Err(wasm_unsupported!("unsupported init expr in global section: {:?}", s));
}
};
let global = GlobalType {
ty: wptype_to_type(content_type).unwrap(),
mutability: mutable.into(),
};
let global =
GlobalType { ty: wptype_to_type(content_type).unwrap(), mutability: mutable.into() };
environ.declare_global(global, initializer)?;
}
@@ -273,11 +256,7 @@ pub fn parse_export_section<'data>(
environ.reserve_exports(exports.get_count())?;
for entry in exports {
let Export {
field,
ref kind,
index,
} = entry?;
let Export { field, ref kind, index } = entry?;
// The input has already been validated, so we should be able to
// assume valid UTF-8 and use `from_utf8_unchecked` if performance
@@ -336,17 +315,11 @@ pub fn parse_element_section<'data>(
for (index, entry) in elements.into_iter().enumerate() {
let Element { kind, items, ty } = entry?;
if ty != wasmparser::Type::FuncRef {
return Err(wasm_unsupported!(
"unsupported table element type: {:?}",
ty
));
return Err(wasm_unsupported!("unsupported table element type: {:?}", ty));
}
let segments = read_elems(&items)?;
match kind {
ElementKind::Active {
table_index,
init_expr,
} => {
ElementKind::Active { table_index, init_expr } => {
let mut init_expr_reader = init_expr.get_binary_reader();
let (base, offset) = match init_expr_reader.read_operator()? {
Operator::I32Const { value } => (None, value as u32 as usize),
@@ -387,10 +360,7 @@ pub fn parse_data_section<'data>(
for (index, entry) in data.into_iter().enumerate() {
let Data { kind, data } = entry?;
match kind {
DataKind::Active {
memory_index,
init_expr,
} => {
DataKind::Active { memory_index, init_expr } => {
let mut init_expr_reader = init_expr.get_binary_reader();
let (base, offset) = match init_expr_reader.read_operator()? {
Operator::I32Const { value } => (None, value as u32 as usize),
@@ -429,10 +399,8 @@ pub fn parse_name_section<'data>(
while let Ok(subsection) = names.read() {
match subsection {
wasmparser::Name::Function(function_subsection) => {
if let Some(function_names) = function_subsection
.get_map()
.ok()
.and_then(parse_function_name_subsection)
if let Some(function_names) =
function_subsection.get_map().ok().and_then(parse_function_name_subsection)
{
for (index, name) in function_names {
environ.declare_function_name(index, name)?;
@@ -461,10 +429,7 @@ fn parse_function_name_subsection(
return None;
}
if function_names
.insert(FunctionIndex::from_u32(index), name)
.is_some()
{
if function_names.insert(FunctionIndex::from_u32(index), name).is_some() {
// If the function index has been previously seen, then we
// break out of the loop and early return `None`, because these
// should be unique.

View File

@@ -28,9 +28,7 @@ pub struct ModuleTranslationState {
impl ModuleTranslationState {
/// Creates a new empty ModuleTranslationState.
pub fn new() -> Self {
Self {
wasm_types: PrimaryMap::new(),
}
Self { wasm_types: PrimaryMap::new() }
}
/// Get the parameter and result types for the given Wasm blocktype.