Skip to content

Commit

Permalink
clippy and fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
chandrakananandi committed May 6, 2023
1 parent 4950914 commit 9fada84
Show file tree
Hide file tree
Showing 12 changed files with 75 additions and 92 deletions.
4 changes: 2 additions & 2 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,12 +240,12 @@ impl SolAST {
self.node_kind(),
self.node_type(),
);
if visitor.skip_node(self, &arg) {
if visitor.skip_node(self, arg) {
log::debug!(" Skipping");
return;
}

if let Some(result) = visitor.visit_node(self, &arg) {
if let Some(result) = visitor.visit_node(self, arg) {
log::debug!(" Visit successful");
acc.push(result);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ pub struct GambitConfigFile {
#[derive(Parser)]
#[clap(rename_all = "kebab-case")]
pub enum Command {
Mutate(MutateParams), // Maybe we want to do other things in the future like support checking mutants?
Mutate(Box<MutateParams>), // Maybe we want to do other things in the future like support checking mutants?
Summary(SummaryParams),
}

Expand Down
14 changes: 8 additions & 6 deletions src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use std::{
path::{Path, PathBuf},
};

type CompilerRet = (i32, Vec<u8>, Vec<u8>);

/// This module provides a wrapper around the solc compiler, as well as several
/// helper functions. The main object of interest in this module is `Solc`.
Expand All @@ -32,8 +34,8 @@ pub struct Solc {
impl Solc {
pub fn new(solc: String, output_directory: PathBuf) -> Solc {
Solc {
solc: solc,
output_directory: output_directory,
solc,
output_directory,
basepath: None,
allow_paths: None,
remappings: None,
Expand Down Expand Up @@ -142,7 +144,7 @@ impl Solc {
&self,
solidity_file: &Path,
outdir: &Path,
) -> Result<(i32, Vec<u8>, Vec<u8>), Box<dyn error::Error>> {
) -> Result<CompilerRet, Box<dyn error::Error>> {
log::debug!("Invoking full compilation on {}", solidity_file.display());
self.invoke_compiler(solidity_file, outdir, false)
}
Expand All @@ -163,7 +165,7 @@ impl Solc {
solidity_file: &Path,
ast_dir: &Path,
stop_after_parse: bool,
) -> Result<(i32, Vec<u8>, Vec<u8>), Box<dyn error::Error>> {
) -> Result<CompilerRet, Box<dyn error::Error>> {
let flags = self.make_compilation_flags(solidity_file, ast_dir, stop_after_parse);
let flags: Vec<&str> = flags.iter().map(|s| s as &str).collect();
let pretty_flags = flags
Expand Down Expand Up @@ -233,7 +235,7 @@ impl Solc {
panic!("Invalid Extension: {}", solidity_file.display());
}

let input_json_dir = output_directory.join(INPUT_JSON.to_owned());
let input_json_dir = output_directory.join(INPUT_JSON);
if input_json_dir.exists() {
log::debug!("{} already exists", input_json_dir.display());
} else {
Expand All @@ -259,7 +261,7 @@ impl Solc {
+ "_json.ast";
let ast_path = sol_ast_dir.join(&ast_fnm);
let json_path = sol_ast_dir.join(ast_fnm + DOT_JSON);
Ok((sol_ast_dir.to_path_buf(), ast_path, json_path))
Ok((sol_ast_dir, ast_path, json_path))
}

/// Create the compilation flags for compiling `solidity_file` in `ast_dir`
Expand Down
12 changes: 5 additions & 7 deletions src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ impl MutantFilter for RandomDownSampleFilter {
) -> Result<Vec<Mutant>, Box<dyn error::Error>> {
// Make a copy that we can mutate
let mutants = mutator.mutants();
let mut mutants: Vec<(usize, Mutant)> =
mutants.iter().map(|m| m.clone()).enumerate().collect();
let mut mutants: Vec<(usize, Mutant)> = mutants.iter().cloned().enumerate().collect();

// The sampled mutants. We want to sort by the original index into
let mut sampled: Vec<(usize, Mutant)> = vec![];
Expand All @@ -53,14 +52,13 @@ impl MutantFilter for RandomDownSampleFilter {
Some(seed) => ChaCha8Rng::seed_from_u64(seed),
};

while mutants.len() > 0 && sampled.len() < num_mutants {
while !mutants.is_empty() && sampled.len() < num_mutants {
// Get a random index into the current list of remaning mutants
let idx = r.gen_range(0..mutants.len());
let mutant = mutants.remove(idx);
if self.validate() {
match mutator.validate_mutant(&mutant.1) {
Ok(true) => sampled.push(mutant),
_ => (),
if let Ok(true) = mutator.validate_mutant(&mutant.1) {
sampled.push(mutant)
}
} else {
sampled.push(mutant);
Expand All @@ -73,6 +71,6 @@ impl MutantFilter for RandomDownSampleFilter {
}

fn validate(&self) -> bool {
return self.validate;
self.validate
}
}
17 changes: 7 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn run_mutate(
let outdir = &params.outdir;
outdir_map
.entry(outdir.to_string())
.or_insert(vec![])
.or_default()
.push(params);
}

Expand Down Expand Up @@ -89,7 +89,6 @@ pub fn run_mutate(
}
}
} else {
eprintln!("");
eprintln!(
"[!] Output directory {} exists! You can:",
outdir_path.display()
Expand Down Expand Up @@ -147,15 +146,13 @@ pub fn run_mutate(
let mutants = filter.filter_mutants(&mutator, num_mutants)?;
log::info!("Filtering resulted in {} mutants", mutants.len());
mutants
} else if params.skip_validate {
log::info!("Skipping validation");
mutants
} else {
if params.skip_validate {
log::info!("Skipping validation");
mutants
} else {
let mutants = mutator.get_valid_mutants(&mutants);
log::info!("Validation resulted in {} mutants", mutants.len());
mutants
}
let mutants = mutator.get_valid_mutants(&mutants);
log::info!("Validation resulted in {} mutants", mutants.len());
mutants
};
total_num_mutants += mutants.len();
log::info!("Adding {} mutants to global mutant pool", mutants.len());
Expand Down
34 changes: 15 additions & 19 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Some(json_path) = &params.json {
log::info!("Running from configuration");
// Run from config file
let json_contents = std::fs::read_to_string(&json_path)?;
let json_contents = std::fs::read_to_string(json_path)?;
let json: serde_json::Value = serde_json::from_reader(json_contents.as_bytes())?;
log::info!("Read configuration json: {:#?}", json);

Expand Down Expand Up @@ -226,21 +226,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// PARAM: solc_remappings
log::info!(" [.] Resolving params.solc_remapping");
let remapping: Option<Vec<String>> =
if let Some(remapping) = &params.solc_remappings {
Some(
remapping
.iter()
.map(|rm| {
repair_remapping(
rm.as_str(),
Some(json_parent_directory.to_str().unwrap()),
)
})
.collect(),
)
} else {
None
};
params.solc_remappings.as_ref().map(|remapping| {
remapping
.iter()
.map(|rm| {
repair_remapping(
rm.as_str(),
Some(json_parent_directory.to_str().unwrap()),
)
})
.collect()
});

// Finally, update params with resolved source root and filename.
// (We don't update earlier to preserve the state of params
Expand Down Expand Up @@ -426,14 +422,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// for error reporting: reporting the parsed in value of
// `params` will be more helpful to the end user than
// reporting the modified value of params).
params.sourceroot = Some(source_root_string.clone());
params.filename = Some(filename_string.clone());
params.sourceroot = Some(source_root_string);
params.filename = Some(filename_string);
params.outdir = outdir;
params.solc_allow_paths = solc_allowpaths;
params.solc_base_path = solc_basepath;
params.solc_remappings = solc_remapping;

run_mutate(vec![params])?;
run_mutate(vec![*params])?;
}
}
Command::Summary(params) => {
Expand Down
4 changes: 2 additions & 2 deletions src/mutant_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl MutantWriter {
let mid = i + 1;
let (lineno, colno) = mutant.get_line_column()?;
let line_col = format!("{}:{}", lineno, colno);
w.write_record(&[
w.write_record([
mid.to_string().as_str(),
mutant.op.to_string().as_str(),
mutant.source.relative_filename()?.to_str().unwrap(),
Expand All @@ -67,7 +67,7 @@ impl MutantWriter {
diffs.push(Self::diff_mutant(mutant)?);
}

let gambit_results_json = PathBuf::from(self.outdir.join("gambit_results.json"));
let gambit_results_json = self.outdir.join("gambit_results.json");
log::info!(
"Writing gambit_results.json to {}",
&gambit_results_json.display()
Expand Down
38 changes: 15 additions & 23 deletions src/mutation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ impl Mutant {
let prelude = &contents[0..self.start];
let postlude = &contents[self.end..contents.len()];

let res = [prelude, &self.repl.as_bytes(), postlude].concat();
let res = [prelude, self.repl.as_bytes(), postlude].concat();
let mut_string = String::from_utf8(res)?;
let mut lines = mut_string.lines();

Expand Down Expand Up @@ -269,13 +269,13 @@ impl Mutation for MutationType {
}
.iter()
.filter(|v| !orig.eq(*v))
.map(|v| *v)
.copied()
.collect();

let (s, e) = rhs.get_bounds();
replacements
.iter()
.map(|r| Mutant::new(source.clone(), self.clone(), s, e, r.to_string()))
.map(|r| Mutant::new(source.clone(), *self, s, e, r.to_string()))
.collect()
}
MutationType::BinOpMutation => {
Expand All @@ -285,36 +285,28 @@ impl Mutation for MutationType {
let ops: Vec<&str> = vec!["+", "-", "*", "/", "%", "**"]
.iter()
.filter(|v| !orig.eq(*v))
.map(|v| *v)
.copied()
.collect();

let (_, endl) = node.left_expression().get_bounds();
let (startr, _) = node.right_expression().get_bounds();
ops.iter()
.map(|op| {
Mutant::new(source.clone(), self.clone(), endl, startr, op.to_string())
})
.map(|op| Mutant::new(source.clone(), *self, endl, startr, op.to_string()))
.collect()
}

MutationType::DeleteExpressionMutation => {
let (start, end) = node.get_bounds();
let commented = format!("/* {} */", node.expression().get_text(source.contents()));
vec![Mutant::new(
source.clone(),
self.clone(),
start,
end,
commented,
)]
vec![Mutant::new(source, *self, start, end, commented)]
}
MutationType::ElimDelegateMutation => {
let (_, endl) = node.expression().expression().get_bounds();
let (_, endr) = node.expression().get_bounds();

vec![Mutant::new(
source,
self.clone(),
*self,
endl + 1,
endr,
"call".to_string(),
Expand All @@ -338,13 +330,13 @@ impl Mutation for MutationType {
let bs: Vec<&str> = vec!["true", "false"]
.iter()
.filter(|v| !orig.eq(*v))
.map(|v| *v)
.copied()
.collect();

let (start, end) = cond.get_bounds();

bs.iter()
.map(|r| Mutant::new(source.clone(), self.clone(), start, end, r.to_string()))
.map(|r| Mutant::new(source.clone(), *self, start, end, r.to_string()))
.collect()
}

Expand All @@ -354,11 +346,11 @@ impl Mutation for MutationType {
let bs: Vec<&str> = vec!["true", "false"]
.iter()
.filter(|v| !orig.eq(*v))
.map(|v| *v)
.copied()
.collect();
let (start, end) = arg.get_bounds();
bs.iter()
.map(|r| Mutant::new(source.clone(), self.clone(), start, end, r.to_string()))
.map(|r| Mutant::new(source.clone(), *self, start, end, r.to_string()))
.collect()
}

Expand Down Expand Up @@ -400,11 +392,11 @@ impl Mutation for MutationType {
let right_contents =
String::from_utf8(contents[right_start..right_end].to_vec()).unwrap();

let mut repl: String = right_contents.to_owned();
let mut repl: String = right_contents;
repl.push_str(&op);
repl.push_str(&left_contents);

vec![Mutant::new(source.clone(), self.clone(), start, end, repl)]
vec![Mutant::new(source.clone(), *self, start, end, repl)]
}

MutationType::UnOpMutation => {
Expand All @@ -420,7 +412,7 @@ impl Mutation for MutationType {
let replacements: Vec<&str> = if is_prefix { prefix_ops } else { suffix_ops }
.iter()
.filter(|v| !op.eq(*v))
.map(|v| *v)
.copied()
.collect();
let (start, end) = if is_prefix {
(start, start + op.len())
Expand All @@ -430,7 +422,7 @@ impl Mutation for MutationType {

replacements
.iter()
.map(|r| Mutant::new(source.clone(), self.clone(), start, end, r.to_string()))
.map(|r| Mutant::new(source.clone(), *self, start, end, r.to_string()))
.collect()
}
}
Expand Down
Loading

0 comments on commit 9fada84

Please sign in to comment.