From b3147f2b6043ee273283dc45832da8757ab654d6 Mon Sep 17 00:00:00 2001 From: pentamassiv <91755244+pentamassiv@users.noreply.github.com> Date: Mon, 10 Oct 2022 11:06:07 +0200 Subject: [PATCH] Fixed various clippy lints (#1383) Fix clippy lints --- src/analysis/bounds.rs | 2 +- src/analysis/child_properties.rs | 6 +-- src/analysis/class_hierarchy.rs | 4 +- src/analysis/conversion_type.rs | 3 +- src/analysis/ffi_type.rs | 2 +- src/analysis/functions.rs | 13 ++---- src/analysis/imports.rs | 2 +- src/analysis/namespaces.rs | 4 +- src/analysis/out_parameters.rs | 2 +- src/analysis/properties.rs | 2 +- src/analysis/record.rs | 27 ++++++------ src/analysis/ref_mode.rs | 3 +- src/analysis/rust_type.rs | 32 ++++++++------ src/analysis/special_functions.rs | 4 +- src/analysis/symbols.rs | 9 ++-- src/codegen/child_properties.rs | 4 +- src/codegen/doc/gi_docgen.rs | 2 +- src/codegen/doc/mod.rs | 54 ++++++++++++------------ src/codegen/function.rs | 16 +++---- src/codegen/function_body_chunk.rs | 27 ++++++------ src/codegen/general.rs | 11 +++-- src/codegen/object.rs | 6 +-- src/codegen/properties.rs | 2 +- src/codegen/record.rs | 2 +- src/codegen/return_value.rs | 2 +- src/codegen/sys/cargo_toml.rs | 4 +- src/codegen/sys/ffi_type.rs | 10 ++--- src/codegen/sys/lib_.rs | 6 +-- src/codegen/trait_impls.rs | 4 +- src/codegen/translate_to_glib.rs | 14 +++--- src/config/config.rs | 6 +-- src/config/external_libraries.rs | 8 ++-- src/config/functions.rs | 4 +- src/config/gobjects.rs | 14 +++--- src/env.rs | 5 +-- src/file_saver.rs | 4 +- src/git.rs | 2 +- src/library.rs | 11 +++-- src/library_postprocessing.rs | 68 +++++++++++++++--------------- src/nameutil.rs | 9 ++-- src/parser.rs | 42 ++++-------------- src/writer/to_code.rs | 2 +- src/xmlparser.rs | 20 ++++----- 43 files changed, 218 insertions(+), 256 deletions(-) diff --git a/src/analysis/bounds.rs b/src/analysis/bounds.rs index fb1321be8..f83d9ce2b 100644 --- a/src/analysis/bounds.rs +++ b/src/analysis/bounds.rs @@ -177,7 +177,7 @@ impl Bounds { } } if (!need_is_into_check || !*par.nullable) && par.c_type != "GDestroyNotify" { - self.add_parameter(&par.name, &type_string, bound_type, r#async) + self.add_parameter(&par.name, &type_string, bound_type, r#async); } } } else if par.instance_parameter { diff --git a/src/analysis/child_properties.rs b/src/analysis/child_properties.rs index 39cbd4bf5..eb6af0fe4 100644 --- a/src/analysis/child_properties.rs +++ b/src/analysis/child_properties.rs @@ -44,11 +44,7 @@ pub fn analyze( return properties; } let config = config.unwrap(); - let child_name = config - .child_name - .as_ref() - .map(|s| &s[..]) - .unwrap_or("child"); + let child_name = config.child_name.as_ref().map_or("child", |s| s.as_str()); let child_type = config .child_type .as_ref() diff --git a/src/analysis/class_hierarchy.rs b/src/analysis/class_hierarchy.rs index 25fd5e6ca..350172201 100644 --- a/src/analysis/class_hierarchy.rs +++ b/src/analysis/class_hierarchy.rs @@ -35,7 +35,7 @@ fn get_node<'a>( let direct_supers: Vec = match library.type_(tid) { Type::Class(Class { parent, implements, .. - }) => parent.iter().chain(implements.iter()).cloned().collect(), + }) => parent.iter().chain(implements.iter()).copied().collect(), Type::Interface(Interface { prerequisites, .. }) => prerequisites.clone(), _ => return None, }; @@ -64,7 +64,7 @@ fn get_node<'a>( impl Info { pub fn subtypes<'a>(&'a self, tid: TypeId) -> Box + 'a> { match self.hier.get(&tid) { - Some(node) => Box::new(node.subs.iter().cloned()), + Some(node) => Box::new(node.subs.iter().copied()), None => Box::new(iter::empty()), } } diff --git a/src/analysis/conversion_type.rs b/src/analysis/conversion_type.rs index 14cabc608..f66e1fe0f 100644 --- a/src/analysis/conversion_type.rs +++ b/src/analysis/conversion_type.rs @@ -32,6 +32,8 @@ impl Default for ConversionType { impl ConversionType { pub fn of(env: &env::Env, type_id: TypeId) -> ConversionType { + use crate::library::{Basic::*, Type::*}; + let library = &env.library; if let Some(conversion_type) = env @@ -43,7 +45,6 @@ impl ConversionType { return conversion_type; } - use crate::library::{Basic::*, Type::*}; match library.type_(type_id) { Basic(fund) => match fund { Boolean => ConversionType::Scalar, diff --git a/src/analysis/ffi_type.rs b/src/analysis/ffi_type.rs index 1c35dab07..cd3a3eb83 100644 --- a/src/analysis/ffi_type.rs +++ b/src/analysis/ffi_type.rs @@ -181,7 +181,7 @@ fn fix_name(env: &Env, type_id: TypeId, name: &str) -> Result { let sys_crate_name = if sys_crate_name == "gobject_ffi" { use_glib_type(env, "gobject_ffi") } else if type_id.ns_id == MAIN_NAMESPACE { - sys_crate_name.to_owned() + sys_crate_name.clone() } else { format!( "{}::{}", diff --git a/src/analysis/functions.rs b/src/analysis/functions.rs index ccb7166a1..ab29687a1 100644 --- a/src/analysis/functions.rs +++ b/src/analysis/functions.rs @@ -175,7 +175,7 @@ pub fn analyze>( let func = func.borrow(); let configured_functions = obj.functions.matched(&func.name); let mut status = obj.status; - for f in configured_functions.iter() { + for f in &configured_functions { match f.status { GStatus::Ignore => continue 'func, GStatus::Manual => { @@ -923,7 +923,7 @@ fn analyze_function( async_future, callbacks, destroys, - remove_params: cross_user_data_check.values().cloned().collect::>(), + remove_params: cross_user_data_check.values().copied().collect::>(), commented, hidden: false, ns_id, @@ -935,12 +935,7 @@ pub fn is_carray_with_direct_elements(env: &Env, typ: library::TypeId) -> bool { match *env.library.type_(typ) { Type::CArray(inner_tid) => { use super::conversion_type::ConversionType; - match env.library.type_(inner_tid) { - Type::Basic(..) if ConversionType::of(env, inner_tid) == ConversionType::Direct => { - true - } - _ => false, - } + matches!(env.library.type_(inner_tid), Type::Basic(..) if ConversionType::of(env, inner_tid) == ConversionType::Direct) } _ => false, } @@ -1157,7 +1152,7 @@ fn analyze_callback( } }); } - for p in parameters.rust_parameters.iter() { + for p in ¶meters.rust_parameters { if let Ok(rust_type) = RustType::builder(env, p.typ) .direction(p.direction) .nullable(p.nullable) diff --git a/src/analysis/imports.rs b/src/analysis/imports.rs index 6b2cc63e1..f3c9d1f8a 100644 --- a/src/analysis/imports.rs +++ b/src/analysis/imports.rs @@ -312,7 +312,7 @@ impl<'a> ImportsWithDefault<'a> { impl Drop for ImportsWithDefault<'_> { fn drop(&mut self) { - self.imports.reset_defaults() + self.imports.reset_defaults(); } } diff --git a/src/analysis/namespaces.rs b/src/analysis/namespaces.rs index 974ec36a4..36bd26e0c 100644 --- a/src/analysis/namespaces.rs +++ b/src/analysis/namespaces.rs @@ -46,7 +46,7 @@ pub fn run(gir: &library::Library) -> Info { for (ns_id, ns) in gir.namespaces.iter().enumerate() { let ns_id = ns_id as NsId; let crate_name = nameutil::crate_name(&ns.name); - let (sys_crate_name, higher_crate_name) = match &crate_name[..] { + let (sys_crate_name, higher_crate_name) = match crate_name.as_str() { "gobject" => ("gobject_ffi".to_owned(), "glib".to_owned()), _ => ("ffi".to_owned(), crate_name.clone()), }; @@ -58,7 +58,7 @@ pub fn run(gir: &library::Library) -> Info { package_name: ns.package_name.clone(), symbol_prefixes: ns.symbol_prefixes.clone(), shared_libs: ns.shared_library.clone(), - versions: ns.versions.iter().cloned().collect(), + versions: ns.versions.iter().copied().collect(), }); if ns.name == "GLib" { glib_ns_id = Some(ns_id); diff --git a/src/analysis/out_parameters.rs b/src/analysis/out_parameters.rs index b5c8472c7..1b25e0fcd 100644 --- a/src/analysis/out_parameters.rs +++ b/src/analysis/out_parameters.rs @@ -150,7 +150,7 @@ fn analyze_type_imports(env: &Env, typ: TypeId, caller_allocates: bool, imports: Type::Alias(alias) => analyze_type_imports(env, alias.typ, caller_allocates, imports), Type::Bitfield(..) | Type::Enumeration(..) => imports.add("std::mem"), Type::Basic(fund) if !matches!(fund, Basic::Utf8 | Basic::OsString | Basic::Filename) => { - imports.add("std::mem") + imports.add("std::mem"); } _ if !caller_allocates => match ConversionType::of(env, typ) { ConversionType::Direct diff --git a/src/analysis/properties.rs b/src/analysis/properties.rs index d9a4db7c4..005b1b306 100644 --- a/src/analysis/properties.rs +++ b/src/analysis/properties.rs @@ -302,7 +302,7 @@ fn analyze_property( name: format!("notify::{}", name), parameters: Vec::new(), ret: library::Parameter { - name: "".into(), + name: String::new(), typ: env .library .find_type(library::INTERNAL_NAMESPACE, "none") diff --git a/src/analysis/record.rs b/src/analysis/record.rs index 9552dd319..c648f9b1c 100644 --- a/src/analysis/record.rs +++ b/src/analysis/record.rs @@ -176,20 +176,19 @@ pub fn new(env: &Env, obj: &GObject) -> Option { || !specials.has_trait(special_functions::Type::Free)) { if let Some((_, get_type_version)) = glib_get_type { - if get_type_version > version { - // FIXME: Ideally we would update it here but that requires fixing *all* the - // versions of functions in this and other types that use this type somewhere in - // the signature. Similar code exists for before the analysis already but that - // doesn't apply directly here. - // - // As the get_type function only has a version if explicitly configured let's just - // panic here. It's easy enough for the user to move the version configuration from - // the function to the type. - panic!( - "Have to use get_type function for {} but version is higher than for the type ({:?} > {:?})", - full_name, get_type_version, version - ); - } + // FIXME: Ideally we would update it here but that requires fixing *all* the + // versions of functions in this and other types that use this type somewhere in + // the signature. Similar code exists for before the analysis already but that + // doesn't apply directly here. + // + // As the get_type function only has a version if explicitly configured let's just + // panic here. It's easy enough for the user to move the version configuration from + // the function to the type. + assert!( + get_type_version <= version, + "Have to use get_type function for {} but version is higher than for the type ({:?} > {:?})", + full_name, get_type_version, version + ); } else { error!("Missing memory management functions for {}", full_name); } diff --git a/src/analysis/ref_mode.rs b/src/analysis/ref_mode.rs index 021a4d473..9879b5c07 100644 --- a/src/analysis/ref_mode.rs +++ b/src/analysis/ref_mode.rs @@ -18,6 +18,8 @@ impl RefMode { tid: library::TypeId, direction: library::ParameterDirection, ) -> RefMode { + use crate::library::Type::*; + let library = &env.library; if let Some(&GObject { @@ -32,7 +34,6 @@ impl RefMode { } } - use crate::library::Type::*; match library.type_(tid) { Basic(library::Basic::Utf8 | library::Basic::Filename | library::Basic::OsString) | Class(..) diff --git a/src/analysis/rust_type.rs b/src/analysis/rust_type.rs index d7bfe53de..cac8cbbee 100644 --- a/src/analysis/rust_type.rs +++ b/src/analysis/rust_type.rs @@ -35,14 +35,14 @@ impl RustType { RustTypeBuilder::new(env, type_id) } - fn new_and_use(rust_type: impl ToString) -> Self { + fn new_and_use(rust_type: &impl ToString) -> Self { RustType { inner: rust_type.to_string(), used_types: vec![rust_type.to_string()], } } - fn new_with_uses(rust_type: impl ToString, uses: &[impl ToString]) -> Self { + fn new_with_uses(rust_type: &impl ToString, uses: &[impl ToString]) -> Self { RustType { inner: rust_type.to_string(), used_types: uses.iter().map(ToString::to_string).collect(), @@ -52,7 +52,7 @@ impl RustType { fn check( env: &Env, type_id: library::TypeId, - type_name: impl ToString, + type_name: &impl ToString, ) -> result::Result { let mut type_name = type_name.to_string(); @@ -76,9 +76,11 @@ impl RustType { } fn try_new_and_use(env: &Env, type_id: library::TypeId) -> Result { - Self::check(env, type_id, env.library.type_(type_id).get_name()).map(|type_name| RustType { - inner: type_name.clone(), - used_types: vec![type_name], + Self::check(env, type_id, &env.library.type_(type_id).get_name()).map(|type_name| { + RustType { + inner: type_name.clone(), + used_types: vec![type_name], + } }) } @@ -87,7 +89,7 @@ impl RustType { type_id: library::TypeId, type_name: impl ToString, ) -> Result { - Self::check(env, type_id, type_name).map(|type_name| RustType { + Self::check(env, type_id, &type_name).map(|type_name| RustType { inner: type_name.clone(), used_types: vec![type_name], }) @@ -246,7 +248,7 @@ impl<'env> RustTypeBuilder<'env> { pub fn try_build(self) -> Result { use crate::library::{Basic::*, Type::*}; let ok = |s: &str| Ok(RustType::from(s)); - let ok_and_use = |s: &str| Ok(RustType::new_and_use(s)); + let ok_and_use = |s: &str| Ok(RustType::new_and_use(&s)); let err = |s: &str| Err(TypeError::Unimplemented(s.into())); let mut skip_option = false; let type_ = self.env.library.type_(self.type_id); @@ -438,7 +440,7 @@ impl<'env> RustTypeBuilder<'env> { } let mut params = Vec::with_capacity(f.parameters.len()); let mut err = false; - for p in f.parameters.iter() { + for p in &f.parameters { if p.closure.is_some() { continue; } @@ -571,14 +573,14 @@ impl<'env> RustTypeBuilder<'env> { if self.direction == ParameterDirection::In { rust_type = rust_type.map_any(|rust_type| { RustType::new_with_uses( - format!("impl Into<{}>", &rust_type.as_str()), + &format!("impl Into<{}>", &rust_type.as_str()), &[&rust_type.as_str()], ) }); } else { rust_type = rust_type.map_any(|_| { RustType::new_with_uses( - format!("Result<{}, {}>", &ok_type, &err_type), + &format!("Result<{}, {}>", &ok_type, &err_type), &[ok_type, err_type], ) }); @@ -611,9 +613,11 @@ impl<'env> RustTypeBuilder<'env> { use crate::library::Type::*; let type_ = self.env.library.type_(self.type_id); - if self.direction == ParameterDirection::None { - panic!("undefined direction for parameter with type {:?}", type_); - } + assert!( + self.direction != ParameterDirection::None, + "undefined direction for parameter with type {:?}", + type_ + ); let rust_type = RustType::builder(self.env, self.type_id) .direction(self.direction) diff --git a/src/analysis/special_functions.rs b/src/analysis/special_functions.rs index c6bc6e502..187158f0b 100644 --- a/src/analysis/special_functions.rs +++ b/src/analysis/special_functions.rs @@ -247,7 +247,7 @@ pub fn analyze_imports(specials: &Infos, imports: &mut Imports) { use self::Type::*; match type_ { Copy if info.first_parameter_mut => { - imports.add_with_version("glib::translate::*", info.version) + imports.add_with_version("glib::translate::*", info.version); } Compare => imports.add_with_version("std::cmp", info.version), Display => imports.add_with_version("std::fmt", info.version), @@ -259,7 +259,7 @@ pub fn analyze_imports(specials: &Infos, imports: &mut Imports) { for info in specials.functions().values() { match info.type_ { FunctionType::StaticStringify => { - imports.add_with_version("std::ffi::CStr", info.version) + imports.add_with_version("std::ffi::CStr", info.version); } } } diff --git a/src/analysis/symbols.rs b/src/analysis/symbols.rs index aa6b1aae0..3e8a6be93 100644 --- a/src/analysis/symbols.rs +++ b/src/analysis/symbols.rs @@ -43,10 +43,11 @@ impl Symbol { } fn make_in_prelude(&mut self) { - if self.module_name.replace("prelude".to_string()).is_some() { - // .expect_none is not stabilized yet - panic!("{:?} already had a module name set!", self) - } + assert!( + self.module_name.replace("prelude".to_string()).is_none(), + "{:?} already had a module name set!", + self + ); } /// Convert this symbol into a trait diff --git a/src/codegen/child_properties.rs b/src/codegen/child_properties.rs index 2d38348f2..1f99ff1c3 100644 --- a/src/codegen/child_properties.rs +++ b/src/codegen/child_properties.rs @@ -105,14 +105,14 @@ fn declaration(env: &Env, prop: &ChildProperty, is_get: bool) -> String { .into_string(); format!(" -> {}", ret_type) } else { - "".to_string() + String::new() }; format!( "fn {}<{}>(&self, item: &T{}){}", func_name, bounds, if is_get { - "".to_owned() + String::new() } else { format!(", {}", prop.set_params) }, diff --git a/src/codegen/doc/gi_docgen.rs b/src/codegen/doc/gi_docgen.rs index 21894396f..5b778820f 100644 --- a/src/codegen/doc/gi_docgen.rs +++ b/src/codegen/doc/gi_docgen.rs @@ -597,7 +597,7 @@ mod tests { namespace: Some("Gtk".to_string()), name: "MapListModelMapFunc".to_string() }) - ) + ); } #[test] diff --git a/src/codegen/doc/mod.rs b/src/codegen/doc/mod.rs index c3fbce253..19f82bc9f 100644 --- a/src/codegen/doc/mod.rs +++ b/src/codegen/doc/mod.rs @@ -140,7 +140,7 @@ fn generate_doc(w: &mut dyn Write, env: &Env) -> Result<()> { && !env.is_totally_deprecated(None, enum_.deprecated_version) { generators.push(( - &enum_.name[..], + enum_.name.as_str(), Box::new(move |w, e| create_enum_doc(w, e, enum_, tid)), )); } @@ -153,7 +153,7 @@ fn generate_doc(w: &mut dyn Write, env: &Env) -> Result<()> { && !env.is_totally_deprecated(None, bitfield.deprecated_version) { generators.push(( - &bitfield.name[..], + bitfield.name.as_str(), Box::new(move |w, e| create_bitfield_doc(w, e, bitfield, tid)), )); } @@ -177,11 +177,10 @@ fn generate_doc(w: &mut dyn Write, env: &Env) -> Result<()> { let fn_new_name = f_info.and_then(|analysed_f| analysed_f.new_name.clone()); let doc_trait_name = f_info.and_then(|f| f.doc_trait_name.as_ref()); let doc_struct_name = f_info.and_then(|f| f.doc_struct_name.as_ref()); - if doc_trait_name.is_some() && doc_struct_name.is_some() { - panic!( - "Can't use both doc_trait_name and doc_struct_name on the same function" - ); - } + assert!( + !(doc_trait_name.is_some() && doc_struct_name.is_some()), + "Can't use both doc_trait_name and doc_struct_name on the same function" + ); let parent = if doc_trait_name.is_some() { doc_trait_name.map(|p| Box::new(TypeStruct::new(SType::Trait, p))) @@ -195,9 +194,8 @@ fn generate_doc(w: &mut dyn Write, env: &Env) -> Result<()> { .map(|analyzed_f| analyzed_f.doc_ignore_parameters.clone()) .unwrap_or_default(); - let should_be_documented = f_info - .map(|f| f.should_docs_be_generated(env)) - .unwrap_or(false); + let should_be_documented = + f_info.map_or(false, |f| f.should_docs_be_generated(env)); if !should_be_documented { continue; } @@ -208,9 +206,9 @@ fn generate_doc(w: &mut dyn Write, env: &Env) -> Result<()> { function, parent, fn_new_name, - doc_ignored_parameters, + &doc_ignored_parameters, None, - f_info.map(|f| f.generate_doc).unwrap_or(true), + f_info.map_or(true, |f| f.generate_doc), )?; } } @@ -356,7 +354,7 @@ fn create_object_doc(w: &mut dyn Write, env: &Env, info: &analysis::object::Info _ => (), } } - for property in builder_properties.iter() { + for property in &builder_properties { let ty = TypeStruct { ty: SType::Fn, name: nameutil::signal_to_snake(&property.name), @@ -461,9 +459,7 @@ fn create_object_doc(w: &mut dyn Write, env: &Env, info: &analysis::object::Info }; if let Some(c_identifier) = &function.c_identifier { let f_info = info.functions.iter().find(|f| &f.glib_name == c_identifier); - let should_be_documented = f_info - .map(|f| f.should_docs_be_generated(env)) - .unwrap_or(false); + let should_be_documented = f_info.map_or(false, |f| f.should_docs_be_generated(env)); if !should_be_documented { continue; @@ -480,9 +476,9 @@ fn create_object_doc(w: &mut dyn Write, env: &Env, info: &analysis::object::Info function, Some(Box::new(ty)), fn_new_name, - doc_ignored_parameters, + &doc_ignored_parameters, Some((&info.type_id, object_location)), - f_info.map(|f| f.generate_doc).unwrap_or(true), + f_info.map_or(true, |f| f.generate_doc), )?; } } @@ -506,7 +502,7 @@ fn create_object_doc(w: &mut dyn Write, env: &Env, info: &analysis::object::Info signal, Some(Box::new(ty)), None, - HashSet::new(), + &HashSet::new(), Some((&info.type_id, object_location)), configured_signals.iter().all(|s| s.generate_doc), )?; @@ -585,9 +581,7 @@ fn create_record_doc(w: &mut dyn Write, env: &Env, info: &analysis::record::Info for function in &record.functions { if let Some(c_identifier) = &function.c_identifier { let f_info = info.functions.iter().find(|f| &f.glib_name == c_identifier); - let should_be_documented = f_info - .map(|f| f.should_docs_be_generated(env)) - .unwrap_or(false); + let should_be_documented = f_info.map_or(false, |f| f.should_docs_be_generated(env)); if !should_be_documented { continue; } @@ -599,9 +593,9 @@ fn create_record_doc(w: &mut dyn Write, env: &Env, info: &analysis::record::Info function, Some(Box::new(ty.clone())), fn_new_name, - HashSet::new(), + &HashSet::new(), Some((&info.type_id, None)), - f_info.map(|f| f.generate_doc).unwrap_or(true), + f_info.map_or(true, |f| f.generate_doc), )?; } } @@ -738,7 +732,7 @@ fn create_fn_doc( fn_: &T, parent: Option>, name_override: Option, - doc_ignored_parameters: HashSet, + doc_ignored_parameters: &HashSet, in_type: Option<(&TypeId, Option)>, generate_doc: bool, ) -> Result<()> @@ -807,7 +801,7 @@ where .iter() .enumerate() .filter_map(|(indice, param)| { - (!indices_to_ignore.contains(&(indice as u32))).then(|| param) + (!indices_to_ignore.contains(&(indice as u32))).then_some(param) }) .filter(|param| !param.instance_parameter) .collect(); @@ -828,7 +822,11 @@ where continue; } if let Some(ref doc) = parameter.doc { - writeln!(w, "## `{}`", nameutil::mangle_keywords(¶meter.name[..]))?; + writeln!( + w, + "## `{}`", + nameutil::mangle_keywords(parameter.name.as_str()) + )?; writeln!( w, "{}", @@ -863,7 +861,7 @@ where writeln!( w, "\n## `{}`", - nameutil::mangle_keywords(¶meter.name[..]) + nameutil::mangle_keywords(parameter.name.as_str()) )?; writeln!( w, diff --git a/src/codegen/function.rs b/src/codegen/function.rs index a2b0e7e5f..8072bfab8 100644 --- a/src/codegen/function.rs +++ b/src/codegen/function.rs @@ -80,7 +80,7 @@ pub fn generate( let mut commented = false; let mut comment_prefix = ""; let pub_prefix = if in_trait { - "".to_owned() + String::new() } else { format!("{} ", analysis.visibility) }; @@ -209,9 +209,9 @@ pub fn declaration(env: &Env, analysis: &analysis::functions::Info) -> String { let (bounds, _) = bounds(&analysis.bounds, &[], false, false); - for par in analysis.parameters.rust_parameters.iter() { + for par in &analysis.parameters.rust_parameters { if !param_str.is_empty() { - param_str.push_str(", ") + param_str.push_str(", "); } let c_par = &analysis.parameters.c_parameters[par.ind_c]; let s = c_par.to_parameter(env, &analysis.bounds, false); @@ -255,7 +255,7 @@ pub fn declaration_futures(env: &Env, analysis: &analysis::functions::Info) -> S } if pos - skipped > 0 { - param_str.push_str(", ") + param_str.push_str(", "); } let s = c_par.to_parameter(env, &analysis.bounds, true); @@ -359,10 +359,10 @@ pub fn body_chunk(env: &Env, analysis: &analysis::functions::Info) -> Chunk { ); } } else { - for trampoline in analysis.callbacks.iter() { + for trampoline in &analysis.callbacks { builder.callback(trampoline); } - for trampoline in analysis.destroys.iter() { + for trampoline in &analysis.destroys { builder.destroy(trampoline); } } @@ -377,7 +377,7 @@ pub fn body_chunk(env: &Env, analysis: &analysis::functions::Info) -> Chunk { let (bounds, bounds_names) = bounds(&analysis.bounds, &[], false, true); - builder.generate(env, bounds, bounds_names.join(", ")) + builder.generate(env, &bounds, &bounds_names.join(", ")) } pub fn body_chunk_futures( @@ -405,7 +405,7 @@ pub fn body_chunk_futures( safety_assertion_mode_to_str(async_future.assertion) )?; } - let skip = if async_future.is_method { 1 } else { 0 }; + let skip = usize::from(async_future.is_method); // Skip the instance parameter for par in analysis.parameters.rust_parameters.iter().skip(skip) { diff --git a/src/codegen/function_body_chunk.rs b/src/codegen/function_body_chunk.rs index dbaf35c72..f48d3815b 100644 --- a/src/codegen/function_body_chunk.rs +++ b/src/codegen/function_body_chunk.rs @@ -135,7 +135,7 @@ impl Builder { self.in_unsafe = in_unsafe; self } - pub fn generate(&self, env: &Env, bounds: String, bounds_names: String) -> Chunk { + pub fn generate(&self, env: &Env, bounds: &str, bounds_names: &str) -> Chunk { let mut body = Vec::new(); let mut uninitialized_vars = if self.outs_as_return { @@ -221,7 +221,7 @@ impl Builder { // Key: user data index // Value: the current pos in the tuple for the given argument. let mut poses = HashMap::with_capacity(group_by_user_data.len()); - for trampoline in self.callbacks.iter() { + for trampoline in &self.callbacks { *poses .entry(&trampoline.user_data_index) .or_insert_with(|| 0) += 1; @@ -231,7 +231,7 @@ impl Builder { .filter(|(_, x)| *x > 1) .map(|(x, _)| (x, 0)) .collect::>(); - for trampoline in self.callbacks.iter() { + for trampoline in &self.callbacks { let user_data_index = trampoline.user_data_index; let pos = poses.entry(&trampoline.user_data_index); self.add_trampoline( @@ -243,23 +243,23 @@ impl Builder { Entry::Occupied(ref x) => Some(*x.get()), _ => None, }, - &bounds, - &bounds_names, + bounds, + bounds_names, false, ); pos.and_modify(|x| { *x += 1; }); } - for destroy in self.destroys.iter() { + for destroy in &self.destroys { self.add_trampoline( env, &mut chunks, destroy, &group_by_user_data[&destroy.user_data_index].full_type, None, // doesn't matter for destroy - &bounds, - &bounds_names, + bounds, + bounds_names, true, ); } @@ -414,7 +414,7 @@ impl Builder { let mut body = Vec::new(); let mut arguments = Vec::new(); - for par in trampoline.parameters.transformations.iter() { + for par in &trampoline.parameters.transformations { if par.name == "this" || trampoline.parameters.c_parameters[par.ind_c].is_real_gpointer(env) { @@ -452,8 +452,7 @@ impl Builder { .parameters .c_parameters .last() - .map(|p| p.name.clone()) - .unwrap_or_else(|| "Unknown".to_owned()); + .map_or_else(|| "Unknown".to_owned(), |p| p.name.clone()); let mut extra_before_call = ""; if let Some(full_type) = full_type { @@ -1048,7 +1047,7 @@ impl Builder { }, )); } - for destroy in self.destroys.iter() { + for destroy in &self.destroys { to_insert.push(( destroy.destroy_index, Chunk::FfiCallParameter { @@ -1060,7 +1059,7 @@ impl Builder { } to_insert.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); for (pos, data) in to_insert { - params.insert(pos, data) + params.insert(pos, data); } params } @@ -1410,7 +1409,7 @@ fn add_chunk_for_type( type_name = format!(": Option<{}>", ty_name); } } else { - type_name = String::from(""); + type_name = String::new(); } body.push(Chunk::Custom(format!( diff --git a/src/codegen/general.rs b/src/codegen/general.rs index 95dbeadf1..543db3c28 100644 --- a/src/codegen/general.rs +++ b/src/codegen/general.rs @@ -148,7 +148,7 @@ pub fn define_fundamental_type( } else { let (ref_fn, unref_fn, ptr, ffi_crate_name) = parents .iter() - .filter_map(|p| { + .find_map(|p| { use crate::library::*; let type_ = env.library.type_(p.type_id); let parent_sys_crate_name = env.sys_crate_import(p.type_id); @@ -166,7 +166,6 @@ pub fn define_fundamental_type( _ => None, } }) - .next() .unwrap(); // otherwise get that information from the parent (ref_fn, unref_fn, ptr, ffi_crate_name) @@ -222,7 +221,7 @@ pub fn define_object_type( if let Some(s) = glib_class_name { format!(", {}::{}", sys_crate_name, s) } else { - "".to_string() + String::new() } }; @@ -706,7 +705,7 @@ pub fn version_condition_no_doc( commented, indent, ) { - writeln!(w, "{}", s)? + writeln!(w, "{}", s)?; } } Ok(()) @@ -721,7 +720,7 @@ pub fn version_condition_doc( match version { Some(v) if v > env.config.min_cfg_version => { if let Some(s) = cfg_condition_string_doc(Some(&v.to_cfg(None)), commented, indent) { - writeln!(w, "{}", s)? + writeln!(w, "{}", s)?; } } _ => {} @@ -983,7 +982,7 @@ pub fn escape_string(s: &str) -> String { '\"' | '\\' => es.push('\\'), _ => (), } - es.push(c) + es.push(c); } es } diff --git a/src/codegen/object.rs b/src/codegen/object.rs index d44a64080..04570b63e 100644 --- a/src/codegen/object.rs +++ b/src/codegen/object.rs @@ -106,7 +106,7 @@ pub fn generate( let mut previous_version = None; let mut previous_ns_id = None; - for (ns_id, versions) in namespaces.iter() { + for (ns_id, versions) in &namespaces { for (&version, stypes) in versions.iter().rev() { let supertypes = analysis .supertypes @@ -365,7 +365,7 @@ fn generate_builder(w: &mut dyn Write, env: &Env, analysis: &analysis::object::I .ref_mode(property.set_in_ref_mode) .try_build() .into_string(); - let (param_type_override, bounds, conversion) = match ¶m_type[..] { + let (param_type_override, bounds, conversion) = match param_type.as_str() { "&str" => (None, String::new(), ".to_string()"), "&[&str]" => (Some("Vec".to_string()), String::new(), ""), _ if !property.bounds.is_empty() => { @@ -602,7 +602,7 @@ pub fn generate_reexports( cfgs.push(cfg); } - contents.push("".to_owned()); + contents.push(String::new()); contents.extend_from_slice(&cfgs); contents.push(format!("mod {};", module_name)); contents.extend_from_slice(&cfgs); diff --git a/src/codegen/properties.rs b/src/codegen/properties.rs index f82ecedb5..dded354b7 100644 --- a/src/codegen/properties.rs +++ b/src/codegen/properties.rs @@ -113,7 +113,7 @@ fn declaration(env: &Env, prop: &Property) -> String { .into_string(); format!(" -> {}", ret_type) } else { - "".to_string() + String::new() }; format!( "fn {}{}(&self{}){}", diff --git a/src/codegen/record.rs b/src/codegen/record.rs index 4f99ddc97..c2a9f5156 100644 --- a/src/codegen/record.rs +++ b/src/codegen/record.rs @@ -166,7 +166,7 @@ pub fn generate_reexports( cfg.push_str(&s); cfg.push('\n'); }; - contents.push("".to_owned()); + contents.push(String::new()); contents.push(format!("{}mod {};", cfg, module_name)); contents.push(format!( "{}{} use self::{}::{};", diff --git a/src/codegen/return_value.rs b/src/codegen/return_value.rs index 40bf1f77b..431748e21 100644 --- a/src/codegen/return_value.rs +++ b/src/codegen/return_value.rs @@ -247,7 +247,7 @@ pub fn out_parameters_as_return(env: &Env, analysis: &analysis::functions::Info) } if pos > skip { - return_str.push_str(", ") + return_str.push_str(", "); } let s = out_parameter_as_return(out, env); return_str.push_str(&s); diff --git a/src/codegen/sys/cargo_toml.rs b/src/codegen/sys/cargo_toml.rs index 351a4df5d..5cd38c3f9 100644 --- a/src/codegen/sys/cargo_toml.rs +++ b/src/codegen/sys/cargo_toml.rs @@ -154,7 +154,7 @@ fn fill_in(root: &mut Table, env: &Env) { let meta = upsert_table(meta, nameutil::lib_name_to_toml(lib_name)); // Allow both the name and version of a system dep to be overridden by hand meta.entry("name") - .or_insert_with(|| Value::String(lib_name.to_owned())); + .or_insert_with(|| Value::String(lib_name.clone())); meta.entry("version") .or_insert_with(|| Value::String(env.config.min_cfg_version.to_string())); @@ -213,7 +213,7 @@ fn get_crate_name(config: &Config, root: &Table) -> String { if let Some(Value::Table(lib)) = root.get("lib") { if let Some(Value::String(lib_name)) = lib.get("name") { //Converting don't needed as library target names cannot contain hyphens - return lib_name.to_owned(); + return lib_name.clone(); } } if let Some(Value::Table(package)) = root.get("package") { diff --git a/src/codegen/sys/ffi_type.rs b/src/codegen/sys/ffi_type.rs index 4fa74e587..7c229ce9a 100644 --- a/src/codegen/sys/ffi_type.rs +++ b/src/codegen/sys/ffi_type.rs @@ -21,10 +21,7 @@ pub fn ffi_type(env: &Env, tid: library::TypeId, c_type: &str) -> Result { if env.library.type_(c_tid).maybe_ref_as::().is_some() { match *env.library.type_(tid) { Type::FixedArray(inner_tid, size, ref inner_c_type) => { - let inner_c_type = inner_c_type - .as_ref() - .map(String::as_str) - .unwrap_or_else(|| c_type); + let inner_c_type = inner_c_type.as_ref().map_or(c_type, String::as_str); ffi_type(env, inner_tid, inner_c_type).map_any(|rust_type| { rust_type.alter_type(|typ_| format!("[{}; {}]", typ_, size)) }) @@ -100,7 +97,7 @@ fn ffi_inner(env: &Env, tid: library::TypeId, mut inner: String) -> Result { OsString => "c_char", Type => "GType", Pointer => { - match &inner[..] { + match inner.as_str() { "void" => "c_void", "tm" => return Err(TypeError::Unimplemented(inner)), //TODO: try use time:Tm _ => &*inner, @@ -135,8 +132,7 @@ fn ffi_inner(env: &Env, tid: library::TypeId, mut inner: String) -> Result { Type::FixedArray(inner_tid, size, ref inner_c_type) => { let inner_c_type = inner_c_type .as_ref() - .map(String::as_str) - .unwrap_or_else(|| inner.as_str()); + .map_or_else(|| inner.as_str(), String::as_str); ffi_type(env, inner_tid, inner_c_type) .map_any(|rust_type| rust_type.alter_type(|typ_| format!("[{}; {}]", typ_, size))) } diff --git a/src/codegen/sys/lib_.rs b/src/codegen/sys/lib_.rs index 7505b926f..06eb07ef8 100644 --- a/src/codegen/sys/lib_.rs +++ b/src/codegen/sys/lib_.rs @@ -178,8 +178,7 @@ fn generate_bitfields(w: &mut dyn Write, env: &Env, items: &[&Bitfield]) -> Resu for member in &item.members { let member_config = config .as_ref() - .map(|c| c.members.matched(&member.name)) - .unwrap_or_else(Vec::new); + .map_or_else(Vec::new, |c| c.members.matched(&member.name)); let version = member_config .iter() .find_map(|m| m.version) @@ -281,8 +280,7 @@ fn generate_enums(w: &mut dyn Write, env: &Env, items: &[&Enumeration]) -> Resul for member in &item.members { let member_config = config .as_ref() - .map(|c| c.members.matched(&member.name)) - .unwrap_or_else(Vec::new); + .map_or_else(Vec::new, |c| c.members.matched(&member.name)); let is_alias = member_config.iter().any(|m| m.alias); let version = member_config .iter() diff --git a/src/codegen/trait_impls.rs b/src/codegen/trait_impls.rs index b1d4c1134..317603865 100644 --- a/src/codegen/trait_impls.rs +++ b/src/codegen/trait_impls.rs @@ -124,13 +124,13 @@ fn generate_display( scope_version: Option, cfg_condition: Option<&String>, ) -> Result<()> { + use crate::analysis::out_parameters::Mode; + writeln!(w)?; let version = Version::if_stricter_than(func.version, scope_version); version_condition(w, env, None, version, false, 0)?; cfg_condition_no_doc(w, cfg_condition, false, 0)?; - use crate::analysis::out_parameters::Mode; - let call = generate_call(func.codegen_name(), &[], trait_name); let body = if let Mode::Throws(_) = func.outs.mode { format!( diff --git a/src/codegen/translate_to_glib.rs b/src/codegen/translate_to_glib.rs index bd601bcb8..01ce3368d 100644 --- a/src/codegen/translate_to_glib.rs +++ b/src/codegen/translate_to_glib.rs @@ -65,26 +65,26 @@ fn to_glib_xxx( match transfer { None => { match ref_mode { - RefMode::None => ("".into(), ".to_glib_none_mut().0"), //unreachable!(), + RefMode::None => (String::new(), ".to_glib_none_mut().0"), //unreachable!(), RefMode::ByRef => match (move_, explicit_target_type.is_empty()) { - (true, true) => ("".into(), ".into_glib_ptr()"), + (true, true) => (String::new(), ".into_glib_ptr()"), (true, false) => ( format!("ToGlibPtr::<{}>::into_glib_ptr(", explicit_target_type), ")", ), - (false, true) => ("".into(), ".to_glib_none().0"), + (false, true) => (String::new(), ".to_glib_none().0"), (false, false) => ( format!("ToGlibPtr::<{}>::to_glib_none(", explicit_target_type), ").0", ), }, - RefMode::ByRefMut => ("".into(), ".to_glib_none_mut().0"), + RefMode::ByRefMut => (String::new(), ".to_glib_none_mut().0"), RefMode::ByRefImmut => ("mut_override(".into(), ".to_glib_none().0)"), RefMode::ByRefConst => ("const_override(".into(), ".to_glib_none().0)"), - RefMode::ByRefFake => ("".into(), ""), //unreachable!(), + RefMode::ByRefFake => (String::new(), ""), //unreachable!(), } } - Full => ("".into(), ".to_glib_full()"), - Container => ("".into(), ".to_glib_container().0"), + Full => (String::new(), ".to_glib_full()"), + Container => (String::new(), ".to_glib_container().0"), } } diff --git a/src/config/config.rs b/src/config/config.rs index ff2b1a8a3..c5b1a9fbd 100644 --- a/src/config/config.rs +++ b/src/config/config.rs @@ -30,7 +30,7 @@ fn normalize_path(path: impl AsRef) -> PathBuf { match (component, parts.last()) { (Component::CurDir, _) | (Component::ParentDir, Some(Component::RootDir)) => {} (Component::ParentDir, None | Some(Component::ParentDir)) => { - parts.push(Component::ParentDir) + parts.push(Component::ParentDir); } (Component::ParentDir, Some(_)) => { parts @@ -359,8 +359,8 @@ impl Config { external_libraries, objects, min_cfg_version, - make_backup, use_gi_docgen, + make_backup, generate_safety_asserts, deprecate_by_min_version, show_statistics, @@ -410,7 +410,7 @@ impl Config { } pub fn resolve_type_ids(&mut self, library: &Library) { - gobjects::resolve_type_ids(&mut self.objects, library) + gobjects::resolve_type_ids(&mut self.objects, library); } pub fn check_disable_format(&mut self) { diff --git a/src/config/external_libraries.rs b/src/config/external_libraries.rs index c0798f82f..34defbe23 100644 --- a/src/config/external_libraries.rs +++ b/src/config/external_libraries.rs @@ -31,10 +31,10 @@ pub fn read_external_libraries(toml: &toml::Value) -> Result Option { } pub fn parse_conversion_type(toml: Option<&Value>, object_name: &str) -> Option { + use crate::analysis::conversion_type::ConversionType::*; + let v = toml?; v.check_unwanted(&["variant", "ok_type", "err_type"], "conversion_type"); @@ -207,8 +209,6 @@ pub fn parse_conversion_type(toml: Option<&Value>, object_name: &str) -> Option< } }; - use crate::analysis::conversion_type::ConversionType::*; - let get_err_type = || -> Arc { err_type.map_or_else( || { @@ -377,12 +377,10 @@ fn parse_object( .unwrap_or(trust_return_value_nullability); let manual_traits = toml_object .lookup_vec("manual_traits", "IGNORED ERROR") - .map(|v| { - v.iter() - .filter_map(|v| v.as_str().map(String::from)) - .collect() - }) - .unwrap_or_else(|_| Vec::new()); + .into_iter() + .flatten() + .filter_map(|v| v.as_str().map(String::from)) + .collect(); let align = toml_object .lookup("align") .and_then(Value::as_integer) diff --git a/src/env.rs b/src/env.rs index 0bd3b3108..58fe12a69 100644 --- a/src/env.rs +++ b/src/env.rs @@ -33,8 +33,7 @@ impl Env { self.config .objects .get(name) - .map(|o| o.status) - .unwrap_or(GStatus::Generate) + .map_or(GStatus::Generate, |o| o.status) } pub fn is_totally_deprecated( @@ -80,7 +79,7 @@ impl Env { if crate_name == "gobject_ffi" { use_glib_type(self, crate_name) } else { - crate_name.to_owned() + crate_name.clone() } } } diff --git a/src/file_saver.rs b/src/file_saver.rs index 5e09ca52e..ee7d13680 100644 --- a/src/file_saver.rs +++ b/src/file_saver.rs @@ -16,11 +16,11 @@ where } if make_backup { - let _backuped = create_backup(&path) + let _backuped = create_backup(path) .unwrap_or_else(|why| panic!("couldn't create backup for {:?}: {:?}", path, why)); } let file = - File::create(&path).unwrap_or_else(|why| panic!("couldn't create {:?}: {}", path, why)); + File::create(path).unwrap_or_else(|why| panic!("couldn't create {:?}: {}", path, why)); let writer = BufWriter::new(file); let mut untabber = Untabber::new(Box::new(writer)); closure(&mut untabber).unwrap_or_else(|why| panic!("couldn't write to {:?}: {:?}", path, why)); diff --git a/src/git.rs b/src/git.rs index 736c1cb52..02a5c7180 100644 --- a/src/git.rs +++ b/src/git.rs @@ -61,7 +61,7 @@ fn path_command(path: impl AsRef, subcommand: &[&str]) -> Option output .stdout .pop() - .map(|c| c as u32) + .map(u32::from) .and_then(std::char::from_u32), Some('\n') ); diff --git a/src/library.rs b/src/library.rs index 735454e1a..20c1ddaad 100644 --- a/src/library.rs +++ b/src/library.rs @@ -745,8 +745,8 @@ impl Type { Enumeration(enum_) => Some(&enum_.c_type), Bitfield(bit_field) => Some(&bit_field.c_type), Record(rec) => Some(&rec.c_type), - Union(union) => union.c_type.as_ref().map(|s| &s[..]), - Function(func) => func.c_identifier.as_ref().map(|s| &s[..]), + Union(union) => union.c_type.as_deref(), + Function(func) => func.c_identifier.as_deref(), Interface(interface) => Some(&interface.c_type), Class(class) => Some(&class.c_type), _ => None, @@ -1030,7 +1030,7 @@ impl Namespace { } fn find_type(&self, name: &str) -> Option { - self.index.get(name).cloned() + self.index.get(name).copied() } } @@ -1108,8 +1108,7 @@ impl Library { .config .objects .get(&full_name) - .map(|obj| obj.generate_builder) - .unwrap_or_else(|| false) + .map_or(false, |obj| obj.generate_builder) && properties .iter() .any(|prop| prop.construct_only || prop.construct || prop.writable) @@ -1247,7 +1246,7 @@ impl Library { } pub fn find_namespace(&self, name: &str) -> Option { - self.index.get(name).cloned() + self.index.get(name).copied() } pub fn add_namespace(&mut self, name: &str) -> u16 { diff --git a/src/library_postprocessing.rs b/src/library_postprocessing.rs index 76dab9443..03e808495 100644 --- a/src/library_postprocessing.rs +++ b/src/library_postprocessing.rs @@ -64,12 +64,36 @@ impl Library { }) .collect(); - if !list.is_empty() { - panic!("Incomplete library, unresolved: {:?}", list); - } + assert!( + list.is_empty(), + "Incomplete library, unresolved: {:?}", + list + ); } fn fill_empty_signals_c_types(&mut self) { + fn update_empty_signals_c_types(signals: &mut [Signal], c_types: &DetectedCTypes) { + for signal in signals { + update_empty_signal_c_types(signal, c_types); + } + } + + fn update_empty_signal_c_types(signal: &mut Signal, c_types: &DetectedCTypes) { + for par in &mut signal.parameters { + update_empty_c_type(&mut par.c_type, par.typ, c_types); + } + update_empty_c_type(&mut signal.ret.c_type, signal.ret.typ, c_types); + } + + fn update_empty_c_type(c_type: &mut String, tid: TypeId, c_types: &DetectedCTypes) { + if !is_empty_c_type(c_type) { + return; + } + if let Some(s) = c_types.get(&tid) { + *c_type = s.clone(); + } + } + let mut tids = Vec::new(); let mut c_types = DetectedCTypes::new(); for (ns_id, ns) in self.namespaces.iter().enumerate() { @@ -95,33 +119,11 @@ impl Library { } } - fn update_empty_signals_c_types(signals: &mut [Signal], c_types: &DetectedCTypes) { - for signal in signals { - update_empty_signal_c_types(signal, c_types); - } - } - - fn update_empty_signal_c_types(signal: &mut Signal, c_types: &DetectedCTypes) { - for par in &mut signal.parameters { - update_empty_c_type(&mut par.c_type, par.typ, c_types); - } - update_empty_c_type(&mut signal.ret.c_type, signal.ret.typ, c_types); - } - - fn update_empty_c_type(c_type: &mut String, tid: TypeId, c_types: &DetectedCTypes) { - if !is_empty_c_type(c_type) { - return; - } - if let Some(s) = c_types.get(&tid) { - *c_type = s.clone(); - } - } - for tid in tids { match self.type_mut(tid) { Type::Class(klass) => update_empty_signals_c_types(&mut klass.signals, &c_types), Type::Interface(iface) => { - update_empty_signals_c_types(&mut iface.signals, &c_types) + update_empty_signals_c_types(&mut iface.signals, &c_types); } _ => (), } @@ -251,12 +253,12 @@ impl Library { if let Some(type_struct) = type_struct { let type_struct_tid = self.find_type(ns_id as u16, type_struct); - if type_struct_tid.is_none() { - panic!( - "\"{}\" has glib:type-struct=\"{}\" but there is no such record", - name, type_struct - ); - } + assert!( + type_struct_tid.is_some(), + "\"{}\" has glib:type-struct=\"{}\" but there is no such record", + name, + type_struct + ); let type_struct_type = self.type_(type_struct_tid.unwrap()); @@ -392,7 +394,7 @@ impl Library { }; match type_ { Type::Union(Union { fields, .. }) if fields.as_slice().is_incomplete(self) => { - unrepresentable.push(tid) + unrepresentable.push(tid); } _ => {} } diff --git a/src/nameutil.rs b/src/nameutil.rs index 90e042160..4bd612971 100644 --- a/src/nameutil.rs +++ b/src/nameutil.rs @@ -6,9 +6,10 @@ static mut CRATE_NAME_OVERRIDES: Option> = None; pub(crate) fn set_crate_name_overrides(overrides: HashMap) { unsafe { - if CRATE_NAME_OVERRIDES.is_some() { - panic!("Crate name overrides already set;"); - } + assert!( + CRATE_NAME_OVERRIDES.is_none(), + "Crate name overrides already set" + ); CRATE_NAME_OVERRIDES = Some(overrides); } } @@ -123,7 +124,7 @@ pub fn signal_to_snake(signal: &str) -> String { } pub fn lib_name_to_toml(name: &str) -> String { - name.to_string().replace(&['-', '.'], "_") + name.to_string().replace(['-', '.'], "_") } pub fn shared_lib_name_to_link_name(name: &str) -> &str { diff --git a/src/parser.rs b/src/parser.rs index f6fec73e6..8cdab8e3f 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -152,7 +152,7 @@ impl Library { let get_type = elem.attr_required("get-type")?; let version = self.read_version(parser, ns_id, elem)?; let deprecated_version = self.read_deprecated_version(parser, ns_id, elem)?; - let is_fundamental = elem.attr("fundamental").map(|x| x == "1").unwrap_or(false); + let is_fundamental = elem.attr("fundamental").map_or(false, |x| x == "1"); let (ref_fn, unref_fn) = if is_fundamental { ( elem.attr("ref-func").map(ToOwned::to_owned), @@ -162,7 +162,7 @@ impl Library { (None, None) }; - let is_abstract = elem.attr("abstract").map(|x| x == "1").unwrap_or(false); + let is_abstract = elem.attr("abstract").map_or(false, |x| x == "1"); let mut fns = Vec::new(); let mut signals = Vec::new(); @@ -313,25 +313,13 @@ impl Library { u = Union { name: format!( "{}{}_{}", - parent_name_prefix - .map(|s| { - let mut s = String::from(s); - s.push('_'); - s - }) - .unwrap_or_else(String::new), + parent_name_prefix.map_or_else(String::new, |s| { format!("{}_", s) }), record_name, field_name ), c_type: Some(format!( "{}{}_{}", - parent_ctype_prefix - .map(|s| { - let mut s = String::from(s); - s.push('_'); - s - }) - .unwrap_or_else(String::new), + parent_ctype_prefix.map_or_else(String::new, |s| { format!("{}_", s) }), c_type, field_name )), @@ -470,25 +458,13 @@ impl Library { r = Record { name: format!( "{}{}_{}", - parent_name_prefix - .map(|s| { - let mut s = String::from(s); - s.push('_'); - s - }) - .unwrap_or_else(String::new), + parent_name_prefix.map_or_else(String::new, |s| { format!("{}_", s) }), union_name, field_name ), c_type: format!( "{}{}_{}", - parent_ctype_prefix - .map(|s| { - let mut s = String::from(s); - s.push('_'); - s - }) - .unwrap_or_else(String::new), + parent_ctype_prefix.map_or_else(String::new, |s| { format!("{}_", s) }), c_type, field_name ), @@ -1015,7 +991,7 @@ impl Library { fns: &mut Vec, ) -> Result<(), String> { if let Some(f) = self.read_function_if_not_moved(parser, ns_id, elem.name(), elem)? { - fns.push(f) + fns.push(f); } Ok(()) } @@ -1199,9 +1175,9 @@ impl Library { }) } else if varargs { Ok(Parameter { - name: "".into(), + name: String::new(), typ: self.find_type(INTERNAL_NAMESPACE, "varargs").unwrap(), - c_type: "".into(), + c_type: String::new(), instance_parameter, direction: Default::default(), transfer: Transfer::None, diff --git a/src/writer/to_code.rs b/src/writer/to_code.rs index f9510cdb8..057133992 100644 --- a/src/writer/to_code.rs +++ b/src/writer/to_code.rs @@ -71,7 +71,7 @@ impl ToCode for Chunk { let type_strings = type_.to_code(env); format_block_one_line(": ", "", &type_strings, "", "") } else { - "".to_owned() + String::new() }; let value_strings = value.to_code(env); let prefix = format!("let {}{}{} = ", modif, name, type_string); diff --git a/src/xmlparser.rs b/src/xmlparser.rs index e860769dc..abdd80e42 100644 --- a/src/xmlparser.rs +++ b/src/xmlparser.rs @@ -142,7 +142,7 @@ impl Element { impl<'a> XmlParser<'a> { pub fn from_path(path: &Path) -> Result, String> { - match File::open(&path) { + match File::open(path) { Err(e) => Err(format!("Can't open file \"{}\": {}", path.display(), e)), Ok(file) => Ok(XmlParser { parser: EventReader::new(Box::new(BufReader::new(file))), @@ -156,13 +156,13 @@ impl<'a> XmlParser<'a> { } #[cfg(test)] - pub fn new<'r, R: 'r + Read>(read: R) -> Result, String> { - Ok(XmlParser { + pub fn new<'r, R: 'r + Read>(read: R) -> XmlParser<'r> { + XmlParser { parser: EventReader::new(Box::new(read)), peek_event: None, peek_position: TextPosition::new(), error_emitter: Rc::new(ErrorEmitter { path: None }), - }) + } } /// Returns an error that combines current position and given error message. @@ -354,22 +354,22 @@ mod tests { where F: FnOnce(XmlParser<'_>) -> Result, { - f(XmlParser::new(xml)?) + f(XmlParser::new(xml)) } #[test] fn test_element_with_name() { - let xml = br#" - - - "#; - fn parse_with_root_name(xml: &[u8], root: &str) -> Result<(), String> { with_parser(xml, |mut p| { p.document(|p, _| p.element_with_name(root, |_, _elem| Ok(()))) }) } + let xml = br#" + + + "#; + assert!(parse_with_root_name(xml, "a").is_ok()); assert!(parse_with_root_name(xml, "b").is_err()); }