Skip to content

Commit

Permalink
apply clippy fix
Browse files Browse the repository at this point in the history
  • Loading branch information
lwshang committed Jun 29, 2024
1 parent 2d54251 commit 8272e87
Show file tree
Hide file tree
Showing 26 changed files with 117 additions and 125 deletions.
11 changes: 6 additions & 5 deletions crates/fuzz-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ where
.join("..") // pop `crates`
.join("target")
.join("walrus-fuzz");
fs::create_dir_all(&dir).expect(&format!("should create directory: {:?}", dir));
fs::create_dir_all(&dir).unwrap_or_else(|_| panic!("should create directory: {:?}", dir));

let scratch = tempfile::NamedTempFile::new_in(dir).expect("should create temp file OK");

Expand Down Expand Up @@ -99,20 +99,20 @@ where
}

fn interp(&self, wasm: &[u8]) -> Result<String> {
fs::write(self.scratch.path(), &wasm).context("failed to write to scratch file")?;
fs::write(self.scratch.path(), wasm).context("failed to write to scratch file")?;
wasm_interp(self.scratch.path())
}

fn round_trip_through_walrus(&self, wasm: &[u8]) -> Result<Vec<u8>> {
let mut module =
walrus::Module::from_buffer(&wasm).context("walrus failed to parse the wasm buffer")?;
walrus::Module::from_buffer(wasm).context("walrus failed to parse the wasm buffer")?;
walrus::passes::gc::run(&mut module);
let buf = module.emit_wasm();
Ok(buf)
}

fn test_wat(&self, wat: &str) -> Result<()> {
let wasm = self.wat2wasm(&wat)?;
let wasm = self.wat2wasm(wat)?;
let expected = self.interp(&wasm)?;

let walrus_wasm = self.round_trip_through_walrus(&wasm)?;
Expand Down Expand Up @@ -160,6 +160,7 @@ where
Ok(()) => {
// We reduced fuel as far as we could, so return the last
// failing test case.
#[allow(clippy::question_mark)]
if failing.is_err() {
return failing;
}
Expand Down Expand Up @@ -313,7 +314,7 @@ impl<R: Rng> WatGen<R> {
self.wat.push_str(&operator.to_string());

for op in immediates.into_iter() {
self.wat.push_str(" ");
self.wat.push(' ');
self.wat.push_str(op.as_ref());
}

Expand Down
18 changes: 9 additions & 9 deletions crates/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ impl Parse for WalrusFieldOpts {
if attr == "skip_visit" {
return Ok(Attr::SkipVisit);
}
return Err(Error::new(attr.span(), "unexpected attribute"));
Err(Error::new(attr.span(), "unexpected attribute"))
}
}
}
Expand Down Expand Up @@ -144,7 +144,7 @@ impl Parse for WalrusVariantOpts {
if attr == "skip_builder" {
return Ok(Attr::SkipBuilder);
}
return Err(Error::new(attr.span(), "unexpected attribute"));
Err(Error::new(attr.span(), "unexpected attribute"))
}
}
}
Expand All @@ -166,7 +166,7 @@ fn walrus_attrs(attrs: &mut Vec<syn::Attribute>) -> TokenStream {
ret.extend(group);
ret.extend(quote! { , });
}
return ret.into();
ret.into()
}

fn create_types(attrs: &[syn::Attribute], variants: &[WalrusVariant]) -> impl quote::ToTokens {
Expand Down Expand Up @@ -328,10 +328,10 @@ fn create_types(attrs: &[syn::Attribute], variants: &[WalrusVariant]) -> impl qu
}
}

fn visit_fields<'a>(
variant: &'a WalrusVariant,
fn visit_fields(
variant: &WalrusVariant,
allow_skip: bool,
) -> impl Iterator<Item = (syn::Ident, proc_macro2::TokenStream, bool)> + 'a {
) -> impl Iterator<Item = (syn::Ident, proc_macro2::TokenStream, bool)> + '_ {
return variant
.syn
.fields
Expand Down Expand Up @@ -439,7 +439,7 @@ fn create_visit(variants: &[WalrusVariant]) -> impl quote::ToTokens {
}
});

