diff --git a/.github/workflows/github-cxx-qt-tests.yml b/.github/workflows/github-cxx-qt-tests.yml index 502d00e54..649c69048 100644 --- a/.github/workflows/github-cxx-qt-tests.yml +++ b/.github/workflows/github-cxx-qt-tests.yml @@ -159,7 +159,7 @@ jobs: # cargo install --locked --no-default-features --version 0.9.1 sccache run: | cargo install --locked --no-default-features --git=https://github.com/ahayzen-kdab/sccache --branch=2092-ignore-notfound-errors sccache - cargo install --locked --version 0.4.36 mdbook + cargo install --locked --version 0.4.36 mdbook cargo install --locked --version 0.7.7 mdbook-linkcheck # We want our compiler cache to always update to the newest state. # The best way for us to achieve this is to **always** update the cache after every landed commit. @@ -203,7 +203,7 @@ jobs: ./emsdk/emsdk install 2.0.14 ./emsdk/emsdk activate 2.0.14 - name: "Install Dependencies" - run: | + run: | sudo apt-get update && sudo apt-get install -y ninja-build pip install --user --break-system-packages clang-format==18.1.8 test -x ~/.local/bin/clang-format @@ -426,12 +426,12 @@ jobs: - name: "Clone Git repository" uses: actions/checkout@v5 # Ensure clippy and rustfmt is installed, they should come from github runner - # clippy version needs to be 1.78.0 for the MSRV lint + # clippy version needs to be 1.87.0 for all lints # # Note we still need rustfmt for the cxx-qt-gen tests - name: "Install Rust toolchain" run: | - rustup toolchain add 1.78.0 --component clippy + rustup toolchain add 1.87.0 --component clippy rustup default 1.77.2 rustup component add rustfmt @@ -450,7 +450,7 @@ jobs: # cargo install --locked --no-default-features --version 0.9.1 sccache run: | cargo install --locked --no-default-features --git=https://github.com/ahayzen-kdab/sccache --branch=2092-ignore-notfound-errors sccache - cargo install --locked --version 0.4.36 mdbook + cargo install --locked --version 0.4.36 mdbook cargo install --locked --version 0.7.7 mdbook-linkcheck # We want our compiler cache to always update to the newest state. diff --git a/CMakeLists.txt b/CMakeLists.txt index 3f5846b73..d0d7bfd40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,7 +49,7 @@ if(NOT USE_QT5) endif() if(NOT Qt6_FOUND) if(BUILD_WASM) - message(FATAL_ERROR + message(FATAL_ERROR "CXX-Qt for WebAssembly only currently supports Qt 6 builds." ) endif() @@ -151,8 +151,8 @@ if(BUILD_TESTING) # Add CMake tests for `cargo test/clippy/fmt/doc`. add_test(NAME cargo_tests COMMAND cargo test --locked --release --all-features --target-dir ${CARGO_TARGET_DIR}) add_test(NAME cargo_doc COMMAND cargo doc --locked --release --all-features --target-dir ${CARGO_TARGET_DIR}) - # Minimum clippy version for the incompatible_msrv lint is 1.78.0 - add_test(NAME cargo_clippy COMMAND cargo +1.78.0 clippy --locked --release --all-features --target-dir ${CARGO_TARGET_DIR} -- -D warnings) + # Minimum clippy version for all lints is 1.87.0 + add_test(NAME cargo_clippy COMMAND cargo +1.87.0 clippy --locked --release --all-features --target-dir ${CARGO_TARGET_DIR} -- -D warnings) set_tests_properties(cargo_tests cargo_clippy PROPERTIES ENVIRONMENT_MODIFICATION "${CARGO_ENV}" @@ -160,16 +160,16 @@ if(BUILD_TESTING) set_tests_properties(cargo_doc PROPERTIES ENVIRONMENT_MODIFICATION "${CARGO_ENV};RUSTDOCFLAGS=set:--deny=warnings" ) - + # Ensure test inputs and outputs are formatted file(GLOB CXX_QT_GEN_TEST_INPUTS ${CMAKE_CURRENT_SOURCE_DIR}/crates/cxx-qt-gen/test_inputs/*.rs) file(GLOB CXX_QT_GEN_TEST_OUTPUTS ${CMAKE_CURRENT_SOURCE_DIR}/crates/cxx-qt-gen/test_outputs/*.rs) add_test(NAME cxx_qt_gen_test_inputs_gen COMMAND rustfmt --check ${CXX_QT_GEN_TEST_INPUTS}) add_test(NAME cxx_qt_gen_test_outputs_gen COMMAND rustfmt --check ${CXX_QT_GEN_TEST_OUTPUTS}) - + # Add test which checks that a build rerun doesn't recompile and uses caches instead add_test(NAME cargo_build_rerun COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/check_cargo_build_rerun.sh" "${CMAKE_CURRENT_SOURCE_DIR}" "${CARGO_TARGET_DIR}") - + # Ensure that cargo_build_rerun doesn't run while we are already building set_tests_properties(cargo_build_rerun PROPERTIES RUN_SERIAL TRUE) endif() diff --git a/Cargo.toml b/Cargo.toml index ed4715f31..98459872a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,8 +65,26 @@ serde_json = "1.0" thiserror = "1.0" [workspace.lints.clippy] +all = { level = "warn", priority = -1 } +pedantic = { level = "warn", priority = -1 } +cast_possible_truncation = "allow" +cast_possible_wrap = "allow" +cast_sign_loss = "allow" +doc_link_with_quotes = "allow" +doc_markdown = "allow" +if_not_else = "allow" incompatible_msrv = "deny" -if_not_else = "warn" -manual_let_else = "warn" -redundant_else = "warn" -single_match_else = "warn" +inline_always = "allow" +manual_let_else = "allow" +many_single_char_names = "allow" +map_unwrap_or = "allow" +match_wildcard_for_single_variants = "allow" +module_name_repetitions = "allow" +must_use_candidate = "allow" +redundant_else = "allow" +return_self_not_must_use = "allow" +should_panic_without_expect = "allow" +similar_names = "allow" +single_match_else = "allow" +struct_excessive_bools = "allow" +too_many_lines = "allow" diff --git a/crates/cxx-qt-build/src/cfg_evaluator.rs b/crates/cxx-qt-build/src/cfg_evaluator.rs index 4eaa02526..038c3727f 100644 --- a/crates/cxx-qt-build/src/cfg_evaluator.rs +++ b/crates/cxx-qt-build/src/cfg_evaluator.rs @@ -12,6 +12,7 @@ use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::{BTreeMap as Map, BTreeSet as Set}; use std::env; +use std::ptr; use std::sync::OnceLock; static ENV: OnceLock = OnceLock::new(); @@ -102,7 +103,7 @@ struct Lookup(str); impl Lookup { fn new(name: &str) -> &Self { - unsafe { &*(name as *const str as *const Self) } + unsafe { &*(ptr::from_ref(name) as *const Self) } } } diff --git a/crates/cxx-qt-build/src/diagnostics.rs b/crates/cxx-qt-build/src/diagnostics.rs index f6744f7ff..a045555ce 100644 --- a/crates/cxx-qt-build/src/diagnostics.rs +++ b/crates/cxx-qt-build/src/diagnostics.rs @@ -159,9 +159,11 @@ impl Diagnostic { pub(crate) fn report(self) { // If loading the source file fails, or printing to stderr isn't // possible, we try panicing as a last resort. - self.try_report().unwrap_or_else(|_| { - panic!("{}", self.errors.first().unwrap()); - }) + assert!( + self.try_report().is_ok(), + "{}", + self.errors.first().unwrap() + ); } } diff --git a/crates/cxx-qt-build/src/interface.rs b/crates/cxx-qt-build/src/interface.rs index 86b6e2e23..934143d5e 100644 --- a/crates/cxx-qt-build/src/interface.rs +++ b/crates/cxx-qt-build/src/interface.rs @@ -81,9 +81,10 @@ impl Interface { } // Ensure that a link name has been set - if self.manifest.link_name.is_empty() { - panic!("The links key must be set when exporting with CXX-Qt-build"); - } + assert!( + !self.manifest.link_name.is_empty(), + "The links key must be set when exporting with CXX-Qt-build" + ); // We automatically reexport all qt_modules and downstream dependencies // as they will always need to be enabled in the final binary. diff --git a/crates/cxx-qt-build/src/lib.rs b/crates/cxx-qt-build/src/lib.rs index 602818d79..688cdbe8a 100644 --- a/crates/cxx-qt-build/src/lib.rs +++ b/crates/cxx-qt-build/src/lib.rs @@ -4,8 +4,8 @@ // SPDX-FileContributor: Gerhard de Clercq // // SPDX-License-Identifier: MIT OR Apache-2.0 - #![deny(missing_docs)] +#![allow(clippy::missing_panics_doc)] //! This crate provides a builder which parses given Rust source code to search //! for CXX-Qt or CXX macros and generate any resulting C++ code. It also builds @@ -115,24 +115,20 @@ impl GeneratedCpp { match item { CxxQtItem::Cxx(m) => { // TODO: later we will allow for multiple CXX or CXX-Qt blocks in one file - if found_bridge { - panic!( + assert!(!found_bridge, "Unfortunately only files with either a single cxx or a single cxx_qt module are currently supported. The file {} has more than one of these.", rust_file_path.display()); - } found_bridge = true; tokens.extend(m.into_token_stream()); } CxxQtItem::CxxQt(m) => { // TODO: later we will allow for multiple CXX or CXX-Qt blocks in one file - if found_bridge { - panic!( + assert!(!found_bridge, "Unfortunately only files with either a single cxx or a single cxx_qt module are currently supported. The file {} has more than one of these.", rust_file_path.display()); - } found_bridge = true; let mut parser = Parser::from(*m.clone()) @@ -203,8 +199,7 @@ impl GeneratedCpp { let mut header = File::create(&header_path).expect("Could not create cxx-qt header file"); let header_generated = match cxx_qt_generated { - CppFragment::Pair { header, source: _ } => header, - CppFragment::Header(header) => header, + CppFragment::Header(header) | CppFragment::Pair { header, source: _ } => header, CppFragment::Source(_) => panic!("Unexpected call for source fragment."), }; header @@ -223,9 +218,8 @@ impl GeneratedCpp { } let mut cpp = File::create(&cpp_path).expect("Could not create cxx-qt source file"); let source_generated = match cxx_qt_generated { - CppFragment::Pair { header: _, source } => source, + CppFragment::Source(source) | CppFragment::Pair { header: _, source } => source, CppFragment::Header(_) => panic!("Unexpected call for header fragment."), - CppFragment::Source(source) => source, }; cpp.write_all(source_generated.as_bytes()) .expect("Could not write cxx-qt source file"); @@ -521,11 +515,9 @@ impl CxxQtBuilder { /// to disable any qt modules that are optional. pub fn qt_module(mut self, module: &str) -> Self { // Ensure that CMake and Cargo build.rs are not out of sync - if qt_modules_import().is_some() && !self.qt_modules.contains(module) { - panic!("Qt module mismatch between cxx-qt-build and CMake!\n\ + assert!(qt_modules_import().is_none() || self.qt_modules.contains(module), "Qt module mismatch between cxx-qt-build and CMake!\n\ Qt module '{module}' was not specified in CMake!\n\ When building with CMake, all Qt modules must be specified with the QT_MODULES argument in cxx_qt_import_crate"); - } self.qt_modules.insert(module.to_owned()); self @@ -608,7 +600,7 @@ impl CxxQtBuilder { self } - fn define_cfg_variable(key: String, value: Option<&str>) { + fn define_cfg_variable(key: &str, value: Option<&str>) { if let Some(value) = value { println!("cargo::rustc-cfg={key}=\"{value}\""); } else { @@ -618,7 +610,7 @@ impl CxxQtBuilder { env::set_var(variable_cargo, value.unwrap_or("true")); } - fn define_cfg_check_variable(key: String, values: Option>) { + fn define_cfg_check_variable(key: &str, values: Option>) { if let Some(values) = values { let values = values .iter() @@ -632,29 +624,26 @@ impl CxxQtBuilder { } } - fn define_qt_version_cfg_variables(version: Version) { + fn define_qt_version_cfg_variables(version: &Version) { // Allow for Qt 5 or Qt 6 as valid values - CxxQtBuilder::define_cfg_check_variable( - "cxxqt_qt_version_major".to_owned(), - Some(vec!["5", "6"]), - ); + CxxQtBuilder::define_cfg_check_variable("cxxqt_qt_version_major", Some(vec!["5", "6"])); // Find the Qt version and tell the Rust compiler // this allows us to have conditional Rust code CxxQtBuilder::define_cfg_variable( - "cxxqt_qt_version_major".to_owned(), + "cxxqt_qt_version_major", Some(version.major.to_string().as_str()), ); // Seed all values from Qt 5.0 through to Qt 7.99 for major in 5..=7 { CxxQtBuilder::define_cfg_check_variable( - format!("cxxqt_qt_version_at_least_{major}"), + &format!("cxxqt_qt_version_at_least_{major}"), None, ); for minor in 0..=99 { CxxQtBuilder::define_cfg_check_variable( - format!("cxxqt_qt_version_at_least_{major}_{minor}"), + &format!("cxxqt_qt_version_at_least_{major}_{minor}"), None, ); } @@ -663,13 +652,13 @@ impl CxxQtBuilder { for minor in 0..=version.minor { let qt_version_at_least = format!("cxxqt_qt_version_at_least_{}_{}", version.major, minor); - CxxQtBuilder::define_cfg_variable(qt_version_at_least, None); + CxxQtBuilder::define_cfg_variable(&qt_version_at_least, None); } // We don't support Qt < 5 for major in 5..=version.major { let at_least_qt_major_version = format!("cxxqt_qt_version_at_least_{major}"); - CxxQtBuilder::define_cfg_variable(at_least_qt_major_version, None); + CxxQtBuilder::define_cfg_variable(&at_least_qt_major_version, None); } } @@ -689,7 +678,7 @@ impl CxxQtBuilder { // A dependency can specify which of its own include paths it wants to export. // Set up each of these exported include paths as symlinks in our own include directory, // or deep copy the files if the platform does not support symlinks. - fn include_dependency(&mut self, dependency: &Dependency) { + fn include_dependency(dependency: &Dependency) { let header_root = dir::header_root(); let dependency_root = dependency.path.join("include"); for include_prefix in &dependency.manifest.exported_include_prefixes { @@ -760,9 +749,9 @@ impl CxxQtBuilder { fn export_object_file( mut obj_builder: cc::Build, file_path: impl AsRef, - export_path: PathBuf, + export_path: &Path, ) { - obj_builder.file(file_path.as_ref()); + obj_builder.file(file_path); // We only expect a single file, so destructure the vec. // If there's 0 or > 1 file, we panic in the `else` branch, because then the builder is @@ -777,7 +766,7 @@ impl CxxQtBuilder { ) }); } - std::fs::copy(obj_file, &export_path).unwrap_or_else(|_| { + std::fs::copy(obj_file, export_path).unwrap_or_else(|_| { panic!("Failed to export object file to {}!", export_path.display()) }); } else { @@ -825,13 +814,12 @@ impl CxxQtBuilder { } }) .collect::>(); - if dirs.len() > 1 { - panic!( - "Only one directory is supported per QmlModule for rust_files.\n\ + assert!( + dirs.len() <= 1, + "Only one directory is supported per QmlModule for rust_files.\n\ This is due to Qt bug https://bugreports.qt.io/browse/QTBUG-93443\n\ Found directories: {dirs:?}" - ); - } + ); // TODO: for now we use the global CxxQtBuilder cc_builder // this means that any includes/files etc on these are in this builder @@ -1035,7 +1023,7 @@ extern "C" bool {init_fun}() {{ std::fs::write(&init_file, init_call).expect("Could not write initializers call file!"); if let Some(export_path) = export_path { - Self::export_object_file(init_call_builder, init_file, export_path); + Self::export_object_file(init_call_builder, init_file, &export_path); } else { // Link the call-init-lib with +whole-archive to ensure that the static initializers are not discarded. // We previously used object files that we linked directly into the final binary, but this caused @@ -1082,6 +1070,8 @@ extern "C" bool {init_fun}() {{ /// Generate and compile cxx-qt C++ code, as well as compile any additional files from /// [CxxQtBuilder::qobject_header] and [CxxQtBuilder::cc_builder]. pub fn build(mut self) -> Interface { + const MAX_INCLUDE_DEPTH: usize = 6; + dir::clean(dir::crate_target()).expect("Failed to clean crate export directory!"); // We will do these two steps first, as setting up the dependencies can modify flags we @@ -1091,7 +1081,7 @@ extern "C" bool {init_fun}() {{ Self::write_common_headers(); let dependencies = Dependency::find_all(); for dependency in &dependencies { - self.include_dependency(dependency); + Self::include_dependency(dependency); } let qt_modules = self.qt_modules(&dependencies); @@ -1103,7 +1093,7 @@ extern "C" bool {init_fun}() {{ let mut qtbuild = qt_build_utils::QtBuild::new(qt_modules.iter().cloned().collect()) .expect("Could not find Qt installation"); qtbuild.cargo_link_libraries(&mut self.cc_builder); - Self::define_qt_version_cfg_variables(qtbuild.version()); + Self::define_qt_version_cfg_variables(&qtbuild.version()); // Ensure that Qt modules and apple framework are linked and searched correctly let mut include_paths = qtbuild.include_paths(); @@ -1115,7 +1105,6 @@ extern "C" bool {init_fun}() {{ // to the generated files without any namespacing. include_paths.push(header_root.join(&self.include_prefix)); - const MAX_INCLUDE_DEPTH: usize = 6; let crate_header_dir = self.crate_include_root.as_ref().map(|subdir| { dir::manifest() .expect("Could not find crate directory!") diff --git a/crates/cxx-qt-gen/src/generator/cfg.rs b/crates/cxx-qt-gen/src/generator/cfg.rs index 872841175..fece59236 100644 --- a/crates/cxx-qt-gen/src/generator/cfg.rs +++ b/crates/cxx-qt-gen/src/generator/cfg.rs @@ -98,7 +98,7 @@ mod tests { use crate::{generator::UnsupportedCfgEvaluator, tests::CfgEvaluatorTest}; use syn::{parse_quote, ItemMod}; - fn assert_eval_insert(module: ItemMod, cfgs: &[&str], [before, after]: [bool; 2]) { + fn assert_eval_insert(module: &ItemMod, cfgs: &[&str], [before, after]: [bool; 2]) { let mut cfg_evaluator = Box::new(CfgEvaluatorTest::default()); assert_eq!( try_eval_attributes(cfg_evaluator.as_ref(), &module.attrs).unwrap(), @@ -122,14 +122,14 @@ mod tests { ); } - fn assert_eval_insert_false_true(module: ItemMod, cfgs: &[&str]) { + fn assert_eval_insert_false_true(module: &ItemMod, cfgs: &[&str]) { assert_eval_insert(module, cfgs, [false, true]); } #[test] fn test_try_eval_attributes_eq() { assert_eval_insert_false_true( - parse_quote! { + &parse_quote! { #[cfg(a = "1")] #[cfg(b = "2")] mod module; @@ -141,7 +141,7 @@ mod tests { #[test] fn test_try_eval_attributes_any() { assert_eval_insert_false_true( - parse_quote! { + &parse_quote! { #[cfg(any(a = "1", b = "2"))] mod module; }, @@ -152,7 +152,7 @@ mod tests { #[test] fn test_try_eval_attributes_all() { assert_eval_insert_false_true( - parse_quote! { + &parse_quote! { #[cfg(all(a = "1", b = "2"))] mod module; }, @@ -163,7 +163,7 @@ mod tests { #[test] fn test_try_eval_attributes_not() { assert_eval_insert( - parse_quote! { + &parse_quote! { #[cfg(not(a = "1"))] mod module; }, diff --git a/crates/cxx-qt-gen/src/generator/cpp/constructor.rs b/crates/cxx-qt-gen/src/generator/cpp/constructor.rs index 60741fa29..2d20702b4 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/constructor.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/constructor.rs @@ -14,8 +14,8 @@ use syn::{Result, Type}; fn default_constructor( qobject: &GeneratedCppQObject, - base_class: String, - initializers: String, + base_class: &str, + initializers: &str, ) -> GeneratedCppQObjectBlocks { let class_name = qobject.name.cxx_unqualified(); let rust_obj = qobject.rust_struct.cxx_qualified(); @@ -23,12 +23,12 @@ fn default_constructor( CppFragment::Pair { header: format!("explicit {class_name}(QObject* parent = nullptr);",), source: formatdoc!( - r#" + r" {class_name}::{class_name}(QObject* parent) : {base_class}(parent) , ::rust::cxxqt1::CxxQtType<{rust_obj}>(::{namespace_internals}::createRs()){initializers} {{ }} - "#, + ", namespace_internals = qobject.namespace_internals, ), } @@ -36,12 +36,12 @@ fn default_constructor( CppFragment::Pair { header: format!("explicit {class_name}();"), source: formatdoc!( - r#" + r" {class_name}::{class_name}() {base_class_line} , ::rust::cxxqt1::CxxQtType<{rust_obj}>(::{namespace_internals}::createRs()){initializers} {{ }} - "#, + ", base_class_line = if base_class.is_empty() { // CODECOV_EXCLUDE_START unreachable!( @@ -82,18 +82,17 @@ fn expand_arguments(arguments: &[Type], type_names: &TypeNames) -> Result Result { let initializers = class_initializers .iter() .map(|initializer| format!("\n , {initializer}")) - .collect::>() - .join(""); + .collect::(); if constructors.is_empty() { - return Ok(default_constructor(qobject, base_class, initializers)); + return Ok(default_constructor(qobject, base_class, &initializers)); } let mut generated = GeneratedCppQObjectBlocks::default(); @@ -108,11 +107,11 @@ pub fn generate( generated.methods.push(CppFragment::Pair { header: format!("explicit {class_name}({argument_list});"), source: formatdoc! { - r#" + r" {class_name}::{class_name}({argument_list}) : {class_name}(::{namespace_internals}::routeArguments{index}({move_arguments})) {{ }} - "#, + ", move_arguments = constructor_argument_names.iter().map(|arg| format!("::std::move({arg})")).collect::>().join(", "), }, }); @@ -138,16 +137,16 @@ pub fn generate( "explicit {class_name}(::{namespace_internals}::CxxQtConstructorArguments{index}&& args);" ), source: formatdoc! { - r#" + r" {class_name}::{class_name}(::{namespace_internals}::CxxQtConstructorArguments{index}&& args) : {base_class}({base_args}) , ::rust::cxxqt1::CxxQtType<{rust_obj}>(::{namespace_internals}::newRs{index}(::std::move(args.new_))){initializers} {{ ::{namespace_internals}::initialize{index}(*this, ::std::move(args.initialize)); }} - "#, + ", }, - }) + }); } Ok(generated) @@ -198,7 +197,7 @@ mod tests { let blocks = generate( &qobject_for_testing(), &[], - "BaseClass".to_owned(), + "BaseClass", &["member1(1)".to_owned(), "member2{ 2 }".to_owned()], &type_names_with_qobject(), ) @@ -228,7 +227,7 @@ mod tests { let blocks = generate( &qobject_for_testing(), &[], - "BaseClass".to_owned(), + "BaseClass", &[], &type_names_with_qobject(), ) @@ -256,14 +255,7 @@ mod tests { fn default_constructor_no_qobject_macro() { let mut qobject = qobject_for_testing(); qobject.has_qobject_macro = false; - let blocks = generate( - &qobject, - &[], - "BaseClass".to_owned(), - &[], - &type_names_with_qobject(), - ) - .unwrap(); + let blocks = generate(&qobject, &[], "BaseClass", &[], &type_names_with_qobject()).unwrap(); assert_empty_blocks(&blocks); assert!(blocks.private_methods.is_empty()); @@ -291,7 +283,7 @@ mod tests { arguments: vec![parse_quote! { i32 }, parse_quote! { *mut QObject }], ..mock_constructor() }], - "BaseClass".to_owned(), + "BaseClass", &[], &type_names_with_qobject(), ) @@ -341,7 +333,7 @@ mod tests { lifetime: Some(parse_quote! { 'a_lifetime }), ..mock_constructor() }], - "BaseClass".to_owned(), + "BaseClass", &["initializer".to_owned()], &type_names_with_qobject(), ) @@ -395,7 +387,7 @@ mod tests { ..mock_constructor() }, ], - "BaseClass".to_owned(), + "BaseClass", &["initializer".to_owned()], &type_names_with_qobject(), ) diff --git a/crates/cxx-qt-gen/src/generator/cpp/cxxqttype.rs b/crates/cxx-qt-gen/src/generator/cpp/cxxqttype.rs index 0fbe10c17..8d09056b7 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/cxxqttype.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/cxxqttype.rs @@ -4,9 +4,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::generator::{cpp::qobject::GeneratedCppQObjectBlocks, naming::qobject::QObjectNames}; -use syn::Result; -pub fn generate(qobject_idents: &QObjectNames) -> Result { +pub fn generate(qobject_idents: &QObjectNames) -> GeneratedCppQObjectBlocks { let mut result = GeneratedCppQObjectBlocks::default(); let rust_struct = qobject_idents.rust_struct.cxx_qualified(); @@ -19,7 +18,7 @@ pub fn generate(qobject_idents: &QObjectNames) -> Result")); - Ok(result) + result } #[cfg(test)] @@ -32,7 +31,7 @@ mod tests { fn test_generate_cpp_cxxqt_type() { let qobject_idents = create_qobjectname(); - let generated = generate(&qobject_idents).unwrap(); + let generated = generate(&qobject_idents); // includes assert_eq!(generated.includes.len(), 1); diff --git a/crates/cxx-qt-gen/src/generator/cpp/fragment.rs b/crates/cxx-qt-gen/src/generator/cpp/fragment.rs index d91ff571f..8835ddd71 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/fragment.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/fragment.rs @@ -45,6 +45,6 @@ mod tests { header: String::new(), source: String::new() } - ) + ); } } diff --git a/crates/cxx-qt-gen/src/generator/cpp/inherit.rs b/crates/cxx-qt-gen/src/generator/cpp/inherit.rs index d40aa48ac..abdca5d0f 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/inherit.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/inherit.rs @@ -19,7 +19,7 @@ use syn::Result; pub fn generate( inherited_methods: &[&ParsedInheritedMethod], - base_class: &Option, + base_class: Option<&str>, type_names: &TypeNames, opt: &GeneratedOpt, ) -> Result { @@ -35,15 +35,15 @@ pub fn generate( // Note that no qobject macro with no base class is an error // // So a default of QObject is fine here - let base_class = base_class.as_deref().unwrap_or("QObject"); + let base_class = base_class.unwrap_or("QObject"); result.methods.push(CppFragment::Header(formatdoc! { - r#" + r" template {return_type} {wrapper_ident}(Args ...args){mutability} {{ return {base_class}::{func_ident}(args...); - }}"#, + }}", mutability = if method.mutable { "" } else { " const" }, func_ident = method.name.cxx_unqualified(), wrapper_ident = method.wrapper_ident(), @@ -72,10 +72,9 @@ mod tests { ) -> Result { let method = ParsedInheritedMethod::parse(method, CaseConversion::none())?; let inherited_methods = vec![&method]; - let base_class = base_class.map(|s| s.to_owned()); generate( &inherited_methods, - &base_class, + base_class, &TypeNames::default(), &GeneratedOpt::default(), ) @@ -95,12 +94,12 @@ mod tests { }; let method = ParsedInheritedMethod::parse(method, CaseConversion::none()).unwrap(); let inherited_methods = vec![&method]; - let base_class = Some("TestBaseClass".to_owned()); + let base_class = Some("TestBaseClass"); let opt = GeneratedOpt { cfg_evaluator: Box::new(CfgEvaluatorTest::default()), }; let generated = - generate(&inherited_methods, &base_class, &TypeNames::default(), &opt).unwrap(); + generate(&inherited_methods, base_class, &TypeNames::default(), &opt).unwrap(); assert!(generated.methods.is_empty()); } diff --git a/crates/cxx-qt-gen/src/generator/cpp/property/meta.rs b/crates/cxx-qt-gen/src/generator/cpp/property/meta.rs index 41f663abf..d2c9bb195 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/property/meta.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/property/meta.rs @@ -26,15 +26,15 @@ pub fn generate(idents: &QPropertyNames, flags: &QPropertyFlags, cxx_ty: &str) - } if flags.constant { - parts.push(String::from("CONSTANT")) + parts.push(String::from("CONSTANT")); } if flags.required { - parts.push(String::from("REQUIRED")) + parts.push(String::from("REQUIRED")); } if flags.is_final { - parts.push(String::from("FINAL")) + parts.push(String::from("FINAL")); } format!( diff --git a/crates/cxx-qt-gen/src/generator/cpp/property/mod.rs b/crates/cxx-qt-gen/src/generator/cpp/property/mod.rs index aa8c1a83b..49b24c0b0 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/property/mod.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/property/mod.rs @@ -43,11 +43,11 @@ pub fn generate_cpp_properties( } if let Some(setter) = setter::generate(&idents, &cxx_ty) { - generated.methods.push(setter) + generated.methods.push(setter); } if let Some(notify) = signal::generate(&idents, &qobject_idents.name) { - signals.push(notify) + signals.push(notify); } } @@ -362,12 +362,12 @@ pub mod tests { assert_str_eq!( header, - indoc! {r#" + indoc! {r" namespace rust::cxxqtgen1 { ::QMetaObject::Connection MyObject_trivialPropertyChangedConnect(MyObject& self, ::rust::cxxqtgen1::MyObjectCxxQtSignalHandlertrivialPropertyChanged closure, ::Qt::ConnectionType type); } // namespace rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, @@ -418,12 +418,12 @@ pub mod tests { assert_str_eq!( header, - indoc! {r#" + indoc! {r" namespace rust::cxxqtgen1 { ::QMetaObject::Connection MyObject_opaquePropertyChangedConnect(MyObject& self, ::rust::cxxqtgen1::MyObjectCxxQtSignalHandleropaquePropertyChanged closure, ::Qt::ConnectionType type); } // namespace rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, @@ -521,12 +521,12 @@ pub mod tests { let (header, source) = require_pair(&generated.fragments[0]).unwrap(); assert_str_eq!( header, - indoc! {r#" + indoc! {r" namespace rust::cxxqtgen1 { ::QMetaObject::Connection MyObject_mappedPropertyChangedConnect(MyObject& self, ::rust::cxxqtgen1::MyObjectCxxQtSignalHandlermappedPropertyChanged closure, ::Qt::ConnectionType type); } // namespace rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, diff --git a/crates/cxx-qt-gen/src/generator/cpp/qenum.rs b/crates/cxx-qt-gen/src/generator/cpp/qenum.rs index 9c7e9b2c1..029e786b6 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/qenum.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/qenum.rs @@ -26,11 +26,11 @@ fn generate_definition(qenum: &ParsedQEnum) -> String { .collect::>() .join(",\n"); - formatdoc! { r#" + formatdoc! { r" enum class {enum_name} : ::std::int32_t {{ {enum_values} }}; - "#, enum_values = enum_values.indented(2) } + ", enum_values = enum_values.indented(2) } } pub fn generate_declaration( @@ -57,10 +57,10 @@ pub fn generate_declaration( // This is redundant with `qnamespace!`, which is now only required if you want to specify // it as QML_ELEMENT. &if is_standalone { - formatdoc! {r#" + formatdoc! {r" Q_NAMESPACE {enum_definition} - Q_ENUM_NS({enum_name}) "# } + Q_ENUM_NS({enum_name}) " } } else { enum_definition }, @@ -90,7 +90,7 @@ pub fn generate_on_qobject<'a>( generated.includes.insert("#include ".to_owned()); let enum_definition = generate_definition(qenum); - generated.metaobjects.push(formatdoc! {r#" + generated.metaobjects.push(formatdoc! {r" #ifdef Q_MOC_RUN {enum_definition} Q_ENUM({enum_name}) @@ -98,7 +98,7 @@ pub fn generate_on_qobject<'a>( using {enum_name} = {qualified_name}; Q_ENUM({enum_name}) #endif - "#, enum_definition = enum_definition.indented(2)}); + ", enum_definition = enum_definition.indented(2)}); } Ok(generated) @@ -156,7 +156,7 @@ mod tests { assert!(generated.includes.contains("#include ")); assert_eq!(generated.metaobjects.len(), 1); assert_str_eq!( - indoc! {r#" + indoc! {r" #ifdef Q_MOC_RUN enum class MyEnum : ::std::int32_t { A, @@ -168,7 +168,7 @@ mod tests { using MyEnum = ::MyEnum; Q_ENUM(MyEnum) #endif - "#}, + "}, generated.metaobjects[0], ); assert_eq!(generated.forward_declares.len(), 0); diff --git a/crates/cxx-qt-gen/src/generator/cpp/qnamespace.rs b/crates/cxx-qt-gen/src/generator/cpp/qnamespace.rs index 591e4fb17..2d7f4de8e 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/qnamespace.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/qnamespace.rs @@ -15,9 +15,9 @@ pub fn generate(qnamespace: &ParsedQNamespace, includes: &mut BTreeSet) let mut result = "Q_NAMESPACE".to_owned(); if qnamespace.qml_element { includes.insert("#include ".to_owned()); - result = formatdoc! { r#" + result = formatdoc! { r" {result} - QML_ELEMENT"#}; + QML_ELEMENT"}; } namespaced(&qnamespace.namespace, &result) } diff --git a/crates/cxx-qt-gen/src/generator/cpp/qobject.rs b/crates/cxx-qt-gen/src/generator/cpp/qobject.rs index 30b5451ae..b4e1389f3 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/qobject.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/qobject.rs @@ -130,7 +130,7 @@ impl GeneratedCppQObject { // Add the CxxQtType rust and rust_mut methods generated .blocks - .append(&mut cxxqttype::generate(&qobject_idents)?); + .append(&mut cxxqttype::generate(&qobject_idents)); // Generate methods for the properties, invokables, signals generated.blocks.append(&mut generate_cpp_properties( @@ -154,12 +154,16 @@ impl GeneratedCppQObject { generated.blocks.append(&mut inherit::generate( &structured_qobject.inherited_methods, - &qobject.base_class.as_ref().map(|ident| ident.to_string()), + qobject + .base_class + .as_ref() + .map(ToString::to_string) + .as_deref(), type_names, opt, )?); generated.blocks.append(&mut qenum::generate_on_qobject( - structured_qobject.qenums.iter().cloned(), + structured_qobject.qenums.iter().copied(), opt, )?); @@ -169,7 +173,7 @@ impl GeneratedCppQObject { // // Note that threading also includes locking C++ generation if structured_qobject.threading { - let (initializer, mut blocks) = threading::generate(&qobject_idents)?; + let (initializer, mut blocks) = threading::generate(&qobject_idents); generated.blocks.append(&mut blocks); class_initializers.push(initializer); } @@ -183,7 +187,7 @@ impl GeneratedCppQObject { generated.blocks.append(&mut constructor::generate( &generated, &structured_qobject.constructors, - base_class, + &base_class, &class_initializers, type_names, )?); diff --git a/crates/cxx-qt-gen/src/generator/cpp/signal.rs b/crates/cxx-qt-gen/src/generator/cpp/signal.rs index 1dc4808da..c6e37b89a 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/signal.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/signal.rs @@ -103,7 +103,7 @@ pub fn generate_cpp_signal( // Prepare the idents let idents = QSignalNames::from(signal); - let idents_helper = QSignalHelperNames::new(&idents, qobject_name)?; + let idents_helper = QSignalHelperNames::new(&idents, qobject_name); let signal_ident = idents.name.cxx_unqualified(); let free_connect_ident_cpp = idents_helper.connect_name.cxx_unqualified(); @@ -125,11 +125,11 @@ pub fn generate_cpp_signal( let signal_handler_type = format!("SignalHandler<::{namespace}::{param_struct} *>"); generated.forward_declares.push(formatdoc! { - r#" + r" namespace {namespace} {{ using {signal_handler_alias} = ::rust::cxxqt1::SignalHandler; }} // namespace {namespace} - "# + " }); // Generate the Q_SIGNAL if this is not an existing signal @@ -141,12 +141,12 @@ pub fn generate_cpp_signal( generated.fragments.push(CppFragment::Pair { header: formatdoc! { - r#" + r" namespace {namespace} {{ ::QMetaObject::Connection {free_connect_ident_cpp}({qobject_ident_namespaced}& self, {signal_handler_alias_namespaced} closure, ::Qt::ConnectionType type); }} // namespace {namespace} - "# + " }, source: formatdoc! { r#" @@ -282,12 +282,12 @@ mod tests { assert_str_eq!( header, - indoc! {r#" + indoc! {r" namespace rust::cxxqtgen1 { ::QMetaObject::Connection MyObject_dataChangedConnect(MyObject& self, ::rust::cxxqtgen1::MyObjectCxxQtSignalHandlerdataChanged closure, ::Qt::ConnectionType type); } // namespace rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, @@ -365,12 +365,12 @@ mod tests { assert_str_eq!( header, - indoc! {r#" + indoc! {r" namespace rust::cxxqtgen1 { ::QMetaObject::Connection MyObject_dataChangedConnect(MyObject& self, ::rust::cxxqtgen1::MyObjectCxxQtSignalHandlerdataChanged closure, ::Qt::ConnectionType type); } // namespace rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, @@ -445,12 +445,12 @@ mod tests { let (header, source) = require_pair(&generated.fragments[0]).unwrap(); assert_str_eq!( header, - indoc! {r#" + indoc! {r" namespace rust::cxxqtgen1 { ::QMetaObject::Connection MyObject_baseNameConnect(MyObject& self, ::rust::cxxqtgen1::MyObjectCxxQtSignalHandlerbaseName closure, ::Qt::ConnectionType type); } // namespace rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, @@ -524,12 +524,12 @@ mod tests { assert_str_eq!( header, indoc! { - r#" + r" namespace rust::cxxqtgen1 { ::QMetaObject::Connection MyObject_signalRustNameConnect(MyObject& self, ::rust::cxxqtgen1::MyObjectCxxQtSignalHandlersignalRustName closure, ::Qt::ConnectionType type); } // namespace rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, @@ -603,12 +603,12 @@ mod tests { assert_str_eq!( header, indoc! { - r#" + r" namespace mynamespace::rust::cxxqtgen1 { ::QMetaObject::Connection ObjCpp_signalCxxNameConnect(mynamespace::ObjCpp& self, ::mynamespace::rust::cxxqtgen1::MyObjectCxxQtSignalHandlersignalCxxName closure, ::Qt::ConnectionType type); } // namespace mynamespace::rust::cxxqtgen1 - "#} + "} ); assert_str_eq!( source, diff --git a/crates/cxx-qt-gen/src/generator/cpp/threading.rs b/crates/cxx-qt-gen/src/generator/cpp/threading.rs index 52eb3d1b6..a1a2b6699 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/threading.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/threading.rs @@ -8,9 +8,8 @@ use crate::generator::{ naming::qobject::QObjectNames, }; use indoc::formatdoc; -use syn::Result; -pub fn generate(qobject_idents: &QObjectNames) -> Result<(String, GeneratedCppQObjectBlocks)> { +pub fn generate(qobject_idents: &QObjectNames) -> (String, GeneratedCppQObjectBlocks) { let mut result = GeneratedCppQObjectBlocks::default(); let cpp_class = &qobject_idents.name.cxx_unqualified(); @@ -38,7 +37,7 @@ pub fn generate(qobject_idents: &QObjectNames) -> Result<(String, GeneratedCppQO let class_initializer = format!("::rust::cxxqt1::CxxQtThreading<{cpp_class}>(this)"); - Ok((class_initializer, result)) + (class_initializer, result) } #[cfg(test)] @@ -54,7 +53,7 @@ mod tests { fn test_generate_cpp_threading() { let qobject_idents = create_qobjectname(); - let (initializer, generated) = generate(&qobject_idents).unwrap(); + let (initializer, generated) = generate(&qobject_idents); // forward declares assert_eq!(generated.forward_declares.len(), 1); diff --git a/crates/cxx-qt-gen/src/generator/cpp/utils.rs b/crates/cxx-qt-gen/src/generator/cpp/utils.rs index b4f321f1a..fe1409688 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/utils.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/utils.rs @@ -29,23 +29,23 @@ mod tests { #[test] fn indent_string() { - let multiline_string = indoc! { r#" + let multiline_string = indoc! { r" A, B, - "#}; + "}; assert_str_eq!( - formatdoc! { r#" + formatdoc! { r" enum Test {{ {multiline_string} }} - "#, multiline_string = multiline_string.indented(2) }, - indoc! { r#" + ", multiline_string = multiline_string.indented(2) }, + indoc! { r" enum Test { A, B, } - "#} + "} ); } } diff --git a/crates/cxx-qt-gen/src/generator/naming/property.rs b/crates/cxx-qt-gen/src/generator/naming/property.rs index 20afb7540..171fad5d4 100644 --- a/crates/cxx-qt-gen/src/generator/naming/property.rs +++ b/crates/cxx-qt-gen/src/generator/naming/property.rs @@ -23,8 +23,7 @@ impl Deref for NameState { fn deref(&self) -> &Self::Target { match self { - Self::Auto(name) => name, - Self::Custom(name) => name, + Self::Custom(name) | Self::Auto(name) => name, } } } @@ -116,26 +115,29 @@ impl QPropertyNames { } } -fn capitalise_first(str: String) -> String { - let mut out = "".to_owned(); - if let Some(first) = str.chars().next() { - out.push(first.to_ascii_uppercase()); - out.push_str(&str[1..]); +fn capitalise_first(s: &mut str) -> &mut str { + if !s.is_empty() { + s[0..1].make_ascii_uppercase(); } - out + s } /// For a given property name generate the getter name pub fn getter_name_from_property(name: &Name) -> Name { - name.clone() - .with_cxx_name(format!("get{}", capitalise_first(name.cxx_unqualified()))) + name.clone().with_cxx_name(format!( + "get{}", + capitalise_first(&mut name.cxx_unqualified()) + )) } /// For a given property name generate the setter name pub fn setter_name_from_property(name: &Name) -> Name { name.clone() .with_rust_name(format_ident!("set_{}", name.rust_unqualified())) - .with_cxx_name(format!("set{}", capitalise_first(name.cxx_unqualified()))) + .with_cxx_name(format!( + "set{}", + capitalise_first(&mut name.cxx_unqualified()) + )) } /// For a given property name generate the notify signal name @@ -209,8 +211,8 @@ pub mod tests { #[test] fn test_capitalise_first() { - assert_eq!(capitalise_first("abc".to_owned()), "Abc".to_owned()); - assert_eq!(capitalise_first(String::new()), String::new()); - assert_eq!(capitalise_first("a".to_owned()), "A".to_owned()); + assert_eq!(capitalise_first(&mut "abc".to_owned()), "Abc"); + assert_eq!(capitalise_first(&mut String::new()), ""); + assert_eq!(capitalise_first(&mut "a".to_owned()), "A"); } } diff --git a/crates/cxx-qt-gen/src/generator/naming/qobject.rs b/crates/cxx-qt-gen/src/generator/naming/qobject.rs index d5a3eb6ab..6d2e3d5e8 100644 --- a/crates/cxx-qt-gen/src/generator/naming/qobject.rs +++ b/crates/cxx-qt-gen/src/generator/naming/qobject.rs @@ -55,12 +55,12 @@ impl QObjectNames { // Only for mocking in tests #[cfg(test)] - pub fn from_idents(ident_left: Ident, ident_right: Ident) -> Self { + pub fn from_idents(ident_left: &Ident, ident_right: &Ident) -> Self { Self { name: Name::mock(&ident_left.to_string()), rust_struct: Name::mock(&ident_right.to_string()), - cxx_qt_thread_class: cxx_qt_thread_class_from_ident(&ident_left), - cxx_qt_thread_queued_fn_struct: cxx_qt_thread_queued_fn_struct_from_ident(&ident_left), + cxx_qt_thread_class: cxx_qt_thread_class_from_ident(ident_left), + cxx_qt_thread_queued_fn_struct: cxx_qt_thread_queued_fn_struct_from_ident(ident_left), } } diff --git a/crates/cxx-qt-gen/src/generator/naming/signals.rs b/crates/cxx-qt-gen/src/generator/naming/signals.rs index 9279b6e31..2aef0f58f 100644 --- a/crates/cxx-qt-gen/src/generator/naming/signals.rs +++ b/crates/cxx-qt-gen/src/generator/naming/signals.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::{naming::Name, parser::signals::ParsedSignal}; use quote::format_ident; -use syn::{Ident, Result}; +use syn::Ident; /// Names for parts of a Q_SIGNAL pub struct QSignalNames { @@ -47,7 +47,7 @@ pub struct QSignalHelperNames { } impl QSignalHelperNames { - pub fn new(idents: &QSignalNames, qobject_name: &Name) -> Result { + pub fn new(idents: &QSignalNames, qobject_name: &Name) -> Self { let signal_ident = &idents.name.cxx_unqualified(); let qobject_ident = qobject_name.rust_unqualified().to_string(); let handler_alias = format_ident!("{qobject_ident}CxxQtSignalHandler{signal_ident}"); @@ -85,7 +85,7 @@ impl QSignalHelperNames { // TODO: in the future we might improve the naming of the methods // to avoid collisions (maybe use a separator similar to how CXX uses $?) - Ok(Self { + Self { connect_name, function_drop: format_ident!("drop_{qobject_ident}_signal_handler_{signal_ident}"), function_call: format_ident!("call_{qobject_ident}_signal_handler_{signal_ident}"), @@ -94,7 +94,7 @@ impl QSignalHelperNames { struct_param: format_ident!("{qobject_ident}CxxQtSignalParams{signal_ident}"), namespace, handler_alias, - }) + } } } diff --git a/crates/cxx-qt-gen/src/generator/rust/constructor.rs b/crates/cxx-qt-gen/src/generator/rust/constructor.rs index 67b1a195b..fcfc59dcd 100644 --- a/crates/cxx-qt-gen/src/generator/rust/constructor.rs +++ b/crates/cxx-qt-gen/src/generator/rust/constructor.rs @@ -33,7 +33,7 @@ fn map_types TokenStream>(args: &[Type], f: F) -> Ve args.iter().enumerate().map(f).collect() } -fn extract_arguments_from_tuple(args: &[Type], tuple_name: Ident) -> Vec { +fn extract_arguments_from_tuple(args: &[Type], tuple_name: &Ident) -> Vec { map_types(args, |(index, _ty)| { let arg_name = format_ident!("arg{index}"); let index = syn::LitInt::new(index.to_string().as_str(), Span::call_site()); @@ -43,7 +43,7 @@ fn extract_arguments_from_tuple(args: &[Type], tuple_name: Ident) -> Vec Vec { +fn extract_arguments_from_struct(args: &[Type], struct_name: &Ident) -> Vec { map_types(args, |(index, _ty)| { let arg_name = format_ident!("arg{index}"); quote! { @@ -128,7 +128,7 @@ fn generate_arguments_struct( fn generate_arguments_initialization( struct_name: &Ident, - instance_name: Ident, + instance_name: &Ident, argument_list: &[Type], cfgs: &[Attribute], ) -> Expr { @@ -326,31 +326,31 @@ pub fn generate( let init_new_arguments = generate_arguments_initialization( &new_arguments_rust, - format_ident!("new_arguments"), + &format_ident!("new_arguments"), &constructor.new_arguments, cfgs, ); let init_initalize_arguments = generate_arguments_initialization( &initialize_arguments_rust, - format_ident!("initialize_arguments"), + &format_ident!("initialize_arguments"), &constructor.initialize_arguments, cfgs, ); let init_base_arguments = generate_arguments_initialization( &base_arguments_rust, - format_ident!("base_arguments"), + &format_ident!("base_arguments"), &constructor.base_arguments, cfgs, ); let extract_new_arguments = extract_arguments_from_struct( &constructor.new_arguments, - format_ident!("new_arguments"), + &format_ident!("new_arguments"), ); let extract_initialize_arguments = extract_arguments_from_struct( &constructor.initialize_arguments, - format_ident!("initialize_arguments"), + &format_ident!("initialize_arguments"), ); result.cxx_mod_contents.append(&mut vec![ @@ -447,7 +447,7 @@ pub fn generate( qobject, (#(#extract_initialize_arguments,)*)); } - }]) + }]); } Ok(result) } @@ -472,7 +472,7 @@ mod tests { } fn mock_name() -> QObjectNames { - QObjectNames::from_idents(format_ident!("MyObject"), format_ident!("MyObjectRust")) + QObjectNames::from_idents(&format_ident!("MyObject"), &format_ident!("MyObjectRust")) } fn mock_namespace() -> NamespaceName { diff --git a/crates/cxx-qt-gen/src/generator/rust/method.rs b/crates/cxx-qt-gen/src/generator/rust/method.rs index c251f16a8..4881030b9 100644 --- a/crates/cxx-qt-gen/src/generator/rust/method.rs +++ b/crates/cxx-qt-gen/src/generator/rust/method.rs @@ -9,12 +9,12 @@ use crate::{ parser::method::ParsedMethod, }; use quote::quote; -use syn::{parse_quote_spanned, spanned::Spanned, Result}; +use syn::{parse_quote_spanned, spanned::Spanned}; pub fn generate_rust_methods( invokables: &[&ParsedMethod], qobject_names: &QObjectNames, -) -> Result { +) -> GeneratedRustFragment { let cpp_class_name_rust = &qobject_names.name.rust_unqualified(); let generated = invokables @@ -75,7 +75,7 @@ pub fn generate_rust_methods( }) .collect::>(); - Ok(GeneratedRustFragment::flatten(generated)) + GeneratedRustFragment::flatten(generated) } #[cfg(test)] @@ -113,7 +113,7 @@ mod tests { let qobject_names = create_qobjectname(); let generated = - generate_rust_methods(&invokables.iter().collect::>(), &qobject_names).unwrap(); + generate_rust_methods(&invokables.iter().collect::>(), &qobject_names); assert_eq!(generated.cxx_mod_contents.len(), 4); assert_eq!(generated.cxx_qt_mod_contents.len(), 0); diff --git a/crates/cxx-qt-gen/src/generator/rust/property/mod.rs b/crates/cxx-qt-gen/src/generator/rust/property/mod.rs index 2b8352fe1..99effc8f1 100644 --- a/crates/cxx-qt-gen/src/generator/rust/property/mod.rs +++ b/crates/cxx-qt-gen/src/generator/rust/property/mod.rs @@ -33,14 +33,14 @@ pub fn generate_rust_properties( if let Some(getter) = getter::generate(&idents, qobject_names, &property.ty, type_names)? { generated.append(getter); - }; + } if let Some(setter) = setter::generate(&idents, qobject_names, &property.ty, type_names)? { generated.append(setter); } if let Some(notify) = signal::generate(&idents, qobject_names) { - signals.push(notify) + signals.push(notify); } } diff --git a/crates/cxx-qt-gen/src/generator/rust/qenum.rs b/crates/cxx-qt-gen/src/generator/rust/qenum.rs index d791aaf52..a23699700 100644 --- a/crates/cxx-qt-gen/src/generator/rust/qenum.rs +++ b/crates/cxx-qt-gen/src/generator/rust/qenum.rs @@ -105,6 +105,6 @@ mod tests { type MyEnum; } }, - ) + ); } } diff --git a/crates/cxx-qt-gen/src/generator/rust/qobject.rs b/crates/cxx-qt-gen/src/generator/rust/qobject.rs index 903d6dc60..d577aecb1 100644 --- a/crates/cxx-qt-gen/src/generator/rust/qobject.rs +++ b/crates/cxx-qt-gen/src/generator/rust/qobject.rs @@ -28,14 +28,14 @@ impl GeneratedRustFragment { let namespace_idents = NamespaceName::from(qobject); let mut generated = vec![ - generate_qobject_definitions(&qobject_names, &qobject.cfgs)?, + generate_qobject_definitions(&qobject_names, &qobject.cfgs), generate_rust_properties( &qobject.properties, &qobject_names, type_names, structured_qobject, )?, - generate_rust_methods(&structured_qobject.methods, &qobject_names)?, + generate_rust_methods(&structured_qobject.methods, &qobject_names), inherit::generate(&qobject_names, &structured_qobject.inherited_methods)?, generate_rust_signals(&structured_qobject.signals, &qobject_names, type_names)?, ]; @@ -47,7 +47,7 @@ impl GeneratedRustFragment { unsafe extern "C++" { include!(); } - })) + })); } } @@ -88,7 +88,7 @@ impl GeneratedRustFragment { fn generate_qobject_definitions( qobject_idents: &QObjectNames, cfgs: &[Attribute], -) -> Result { +) -> GeneratedRustFragment { let cpp_class_name_rust = &qobject_idents.name.rust_unqualified(); let cpp_class_name_cpp = &qobject_idents.name.cxx_unqualified(); @@ -105,7 +105,7 @@ fn generate_qobject_definitions( } }; - Ok(GeneratedRustFragment { + GeneratedRustFragment { cxx_mod_contents: vec![ parse_quote! { unsafe extern "C++" { @@ -134,7 +134,7 @@ fn generate_qobject_definitions( }, ], cxx_qt_mod_contents: vec![], - }) + } } #[cfg(test)] diff --git a/crates/cxx-qt-gen/src/generator/rust/signals.rs b/crates/cxx-qt-gen/src/generator/rust/signals.rs index 497e6a955..e77f47532 100644 --- a/crates/cxx-qt-gen/src/generator/rust/signals.rs +++ b/crates/cxx-qt-gen/src/generator/rust/signals.rs @@ -20,6 +20,7 @@ use quote::{quote, quote_spanned}; use syn::spanned::Spanned; use syn::{parse_quote, parse_quote_spanned, FnArg, Ident, Result, Type}; +#[allow(clippy::needless_pass_by_value)] pub fn generate_rust_signal( signal: &ParsedSignal, qobject_name: &Name, @@ -28,7 +29,7 @@ pub fn generate_rust_signal( ) -> Result { let span = signal.method.span(); let idents = QSignalNames::from(signal); - let idents_helper = QSignalHelperNames::new(&idents, qobject_name)?; + let idents_helper = QSignalHelperNames::new(&idents, qobject_name); let qobject_name_rust = qobject_name.rust_unqualified(); @@ -284,7 +285,7 @@ mod tests { use quote::{format_ident, quote}; use syn::{parse_quote, ForeignItemFn, Item}; - fn common_asserts(cxx_mod_contents: &Vec, cxx_qt_mod_contents: &Vec) { + fn common_asserts(cxx_mod_contents: &[Item], cxx_qt_mod_contents: &[Item]) { assert_eq!(cxx_mod_contents.len(), 2); assert_eq!(cxx_qt_mod_contents.len(), 8); @@ -436,7 +437,7 @@ mod tests { ); common_asserts( - &generated.cxx_mod_contents[1..].into(), + &generated.cxx_mod_contents[1..], &generated.cxx_qt_mod_contents, ); } diff --git a/crates/cxx-qt-gen/src/generator/structuring/qobject.rs b/crates/cxx-qt-gen/src/generator/structuring/qobject.rs index f9700467f..37d7ea8bb 100644 --- a/crates/cxx-qt-gen/src/generator/structuring/qobject.rs +++ b/crates/cxx-qt-gen/src/generator/structuring/qobject.rs @@ -8,6 +8,7 @@ use crate::naming::Name; use crate::parser::constructor::Constructor; use crate::parser::inherit::ParsedInheritedMethod; use crate::parser::method::ParsedMethod; +use crate::parser::property::ParsedQProperty; use crate::parser::signals::ParsedSignal; use crate::parser::{qenum::ParsedQEnum, qobject::ParsedQObject}; use proc_macro2::Ident; @@ -45,13 +46,13 @@ impl<'a> StructuredQObject<'a> { let pending_methods = qobject .properties .iter() - .flat_map(|property| property.pending_methods()) + .flat_map(ParsedQProperty::pending_methods) .collect(); let pending_signals = qobject .properties .iter() - .flat_map(|property| property.pending_signals()) + .flat_map(ParsedQProperty::pending_signals) .collect(); Self { diff --git a/crates/cxx-qt-gen/src/lib.rs b/crates/cxx-qt-gen/src/lib.rs index 2d025fce4..69975edc7 100644 --- a/crates/cxx-qt-gen/src/lib.rs +++ b/crates/cxx-qt-gen/src/lib.rs @@ -3,8 +3,11 @@ // SPDX-FileContributor: Gerhard de Clercq // // SPDX-License-Identifier: MIT OR Apache-2.0 - #![deny(missing_docs)] +#![allow(clippy::format_collect)] +#![allow(clippy::missing_panics_doc)] +#![allow(clippy::ref_option)] +#![allow(clippy::missing_errors_doc)] //! The cxx-qt-gen crate provides methods for generated C++ and Rust code from a TokenStream. @@ -39,13 +42,7 @@ mod tests { use pretty_assertions::assert_str_eq; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; - use std::{ - collections::HashMap, - env, - fs::OpenOptions, - io::Write, - path::{Path, PathBuf}, - }; + use std::{collections::HashMap, env, fs::OpenOptions, io::Write, path::Path}; use writer::{cpp::write_cpp, rust::write_rust}; #[derive(Default)] @@ -53,7 +50,7 @@ mod tests { pub cfgs: HashMap<&'a str, Option<&'a str>>, } - impl<'a> CfgEvaluator for CfgEvaluatorTest<'a> { + impl CfgEvaluator for CfgEvaluatorTest<'_> { fn eval(&self, name: &str, query_value: Option<&str>) -> CfgResult { if self.cfgs.get(name) == Some(&query_value) { CfgResult::True @@ -64,6 +61,7 @@ mod tests { } /// Helper to ensure that a given syn item is the same as the given TokenStream + #[allow(clippy::needless_pass_by_value)] pub fn assert_tokens_eq(item: &T, tokens: TokenStream) { // For understanding what's going on, it is nicer to use format_rs_source // So that the TokenStream is actually legible. @@ -127,7 +125,7 @@ mod tests { } // CODECOV_EXCLUDE_START - fn update_expected_file(path: PathBuf, source: &str) { + fn update_expected_file(path: &Path, source: &str) { println!("Updating expected file: {path:?}"); let mut file = OpenOptions::new() @@ -155,7 +153,7 @@ mod tests { let update = |file_ending, contents| { update_expected_file( - output_folder.join(format!("{test_name}.{file_ending}")), + &output_folder.join(format!("{test_name}.{file_ending}")), contents, ); }; @@ -262,6 +260,6 @@ mod tests { assert_tokens_eq( "e! { struct MyStruct; }, quote! { struct MyOtherStruct; }, - ) + ); } } diff --git a/crates/cxx-qt-gen/src/naming/cpp.rs b/crates/cxx-qt-gen/src/naming/cpp.rs index 38a7a18ed..82e87155a 100644 --- a/crates/cxx-qt-gen/src/naming/cpp.rs +++ b/crates/cxx-qt-gen/src/naming/cpp.rs @@ -17,7 +17,7 @@ pub(crate) fn err_unsupported_item(item: &impl ToTokens) -> Error { } /// For a given Rust return type determine if the C++ header should have noexcept -pub(crate) fn syn_return_type_to_cpp_except(return_ty: &ReturnType) -> &str { +pub(crate) fn syn_return_type_to_cpp_except(return_ty: &ReturnType) -> &'static str { if let ReturnType::Type(_, ty) = return_ty { // If we are a Result then we can have an exception if let Type::Path(ty_path) = &**ty { diff --git a/crates/cxx-qt-gen/src/naming/name.rs b/crates/cxx-qt-gen/src/naming/name.rs index 1f631c7d7..ec537b95e 100644 --- a/crates/cxx-qt-gen/src/naming/name.rs +++ b/crates/cxx-qt-gen/src/naming/name.rs @@ -323,7 +323,7 @@ mod tests { let old_namespace = name.set_namespace(None); assert_eq!(old_namespace, Some("my_namespace".into())); - assert!(name.namespace.is_none()) + assert!(name.namespace.is_none()); } #[test] diff --git a/crates/cxx-qt-gen/src/naming/rust.rs b/crates/cxx-qt-gen/src/naming/rust.rs index 5ecaa9506..c550d7a35 100644 --- a/crates/cxx-qt-gen/src/naming/rust.rs +++ b/crates/cxx-qt-gen/src/naming/rust.rs @@ -23,9 +23,9 @@ fn qualify_type_path(ty_path: &TypePath, type_names: &TypeNames) -> Result let mut ty_path = ty_path.clone(); // Convert any generic arguments - for segment in ty_path.path.segments.iter_mut() { + for segment in &mut ty_path.path.segments { if let PathArguments::AngleBracketed(angled) = &mut segment.arguments { - for arg in angled.args.iter_mut() { + for arg in &mut angled.args { if let GenericArgument::Type(ty) = arg { *ty = syn_type_cxx_bridge_to_qualified(ty, type_names)?; } else { @@ -89,7 +89,7 @@ pub(crate) fn syn_type_cxx_bridge_to_qualified(ty: &Type, type_names: &TypeNames **ty = syn_type_cxx_bridge_to_qualified(ty, type_names)?; } - for arg in ty_bare_fn.inputs.iter_mut() { + for arg in &mut ty_bare_fn.inputs { arg.ty = syn_type_cxx_bridge_to_qualified(&arg.ty, type_names)?; } @@ -101,7 +101,7 @@ pub(crate) fn syn_type_cxx_bridge_to_qualified(ty: &Type, type_names: &TypeNames Type::Slice(ty_slice) => convert_elem!(ty_slice, Type::Slice, type_names), Type::Tuple(ty_tuple) => { let mut ty_tuple = ty_tuple.clone(); - for elem in ty_tuple.elems.iter_mut() { + for elem in &mut ty_tuple.elems { *elem = syn_type_cxx_bridge_to_qualified(elem, type_names)?; } Ok(Type::Tuple(ty_tuple)) diff --git a/crates/cxx-qt-gen/src/naming/type_names.rs b/crates/cxx-qt-gen/src/naming/type_names.rs index 662618089..7e4f65e1c 100644 --- a/crates/cxx-qt-gen/src/naming/type_names.rs +++ b/crates/cxx-qt-gen/src/naming/type_names.rs @@ -187,7 +187,7 @@ impl TypeNames { self.populate_from_foreign_mod_item(&foreign_mod, bridge_namespace, module_ident)?; // Find and register the names of any qobjects in extern "C++Qt" - for qobject in extern_cxxqt.qobjects.iter() { + for qobject in &extern_cxxqt.qobjects { self.insert(qobject.name.clone())?; } @@ -225,7 +225,7 @@ impl TypeNames { if !this.shared_types.contains(&name.rust) || this.extern_types.contains(&name.rust) { - return Err(this.err_duplicate_type(&name.rust)); + return Err(Self::err_duplicate_type(&name.rust)); } this.check_duplicate_compatability(&name) }, @@ -270,7 +270,7 @@ impl TypeNames { if !this.extern_types.contains(&name.rust) || this.shared_types.contains(&name.rust) { - return Err(this.err_duplicate_type(&name.rust)); + return Err(Self::err_duplicate_type(&name.rust)); } this.check_duplicate_compatability(&name) })?; @@ -287,7 +287,7 @@ impl TypeNames { Ok(()) } - fn err_unknown_type(&self, ident: &Ident) -> Error { + fn err_unknown_type(ident: &Ident) -> Error { Error::new_spanned(ident, format!("Undeclared type: `{ident}`!")) } @@ -297,7 +297,7 @@ impl TypeNames { pub fn lookup(&self, ident: &Ident) -> Result<&Name> { self.names .get(ident) - .ok_or_else(|| self.err_unknown_type(ident)) + .ok_or_else(|| Self::err_unknown_type(ident)) } /// For a given rust ident return the CXX name with its namespace @@ -334,7 +334,7 @@ impl TypeNames { self.lookup(ident).map(Name::rust_qualified) } - fn err_duplicate_type(&self, ident: &Ident) -> Error { + fn err_duplicate_type(ident: &Ident) -> Error { Error::new_spanned( ident, format!("The type name `{ident}` is defined multiple times"), @@ -350,13 +350,11 @@ impl TypeNames { parent_namespace: Option<&str>, module_ident: &Ident, ) -> Result<()> { - self.populate_or_else( - ident, - attrs, - parent_namespace, - module_ident, - |this, name| Err(this.err_duplicate_type(&name.rust)), - ) + // CODECOV_EXCLUDE_START + self.populate_or_else(ident, attrs, parent_namespace, module_ident, |_, name| { + Err(Self::err_duplicate_type(&name.rust)) + }) + // CODECOV_EXCLUDE_STOP } fn populate_or_else( @@ -390,7 +388,7 @@ impl TypeNames { let entry = self.names.entry(name.rust.clone()); match entry { - Entry::Occupied(_) => Err(self.err_duplicate_type(&name.rust)), + Entry::Occupied(_) => Err(Self::err_duplicate_type(&name.rust)), Entry::Vacant(entry) => { entry.insert(name); Ok(()) @@ -911,6 +909,6 @@ mod tests { let mut types = TypeNames::default(); assert!(types .populate_from_foreign_mod_item(&item_mod, None, &format_ident!("ffi")) - .is_err()) + .is_err()); } } diff --git a/crates/cxx-qt-gen/src/parser/method.rs b/crates/cxx-qt-gen/src/parser/method.rs index 89c708da5..a94d2a6a9 100644 --- a/crates/cxx-qt-gen/src/parser/method.rs +++ b/crates/cxx-qt-gen/src/parser/method.rs @@ -33,7 +33,7 @@ impl ParsedQInvokableSpecifiers { } } - fn from_attrs(attrs: BTreeMap<&str, &Attribute>) -> HashSet { + fn from_attrs(attrs: &BTreeMap<&str, &Attribute>) -> HashSet { let mut output = HashSet::new(); for specifier in [ ParsedQInvokableSpecifiers::Final, @@ -127,7 +127,7 @@ impl ParsedMethod { // Determine if the method is invokable let is_qinvokable = attrs.contains_key("qinvokable"); let is_pure = attrs.contains_key("cxx_pure"); - let specifiers = ParsedQInvokableSpecifiers::from_attrs(attrs); + let specifiers = ParsedQInvokableSpecifiers::from_attrs(&attrs); Ok(Self { method_fields: fields, diff --git a/crates/cxx-qt-gen/src/parser/mod.rs b/crates/cxx-qt-gen/src/parser/mod.rs index 7dacdbe94..2be393926 100644 --- a/crates/cxx-qt-gen/src/parser/mod.rs +++ b/crates/cxx-qt-gen/src/parser/mod.rs @@ -83,7 +83,7 @@ impl CaseConversion { .map(|attr| meta_to_case(attr, Case::Camel)) .transpose()?; - Ok(Self { rust, cxx }) + Ok(Self { cxx, rust }) } } @@ -244,7 +244,7 @@ impl Parser { // Check that there are items in the module if let Some((_, items)) = module.content { // Loop through items and load into qobject or others and populate mappings - for item in items.into_iter() { + for item in items { // Try to find any CXX-Qt items, if found add them to the relevant // qobject or extern C++Qt block. Otherwise return them to be added to other if let Some(other) = cxx_qt_data.parse_cxx_qt_item(item)? { diff --git a/crates/cxx-qt-gen/src/parser/parameter.rs b/crates/cxx-qt-gen/src/parser/parameter.rs index 4faf75078..7d45f55b3 100644 --- a/crates/cxx-qt-gen/src/parser/parameter.rs +++ b/crates/cxx-qt-gen/src/parser/parameter.rs @@ -123,13 +123,13 @@ mod tests { let parameters = ParsedFunctionParameter::parse_remaining(function.sig.inputs.iter()).unwrap(); - assert_eq!(parameters.len(), 0) + assert_eq!(parameters.len(), 0); } #[test] fn test_parse_non_ident_type_pat() { let type_pattern: PatType = parse_quote!( (a, b): (i32, i32) ); - assert!(ParsedFunctionParameter::parse(&type_pattern).is_err()) + assert!(ParsedFunctionParameter::parse(&type_pattern).is_err()); } #[test] @@ -170,6 +170,6 @@ mod tests { fn foo(); }; - assert!(ParsedFunctionParameter::parse_all_ignoring_receiver(&function.sig).is_err()) + assert!(ParsedFunctionParameter::parse_all_ignoring_receiver(&function.sig).is_err()); } } diff --git a/crates/cxx-qt-gen/src/parser/property.rs b/crates/cxx-qt-gen/src/parser/property.rs index d3b9d6c9e..9f6516b86 100644 --- a/crates/cxx-qt-gen/src/parser/property.rs +++ b/crates/cxx-qt-gen/src/parser/property.rs @@ -175,7 +175,7 @@ impl ParsedQProperty { )) } } - }; + } Ok(()) }; diff --git a/crates/cxx-qt-gen/src/parser/qobject.rs b/crates/cxx-qt-gen/src/parser/qobject.rs index ce2c34a61..adb24591f 100644 --- a/crates/cxx-qt-gen/src/parser/qobject.rs +++ b/crates/cxx-qt-gen/src/parser/qobject.rs @@ -258,7 +258,7 @@ pub mod tests { assert_eq!(properties[1].ty, f64_type()); } - fn assert_qml_name(obj: ParsedQObject, str_name: &str) { + fn assert_qml_name(obj: &ParsedQObject, str_name: &str) { assert_eq!( obj.qml_metadata, Some(QmlElementMetadata { @@ -276,7 +276,7 @@ pub mod tests { #[qml_element] type MyObject = super::MyObjectRust; }; - assert_qml_name(qobject, "MyObject"); + assert_qml_name(&qobject, "MyObject"); } #[test] @@ -286,7 +286,7 @@ pub mod tests { #[qml_element = "OtherName"] type MyObject = super::MyObjectRust; }; - assert_qml_name(qobject, "OtherName"); + assert_qml_name(&qobject, "OtherName"); } #[test] @@ -304,7 +304,7 @@ pub mod tests { CaseConversion::none(), ) .unwrap(); - assert_qml_name(qobject, "RenamedObject"); + assert_qml_name(&qobject, "RenamedObject"); } #[test] diff --git a/crates/cxx-qt-gen/src/parser/trait_impl.rs b/crates/cxx-qt-gen/src/parser/trait_impl.rs index bae937088..a9f03f645 100644 --- a/crates/cxx-qt-gen/src/parser/trait_impl.rs +++ b/crates/cxx-qt-gen/src/parser/trait_impl.rs @@ -135,7 +135,7 @@ mod tests { }; let marker = TraitImpl::parse(imp).unwrap(); assert_eq!(marker.qobject, format_ident!("MyObject")); - assert!(matches!(marker.kind, TraitKind::Constructor(_))) + assert!(matches!(marker.kind, TraitKind::Constructor(_))); } #[test] diff --git a/crates/cxx-qt-gen/src/syntax/foreignmod.rs b/crates/cxx-qt-gen/src/syntax/foreignmod.rs index be1565fef..f53a6ee60 100644 --- a/crates/cxx-qt-gen/src/syntax/foreignmod.rs +++ b/crates/cxx-qt-gen/src/syntax/foreignmod.rs @@ -225,7 +225,7 @@ mod tests { } }; let result = foreign_mod_to_foreign_item_types(&item); - assert!(result.is_err()) + assert!(result.is_err()); } #[test] diff --git a/crates/cxx-qt-gen/src/syntax/qtfile.rs b/crates/cxx-qt-gen/src/syntax/qtfile.rs index e6a236e11..7a5d8c674 100644 --- a/crates/cxx-qt-gen/src/syntax/qtfile.rs +++ b/crates/cxx-qt-gen/src/syntax/qtfile.rs @@ -77,7 +77,7 @@ mod tests { assert!(qt_file.attrs.is_empty()); assert_eq!(qt_file.items.len(), 1); - assert!(matches!(qt_file.items.first(), Some(CxxQt(_)))) + assert!(matches!(qt_file.items.first(), Some(CxxQt(_)))); } #[test] @@ -88,7 +88,7 @@ mod tests { assert!(qt_file.attrs.is_empty()); assert_eq!(qt_file.items.len(), 1); - assert!(matches!(qt_file.items.first(), Some(CxxQt(_)))) + assert!(matches!(qt_file.items.first(), Some(CxxQt(_)))); } #[test] @@ -133,7 +133,7 @@ mod tests { name: &str } }, - ) + ); } #[test] diff --git a/crates/cxx-qt-gen/src/syntax/qtitem.rs b/crates/cxx-qt-gen/src/syntax/qtitem.rs index 9f38d3543..2b6d3c3a9 100644 --- a/crates/cxx-qt-gen/src/syntax/qtitem.rs +++ b/crates/cxx-qt-gen/src/syntax/qtitem.rs @@ -73,10 +73,7 @@ impl ToTokens for CxxQtItem { CxxQtItem::Item(item) => { item.to_tokens(tokens); } - CxxQtItem::Cxx(module) => { - module.to_tokens(tokens); - } - CxxQtItem::CxxQt(module) => { + CxxQtItem::Cxx(module) | CxxQtItem::CxxQt(module) => { module.to_tokens(tokens); } } @@ -94,7 +91,7 @@ mod tests { mod ffi {} }; let debug_formatted = format!("{cxx:?}"); - assert!(debug_formatted.starts_with("Cxx(ItemMod")) + assert!(debug_formatted.starts_with("Cxx(ItemMod")); } #[test] @@ -104,7 +101,7 @@ mod tests { mod ffi {} }; let debug_formatted = format!("{cxx_qt:?}"); - assert!(debug_formatted.starts_with("CxxQt(ItemMod")) + assert!(debug_formatted.starts_with("CxxQt(ItemMod")); } #[test] @@ -114,7 +111,7 @@ mod tests { mod ffi {} }; let debug_formatted = format!("{cxx:?}"); - assert!(debug_formatted.starts_with("Item(Item::Mod")) + assert!(debug_formatted.starts_with("Item(Item::Mod")); } #[test] @@ -125,6 +122,6 @@ mod tests { } }; let debug_formatted = format!("{rust:?}"); - assert!(debug_formatted.starts_with("Item(Item::Struct")) + assert!(debug_formatted.starts_with("Item(Item::Struct")); } } diff --git a/crates/cxx-qt-gen/src/syntax/types.rs b/crates/cxx-qt-gen/src/syntax/types.rs index 307c57a2f..ce02c559f 100644 --- a/crates/cxx-qt-gen/src/syntax/types.rs +++ b/crates/cxx-qt-gen/src/syntax/types.rs @@ -152,16 +152,16 @@ mod tests { assert!(!super::is_pin_of_self(&parse_quote! { *mut T })); } - fn assert_qobject_ident(ty: Type, expected_ident: &str, expected_mutability: bool) { - let (ident, mutability) = super::extract_qobject_ident(&ty).unwrap(); + fn assert_qobject_ident(ty: &Type, expected_ident: &str, expected_mutability: bool) { + let (ident, mutability) = super::extract_qobject_ident(ty).unwrap(); assert_eq!(ident.to_string(), expected_ident); assert_eq!(mutability.is_some(), expected_mutability); } #[test] fn test_extract_qobject_ident() { - assert_qobject_ident(parse_quote! { &Foo }, "Foo", false); - assert_qobject_ident(parse_quote! { Pin<&mut Foo> }, "Foo", true); + assert_qobject_ident(&parse_quote! { &Foo }, "Foo", false); + assert_qobject_ident(&parse_quote! { Pin<&mut Foo> }, "Foo", true); assert_parse_errors! { |ty| super::extract_qobject_ident(&ty) => @@ -182,6 +182,6 @@ mod tests { unsafe fn test(self: Pin); }; let parsed = ParsedMethod::parse(method, CaseConversion::none(), false); - assert!(parsed.is_err()) + assert!(parsed.is_err()); } } diff --git a/crates/cxx-qt-gen/src/writer/cpp/header.rs b/crates/cxx-qt-gen/src/writer/cpp/header.rs index dae01fe7c..0ae79a195 100644 --- a/crates/cxx-qt-gen/src/writer/cpp/header.rs +++ b/crates/cxx-qt-gen/src/writer/cpp/header.rs @@ -14,10 +14,10 @@ fn create_block(block: &str, items: &[String]) -> String { if items.is_empty() { String::new() } else { - formatdoc! {r#" + formatdoc! {r" {block}: {items} - "#, + ", block = block, items = items .iter() @@ -40,19 +40,19 @@ fn forward_declare(generated: &GeneratedCppBlocks) -> Vec { .map(|qobject| { let forward_declares = namespaced( qobject.name.namespace().unwrap_or_default(), - &formatdoc! {r#" + &formatdoc! {r" class {ident}; {forward_declares} - "#, + ", ident = &qobject.name.cxx_unqualified(), forward_declares = qobject.blocks.forward_declares.join("\n"), }, ); let forward_declares_namespaced = qobject.blocks.forward_declares_namespaced.join("\n"); - formatdoc! {r#" + formatdoc! {r" {forward_declares} {forward_declares_namespaced} - "#} + "} }) .chain(generated.forward_declares.iter().cloned()) .chain( @@ -80,7 +80,7 @@ fn qobjects_header(generated: &GeneratedCppBlocks) -> Vec { }; let class_definition = namespaced( qobject.name.namespace().unwrap_or_default(), - &formatdoc! { r#" + &formatdoc! { r" class {ident} : {base_classes} {{ {qobject_macro} @@ -93,7 +93,7 @@ fn qobjects_header(generated: &GeneratedCppBlocks) -> Vec { {private_methods} }}; - {qobject_assert}"#, + {qobject_assert}", // Note that there is always a base class as we always have CxxQtType base_classes = qobject.blocks.base_classes.iter().map(|base| format!("public {base}")).collect::>().join(", "), metaobjects = qobject.blocks.metaobjects.join("\n "), @@ -116,12 +116,12 @@ fn qobjects_header(generated: &GeneratedCppBlocks) -> Vec { String::new() }; - formatdoc! {r#" + formatdoc! {r" {fragments} {class_definition} {declare_metatype} - "# + " } }).collect::>() } @@ -288,6 +288,6 @@ public: "#}; - assert_str_eq!(format_cpp(&header), format_cpp(expected)) + assert_str_eq!(format_cpp(&header), format_cpp(expected)); } } diff --git a/crates/cxx-qt-gen/src/writer/cpp/mod.rs b/crates/cxx-qt-gen/src/writer/cpp/mod.rs index ec4d23401..b1e1963dd 100644 --- a/crates/cxx-qt-gen/src/writer/cpp/mod.rs +++ b/crates/cxx-qt-gen/src/writer/cpp/mod.rs @@ -17,11 +17,11 @@ pub fn namespaced(namespace: &str, cpp_code: &str) -> String { if namespace.is_empty() { cpp_code.to_owned() } else { - formatdoc! {r#" + formatdoc! {r" namespace {namespace} {{ {cpp_code} }} // namespace {namespace} - "# } + " } } } @@ -38,18 +38,20 @@ pub fn write_cpp(generated: &GeneratedCppBlocks, include_path: &str) -> CppFragm /// Extract the header from a given CppFragment pub fn pair_as_header(pair: &CppFragment) -> Option { match pair { - CppFragment::Pair { header, source: _ } => Some(header.clone()), - CppFragment::Header(header) => Some(header.clone()), CppFragment::Source(_) => None, + CppFragment::Header(header) | CppFragment::Pair { header, source: _ } => { + Some(header.clone()) + } } } /// Extract the source from a given CppFragment pub fn pair_as_source(pair: &CppFragment) -> Option { match pair { - CppFragment::Pair { header: _, source } => Some(source.clone()), CppFragment::Header(_) => None, - CppFragment::Source(source) => Some(source.clone()), + CppFragment::Source(source) | CppFragment::Pair { header: _, source } => { + Some(source.clone()) + } } } @@ -125,68 +127,68 @@ mod tests { methods: vec![ CppFragment::Pair { header: "int count() const;".to_owned(), - source: indoc! {r#" + source: indoc! {r" int MyObject::count() const { // getter } - "#} + "} .to_owned(), }, CppFragment::Pair { header: "bool toggle() const;".to_owned(), - source: indoc! {r#" + source: indoc! {r" bool MyObject::toggle() const { // getter } - "#} + "} .to_owned(), }, CppFragment::Pair { header: "Q_INVOKABLE void invokable();".to_owned(), - source: indoc! {r#" + source: indoc! {r" void MyObject::invokable() { // invokable method } - "#} + "} .to_owned(), }, CppFragment::Pair { header: "void cppMethod();".to_owned(), - source: indoc! {r#" + source: indoc! {r" void MyObject::cppMethod() { // cpp method } - "#} + "} .to_owned(), }, CppFragment::Pair { header: "Q_SLOT void setCount(int count);".to_owned(), - source: indoc! {r#" + source: indoc! {r" void MyObject::setCount(int count) const { // setter } - "#} + "} .to_owned(), }, CppFragment::Pair { header: "Q_SLOT void setToggle(bool toggle);".to_owned(), - source: indoc! {r#" + source: indoc! {r" void MyObject::setToggle(bool toggle) const { // setter } - "#} + "} .to_owned(), }, CppFragment::Header ( @@ -198,20 +200,20 @@ mod tests { ], private_methods: vec![CppFragment::Pair{ header: "void privateMethod() const;".to_owned(), - source: indoc! {r#" + source: indoc! {r" void MyObject::privateMethod() const { // private method } - "#}.to_owned(), + "}.to_owned(), }, CppFragment::Pair{ header: "void privateMethod();".to_owned(), - source: indoc! {r#" + source: indoc! {r" void MyObject::privateMethod() { // non-const private method } - "#}.to_owned(), + "}.to_owned(), }], ..Default::default() } @@ -245,24 +247,24 @@ mod tests { ], methods: vec![CppFragment::Pair { header: "int count() const;".to_owned(), - source: indoc! {r#" + source: indoc! {r" int FirstObject::count() const { // getter } - "#} + "} .to_owned(), }, CppFragment::Pair { header: "Q_SLOT void setCount(int count);".to_owned(), - source: indoc! {r#" + source: indoc! {r" void FirstObject::setCount(int count) const { // setter } - "#} + "} .to_owned(), }, CppFragment::Header("Q_SIGNAL void countChanged();".to_owned()), @@ -288,24 +290,24 @@ mod tests { ], methods: vec![CppFragment::Pair { header: "int count() const;".to_owned(), - source: indoc! {r#" + source: indoc! {r" int SecondObject::count() const { // getter } - "#} + "} .to_owned(), }, CppFragment::Pair { header: "Q_SLOT void setCount(int count);".to_owned(), - source: indoc! {r#" + source: indoc! {r" void SecondObject::setCount(int count) const { // setter } - "#} + "} .to_owned(), }, CppFragment::Header("Q_SIGNAL void countChanged();".to_owned()), @@ -313,11 +315,11 @@ mod tests { private_methods: vec![ CppFragment::Pair{ header: "void privateMethod() const;".to_owned(), - source: indoc! {r#" + source: indoc! {r" void SecondObject::privateMethod() const { // private method } - "#}.to_owned(), + "}.to_owned(), }], ..Default::default() }, @@ -673,12 +675,12 @@ mod tests { let namespaced_code = namespaced("my_namespace", cpp_code); assert_str_eq!( - indoc! {r#" + indoc! {r" namespace my_namespace { // My C++ Code // with multi-line } // namespace my_namespace - "# + " }, namespaced_code ); @@ -686,9 +688,9 @@ mod tests { #[test] fn namespacing_with_empty_namespace() { - let cpp_code = indoc! {r#" + let cpp_code = indoc! {r" // My C++ Code - "#}; + "}; let namespaced_code = namespaced("", cpp_code); assert_str_eq!(cpp_code, namespaced_code); } diff --git a/crates/cxx-qt-lib-extras/src/core/qcommandlineoption.rs b/crates/cxx-qt-lib-extras/src/core/qcommandlineoption.rs index 6eda5495c..4c9893e51 100644 --- a/crates/cxx-qt-lib-extras/src/core/qcommandlineoption.rs +++ b/crates/cxx-qt-lib-extras/src/core/qcommandlineoption.rs @@ -103,7 +103,7 @@ impl Clone for QCommandLineOption { impl Drop for QCommandLineOption { /// Destroys the `QCommandLineOption`. fn drop(&mut self) { - ffi::qcommandlineoption_drop(self) + ffi::qcommandlineoption_drop(self); } } diff --git a/crates/cxx-qt-lib-extras/src/core/qeventloop.rs b/crates/cxx-qt-lib-extras/src/core/qeventloop.rs index e465300c3..c780997b3 100644 --- a/crates/cxx-qt-lib-extras/src/core/qeventloop.rs +++ b/crates/cxx-qt-lib-extras/src/core/qeventloop.rs @@ -2,6 +2,7 @@ // SPDX-FileContributor: Joshua Booth // // SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::elidable_lifetime_names)] use std::pin::Pin; use std::time::Duration; @@ -190,7 +191,7 @@ struct EventLoopClosure<'a> { closure: Option>, } -impl<'a> EventLoopClosure<'a> { +impl EventLoopClosure<'_> { pub fn run(&mut self) { self.closure.take().unwrap()(); } diff --git a/crates/cxx-qt-lib-extras/src/gui/qapplication.rs b/crates/cxx-qt-lib-extras/src/gui/qapplication.rs index 24ce34579..33d4d19cd 100644 --- a/crates/cxx-qt-lib-extras/src/gui/qapplication.rs +++ b/crates/cxx-qt-lib-extras/src/gui/qapplication.rs @@ -175,7 +175,7 @@ impl QApplication { /// Removes `path` from the library path list. If `path` is empty or not in the path list, the list is not changed. pub fn remove_library_path(&self, path: &QString) { - ffi::qapplication_remove_library_path(self, path) + ffi::qapplication_remove_library_path(self, path); } /// Set the `version` of this application. diff --git a/crates/cxx-qt-lib/src/core/qbytearray.rs b/crates/cxx-qt-lib/src/core/qbytearray.rs index 98c52b289..fbdc87926 100644 --- a/crates/cxx-qt-lib/src/core/qbytearray.rs +++ b/crates/cxx-qt-lib/src/core/qbytearray.rs @@ -228,7 +228,7 @@ impl fmt::Debug for QByteArray { impl Drop for QByteArray { /// Destroys the byte array. fn drop(&mut self) { - ffi::qbytearray_drop(self) + ffi::qbytearray_drop(self); } } @@ -303,10 +303,14 @@ impl QByteArray { /// If `size` is different from -1, /// the byte array is resized to size `size` beforehand. pub fn fill(&mut self, ch: u8, size: isize) { - ffi::qbytearray_fill(self, ch, size) + ffi::qbytearray_fill(self, ch, size); } /// Decodes the Base64 array `base64`, using the options defined by `options`. + /// + /// # Errors + /// + /// This function will return an error if the contents of `base64` are not Base64 encoded. pub fn from_base64_encoding( base64: &Self, options: QByteArrayBase64Options, @@ -433,7 +437,6 @@ unsafe impl ExternType for QByteArrayFromBase64Result { type Kind = cxx::kind::Trivial; } -#[allow(clippy::enum_variant_names)] #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum QByteArrayFromBase64Error { IllegalInputLength = 1, @@ -484,9 +487,9 @@ impl<'de> serde::Deserialize<'de> for QByteArray { fn visit_seq>(self, mut seq: A) -> Result { let mut values = Self::Value::default(); - if let Some(size_hint) = seq.size_hint() { - if size_hint != 0 && size_hint <= isize::MAX as usize { - values.reserve(size_hint as isize); + if let Some(size_hint) = seq.size_hint().and_then(|hint| hint.try_into().ok()) { + if size_hint != 0 { + values.reserve(size_hint); } } while let Some(value) = seq.next_element()? { @@ -517,7 +520,7 @@ mod tests { #[test] fn qbytearray_serde() { let qbytearray = QByteArray::from("KDAB"); - assert_eq!(crate::serde_impl::roundtrip(&qbytearray), qbytearray) + assert_eq!(crate::serde_impl::roundtrip(&qbytearray), qbytearray); } #[test] @@ -546,12 +549,12 @@ mod tests { assert_eq!(bytes.as_ref(), qbytearray.as_ref()); let bytes_bytes = bytes::Bytes::from(&qbytearray); - assert_eq!(bytes, bytes_bytes) + assert_eq!(bytes, bytes_bytes); } #[test] fn test_display_fmt() { let qbytearray = QByteArray::from("KDAB"); - assert_eq!(format!("{qbytearray:-<8}"), "KDAB----") + assert_eq!(format!("{qbytearray:-<8}"), "KDAB----"); } } diff --git a/crates/cxx-qt-lib/src/core/qcoreapplication.rs b/crates/cxx-qt-lib/src/core/qcoreapplication.rs index a8c1c5c7d..add88b734 100644 --- a/crates/cxx-qt-lib/src/core/qcoreapplication.rs +++ b/crates/cxx-qt-lib/src/core/qcoreapplication.rs @@ -161,7 +161,7 @@ impl QCoreApplication { /// Removes `path` from the library path list. If `path` is empty or not in the path list, the list is not changed. pub fn remove_library_path(&self, path: &QString) { - ffi::qcoreapplication_remove_library_path(self, path) + ffi::qcoreapplication_remove_library_path(self, path); } /// Set the `name` of this application. diff --git a/crates/cxx-qt-lib/src/core/qdate.rs b/crates/cxx-qt-lib/src/core/qdate.rs index bb1153f94..a11dbe5bd 100644 --- a/crates/cxx-qt-lib/src/core/qdate.rs +++ b/crates/cxx-qt-lib/src/core/qdate.rs @@ -275,8 +275,8 @@ impl From for QDate { fn from(value: time::Date) -> Self { QDate::new( value.year(), - Into::::into(value.month()) as i32, - value.day() as i32, + u8::from(value.month()).into(), + value.day().into(), ) } } diff --git a/crates/cxx-qt-lib/src/core/qdatetime.rs b/crates/cxx-qt-lib/src/core/qdatetime.rs index cd03a0616..79879a889 100644 --- a/crates/cxx-qt-lib/src/core/qdatetime.rs +++ b/crates/cxx-qt-lib/src/core/qdatetime.rs @@ -266,7 +266,7 @@ impl QDateTime { /// /// If `time_zone` is invalid then the datetime will be invalid. pub fn set_time_zone(&mut self, time_zone: &QTimeZone) { - ffi::qdatetime_settimezone(self, time_zone) + ffi::qdatetime_settimezone(self, time_zone); } /// Returns a `QDateTime` object containing a datetime `ndays` days later than the datetime of this object (or earlier if `ndays` is negative). diff --git a/crates/cxx-qt-lib/src/core/qhash/mod.rs b/crates/cxx-qt-lib/src/core/qhash/mod.rs index 28ff34597..a3a53051f 100644 --- a/crates/cxx-qt-lib/src/core/qhash/mod.rs +++ b/crates/cxx-qt-lib/src/core/qhash/mod.rs @@ -2,6 +2,8 @@ // SPDX-FileContributor: Andrew Hayzen // // SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::trivially_copy_pass_by_ref)] + use core::{marker::PhantomData, mem::MaybeUninit}; use cxx::{type_id, ExternType}; use std::fmt; @@ -49,7 +51,7 @@ where { /// Destroys the hash. fn drop(&mut self) { - T::drop(self) + T::drop(self); } } @@ -76,7 +78,7 @@ where { /// Removes all items from the hash and frees up all memory used by it. pub fn clear(&mut self) { - T::clear(self) + T::clear(self); } /// Returns `true` if the hash contains an item with the key; otherwise returns `false`. @@ -107,7 +109,7 @@ where /// The key and value is a reference here so it can be opaque or trivial but /// note that the key and value is copied when being inserted into the hash. pub fn insert_clone(&mut self, key: &T::Key, value: &T::Value) { - T::insert_clone(self, key, value) + T::insert_clone(self, key, value); } /// Returns `true` if the hash contains no items; otherwise returns `false`. @@ -145,7 +147,7 @@ where { /// Inserts a new item with the `key` and a value of `value`. pub fn insert(&mut self, key: T::Key, value: T::Value) { - T::insert(self, key, value) + T::insert(self, key, value); } } diff --git a/crates/cxx-qt-lib/src/core/qlist/mod.rs b/crates/cxx-qt-lib/src/core/qlist/mod.rs index 72107a6fc..150e2fd00 100644 --- a/crates/cxx-qt-lib/src/core/qlist/mod.rs +++ b/crates/cxx-qt-lib/src/core/qlist/mod.rs @@ -2,6 +2,7 @@ // SPDX-FileContributor: Andrew Hayzen // // SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::trivially_copy_pass_by_ref)] #[cfg(feature = "qt_gui")] use crate::QColor; @@ -199,7 +200,7 @@ where /// The original `QList` can still be used after constructing the `Vec`. fn from(qlist: &QList) -> Self { let mut vec = Vec::with_capacity(qlist.len().try_into().unwrap()); - for element in qlist.iter() { + for element in qlist { vec.push(element.clone()); } vec diff --git a/crates/cxx-qt-lib/src/core/qmap/mod.rs b/crates/cxx-qt-lib/src/core/qmap/mod.rs index f79bcbdf4..e1da03c4c 100644 --- a/crates/cxx-qt-lib/src/core/qmap/mod.rs +++ b/crates/cxx-qt-lib/src/core/qmap/mod.rs @@ -46,7 +46,7 @@ where { /// Destroys the map. fn drop(&mut self) { - T::drop(self) + T::drop(self); } } @@ -85,7 +85,7 @@ where { /// Removes all items from the map. pub fn clear(&mut self) { - T::clear(self) + T::clear(self); } /// Returns `true` if the map contains an item with key `key`; otherwise returns `false`. @@ -114,7 +114,7 @@ where /// The key and value are references here so they can be opaque or trivial. /// Note that the key and value are cloned before inserting into the map. pub fn insert_clone(&mut self, key: &T::Key, value: &T::Value) { - T::insert_clone(self, key, value) + T::insert_clone(self, key, value); } /// Returns `true` if the map contains no items; otherwise returns `false`. @@ -152,7 +152,7 @@ where { /// Inserts a new item with the key `key` and a value of `value`. pub fn insert(&mut self, key: T::Key, value: T::Value) { - T::insert(self, key, value) + T::insert(self, key, value); } } diff --git a/crates/cxx-qt-lib/src/core/qobject.rs b/crates/cxx-qt-lib/src/core/qobject.rs index b977555ef..99e6e46f3 100644 --- a/crates/cxx-qt-lib/src/core/qobject.rs +++ b/crates/cxx-qt-lib/src/core/qobject.rs @@ -95,7 +95,7 @@ impl QObjectExt for QObject { } fn set_object_name(self: Pin<&mut Self>, name: &QString) { - cast_pin(self).set_object_name(name) + cast_pin(self).set_object_name(name); } fn object_name(&self) -> QString { @@ -103,7 +103,7 @@ impl QObjectExt for QObject { } fn parent(&self) -> *mut Self { - cast(self).parent() as *mut Self + cast(self).parent().cast() } fn set_parent(self: Pin<&mut Self>, parent: Pin<&mut T>) @@ -112,7 +112,7 @@ impl QObjectExt for QObject { { unsafe { let parent = ptr::from_mut(parent.get_unchecked_mut().upcast_mut()).cast(); - cast_pin(self).set_parent(parent) + cast_pin(self).set_parent(parent); } } diff --git a/crates/cxx-qt-lib/src/core/qpersistentmodelindex.rs b/crates/cxx-qt-lib/src/core/qpersistentmodelindex.rs index 3409b06eb..d463d8ec5 100644 --- a/crates/cxx-qt-lib/src/core/qpersistentmodelindex.rs +++ b/crates/cxx-qt-lib/src/core/qpersistentmodelindex.rs @@ -77,7 +77,7 @@ impl Clone for QPersistentModelIndex { impl Drop for QPersistentModelIndex { /// Destroys the persistent model index. fn drop(&mut self) { - ffi::qpersistentmodelindex_drop(self) + ffi::qpersistentmodelindex_drop(self); } } diff --git a/crates/cxx-qt-lib/src/core/qset/mod.rs b/crates/cxx-qt-lib/src/core/qset/mod.rs index 62e1086b5..605011f34 100644 --- a/crates/cxx-qt-lib/src/core/qset/mod.rs +++ b/crates/cxx-qt-lib/src/core/qset/mod.rs @@ -2,6 +2,8 @@ // SPDX-FileContributor: Andrew Hayzen // // SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::trivially_copy_pass_by_ref)] + #[cfg(not(target_os = "emscripten"))] use crate::QDateTime; use crate::{QByteArray, QDate, QPersistentModelIndex, QString, QTime, QUrl, QUuid}; @@ -373,6 +375,6 @@ mod test { set.insert(0); set.insert(1); set.insert(2); - assert_eq!(crate::serde_impl::roundtrip(&set), set) + assert_eq!(crate::serde_impl::roundtrip(&set), set); } } diff --git a/crates/cxx-qt-lib/src/core/qstring.rs b/crates/cxx-qt-lib/src/core/qstring.rs index eb07d35ff..3b395ff77 100644 --- a/crates/cxx-qt-lib/src/core/qstring.rs +++ b/crates/cxx-qt-lib/src/core/qstring.rs @@ -291,7 +291,7 @@ impl std::ops::Add for QString { impl Drop for QString { /// Destroys the string. fn drop(&mut self) { - ffi::qstring_drop(self) + ffi::qstring_drop(self); } } diff --git a/crates/cxx-qt-lib/src/core/qstringlist.rs b/crates/cxx-qt-lib/src/core/qstringlist.rs index 84016306c..02a6c1524 100644 --- a/crates/cxx-qt-lib/src/core/qstringlist.rs +++ b/crates/cxx-qt-lib/src/core/qstringlist.rs @@ -252,6 +252,6 @@ mod test { let mut qstringlist = QStringList::default(); qstringlist.append(QString::from("element 1")); qstringlist.append(QString::from("element 2")); - assert_eq!(crate::serde_impl::roundtrip(&qstringlist), qstringlist) + assert_eq!(crate::serde_impl::roundtrip(&qstringlist), qstringlist); } } diff --git a/crates/cxx-qt-lib/src/core/qtime.rs b/crates/cxx-qt-lib/src/core/qtime.rs index 7fc52f0bd..2c92ad24c 100644 --- a/crates/cxx-qt-lib/src/core/qtime.rs +++ b/crates/cxx-qt-lib/src/core/qtime.rs @@ -272,10 +272,10 @@ impl TryFrom for chrono::NaiveTime { impl From for QTime { fn from(value: time::Time) -> Self { QTime::new( - value.hour() as i32, - value.minute() as i32, - value.second() as i32, - value.millisecond() as i32, + value.hour().into(), + value.minute().into(), + value.second().into(), + value.millisecond().into(), ) } } diff --git a/crates/cxx-qt-lib/src/core/qurl.rs b/crates/cxx-qt-lib/src/core/qurl.rs index 94c69291e..82d85c067 100644 --- a/crates/cxx-qt-lib/src/core/qurl.rs +++ b/crates/cxx-qt-lib/src/core/qurl.rs @@ -320,45 +320,45 @@ impl QUrl { /// Sets the authority of the URL to `authority`. pub fn set_authority(&mut self, authority: &QString) { - ffi::qurl_set_authority(self, authority) + ffi::qurl_set_authority(self, authority); } /// Sets the fragment of the URL to `fragment`. /// The fragment is the last part of the URL, represented by a `'#'` followed by a string of characters. pub fn set_fragment(&mut self, fragment: &QString) { - ffi::qurl_set_fragment(self, fragment) + ffi::qurl_set_fragment(self, fragment); } /// Sets the host of the URL to `host`. The host is part of the authority. pub fn set_host(&mut self, host: &QString) { - ffi::qurl_set_host(self, host) + ffi::qurl_set_host(self, host); } /// Sets the whitelist of Top-Level Domains (TLDs) that are allowed to have non-ASCII characters in domains to the value of `list`. pub fn set_idn_whitelist(list: &QStringList) { - ffi::qurl_set_idn_whitelist(list) + ffi::qurl_set_idn_whitelist(list); } /// Sets the URL's password to `password`. pub fn set_password(&mut self, password: &QString) { - ffi::qurl_set_password(self, password) + ffi::qurl_set_password(self, password); } /// Sets the path of the URL to `path`. /// The path is the part of the URL that comes after the authority but before the query string. pub fn set_path(&mut self, path: &QString) { - ffi::qurl_set_path(self, path) + ffi::qurl_set_path(self, path); } /// Sets the query string of the URL to `query`. pub fn set_query(&mut self, query: &QString) { - ffi::qurl_set_query(self, query) + ffi::qurl_set_query(self, query); } /// Sets the scheme of the URL to `scheme`. As a scheme can only contain ASCII characters, /// no conversion or decoding is done on the input. It must also start with an ASCII letter. pub fn set_scheme(&mut self, scheme: &QString) { - ffi::qurl_set_scheme(self, scheme) + ffi::qurl_set_scheme(self, scheme); } /// Parses `url` and sets this object to that value. @@ -367,17 +367,17 @@ impl QUrl { /// (letters, digits, hyphens, underscores, dots and tildes). /// All other characters are left in their original forms. pub fn set_url(&mut self, url: &QString) { - ffi::qurl_set_url(self, url) + ffi::qurl_set_url(self, url); } /// Sets the user info of the URL to `user_info`. pub fn set_user_info(&mut self, user_info: &QString) { - ffi::qurl_set_user_info(self, user_info) + ffi::qurl_set_user_info(self, user_info); } /// Sets the URL's user name to `user_name`. pub fn set_user_name(&mut self, user_name: &QString) { - ffi::qurl_set_user_name(self, user_name) + ffi::qurl_set_user_name(self, user_name); } /// Returns a human-displayable string representation of the URL. @@ -461,7 +461,7 @@ impl fmt::Display for QUrl { /// Format the `QUrl` as a Rust string. /// /// Note that this converts from UTF-16 to UTF-8. - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result { ffi::qurl_to_display_string(self).fmt(f) } } @@ -475,7 +475,7 @@ impl fmt::Debug for QUrl { impl Drop for QUrl { /// Destructor; called immediately before the object is deleted. fn drop(&mut self) { - ffi::qurl_drop(self) + ffi::qurl_drop(self); } } diff --git a/crates/cxx-qt-lib/src/core/quuid.rs b/crates/cxx-qt-lib/src/core/quuid.rs index 87f742ec5..a198e04db 100644 --- a/crates/cxx-qt-lib/src/core/quuid.rs +++ b/crates/cxx-qt-lib/src/core/quuid.rs @@ -354,6 +354,7 @@ impl From for Uuid { } #[cfg(test)] +#[allow(clippy::unreadable_literal)] mod test { use super::*; @@ -361,12 +362,12 @@ mod test { #[test] fn quuid_is_null() { - assert!(QUuid::null().is_null()) + assert!(QUuid::null().is_null()); } #[test] fn quuid_is_not_null() { - assert!(!QUuid::create_uuid().is_null()) + assert!(!QUuid::create_uuid().is_null()); } #[test] @@ -392,13 +393,13 @@ mod test { QUuidVersion::Random, QUuidVersion::Sha1 ] - ) + ); } #[test] fn quuid_to_rfc_4122() { let bytes = <[u8; 16]>::try_from("random test data".as_bytes()).unwrap(); - assert_eq!(Vec::from(&QUuid::from_bytes(bytes).to_rfc_4122()), bytes) + assert_eq!(Vec::from(&QUuid::from_bytes(bytes).to_rfc_4122()), bytes); } #[test] @@ -432,21 +433,21 @@ mod test { assert_eq!( QUuid::from_u128(0x7e95e361a22c51c18c297ac24cb61e83).to_string(), "{7e95e361-a22c-51c1-8c29-7ac24cb61e83}" - ) + ); } #[test] fn quuid_qstring_round_trip() { let uuid = QUuid::create_uuid(); let roundtrip = QUuid::from(&QString::from(&uuid.to_string())); - assert_eq!(uuid, roundtrip) + assert_eq!(uuid, roundtrip); } #[test] fn quuid_str_round_trip() { let uuid = QUuid::create_uuid(); let roundtrip = QUuid::from(&uuid.to_string()); - assert_eq!(uuid, roundtrip) + assert_eq!(uuid, roundtrip); } #[test] @@ -454,27 +455,27 @@ mod test { let uuid = QUuid::create_uuid(); let (d1, d2, d3, &d4) = uuid.as_fields(); let roundtrip = QUuid::from_fields(d1, d2, d3, d4); - assert_eq!(uuid, roundtrip) + assert_eq!(uuid, roundtrip); } #[test] fn quuid_bytes_round_trip() { let uuid = QUuid::create_uuid(); let roundtrip = QUuid::from_bytes(uuid.to_bytes()); - assert_eq!(uuid, roundtrip) + assert_eq!(uuid, roundtrip); } #[test] fn quuid_qbytearray_round_trip() { let uuid = QUuid::create_uuid(); let roundtrip = QUuid::from_rfc_4122(&uuid.to_rfc_4122()); - assert_eq!(uuid, roundtrip) + assert_eq!(uuid, roundtrip); } #[test] fn quuid_u128_round_trip() { let uuid = QUuid::create_uuid(); let roundtrip = QUuid::from_u128(uuid.to_u128()); - assert_eq!(uuid, roundtrip) + assert_eq!(uuid, roundtrip); } } diff --git a/crates/cxx-qt-lib/src/core/qvariant/mod.rs b/crates/cxx-qt-lib/src/core/qvariant/mod.rs index 0008d7558..720bd3818 100644 --- a/crates/cxx-qt-lib/src/core/qvariant/mod.rs +++ b/crates/cxx-qt-lib/src/core/qvariant/mod.rs @@ -3,6 +3,8 @@ // SPDX-FileContributor: Gerhard de Clercq // // SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::trivially_copy_pass_by_ref)] + use cxx::{type_id, ExternType}; use std::fmt; use std::mem::MaybeUninit; @@ -95,7 +97,7 @@ impl Default for QVariant { impl Drop for QVariant { /// Destroys the `QVariant` and the contained object. fn drop(&mut self) { - ffi::qvariant_drop(self) + ffi::qvariant_drop(self); } } diff --git a/crates/cxx-qt-lib/src/core/qvector/mod.rs b/crates/cxx-qt-lib/src/core/qvector/mod.rs index 612e7827a..197244ed7 100644 --- a/crates/cxx-qt-lib/src/core/qvector/mod.rs +++ b/crates/cxx-qt-lib/src/core/qvector/mod.rs @@ -2,6 +2,7 @@ // SPDX-FileContributor: Andrew Hayzen // // SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::trivially_copy_pass_by_ref)] #[cfg(feature = "qt_gui")] use crate::QColor; @@ -197,7 +198,7 @@ where /// The original `QVector` can still be used after constructing the `Vec`. fn from(qvec: &QVector) -> Self { let mut vec = Vec::with_capacity(qvec.len().try_into().unwrap()); - for element in qvec.iter() { + for element in qvec { vec.push(element.clone()); } vec diff --git a/crates/cxx-qt-lib/src/gui/qcolor.rs b/crates/cxx-qt-lib/src/gui/qcolor.rs index f8ff36ecf..e2fb99a54 100644 --- a/crates/cxx-qt-lib/src/gui/qcolor.rs +++ b/crates/cxx-qt-lib/src/gui/qcolor.rs @@ -596,7 +596,7 @@ impl fmt::Debug for QColor { #[cfg(feature = "rgb")] impl From<&rgb::RGB8> for QColor { fn from(value: &rgb::RGB8) -> Self { - Self::from_rgb(value.r as i32, value.g as i32, value.b as i32) + Self::from_rgb(value.r.into(), value.g.into(), value.b.into()) } } @@ -604,10 +604,10 @@ impl From<&rgb::RGB8> for QColor { impl From<&rgb::RGBA8> for QColor { fn from(value: &rgb::RGBA8) -> Self { Self::from_rgba( - value.r as i32, - value.g as i32, - value.b as i32, - value.a as i32, + value.r.into(), + value.g.into(), + value.b.into(), + value.a.into(), ) } } diff --git a/crates/cxx-qt-lib/src/gui/qguiapplication.rs b/crates/cxx-qt-lib/src/gui/qguiapplication.rs index b5e3893c0..daec44ab9 100644 --- a/crates/cxx-qt-lib/src/gui/qguiapplication.rs +++ b/crates/cxx-qt-lib/src/gui/qguiapplication.rs @@ -205,7 +205,7 @@ impl QGuiApplication { /// Removes `path` from the library path list. If `path` is empty or not in the path list, the list is not changed. pub fn remove_library_path(&self, path: &QString) { - ffi::qguiapplication_remove_library_path(self, path) + ffi::qguiapplication_remove_library_path(self, path); } /// Set the `version` of this application. diff --git a/crates/cxx-qt-lib/src/gui/qimage.rs b/crates/cxx-qt-lib/src/gui/qimage.rs index 90f7cc9d8..371b77593 100644 --- a/crates/cxx-qt-lib/src/gui/qimage.rs +++ b/crates/cxx-qt-lib/src/gui/qimage.rs @@ -548,12 +548,12 @@ impl QImage { // In this case the *mut ffi::c_void is actually a `*mut Vec` that was created by // Box::into_raw(), so can be re-created by Box::from_raw(). // QImage also guarantees that this is only called once when the last copy is destroyed. - let the_box: Box> = unsafe { Box::from_raw(boxed_vec as *mut Vec) }; + let the_box: Box> = unsafe { Box::from_raw(boxed_vec.cast()) }; drop(the_box); } let data = Box::new(data); let bytes = data.as_ptr() as *mut ffi::uchar; - let raw_box = Box::into_raw(data) as *mut ffi::c_void; + let raw_box = Box::into_raw(data).cast(); QImage::from_raw_parts_mut(bytes, width, height, format, delete_boxed_vec, raw_box) } diff --git a/crates/cxx-qt-lib/src/lib.rs b/crates/cxx-qt-lib/src/lib.rs index 3ba11e1a0..ac6cdcb36 100644 --- a/crates/cxx-qt-lib/src/lib.rs +++ b/crates/cxx-qt-lib/src/lib.rs @@ -3,7 +3,6 @@ // SPDX-FileContributor: Gerhard de Clercq // // SPDX-License-Identifier: MIT OR Apache-2.0 - #![cfg_attr(docsrs, feature(doc_auto_cfg))] #[cfg(not(any(cxxqt_qt_version_major = "5", cxxqt_qt_version_major = "6")))] diff --git a/crates/cxx-qt-lib/src/quickcontrols/qquickstyle.rs b/crates/cxx-qt-lib/src/quickcontrols/qquickstyle.rs index 7e3f702e5..09582ca6d 100644 --- a/crates/cxx-qt-lib/src/quickcontrols/qquickstyle.rs +++ b/crates/cxx-qt-lib/src/quickcontrols/qquickstyle.rs @@ -51,13 +51,13 @@ impl QQuickStyle { /// /// The fallback style can be also specified by setting the `QT_QUICK_CONTROLS_FALLBACK_STYLE` [environment variable](https://doc.qt.io/qt/qtquickcontrols-environment.html). pub fn set_fallback_style(style: &QString) { - ffi::qquickstyle_set_fallback_style(style) + ffi::qquickstyle_set_fallback_style(style); } /// Sets the application style to `style`. /// /// Note: The style must be configured before loading QML that imports Qt Quick Controls. It is not possible to change the style after the QML types have been registered. pub fn set_style(style: &QString) { - ffi::qquickstyle_set_style(style) + ffi::qquickstyle_set_style(style); } } diff --git a/crates/cxx-qt-macro/src/lib.rs b/crates/cxx-qt-macro/src/lib.rs index 96c1a7517..d58340bd6 100644 --- a/crates/cxx-qt-macro/src/lib.rs +++ b/crates/cxx-qt-macro/src/lib.rs @@ -7,6 +7,7 @@ // We explicitly allow missing docs for the macros in this crate, as they should be documented in // cxx-qt itself. #![allow(missing_docs)] +#![allow(clippy::missing_panics_doc)] //! The cxx-qt-macro crate provides the procedural attribute macros which are used with cxx-qt. //! //! See the [cxx-qt crate docs](https://docs.rs/cxx-qt/latest/) for documentation of the macros diff --git a/crates/cxx-qt/src/casting.rs b/crates/cxx-qt/src/casting.rs index e4ba48f96..45ed6e21e 100644 --- a/crates/cxx-qt/src/casting.rs +++ b/crates/cxx-qt/src/casting.rs @@ -3,7 +3,6 @@ // // SPDX-License-Identifier: MIT OR Apache-2.0 -use std::ops::Deref; use std::pin::Pin; /// This trait is automatically implemented by CXX-Qt and you most likely do not need to manually implement it. @@ -35,29 +34,17 @@ pub unsafe trait Upcast { /// Upcast a reference to self to a reference to the base class fn upcast(&self) -> &T { - let ptr = self as *const Self; - unsafe { - let base = Self::upcast_ptr(ptr); - &*base - } + unsafe { &*Self::upcast_ptr(self) } } /// Upcast a mutable reference to sell to a mutable reference to the base class fn upcast_mut(&mut self) -> &mut T { - let ptr = self as *const Self; - unsafe { - let base = Self::upcast_ptr(ptr) as *mut T; - &mut *base - } + unsafe { &mut *Self::upcast_ptr(self).cast_mut() } } /// Upcast a pinned mutable reference to self to a pinned mutable reference to the base class fn upcast_pin(self: Pin<&mut Self>) -> Pin<&mut T> { - let this = self.deref() as *const Self; - unsafe { - let base = Self::upcast_ptr(this) as *mut T; - Pin::new_unchecked(&mut *base) - } + unsafe { Pin::new_unchecked(Self::upcast_mut(self.get_unchecked_mut())) } } } @@ -67,38 +54,19 @@ pub unsafe trait Upcast { pub trait Downcast: Sized { /// Try to downcast to a subclass of this type, given that the subclass upcasts to this type fn downcast>(&self) -> Option<&Sub> { - unsafe { - let ptr = Sub::from_base_ptr(self as *const Self); - if ptr.is_null() { - None - } else { - Some(&*ptr) - } - } + unsafe { Sub::from_base_ptr(self).as_ref() } } /// Try to downcast mutably to a subclass of this, given that the subclass upcasts to this type fn downcast_mut>(&mut self) -> Option<&mut Sub> { - unsafe { - let ptr = Sub::from_base_ptr(self as *const Self) as *mut Sub; - if ptr.is_null() { - None - } else { - Some(&mut *ptr) - } - } + unsafe { Sub::from_base_ptr(self).cast_mut().as_mut() } } /// Try to downcast a pin to a pinned subclass of this, given that the subclass upcasts to this type fn downcast_pin>(self: Pin<&mut Self>) -> Option> { - let this = self.deref() as *const Self; unsafe { - let ptr = Sub::from_base_ptr(this) as *mut Sub; - if ptr.is_null() { - None - } else { - Some(Pin::new_unchecked(&mut *ptr)) - } + let base = Self::downcast_mut(self.get_unchecked_mut())?; + Some(Pin::new_unchecked(base)) } } } diff --git a/crates/cxx-qt/src/lib.rs b/crates/cxx-qt/src/lib.rs index 41fbe1668..262d29a93 100644 --- a/crates/cxx-qt/src/lib.rs +++ b/crates/cxx-qt/src/lib.rs @@ -2,7 +2,6 @@ // SPDX-FileContributor: Leon Matthes // // SPDX-License-Identifier: MIT OR Apache-2.0 - #![deny(missing_docs)] //! This crate and its associated crates provide a framework for generating QObjects from Rust. diff --git a/crates/cxx-qt/src/threading.rs b/crates/cxx-qt/src/threading.rs index 8f6a49a27..41779f1b8 100644 --- a/crates/cxx-qt/src/threading.rs +++ b/crates/cxx-qt/src/threading.rs @@ -99,6 +99,10 @@ where /// /// The first argument of the closure is a pinned mutable reference to the QObject. /// With this parameter, you can then update the QObject to reflect any state changes that have occured in the background thread. + /// + /// # Errors + /// + /// This function returns an error if the closure cannot be queued. pub fn queue(&self, f: F) -> Result<(), crate::ThreadingQueueError> where F: FnOnce(Pin<&mut T>), diff --git a/crates/qt-build-utils/src/installation/qmake.rs b/crates/qt-build-utils/src/installation/qmake.rs index 0221ad659..d131725fb 100644 --- a/crates/qt-build-utils/src/installation/qmake.rs +++ b/crates/qt-build-utils/src/installation/qmake.rs @@ -228,11 +228,16 @@ impl QtInstallation for QtInstallationQMake { } else { ( format!("Qt{}{qt_module}", self.qmake_version.major), - self.find_qt_module_prl(&lib_path, prefix, self.qmake_version.major, qt_module), + Self::find_qt_module_prl( + &lib_path, + prefix, + self.qmake_version.major, + qt_module, + ), ) }; - self.link_qt_library( + Self::link_qt_library( &format!("Qt{}{qt_module}", self.qmake_version.major), &prefix_path, &lib_path, @@ -245,7 +250,7 @@ impl QtInstallation for QtInstallationQMake { if utils::is_emscripten_target() { let platforms_path = format!("{}/platforms", self.qmake_query("QT_INSTALL_PLUGINS")); println!("cargo::rustc-link-search={platforms_path}"); - self.link_qt_library( + Self::link_qt_library( "qwasm", &prefix_path, &lib_path, @@ -280,7 +285,6 @@ impl QtInstallationQMake { /// Some prl files include their architecture in their naming scheme. /// Just try all known architectures and fallback to non when they all failed. fn find_qt_module_prl( - &self, lib_path: &str, prefix: &str, version_major: u64, @@ -304,7 +308,6 @@ impl QtInstallationQMake { } fn link_qt_library( - &self, name: &str, prefix_path: &str, lib_path: &str, diff --git a/crates/qt-build-utils/src/lib.rs b/crates/qt-build-utils/src/lib.rs index e9026d3be..3eb6bf7a9 100644 --- a/crates/qt-build-utils/src/lib.rs +++ b/crates/qt-build-utils/src/lib.rs @@ -2,7 +2,6 @@ // SPDX-FileContributor: Be Wilson // // SPDX-License-Identifier: MIT OR Apache-2.0 - #![deny(missing_docs)] //! This crate provides information about the Qt installation and can invoke Qt's @@ -12,8 +11,9 @@ //! [cc](https://docs.rs/cc/latest/cc/), //! [cxx_build](https://docs.rs/cxx-build/latest/cxx_build/), or //! [cpp_build](https://docs.rs/cpp_build/latest/cpp_build/). - #![allow(clippy::too_many_arguments)] +#![allow(clippy::missing_panics_doc)] +#![allow(clippy::missing_errors_doc)] mod error; pub use error::QtBuildError; @@ -319,7 +319,7 @@ prefer :/qt/qml/{qml_uri_dirs}/ metatypes_json, qmltypes_path, uri, - Version::new(version_major as u64, version_minor as u64, 0), + &Version::new(version_major as u64, version_minor as u64, 0), ); // Generate QQmlEngineExtensionPlugin @@ -391,10 +391,10 @@ public: file: None, init_call: None, init_declaration: Some(format!( - r#" + r" #include Q_IMPORT_PLUGIN({plugin_class_name}); -"# +" )), }; diff --git a/crates/qt-build-utils/src/parse_cflags.rs b/crates/qt-build-utils/src/parse_cflags.rs index 83b2b21c0..4d4c4a826 100644 --- a/crates/qt-build-utils/src/parse_cflags.rs +++ b/crates/qt-build-utils/src/parse_cflags.rs @@ -148,7 +148,6 @@ pub(crate) fn parse_libs_cflags(name: &str, link_args: &[u8], _builder: &mut cc: "-F" => { println!("cargo::rustc-link-search=framework={val}"); } - "-I" => (), "-l" => { // These are provided by the CRT with MSVC if is_msvc && ["m", "c", "pthread"].contains(&val) { @@ -157,8 +156,7 @@ pub(crate) fn parse_libs_cflags(name: &str, link_args: &[u8], _builder: &mut cc: println!("cargo::rustc-link-lib={val}"); } - "-D" => (), - _ => {} + _ => (), } } @@ -188,6 +186,7 @@ pub(crate) fn parse_libs_cflags(name: &str, link_args: &[u8], _builder: &mut cc: { if is_object_file(path) { #[cfg(feature = "link_qt_object_files")] + #[allow(clippy::used_underscore_binding)] { // Linking will fail with duplicate symbol errors if the same .o file is linked twice. // Many of Qt's .prl files repeat listing .o files that other .prl files also list. diff --git a/crates/qt-build-utils/src/tool/moc.rs b/crates/qt-build-utils/src/tool/moc.rs index fadf6152b..a38ae6dcb 100644 --- a/crates/qt-build-utils/src/tool/moc.rs +++ b/crates/qt-build-utils/src/tool/moc.rs @@ -106,13 +106,12 @@ impl QtToolMoc { .output() .unwrap_or_else(|_| panic!("moc failed for {}", input_path.display())); - if !cmd.status.success() { - panic!( - "moc failed for {}:\n{}", - input_path.display(), - String::from_utf8_lossy(&cmd.stderr) - ); - } + assert!( + cmd.status.success(), + "moc failed for {}:\n{}", + input_path.display(), + String::from_utf8_lossy(&cmd.stderr) + ); MocProducts { cpp: output_path, diff --git a/crates/qt-build-utils/src/tool/qmlcachegen.rs b/crates/qt-build-utils/src/tool/qmlcachegen.rs index b1e6345ea..26e8640c3 100644 --- a/crates/qt-build-utils/src/tool/qmlcachegen.rs +++ b/crates/qt-build-utils/src/tool/qmlcachegen.rs @@ -90,13 +90,12 @@ impl QtToolQmlCacheGen { file.as_ref().display() ) }); - if !cmd.status.success() { - panic!( - "qmlcachegen failed for {} in QML module {uri}:\n{}", - file.as_ref().display(), - String::from_utf8_lossy(&cmd.stderr) - ); - } + assert!( + cmd.status.success(), + "qmlcachegen failed for {} in QML module {uri}:\n{}", + file.as_ref().display(), + String::from_utf8_lossy(&cmd.stderr) + ); QmlCacheProducts { qml_cache_path, @@ -142,12 +141,11 @@ impl QtToolQmlCacheGen { ) .output() .unwrap_or_else(|_| panic!("qmlcachegen failed for QML module {uri}")); - if !cmd.status.success() { - panic!( - "qmlcachegen failed for QML module {uri}:\n{}", - String::from_utf8_lossy(&cmd.stderr) - ); - } + assert!( + cmd.status.success(), + "qmlcachegen failed for QML module {uri}:\n{}", + String::from_utf8_lossy(&cmd.stderr) + ); qmlcachegen_loader } diff --git a/crates/qt-build-utils/src/tool/qmltyperegistrar.rs b/crates/qt-build-utils/src/tool/qmltyperegistrar.rs index 6273b79e4..8d259a948 100644 --- a/crates/qt-build-utils/src/tool/qmltyperegistrar.rs +++ b/crates/qt-build-utils/src/tool/qmltyperegistrar.rs @@ -31,7 +31,7 @@ impl QtToolQmlTypeRegistrar { metatypes_json: &[impl AsRef], qmltypes: impl AsRef, uri: &str, - version: Version, + version: &Version, ) -> Option { // Filter out empty jsons let metatypes_json: Vec<_> = metatypes_json @@ -74,12 +74,11 @@ impl QtToolQmlTypeRegistrar { .args(args) .output() .unwrap_or_else(|_| panic!("qmltyperegistrar failed for {uri}")); - if !cmd.status.success() { - panic!( - "qmltyperegistrar failed for {uri}:\n{}", - String::from_utf8_lossy(&cmd.stderr) - ); - } + assert!( + cmd.status.success(), + "qmltyperegistrar failed for {uri}:\n{}", + String::from_utf8_lossy(&cmd.stderr) + ); Some(qmltyperegistrar_output_path) } diff --git a/crates/qt-build-utils/src/tool/rcc.rs b/crates/qt-build-utils/src/tool/rcc.rs index 868f5faaa..db8cbd6ae 100644 --- a/crates/qt-build-utils/src/tool/rcc.rs +++ b/crates/qt-build-utils/src/tool/rcc.rs @@ -61,13 +61,12 @@ impl QtToolRcc { .output() .unwrap_or_else(|_| panic!("rcc failed for {}", input_path.display())); - if !cmd.status.success() { - panic!( - "rcc failed for {}:\n{}", - input_path.display(), - String::from_utf8_lossy(&cmd.stderr) - ); - } + assert!( + cmd.status.success(), + "rcc failed for {}:\n{}", + input_path.display(), + String::from_utf8_lossy(&cmd.stderr) + ); let qt_6_5 = Version::new(6, 5, 0); let init_header = if self.qt_version >= qt_6_5 { @@ -92,13 +91,12 @@ impl QtToolRcc { .output() .unwrap_or_else(|_| panic!("rcc --list failed for {}", input_path.display())); - if !cmd_list.status.success() { - panic!( - "rcc --list failed for {}:\n{}", - input_path.display(), - String::from_utf8_lossy(&cmd_list.stderr) - ); - } + assert!( + cmd_list.status.success(), + "rcc --list failed for {}:\n{}", + input_path.display(), + String::from_utf8_lossy(&cmd_list.stderr) + ); String::from_utf8_lossy(&cmd_list.stdout) .split('\n')