diff --git a/build.rs b/build.rs index 8390b5f6..c6e8a799 100644 --- a/build.rs +++ b/build.rs @@ -3,10 +3,10 @@ fn generate_tests() { use std::ffi::OsStr; use std::fs::{self, File}; use std::io::Write; - use std::path::{Path, PathBuf}; + use std::path::PathBuf; let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); - let mut dst = File::create(Path::new(&out_dir).join("tests.rs")).unwrap(); + let mut dst = File::create(out_dir.join("tests.rs")).unwrap(); let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let tests_dir = manifest_dir.join("tests").join("rust"); @@ -55,10 +55,10 @@ fn generate_depfile_tests() { use std::env; use std::fs::{self, File}; use std::io::Write; - use std::path::{Path, PathBuf}; + use std::path::PathBuf; let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); - let mut dst = File::create(Path::new(&out_dir).join("depfile_tests.rs")).unwrap(); + let mut dst = File::create(out_dir.join("depfile_tests.rs")).unwrap(); let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let tests_dir = manifest_dir.join("tests").join("depfile"); diff --git a/src/bindgen/bindings.rs b/src/bindgen/bindings.rs index dbd0b7d6..eceeba09 100644 --- a/src/bindgen/bindings.rs +++ b/src/bindgen/bindings.rs @@ -7,7 +7,7 @@ use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::fs::File; -use std::io::{BufWriter, Read, Write}; +use std::io::{BufWriter, Write}; use std::path; use std::rc::Rc; @@ -243,7 +243,7 @@ impl Bindings { // Don't compare files if we've never written this file before if !path.as_ref().is_file() { - if let Some(parent) = path::Path::new(path.as_ref()).parent() { + if let Some(parent) = path.as_ref().parent() { fs::create_dir_all(parent).unwrap(); } self.write(File::create(path).unwrap()); @@ -253,15 +253,10 @@ impl Bindings { let mut new_file_contents = Vec::new(); self.write(&mut new_file_contents); - let mut old_file_contents = Vec::new(); - { - let mut old_file = File::open(&path).unwrap(); - old_file.read_to_end(&mut old_file_contents).unwrap(); - } + let old_file_contents = std::fs::read(&path).unwrap(); if old_file_contents != new_file_contents { - let mut new_file = File::create(&path).unwrap(); - new_file.write_all(&new_file_contents).unwrap(); + std::fs::write(&path, &new_file_contents).unwrap(); true } else { false diff --git a/src/bindgen/builder.rs b/src/bindgen/builder.rs index 74aeef1b..8521b706 100644 --- a/src/bindgen/builder.rs +++ b/src/bindgen/builder.rs @@ -381,11 +381,11 @@ impl Builder { result.extend_with(&parser::parse_src(x, &self.config)?); } - if let Some((lib_dir, binding_lib_name)) = self.lib.clone() { + if let Some((lib_dir, binding_lib_name)) = &self.lib { let lockfile = self.lockfile.as_deref(); let cargo = Cargo::load( - &lib_dir, + lib_dir, lockfile, binding_lib_name.as_deref(), self.config.parse.parse_deps, diff --git a/src/bindgen/cargo/cargo.rs b/src/bindgen/cargo/cargo.rs index c8f820ce..f5e5de46 100644 --- a/src/bindgen/cargo/cargo.rs +++ b/src/bindgen/cargo/cargo.rs @@ -17,7 +17,7 @@ use crate::bindgen::ir::Cfg; fn parse_dep_string(dep_string: &str) -> (&str, Option<&str>) { let split: Vec<&str> = dep_string.split_whitespace().collect(); - (split[0], split.get(1).cloned()) + (split[0], split.get(1).copied()) } /// A collection of metadata for a library from cargo. @@ -207,14 +207,8 @@ impl Cargo { /// Finds the directory for a specified package reference. #[allow(unused)] pub(crate) fn find_crate_dir(&self, package: &PackageRef) -> Option { - self.metadata - .packages - .get(package) - .and_then(|meta_package| { - Path::new(&meta_package.manifest_path) - .parent() - .map(|x| x.to_owned()) - }) + let meta_package = self.metadata.packages.get(package)?; + Some(Path::new(&meta_package.manifest_path).parent()?.to_owned()) } /// Finds `src/lib.rs` for a specified package reference. @@ -225,22 +219,18 @@ impl Cargo { let kind_cdylib = String::from("cdylib"); let kind_dylib = String::from("dylib"); - self.metadata - .packages - .get(package) - .and_then(|meta_package| { - for target in &meta_package.targets { - if target.kind.contains(&kind_lib) - || target.kind.contains(&kind_staticlib) - || target.kind.contains(&kind_rlib) - || target.kind.contains(&kind_cdylib) - || target.kind.contains(&kind_dylib) - { - return Some(PathBuf::from(&target.src_path)); - } - } - None - }) + let meta_package = self.metadata.packages.get(package)?; + for target in &meta_package.targets { + if target.kind.contains(&kind_lib) + || target.kind.contains(&kind_staticlib) + || target.kind.contains(&kind_rlib) + || target.kind.contains(&kind_cdylib) + || target.kind.contains(&kind_dylib) + { + return Some(PathBuf::from(&target.src_path)); + } + } + None } pub(crate) fn expand_crate( diff --git a/src/bindgen/cargo/cargo_expand.rs b/src/bindgen/cargo/cargo_expand.rs index ed46a583..dc4df40b 100644 --- a/src/bindgen/cargo/cargo_expand.rs +++ b/src/bindgen/cargo/cargo_expand.rs @@ -105,14 +105,7 @@ pub fn expand( cmd.arg(manifest_path); if let Some(features) = expand_features { cmd.arg("--features"); - let mut features_str = String::new(); - for (index, feature) in features.iter().enumerate() { - if index != 0 { - features_str.push(' '); - } - features_str.push_str(feature); - } - cmd.arg(features_str); + cmd.arg(features.join(" ")); } if expand_all_features { cmd.arg("--all-features"); diff --git a/src/bindgen/cargo/cargo_lock.rs b/src/bindgen/cargo/cargo_lock.rs index a770ede9..e24abf0a 100644 --- a/src/bindgen/cargo/cargo_lock.rs +++ b/src/bindgen/cargo/cargo_lock.rs @@ -2,15 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use std::fs::File; use std::io; -use std::io::Read; use std::path::Path; #[derive(Debug)] -/// Possible errors that can occur during Cargo.toml parsing. +/// Possible errors that can occur during Cargo.lock parsing. pub enum Error { - /// Error during reading of Cargo.toml + /// Error during reading of Cargo.lock #[allow(dead_code)] Io(io::Error), /// Deserialization error @@ -43,11 +41,8 @@ pub struct Package { pub dependencies: Option>, } -/// Parse the Cargo.toml for a given path +/// Parse the Cargo.lock for a given path pub fn lock(manifest_path: &Path) -> Result { - let mut s = String::new(); - let mut f = File::open(manifest_path)?; - f.read_to_string(&mut s)?; - + let s = std::fs::read_to_string(manifest_path)?; toml::from_str::(&s).map_err(|x| x.into()) } diff --git a/src/bindgen/cargo/cargo_toml.rs b/src/bindgen/cargo/cargo_toml.rs index 998176e0..0c525477 100644 --- a/src/bindgen/cargo/cargo_toml.rs +++ b/src/bindgen/cargo/cargo_toml.rs @@ -4,9 +4,7 @@ use std::error; use std::fmt; -use std::fs::File; use std::io; -use std::io::Read; use std::path::Path; #[derive(Debug)] @@ -59,9 +57,6 @@ pub struct Package { /// Parse the Cargo.toml for a given path pub fn manifest(manifest_path: &Path) -> Result { - let mut s = String::new(); - let mut f = File::open(manifest_path)?; - f.read_to_string(&mut s)?; - + let s = std::fs::read_to_string(manifest_path)?; toml::from_str::(&s).map_err(|x| x.into()) } diff --git a/src/bindgen/config.rs b/src/bindgen/config.rs index e92b6547..acffa3b2 100644 --- a/src/bindgen/config.rs +++ b/src/bindgen/config.rs @@ -451,17 +451,15 @@ impl Default for FunctionConfig { impl FunctionConfig { pub(crate) fn prefix(&self, annotations: &AnnotationSet) -> Option { - if let Some(x) = annotations.atom("prefix") { - return x; - } - self.prefix.clone() + annotations + .atom("prefix") + .unwrap_or_else(|| self.prefix.clone()) } pub(crate) fn postfix(&self, annotations: &AnnotationSet) -> Option { - if let Some(x) = annotations.atom("postfix") { - return x; - } - self.postfix.clone() + annotations + .atom("postfix") + .unwrap_or_else(|| self.postfix.clone()) } } @@ -506,52 +504,32 @@ pub struct StructConfig { impl StructConfig { pub(crate) fn derive_constructor(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-constructor") { - return x; - } - self.derive_constructor + annotations + .bool("derive-constructor") + .unwrap_or(self.derive_constructor) } pub(crate) fn derive_eq(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-eq") { - return x; - } - self.derive_eq + annotations.bool("derive-eq").unwrap_or(self.derive_eq) } pub(crate) fn derive_neq(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-neq") { - return x; - } - self.derive_neq + annotations.bool("derive-neq").unwrap_or(self.derive_neq) } pub(crate) fn derive_lt(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-lt") { - return x; - } - self.derive_lt + annotations.bool("derive-lt").unwrap_or(self.derive_lt) } pub(crate) fn derive_lte(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-lte") { - return x; - } - self.derive_lte + annotations.bool("derive-lte").unwrap_or(self.derive_lte) } pub(crate) fn derive_gt(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-gt") { - return x; - } - self.derive_gt + annotations.bool("derive-gt").unwrap_or(self.derive_gt) } pub(crate) fn derive_gte(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-gte") { - return x; - } - self.derive_gte + annotations.bool("derive-gte").unwrap_or(self.derive_gte) } pub(crate) fn derive_ostream(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-ostream") { - return x; - } - self.derive_ostream + annotations + .bool("derive-ostream") + .unwrap_or(self.derive_ostream) } } @@ -640,67 +618,55 @@ impl Default for EnumConfig { impl EnumConfig { pub(crate) fn add_sentinel(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("add-sentinel") { - return x; - } - self.add_sentinel + annotations + .bool("add-sentinel") + .unwrap_or(self.add_sentinel) } pub(crate) fn derive_helper_methods(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-helper-methods") { - return x; - } - self.derive_helper_methods + annotations + .bool("derive-helper-methods") + .unwrap_or(self.derive_helper_methods) } pub(crate) fn derive_const_casts(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-const-casts") { - return x; - } - self.derive_const_casts + annotations + .bool("derive-const-casts") + .unwrap_or(self.derive_const_casts) } pub(crate) fn derive_mut_casts(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-mut-casts") { - return x; - } - self.derive_mut_casts + annotations + .bool("derive-mut-casts") + .unwrap_or(self.derive_mut_casts) } pub(crate) fn derive_tagged_enum_destructor(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-tagged-enum-destructor") { - return x; - } - self.derive_tagged_enum_destructor + annotations + .bool("derive-tagged-enum-destructor") + .unwrap_or(self.derive_tagged_enum_destructor) } pub(crate) fn derive_tagged_enum_copy_constructor(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-tagged-enum-copy-constructor") { - return x; - } - self.derive_tagged_enum_copy_constructor + annotations + .bool("derive-tagged-enum-copy-constructor") + .unwrap_or(self.derive_tagged_enum_copy_constructor) } pub(crate) fn derive_tagged_enum_copy_assignment(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-tagged-enum-copy-assignment") { - return x; - } - self.derive_tagged_enum_copy_assignment + annotations + .bool("derive-tagged-enum-copy-assignment") + .unwrap_or(self.derive_tagged_enum_copy_assignment) } pub(crate) fn derive_ostream(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("derive-ostream") { - return x; - } - self.derive_ostream + annotations + .bool("derive-ostream") + .unwrap_or(self.derive_ostream) } pub(crate) fn enum_class(&self, annotations: &AnnotationSet) -> bool { - if let Some(x) = annotations.bool("enum-class") { - return x; - } - self.enum_class + annotations.bool("enum-class").unwrap_or(self.enum_class) } pub(crate) fn private_default_tagged_enum_constructor( &self, annotations: &AnnotationSet, ) -> bool { - if let Some(x) = annotations.bool("private-default-tagged-enum-constructor") { - return x; - } - self.private_default_tagged_enum_constructor + annotations + .bool("private-default-tagged-enum-constructor") + .unwrap_or(self.private_default_tagged_enum_constructor) } } diff --git a/src/bindgen/ir/annotation.rs b/src/bindgen/ir/annotation.rs index ec0c6e79..05507c6e 100644 --- a/src/bindgen/ir/annotation.rs +++ b/src/bindgen/ir/annotation.rs @@ -210,17 +210,11 @@ impl AnnotationSet { /// Parse lists like "[x, y, z]". This is not implemented efficiently or well. fn parse_list(list: &str) -> Option> { - if list.len() < 2 { - return None; - } - - match (list.chars().next(), list.chars().last()) { - (Some('['), Some(']')) => Some( - list[1..list.len() - 1] - .split(',') - .map(|x| x.trim().to_string()) - .collect(), - ), - _ => None, - } + let parsed = list + .strip_prefix('[')? + .strip_suffix(']')? + .split(',') + .map(|x| x.trim().to_string()) + .collect(); + Some(parsed) } diff --git a/src/bindgen/ir/function.rs b/src/bindgen/ir/function.rs index e4bfb95d..715fa236 100644 --- a/src/bindgen/ir/function.rs +++ b/src/bindgen/ir/function.rs @@ -101,13 +101,11 @@ impl Function { .trim_start_matches(type_name) .trim_start_matches('_'); - let item_args = { - let mut items = Vec::with_capacity(self.args.len()); - for arg in self.args.iter() { - items.push(format!("{}:", arg.name.as_ref()?.as_str())); - } - items.join("") - }; + let item_args = self + .args + .iter() + .map(|arg| Some(format!("{}:", arg.name.as_ref()?.as_str()))) + .collect::>()?; Some(format!("{type_prefix}{item_name}({item_args})")) } @@ -188,8 +186,7 @@ impl Function { // Save the array length of the pointer arguments which need to use // the C-array notation if let Some(tuples) = self.annotations.list("ptrs-as-arrays") { - let mut ptrs_as_arrays: HashMap = HashMap::new(); - for str_tuple in tuples { + let ptrs_as_arrays: HashMap = tuples.iter().filter_map(|str_tuple| { let parts: Vec<&str> = str_tuple[1..str_tuple.len() - 1] .split(';') .map(|x| x.trim()) @@ -198,10 +195,10 @@ impl Function { warn!( "{parts:?} does not follow the correct syntax, so the annotation is being ignored" ); - continue; + return None; } - ptrs_as_arrays.insert(parts[0].to_string(), parts[1].to_string()); - } + Some((parts[0].to_string(), parts[1].to_string())) + }).collect(); for arg in &mut self.args { match arg.ty { diff --git a/src/bindgen/utilities.rs b/src/bindgen/utilities.rs index 6c58b6de..07e701a5 100644 --- a/src/bindgen/utilities.rs +++ b/src/bindgen/utilities.rs @@ -269,29 +269,32 @@ pub trait SynAttributeHelpers { } fn unsafe_attr_name_value_lookup(&self, name: &str) -> Option { - self.attrs() - .iter() - .filter_map(|attr| { - let syn::Meta::List(list) = &attr.meta else { return None }; - if !list.path.is_ident("unsafe") { - return None; + self.attrs().iter().find_map(|attr| { + let syn::Meta::List(list) = &attr.meta else { + return None; + }; + if !list.path.is_ident("unsafe") { + return None; + } + let parser = + syn::punctuated::Punctuated::::parse_terminated; + let Ok(args) = list.parse_args_with(parser) else { + return None; + }; + for arg in args { + if !arg.path.is_ident(name) { + continue; } - let parser = syn::punctuated::Punctuated::::parse_terminated; - let Ok(args) = list.parse_args_with(parser) else { return None }; - for arg in args { - if !arg.path.is_ident(name) { - continue; - } - if let syn::Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(lit), - .. - }) = arg.value { - return Some(lit.value()); - } + if let syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(lit), + .. + }) = arg.value + { + return Some(lit.value()); } - None - }) - .next() + } + None + }) } fn get_comment_lines(&self) -> Vec {