let doc = format!("Visit `{}`.", name.to_string());
let doc = format!("Visit `{}`.", name);
visitor_trait_methods.push(quote! {
#[doc=#doc]
#[inline]
Expand Down Expand Up @@ -723,13 +723,13 @@ fn create_builder(variants: &[WalrusVariant]) -> impl quote::ToTokens {

let doc = format!(
"Push a new `{}` instruction onto this builder's block.",
name.to_string()
name
);
let at_doc = format!(
"Splice a new `{}` instruction into this builder's block at the given index.\n\n\
# Panics\n\n\
Panics if `position > self.instrs.len()`.",
name.to_string()
name
);

let arg_names = &arg_names;
Expand Down
2 changes: 1 addition & 1 deletion crates/tests-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ where
cmd.arg(input);
cmd.arg("-o");
cmd.arg(tmp.path());
cmd.args(&[
cmd.args([
"--enable-threads",
"--enable-bulk-memory",
// "--enable-reference-types",
Expand Down
26 changes: 12 additions & 14 deletions crates/tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ impl FileCheck {
let mut iter = contents.lines().map(str::trim);
while let Some(line) = iter.next() {
if line.starts_with("(; CHECK-ALL:") {
if patterns.len() != 0 {
if !patterns.is_empty() {
panic!("CHECK cannot be used with CHECK-ALL");
}
let mut pattern = Vec::new();
while let Some(line) = iter.next() {
for line in iter.by_ref() {
if line == ";)" {
break;
}
Expand All @@ -94,19 +94,17 @@ impl FileCheck {
}
return FileCheck::Exhaustive(pattern, path.to_path_buf());
}

if line.starts_with(";; CHECK:") {
let p = line[";; CHECK:".len()..].to_string();
patterns.push(vec![p]);
if let Some(p) = line.strip_prefix(";; CHECK:") {
patterns.push(vec![p.to_string()]);
}
if line.starts_with(";; NEXT:") {
let p = patterns
if let Some(p) = line.strip_prefix(";; NEXT:") {
let v = patterns
.last_mut()
.expect("NEXT should never come before CHECK");
p.push(line[";; NEXT:".len()..].to_string());
v.push(p.to_string());
}
}
if patterns.len() == 0 {
if patterns.is_empty() {
FileCheck::None(path.to_path_buf())
} else {
FileCheck::Patterns(patterns)
Expand All @@ -125,7 +123,7 @@ impl FileCheck {

'inner: while let Some(pos) = output_lines[start..]
.iter()
.position(|l| matches(*l, first_line))
.position(|l| matches(l, first_line))
{
start = pos + 1;
if output_lines[pos..].len() + 1 < pattern.len() {
Expand Down Expand Up @@ -155,11 +153,11 @@ impl FileCheck {
}
}
FileCheck::None(_) => {
println!("");
println!();
println!("no test assertions were found in this file, but");
println!("you can rerun tests with `WALRUS_BLESS=1` to");
println!("automatically add assertions to this file");
println!("");
println!();
panic!("no tests to run")
}
}
Expand Down Expand Up @@ -210,7 +208,7 @@ fn update_output(path: &Path, output: &str) {
new_output.push_str(" ");
new_output.push_str(line.trim_end());
}
new_output.push_str("\n");
new_output.push('\n');
}
let new = format!(
"{}\n\n(; CHECK-ALL:\n{}\n;)\n",
Expand Down
9 changes: 4 additions & 5 deletions crates/tests/tests/spec-tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ fn run(wast: &Path) -> Result<(), anyhow::Error> {
let proposal = wast
.iter()
.skip_while(|part| *part != "proposals")
.skip(1)
.next()
.nth(1)
.map(|s| s.to_str().unwrap());

let extra_args: &[&str] = match proposal {
Expand Down Expand Up @@ -54,7 +53,7 @@ fn run(wast: &Path) -> Result<(), anyhow::Error> {
let mut files = Vec::new();

let mut config = walrus::ModuleConfig::new();
if extra_args.len() == 0 {
if extra_args.is_empty() {
config.only_stable_features(true);
}

Expand Down Expand Up @@ -154,7 +153,7 @@ fn run(wast: &Path) -> Result<(), anyhow::Error> {
}

let wasm = module.emit_wasm();
fs::write(&file, wasm)?;
fs::write(file, wasm)?;
}

run_spectest_interp(tempdir.path(), extra_args)?;
Expand All @@ -177,7 +176,7 @@ fn run_spectest_interp(cwd: &Path, extra_args: &[&str]) -> Result<(), anyhow::Er
let stdout = String::from_utf8_lossy(&output.stdout);
if let Some(line) = stdout.lines().find(|l| l.ends_with("tests passed.")) {
let part = line.split_whitespace().next().unwrap();
let mut parts = part.split("/");
let mut parts = part.split('/');
let a = parts.next().unwrap().parse::<u32>();
let b = parts.next().unwrap().parse::<u32>();
if a == b {
Expand Down
2 changes: 1 addition & 1 deletion examples/round-trip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ fn main() -> anyhow::Result<()> {
let a = std::env::args()
.nth(1)
.ok_or_else(|| anyhow::anyhow!("must provide the input wasm file as the first argument"))?;
let mut m = walrus::Module::from_file(&a)?;
let mut m = walrus::Module::from_file(a)?;
let wasm = m.emit_wasm();
if let Some(destination) = std::env::args().nth(2) {
std::fs::write(destination, wasm)?;
Expand Down
18 changes: 9 additions & 9 deletions src/const_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,17 @@ impl ConstExpr {
Ok(val)
}

pub(crate) fn to_wasmencoder_type(&self, cx: &EmitContext) -> wasm_encoder::ConstExpr {
pub(crate) fn to_wasmencoder_type(self, cx: &EmitContext) -> wasm_encoder::ConstExpr {
match self {
ConstExpr::Value(v) => match v {
Value::I32(v) => wasm_encoder::ConstExpr::i32_const(*v),
Value::I64(v) => wasm_encoder::ConstExpr::i64_const(*v),
Value::F32(v) => wasm_encoder::ConstExpr::f32_const(*v),
Value::F64(v) => wasm_encoder::ConstExpr::f64_const(*v),
Value::V128(v) => wasm_encoder::ConstExpr::v128_const(*v as i128),
Value::I32(v) => wasm_encoder::ConstExpr::i32_const(v),
Value::I64(v) => wasm_encoder::ConstExpr::i64_const(v),
Value::F32(v) => wasm_encoder::ConstExpr::f32_const(v),
Value::F64(v) => wasm_encoder::ConstExpr::f64_const(v),
Value::V128(v) => wasm_encoder::ConstExpr::v128_const(v as i128),
},
ConstExpr::Global(g) => {
wasm_encoder::ConstExpr::global_get(cx.indices.get_global_index(*g))
wasm_encoder::ConstExpr::global_get(cx.indices.get_global_index(g))
}
ConstExpr::RefNull(ty) => wasm_encoder::ConstExpr::ref_null(match ty {
RefType::Externref => wasm_encoder::HeapType::Abstract {
Expand All @@ -81,15 +81,15 @@ impl ConstExpr {
},
}),
ConstExpr::RefFunc(f) => {
wasm_encoder::ConstExpr::ref_func(cx.indices.get_func_index(*f))
wasm_encoder::ConstExpr::ref_func(cx.indices.get_func_index(f))
}
}
}
}

pub(crate) fn v128_to_u128(value: &wasmparser::V128) -> u128 {
let n = value.bytes();
((n[0] as u128) << 0)
(n[0] as u128)
| ((n[1] as u128) << 8)
| ((n[2] as u128) << 16)
| ((n[3] as u128) << 24)
Expand Down
8 changes: 4 additions & 4 deletions src/dot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ impl<T: DotNode> Dot for T {

impl FieldAggregator for AppendFields<'_> {
fn add_field(&mut self, field: &[&str]) {
assert!(field.len() > 0);
assert!(!field.is_empty());
self.out.push_str("<tr>");
for f in field {
self.out.push_str("<td>");
Expand All @@ -114,7 +114,7 @@ impl<T: DotNode> Dot for T {
}

fn add_field_with_port(&mut self, port: &str, field: &str) {
assert!(field.len() > 0);
assert!(!field.is_empty());
self.out.push_str("<tr>");
self.out.push_str("<td port=\"");
self.out.push_str(port);
Expand Down Expand Up @@ -142,7 +142,7 @@ impl<T: DotNode> Dot for T {
fn add_edge_from_port(&mut self, port: &str, to: &impl DotName) {
self.out.push_str(" ");
self.out.push_str(self.from);
self.out.push_str(":");
self.out.push(':');
self.out.push_str(port);
self.out.push_str(" -> ");
self.out.push_str(&to.dot_name());
Expand Down Expand Up @@ -174,7 +174,7 @@ impl Dot for Module {
// self.name.dot(out);
// self.config.dot(out);

out.push_str("}");
out.push('}');
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/module/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ pub struct ModuleConfig {
pub(crate) skip_producers_section: bool,
pub(crate) skip_name_section: bool,
pub(crate) preserve_code_transform: bool,
#[allow(clippy::type_complexity)]
pub(crate) on_parse:
Option<Box<dyn Fn(&mut Module, &IndicesToIds) -> Result<()> + Sync + Send + 'static>>,
#[allow(clippy::type_complexity)]
pub(crate) on_instr_loc: Option<Box<dyn Fn(&usize) -> InstrLocId + Sync + Send + 'static>>,
}

Expand Down
25 changes: 7 additions & 18 deletions src/module/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,7 @@ where
T: CustomSection,
{
fn clone(&self) -> Self {
TypedCustomSectionId {
id: self.id,
_phantom: PhantomData,
}
*self
}
}

Expand Down Expand Up @@ -366,26 +363,18 @@ impl ModuleCustomSections {

/// Iterate over shared references to custom sections and their ids.
pub fn iter(&self) -> impl Iterator<Item = (UntypedCustomSectionId, &dyn CustomSection)> {
self.arena.iter().flat_map(|(id, s)| {
if let Some(s) = s.as_ref() {
Some((UntypedCustomSectionId(id), &**s))
} else {
None
}
})
self.arena
.iter()
.flat_map(|(id, s)| s.as_ref().map(|s| (UntypedCustomSectionId(id), &**s)))
}

/// Iterate over exclusive references to custom sections and their ids.
pub fn iter_mut(
&mut self,
) -> impl Iterator<Item = (UntypedCustomSectionId, &mut dyn CustomSection)> {
self.arena.iter_mut().flat_map(|(id, s)| {
if let Some(s) = s.as_mut() {
Some((UntypedCustomSectionId(id), &mut **s))
} else {
None
}
})
self.arena
.iter_mut()
.flat_map(|(id, s)| s.as_mut().map(|s| (UntypedCustomSectionId(id), &mut **s)))
}

/// Remove a custom section (by type) from the module.
Expand Down
7 changes: 2 additions & 5 deletions src/module/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ impl Data {

/// Is this a passive data segment?
pub fn is_passive(&self) -> bool {
match self.kind {
DataKind::Passive => true,
_ => false,
}
matches!(self.kind, DataKind::Passive)
}
}

Expand Down Expand Up @@ -143,7 +140,7 @@ impl ModuleData {
let mut any_passive = false;

for data in self.iter() {
cx.indices.set_data_index(data.id(), count as u32);
cx.indices.set_data_index(data.id(), count);
count += 1;
any_passive |= data.is_passive();
}
Expand Down
Loading

0 comments on commit 8272e87

Please sign in to comment.