Skip to content

Commit

Permalink
Address clippy warnings (model-checking#2807)
Browse files Browse the repository at this point in the history
Versions of clippy that come with newer toolchains report a large number
of needless_borrows_for_generic_args. We can address these now so that
we don't have to make these changes as part of a toolchain update.
  • Loading branch information
tautschnig authored Oct 4, 2023
1 parent fb08f3e commit fece7ee
Show file tree
Hide file tree
Showing 24 changed files with 54 additions and 52 deletions.
2 changes: 1 addition & 1 deletion cprover_bindings/src/goto_program/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ impl BuiltinFn {
/// Converters: build symbols and expressions from Builtins
impl BuiltinFn {
pub fn as_symbol(&self) -> Symbol {
Symbol::builtin_function(&self.to_string(), self.param_types(), self.return_type())
Symbol::builtin_function(self.to_string(), self.param_types(), self.return_type())
}

pub fn as_expr(&self) -> Expr {
Expand Down
8 changes: 4 additions & 4 deletions kani-compiler/src/codegen_cprover_gotoc/codegen/operand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ impl<'tcx> GotocCtx<'tcx> {
}

let mem_place =
self.symbol_table.lookup(&self.alloc_map.get(&alloc).unwrap()).unwrap().to_expr();
self.symbol_table.lookup(self.alloc_map.get(&alloc).unwrap()).unwrap().to_expr();
mem_place.address_of()
}

Expand All @@ -579,16 +579,16 @@ impl<'tcx> GotocCtx<'tcx> {
// initializers. For example, for a boolean static variable, the variable will have type
// CBool and the initializer will be a single byte (a one-character array) representing the
// bit pattern for the boolean value.
let alloc_typ_ref = self.ensure_struct(&struct_name, &struct_name, |ctx, _| {
let alloc_typ_ref = self.ensure_struct(struct_name, struct_name, |ctx, _| {
ctx.codegen_allocation_data(alloc)
.iter()
.enumerate()
.map(|(i, d)| match d {
AllocData::Bytes(bytes) => DatatypeComponent::field(
&i.to_string(),
i.to_string(),
Type::unsigned_int(8).array_of(bytes.len()),
),
AllocData::Expr(e) => DatatypeComponent::field(&i.to_string(), e.typ().clone()),
AllocData::Expr(e) => DatatypeComponent::field(i.to_string(), e.typ().clone()),
})
.collect()
});
Expand Down
12 changes: 7 additions & 5 deletions kani-compiler/src/codegen_cprover_gotoc/codegen/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,10 @@ impl<'tcx> GotocCtx<'tcx> {
| ty::Param(_)
| ty::Infer(_)
| ty::Error(_) => unreachable!("type {parent_ty:?} does not have a field"),
ty::Tuple(_) => Ok(parent_expr
.member(&Self::tuple_fld_name(field.index()), &self.symbol_table)),
ty::Tuple(_) => {
Ok(parent_expr
.member(Self::tuple_fld_name(field.index()), &self.symbol_table))
}
ty::Adt(def, _) if def.repr().simd() => Ok(self.codegen_simd_field(
parent_expr,
*field,
Expand All @@ -278,10 +280,10 @@ impl<'tcx> GotocCtx<'tcx> {
// if we fall here, then we are handling either a struct or a union
ty::Adt(def, _) => {
let field = &def.variants().raw[0].fields[*field];
Ok(parent_expr.member(&field.name.to_string(), &self.symbol_table))
Ok(parent_expr.member(field.name.to_string(), &self.symbol_table))
}
ty::Closure(..) => {
Ok(parent_expr.member(&field.index().to_string(), &self.symbol_table))
Ok(parent_expr.member(field.index().to_string(), &self.symbol_table))
}
ty::Generator(..) => {
let field_name = self.generator_field_name(field.as_usize());
Expand All @@ -299,7 +301,7 @@ impl<'tcx> GotocCtx<'tcx> {
// if we fall here, then we are handling an enum
TypeOrVariant::Variant(parent_var) => {
let field = &parent_var.fields[*field];
Ok(parent_expr.member(&field.name.to_string(), &self.symbol_table))
Ok(parent_expr.member(field.name.to_string(), &self.symbol_table))
}
TypeOrVariant::GeneratorVariant(_var_idx) => {
let field_name = self.generator_field_name(field.index());
Expand Down
6 changes: 3 additions & 3 deletions kani-compiler/src/codegen_cprover_gotoc/codegen/typ.rs
Original file line number Diff line number Diff line change
Expand Up @@ -864,7 +864,7 @@ impl<'tcx> GotocCtx<'tcx> {
// We need to pad to the next offset
let padding_size = next_offset - current_offset;
let name = format!("$pad{idx}");
Some(DatatypeComponent::padding(&name, padding_size.bits()))
Some(DatatypeComponent::padding(name, padding_size.bits()))
} else {
None
}
Expand Down Expand Up @@ -1378,7 +1378,7 @@ impl<'tcx> GotocCtx<'tcx> {
.iter()
.map(|f| {
DatatypeComponent::field(
&f.name.to_string(),
f.name.to_string(),
ctx.codegen_ty(f.ty(ctx.tcx, subst)),
)
})
Expand Down Expand Up @@ -1641,7 +1641,7 @@ impl<'tcx> GotocCtx<'tcx> {
None
} else {
Some(DatatypeComponent::field(
&case.name.to_string(),
case.name.to_string(),
self.codegen_enum_case_struct(
name,
pretty_name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ impl CodegenBackend for GotocCodegenBackend {
if let MonoItem::Fn(instance) = test_fn { instance } else { continue };
let metadata = gen_test_metadata(tcx, *test_desc, *instance, &base_filename);
let test_model_path = &metadata.goto_file.as_ref().unwrap();
std::fs::copy(&model_path, &test_model_path).expect(&format!(
std::fs::copy(&model_path, test_model_path).expect(&format!(
"Failed to copy {} to {}",
model_path.display(),
test_model_path.display()
Expand Down
2 changes: 1 addition & 1 deletion kani-compiler/src/kani_compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ impl KaniCompiler {
/// Write the metadata to a file
fn store_metadata(&self, metadata: &KaniMetadata, filename: &Path) {
debug!(?filename, "write_metadata");
let out_file = File::create(&filename).unwrap();
let out_file = File::create(filename).unwrap();
let writer = BufWriter::new(out_file);
if self.queries.lock().unwrap().args().output_pretty_json {
serde_json::to_writer_pretty(writer, &metadata).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion kani-compiler/src/kani_middle/reachability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ mod debug {
debug!(?target, "dump_dot");
let outputs = tcx.output_filenames(());
let path = outputs.output_path(OutputType::Metadata).with_extension("dot");
let out_file = File::create(&path)?;
let out_file = File::create(path)?;
let mut writer = BufWriter::new(out_file);
writeln!(writer, "digraph ReachabilityGraph {{")?;
if target.is_empty() {
Expand Down
6 changes: 3 additions & 3 deletions kani-driver/src/args/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ fn check_no_cargo_opt(is_set: bool, name: &str) -> Result<(), Error> {
if is_set {
Err(Error::raw(
ErrorKind::UnknownArgument,
&format!("argument `{}` cannot be used with standalone Kani.", name),
format!("argument `{}` cannot be used with standalone Kani.", name),
))
} else {
Ok(())
Expand All @@ -453,7 +453,7 @@ impl ValidateArgs for StandaloneArgs {
if !input.is_file() {
return Err(Error::raw(
ErrorKind::InvalidValue,
&format!(
format!(
"Invalid argument: Input invalid. `{}` is not a regular file.",
input.display()
),
Expand Down Expand Up @@ -583,7 +583,7 @@ impl ValidateArgs for VerificationArgs {
if out_dir.exists() && !out_dir.is_dir() {
return Err(Error::raw(
ErrorKind::InvalidValue,
&format!(
format!(
"Invalid argument: `--target-dir` argument `{}` is not a directory",
out_dir.display()
),
Expand Down
2 changes: 1 addition & 1 deletion kani-driver/src/args/playback_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl ValidateArgs for KaniPlaybackArgs {
if !self.input.is_file() {
return Err(Error::raw(
ErrorKind::InvalidValue,
&format!(
format!(
"Invalid argument: Input invalid. `{}` is not a regular file.",
self.input.display()
),
Expand Down
2 changes: 1 addition & 1 deletion kani-driver/src/assess/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub struct SessionError {
/// If given the argument to so do, write the assess metadata to the target file.
pub(crate) fn write_metadata(args: &AssessArgs, metadata: AssessMetadata) -> Result<()> {
if let Some(path) = &args.emit_metadata {
let out_file = File::create(&path)?;
let out_file = File::create(path)?;
let writer = BufWriter::new(out_file);
// use pretty for now to keep things readable and debuggable, but this should change eventually
serde_json::to_writer_pretty(writer, &metadata)?;
Expand Down
2 changes: 1 addition & 1 deletion kani-driver/src/assess/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ fn invoke_assess(
// Additionally, this should be `--manifest-path` but `cargo kani` doesn't support that yet.
cmd.arg("-p").arg(package);
cmd.arg("--enable-unstable"); // This has to be after `-p` due to an argument parsing bug in kani-driver
cmd.args(&["assess", "--emit-metadata"])
cmd.args(["assess", "--emit-metadata"])
.arg(outfile)
.current_dir(dir)
.stdout(log.try_clone()?)
Expand Down
2 changes: 1 addition & 1 deletion kani-driver/src/concrete_playback/playback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ fn build_test(install: &InstallType, args: &KaniPlaybackArgs) -> Result<PathBuf>
rustc_args.push("--error-format=json".into());
}

let mut cmd = Command::new(&install.kani_compiler()?);
let mut cmd = Command::new(install.kani_compiler()?);
cmd.args(rustc_args);

session::run_terminal(&args.playback.common_opts, cmd)?;
Expand Down
2 changes: 1 addition & 1 deletion kani-driver/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,6 @@ fn metadata_with_function(
// Note: `out_dir` is already on canonical form, so no need to invoke `try_new()`.
fn standalone_artifact(out_dir: &Path, crate_name: &String, typ: ArtifactType) -> Artifact {
let mut path = out_dir.join(crate_name);
let _ = path.set_extension(&typ);
let _ = path.set_extension(typ);
Artifact { path, typ }
}
2 changes: 1 addition & 1 deletion kani-driver/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ pub fn run_redirect(
stdout.display()
);
}
let output_file = std::fs::File::create(&stdout)?;
let output_file = std::fs::File::create(stdout)?;
cmd.stdout(output_file);

let program = cmd.get_program().to_string_lossy().to_string();
Expand Down
4 changes: 2 additions & 2 deletions kani_metadata/src/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub fn convert_type(path: &Path, from: ArtifactType, to: ArtifactType) -> PathBu
match from {
// Artifact types that has only one extension.
ArtifactType::Goto => {
result.set_extension(&to);
result.set_extension(to);
}
// Artifact types that has two extensions.
ArtifactType::Metadata
Expand All @@ -66,7 +66,7 @@ pub fn convert_type(path: &Path, from: ArtifactType, to: ArtifactType) -> PathBu
| ArtifactType::VTableRestriction
| ArtifactType::PrettyNameMap => {
result.set_extension("");
result.set_extension(&to);
result.set_extension(to);
}
}
result
Expand Down
10 changes: 5 additions & 5 deletions src/os_hacks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ pub fn setup_python_deps_on_ubuntu_18_04(pyroot: &Path, pkg_versions: &[&str]) -

// Step 1: use `--system --prefix pyroot`. This disables the broken behavior, and creates `bin` but...
Command::new("python3")
.args(&["-m", "pip", "install", "--system", "--prefix"])
.arg(&pyroot)
.args(["-m", "pip", "install", "--system", "--prefix"])
.arg(pyroot)
.args(pkg_versions)
.run()?;

Expand Down Expand Up @@ -128,7 +128,7 @@ fn setup_nixos_patchelf(kani_dir: &Path) -> Result<()> {
// Find the correct path to link C++ stdlib:
// `rpath=$(nix-instantiate --eval -E "(import <nixpkgs> {}).stdenv.cc.cc.lib.outPath")/lib`
let rpath_output = Command::new("nix-instantiate")
.args(&["--eval", "-E", "(import <nixpkgs> {}).stdenv.cc.cc.lib.outPath"])
.args(["--eval", "-E", "(import <nixpkgs> {}).stdenv.cc.cc.lib.outPath"])
.output()?;
if !rpath_output.status.success() {
bail!("Failed to find C++ standard library with `nix-instantiate`");
Expand All @@ -139,10 +139,10 @@ fn setup_nixos_patchelf(kani_dir: &Path) -> Result<()> {
let rpath = format!("{rpath_prefix}/lib");

let patch_interp = |file: &Path| -> Result<()> {
Command::new("patchelf").args(&["--set-interpreter", interp]).arg(file).run()
Command::new("patchelf").args(["--set-interpreter", interp]).arg(file).run()
};
let patch_rpath = |file: &Path| -> Result<()> {
Command::new("patchelf").args(&["--set-rpath", &rpath]).arg(file).run()
Command::new("patchelf").args(["--set-rpath", &rpath]).arg(file).run()
};

let bin = kani_dir.join("bin");
Expand Down
8 changes: 4 additions & 4 deletions src/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ fn setup_kani_bundle(kani_dir: &Path, use_local_bundle: Option<OsString>) -> Res
.arg("--strip-components=1")
.arg("-zxf")
.arg(&path)
.current_dir(&kani_dir)
.current_dir(kani_dir)
.run()
.context(
"Failed to extract tar file, try removing Kani setup located in .kani in your home directory and restarting",
Expand All @@ -118,7 +118,7 @@ fn setup_kani_bundle(kani_dir: &Path, use_local_bundle: Option<OsString>) -> Res
fail_if_unsupported_target()?;
let bundle = base_dir.join(filename);
Command::new("curl")
.args(&["-sSLf", "-o"])
.args(["-sSLf", "-o"])
.arg(&bundle)
.arg(download_url())
.run()
Expand All @@ -143,7 +143,7 @@ fn setup_rust_toolchain(kani_dir: &Path) -> Result<String> {
// Currently this means we require the bundle to have been unpacked first!
let toolchain_version = get_rust_toolchain_version(kani_dir)?;
println!("[3/5] Installing rust toolchain version: {}", &toolchain_version);
Command::new("rustup").args(&["toolchain", "install", &toolchain_version]).run()?;
Command::new("rustup").args(["toolchain", "install", &toolchain_version]).run()?;

let toolchain = home::rustup_home()?.join("toolchains").join(&toolchain_version);

Expand All @@ -165,7 +165,7 @@ fn setup_python_deps(kani_dir: &Path, os: &os_info::Info) -> Result<()> {
}

Command::new("python3")
.args(&["-m", "pip", "install", "--target"])
.args(["-m", "pip", "install", "--target"])
.arg(&pyroot)
.args(pkg_versions)
.run()?;
Expand Down
6 changes: 3 additions & 3 deletions tools/bookrunner/src/books.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ impl Book {
let summary_dir = summary_path.parent().unwrap().to_path_buf();
let summary = fs::read_to_string(summary_path.clone()).unwrap();
assert!(
summary.starts_with(&summary_start.as_str()),
summary.starts_with(summary_start.as_str()),
"Error: The start of {} summary file changed.",
self.name
);
Expand Down Expand Up @@ -409,7 +409,7 @@ fn extract(
config_paths: &mut HashSet<PathBuf>,
default_edition: Edition,
) {
let code = fs::read_to_string(&par_from).unwrap();
let code = fs::read_to_string(par_from).unwrap();
let mut examples = Examples(Vec::new());
find_testable_code(&code, &mut examples, ErrorCodes::No, false, None);
for mut example in examples.0 {
Expand Down Expand Up @@ -514,7 +514,7 @@ fn generate_text_bookrunner(bookrunner: bookrunner::Tree, path: &Path) {
bookrunner.data.num_fail,
bookrunner
);
fs::write(&path, bookrunner_str).expect("Error: Unable to write bookrunner results");
fs::write(path, bookrunner_str).expect("Error: Unable to write bookrunner results");
}

/// Runs examples using Litani build.
Expand Down
2 changes: 1 addition & 1 deletion tools/bookrunner/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ pub fn add_verification_job(litani: &mut Litani, test_props: &TestProps) {
// Add `--function main` so we can run these without having to amend them to add `#[kani::proof]`.
// Some of test_props.kani_args will contains `--cbmc-args` so we should always put that last.
kani.arg(&test_props.path)
.args(&["--enable-unstable", "--function", "main"])
.args(["--enable-unstable", "--function", "main"])
.args(&test_props.kani_args);
if !test_props.rustc_args.is_empty() {
kani.env("RUSTFLAGS", test_props.rustc_args.join(" "));
Expand Down
4 changes: 2 additions & 2 deletions tools/build-kani/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ fn bundle_kani(dir: &Path) -> Result<()> {

// 2. Kani scripts
let scripts = dir.join("scripts");
std::fs::create_dir(&scripts)?;
std::fs::create_dir(scripts)?;

// 3. Kani libraries
let library = dir.join("library");
Expand Down Expand Up @@ -148,7 +148,7 @@ fn bundle_kissat(dir: &Path) -> Result<()> {
/// This should include all files as `dir/<path>` in the tarball.
/// e.g. `kani-1.0/bin/kani-compiler` not just `bin/kani-compiler`.
fn create_release_bundle(dir: &Path, bundle: &str) -> Result<()> {
Command::new("tar").args(&["zcf", bundle]).arg(dir).run()
Command::new("tar").args(["zcf", bundle]).arg(dir).run()
}

/// Helper trait to fallibly run commands
Expand Down
2 changes: 1 addition & 1 deletion tools/build-kani/src/sysroot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ fn build_kani_lib(
/// Copy all the artifacts to their correct place to generate a valid sysroot.
fn copy_artifacts(artifacts: &[Artifact], sysroot_lib: &Path, target: &str) -> Result<()> {
// Create sysroot folder hierarchy.
sysroot_lib.exists().then(|| fs::remove_dir_all(&sysroot_lib));
sysroot_lib.exists().then(|| fs::remove_dir_all(sysroot_lib));
let std_path = path_buf!(&sysroot_lib, "rustlib", target, "lib");
fs::create_dir_all(&std_path).expect(&format!("Failed to create {std_path:?}"));

Expand Down
2 changes: 1 addition & 1 deletion tools/compiletest/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub fn extract_rendered(output: &str) -> String {
String::new(),
|mut output, item| {
use std::fmt::Write;
let _ = write!(output, "Future breakage diagnostic:\n");
let _ = writeln!(output, "Future breakage diagnostic:");
let s = item
.diagnostic
.rendered
Expand Down
4 changes: 2 additions & 2 deletions tools/compiletest/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ fn collect_rs_tests_from_dir(
// tests themselves, they race for the privilege of
// creating the directories and sometimes fail randomly.
let build_dir = output_relative_path(config, relative_dir_path);
fs::create_dir_all(&build_dir).unwrap();
fs::create_dir_all(build_dir).unwrap();

// Add each `.rs` file as a test, and recurse further on any
// subdirectories we find, except for `aux` directories.
Expand Down Expand Up @@ -571,7 +571,7 @@ fn make_test_name(config: &Config, testpaths: &TestPaths) -> test::TestName {
// ui/foo/bar/baz.rs
let path = PathBuf::from(config.src_base.file_name().unwrap())
.join(&testpaths.relative_dir)
.join(&testpaths.file.file_name().unwrap());
.join(testpaths.file.file_name().unwrap());

test::DynTestName(format!("[{}] {}", config.mode, path.display()))
}
Expand Down
Loading

0 comments on commit fece7ee

Please sign in to comment.