diff --git a/Cargo.lock b/Cargo.lock index 1b57dbf60195d..16250b24d0baf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -669,7 +669,6 @@ dependencies = [ "clippy_utils", "color-print", "declare_clippy_lint", - "filetime", "itertools", "pulldown-cmark", "regex", @@ -677,8 +676,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "termize", - "toml 0.9.8", + "toml 1.1.0+spec-1.1.0", "ui_test", "walkdir", ] @@ -687,10 +685,10 @@ dependencies = [ name = "clippy_config" version = "0.1.99" dependencies = [ + "arrayvec", "clippy_utils", "itertools", - "serde", - "toml 0.7.8", + "toml 1.1.0+spec-1.1.0", "walkdir", ] @@ -717,15 +715,15 @@ dependencies = [ "clippy_utils", "declare_clippy_lint", "itertools", + "memchr", "quine-mc_cluskey", "regex-syntax", "semver", "serde", - "toml 0.9.8", + "toml 1.1.0+spec-1.1.0", "unicode-normalization", "unicode-script", "url", - "walkdir", ] [[package]] @@ -736,7 +734,6 @@ dependencies = [ "clippy_utils", "itertools", "regex", - "rustc-semver", ] [[package]] @@ -746,7 +743,6 @@ dependencies = [ "arrayvec", "itertools", "rustc_apfloat", - "serde", ] [[package]] @@ -3572,12 +3568,6 @@ dependencies = [ "wasi 0.14.2+wasi-0.2.4", ] -[[package]] -name = "rustc-semver" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be1bdc7edf596692617627bbfeaba522131b18e06ca4df2b6b689e3c5d5ce84" - [[package]] name = "rustc-stable-hash" version = "0.1.2" diff --git a/src/tools/clippy/.github/workflows/clippy_mq.yml b/src/tools/clippy/.github/workflows/clippy_mq.yml index 7d313ece05b80..43cab49d8ece6 100644 --- a/src/tools/clippy/.github/workflows/clippy_mq.yml +++ b/src/tools/clippy/.github/workflows/clippy_mq.yml @@ -131,7 +131,7 @@ jobs: - name: Extract Binaries run: | DIR=$CARGO_TARGET_DIR/debug - find $DIR/deps/integration-* -executable ! -type d | xargs -I {} mv {} $DIR/integration + find $DIR/build/clippy/*/out/integration* -executable ! -type d | xargs -I {} mv {} $DIR/integration find $DIR ! -executable -o -type d ! -path $DIR | xargs rm -rf - name: Upload Binaries diff --git a/src/tools/clippy/CHANGELOG.md b/src/tools/clippy/CHANGELOG.md index b809638dfcf93..3876af9b2f37b 100644 --- a/src/tools/clippy/CHANGELOG.md +++ b/src/tools/clippy/CHANGELOG.md @@ -6,7 +6,120 @@ document. ## Unreleased / Beta / In Rust Nightly -[88f787...master](https://github.com/rust-lang/rust-clippy/compare/88f787...master) +[b147b68...master](https://github.com/rust-lang/rust-clippy/compare/b147b68...master) + +## Rust 1.97 + +Current stable, released 2026-07-09 + +[View all 55 merged pull requests](https://github.com/rust-lang/rust-clippy/pulls?q=merged%3A2026-04-04T13%3A32%3A00Z..2026-05-13T17%3A35%3A43Z+base%3Amaster) + +### New Lints + +* Added [`manual_assert_eq`] to `pedantic` + [#16025](https://github.com/rust-lang/rust-clippy/pull/16025) +* Added [`manual_clear`] to `perf` + [#16617](https://github.com/rust-lang/rust-clippy/pull/16617) +* Added [`useless_borrows_in_formatting`] to `perf` + [#16523](https://github.com/rust-lang/rust-clippy/pull/16523) +* Added [`inline_trait_bounds`] to `restriction` + [#16486](https://github.com/rust-lang/rust-clippy/pull/16486) +* Added [`inline_modules`] to `restriction` + [#16732](https://github.com/rust-lang/rust-clippy/pull/16732) + +### Moves and Deprecations + +* Moved [`nonminimal_bool`] from `complexity` to `pedantic` + [#16761](https://github.com/rust-lang/rust-clippy/pull/16761) +* Moved [`overly_complex_bool_expr`] from `correctness` to `pedantic` + [#16761](https://github.com/rust-lang/rust-clippy/pull/16761) + +### Enhancements + +* [`unused_format_specs`] detect format width below the minimum output size for `#x`/`#o`/`#b`, + exponent, and pointer formats + [#16542](https://github.com/rust-lang/rust-clippy/pull/16542) +* [`zst_offset`] detect zero-sized `NonNull` offset calculations + [#16888](https://github.com/rust-lang/rust-clippy/pull/16888) +* [`byte_char_slices`] enhance to cover arrays + [#16770](https://github.com/rust-lang/rust-clippy/pull/16770) +* [`manual_filter`] enhance to cover `and_then` + [#16456](https://github.com/rust-lang/rust-clippy/pull/16456) +* [`unneeded_wildcard_pattern`] add support for struct constructs + [#16733](https://github.com/rust-lang/rust-clippy/pull/16733) +* [`needless_late_init`] enhance to cover grouped assignments + [#16746](https://github.com/rust-lang/rust-clippy/pull/16746) +* [`needless_return_with_question_mark`] fix FN in async function bodies + [#16952](https://github.com/rust-lang/rust-clippy/pull/16952) +* [`needless_ifs`] fix FN when code contains a vertical tab (`\x0B`) whitespace + [#16845](https://github.com/rust-lang/rust-clippy/pull/16845) +* [`cloned_ref_to_slice_refs`] fix FN on `to_owned()` + [#16329](https://github.com/rust-lang/rust-clippy/pull/16329) +* [`for_kv_map`] fix FN when using `iter` and `iter_mut` + [#16830](https://github.com/rust-lang/rust-clippy/pull/16830) +* [`question_mark`] fix FN for manual unwrap with `if let` or `match`, when the scrutinee is behind + a reference, and when the binding is behind `ref` or `mut` + [#16769](https://github.com/rust-lang/rust-clippy/pull/16769) +* [`question_mark`] fix wrong suggestion when the match arm body is a destructuring assignment + [#16863](https://github.com/rust-lang/rust-clippy/pull/16863) +* [`expect_fun_call`] fix wrong suggestions for string slicing + [#16752](https://github.com/rust-lang/rust-clippy/pull/16752) +* [`println_empty_string`] fix wrong suggestion with non-parenthesis delimiters + [#16846](https://github.com/rust-lang/rust-clippy/pull/16846) +* [`int_plus_one`] parenthesize an `as` cast in the suggestion when the replacement operator is `<` + to avoid a parse error + [#16848](https://github.com/rust-lang/rust-clippy/pull/16848) +* [`bad_bit_mask`] truncate the constant to the target type before warning about impossible equality + [#16782](https://github.com/rust-lang/rust-clippy/pull/16782) +* [`manual_rotate`], [`map_with_unused_argument_over_ranges`], [`needless_bool`], + [`manual_is_power_of_two`], [`manual_div_ceil`], [`implicit_saturating_sub`], [`range_minus_one`], + [`range_plus_one`], [`manual_swap`], [`let_and_return`] fix wrongly unmangled macros + [#16443](https://github.com/rust-lang/rust-clippy/pull/16443) +* [`manual_noop_waker`] add an MSRV check + [#16850](https://github.com/rust-lang/rust-clippy/pull/16850) + +### False Positive Fixes + +* [`manual_option_zip`] fix FP when the outer param is used in a closure + [#16970](https://github.com/rust-lang/rust-clippy/pull/16970) +* [`non_canonical_clone_impl`] fix incompatibility with [`implicit_return`] + [#16949](https://github.com/rust-lang/rust-clippy/pull/16949) +* [`from_over_into`] don't lint when a blanket `From` impl would cause a coherence conflict + [#16881](https://github.com/rust-lang/rust-clippy/pull/16881) +* [`collapsible_match`] no longer suggests collapsing `pattern => { if test { body } }` into a match + guard when non-wildcard arms follow, as this changes the semantics of the match + [#16878](https://github.com/rust-lang/rust-clippy/pull/16878) +* [`unused_async`] fix FP for stubs with args + [#16832](https://github.com/rust-lang/rust-clippy/pull/16832) +* [`useless_conversion`] do not lint on `(a..b).into_iter()`, for compatibility with future range + syntax changes + [#16891](https://github.com/rust-lang/rust-clippy/pull/16891) +* [`bind_instead_of_map`] do not propose a rewrite when the only way to leave the closure is through + a divergent statement other than `return` + [#16867](https://github.com/rust-lang/rust-clippy/pull/16867) +* [`let_and_return`] do not trigger on the `let else` construct + [#16829](https://github.com/rust-lang/rust-clippy/pull/16829) +* [`fn_to_numeric_cast_any`] fix FP on a cast to a raw pointer + [#14109](https://github.com/rust-lang/rust-clippy/pull/14109) +* [`unnecessary_cast`] no longer suggests removing a cast that can cause a compilation error + [#16796](https://github.com/rust-lang/rust-clippy/pull/16796) +* [`unsafe_removed_from_name`] skip linting when renaming to `_` + [#16802](https://github.com/rust-lang/rust-clippy/pull/16802) + +### ICE Fixes + +* [`bad_bit_mask`] fix ICE for overloaded bit ops + [#16937](https://github.com/rust-lang/rust-clippy/pull/16937) + +### Performance Improvements + +* Fold all late lint passes into one statically-combined pass + [#17124](https://github.com/rust-lang/rust-clippy/pull/17124) + +### New Lints + +* Added [`assert_is_empty`] to `pedantic` + [#17114](https://github.com/rust-lang/rust-clippy/issues/17114) ## Rust 1.96 @@ -6639,6 +6752,7 @@ Released 2018-09-13 [`as_pointer_underscore`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_pointer_underscore [`as_ptr_cast_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_ptr_cast_mut [`as_underscore`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_underscore +[`assert_is_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#assert_is_empty [`assertions_on_constants`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants [`assertions_on_result_states`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_result_states [`assign_op_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#assign_op_pattern @@ -6655,6 +6769,7 @@ Released 2018-09-13 [`blanket_clippy_restriction_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#blanket_clippy_restriction_lints [`block_in_if_condition_expr`]: https://rust-lang.github.io/rust-clippy/master/index.html#block_in_if_condition_expr [`block_in_if_condition_stmt`]: https://rust-lang.github.io/rust-clippy/master/index.html#block_in_if_condition_stmt +[`block_scrutinee`]: https://rust-lang.github.io/rust-clippy/master/index.html#block_scrutinee [`blocks_in_conditions`]: https://rust-lang.github.io/rust-clippy/master/index.html#blocks_in_conditions [`blocks_in_if_conditions`]: https://rust-lang.github.io/rust-clippy/master/index.html#blocks_in_if_conditions [`bool_assert_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_assert_comparison @@ -6732,6 +6847,7 @@ Released 2018-09-13 [`default_numeric_fallback`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback [`default_trait_access`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_trait_access [`default_union_representation`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_union_representation +[`definition_in_module_root`]: https://rust-lang.github.io/rust-clippy/master/index.html#definition_in_module_root [`deprecated_cfg_attr`]: https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_cfg_attr [`deprecated_clippy_cfg_attr`]: https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_clippy_cfg_attr [`deprecated_semver`]: https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_semver @@ -7170,6 +7286,7 @@ Released 2018-09-13 [`non_std_lazy_statics`]: https://rust-lang.github.io/rust-clippy/master/index.html#non_std_lazy_statics [`non_zero_suggestions`]: https://rust-lang.github.io/rust-clippy/master/index.html#non_zero_suggestions [`nonminimal_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonminimal_bool +[`nonnull_unchecked_on_box_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonnull_unchecked_on_box_ptr [`nonsensical_open_options`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonsensical_open_options [`nonstandard_macro_braces`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonstandard_macro_braces [`not_unsafe_ptr_arg_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#not_unsafe_ptr_arg_deref @@ -7286,6 +7403,7 @@ Released 2018-09-13 [`repr_packed_without_abi`]: https://rust-lang.github.io/rust-clippy/master/index.html#repr_packed_without_abi [`reserve_after_initialization`]: https://rust-lang.github.io/rust-clippy/master/index.html#reserve_after_initialization [`rest_pat_in_fully_bound_structs`]: https://rust-lang.github.io/rust-clippy/master/index.html#rest_pat_in_fully_bound_structs +[`rest_pattern_accessible_field`]: https://rust-lang.github.io/rust-clippy/master/index.html#rest_pattern_accessible_field [`result_expect_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_expect_used [`result_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_filter_map [`result_large_err`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_large_err @@ -7451,6 +7569,7 @@ Released 2018-09-13 [`unnecessary_operation`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation [`unnecessary_option_map_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_option_map_or_else [`unnecessary_owned_empty_strings`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_owned_empty_strings +[`unnecessary_rest_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_rest_pattern [`unnecessary_result_map_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_result_map_or_else [`unnecessary_safety_comment`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_safety_comment [`unnecessary_safety_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_safety_doc @@ -7607,6 +7726,7 @@ Released 2018-09-13 [`max-struct-bools`]: https://doc.rust-lang.org/clippy/lint_configuration.html#max-struct-bools [`max-suggested-slice-pattern-length`]: https://doc.rust-lang.org/clippy/lint_configuration.html#max-suggested-slice-pattern-length [`max-trait-bounds`]: https://doc.rust-lang.org/clippy/lint_configuration.html#max-trait-bounds +[`min-ident-chars-lint-trait-impl`]: https://doc.rust-lang.org/clippy/lint_configuration.html#min-ident-chars-lint-trait-impl [`min-ident-chars-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#min-ident-chars-threshold [`missing-docs-allow-unused`]: https://doc.rust-lang.org/clippy/lint_configuration.html#missing-docs-allow-unused [`missing-docs-in-crate-items`]: https://doc.rust-lang.org/clippy/lint_configuration.html#missing-docs-in-crate-items @@ -7628,6 +7748,7 @@ Released 2018-09-13 [`too-many-arguments-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#too-many-arguments-threshold [`too-many-lines-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#too-many-lines-threshold [`trait-assoc-item-kinds-order`]: https://doc.rust-lang.org/clippy/lint_configuration.html#trait-assoc-item-kinds-order +[`trait-impl-item-order`]: https://doc.rust-lang.org/clippy/lint_configuration.html#trait-impl-item-order [`trivial-copy-size-limit`]: https://doc.rust-lang.org/clippy/lint_configuration.html#trivial-copy-size-limit [`type-complexity-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#type-complexity-threshold [`unnecessary-box-size`]: https://doc.rust-lang.org/clippy/lint_configuration.html#unnecessary-box-size diff --git a/src/tools/clippy/Cargo.toml b/src/tools/clippy/Cargo.toml index e687da25a8f78..fe9a2e3b7ad58 100644 --- a/src/tools/clippy/Cargo.toml +++ b/src/tools/clippy/Cargo.toml @@ -28,7 +28,6 @@ declare_clippy_lint = { path = "declare_clippy_lint" } rustc_tools_util = { path = "rustc_tools_util", version = "0.4.2" } clippy_lints_internal = { path = "clippy_lints_internal", optional = true } tempfile = { version = "3.20", optional = true } -termize = "0.2" color-print = "0.3.4" anstream = "0.6.18" @@ -39,13 +38,12 @@ regex = "1.5.5" serde = { version = "1.0.145", features = ["derive"] } serde_json = "1.0.122" walkdir = "2.3" -filetime = "0.2.9" itertools = "0.15" pulldown-cmark = { version = "0.11", default-features = false, features = ["html"] } askama = { version = "0.16.0", default-features = false, features = ["alloc", "config", "derive"] } [dev-dependencies.toml] -version = "0.9.7" +version = "1.1" default-features = false # preserve_order keeps diagnostic output in file order features = ["parse", "preserve_order"] diff --git a/src/tools/clippy/README.md b/src/tools/clippy/README.md index 8bccd040c1f94..21a230318798b 100644 --- a/src/tools/clippy/README.md +++ b/src/tools/clippy/README.md @@ -140,18 +140,27 @@ before_script: script: - cargo clippy # if you want the build job to fail when encountering warnings, use - - cargo clippy -- -D warnings + - CARGO_BUILD_WARNINGS=deny cargo clippy # in order to also check tests and non-default crate features, use - - cargo clippy --all-targets --all-features -- -D warnings + - CARGO_BUILD_WARNINGS=deny cargo clippy --all-targets --all-features - cargo test # etc. ``` -Note that adding `-D warnings` will cause your build to fail if **any** warnings are found in your code. +Note that setting `CARGO_BUILD_WARNINGS=deny` will cause your build to fail if **any** warnings are found in your code. That includes warnings found by rustc (e.g. `dead_code`, etc.). If you want to avoid this and only cause an error for Clippy warnings, use `#![deny(clippy::all)]` in your code or `-D clippy::all` on the command line. (You can swap `clippy::all` with the specific lint category you are targeting.) +Also note that before Cargo 1.97, the usual way to deny all warnings was by using `-D warnings`: + +```shell +cargo clippy -- -D warnings +``` + +However, [`CARGO_BUILD_WARNINGS`] has the benefit of not invalidating build caches, +and is thus to be preferred going forward. + ## Configuration ### Allowing/denying lints @@ -286,3 +295,5 @@ option. Files in the project may not be copied, modified, or distributed except according to those terms. + +[`CARGO_BUILD_WARNINGS`]: https://doc.rust-lang.org/cargo/reference/config.html#buildwarnings diff --git a/src/tools/clippy/book/src/development/adding_lints.md b/src/tools/clippy/book/src/development/adding_lints.md index f28985d375f64..ef224e230d7c9 100644 --- a/src/tools/clippy/book/src/development/adding_lints.md +++ b/src/tools/clippy/book/src/development/adding_lints.md @@ -471,7 +471,7 @@ pub struct ManualStrip { impl ManualStrip { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } ``` @@ -526,7 +526,7 @@ define_Conf! { } ``` -[`clippy_utils::msrvs`]: https://doc.rust-lang.org/nightly/nightly-rustc/clippy_config/msrvs/index.html +[`clippy_utils::msrvs`]: https://doc.rust-lang.org/nightly/nightly-rustc/clippy_utils/msrvs/index.html Afterwards update the documentation for the book as described in [Adding configuration to a lint](#adding-configuration-to-a-lint). diff --git a/src/tools/clippy/book/src/lint_configuration.md b/src/tools/clippy/book/src/lint_configuration.md index b3bef3b4666dc..6869cc56ed956 100644 --- a/src/tools/clippy/book/src/lint_configuration.md +++ b/src/tools/clippy/book/src/lint_configuration.md @@ -863,6 +863,16 @@ The maximum number of bounds a trait can have to be linted * [`type_repetition_in_bounds`](https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds) +## `min-ident-chars-lint-trait-impl` +Whether to lint idents that have too few chars even when following trait declaration. + +**Default Value:** `false` + +--- +**Affected lints:** +* [`min_ident_chars`](https://rust-lang.github.io/rust-clippy/master/index.html#min_ident_chars) + + ## `min-ident-chars-threshold` Minimum chars an ident can have, anything below or equal to this will be linted. @@ -941,6 +951,7 @@ The minimum rust version that the project supports. Defaults to the `rust-versio * [`filter_map_next`](https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_next) * [`from_over_into`](https://rust-lang.github.io/rust-clippy/master/index.html#from_over_into) * [`if_then_some_else_none`](https://rust-lang.github.io/rust-clippy/master/index.html#if_then_some_else_none) +* [`implicit_saturating_sub`](https://rust-lang.github.io/rust-clippy/master/index.html#implicit_saturating_sub) * [`index_refutable_slice`](https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice) * [`inefficient_to_string`](https://rust-lang.github.io/rust-clippy/master/index.html#inefficient_to_string) * [`io_other_error`](https://rust-lang.github.io/rust-clippy/master/index.html#io_other_error) @@ -985,6 +996,7 @@ The minimum rust version that the project supports. Defaults to the `rust-versio * [`missing_const_for_fn`](https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn) * [`needless_borrow`](https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow) * [`non_std_lazy_statics`](https://rust-lang.github.io/rust-clippy/master/index.html#non_std_lazy_statics) +* [`nonnull_unchecked_on_box_ptr`](https://rust-lang.github.io/rust-clippy/master/index.html#nonnull_unchecked_on_box_ptr) * [`option_as_ref_deref`](https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref) * [`or_fun_call`](https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call) * [`ptr_as_ptr`](https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr) @@ -1168,6 +1180,30 @@ The order of associated items in traits. * [`arbitrary_source_item_ordering`](https://rust-lang.github.io/rust-clippy/master/index.html#arbitrary_source_item_ordering) +## `trait-impl-item-order` +The required ordering of associated items in trait impls: purely alphabetical, +following the trait definition order, or accepting either. + +Note that the trait definition order may change between versions of the +crate defining the trait without being considered a breaking change. + +Examples: +When using trait definition item ordering: +```toml +trait-impl-item-order = "trait_item_ordering" +``` +When using trait definition item ordering and alphabetical for fallbacks: +```toml +trait-impl-item-order = "alphabetical_or_trait_item_ordering" +``` + +**Default Value:** `"alphabetical"` + +--- +**Affected lints:** +* [`arbitrary_source_item_ordering`](https://rust-lang.github.io/rust-clippy/master/index.html#arbitrary_source_item_ordering) + + ## `trivial-copy-size-limit` The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference. diff --git a/src/tools/clippy/book/src/usage.md b/src/tools/clippy/book/src/usage.md index 23edf6c2abaaf..a7e07e9e92d68 100644 --- a/src/tools/clippy/book/src/usage.md +++ b/src/tools/clippy/book/src/usage.md @@ -36,16 +36,40 @@ You can configure lint levels on the command line by adding cargo clippy -- -Aclippy::style -Wclippy::box_default -Dclippy::perf ``` +#### Elevating warning to errors + For [CI] all warnings can be elevated to errors which will in turn fail the build and cause Clippy to exit with a code other than `0`. +Since Cargo 1.97, the recommended way to do this is by using the [`build.warnings`] config option. + +It can be enabled on the command line using the environment variable: + +```bash +CARGO_BUILD_WARNINGS=deny cargo clippy ``` -cargo clippy -- -Dwarnings + +.. or permanently, in `.cargo/config.toml`: + +```toml +# .cargo/config.toml +[build] +warnings = "deny" ``` -> _Note:_ Adding `-D warnings` will cause your build to fail if **any** warnings +> _Note:_ Using `CARGO_BUILD_WARNINGS=deny` (or `-D warnings`) will cause your build to fail if **any** warnings > are found in your code. That includes warnings found by rustc (e.g. -> `dead_code`, etc.). +> `dead_code`, etc.) + +If you use an older version of Cargo, you can use the following instead: + +```bash +cargo clippy -- -Dwarnings +``` + +Note, however, that this will invalidate build caches and is therefore not recommended. + +[`build.warnings`]: https://doc.rust-lang.org/cargo/reference/config.html#buildwarnings For more information on configuring lint levels, see the [rustc documentation]. diff --git a/src/tools/clippy/clippy_config/Cargo.toml b/src/tools/clippy/clippy_config/Cargo.toml index 0007cece5de96..d81431d58434f 100644 --- a/src/tools/clippy/clippy_config/Cargo.toml +++ b/src/tools/clippy/clippy_config/Cargo.toml @@ -7,10 +7,15 @@ publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +arrayvec = { version = "0.7", default-features = false } clippy_utils = { path = "../clippy_utils" } itertools = "0.15" -serde = { version = "1.0", features = ["derive"] } -toml = "0.7.3" + +[dependencies.toml] +version = "1.1" +default-features = false +# preserve_order keeps diagnostic output in file order +features = ["parse", "preserve_order"] [dev-dependencies] walkdir = "2.3" diff --git a/src/tools/clippy/clippy_config/src/conf.rs b/src/tools/clippy/clippy_config/src/conf.rs index 5dfb934b90ce7..13c73e9445818 100644 --- a/src/tools/clippy/clippy_config/src/conf.rs +++ b/src/tools/clippy/clippy_config/src/conf.rs @@ -1,28 +1,23 @@ -use crate::ClippyConfiguration; +use crate::ConfMetadata; +use crate::de::{DeserializeOrDefault, DiagCtxt, FromDefault, create_value_list_msg, find_closest_match}; use crate::types::{ DisallowedPath, DisallowedPathWithoutReplacement, InherentImplLintScope, MacroMatcher, MatchLintBehaviour, - PubUnderscoreFieldsBehaviour, Rename, SourceItemOrdering, SourceItemOrderingCategory, - SourceItemOrderingModuleItemGroupings, SourceItemOrderingModuleItemKind, SourceItemOrderingTraitAssocItemKind, - SourceItemOrderingTraitAssocItemKinds, SourceItemOrderingWithinModuleItemGroupings, + PubUnderscoreFieldsBehaviour, Rename, SourceItemOrdering, SourceItemOrderingModuleItemGroupings, + SourceItemOrderingTraitAssocItemKinds, SourceItemOrderingWithinModuleItemGroupings, TraitImplItemOrder, }; -use clippy_utils::msrvs::Msrv; -use itertools::Itertools; +use rustc_attr_parsing::parse_version; +use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; +use rustc_hir::attrs::RustcVersion; use rustc_session::Session; -use rustc_span::edit_distance::edit_distance; -use rustc_span::{BytePos, Pos, SourceFile, Span, SyntaxContext}; -use serde::de::{IgnoredAny, IntoDeserializer, MapAccess, Visitor}; -use serde::{Deserialize, Deserializer, Serialize}; -use std::collections::HashMap; -use std::fmt::{Debug, Display, Formatter}; -use std::ops::Range; +use rustc_span::{Pos as _, SourceFile, Symbol}; use std::path::PathBuf; -use std::str::FromStr; -use std::sync::OnceLock; -use std::{cmp, env, fmt, fs, io}; +use std::sync::{Arc, OnceLock}; +use std::{env, fs, io}; +use toml::de::DeTable; #[rustfmt::skip] -const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[ +static DEFAULT_DOC_VALID_IDENTS: &[&str] = &[ "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "MHz", "GHz", "THz", "AccessKit", @@ -51,347 +46,228 @@ const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[ "MinGW", "CamelCase", ]; -const DEFAULT_DISALLOWED_NAMES: &[&str] = &["foo", "baz", "quux"]; -const DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS: &[&str] = &["i", "j", "x", "y", "z", "w", "n"]; -const DEFAULT_ALLOWED_PREFIXES: &[&str] = &["to", "as", "into", "from", "try_into", "try_from"]; -const DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS: &[&str] = +static DEFAULT_DISALLOWED_NAMES: &[&str] = &["foo", "baz", "quux"]; +static DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS: &[&str] = &["i", "j", "x", "y", "z", "w", "n"]; +static DEFAULT_ALLOWED_PREFIXES: &[&str] = &["to", "as", "into", "from", "try_into", "try_from"]; +static DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS: &[&str] = &["core::convert::From", "core::convert::TryFrom", "core::str::FromStr"]; -const DEFAULT_MODULE_ITEM_ORDERING_GROUPS: &[(&str, &[SourceItemOrderingModuleItemKind])] = { - #[allow(clippy::enum_glob_use)] // Very local glob use for legibility. - use SourceItemOrderingModuleItemKind::*; - &[ - ("modules", &[ExternCrate, Mod, ForeignMod]), - ("use", &[Use]), - ("macros", &[Macro]), - ("global_asm", &[GlobalAsm]), - ("UPPER_SNAKE_CASE", &[Static, Const]), - ("PascalCase", &[TyAlias, Enum, Struct, Union, Trait, TraitAlias, Impl]), - ("lower_snake_case", &[Fn]), - ] -}; -const DEFAULT_TRAIT_ASSOC_ITEM_KINDS_ORDER: &[SourceItemOrderingTraitAssocItemKind] = { - #[allow(clippy::enum_glob_use)] // Very local glob use for legibility. - use SourceItemOrderingTraitAssocItemKind::*; - &[Const, Type, Fn] -}; -const DEFAULT_SOURCE_ITEM_ORDERING: &[SourceItemOrderingCategory] = { - #[allow(clippy::enum_glob_use)] // Very local glob use for legibility. - use SourceItemOrderingCategory::*; - &[Enum, Impl, Module, Struct, Trait] -}; -/// Conf with parse errors -#[derive(Default)] -struct TryConf { - conf: Conf, - value_spans: HashMap>, - errors: Vec, - warnings: Vec, -} +static DEFAULT_ALLOWED_SCRIPTS: &[&str] = &["Latin"]; +static DEFAULT_IGNORE_INTERIOR_MUTABILITY: &[&str] = &["bytes::Bytes"]; -impl TryConf { - fn from_toml_error(file: &SourceFile, error: &toml::de::Error) -> Self { - Self { - conf: Conf::default(), - value_spans: HashMap::default(), - errors: vec![ConfError::from_toml(file, error)], - warnings: vec![], - } - } +macro_rules! first_expr { + ($e:expr $(,$_e:expr)*) => { + $e + }; } -#[derive(Debug)] -struct ConfError { - message: String, - suggestion: Option, - span: Span, +macro_rules! filtered_names { + (($($names:literal)*)) => { &[$($names),*] }; + (($($names:literal)*) $name:literal $($rest:tt)*) => { + filtered_names!(($($names)* $name) $($rest)*) + }; + (($($names:literal)*) $new_name:ident $name:literal $($rest:tt)*) => { + filtered_names!(($($names)*) $($rest)*) + }; } -impl ConfError { - fn from_toml(file: &SourceFile, error: &toml::de::Error) -> Self { - let span = error.span().unwrap_or(0..file.normalized_source_len.0 as usize); - Self::spanned(file, error.message(), None, span) - } - - fn spanned( - file: &SourceFile, - message: impl Into, - suggestion: Option, - span: Range, - ) -> Self { - Self { - message: message.into(), - suggestion, - span: span_from_toml_range(file, span), +macro_rules! define_Conf { + ( + $( + $(#[doc = $doc:literal])* + $(#[default_text = $default_text:literal])? + $(#[rename = $new_name:ident])? + $(#[lints($($for_lints:ident),* $(,)?)])? + // The type must exist for regular fields and shouldn't exist for deprecated ones. + $name:ident($name_str:literal) $(: $ty:ty $(= $default:expr)?)?, + )* + ) => { + #[allow(non_camel_case_types)] + #[derive(Clone, Copy)] + enum ConfField { + $($name,)* + ThirdParty, } - } -} - -// Remove code tags and code behind '# 's, as they are not needed for the lint docs and --explain -pub fn sanitize_explanation(raw_docs: &str) -> String { - // Remove tags and hidden code: - let mut explanation = String::with_capacity(128); - let mut in_code = false; - for line in raw_docs.lines() { - let line = line.strip_prefix(' ').unwrap_or(line); + impl ConfField { + const NAMES: &'static [&'static str] = &[$($name_str,)* "third-party"]; + const FIELDS: &'static [Self] = &[$(first_expr!($(Self::$new_name,)? Self::$name),)* Self::ThirdParty]; + const SUGG_NAMES: &'static [&'static str] = filtered_names!(() $($($new_name)? $name_str)* "third-party"); - if let Some(lang) = line.strip_prefix("```") { - let tag = lang.split_once(',').map_or(lang, |(left, _)| left); - if !in_code && matches!(tag, "" | "rust" | "ignore" | "should_panic" | "no_run" | "compile_fail") { - explanation += "```rust\n"; - } else { - explanation += line; - explanation.push('\n'); + fn name(self) -> &'static str { + Self::NAMES[self as usize] } - in_code = !in_code; - } else if !(in_code && line.starts_with("# ")) { - explanation += line; - explanation.push('\n'); - } - } - - explanation -} - -macro_rules! wrap_option { - () => { - None - }; - ($x:literal) => { - Some($x) - }; -} -macro_rules! default_text { - ($value:expr) => {{ - let mut text = String::new(); - $value.serialize(toml::ser::ValueSerializer::new(&mut text)).unwrap(); - text - }}; - ($value:expr, $override:expr) => { - $override.to_string() - }; -} - -macro_rules! deserialize { - ($map:expr, $ty:ty, $errors:expr, $file:expr) => {{ - let raw_value = $map.next_value::>()?; - let value_span = raw_value.span(); - let value = match <$ty>::deserialize(raw_value.into_inner()) { - Err(e) => { - $errors.push(ConfError::spanned( - $file, - e.to_string().replace('\n', " ").trim(), - None, - value_span, - )); - continue; - }, - Ok(value) => value, - }; - (value, value_span) - }}; + fn new_field(self) -> Self { + Self::FIELDS[self as usize] + } - ($map:expr, $ty:ty, $errors:expr, $file:expr, $replacements_allowed:expr) => {{ - let array = $map.next_value::>>()?; - let mut disallowed_paths_span = Range { - start: usize::MAX, - end: usize::MIN, - }; - let mut disallowed_paths = Vec::new(); - for raw_value in array { - let value_span = raw_value.span(); - let mut disallowed_path = match DisallowedPath::<$replacements_allowed>::deserialize(raw_value.into_inner()) - { - Err(e) => { - $errors.push(ConfError::spanned( - $file, - e.to_string().replace('\n', " ").trim(), - None, - value_span, - )); - continue; - }, - Ok(disallowed_path) => disallowed_path, - }; - disallowed_paths_span = union(&disallowed_paths_span, &value_span); - disallowed_path.set_span(span_from_toml_range($file, value_span)); - disallowed_paths.push(disallowed_path); + fn parse(s: &str) -> Option { + match s { + $($name_str => Some(Self::$name),)* + "third-party" => Some(Self::ThirdParty), + _ => None, + } + } } - (disallowed_paths, disallowed_paths_span) - }}; -} -macro_rules! define_Conf { - ($( - $(#[doc = $doc:literal])+ - $(#[conf_deprecated($dep:literal, $new_conf:ident)])? - $(#[default_text = $default_text:expr])? - $(#[disallowed_paths_allow_replacements = $replacements_allowed:expr])? - $(#[lints($($for_lints:ident),* $(,)?)])? - $name:ident: $ty:ty = $default:expr, - )*) => { /// Clippy lint configuration pub struct Conf { - $($(#[cfg_attr(doc, doc = $doc)])+ pub $name: $ty,)* - } - - mod defaults { - use super::*; - $(pub fn $name() -> $ty { $default })* + // TODO: emit documentation + $($(pub $name: $ty,)?)* } impl Default for Conf { fn default() -> Self { - Self { $($name: defaults::$name(),)* } + Self { + $($($name: <$ty as FromDefault<_>>::from_default(first_expr!($($default,)? ())),)?)* + } } } - #[derive(Deserialize)] - #[serde(field_identifier, rename_all = "kebab-case")] - #[expect(non_camel_case_types)] - enum Field { $($name,)* third_party, } - - struct ConfVisitor<'a>(&'a SourceFile); - - impl<'de> Visitor<'de> for ConfVisitor<'_> { - type Value = TryConf; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("Conf") + impl Conf { + pub fn get_metadata() -> Vec { + vec![$( + ConfMetadata { + name: $name_str, + default: first_expr!( + $($default_text.into(),)? + $(<$ty as FromDefault<_>>::display_default(first_expr!($($default,)? ())).to_string(),)? + String::new() + ), + lints: &[$($(stringify!($for_lints)),*)?], + doc: concat!($($doc, '\n',)*), + renamed_to: first_expr!($(Some(ConfField::$new_name.name()),)? None), + }, + )*] } - fn visit_map(self, mut map: V) -> Result where V: MapAccess<'de> { - let mut value_spans = HashMap::new(); - let mut errors = Vec::new(); - let mut warnings = Vec::new(); - - // Declare a local variable for each field available to a configuration file. - $(let mut $name = None;)* + fn deserialize(dcx: &DiagCtxt<'_>, table: &toml::de::DeTable<'_>) -> Self { + $($(let mut $name: Option<$ty> = None;)?)* - // could get `Field` here directly, but get `String` first for diagnostics - while let Some(name) = map.next_key::>()? { - let field = match Field::deserialize(name.get_ref().as_str().into_deserializer()) { - Err(e) => { - let e: FieldError = e; - errors.push(ConfError::spanned(self.0, e.error, e.suggestion, name.span())); - continue; + for (key, value) in table.iter() { + let Some(mut conf_key) = ConfField::parse(key.get_ref()) else { + let sp = dcx.make_sp(key.span()); + let mut diag = dcx.inner.struct_span_err(sp, "unknown field name"); + if let Some(sugg) = find_closest_match(key.get_ref(), ConfField::SUGG_NAMES) { + diag.span_suggestion(sp, "did you mean", sugg, Applicability::MaybeIncorrect); } - Ok(field) => field + diag.note_once(create_value_list_msg(dcx, ConfField::SUGG_NAMES)); + diag.emit(); + continue; }; - - match field { - $(Field::$name => { - // Is this a deprecated field, i.e., is `$dep` set? If so, push a warning. - $(warnings.push(ConfError::spanned(self.0, format!("deprecated field `{}`. {}", name.get_ref(), $dep), None, name.span()));)? - let (value, value_span) = - deserialize!(map, $ty, errors, self.0 $(, $replacements_allowed)?); - // Was this field set previously? - if $name.is_some() { - errors.push(ConfError::spanned(self.0, format!("duplicate field `{}`", name.get_ref()), None, name.span())); - continue; - } - $name = Some(value); - value_spans.insert(name.get_ref().as_str().to_string(), value_span); - // If this is a deprecated field, was the new field (`$new_conf`) set previously? - // Note that `$new_conf` is one of the defined `$name`s. - $(match $new_conf { - Some(_) => errors.push(ConfError::spanned(self.0, concat!( - "duplicate field `", stringify!($new_conf), - "` (provided as `", stringify!($name), "`)" - ), None, name.span())), - None => $new_conf = $name.clone(), - })? - })* - // ignore contents of the third_party key - Field::third_party => drop(map.next_value::()) + loop { + match conf_key { + $($(ConfField::$name => { + // Duplicate keys are handled by the toml parser. + $name = Some( + <$ty as DeserializeOrDefault<_>>::deserialize_or_default( + dcx, + value.into(), + first_expr!($($default,)? ()), + ), + ); + },)?)* + ConfField::ThirdParty => {}, + // All deprecated fields. + _ => { + let sp = dcx.make_sp(table.get_key_value(key).unwrap().0.span()); + conf_key = conf_key.new_field(); + let other_value = table.get_key_value(conf_key.name()); + dcx.inner.struct_span_warn(sp, format!("use of a deprecated field")) + .with_span_suggestion( + sp, "use new name", conf_key.name(), + if other_value.is_some() { + Applicability::MaybeIncorrect + } else { + Applicability::MachineApplicable + } + ).emit(); + + if let Some((other_key, _)) = other_value { + dcx.inner.struct_span_err(sp, format!("duplicate key in document root")) + .with_span_note(dcx.make_sp(other_key.span()), "previous definition here") + .emit(); + } else { + continue; + } + }, + } + break; } } - let conf = Conf { $($name: $name.unwrap_or_else(defaults::$name),)* }; - Ok(TryConf { conf, value_spans, errors, warnings }) + + Self {$($( + $name: $name.unwrap_or_else( + || <$ty as FromDefault<_>>::from_default(first_expr!($($default,)? ())) + ), + )?)*} } } - pub fn get_configuration_metadata() -> Vec { - vec![$( - ClippyConfiguration { - name: stringify!($name).replace('_', "-"), - default: default_text!(defaults::$name() $(, $default_text)?), - lints: &[$($(stringify!($for_lints)),*)?], - doc: concat!($($doc, '\n',)*), - deprecation_reason: wrap_option!($($dep)?) - }, - )*] + #[test] + fn check_conf_order() { + for [x, y] in ConfField::NAMES[..ConfField::NAMES.len() - 1].array_windows::<2>() { + assert!(x <= y, "configuration `{x}` and `{y}` are out of order"); + } } - }; -} - -fn union(x: &Range, y: &Range) -> Range { - Range { - start: cmp::min(x.start, y.start), - end: cmp::max(x.end, y.end), - } -} -fn span_from_toml_range(file: &SourceFile, span: Range) -> Span { - Span::new( - file.start_pos + BytePos::from_usize(span.start), - file.start_pos + BytePos::from_usize(span.end), - SyntaxContext::root(), - None, - ) + #[test] + fn check_conf_names() {$( + assert_eq!(stringify!($name).replace('_', "-"), $name_str); + )*} + }; } define_Conf! { /// Which crates to allow absolute paths from #[lints(absolute_paths)] - absolute_paths_allowed_crates: Vec = Vec::new(), + absolute_paths_allowed_crates("absolute-paths-allowed-crates"): FxHashSet, /// The maximum number of segments a path can have before being linted, anything above this will /// be linted. #[lints(absolute_paths)] - absolute_paths_max_segments: u64 = 2, + absolute_paths_max_segments("absolute-paths-max-segments"): u64 = 2, /// Whether to accept a safety comment to be placed above the attributes for the `unsafe` block #[lints(undocumented_unsafe_blocks)] - accept_comment_above_attributes: bool = true, + accept_comment_above_attributes("accept-comment-above-attributes"): bool = true, /// Whether to accept a safety comment to be placed above the statement containing the `unsafe` block #[lints(undocumented_unsafe_blocks)] - accept_comment_above_statement: bool = true, + accept_comment_above_statement("accept-comment-above-statement"): bool = true, /// Don't lint when comparing the result of a modulo operation to zero. #[lints(modulo_arithmetic)] - allow_comparison_to_zero: bool = true, + allow_comparison_to_zero("allow-comparison-to-zero"): bool = true, /// Whether `dbg!` should be allowed in test functions or `#[cfg(test)]` #[lints(dbg_macro)] - allow_dbg_in_tests: bool = false, + allow_dbg_in_tests("allow-dbg-in-tests"): bool = false, /// Whether an item should be allowed to have the same name as its containing module #[lints(module_name_repetitions)] - allow_exact_repetitions: bool = true, + allow_exact_repetitions("allow-exact-repetitions"): bool = true, /// Whether `expect` should be allowed in code always evaluated at compile time #[lints(expect_used)] - allow_expect_in_consts: bool = true, + allow_expect_in_consts("allow-expect-in-consts"): bool = true, /// Whether `expect` should be allowed in test functions or `#[cfg(test)]` #[lints(expect_used)] - allow_expect_in_tests: bool = false, + allow_expect_in_tests("allow-expect-in-tests"): bool = false, /// Whether `indexing_slicing` should be allowed in test functions or `#[cfg(test)]` #[lints(indexing_slicing)] - allow_indexing_slicing_in_tests: bool = false, + allow_indexing_slicing_in_tests("allow-indexing-slicing-in-tests"): bool = false, /// Whether functions inside `#[cfg(test)]` modules or test functions should be checked. #[lints(large_stack_frames)] - allow_large_stack_frames_in_tests: bool = true, + allow_large_stack_frames_in_tests("allow-large-stack-frames-in-tests"): bool = true, /// Whether to allow mixed uninlined format args, e.g. `format!("{} {}", a, foo.bar)` #[lints(uninlined_format_args)] - allow_mixed_uninlined_format_args: bool = true, + allow_mixed_uninlined_format_args("allow-mixed-uninlined-format-args"): bool = true, /// Whether to allow `r#""#` when `r""` can be used #[lints(needless_raw_string_hashes)] - allow_one_hash_in_raw_strings: bool = false, + allow_one_hash_in_raw_strings("allow-one-hash-in-raw-strings"): bool = false, /// Whether `panic` should be allowed in test functions or `#[cfg(test)]` #[lints(panic)] - allow_panic_in_tests: bool = false, + allow_panic_in_tests("allow-panic-in-tests"): bool = false, /// Whether print macros (ex. `println!`) should be allowed in test functions or `#[cfg(test)]` #[lints(print_stderr, print_stdout)] - allow_print_in_tests: bool = false, + allow_print_in_tests("allow-print-in-tests"): bool = false, /// Whether to allow module inception if it's not public. #[lints(module_inception)] - allow_private_module_inception: bool = false, + allow_private_module_inception("allow-private-module-inception"): bool = false, /// List of trait paths to ignore when checking renamed function parameters. /// /// #### Example @@ -406,14 +282,13 @@ define_Conf! { /// - `".."` can be used as part of the list to indicate that the configured values should be appended to the /// default configuration of Clippy. By default, any configuration will replace the default value. #[lints(renamed_function_params)] - allow_renamed_params_for: Vec = - DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS.iter().map(ToString::to_string).collect(), + allow_renamed_params_for("allow-renamed-params-for"): Vec = DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS, /// Whether `unwrap` should be allowed in code always evaluated at compile time #[lints(unwrap_used)] - allow_unwrap_in_consts: bool = true, + allow_unwrap_in_consts("allow-unwrap-in-consts"): bool = true, /// Whether `unwrap` should be allowed in test functions or `#[cfg(test)]` #[lints(unwrap_used)] - allow_unwrap_in_tests: bool = false, + allow_unwrap_in_tests("allow-unwrap-in-tests"): bool = false, /// List of types to allow `unwrap()` and `expect()` on. /// /// #### Example @@ -422,22 +297,21 @@ define_Conf! { /// allow-unwrap-types = [ "std::sync::LockResult" ] /// ``` #[lints(expect_used, unwrap_used)] - allow_unwrap_types: Vec = Vec::new(), + allow_unwrap_types("allow-unwrap-types"): Vec, /// Whether `useless_vec` should ignore test functions or `#[cfg(test)]` #[lints(useless_vec)] - allow_useless_vec_in_tests: bool = false, + allow_useless_vec_in_tests("allow-useless-vec-in-tests"): bool = false, /// Additional dotfiles (files or directories starting with a dot) to allow #[lints(path_ends_with_ext)] - allowed_dotfiles: Vec = Vec::default(), + allowed_dotfiles("allowed-dotfiles"): Vec, /// A list of crate names to allow duplicates of #[lints(multiple_crate_versions)] - allowed_duplicate_crates: Vec = Vec::new(), + allowed_duplicate_crates("allowed-duplicate-crates"): FxHashSet, /// Allowed names below the minimum allowed characters. The value `".."` can be used as part of /// the list to indicate that the configured values should be appended to the default /// configuration of Clippy. By default, any configuration will replace the default value. #[lints(min_ident_chars)] - allowed_idents_below_min_chars: Vec = - DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS.iter().map(ToString::to_string).collect(), + allowed_idents_below_min_chars("allowed-idents-below-min-chars"): FxHashSet = DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS, /// List of prefixes to allow when determining whether an item's name ends with the module's name. /// If the rest of an item's name is an allowed prefix (e.g. item `ToFoo` or `to_foo` in module `foo`), /// then don't emit a warning. @@ -456,10 +330,10 @@ define_Conf! { /// - Use `".."` as part of the list to indicate that the configured values should be appended to the /// default configuration of Clippy. By default, any configuration will replace the default value #[lints(module_name_repetitions)] - allowed_prefixes: Vec = DEFAULT_ALLOWED_PREFIXES.iter().map(ToString::to_string).collect(), + allowed_prefixes("allowed-prefixes"): Vec = DEFAULT_ALLOWED_PREFIXES, /// The list of unicode scripts allowed to be used in the scope. #[lints(disallowed_script_idents)] - allowed_scripts: Vec = vec!["Latin".to_string()], + allowed_scripts("allowed-scripts"): Vec = DEFAULT_ALLOWED_SCRIPTS, /// List of path segments allowed to have wildcard imports. /// /// #### Example @@ -474,7 +348,7 @@ define_Conf! { /// 2. Paths with any segment that containing the word 'prelude' /// are already allowed by default. #[lints(wildcard_imports)] - allowed_wildcard_imports: Vec = Vec::new(), + allowed_wildcard_imports("allowed-wildcard-imports"): FxHashSet, /// Suppress checking of the passed type names in all types of operations. /// /// If a specific operation is desired, consider using `arithmetic_side_effects_allowed_binary` or `arithmetic_side_effects_allowed_unary` instead. @@ -490,7 +364,7 @@ define_Conf! { /// A type, say `SomeType`, listed in this configuration has the same behavior of /// `["SomeType" , "*"], ["*", "SomeType"]` in `arithmetic_side_effects_allowed_binary`. #[lints(arithmetic_side_effects)] - arithmetic_side_effects_allowed: Vec = <_>::default(), + arithmetic_side_effects_allowed("arithmetic-side-effects-allowed"): Vec, /// Suppress checking of the passed type pair names in binary operations like addition or /// multiplication. /// @@ -506,7 +380,7 @@ define_Conf! { /// arithmetic-side-effects-allowed-binary = [["SomeType" , "f32"], ["AnotherType", "*"]] /// ``` #[lints(arithmetic_side_effects)] - arithmetic_side_effects_allowed_binary: Vec<(String, String)> = <_>::default(), + arithmetic_side_effects_allowed_binary("arithmetic-side-effects-allowed-binary"): Vec<[String; 2]>, /// Suppress checking of the passed type names in unary operations like "negation" (`-`). /// /// #### Example @@ -515,10 +389,10 @@ define_Conf! { /// arithmetic-side-effects-allowed-unary = ["SomeType", "AnotherType"] /// ``` #[lints(arithmetic_side_effects)] - arithmetic_side_effects_allowed_unary: Vec = <_>::default(), + arithmetic_side_effects_allowed_unary("arithmetic-side-effects-allowed-unary"): Vec, /// The maximum allowed size for arrays on the stack #[lints(large_const_arrays, large_stack_arrays)] - array_size_threshold: u64 = 16 * 1024, + array_size_threshold("array-size-threshold"): u64 = 16 * 1024, /// Suppress lints whenever the suggested change would cause breakage for other crates. #[lints( box_collection, @@ -541,19 +415,15 @@ define_Conf! { vec_box, wrong_self_convention, )] - avoid_breaking_exported_api: bool = true, + avoid_breaking_exported_api("avoid-breaking-exported-api"): bool = true, /// The list of types which may not be held across an await point. - #[disallowed_paths_allow_replacements = false] #[lints(await_holding_invalid_type)] - await_holding_invalid_types: Vec = Vec::new(), - /// DEPRECATED LINT: BLACKLISTED_NAME. - /// - /// Use the Disallowed Names lint instead - #[conf_deprecated("Please use `disallowed-names` instead", disallowed_names)] - blacklisted_names: Vec = Vec::new(), + await_holding_invalid_types("await-holding-invalid-types"): Vec, + #[rename = disallowed_names] + blacklisted_names("blacklisted-names"), /// For internal testing only, ignores the current `publish` settings in the Cargo manifest. #[lints(cargo_common_metadata)] - cargo_ignore_publish: bool = false, + cargo_ignore_publish("cargo-ignore-publish"): bool = false, /// Whether to check for grouped late initializations from multiple `let` statements. /// /// #### Example @@ -577,10 +447,10 @@ define_Conf! { /// }; /// ``` #[lints(needless_late_init)] - check_grouped_late_init: bool = true, + check_grouped_late_init("check-grouped-late-init"): bool = true, /// Whether to check MSRV compatibility in `#[test]` and `#[cfg(test)]` code. #[lints(incompatible_msrv)] - check_incompatible_msrv_in_tests: bool = false, + check_incompatible_msrv_in_tests("check-incompatible-msrv-in-tests"): bool = false, /// Whether to suggest reordering constructor fields when initializers are present. /// /// Warnings produced by this configuration aren't necessarily fixed by just reordering the fields. Even if the @@ -600,21 +470,18 @@ define_Conf! { /// /// [from rust-clippy#11846]: https://github.com/rust-lang/rust-clippy/issues/11846#issuecomment-1820747924 #[lints(inconsistent_struct_constructor)] - check_inconsistent_struct_field_initializers: bool = false, + check_inconsistent_struct_field_initializers("check-inconsistent-struct-field-initializers"): bool = false, /// Whether to also run the listed lints on private items. #[lints(missing_errors_doc, missing_panics_doc, missing_safety_doc, unnecessary_safety_doc)] - check_private_items: bool = false, + check_private_items("check-private-items"): bool = false, /// The maximum cognitive complexity a function can have #[lints(cognitive_complexity)] - cognitive_complexity_threshold: u64 = 25, + cognitive_complexity_threshold("cognitive-complexity-threshold"): u64 = 25, /// The minimum digits a const float literal must have to supress the `excessive_precicion` lint #[lints(excessive_precision)] - const_literal_digits_threshold: usize = 30, - /// DEPRECATED LINT: CYCLOMATIC_COMPLEXITY. - /// - /// Use the Cognitive Complexity lint instead. - #[conf_deprecated("Please use `cognitive-complexity-threshold` instead", cognitive_complexity_threshold)] - cyclomatic_complexity_threshold: u64 = 25, + const_literal_digits_threshold("const-literal-digits-threshold"): u32 = 30, + #[rename = cognitive_complexity_threshold] + cyclomatic_complexity_threshold("cyclomatic-complexity-threshold"), /// The list of disallowed fields, written as fully qualified paths. /// /// **Fields:** @@ -623,9 +490,8 @@ define_Conf! { /// - `replacement` (optional): suggested alternative method /// - `allow-invalid` (optional, `false` by default): when set to `true`, it will ignore this entry /// if the path doesn't exist, instead of emitting an error - #[disallowed_paths_allow_replacements = true] #[lints(disallowed_fields)] - disallowed_fields: Vec = Vec::new(), + disallowed_fields("disallowed-fields"): Vec, /// The list of disallowed macros, written as fully qualified paths. /// /// **Fields:** @@ -634,9 +500,8 @@ define_Conf! { /// - `replacement` (optional): suggested alternative macro /// - `allow-invalid` (optional, `false` by default): when set to `true`, it will ignore this entry /// if the path doesn't exist, instead of emitting an error - #[disallowed_paths_allow_replacements = true] #[lints(disallowed_macros)] - disallowed_macros: Vec = Vec::new(), + disallowed_macros("disallowed-macros"): Vec, /// The list of disallowed methods, written as fully qualified paths. /// /// **Fields:** @@ -645,14 +510,13 @@ define_Conf! { /// - `replacement` (optional): suggested alternative method /// - `allow-invalid` (optional, `false` by default): when set to `true`, it will ignore this entry /// if the path doesn't exist, instead of emitting an error - #[disallowed_paths_allow_replacements = true] #[lints(disallowed_methods)] - disallowed_methods: Vec = Vec::new(), + disallowed_methods("disallowed-methods"): Vec, /// The list of disallowed names to lint about. NB: `bar` is not here since it has legitimate uses. The value /// `".."` can be used as part of the list to indicate that the configured values should be appended to the /// default configuration of Clippy. By default, any configuration will replace the default value. #[lints(disallowed_names)] - disallowed_names: Vec = DEFAULT_DISALLOWED_NAMES.iter().map(ToString::to_string).collect(), + disallowed_names("disallowed-names"): Vec = DEFAULT_DISALLOWED_NAMES, /// The list of disallowed types, written as fully qualified paths. /// /// **Fields:** @@ -661,19 +525,18 @@ define_Conf! { /// - `replacement` (optional): suggested alternative type /// - `allow-invalid` (optional, `false` by default): when set to `true`, it will ignore this entry /// if the path doesn't exist, instead of emitting an error - #[disallowed_paths_allow_replacements = true] #[lints(disallowed_types)] - disallowed_types: Vec = Vec::new(), + disallowed_types("disallowed-types"): Vec, /// The list of words this lint should not consider as identifiers needing ticks. The value /// `".."` can be used as part of the list to indicate that the configured values should be appended to the /// default configuration of Clippy. By default, any configuration will replace the default value. For example: /// * `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`. /// * `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list. #[lints(doc_markdown)] - doc_valid_idents: Vec = DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect(), + doc_valid_idents("doc-valid-idents"): FxHashSet = DEFAULT_DOC_VALID_IDENTS, /// Whether to apply the raw pointer heuristic to determine if a type is `Send`. #[lints(non_send_fields_in_send_ty)] - enable_raw_pointer_heuristic_for_send: bool = true, + enable_raw_pointer_heuristic_for_send("enable-raw-pointer-heuristic-for-send"): bool = true, /// Whether to recommend using implicit into iter for reborrowed values. /// /// #### Example @@ -692,90 +555,88 @@ define_Conf! { /// for _ in &mut *rmvec {} /// ``` #[lints(explicit_iter_loop)] - enforce_iter_loop_reborrow: bool = false, + enforce_iter_loop_reborrow("enforce-iter-loop-reborrow"): bool = false, /// The list of imports to always rename, a fully qualified path followed by the rename. #[lints(missing_enforced_import_renames)] - enforced_import_renames: Vec = Vec::new(), + enforced_import_renames("enforced-import-renames"): Vec, /// The minimum number of enum variants for the lints about variant names to trigger #[lints(enum_variant_names)] - enum_variant_name_threshold: u64 = 3, + enum_variant_name_threshold("enum-variant-name-threshold"): u64 = 3, /// The maximum size of an enum's variant to avoid box suggestion #[lints(large_enum_variant)] - enum_variant_size_threshold: u64 = 200, + enum_variant_size_threshold("enum-variant-size-threshold"): u64 = 200, /// The maximum amount of nesting a block can reside in #[lints(excessive_nesting)] - excessive_nesting_threshold: u64 = 0, + excessive_nesting_threshold("excessive-nesting-threshold"): u64 = 0, /// The maximum byte size a `Future` can have, before it triggers the `clippy::large_futures` lint #[lints(large_futures)] - future_size_threshold: u64 = 16 * 1024, + future_size_threshold("future-size-threshold"): u64 = 16 * 1024, /// A list of paths to types that should be treated as if they do not contain interior mutability #[lints(borrow_interior_mutable_const, declare_interior_mutable_const, ifs_same_cond, mutable_key_type)] - ignore_interior_mutability: Vec = Vec::from(["bytes::Bytes".into()]), + ignore_interior_mutability("ignore-interior-mutability"): Vec = DEFAULT_IGNORE_INTERIOR_MUTABILITY, /// Sets the scope ("crate", "file", or "module") in which duplicate inherent `impl` blocks for the same type are linted. #[lints(multiple_inherent_impl)] - inherent_impl_lint_scope: InherentImplLintScope = InherentImplLintScope::Crate, + inherent_impl_lint_scope("inherent-impl-lint-scope"): InherentImplLintScope = InherentImplLintScope::Crate, /// A list of paths to types that should be ignored as overly large `Err`-variants in a /// `Result` returned from a function #[lints(result_large_err)] - large_error_ignored: Vec = Vec::default(), + large_error_ignored("large-error-ignored"): Vec, /// The maximum size of the `Err`-variant in a `Result` returned from a function #[lints(result_large_err)] - large_error_threshold: u64 = 128, + large_error_threshold("large-error-threshold"): u64 = 128, /// Whether collapsible `if` and `else if` chains are linted if they contain comments inside the parts /// that would be collapsed. #[lints(collapsible_else_if, collapsible_if)] - lint_commented_code: bool = false, - /// Whether to suggest reordering constructor fields when initializers are present. - /// DEPRECATED CONFIGURATION: lint-inconsistent-struct-field-initializers - /// - /// Use the `check-inconsistent-struct-field-initializers` configuration instead. - #[conf_deprecated("Please use `check-inconsistent-struct-field-initializers` instead", check_inconsistent_struct_field_initializers)] - lint_inconsistent_struct_field_initializers: bool = false, + lint_commented_code("lint-commented-code"): bool = false, + #[rename = check_inconsistent_struct_field_initializers] + lint_inconsistent_struct_field_initializers("lint-inconsistent-struct-field-initializers"): bool = false, /// The lower bound for linting decimal literals #[lints(decimal_literal_representation)] - literal_representation_threshold: u64 = 16384, + literal_representation_threshold("literal-representation-threshold"): u64 = 16384, /// Whether the matches should be considered by the lint, and whether there should /// be filtering for common types. #[lints(manual_let_else)] - matches_for_let_else: MatchLintBehaviour = MatchLintBehaviour::WellKnownTypes, + matches_for_let_else("matches-for-let-else"): MatchLintBehaviour = MatchLintBehaviour::WellKnownTypes, /// The maximum number of bool parameters a function can have. /// Use `0` to lint on any function with a bool parameter. #[lints(fn_params_excessive_bools)] - max_fn_params_bools: u64 = 3, + max_fn_params_bools("max-fn-params-bools"): u64 = 3, /// The maximum size of a file included via `include_bytes!()` or `include_str!()`, in bytes #[lints(large_include_file)] - max_include_file_size: u64 = 1_000_000, + max_include_file_size("max-include-file-size"): u64 = 1_000_000, /// The maximum number of bool fields a struct can have #[lints(struct_excessive_bools)] - max_struct_bools: u64 = 3, + max_struct_bools("max-struct-bools"): u64 = 3, /// When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in /// the slice pattern that is suggested. If more elements are necessary, the lint is suppressed. /// For example, `[_, _, _, e, ..]` is a slice pattern with 4 elements. #[lints(index_refutable_slice)] - max_suggested_slice_pattern_length: u64 = 3, + max_suggested_slice_pattern_length("max-suggested-slice-pattern-length"): u64 = 3, /// The maximum number of bounds a trait can have to be linted #[lints(type_repetition_in_bounds)] - max_trait_bounds: u64 = 3, + max_trait_bounds("max-trait-bounds"): u64 = 3, + /// Whether to lint idents that have too few chars even when following trait declaration. + #[lints(min_ident_chars)] + min_ident_chars_lint_trait_impl("min-ident-chars-lint-trait-impl"): bool = false, /// Minimum chars an ident can have, anything below or equal to this will be linted. #[lints(min_ident_chars)] - min_ident_chars_threshold: u64 = 1, + min_ident_chars_threshold("min-ident-chars-threshold"): u64 = 1, /// Whether to allow fields starting with an underscore to skip documentation requirements #[lints(missing_docs_in_private_items)] - missing_docs_allow_unused: bool = false, + missing_docs_allow_unused("missing-docs-allow-unused"): bool = false, /// Whether to **only** check for missing documentation in items visible within the current /// crate. For example, `pub(crate)` items. #[lints(missing_docs_in_private_items)] - missing_docs_in_crate_items: bool = false, + missing_docs_in_crate_items("missing-docs-in-crate-items"): bool = false, /// The named groupings of different source item kinds within modules. #[lints(arbitrary_source_item_ordering)] - module_item_order_groupings: SourceItemOrderingModuleItemGroupings = DEFAULT_MODULE_ITEM_ORDERING_GROUPS.into(), + module_item_order_groupings("module-item-order-groupings"): SourceItemOrderingModuleItemGroupings, /// Whether the items within module groups should be ordered alphabetically or not. /// /// This option can be configured to "all", "none", or a list of specific grouping names that should be checked /// (e.g. only "enums"). #[lints(arbitrary_source_item_ordering)] - module_items_ordered_within_groupings: SourceItemOrderingWithinModuleItemGroupings = - SourceItemOrderingWithinModuleItemGroupings::None, + module_items_ordered_within_groupings("module-items-ordered-within-groupings"): SourceItemOrderingWithinModuleItemGroupings, /// The minimum rust version that the project supports. Defaults to the `rust-version` field in `Cargo.toml` #[default_text = "current version"] #[lints( @@ -796,6 +657,7 @@ define_Conf! { filter_map_next, from_over_into, if_then_some_else_none, + implicit_saturating_sub, index_refutable_slice, inefficient_to_string, io_other_error, @@ -840,6 +702,7 @@ define_Conf! { missing_const_for_fn, needless_borrow, non_std_lazy_statics, + nonnull_unchecked_on_box_ptr, option_as_ref_deref, or_fun_call, ptr_as_ptr, @@ -862,412 +725,268 @@ define_Conf! { use_self, zero_ptr, )] - msrv: Msrv = Msrv::default(), + msrv("msrv"): Option, /// The minimum size (in bytes) to consider a type for passing by reference instead of by value. #[lints(large_types_passed_by_value)] - pass_by_value_size_limit: u64 = 256, + pass_by_value_size_limit("pass-by-value-size-limit"): u64 = 256, /// Lint "public" fields in a struct that are prefixed with an underscore based on their /// exported visibility, or whether they are marked as "pub". #[lints(pub_underscore_fields)] - pub_underscore_fields_behavior: PubUnderscoreFieldsBehaviour = PubUnderscoreFieldsBehaviour::PubliclyExported, + pub_underscore_fields_behavior("pub-underscore-fields-behavior"): PubUnderscoreFieldsBehaviour = PubUnderscoreFieldsBehaviour::PubliclyExported, /// Whether the type itself in a struct or enum should be replaced with `Self` when encountering recursive types. #[lints(use_self)] - recursive_self_in_type_definitions: bool = true, + recursive_self_in_type_definitions("recursive-self-in-type-definitions"): bool = true, /// Whether to lint only if it's multiline. #[lints(semicolon_inside_block)] - semicolon_inside_block_ignore_singleline: bool = false, + semicolon_inside_block_ignore_singleline("semicolon-inside-block-ignore-singleline"): bool = false, /// Whether to lint only if it's singleline. #[lints(semicolon_outside_block)] - semicolon_outside_block_ignore_multiline: bool = false, + semicolon_outside_block_ignore_multiline("semicolon-outside-block-ignore-multiline"): bool = false, /// The maximum number of single char bindings a scope may have #[lints(many_single_char_names)] - single_char_binding_names_threshold: u64 = 4, + single_char_binding_names_threshold("single-char-binding-names-threshold"): u64 = 4, /// Which kind of elements should be ordered internally, possible values being `enum`, `impl`, `module`, `struct`, `trait`. #[lints(arbitrary_source_item_ordering)] - source_item_ordering: SourceItemOrdering = DEFAULT_SOURCE_ITEM_ORDERING.into(), + source_item_ordering("source-item-ordering"): SourceItemOrdering, /// The maximum allowed stack size for functions in bytes #[lints(large_stack_frames)] - stack_size_threshold: u64 = 512_000, + stack_size_threshold("stack-size-threshold"): u64 = 512_000, /// Enforce the named macros always use the braces specified. /// /// A `MacroMatcher` can be added like so `{ name = "macro_name", brace = "(" }`. If the macro /// could be used with a full path two `MacroMatcher`s have to be added one with the full path /// `crate_name::macro_name` and one with just the macro name. #[lints(nonstandard_macro_braces)] - standard_macro_braces: Vec = Vec::new(), + standard_macro_braces("standard-macro-braces"): Vec, /// The minimum number of struct fields for the lints about field names to trigger #[lints(struct_field_names)] - struct_field_name_threshold: u64 = 3, + struct_field_name_threshold("struct-field-name-threshold"): u64 = 3, /// Whether to suppress a restriction lint in constant code. In same /// cases the restructured operation might not be unavoidable, as the /// suggested counterparts are unavailable in constant code. This /// configuration will cause restriction lints to trigger even /// if no suggestion can be made. #[lints(indexing_slicing)] - suppress_restriction_lint_in_const: bool = false, + suppress_restriction_lint_in_const("suppress-restriction-lint-in-const"): bool = false, /// The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap #[lints(boxed_local, useless_vec)] - too_large_for_stack: u64 = 200, + too_large_for_stack("too-large-for-stack"): u64 = 200, /// The maximum number of argument a function or method can have #[lints(too_many_arguments)] - too_many_arguments_threshold: u64 = 7, + too_many_arguments_threshold("too-many-arguments-threshold"): u64 = 7, /// The maximum number of lines a function or method can have #[lints(too_many_lines)] - too_many_lines_threshold: u64 = 100, + too_many_lines_threshold("too-many-lines-threshold"): u64 = 100, /// The order of associated items in traits. #[lints(arbitrary_source_item_ordering)] - trait_assoc_item_kinds_order: SourceItemOrderingTraitAssocItemKinds = DEFAULT_TRAIT_ASSOC_ITEM_KINDS_ORDER.into(), + trait_assoc_item_kinds_order("trait-assoc-item-kinds-order"): SourceItemOrderingTraitAssocItemKinds, + /// The required ordering of associated items in trait impls: purely alphabetical, + /// following the trait definition order, or accepting either. + /// + /// Note that the trait definition order may change between versions of the + /// crate defining the trait without being considered a breaking change. + /// + /// Examples: + /// When using trait definition item ordering: + /// ```toml + /// trait-impl-item-order = "trait_item_ordering" + /// ``` + /// When using trait definition item ordering and alphabetical for fallbacks: + /// ```toml + /// trait-impl-item-order = "alphabetical_or_trait_item_ordering" + /// ``` + #[lints(arbitrary_source_item_ordering)] + trait_impl_item_order("trait-impl-item-order"): TraitImplItemOrder, /// The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by /// reference. #[default_text = "target_pointer_width"] #[lints(trivially_copy_pass_by_ref)] - trivial_copy_size_limit: Option = None, + trivial_copy_size_limit("trivial-copy-size-limit"): Option, /// The maximum complexity a type can have #[lints(type_complexity)] - type_complexity_threshold: u64 = 250, + type_complexity_threshold("type-complexity-threshold"): u64 = 250, /// The byte size a `T` in `Box` can have, below which it triggers the `clippy::unnecessary_box` lint #[lints(unnecessary_box_returns)] - unnecessary_box_size: u64 = 128, + unnecessary_box_size("unnecessary-box-size"): u64 = 128, /// Should the fraction of a decimal be linted to include separators. #[lints(unreadable_literal)] - unreadable_literal_lint_fractions: bool = true, + unreadable_literal_lint_fractions("unreadable-literal-lint-fractions"): bool = true, /// Enables verbose mode. Triggers if there is more than one uppercase char next to each other #[lints(upper_case_acronyms)] - upper_case_acronyms_aggressive: bool = false, + upper_case_acronyms_aggressive("upper-case-acronyms-aggressive"): bool = false, /// The size of the boxed type in bytes, where boxing in a `Vec` is allowed #[lints(vec_box)] - vec_box_size_threshold: u64 = 4096, + vec_box_size_threshold("vec-box-size-threshold"): u64 = 4096, /// The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros' #[lints(verbose_bit_mask)] - verbose_bit_mask_threshold: u64 = 1, + verbose_bit_mask_threshold("verbose-bit-mask-threshold"): u64 = 1, /// Whether to emit warnings on all wildcard imports, including those from `prelude`, from `super` in tests, /// or for `pub use` reexports. #[lints(wildcard_imports)] - warn_on_all_wildcard_imports: bool = false, + warn_on_all_wildcard_imports("warn-on-all-wildcard-imports"): bool = false, /// Whether to also emit warnings for unsafe blocks with metavariable expansions in **private** macros. #[lints(macro_metavars_in_unsafe)] - warn_unsafe_macro_metavars_in_private_macros: bool = false, + warn_unsafe_macro_metavars_in_private_macros("warn-unsafe-macro-metavars-in-private-macros"): bool = false, } -/// Search for the configuration file. +// Remove code tags and code behind '# 's, as they are not needed for the lint docs and --explain +pub fn sanitize_explanation(raw_docs: &str) -> String { + // Remove tags and hidden code: + let mut explanation = String::with_capacity(128); + let mut in_code = false; + for line in raw_docs.lines() { + let line = line.strip_prefix(' ').unwrap_or(line); + + if let Some(lang) = line.strip_prefix("```") { + let tag = lang.split_once(',').map_or(lang, |(left, _)| left); + if !in_code && matches!(tag, "" | "rust" | "ignore" | "should_panic" | "no_run" | "compile_fail") { + explanation += "```rust\n"; + } else { + explanation += line; + explanation.push('\n'); + } + in_code = !in_code; + } else if !(in_code && line.starts_with("# ")) { + explanation += line; + explanation.push('\n'); + } + } + + explanation +} + +/// Searches for and loads the config file into the source map. /// /// # Errors /// /// Returns any unexpected filesystem error encountered when searching for the config file -pub fn lookup_conf_file() -> io::Result<(Option, Vec)> { +fn load_conf_file(sess: &Session) -> Option> { /// Possible filename to search for. const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"]; // Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR. // If neither of those exist, use ".". (Update documentation if this priority changes) - let mut current = env::var_os("CLIPPY_CONF_DIR") - .or_else(|| env::var_os("CARGO_MANIFEST_DIR")) - .map_or_else(|| PathBuf::from("."), PathBuf::from) - .canonicalize()?; - - let mut found_config: Option = None; - let mut warnings = vec![]; + const CONFIG_VARS: [(&str, &str); 2] = [ + ("CLIPPY_CONF_DIR", "failed to read `CLIPPY_CONF_DIR` as a directory"), + ( + "CARGO_MANIFEST_DIR", + "failed to read `CARGO_MANIFEST_DIR` as a directory", + ), + ]; + let (current, msg) = CONFIG_VARS + .into_iter() + .find_map(|(var, msg)| env::var_os(var).map(|p| (PathBuf::from(p), msg))) + .unwrap_or_else(|| (PathBuf::from("."), "failed to get the current directory")); + let mut current = match current.canonicalize() { + Ok(x) => x, + Err(e) => { + sess.dcx().err(format!("{msg}: {e}")); + return None; + }, + }; + let mut loaded_config: Option<(PathBuf, Arc)> = None; loop { - for config_file_name in &CONFIG_FILE_NAMES { - if let Ok(config_file) = current.join(config_file_name).canonicalize() { - match fs::metadata(&config_file) { - Err(e) if e.kind() == io::ErrorKind::NotFound => {}, - Err(e) => return Err(e), - Ok(md) if md.is_dir() => {}, - Ok(_) => { - // warn if we happen to find two config files #8323 - if let Some(ref found_config) = found_config { - warnings.push(format!( - "using config file `{}`, `{}` will be ignored", - found_config.display(), - config_file.display() - )); - } else { - found_config = Some(config_file); - } - }, + for config_file_name in CONFIG_FILE_NAMES { + if let Ok(config_path) = current.join(config_file_name).canonicalize() { + if let Some((loaded_path, _)) = &loaded_config { + if fs::metadata(loaded_path).is_ok_and(|x| x.is_file()) { + // Warn if `.clippy.toml` and `clippy.toml` exist + sess.dcx().warn(format!( + "using config file `{}`, `{}` will be ignored", + loaded_path.display(), + config_path.display(), + )); + } + } else { + match sess.source_map().load_file(&config_path) { + Ok(src) => loaded_config = Some((config_path, src)), + Err(e) + if matches!( + e.kind(), + io::ErrorKind::NotFound | io::ErrorKind::IsADirectory | io::ErrorKind::NotADirectory + ) => {}, + Err(e) => { + sess.dcx() + .err(format!("error reading `{}`: {e}", config_path.display())); + return None; + }, + } } } } - if found_config.is_some() { - return Ok((found_config, warnings)); + // Don't mention config files in parent directories. + if let Some((_, src)) = loaded_config { + return Some(src); } // If the current directory has no parent, we're done searching. if !current.pop() { - return Ok((None, warnings)); + return None; } } } -fn deserialize(file: &SourceFile) -> TryConf { - match toml::de::Deserializer::new(file.src.as_ref().unwrap()).deserialize_map(ConfVisitor(file)) { - Ok(mut conf) => { - extend_vec_if_indicator_present(&mut conf.conf.disallowed_names, DEFAULT_DISALLOWED_NAMES); - extend_vec_if_indicator_present(&mut conf.conf.allowed_prefixes, DEFAULT_ALLOWED_PREFIXES); - extend_vec_if_indicator_present( - &mut conf.conf.allow_renamed_params_for, - DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS, - ); - - // Confirms that the user has not accidentally configured ordering requirements for groups that - // aren't configured. - if let SourceItemOrderingWithinModuleItemGroupings::Custom(groupings) = - &conf.conf.module_items_ordered_within_groupings - { - for grouping in groupings { - if !conf.conf.module_item_order_groupings.is_grouping(grouping) { - // Since this isn't fixable by rustfix, don't emit a `Suggestion`. This just adds some useful - // info for the user instead. - - let names = conf.conf.module_item_order_groupings.grouping_names(); - let suggestion = suggest_candidate(grouping, names.iter().map(String::as_str)) - .map(|s| format!(" perhaps you meant `{s}`?")) - .unwrap_or_default(); - let names = names.iter().map(|s| format!("`{s}`")).join(", "); - let message = format!( - "unknown ordering group: `{grouping}` was not specified in `module-items-ordered-within-groupings`,{suggestion} expected one of: {names}" - ); - - let span = conf - .value_spans - .get("module_item_order_groupings") - .cloned() - .unwrap_or_default(); - conf.errors.push(ConfError::spanned(file, message, None, span)); - } - } - } - - // TODO: THIS SHOULD BE TESTED, this comment will be gone soon - if conf.conf.allowed_idents_below_min_chars.iter().any(|e| e == "..") { - conf.conf - .allowed_idents_below_min_chars - .extend(DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS.iter().map(ToString::to_string)); - } - if conf.conf.doc_valid_idents.iter().any(|e| e == "..") { - conf.conf - .doc_valid_idents - .extend(DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string)); - } - - conf - }, - Err(e) => TryConf::from_toml_error(file, &e), - } -} - -fn extend_vec_if_indicator_present(vec: &mut Vec, default: &[&str]) { - if vec.contains(&"..".to_string()) { - vec.extend(default.iter().map(ToString::to_string)); - } -} - impl Conf { - pub fn read(sess: &Session, path: &io::Result<(Option, Vec)>) -> &'static Conf { + pub fn load(sess: &Session) -> &'static Conf { static CONF: OnceLock = OnceLock::new(); - CONF.get_or_init(|| Conf::read_inner(sess, path)) + CONF.get_or_init(|| Conf::load_inner(sess)) } - fn read_inner(sess: &Session, path: &io::Result<(Option, Vec)>) -> Conf { - match path { - Ok((_, warnings)) => { - for warning in warnings { - sess.dcx().warn(warning.clone()); + fn load_inner(sess: &Session) -> Conf { + let mut conf = if let Some(src) = load_conf_file(sess) { + let dcx = DiagCtxt::new(sess, src.start_pos.to_usize()); + let src = src.src.as_ref().unwrap(); + + let (toml, errs) = DeTable::parse_recoverable(src.as_str()); + for e in errs { + match e.span() { + Some(sp) => dcx.span_err(sp, e.message().to_owned()), + None => { + dcx.inner + .struct_err(format!("error parsing `clippy.toml`: {}", e.message())) + .emit(); + }, } - }, - Err(error) => { - sess.dcx() - .err(format!("error finding Clippy's configuration file: {error}")); - }, - } - - let TryConf { - mut conf, - value_spans: _, - errors, - warnings, - } = match path { - Ok((Some(path), _)) => match sess.source_map().load_file(path) { - Ok(file) => deserialize(&file), - Err(error) => { - sess.dcx().err(format!("failed to read `{}`: {error}", path.display())); - TryConf::default() - }, - }, - _ => TryConf::default(), - }; - - conf.msrv.read_cargo(sess); - - // all conf errors are non-fatal, we just use the default conf in case of error - for error in errors { - let mut diag = sess.dcx().struct_span_err( - error.span, - format!("error reading Clippy's configuration file: {}", error.message), - ); - - if let Some(sugg) = error.suggestion { - diag.span_suggestion(error.span, sugg.message, sugg.suggestion, Applicability::MaybeIncorrect); } + Conf::deserialize(&dcx, toml.get_ref()) + } else { + Conf::default() + }; - diag.emit(); - } - - for warning in warnings { - sess.dcx().span_warn( - warning.span, - format!("error reading Clippy's configuration file: {}", warning.message), - ); - } - - conf - } -} - -const SEPARATOR_WIDTH: usize = 4; - -#[derive(Debug)] -struct FieldError { - error: String, - suggestion: Option, -} - -#[derive(Debug)] -struct Suggestion { - message: &'static str, - suggestion: &'static str, -} - -impl std::error::Error for FieldError {} - -impl Display for FieldError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.pad(&self.error) - } -} - -impl serde::de::Error for FieldError { - fn custom(msg: T) -> Self { - Self { - error: msg.to_string(), - suggestion: None, - } - } - - fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self { - // List the available fields sorted and at least one per line, more if `CLIPPY_TERMINAL_WIDTH` is - // set and allows it. - use fmt::Write; - - let metadata = get_configuration_metadata(); - let deprecated = metadata - .iter() - .filter_map(|conf| { - if conf.deprecation_reason.is_some() { - Some(conf.name.as_str()) - } else { - None + let cargo_msrv = env::var("CARGO_PKG_RUST_VERSION") + .ok() + .and_then(|v| parse_version(Symbol::intern(&v))); + match (&conf.msrv, cargo_msrv) { + (None, Some(cargo_msrv)) => conf.msrv = Some(cargo_msrv), + (Some(clippy_msrv), Some(cargo_msrv)) => { + if *clippy_msrv != cargo_msrv { + sess.dcx().warn(format!( + "the MSRV in `clippy.toml` and `Cargo.toml` differ; using `{clippy_msrv}` from `clippy.toml`" + )); } - }) - .collect::>(); - - let mut expected = expected - .iter() - .copied() - .filter(|name| !deprecated.contains(name)) - .collect::>(); - expected.sort_unstable(); - - let (rows, column_widths) = calculate_dimensions(&expected); - - let mut msg = format!("unknown field `{field}`, expected one of"); - for row in 0..rows { - writeln!(msg).unwrap(); - for (column, column_width) in column_widths.iter().copied().enumerate() { - let index = column * rows + row; - let field = expected.get(index).copied().unwrap_or_default(); - write!(msg, "{:SEPARATOR_WIDTH$}{field:column_width$}", " ").unwrap(); - } + }, + (_, None) => {}, } - let suggestion = suggest_candidate(field, expected).map(|suggestion| Suggestion { - message: "perhaps you meant", - suggestion, - }); - - Self { error: msg, suggestion } + conf } } -fn calculate_dimensions(fields: &[&str]) -> (usize, Vec) { - let columns = env::var("CLIPPY_TERMINAL_WIDTH") - .ok() - .and_then(|s| ::from_str(&s).ok()) - .map_or(1, |terminal_width| { - let max_field_width = fields.iter().map(|field| field.len()).max().unwrap(); - cmp::max(1, terminal_width / (SEPARATOR_WIDTH + max_field_width)) - }); - - let rows = fields.len().div_ceil(columns); - - let column_widths = (0..columns) - .map(|column| { - if column < columns - 1 { - (0..rows) - .map(|row| { - let index = column * rows + row; - let field = fields.get(index).copied().unwrap_or_default(); - field.len() - }) - .max() - .unwrap() - } else { - // Avoid adding extra space to the last column. - 0 - } - }) - .collect::>(); - - (rows, column_widths) -} - -/// Given a user-provided value that couldn't be matched to a known option, finds the most likely -/// candidate among candidates that the user might have meant. -fn suggest_candidate<'a, I>(value: &str, candidates: I) -> Option<&'a str> -where - I: IntoIterator, -{ - candidates - .into_iter() - .filter_map(|expected| { - let dist = edit_distance(value, expected, 4)?; - Some((dist, expected)) - }) - .min_by_key(|&(dist, _)| dist) - .map(|(_, suggestion)| suggestion) -} - #[cfg(test)] mod tests { - use serde::de::IgnoredAny; - use std::collections::{HashMap, HashSet}; + use rustc_data_structures::fx::FxHashSet; use std::fs; + use toml::de::DeTable; use walkdir::WalkDir; #[test] fn configs_are_tested() { - let mut names: HashSet = crate::get_configuration_metadata() + let mut names: FxHashSet<_> = super::Conf::get_metadata() .into_iter() - .filter_map(|meta| { - if meta.deprecation_reason.is_none() { - Some(meta.name.replace('_', "-")) - } else { - None - } - }) + .filter(|meta| meta.renamed_to.is_none()) + .map(|meta| meta.name) .collect(); let toml_files = WalkDir::new("../tests") @@ -1277,10 +996,9 @@ mod tests { for entry in toml_files { let file = fs::read_to_string(entry.path()).unwrap(); - #[expect(clippy::zero_sized_map_values)] - if let Ok(map) = toml::from_str::>(&file) { - for name in map.keys() { - names.remove(name.as_str()); + if let Ok(toml) = DeTable::parse(&file) { + for (key, _) in toml.as_ref() { + names.remove(&**key.get_ref()); } } } diff --git a/src/tools/clippy/clippy_config/src/de.rs b/src/tools/clippy/clippy_config/src/de.rs new file mode 100644 index 0000000000000..803e34aefe91d --- /dev/null +++ b/src/tools/clippy/clippy_config/src/de.rs @@ -0,0 +1,562 @@ +use arrayvec::ArrayVec; +use core::str::FromStr as _; +use itertools::Itertools as _; +use rustc_attr_parsing::parse_version; +use rustc_errors::{DiagCtxtHandle, DiagMessage}; +use rustc_hir::attrs::RustcVersion; +use rustc_session::Session; +use rustc_session::config::ErrorOutputType; +use rustc_span::edit_distance::edit_distance; +use rustc_span::{BytePos, Pos as _, Span, Spanned, Symbol}; +use std::collections::{HashMap, HashSet}; +use std::fmt::{self, Display, Write as _}; +use std::hash::{BuildHasher, Hash}; +use std::marker::PhantomData; +use std::ops::{ControlFlow, Range}; +use toml::de::DeValue; + +pub type TomlValue<'a> = toml::Spanned>; + +pub struct DiagCtxt<'a> { + pub inner: DiagCtxtHandle<'a>, + pub width: usize, + pub render_pretty: bool, + offset: usize, +} +impl<'a> DiagCtxt<'a> { + pub fn new(sess: &'a Session, offset: usize) -> Self { + Self { + inner: sess.dcx(), + width: sess.diagnostic_width(), + render_pretty: match sess.opts.error_format { + ErrorOutputType::HumanReadable { .. } => true, + ErrorOutputType::Json { pretty, .. } => pretty, + }, + offset, + } + } + + pub fn make_sp(&self, range: Range) -> Span { + Span::with_root_ctxt( + BytePos::from_usize(self.offset + range.start), + BytePos::from_usize(self.offset + range.end), + ) + } + + pub fn span_err(&self, range: Range, msg: impl Into) { + self.inner.span_err(self.make_sp(range), msg); + } + + pub fn span_warn(&self, range: Range, msg: impl Into) { + self.inner.span_warn(self.make_sp(range), msg); + } +} + +/// Attempts to find the closest matching string from the list. Returns `None` +/// if the edit distance is too large. +pub fn find_closest_match<'a>(s: &str, options: &[&'a str]) -> Option<&'a str> { + // Don't treat `_` to `-` and case conversions as an edit. + let mut s = s.replace('_', "-"); + s.make_ascii_lowercase(); + options + .iter() + .filter_map(|&option| edit_distance(&s, &option.to_ascii_lowercase(), 4).map(|x| (x, option))) + .min_by_key(|&(dist, _)| dist) + .map(|(_, x)| x) +} + +/// Creates a message listing all possible values suitable for use in `Diag::note`. +pub fn create_value_list_msg(dcx: &DiagCtxt<'_>, values: &[&str]) -> String { + const NOTE_WITH_MSG_LEN: usize = " = note: possible values: ".len(); + const NOTE_LEN: usize = " = note: ".len(); + const TBL_SEP: &str = " "; + const INLINE_SEP: &str = ", "; + + // Print everything on one line if it will fit and there aren't too many values. + // e.g. "note: possible values: `value1`, `value2`, `value3`" + // + // If there are too many values and the note would exceed the terminal width lay the + // values out into columns. e.g. + // possible values: + // value1 value5 + // value2 value6 + // value3 value7 + // value4 + if values.len() <= 8 + && NOTE_WITH_MSG_LEN + values.iter().map(|x| x.len() + INLINE_SEP.len() + 2).sum::() <= dcx.width + { + format!( + "possible values: {}", + values.iter().format_with(INLINE_SEP, |x, f| f(&format_args!("`{x}`"))), + ) + } else if dcx.render_pretty { + // The minimum width a column could possibly have. + let min_width = values.iter().map(|x| x.len()).min().unwrap_or(0); + // The number of columns that fit using the minimum width. + let max_col = dcx.width.saturating_sub(NOTE_WITH_MSG_LEN) / (min_width + TBL_SEP.len()); + + // Determine the starting dimensions of the search. + let start_size = (2..=max_col).try_fold(values.len(), |row_count, col_count| { + let needed_rows = values.len().div_ceil(col_count); + // Only add a new column if it will remove several rows. + if needed_rows + 3 <= row_count { + ControlFlow::Continue(needed_rows) + } else { + ControlFlow::Break((row_count, col_count - 1)) + } + }); + let (mut row_count, init_col_count) = match start_size { + // Also handles the case where `max_col < 2` + ControlFlow::Continue(x) => (x, max_col), + ControlFlow::Break(x) => x, + }; + + // The current total width required. + let mut total_width = init_col_count * (min_width + TBL_SEP.len()) + NOTE_LEN; + // The current width of each column without the prefix. + let mut col_widths = vec![min_width; init_col_count]; + + // Determine the required width of each column. + 'outer: loop { + // Also handles the case where `max_col` is zero. + if col_widths.len() <= 1 { + return format!( + "possible values:\n{}", + values.iter().format_with("\n", |x, f| f(&format_args!("{x}"))), + ); + } + for (col_values, col_width) in values.chunks(row_count).zip(col_widths.iter_mut()) { + for value in col_values { + if value.len() > *col_width { + let delta = value.len() - *col_width; + *col_width += delta; + total_width += delta; + if total_width > dcx.width { + // Remove a column and reset the metrics then retry. + col_widths.pop(); + row_count = values.len().div_ceil(col_widths.len()); + col_widths.fill(min_width); + total_width = col_widths.len() * (min_width + TBL_SEP.len()) + NOTE_LEN; + continue 'outer; + } + } + } + } + break; + } + + format!( + "possible values:\n{}", + (0..row_count).format_with("\n", |row, f| { + f(&(row..values.len()) + .step_by(row_count) + .zip(&col_widths) + .format_with(TBL_SEP, |(i, &width), f| { + // Don't print trailing whitespace on the right edge. + let width = if i + row_count < values.len() { width } else { 0 }; + f(&format_args!("{:width$}", values[i])) + })) + }), + ) + } else { + format!( + "possible values:{}", + values.iter().format_with("", |x, f| f(&format_args!("\n{x}"))), + ) + } +} + +/// A type which can be constructed from a default value. +pub trait FromDefault: Sized { + /// Creates this value from a default value. + fn from_default(default: T) -> Self; + /// Writes the default value to a string. + fn display_default(default: T) -> impl Display; +} + +macro_rules! impl_from_default_passthrough { + ($($ty:ty),*) => {$( + impl FromDefault<$ty> for $ty { + #[inline] + fn from_default(default: $ty) -> Self { + default + } + #[inline] + fn display_default(default: $ty) -> impl Display { + default + } + } + )*} +} +impl_from_default_passthrough!(bool, u8, i8, u16, i16, u32, i32, u64, i64, f32, f64); + +impl FromDefault<()> for Option { + fn from_default((): ()) -> Self { + None + } + fn display_default((): ()) -> impl Display { + // will cause an error in the metadata collector + "" + } +} + +struct DisplayStr(&'static str); +impl Display for DisplayStr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self.0, f) + } +} + +impl FromDefault<&'static str> for String { + fn from_default(default: &'static str) -> Self { + default.into() + } + fn display_default(default: &'static str) -> impl Display { + DisplayStr(default) + } +} + +impl FromDefault<()> for Vec { + fn from_default((): ()) -> Self { + Vec::new() + } + fn display_default((): ()) -> impl Display { + "[]" + } +} + +impl FromDefault<()> for HashSet { + fn from_default((): ()) -> Self { + HashSet::default() + } + fn display_default((): ()) -> impl Display { + "[]" + } +} + +struct DisplaySlice(&'static [T], PhantomData); +impl Display for DisplaySlice +where + T: 'static + Copy, + U: FromDefault, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_char('[')?; + if let Some((head, tail)) = self.0.split_first() { + U::display_default(*head).fmt(f)?; + for x in tail { + write!(f, ", {}", U::display_default(*x))?; + } + } + f.write_char(']') + } +} + +impl FromDefault<&'static [U]> for Vec +where + T: FromDefault, + U: 'static + Copy, +{ + fn from_default(default: &'static [U]) -> Self { + default.iter().map(|&x| T::from_default(x)).collect() + } + fn display_default(default: &'static [U]) -> impl Display { + DisplaySlice::<_, T>(default, PhantomData) + } +} + +impl FromDefault<&'static [U]> for HashSet +where + T: FromDefault + Eq + Hash, + U: 'static + Copy, + S: Default + BuildHasher, +{ + fn from_default(default: &'static [U]) -> Self { + default.iter().map(|&x| T::from_default(x)).collect() + } + fn display_default(default: &'static [U]) -> impl Display { + DisplaySlice::<_, T>(default, PhantomData) + } +} + +/// A type which can be deserialized from a toml value. +pub trait Deserialize: Sized { + /// Attempt to deserialize the value. Returns `None` and raises an error on failure. + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option; +} + +impl Deserialize for bool { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + match value.get_ref().as_bool() { + None => { + dcx.span_err(value.span(), "expected a boolean"); + None + }, + x => x, + } + } +} + +macro_rules! impl_deserialize_int { + ($($ty:ident),*) => {$( + impl Deserialize for $ty { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + match value.get_ref().as_integer() { + None => { + dcx.span_err(value.span(), "expected an integer"); + None + }, + Some(x) => match $ty::from_str_radix(x.as_str(), x.radix()) { + Ok(x) => Some(x), + Err(_) => { + dcx.span_err( + value.span(), + format!("integer is not within the expected range ({}..{})", $ty::MIN, $ty::MAX), + ); + None + } + } + } + } + } + )*} +} +impl_deserialize_int!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); + +macro_rules! impl_deserialize_float { + ($($ty:ident),*) => {$( + impl Deserialize for $ty { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + match value.get_ref().as_float() { + None => { + dcx.span_err(value.span(), "expected a number"); + None + }, + Some(x) => match $ty::from_str(x.as_str()) { + Ok(x) => Some(x), + Err(_) => { + dcx.span_err(value.span(), "failed to parse number"); + None + } + } + } + } + } + )*} +} +impl_deserialize_float!(f32, f64); + +impl Deserialize for String { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(x) = value.get_ref().as_str() { + Some(x.into()) + } else { + dcx.span_err(value.span(), "expected a string"); + None + } + } +} + +impl Deserialize for Symbol { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(x) = value.get_ref().as_str() { + Some(Symbol::intern(x)) + } else { + dcx.span_err(value.span(), "expected a string"); + None + } + } +} + +impl Deserialize for RustcVersion { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(x) = value.get_ref().as_str() { + if let Some(x) = parse_version(Symbol::intern(x)) { + Some(x) + } else { + dcx.span_err(value.span(), "failed to parse rust version"); + None + } + } else { + dcx.span_err(value.span(), "expected a version string"); + None + } + } +} + +impl Deserialize for [T; N] { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(values) = value.get_ref().as_array() + && values.len() == N + { + let values = values + .iter() + .filter_map(|x| T::deserialize(dcx, x)) + .collect::>(); + // A value's deserialize impl will have already given an error + values.into_inner().ok() + } else { + dcx.span_err(value.span(), "expected an array of length `{N}`"); + None + } + } +} + +impl Deserialize for Vec { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(values) = value.get_ref().as_array() { + Some(values.iter().filter_map(|x| T::deserialize(dcx, x)).collect()) + } else { + dcx.span_err(value.span(), "expected an array"); + None + } + } +} + +impl Deserialize for HashSet +where + T: Deserialize + Eq + Hash, + S: Default + BuildHasher, +{ + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(values) = value.as_ref().as_array() { + Some(values.iter().filter_map(|x| T::deserialize(dcx, x)).collect()) + } else { + dcx.span_err(value.span(), "expected an array"); + None + } + } +} + +impl Deserialize for HashMap +where + T: Deserialize + Eq + Hash, + S: Default + BuildHasher, +{ + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(values) = value.as_ref().as_array() { + Some( + values + .iter() + .filter_map(|x| T::deserialize(dcx, x).map(|value| (value, dcx.make_sp(x.span())))) + .collect(), + ) + } else { + dcx.span_err(value.span(), "expected an array"); + None + } + } +} + +impl Deserialize for Spanned { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + T::deserialize(dcx, value).map(|x| Spanned { + node: x, + span: dcx.make_sp(value.span()), + }) + } +} + +/// A type which can be deserialized from a toml value with a fallback to a default value. +pub trait DeserializeOrDefault: Sized { + /// Attempt to deserialize the value. Returns the default value and raises an error on failure. + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: T) -> Self; +} + +impl> DeserializeOrDefault for T { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: T) -> Self { + T::deserialize(dcx, value).unwrap_or_else(|| T::from_default(default)) + } +} + +impl DeserializeOrDefault<()> for T { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, (): ()) -> Self { + T::deserialize(dcx, value).unwrap_or_default() + } +} + +impl DeserializeOrDefault<()> for Option { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, (): ()) -> Self { + T::deserialize(dcx, value) + } +} + +pub fn deserialize_array(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: &'static [U]) -> C +where + T: Deserialize + FromDefault, + U: Copy, + C: FromIterator + Extend, +{ + let default_iter = default.iter().map(|&x| T::from_default(x)); + if let Some(values) = value.as_ref().as_array() { + let mut has_default = false; + let mut res: C = values + .iter() + .filter(|x| { + if x.as_ref().as_str().is_some_and(|x| x == "..") { + if has_default { + dcx.span_warn(value.span(), "duplicate `..` item"); + } + has_default = true; + false + } else { + true + } + }) + .filter_map(|x| T::deserialize(dcx, x)) + .collect(); + if has_default { + res.extend(default_iter); + } + res + } else { + dcx.span_err(value.span(), "expected an array"); + default_iter.collect() + } +} + +impl DeserializeOrDefault<&'static [U]> for Vec +where + T: Deserialize + FromDefault, + U: Copy, +{ + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: &'static [U]) -> Self { + deserialize_array(dcx, value, default) + } +} + +impl DeserializeOrDefault<&'static [U]> for HashSet +where + T: Deserialize + FromDefault + Eq + Hash, + U: Copy, + S: Default + BuildHasher, +{ + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: &'static [U]) -> Self { + deserialize_array(dcx, value, default) + } +} + +macro_rules! deserialize_table { + ($dcx:ident, $table:ident, $($name:ident($name_str:literal): $ty:ty,)+) => { + $(let mut $name: Option<$ty> = None;)+ + + for (key, value) in $table.iter() { + match &**key.get_ref() { + $($name_str => { + // Duplicate keys are handled by the toml parser + $name = <$ty as crate::de::Deserialize>::deserialize($dcx, value.into()); + },)+ + _ => { + const NAMES: &[&str] = &[$($name_str),*]; + let sp = $dcx.make_sp(key.span()); + let mut diag = $dcx.inner.struct_span_err(sp, "unknown key"); + if let Some(sugg) = crate::de::find_closest_match(key.as_ref(), NAMES) { + diag.span_suggestion(sp, "did you mean", sugg, Applicability::MaybeIncorrect); + } + diag.note(crate::de::create_value_list_msg($dcx, NAMES)); + diag.emit(); + }, + } + } + } +} diff --git a/src/tools/clippy/clippy_config/src/lib.rs b/src/tools/clippy/clippy_config/src/lib.rs index 0a891e75eb3e9..997262630ea05 100644 --- a/src/tools/clippy/clippy_config/src/lib.rs +++ b/src/tools/clippy/clippy_config/src/lib.rs @@ -1,13 +1,14 @@ -#![feature(rustc_private)] +#![feature(io_error_more, rustc_private)] #![warn( + rust_2018_idioms, trivial_casts, trivial_numeric_casts, - rust_2018_idioms, unused_lifetimes, unused_qualifications )] -#![allow(clippy::must_use_candidate, clippy::missing_panics_doc)] +#![expect(clippy::must_use_candidate)] +extern crate rustc_attr_parsing; extern crate rustc_data_structures; extern crate rustc_errors; extern crate rustc_hir; @@ -15,9 +16,11 @@ extern crate rustc_middle; extern crate rustc_session; extern crate rustc_span; +#[macro_use] +mod de; mod conf; mod metadata; pub mod types; -pub use conf::{Conf, get_configuration_metadata, lookup_conf_file, sanitize_explanation}; -pub use metadata::ClippyConfiguration; +pub use conf::{Conf, sanitize_explanation}; +pub use metadata::ConfMetadata; diff --git a/src/tools/clippy/clippy_config/src/metadata.rs b/src/tools/clippy/clippy_config/src/metadata.rs index 7cbd92a9b7100..740ba3750948b 100644 --- a/src/tools/clippy/clippy_config/src/metadata.rs +++ b/src/tools/clippy/clippy_config/src/metadata.rs @@ -1,16 +1,15 @@ -use itertools::Itertools; -use std::fmt; +use itertools::Itertools as _; +use std::fmt::{self, Display}; -#[derive(Debug, Clone, Default)] -pub struct ClippyConfiguration { - pub name: String, +pub struct ConfMetadata { + pub name: &'static str, pub default: String, pub lints: &'static [&'static str], pub doc: &'static str, - pub deprecation_reason: Option<&'static str>, + pub renamed_to: Option<&'static str>, } -impl fmt::Display for ClippyConfiguration { +impl Display for ConfMetadata { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "- `{}`: {}", self.name, self.doc)?; if !self.default.is_empty() { @@ -20,21 +19,40 @@ impl fmt::Display for ClippyConfiguration { } } -impl ClippyConfiguration { - pub fn to_markdown_paragraph(&self) -> String { - format!( - "## `{}`\n{}\n\n**Default Value:** `{}`\n\n---\n**Affected lints:**\n{}\n\n", - self.name, - self.doc.lines().map(|x| x.strip_prefix(' ').unwrap_or(x)).join("\n"), - self.default, - self.lints.iter().format_with("\n", |name, f| f(&format_args!( - "* [`{name}`](https://rust-lang.github.io/rust-clippy/master/index.html#{name})" - ))), - ) +impl ConfMetadata { + pub fn display_markdown_paragraph(&self) -> impl '_ + Display { + struct S<'a>(&'a ConfMetadata); + impl Display for S<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "## `{}`\n{}\n\n**Default Value:** `{}`\n\n---\n**Affected lints:**\n{}\n\n", + self.0.name, + self.0 + .doc + .lines() + .format_with("\n", |doc, f| f(&doc.strip_prefix(" ").unwrap_or(doc))), + self.0.default, + self.0.lints.iter().format_with("\n", |name, f| f(&format_args!( + "* [`{name}`](https://rust-lang.github.io/rust-clippy/master/index.html#{name})" + ))), + ) + } + } + S(self) } - pub fn to_markdown_link(&self) -> String { - const BOOK_CONFIGS_PATH: &str = "https://doc.rust-lang.org/clippy/lint_configuration.html"; - format!("[`{}`]: {BOOK_CONFIGS_PATH}#{}", self.name, self.name) + pub fn display_markdown_link(&self) -> impl '_ + Display { + struct S<'a>(&'a ConfMetadata); + impl Display for S<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "[`{}`]: https://doc.rust-lang.org/clippy/lint_configuration.html#{}", + self.0.name, self.0.name, + ) + } + } + S(self) } } diff --git a/src/tools/clippy/clippy_config/src/types.rs b/src/tools/clippy/clippy_config/src/types.rs index 8d9326a904b1e..4dc2549c6e233 100644 --- a/src/tools/clippy/clippy_config/src/types.rs +++ b/src/tools/clippy/clippy_config/src/types.rs @@ -1,28 +1,131 @@ +use crate::de::{ + Deserialize, DeserializeOrDefault, DiagCtxt, FromDefault, TomlValue, create_value_list_msg, find_closest_match, +}; use clippy_utils::paths::{PathNS, find_crates, lookup_path}; -use rustc_data_structures::fx::FxHashMap; +use core::fmt::{self, Display}; +use itertools::Itertools as _; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::{Applicability, Diag}; use rustc_hir::PrimTy; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefIdMap; use rustc_middle::ty::TyCtxt; -use rustc_span::{Span, Symbol}; -use serde::de::{self, Deserializer, Visitor}; -use serde::{Deserialize, Serialize, ser}; +use rustc_session::Session; +use rustc_span::{Span, Spanned, Symbol}; use std::collections::HashMap; -use std::fmt; -#[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] +macro_rules! concat_expr { + ($($e:expr)*) => { + concat!($($e),*) + } +} + +macro_rules! name_or_lit { + ($name:ident) => { + stringify!($name) + }; + ($name:ident $lit:literal) => { + $lit + }; +} + +macro_rules! conf_enum { + ( + $(#[$attrs:meta])* + $vis:vis $name:ident {$( + $(#[$var_attrs:meta])* + $var_name:ident $(($var_lit:literal))?, + )*} + ) => { + $(#[$attrs])* + #[derive(Clone, Copy)] + $vis enum $name {$( + $(#[$var_attrs])* + $var_name, + )*} + impl $name { + const NAMES: &[&'static str] = &[$(name_or_lit!($var_name $($var_lit)?)),*]; + #[allow(dead_code)] + const COUNT: usize = { + enum __ITEMS__ { $($var_name,)* __COUNT__ } + __ITEMS__::__COUNT__ as usize + }; + + pub fn name(self) -> &'static str { + Self::NAMES[self as usize] + } + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str) -> Option { + match s { + $(name_or_lit!($var_name $($var_lit)?) => Some(Self::$var_name),)* + _ => None, + } + } + } + impl FromDefault<$name> for $name { + fn from_default(default: $name) -> Self { + default + } + fn display_default(default: $name) -> impl Display { + String::display_default(default.name()) + } + } + impl Deserialize for $name { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + let Some(s) = value.get_ref().as_str() else { + dcx.span_err(value.span(), "expected a string"); + return None; + }; + let x = Self::from_str(s); + if x.is_none() { + let sp = dcx.make_sp(value.span()); + let mut diag = dcx.inner.struct_span_err( + sp, + concat_expr!("expected one of: " $("`" name_or_lit!($var_name $($var_lit)?) "`")", "*), + ); + if let Some(sugg) = find_closest_match(s, Self::NAMES) { + diag.span_suggestion(sp, "did you mean", sugg, Applicability::MaybeIncorrect); + } + diag.note(create_value_list_msg(dcx, Self::NAMES)); + diag.emit(); + } + x + } + } + }; +} pub struct Rename { pub path: String, pub rename: String, } +impl Deserialize for Rename { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(table) = value.as_ref().as_table() { + deserialize_table!(dcx, table, + path("path"): String, + rename("rename"): String, + ); + let Some(path) = path else { + dcx.span_err(value.span().clone(), "missing required field `path`"); + return None; + }; + let Some(rename) = rename else { + dcx.span_err(value.span().clone(), "missing required field `rename`"); + return None; + }; + Some(Rename { path, rename }) + } else { + dcx.span_err(value.span(), "expected a table"); + None + } + } +} + pub type DisallowedPathWithoutReplacement = DisallowedPath; -#[derive(Debug, Serialize)] pub struct DisallowedPath { - path: String, + path: Spanned, reason: Option, replacement: Option, /// Setting `allow_invalid` to true suppresses a warning if `path` does not refer to an existing @@ -31,50 +134,11 @@ pub struct DisallowedPath { /// This could be useful when conditional compilation is used, or when a clippy.toml file is /// shared among multiple projects. allow_invalid: bool, - /// The span of the `DisallowedPath`. - /// - /// Used for diagnostics. - #[serde(skip_serializing)] - span: Span, -} - -impl<'de, const REPLACEMENT_ALLOWED: bool> Deserialize<'de> for DisallowedPath { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let enum_ = DisallowedPathEnum::deserialize(deserializer)?; - if !REPLACEMENT_ALLOWED && enum_.replacement().is_some() { - return Err(de::Error::custom("replacement not allowed for this configuration")); - } - Ok(Self { - path: enum_.path().to_owned(), - reason: enum_.reason().map(ToOwned::to_owned), - replacement: enum_.replacement().map(ToOwned::to_owned), - allow_invalid: enum_.allow_invalid(), - span: Span::default(), - }) - } -} - -// `DisallowedPathEnum` is an implementation detail to enable the `Deserialize` implementation just -// above. `DisallowedPathEnum` is not meant to be used outside of this file. -#[derive(Debug, Deserialize, Serialize)] -#[serde(untagged, deny_unknown_fields)] -enum DisallowedPathEnum { - Simple(String), - WithReason { - path: String, - reason: Option, - replacement: Option, - #[serde(rename = "allow-invalid")] - allow_invalid: Option, - }, } impl DisallowedPath { pub fn path(&self) -> &str { - &self.path + &self.path.node } pub fn diag_amendment(&self, span: Span) -> impl FnOnce(&mut Diag<'_, ()>) { @@ -91,41 +155,75 @@ impl DisallowedPath { } } } - - pub fn span(&self) -> Span { - self.span - } - - pub fn set_span(&mut self, span: Span) { - self.span = span; - } } -impl DisallowedPathEnum { - pub fn path(&self) -> &str { - let (Self::Simple(path) | Self::WithReason { path, .. }) = self; - - path - } - - fn reason(&self) -> Option<&str> { - match &self { - Self::WithReason { reason, .. } => reason.as_deref(), - Self::Simple(_) => None, - } - } - - fn replacement(&self) -> Option<&str> { - match &self { - Self::WithReason { replacement, .. } => replacement.as_deref(), - Self::Simple(_) => None, +impl Deserialize for DisallowedPath { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(s) = value.as_ref().as_str() { + Some(DisallowedPath { + path: Spanned { + node: s.into(), + span: dcx.make_sp(value.span()), + }, + reason: None, + replacement: None, + allow_invalid: false, + }) + } else if let Some(table) = value.as_ref().as_table() { + deserialize_table!(dcx, table, + path("path"): Spanned, + reason("reason"): String, + allow_invalid("allow-invalid"): bool, + ); + let Some(path) = path else { + dcx.span_err(value.span(), "missing required field `path`"); + return None; + }; + Some(DisallowedPath { + path, + reason, + replacement: None, + allow_invalid: allow_invalid.unwrap_or(false), + }) + } else { + dcx.span_err(value.span(), "expected either a string or an inline table"); + None } } +} - fn allow_invalid(&self) -> bool { - match &self { - Self::WithReason { allow_invalid, .. } => allow_invalid.unwrap_or_default(), - Self::Simple(_) => false, +impl Deserialize for DisallowedPath { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(s) = value.as_ref().as_str() { + Some(DisallowedPath { + path: Spanned { + node: s.into(), + span: dcx.make_sp(value.span()), + }, + reason: None, + replacement: None, + allow_invalid: false, + }) + } else if let Some(table) = value.as_ref().as_table() { + deserialize_table!(dcx, table, + path("path"): Spanned, + reason("reason"): String, + replacement("replacement"): String, + allow_invalid("allow-invalid"): bool, + ); + let Some(path) = path else { + dcx.span_err(value.span(), "missing required field `path`"); + return None; + }; + Some(DisallowedPath { + path, + reason, + replacement, + allow_invalid: allow_invalid.unwrap_or(false), + }) + } else { + dcx.span_err(value.span(), "expected either a string or an inline table"); + None } } } @@ -147,7 +245,7 @@ pub fn create_disallowed_map( let mut prim_tys: FxHashMap)> = FxHashMap::default(); for disallowed_path in disallowed_paths { - let path = disallowed_path.path(); + let path = &*disallowed_path.path.node; let sym_path: Vec = path.split("::").map(Symbol::intern).collect(); let mut resolutions = lookup_path(tcx, ns, &sym_path); resolutions.retain(|&def_id| def_kind_predicate(tcx.def_kind(def_id))); @@ -179,7 +277,7 @@ pub fn create_disallowed_map( }; tcx.sess .dcx() - .struct_span_warn(disallowed_path.span(), message) + .struct_span_warn(disallowed_path.path.span, message) .with_help("add `allow-invalid = true` to the entry to suppress this warning") .emit(); } @@ -195,87 +293,92 @@ pub fn create_disallowed_map( (def_ids, prim_tys) } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub enum MatchLintBehaviour { - AllTypes, - WellKnownTypes, - Never, +conf_enum! { + #[derive(PartialEq, Eq)] + pub MatchLintBehaviour { + AllTypes, + WellKnownTypes, + Never, + } +} + +enum BraceKind { + Brace, + Bracket, + Paren, +} + +impl Deserialize for BraceKind { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + let msg = if let Some(s) = value.as_ref().as_str() { + match s { + "{" | "{}" => return Some(BraceKind::Brace), + "[" | "[]" => return Some(BraceKind::Bracket), + "(" | "()" => return Some(BraceKind::Paren), + _ => "unknown value", + } + } else { + "expected a string" + }; + let mut diag = dcx.inner.struct_span_err(dcx.make_sp(value.span()), msg); + diag.note("possible values: `()`, `[]`, `{}`"); + diag.emit(); + None + } } -#[derive(Debug)] pub struct MacroMatcher { pub name: String, pub braces: (char, char), } -impl<'de> Deserialize<'de> for MacroMatcher { - fn deserialize(deser: D) -> Result - where - D: Deserializer<'de>, - { - #[derive(Deserialize)] - #[serde(field_identifier, rename_all = "lowercase")] - enum Field { - Name, - Brace, - } - struct MacVisitor; - impl<'de> Visitor<'de> for MacVisitor { - type Value = MacroMatcher; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("struct MacroMatcher") - } - - fn visit_map(self, mut map: V) -> Result - where - V: de::MapAccess<'de>, - { - let mut name = None; - let mut brace: Option = None; - while let Some(key) = map.next_key()? { - match key { - Field::Name => { - if name.is_some() { - return Err(de::Error::duplicate_field("name")); - } - name = Some(map.next_value()?); - }, - Field::Brace => { - if brace.is_some() { - return Err(de::Error::duplicate_field("brace")); - } - brace = Some(map.next_value()?); - }, - } - } - let name = name.ok_or_else(|| de::Error::missing_field("name"))?; - let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?; - Ok(MacroMatcher { - name, - braces: [('(', ')'), ('{', '}'), ('[', ']')] - .into_iter() - .find(|b| b.0 == brace) - .map(|(o, c)| (o.to_owned(), c.to_owned())) - .ok_or_else(|| de::Error::custom(format!("expected one of `(`, `{{`, `[` found `{brace}`")))?, - }) - } +impl Deserialize for MacroMatcher { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + if let Some(table) = value.as_ref().as_table() { + deserialize_table!(dcx, table, + name("name"): String, + brace("brace"): BraceKind, + ); + let Some(name) = name else { + dcx.span_err(value.span(), "missing required field `name`"); + return None; + }; + let Some(brace) = brace else { + dcx.span_err(value.span(), "missing required field `brace`"); + return None; + }; + Some(MacroMatcher { + name, + braces: match brace { + BraceKind::Brace => ('{', '}'), + BraceKind::Bracket => ('[', ']'), + BraceKind::Paren => ('(', ')'), + }, + }) + } else { + dcx.span_err(value.span(), "expected an inline table"); + None } + } +} - const FIELDS: &[&str] = &["name", "brace"]; - deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor) +conf_enum! { + pub PubUnderscoreFieldsBehaviour { + PubliclyExported, + AllPubFields, } } -/// Represents the item categories that can be ordered by the source ordering lint. -#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum SourceItemOrderingCategory { - Enum, - Impl, - Module, - Struct, - Trait, +conf_enum! { + /// Represents the item categories that can be ordered by the source ordering lint. + #[derive(Debug, PartialEq, Eq, Hash)] + pub SourceItemOrderingCategory { + Enum("enum"), + Impl("impl"), + Module("module"), + Struct("struct"), + Trait("trait"), + } } /// Represents which item categories are enabled for ordering. @@ -285,76 +388,78 @@ pub enum SourceItemOrderingCategory { pub struct SourceItemOrdering(Vec); impl SourceItemOrdering { - pub fn contains(&self, category: &SourceItemOrderingCategory) -> bool { - self.0.contains(category) - } -} - -impl From for SourceItemOrdering -where - T: Into>, -{ - fn from(value: T) -> Self { - Self(value.into()) + pub fn contains(&self, category: SourceItemOrderingCategory) -> bool { + self.0.contains(&category) } } -impl core::fmt::Debug for SourceItemOrdering { +impl fmt::Debug for SourceItemOrdering { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } -impl<'de> Deserialize<'de> for SourceItemOrdering { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let items = Vec::::deserialize(deserializer)?; - let mut items_set = std::collections::HashSet::new(); +impl Deserialize for SourceItemOrdering { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + let items = Vec::::deserialize(dcx, value)?; + let mut items_set = FxHashSet::default(); for item in &items { if items_set.contains(item) { - return Err(de::Error::custom(format!( - "The category \"{item:?}\" was enabled more than once in the source ordering configuration." - ))); + dcx.span_err( + value.span(), + format!( + "The category \"{}\" was enabled more than once in the source ordering configuration.", + item.name() + ), + ); + return None; } items_set.insert(item); } - - Ok(Self(items)) + Some(SourceItemOrdering(items)) } } - -impl Serialize for SourceItemOrdering { - fn serialize(&self, serializer: S) -> Result - where - S: ser::Serializer, - { - self.0.serialize(serializer) +impl FromDefault<()> for SourceItemOrdering { + fn from_default((): ()) -> Self { + Self(vec![ + SourceItemOrderingCategory::Enum, + SourceItemOrderingCategory::Impl, + SourceItemOrderingCategory::Module, + SourceItemOrderingCategory::Struct, + SourceItemOrderingCategory::Trait, + ]) + } + fn display_default((): ()) -> impl Display { + r#"["enum", "impl", "module", "struct", "trait"]"# + } +} +impl DeserializeOrDefault<()> for SourceItemOrdering { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: ()) -> Self { + Self::deserialize(dcx, value).unwrap_or_else(|| Self::from_default(default)) } } -/// Represents the items that can occur within a module. -#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum SourceItemOrderingModuleItemKind { - ExternCrate, - Mod, - ForeignMod, - Use, - Macro, - GlobalAsm, - Static, - Const, - TyAlias, - Enum, - Struct, - Union, - Trait, - TraitAlias, - Impl, - Fn, +conf_enum! { + #[derive(Debug, PartialEq, Eq, Hash)] + pub SourceItemOrderingModuleItemKind { + ExternCrate("extern_crate"), + Mod("mod"), + ForeignMod("foreign_mod"), + Use("use"), + Macro("macro"), + GlobalAsm("global_asm"), + Static("static"), + Const("const"), + TyAlias("ty_alias"), + Enum("enum"), + Struct("struct"), + Union("union"), + Trait("trait"), + TraitAlias("trait_alias"), + Impl("impl"), + Fn("fn"), + } } impl SourceItemOrderingModuleItemKind { @@ -393,14 +498,20 @@ pub struct SourceItemOrderingModuleItemGroupings { back_lut: HashMap, } +impl fmt::Debug for SourceItemOrderingModuleItemGroupings { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.groups.fmt(f) + } +} + impl SourceItemOrderingModuleItemGroupings { fn build_lut( groups: &[(String, Vec)], ) -> HashMap { let mut lut = HashMap::new(); for (group_index, (_, items)) in groups.iter().enumerate() { - for item in items { - lut.insert(item.clone(), group_index); + for &item in items { + lut.insert(item, group_index); } } lut @@ -411,15 +522,15 @@ impl SourceItemOrderingModuleItemGroupings { ) -> HashMap { let mut lut = HashMap::new(); for (group_name, items) in groups { - for item in items { - lut.insert(item.clone(), group_name.clone()); + for &item in items { + lut.insert(item, group_name.clone()); } } lut } - pub fn grouping_name_of(&self, item: &SourceItemOrderingModuleItemKind) -> Option<&String> { - self.back_lut.get(item) + pub fn grouping_name_of(&self, item: SourceItemOrderingModuleItemKind) -> Option<&String> { + self.back_lut.get(&item) } pub fn grouping_names(&self) -> Vec { @@ -430,33 +541,32 @@ impl SourceItemOrderingModuleItemGroupings { self.groups.iter().any(|(g, _)| g == grouping) } - pub fn module_level_order_of(&self, item: &SourceItemOrderingModuleItemKind) -> Option { - self.lut.get(item).copied() + pub fn module_level_order_of(&self, item: SourceItemOrderingModuleItemKind) -> Option { + self.lut.get(&item).copied() } } -impl From<&[(&str, &[SourceItemOrderingModuleItemKind])]> for SourceItemOrderingModuleItemGroupings { - fn from(value: &[(&str, &[SourceItemOrderingModuleItemKind])]) -> Self { - let groups: Vec<(String, Vec)> = - value.iter().map(|item| (item.0.to_string(), item.1.to_vec())).collect(); - let lut = Self::build_lut(&groups); - let back_lut = Self::build_back_lut(&groups); - Self { groups, lut, back_lut } - } -} - -impl core::fmt::Debug for SourceItemOrderingModuleItemGroupings { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.groups.fmt(f) - } -} +impl Deserialize for SourceItemOrderingModuleItemGroupings { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + let Some(values) = value.as_ref().as_array() else { + dcx.span_err(value.span(), "expected an array"); + return None; + }; + let mut groups = Vec::with_capacity(values.len()); + for value in values { + if let Some(values) = value.as_ref().as_array() + && let [value1, value2] = &**values + { + groups.push(( + String::deserialize(dcx, value1)?, + Vec::::deserialize(dcx, value2)?, + )); + } else { + dcx.span_err(value.span(), "expected an array of length two"); + return None; + } + } -impl<'de> Deserialize<'de> for SourceItemOrderingModuleItemGroupings { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let groups = Vec::<(String, Vec)>::deserialize(deserializer)?; let items_total: usize = groups.iter().map(|(_, v)| v.len()).sum(); let lut = Self::build_lut(&groups); let back_lut = Self::build_back_lut(&groups); @@ -469,51 +579,134 @@ impl<'de> Deserialize<'de> for SourceItemOrderingModuleItemGroupings { let all_items = SourceItemOrderingModuleItemKind::all_variants(); if expected_items.is_empty() && items_total == all_items.len() { let Some(use_group_index) = lut.get(&SourceItemOrderingModuleItemKind::Use) else { - return Err(de::Error::custom("Error in internal LUT.")); + dcx.span_err(value.span(), "Error in internal LUT."); + return None; }; let Some((_, use_group_items)) = groups.get(*use_group_index) else { - return Err(de::Error::custom("Error in internal LUT.")); + dcx.span_err(value.span(), "Error in internal LUT."); + return None; }; if use_group_items.len() > 1 { - return Err(de::Error::custom( + dcx.span_err( + value.span(), "The group containing the \"use\" item kind may not contain any other item kinds. \ The \"use\" items will (generally) be sorted by rustfmt already. \ Therefore it makes no sense to implement linting rules that may conflict with rustfmt.", - )); + ); + return None; } - - Ok(Self { groups, lut, back_lut }) + Some(Self { groups, lut, back_lut }) } else if items_total != all_items.len() { - Err(de::Error::custom(format!( - "Some module item kinds were configured more than once, or were missing, in the source ordering configuration. \ - The module item kinds are: {all_items:?}" - ))) + dcx.span_err(value.span(), + format!( + "Some module item kinds were configured more than once, or were missing, in the source ordering configuration. \ + The module item kinds are: {all_items:?}" + ) + ); + None } else { - Err(de::Error::custom(format!( - "Not all module item kinds were part of the configured source ordering rule. \ - All item kinds must be provided in the config, otherwise the required source ordering would remain ambiguous. \ - The module item kinds are: {all_items:?}" - ))) + dcx.span_err(value.span(), + format!( + "Not all module item kinds were part of the configured source ordering rule. \ + All item kinds must be provided in the config, otherwise the required source ordering would remain ambiguous. \ + The module item kinds are: {all_items:?}" + ) + ); + None } } } - -impl Serialize for SourceItemOrderingModuleItemGroupings { - fn serialize(&self, serializer: S) -> Result - where - S: ser::Serializer, - { - self.groups.serialize(serializer) +impl FromDefault<()> for SourceItemOrderingModuleItemGroupings { + fn from_default((): ()) -> Self { + Self { + groups: vec![ + ( + "modules".into(), + vec![ + SourceItemOrderingModuleItemKind::ExternCrate, + SourceItemOrderingModuleItemKind::Mod, + SourceItemOrderingModuleItemKind::ForeignMod, + ], + ), + ("use".into(), vec![SourceItemOrderingModuleItemKind::Use]), + ("macros".into(), vec![SourceItemOrderingModuleItemKind::Macro]), + ("global_asm".into(), vec![SourceItemOrderingModuleItemKind::GlobalAsm]), + ( + "UPPER_SNAKE_CASE".into(), + vec![ + SourceItemOrderingModuleItemKind::Static, + SourceItemOrderingModuleItemKind::Const, + ], + ), + ( + "PascalCase".into(), + vec![ + SourceItemOrderingModuleItemKind::TyAlias, + SourceItemOrderingModuleItemKind::Enum, + SourceItemOrderingModuleItemKind::Struct, + SourceItemOrderingModuleItemKind::Union, + SourceItemOrderingModuleItemKind::Trait, + SourceItemOrderingModuleItemKind::TraitAlias, + SourceItemOrderingModuleItemKind::Impl, + ], + ), + ("lower_snake_case".into(), vec![SourceItemOrderingModuleItemKind::Fn]), + ], + lut: HashMap::from_iter([ + (SourceItemOrderingModuleItemKind::ExternCrate, 0), + (SourceItemOrderingModuleItemKind::Mod, 0), + (SourceItemOrderingModuleItemKind::ForeignMod, 0), + (SourceItemOrderingModuleItemKind::Use, 1), + (SourceItemOrderingModuleItemKind::Macro, 2), + (SourceItemOrderingModuleItemKind::GlobalAsm, 3), + (SourceItemOrderingModuleItemKind::Static, 4), + (SourceItemOrderingModuleItemKind::Const, 4), + (SourceItemOrderingModuleItemKind::TyAlias, 5), + (SourceItemOrderingModuleItemKind::Enum, 5), + (SourceItemOrderingModuleItemKind::Struct, 5), + (SourceItemOrderingModuleItemKind::Union, 5), + (SourceItemOrderingModuleItemKind::Trait, 5), + (SourceItemOrderingModuleItemKind::TraitAlias, 5), + (SourceItemOrderingModuleItemKind::Impl, 5), + (SourceItemOrderingModuleItemKind::Fn, 6), + ]), + back_lut: HashMap::from_iter([ + (SourceItemOrderingModuleItemKind::ExternCrate, "modules".into()), + (SourceItemOrderingModuleItemKind::Mod, "modules".into()), + (SourceItemOrderingModuleItemKind::ForeignMod, "modules".into()), + (SourceItemOrderingModuleItemKind::Use, "use".into()), + (SourceItemOrderingModuleItemKind::Macro, "macros".into()), + (SourceItemOrderingModuleItemKind::GlobalAsm, "global_asm".into()), + (SourceItemOrderingModuleItemKind::Static, "UPPER_SNAKE_CASE".into()), + (SourceItemOrderingModuleItemKind::Const, "UPPER_SNAKE_CASE".into()), + (SourceItemOrderingModuleItemKind::TyAlias, "PascalCase".into()), + (SourceItemOrderingModuleItemKind::Enum, "PascalCase".into()), + (SourceItemOrderingModuleItemKind::Struct, "PascalCase".into()), + (SourceItemOrderingModuleItemKind::Union, "PascalCase".into()), + (SourceItemOrderingModuleItemKind::Trait, "PascalCase".into()), + (SourceItemOrderingModuleItemKind::TraitAlias, "PascalCase".into()), + (SourceItemOrderingModuleItemKind::Impl, "PascalCase".into()), + (SourceItemOrderingModuleItemKind::Fn, "lower_snake_case".into()), + ]), + } + } + fn display_default((): ()) -> impl Display { + r#"[["modules", ["extern_crate", "mod", "foreign_mod"]], ["use", ["use"]], ["macros", ["macro"]], ["global_asm", ["global_asm"]], ["UPPER_SNAKE_CASE", ["static", "const"]], ["PascalCase", ["ty_alias", "enum", "struct", "union", "trait", "trait_alias", "impl"]], ["lower_snake_case", ["fn"]]]"# + } +} +impl DeserializeOrDefault<()> for SourceItemOrderingModuleItemGroupings { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: ()) -> Self { + Self::deserialize(dcx, value).unwrap_or_else(|| Self::from_default(default)) } } -/// Represents all kinds of trait associated items. -#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum SourceItemOrderingTraitAssocItemKind { - Const, - Fn, - Type, +conf_enum! { + #[derive(Debug, PartialEq)] + pub SourceItemOrderingTraitAssocItemKind { + Const("const"), + Fn("fn"), + Type("type"), + } } impl SourceItemOrderingTraitAssocItemKind { @@ -534,33 +727,21 @@ impl SourceItemOrderingTraitAssocItemKind { #[derive(Clone)] pub struct SourceItemOrderingTraitAssocItemKinds(Vec); -impl SourceItemOrderingTraitAssocItemKinds { - pub fn index_of(&self, item: &SourceItemOrderingTraitAssocItemKind) -> Option { - self.0.iter().position(|i| i == item) - } -} - -impl From for SourceItemOrderingTraitAssocItemKinds -where - T: Into>, -{ - fn from(value: T) -> Self { - Self(value.into()) +impl fmt::Debug for SourceItemOrderingTraitAssocItemKinds { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) } } -impl core::fmt::Debug for SourceItemOrderingTraitAssocItemKinds { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(f) +impl SourceItemOrderingTraitAssocItemKinds { + pub fn index_of(&self, item: SourceItemOrderingTraitAssocItemKind) -> Option { + self.0.iter().position(|&i| i == item) } } -impl<'de> Deserialize<'de> for SourceItemOrderingTraitAssocItemKinds { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let items = Vec::::deserialize(deserializer)?; +impl Deserialize for SourceItemOrderingTraitAssocItemKinds { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + let items = Vec::::deserialize(dcx, value)?; let mut expected_items = SourceItemOrderingTraitAssocItemKind::all_variants(); for item in &items { @@ -569,28 +750,44 @@ impl<'de> Deserialize<'de> for SourceItemOrderingTraitAssocItemKinds { let all_items = SourceItemOrderingTraitAssocItemKind::all_variants(); if expected_items.is_empty() && items.len() == all_items.len() { - Ok(Self(items)) + Some(Self(items)) } else if items.len() != all_items.len() { - Err(de::Error::custom(format!( - "Some trait associated item kinds were configured more than once, or were missing, in the source ordering configuration. \ - The trait associated item kinds are: {all_items:?}", - ))) + dcx.span_err( + value.span(), + format!( + "Some trait associated item kinds were configured more than once, or were missing, in the source ordering configuration. \ + The trait associated item kinds are: {all_items:?}", + ) + ); + None } else { - Err(de::Error::custom(format!( - "Not all trait associated item kinds were part of the configured source ordering rule. \ - All item kinds must be provided in the config, otherwise the required source ordering would remain ambiguous. \ - The trait associated item kinds are: {all_items:?}" - ))) + dcx.span_err( + value.span(), + format!( + "Not all trait associated item kinds were part of the configured source ordering rule. \ + All item kinds must be provided in the config, otherwise the required source ordering would remain ambiguous. \ + The trait associated item kinds are: {all_items:?}" + ) + ); + None } } } - -impl Serialize for SourceItemOrderingTraitAssocItemKinds { - fn serialize(&self, serializer: S) -> Result - where - S: ser::Serializer, - { - self.0.serialize(serializer) +impl FromDefault<()> for SourceItemOrderingTraitAssocItemKinds { + fn from_default((): ()) -> Self { + Self(vec![ + SourceItemOrderingTraitAssocItemKind::Const, + SourceItemOrderingTraitAssocItemKind::Type, + SourceItemOrderingTraitAssocItemKind::Fn, + ]) + } + fn display_default((): ()) -> impl Display { + r#"["const", "type", "fn"]"# + } +} +impl DeserializeOrDefault<()> for SourceItemOrderingTraitAssocItemKinds { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: ()) -> Self { + Self::deserialize(dcx, value).unwrap_or_else(|| Self::from_default(default)) } } @@ -610,7 +807,7 @@ pub enum SourceItemOrderingWithinModuleItemGroupings { None, /// Only the specified groupings should have their order checked. - Custom(Vec), + Custom(Vec>), } impl SourceItemOrderingWithinModuleItemGroupings { @@ -618,91 +815,97 @@ impl SourceItemOrderingWithinModuleItemGroupings { match self { SourceItemOrderingWithinModuleItemGroupings::All => true, SourceItemOrderingWithinModuleItemGroupings::None => false, - SourceItemOrderingWithinModuleItemGroupings::Custom(groups) => groups.contains(grouping_name), + SourceItemOrderingWithinModuleItemGroupings::Custom(groups) => { + groups.iter().any(|x| x.node == *grouping_name) + }, } } -} -/// Helper struct for deserializing the [`SourceItemOrderingWithinModuleItemGroupings`]. -#[derive(Deserialize)] -#[serde(untagged)] -enum StringOrVecOfString { - String(String), - Vec(Vec), + pub fn check_groupings(&self, sess: &Session, module_item_order_groupings: &SourceItemOrderingModuleItemGroupings) { + if let SourceItemOrderingWithinModuleItemGroupings::Custom(groupings) = self { + for grouping in groupings { + if !module_item_order_groupings.is_grouping(&grouping.node) { + // Since this isn't fixable by rustfix, don't emit a `Suggestion`. This just adds some useful + // info for the user instead. + let names = module_item_order_groupings + .groups + .iter() + .map(|(x, _)| &**x) + .collect::>(); + let suggestion = find_closest_match(&grouping.node, &names) + .map(|s| format!(" perhaps you meant `{s}`?")) + .unwrap_or_default(); + let names = names.iter().map(|s| format!("`{s}`")).join(", "); + sess.dcx().span_err(grouping.span, format!( + "unknown ordering group: `{}` was not specified in `module-items-ordered-within-groupings`,{suggestion} expected one of: {names}", + grouping.node, + )); + } + } + } + } } -impl<'de> Deserialize<'de> for SourceItemOrderingWithinModuleItemGroupings { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let description = "The available options for configuring an ordering within module item groups are: \ - \"all\", \"none\", or a list of module item group names \ - (as configured with the `module-item-order-groupings` configuration option)."; - - match StringOrVecOfString::deserialize(deserializer) { - Ok(StringOrVecOfString::String(preset)) if preset == "all" => { - Ok(SourceItemOrderingWithinModuleItemGroupings::All) - }, - Ok(StringOrVecOfString::String(preset)) if preset == "none" => { - Ok(SourceItemOrderingWithinModuleItemGroupings::None) +impl Deserialize for SourceItemOrderingWithinModuleItemGroupings { + fn deserialize(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>) -> Option { + match value.as_ref() { + toml::de::DeValue::String(str_value) => match &**str_value { + "all" => Some(Self::All), + "none" => Some(Self::None), + _ => { + dcx.span_err(value.span(), "expected: `all`, `none` or a list of category names"); + None + }, }, - Ok(StringOrVecOfString::String(preset)) => Err(de::Error::custom(format!( - "Unknown configuration option: {preset}.\n{description}" - ))), - Ok(StringOrVecOfString::Vec(groupings)) => { - Ok(SourceItemOrderingWithinModuleItemGroupings::Custom(groupings)) + toml::de::DeValue::Array(_) => Vec::deserialize(dcx, value).map(Self::Custom), + _ => { + dcx.span_err(value.span(), "expected a string or an array of strings"); + None }, - Err(e) => Err(de::Error::custom(format!("{e}\n{description}"))), } } } - -impl Serialize for SourceItemOrderingWithinModuleItemGroupings { - fn serialize(&self, serializer: S) -> Result - where - S: ser::Serializer, - { - match self { - SourceItemOrderingWithinModuleItemGroupings::All => serializer.serialize_str("all"), - SourceItemOrderingWithinModuleItemGroupings::None => serializer.serialize_str("none"), - SourceItemOrderingWithinModuleItemGroupings::Custom(vec) => vec.serialize(serializer), - } +impl FromDefault<()> for SourceItemOrderingWithinModuleItemGroupings { + fn from_default((): ()) -> Self { + Self::None + } + fn display_default((): ()) -> impl Display { + r#""none""# } } - -// these impls are never actually called but are used by the various config options that default to -// empty lists -macro_rules! unimplemented_serialize { - ($($t:ty,)*) => { - $( - impl Serialize for $t { - fn serialize(&self, _serializer: S) -> Result - where - S: ser::Serializer, - { - Err(ser::Error::custom("unimplemented")) - } - } - )* +impl DeserializeOrDefault<()> for SourceItemOrderingWithinModuleItemGroupings { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: ()) -> Self { + Self::deserialize(dcx, value).unwrap_or_else(|| Self::from_default(default)) } } -unimplemented_serialize! { - Rename, - MacroMatcher, +conf_enum! { + #[derive(Debug, PartialEq, Eq, Hash)] + pub InherentImplLintScope { + Crate("crate"), + File("file"), + Module("module"), + } } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub enum PubUnderscoreFieldsBehaviour { - PubliclyExported, - AllPubFields, +conf_enum! { + #[derive(Debug, PartialEq, Eq, Hash)] + pub TraitImplItemOrder { + Alphabetical("alphabetical"), + TraitItemOrdering("trait_item_ordering"), + AlphabeticalOrTraitItemOrdering("alphabetical_or_trait_item_ordering"), + } } - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum InherentImplLintScope { - Crate, - File, - Module, +impl FromDefault<()> for TraitImplItemOrder { + fn from_default((): ()) -> Self { + Self::Alphabetical + } + fn display_default((): ()) -> impl Display { + r#""alphabetical""# + } +} +impl DeserializeOrDefault<()> for TraitImplItemOrder { + fn deserialize_or_default(dcx: &DiagCtxt<'_>, value: &TomlValue<'_>, default: ()) -> Self { + Self::deserialize(dcx, value).unwrap_or_else(|| Self::from_default(default)) + } } diff --git a/src/tools/clippy/clippy_dev/src/deprecate_lint.rs b/src/tools/clippy/clippy_dev/src/deprecate_lint.rs index bee7508dabb9a..616245ac99a71 100644 --- a/src/tools/clippy/clippy_dev/src/deprecate_lint.rs +++ b/src/tools/clippy/clippy_dev/src/deprecate_lint.rs @@ -55,7 +55,7 @@ pub fn deprecate<'cx>(cx: ParseCx<'cx>, clippy_version: Version, name: &'cx str, if remove_lint_declaration(name, &mod_path, &mut lints).unwrap_or(false) { generate_lint_files(UpdateMode::Change, &lints, &deprecated_lints, &renamed_lints); println!("info: `{name}` has successfully been deprecated"); - println!("note: you must run `cargo uitest` to update the test results"); + println!("note: you must run `cargo uibless` to update the test results"); } else { eprintln!("error: lint not found"); } @@ -107,7 +107,7 @@ pub fn uplift<'cx, 'env: 'cx>(cx: ParseCx<'cx>, clippy_version: Version, old_nam if remove_lint_declaration(old_name, &mod_path, &mut lints).unwrap_or(false) { generate_lint_files(UpdateMode::Change, &lints, &deprecated_lints, &renamed_lints); println!("info: `{old_name}` has successfully been uplifted"); - println!("note: you must run `cargo uitest` to update the test results"); + println!("note: you must run `cargo uibless` to update the test results"); } else { eprintln!("error: lint not found"); } diff --git a/src/tools/clippy/clippy_dev/src/dogfood.rs b/src/tools/clippy/clippy_dev/src/dogfood.rs index 9eb323eaef5aa..1adb846212f53 100644 --- a/src/tools/clippy/clippy_dev/src/dogfood.rs +++ b/src/tools/clippy/clippy_dev/src/dogfood.rs @@ -1,5 +1,5 @@ use crate::utils::{cargo_cmd, run_exit_on_err}; -use itertools::Itertools; +use itertools::Itertools as _; /// # Panics /// diff --git a/src/tools/clippy/clippy_dev/src/fmt.rs b/src/tools/clippy/clippy_dev/src/fmt.rs index 8a7150052f031..ba09dca6abd78 100644 --- a/src/tools/clippy/clippy_dev/src/fmt.rs +++ b/src/tools/clippy/clippy_dev/src/fmt.rs @@ -5,11 +5,11 @@ use crate::utils::{ ErrAction, FileUpdater, UpdateMode, UpdateStatus, expect_action, run_with_output, split_args_for_threads, walk_dir_no_dot_or_target, }; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; -use std::fmt::Write; +use std::fmt::Write as _; use std::fs; -use std::io::{self, Read}; +use std::io::{self, Read as _}; use std::ops::ControlFlow; use std::path::PathBuf; use std::process::{self, Command, Stdio}; diff --git a/src/tools/clippy/clippy_dev/src/generate.rs b/src/tools/clippy/clippy_dev/src/generate.rs index c35e718fa7913..f1c3375e1c7c1 100644 --- a/src/tools/clippy/clippy_dev/src/generate.rs +++ b/src/tools/clippy/clippy_dev/src/generate.rs @@ -2,9 +2,9 @@ use crate::parse::cursor::Cursor; use crate::parse::{Lint, LintData, LintPass, VecBuf}; use crate::utils::{FileUpdater, UpdateMode, UpdateStatus, slice_groups, update_text_region_fn}; use core::range::Range; -use itertools::Itertools; +use itertools::Itertools as _; use std::collections::HashSet; -use std::fmt::Write; +use std::fmt::Write as _; use std::path::{self, Path}; const GENERATED_FILE_COMMENT: &str = "// This file was generated by `cargo dev update_lints`.\n\ diff --git a/src/tools/clippy/clippy_dev/src/lib.rs b/src/tools/clippy/clippy_dev/src/lib.rs index b707c2cea6e5b..70783118efedf 100644 --- a/src/tools/clippy/clippy_dev/src/lib.rs +++ b/src/tools/clippy/clippy_dev/src/lib.rs @@ -7,13 +7,13 @@ rustc_private )] #![warn( + rust_2018_idioms, trivial_casts, trivial_numeric_casts, - rust_2018_idioms, unused_lifetimes, unused_qualifications )] -#![allow(clippy::case_sensitive_file_extension_comparisons, clippy::missing_panics_doc)] +#![expect(clippy::missing_panics_doc)] extern crate rustc_arena; extern crate rustc_data_structures; diff --git a/src/tools/clippy/clippy_dev/src/new_lint.rs b/src/tools/clippy/clippy_dev/src/new_lint.rs index 4e44cad472ae0..b6f3e42f31e48 100644 --- a/src/tools/clippy/clippy_dev/src/new_lint.rs +++ b/src/tools/clippy/clippy_dev/src/new_lint.rs @@ -266,13 +266,9 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String { Pass::Early => ("EarlyLintPass", "", "use rustc_ast::ast::*;", "EarlyContext"), Pass::Late => ("LateLintPass", "<'_>", "use rustc_hir::*;", "LateContext"), }; - let (msrv_ty, msrv_ctor, extract_msrv) = match lint.pass { - Pass::Early => ( - "MsrvStack", - "MsrvStack::new(conf.msrv)", - "\n extract_msrv_attr!();\n", - ), - Pass::Late => ("Msrv", "conf.msrv", ""), + let (msrv_ty, extract_msrv) = match lint.pass { + Pass::Early => ("MsrvStack", "\n extract_msrv_attr!();\n"), + Pass::Late => ("Msrv", ""), }; let lint_name = lint.name; @@ -320,7 +316,7 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String { impl {name_camel} {{ pub fn new(conf: &'static Conf) -> Self {{ - Self {{ msrv: {msrv_ctor} }} + Self {{ msrv: conf.msrv.into() }} }} }} diff --git a/src/tools/clippy/clippy_dev/src/release.rs b/src/tools/clippy/clippy_dev/src/release.rs index d11070bab85bf..25d7d2a47025e 100644 --- a/src/tools/clippy/clippy_dev/src/release.rs +++ b/src/tools/clippy/clippy_dev/src/release.rs @@ -1,5 +1,5 @@ use crate::utils::{FileUpdater, UpdateStatus, Version, parse_cargo_package}; -use std::fmt::Write; +use std::fmt::Write as _; static CARGO_TOML_FILES: &[&str] = &[ "clippy_config/Cargo.toml", diff --git a/src/tools/clippy/clippy_dev/src/sync.rs b/src/tools/clippy/clippy_dev/src/sync.rs index 98fd72fc0bd1a..5bd5e5f0dfbd2 100644 --- a/src/tools/clippy/clippy_dev/src/sync.rs +++ b/src/tools/clippy/clippy_dev/src/sync.rs @@ -1,6 +1,6 @@ use crate::utils::{FileUpdater, update_text_region_fn}; use chrono::offset::Utc; -use std::fmt::Write; +use std::fmt::Write as _; pub fn update_nightly() { let date = Utc::now().format("%Y-%m-%d").to_string(); diff --git a/src/tools/clippy/clippy_dev/src/utils.rs b/src/tools/clippy/clippy_dev/src/utils.rs index 797eed7d59348..f10540e98ca74 100644 --- a/src/tools/clippy/clippy_dev/src/utils.rs +++ b/src/tools/clippy/clippy_dev/src/utils.rs @@ -7,7 +7,7 @@ use core::range::Range; use core::str::FromStr; use std::ffi::OsStr; use std::fs::{self, OpenOptions}; -use std::io::{self, Read as _, Seek as _, SeekFrom, Write}; +use std::io::{self, Read as _, Seek as _, SeekFrom, Write as _}; use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use std::{env, thread}; diff --git a/src/tools/clippy/clippy_lints/Cargo.toml b/src/tools/clippy/clippy_lints/Cargo.toml index c2f524a7ee235..893ab32d19c1b 100644 --- a/src/tools/clippy/clippy_lints/Cargo.toml +++ b/src/tools/clippy/clippy_lints/Cargo.toml @@ -15,6 +15,7 @@ clippy_config = { path = "../clippy_config" } clippy_utils = { path = "../clippy_utils" } declare_clippy_lint = { path = "../declare_clippy_lint" } itertools = "0.15" +memchr = "2" quine-mc_cluskey = "0.2" regex-syntax = "0.8" serde = { version = "1.0", features = ["derive"] } @@ -24,14 +25,11 @@ semver = "1.0" url = "2.2" [dependencies.toml] -version = "0.9.7" +version = "1.1" default-features = false # preserve_order keeps diagnostic output in file order features = ["parse", "preserve_order"] -[dev-dependencies] -walkdir = "2.3" - [lints.rust.unexpected_cfgs] level = "warn" check-cfg = ['cfg(bootstrap)'] diff --git a/src/tools/clippy/clippy_lints/src/absolute_paths.rs b/src/tools/clippy/clippy_lints/src/absolute_paths.rs index cf2059eecc079..548668dcf648b 100644 --- a/src/tools/clippy/clippy_lints/src/absolute_paths.rs +++ b/src/tools/clippy/clippy_lints/src/absolute_paths.rs @@ -56,19 +56,15 @@ declare_clippy_lint! { impl_lint_pass!(AbsolutePaths => [ABSOLUTE_PATHS]); pub struct AbsolutePaths { - pub absolute_paths_max_segments: u64, - pub absolute_paths_allowed_crates: FxHashSet, + absolute_paths_max_segments: u64, + absolute_paths_allowed_crates: &'static FxHashSet, } impl AbsolutePaths { pub fn new(conf: &'static Conf) -> Self { Self { absolute_paths_max_segments: conf.absolute_paths_max_segments, - absolute_paths_allowed_crates: conf - .absolute_paths_allowed_crates - .iter() - .map(|x| Symbol::intern(x)) - .collect(), + absolute_paths_allowed_crates: &conf.absolute_paths_allowed_crates, } } } diff --git a/src/tools/clippy/clippy_lints/src/almost_complete_range.rs b/src/tools/clippy/clippy_lints/src/almost_complete_range.rs index 2589703930239..20e58ae1e18aa 100644 --- a/src/tools/clippy/clippy_lints/src/almost_complete_range.rs +++ b/src/tools/clippy/clippy_lints/src/almost_complete_range.rs @@ -4,7 +4,7 @@ use clippy_utils::msrvs::{self, MsrvStack}; use clippy_utils::source::{trim_span, walk_span_to_context}; use rustc_ast::ast::{Expr, ExprKind, LitKind, Pat, PatKind, RangeEnd, RangeLimits}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; declare_clippy_lint! { @@ -36,9 +36,7 @@ pub struct AlmostCompleteRange { } impl AlmostCompleteRange { pub fn new(conf: &'static Conf) -> Self { - Self { - msrv: MsrvStack::new(conf.msrv), - } + Self { msrv: conf.msrv.into() } } } impl EarlyLintPass for AlmostCompleteRange { diff --git a/src/tools/clippy/clippy_lints/src/approx_const.rs b/src/tools/clippy/clippy_lints/src/approx_const.rs index 1234f4bf96cf0..24f7d1e7ab7fd 100644 --- a/src/tools/clippy/clippy_lints/src/approx_const.rs +++ b/src/tools/clippy/clippy_lints/src/approx_const.rs @@ -43,7 +43,7 @@ declare_clippy_lint! { impl_lint_pass!(ApproxConstant => [APPROX_CONSTANT]); // Tuples are of the form (constant, name, min_digits, msrv) -const KNOWN_CONSTS: [(f64, &str, usize, Option); 19] = [ +const KNOWN_CONSTS: [(f64, &str, usize, Option); 21] = [ (f64::E, "E", 4, None), (f64::FRAC_1_PI, "FRAC_1_PI", 4, None), (f64::FRAC_1_SQRT_2, "FRAC_1_SQRT_2", 5, None), @@ -63,6 +63,8 @@ const KNOWN_CONSTS: [(f64, &str, usize, Option); 19] = [ (f64::PI, "PI", 3, None), (f64::SQRT_2, "SQRT_2", 5, None), (f64::TAU, "TAU", 3, Some(msrvs::TAU)), + (f64::EULER_GAMMA, "EULER_GAMMA", 5, Some(msrvs::EULER_GAMMA)), + (f64::GOLDEN_RATIO, "GOLDEN_RATIO", 5, Some(msrvs::GOLDEN_RATIO)), ]; pub struct ApproxConstant { @@ -71,7 +73,7 @@ pub struct ApproxConstant { impl ApproxConstant { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs b/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs index 6afc1f9ef0928..ca3a923aac5db 100644 --- a/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs +++ b/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_config::types::{ SourceItemOrderingCategory, SourceItemOrderingModuleItemGroupings, SourceItemOrderingModuleItemKind, SourceItemOrderingTraitAssocItemKind, SourceItemOrderingTraitAssocItemKinds, - SourceItemOrderingWithinModuleItemGroupings, + SourceItemOrderingWithinModuleItemGroupings, TraitImplItemOrder, }; use clippy_utils::diagnostics::span_lint_and_note; use clippy_utils::is_cfg_test; @@ -12,9 +12,9 @@ use rustc_hir::{ VariantData, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; -use rustc_middle::ty::AssocKind; +use rustc_middle::ty::{AssocKind, TyCtxt}; use rustc_session::impl_lint_pass; -use rustc_span::Ident; +use rustc_span::{Ident, Symbol}; declare_clippy_lint! { /// ### What it does @@ -177,21 +177,25 @@ pub struct ArbitrarySourceItemOrdering { enable_ordering_for_trait: bool, module_item_order_groupings: SourceItemOrderingModuleItemGroupings, module_items_ordered_within_groupings: SourceItemOrderingWithinModuleItemGroupings, + trait_impl_item_order: TraitImplItemOrder, } impl ArbitrarySourceItemOrdering { - pub fn new(conf: &'static Conf) -> Self { + pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self { #[allow(clippy::enum_glob_use)] // Very local glob use for legibility. use SourceItemOrderingCategory::*; + conf.module_items_ordered_within_groupings + .check_groupings(tcx.sess, &conf.module_item_order_groupings); Self { assoc_types_order: conf.trait_assoc_item_kinds_order.clone(), - enable_ordering_for_enum: conf.source_item_ordering.contains(&Enum), - enable_ordering_for_impl: conf.source_item_ordering.contains(&Impl), - enable_ordering_for_module: conf.source_item_ordering.contains(&Module), - enable_ordering_for_struct: conf.source_item_ordering.contains(&Struct), - enable_ordering_for_trait: conf.source_item_ordering.contains(&Trait), + enable_ordering_for_enum: conf.source_item_ordering.contains(Enum), + enable_ordering_for_impl: conf.source_item_ordering.contains(Impl), + enable_ordering_for_module: conf.source_item_ordering.contains(Module), + enable_ordering_for_struct: conf.source_item_ordering.contains(Struct), + enable_ordering_for_trait: conf.source_item_ordering.contains(Trait), module_item_order_groupings: conf.module_item_order_groupings.clone(), module_items_ordered_within_groupings: conf.module_items_ordered_within_groupings.clone(), + trait_impl_item_order: conf.trait_impl_item_order, } } @@ -210,6 +214,18 @@ impl ArbitrarySourceItemOrdering { ); } + /// Produces a linting warning for impl items that don't follow the trait definition order. + fn lint_trait_impl_item(cx: &LateContext<'_>, item: ImplItemId, before_item: ImplItemId) { + span_lint_and_note( + cx, + ARBITRARY_SOURCE_ITEM_ORDERING, + cx.tcx.def_span(item.owner_id), + "incorrect ordering of impl items (should follow the trait definition order)", + Some(cx.tcx.def_span(before_item.owner_id)), + format!("should be placed before `{}`", cx.tcx.item_name(before_item.owner_id)), + ); + } + /// Produces a linting warning for incorrectly ordered item members. fn lint_member_name(cx: &T, ident: Ident, before_ident: Ident) { span_lint_and_note( @@ -260,6 +276,121 @@ impl ArbitrarySourceItemOrdering { format!("should be placed before `{}`", cx.tcx.item_name(before_item.owner_id)), ); } + + /// Checks the ordering of items in an impl block against the configured + /// associated item kind order, alphabetically within each kind. + fn check_impl_alphabetical(&self, cx: &LateContext<'_>, trait_impl: &rustc_hir::Impl<'_>) { + let mut cur_t: Option<(ImplItemId, Ident)> = None; + + for &item in trait_impl.items { + let span = cx.tcx.def_span(item.owner_id); + let ident = cx.tcx.item_ident(item.owner_id); + if span.in_external_macro(cx.sess().source_map()) { + continue; + } + + if let Some((cur_t, cur_ident)) = cur_t { + let cur_t_kind = convert_assoc_item_kind(cx, cur_t.owner_id); + let cur_t_kind_index = self.assoc_types_order.index_of(cur_t_kind); + let item_kind = convert_assoc_item_kind(cx, item.owner_id); + let item_kind_index = self.assoc_types_order.index_of(item_kind); + + if cur_t_kind == item_kind && cur_ident.name.as_str() > ident.name.as_str() { + Self::lint_member_name(cx, ident, cur_ident); + } else if cur_t_kind_index > item_kind_index { + self.lint_impl_item(cx, item, cur_t); + } + } + cur_t = Some((item, ident)); + } + } + + /// Checks the ordering of items in a trait impl against the order in + /// which they are declared in the trait definition. + /// + /// Falls back to the alphabetical check for impl blocks without a trait. + fn check_impl_trait_def_order(&self, cx: &LateContext<'_>, trait_impl: &rustc_hir::Impl<'_>) { + let Some(trait_order) = get_trait_item_order(cx, trait_impl) else { + // Bare impl blocks have no trait definition to compare against. + self.check_impl_alphabetical(cx, trait_impl); + return; + }; + + let mut cur_t: Option<(ImplItemId, Ident)> = None; + + for &item in trait_impl.items { + let span = cx.tcx.def_span(item.owner_id); + let ident = cx.tcx.item_ident(item.owner_id); + if span.in_external_macro(cx.sess().source_map()) { + continue; + } + + if let Some((cur_t, cur_ident)) = cur_t { + // Compare positions in the trait definition. + let cur_pos = trait_order.iter().position(|n| *n == cur_ident.name); + let item_pos = trait_order.iter().position(|n| *n == ident.name); + if let (Some(cur_pos), Some(item_pos)) = (cur_pos, item_pos) + && cur_pos > item_pos + { + Self::lint_trait_impl_item(cx, item, cur_t); + } + } + cur_t = Some((item, ident)); + } + } + + /// Checks impl items, accepting either the alphabetical + kind ordering + /// or the trait definition order. Lints only when both are violated. + /// + /// Fallbacks to the alphabetical check for impl blocks without a trait. + fn check_impl_alphabetical_or_trait_def_order(&self, cx: &LateContext<'_>, trait_impl: &rustc_hir::Impl<'_>) { + let Some(trait_order) = get_trait_item_order(cx, trait_impl) else { + // Bare impl blocks have no trait definition to compare against, + // so only the alphabetical ordering applies. + self.check_impl_alphabetical(cx, trait_impl); + return; + }; + + let mut cur_t: Option<(ImplItemId, Ident)> = None; + + for &item in trait_impl.items { + let span = cx.tcx.def_span(item.owner_id); + let ident = cx.tcx.item_ident(item.owner_id); + if span.in_external_macro(cx.sess().source_map()) { + continue; + } + + if let Some((cur_t, cur_ident)) = cur_t { + let cur_t_kind = convert_assoc_item_kind(cx, cur_t.owner_id); + let cur_t_kind_index = self.assoc_types_order.index_of(cur_t_kind); + let item_kind = convert_assoc_item_kind(cx, item.owner_id); + let item_kind_index = self.assoc_types_order.index_of(item_kind); + + // Same check as in `check_impl_alphabetical` + let alpha_violation = if cur_t_kind == item_kind { + cur_ident.name.as_str() > ident.name.as_str() + } else { + cur_t_kind_index > item_kind_index + }; + + // Same check as in `check_impl_trait_def_order` + let trait_violation = matches!( + ( + trait_order.iter().position(|n| *n == cur_ident.name), + trait_order.iter().position(|n| *n == ident.name), + ), + (Some(cur_pos), Some(item_pos)) if cur_pos > item_pos + ); + + // Accepting either ordering means linting only when the pair + // satisfies neither of them. + if alpha_violation && trait_violation { + Self::lint_trait_impl_item(cx, item, cur_t); + } + } + cur_t = Some((item, ident)); + } + } } impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { @@ -327,9 +458,9 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { if let Some((cur_t, cur_ident)) = cur_t { let cur_t_kind = convert_assoc_item_kind(cx, cur_t.owner_id); - let cur_t_kind_index = self.assoc_types_order.index_of(&cur_t_kind); + let cur_t_kind_index = self.assoc_types_order.index_of(cur_t_kind); let item_kind = convert_assoc_item_kind(cx, item.owner_id); - let item_kind_index = self.assoc_types_order.index_of(&item_kind); + let item_kind_index = self.assoc_types_order.index_of(item_kind); if cur_t_kind == item_kind && cur_ident.name.as_str() > ident.name.as_str() { Self::lint_member_name(cx, ident, cur_ident); @@ -340,30 +471,17 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { cur_t = Some((item, ident)); } }, - ItemKind::Impl(trait_impl) if self.enable_ordering_for_impl => { - let mut cur_t: Option<(ImplItemId, Ident)> = None; - - for &item in trait_impl.items { - let span = cx.tcx.def_span(item.owner_id); - let ident = cx.tcx.item_ident(item.owner_id); - if span.in_external_macro(cx.sess().source_map()) { - continue; - } - - if let Some((cur_t, cur_ident)) = cur_t { - let cur_t_kind = convert_assoc_item_kind(cx, cur_t.owner_id); - let cur_t_kind_index = self.assoc_types_order.index_of(&cur_t_kind); - let item_kind = convert_assoc_item_kind(cx, item.owner_id); - let item_kind_index = self.assoc_types_order.index_of(&item_kind); - - if cur_t_kind == item_kind && cur_ident.name.as_str() > ident.name.as_str() { - Self::lint_member_name(cx, ident, cur_ident); - } else if cur_t_kind_index > item_kind_index { - self.lint_impl_item(cx, item, cur_t); - } - } - cur_t = Some((item, ident)); - } + ItemKind::Impl(trait_impl) if self.enable_ordering_for_impl => match self.trait_impl_item_order { + // Match trait impl item orderings based on the configured ordering. + TraitImplItemOrder::Alphabetical => { + self.check_impl_alphabetical(cx, trait_impl); + }, + TraitImplItemOrder::TraitItemOrdering => { + self.check_impl_trait_def_order(cx, trait_impl); + }, + TraitImplItemOrder::AlphabeticalOrTraitItemOrdering => { + self.check_impl_alphabetical_or_trait_def_order(cx, trait_impl); + }, }, _ => {}, // Catch-all for `ItemKinds` that don't have fields. } @@ -423,10 +541,10 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { } let item_kind = convert_module_item_kind(&item.kind); - let grouping_name = self.module_item_order_groupings.grouping_name_of(&item_kind); + let grouping_name = self.module_item_order_groupings.grouping_name_of(item_kind); let module_level_order = self .module_item_order_groupings - .module_level_order_of(&item_kind) + .module_level_order_of(item_kind) .unwrap_or_default(); if let Some(cur_t) = cur_t.as_ref() { @@ -566,3 +684,18 @@ fn get_item_name(item: &Item<'_>) -> Option { _ => item.kind.ident().map(|name| name.as_str().to_owned()), } } + +/// Returns the associated item names of the implemented trait in +/// definition order, or `None` if the impl block has no trait. +fn get_trait_item_order(cx: &LateContext<'_>, trait_impl: &rustc_hir::Impl<'_>) -> Option> { + trait_impl + .of_trait + .and_then(|t| t.trait_ref.trait_def_id()) + .map(|def_id| { + cx.tcx + .associated_items(def_id) + .in_definition_order() + .map(rustc_middle::ty::AssocItem::name) + .collect() + }) +} diff --git a/src/tools/clippy/clippy_lints/src/arc_with_non_send_sync.rs b/src/tools/clippy/clippy_lints/src/arc_with_non_send_sync.rs index e449b06199d36..0c790a5343838 100644 --- a/src/tools/clippy/clippy_lints/src/arc_with_non_send_sync.rs +++ b/src/tools/clippy/clippy_lints/src/arc_with_non_send_sync.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::implements_trait; use rustc_hir::{Expr, ExprKind, QPath}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/as_conversions.rs b/src/tools/clippy/clippy_lints/src/as_conversions.rs index 27e304a848e33..f273a3d948c92 100644 --- a/src/tools/clippy/clippy_lints/src/as_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/as_conversions.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; use rustc_hir::{Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/asm_syntax.rs b/src/tools/clippy/clippy_lints/src/asm_syntax.rs index 3c5cf74d5a17f..db59221b78b6a 100644 --- a/src/tools/clippy/clippy_lints/src/asm_syntax.rs +++ b/src/tools/clippy/clippy_lints/src/asm_syntax.rs @@ -3,7 +3,7 @@ use std::fmt; use clippy_utils::diagnostics::span_lint_and_then; use rustc_ast::ast::{Expr, ExprKind, InlineAsmOptions}; use rustc_ast::{InlineAsm, Item, ItemKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::Span; use rustc_target::asm::InlineAsmArch; diff --git a/src/tools/clippy/clippy_lints/src/assert_is_empty.rs b/src/tools/clippy/clippy_lints/src/assert_is_empty.rs new file mode 100644 index 0000000000000..cfaa3c6fd64e9 --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/assert_is_empty.rs @@ -0,0 +1,310 @@ +use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::macros::{find_assert_args, root_macro_call_first_node}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::walk_span_to_context; +use clippy_utils::sugg::Sugg; +use clippy_utils::sym; +use clippy_utils::ty::implements_trait; +use rustc_errors::Applicability; +use rustc_hir::{Expr, ExprKind, LangItem, UnOp}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; +use rustc_middle::ty::{self, Ty}; +use rustc_session::declare_lint_pass; +use rustc_span::Span; + +declare_clippy_lint! { + /// ### What it does + /// + /// Checks assertions that only test whether a supported value is empty. + /// + /// The lint handles `assert!` and `debug_assert!` calls on strings, slices, arrays, and `Vec`. + /// + /// ### Why is this bad? + /// + /// A boolean assertion only reports that the emptiness check failed. It does not show what the + /// asserted value contained. + /// + /// In CI or another remote test service, the failure output tells you that the value was + /// unexpectedly empty or non-empty, but not which values were present. The next step is often + /// to reproduce the failure locally, add temporary logging, or change the test so it exposes + /// the value. That extra investigation can be much slower than fixing the problem from the + /// original CI failure. + /// + /// The emptiness check also commonly appears before a deeper contents assertion: + /// + /// ```no_run + /// # let items = vec!["baz"]; + /// assert!(!items.is_empty()); + /// assert_eq!(items[0], "bar"); + /// ``` + /// + /// If the first assertion fails, the second assertion never runs, so the failure can hide the + /// check that would have shown more useful context. + /// + /// Instead, compare the value with an empty value using `assert_eq!`, `assert_ne!`, + /// `debug_assert_eq!`, or `debug_assert_ne!`. These macros print the asserted value on failure. + /// + /// ### Known problems + /// + /// Printing the asserted value can be undesirable outside tests, especially when the value may + /// be very large or contain sensitive information. If the assertion failure should not reveal + /// the value, keep the boolean assertion and allow this lint at that assertion. + /// + /// ### Example + /// + /// ```no_run + /// # let items = vec![1, 2, 3]; + /// assert!(items.is_empty()); + /// assert!(!items.is_empty()); + /// ``` + /// + /// Use instead: + /// + /// ```no_run + /// # let items = vec![1, 2, 3]; + /// assert_eq!(items, [] as [i32; 0]); + /// assert_ne!(items, [] as [i32; 0]); + /// ``` + #[clippy::version = "1.98.0"] + pub ASSERT_IS_EMPTY, + pedantic, + "asserting on emptiness without showing the asserted value on failure" +} + +declare_lint_pass!(AssertIsEmpty => [ASSERT_IS_EMPTY]); + +impl<'tcx> LateLintPass<'tcx> for AssertIsEmpty { + /// Finds assertion conditions that only test emptiness. + /// + /// Matching assertions without a custom message are rewritten as equality or inequality + /// assertions against an empty value. + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { + // `assert!` and `debug_assert!` expand to `if`; skip other expressions before walking the + // macro backtrace. + if !matches!(expr.kind, ExprKind::If(..)) { + return; + } + + let Some((macro_name, condition, assert_span)) = assert_call(cx, expr) else { + return; + }; + let Some((assertion_kind, receiver)) = emptiness_assertion(condition) else { + return; + }; + let Some((receiver_suffix, empty_value)) = assertion_suggestion(cx, receiver) else { + return; + }; + + emit_assertion_suggestion( + cx, + macro_name, + assert_span, + condition, + assertion_kind, + receiver, + (receiver_suffix, &empty_value), + ); + } +} + +/// Extracts the source-level condition from `assert!` and `debug_assert!`. +/// +/// The returned macro name omits the trailing `!` so the diagnostic can build `assert_eq`, +/// `assert_ne`, `debug_assert_eq`, or `debug_assert_ne` from the original macro. Returns `None` +/// for other macros, assertions with a custom message parameter, and conditions from macro +/// expansions, where rewriting the condition span would produce confusing or invalid suggestions. +fn assert_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'static str, &'tcx Expr<'tcx>, Span)> { + let macro_call = root_macro_call_first_node(cx, expr)?; + let macro_name = match cx.tcx.get_diagnostic_name(macro_call.def_id) { + Some(sym::assert_macro) => "assert", + Some(sym::debug_assert_macro) => "debug_assert", + _ => return None, + }; + let (condition, panic_expn) = find_assert_args(cx, expr, macro_call.expn)?; + if !panic_expn.is_default_message() { + return None; + } + + if condition.span.from_expansion() { + return None; + } + + Some((macro_name, condition, macro_call.span)) +} + +/// Returns the assertion kind and receiver for an emptiness predicate. +/// +/// `value.is_empty()` maps to an equality assertion against an empty value. `!value.is_empty()` +/// maps to an inequality assertion. Returns `None` when the condition is neither form. +fn emptiness_assertion<'tcx>(condition: &'tcx Expr<'tcx>) -> Option<(AssertionKind, &'tcx Expr<'tcx>)> { + if let Some(receiver) = is_empty_receiver(condition) { + return Some((AssertionKind::Eq, receiver)); + } + + let ExprKind::Unary(UnOp::Not, inner) = condition.kind else { + return None; + }; + + is_empty_receiver(inner).map(|receiver| (AssertionKind::Ne, receiver)) +} + +/// Returns the receiver when `expr` is a direct `value.is_empty()` call. +/// +/// Returns `None` for other method calls, negated expressions, and non-method expressions. +fn is_empty_receiver<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { + let ExprKind::MethodCall(method, receiver, [], _) = expr.kind else { + return None; + }; + (method.ident.name == sym::is_empty).then_some(receiver) +} + +/// Assertion macro polarity for the replacement assertion. +/// +/// The variants are named after the comparison macro suffixes rather than the original predicate +/// shape because suggestions are the only consumer. +#[derive(Clone, Copy, PartialEq, Eq)] +enum AssertionKind { + /// Use an equality assertion against an empty value. + Eq, + + /// Use an inequality assertion against an empty value. + Ne, +} + +impl AssertionKind { + /// Returns the assertion macro suffix for this emptiness predicate. + /// + /// Empty checks become equality assertions. Non-empty checks become inequality assertions. + fn suffix(self) -> &'static str { + match self { + Self::Eq => "_eq", + Self::Ne => "_ne", + } + } + + /// Returns the expected state named in the diagnostic. + fn expected_state(self) -> &'static str { + match self { + Self::Eq => "empty", + Self::Ne => "not empty", + } + } +} + +/// Builds replacement operands when the resulting assertion is useful. +/// +/// The replacement assertion must compile, compare the same value, and print useful failure +/// output. Returns `None` for unsupported collection types and for element types that cannot be +/// printed and compared by the replacement assertion. +fn assertion_suggestion<'tcx>(cx: &LateContext<'tcx>, receiver: &'tcx Expr<'tcx>) -> Option<(&'static str, String)> { + let receiver_ty = cx.typeck_results().expr_ty(receiver); + let suggestion = suggestion_for_type(cx, receiver_ty)?; + if type_is_printable_and_comparable(cx, receiver_ty.peel_refs()) { + Some(suggestion) + } else { + None + } +} + +/// Returns the receiver suffix and empty value for this receiver type. +/// +/// Arrays and borrowed vectors are compared through slices because direct comparison with `[]` does +/// not compile for those receiver types. Returns `None` when the receiver has no compact +/// empty-literal comparison. +fn suggestion_for_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<(&'static str, String)> { + match ty.kind() { + ty::Array(..) => Some((".as_slice()", "[]".to_string())), + ty::Ref(_, inner, _) if matches!(inner.kind(), ty::Array(..)) => Some((".as_slice()", "[]".to_string())), + ty::Ref(_, inner, _) if inner.is_diag_item(cx, sym::Vec) => Some((".as_slice()", "[]".to_string())), + _ => suggestion_for_peeled_type(cx, ty.peel_refs()), + } +} + +/// Returns the empty value for receivers that compare directly after peeling references. +/// +/// `String` and `str` compare against `""`. Slices compare against `[]`. `Vec` compares +/// against `[] as [T; 0]` so the empty value carries the element type. Returns `None` for other +/// receiver types. +fn suggestion_for_peeled_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<(&'static str, String)> { + if ty.is_str() || ty.is_lang_item(cx, LangItem::String) { + Some(("", "\"\"".to_string())) + } else if matches!(ty.kind(), ty::Slice(..)) { + Some(("", "[]".to_string())) + } else if ty.is_diag_item(cx, sym::Vec) { + Some(("", format!("[] as [{}; 0]", element_type(cx, ty)?))) + } else { + None + } +} + +/// Returns whether the replacement assertion has useful failure output. +/// +/// Suggestions are limited to cases where the replacement assertion can both compare the value and +/// print it on failure. Strings satisfy this directly; sequence-like values require printable, +/// self-comparable elements. Returns `false` when either trait bound is missing. +fn type_is_printable_and_comparable<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { + if ty.is_str() || ty.is_lang_item(cx, LangItem::String) { + return true; + } + + if let Some(element_ty) = element_type(cx, ty) + && let Some(debug_trait) = cx.tcx.get_diagnostic_item(sym::Debug) + && let Some(partial_eq_trait) = cx.tcx.get_diagnostic_item(sym::PartialEq) + { + implements_trait(cx, element_ty, debug_trait, &[]) + && implements_trait(cx, element_ty, partial_eq_trait, &[element_ty.into()]) + } else { + false + } +} + +/// Extracts the element type from supported sequence-like values. +/// +/// The element type is used both for trait checks and for the typed empty-array suggestion required +/// by `Vec` suggestions. Returns `None` for non-sequence receiver types. +fn element_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option> { + match ty.kind() { + ty::Array(ty, _) | ty::Slice(ty) => Some(*ty), + ty::Adt(_, args) if ty.is_diag_item(cx, sym::Vec) => args.types().next(), + _ => None, + } +} + +/// Emits the rewrite from a boolean assertion to a comparison assertion. +fn emit_assertion_suggestion( + cx: &LateContext<'_>, + macro_name: &str, + assert_span: Span, + condition: &Expr<'_>, + assertion_kind: AssertionKind, + receiver: &Expr<'_>, + suggestion: (&str, &str), +) { + let mut applicability = Applicability::MachineApplicable; + let receiver_snip = + Sugg::hir_with_context(cx, receiver, assert_span.ctxt(), "..", &mut applicability).maybe_paren(); + let (receiver_suffix, empty_value) = suggestion; + let receiver_snip = format!("{receiver_snip}{receiver_suffix}"); + let assertion_suffix = assertion_kind.suffix(); + let expected_state = assertion_kind.expected_state(); + + span_lint_and_then( + cx, + ASSERT_IS_EMPTY, + assert_span, + format!("used `{macro_name}!` to check that a value is {expected_state}"), + |diag| { + let macro_name_span = cx.sess().source_map().span_until_char(assert_span, '!'); + let condition_span = walk_span_to_context(condition.span, assert_span.ctxt()).unwrap_or(condition.span); + + diag.multipart_suggestion( + format!("use `{macro_name}{assertion_suffix}!` to show the value on failure"), + vec![ + (macro_name_span.shrink_to_hi(), assertion_suffix.to_string()), + (condition_span, format!("{receiver_snip}, {empty_value}")), + ], + applicability, + ); + }, + ); +} diff --git a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs index 118c3c23d727d..3f7aa4c9225cf 100644 --- a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs +++ b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs @@ -39,7 +39,7 @@ pub struct AssertionsOnConstants { } impl AssertionsOnConstants { pub fn new(conf: &Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs b/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs index d48ef10c8cd25..d37e84a4b0116 100644 --- a/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs +++ b/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::{find_assert_args, root_macro_call_first_node}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::sym; use clippy_utils::ty::{has_debug_impl, is_copy}; diff --git a/src/tools/clippy/clippy_lints/src/assigning_clones.rs b/src/tools/clippy/clippy_lints/src/assigning_clones.rs index 60bc9b2b5b853..a625a43874c8b 100644 --- a/src/tools/clippy/clippy_lints/src/assigning_clones.rs +++ b/src/tools/clippy/clippy_lints/src/assigning_clones.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::mir::{PossibleBorrowerMap, enclosing_mir}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sugg::Sugg; use clippy_utils::{is_in_test, last_path_segment, local_is_initialized, sym}; use rustc_errors::Applicability; @@ -61,7 +61,7 @@ pub struct AssigningClones { impl AssigningClones { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs index 0235b130b6c01..ccedacbccd7ab 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs @@ -1,16 +1,16 @@ use super::ALLOW_ATTRIBUTES; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; -use rustc_ast::attr::AttributeExt; +use rustc_ast::attr::AttributeExt as _; use rustc_ast::{AttrStyle, Attribute}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, LintContext}; +use rustc_lint::{EarlyContext, LintContext as _}; // Separate each crate's features. pub fn check<'cx>(cx: &EarlyContext<'cx>, attr: &'cx Attribute) { - if !attr.span.in_external_macro(cx.sess().source_map()) - && let AttrStyle::Outer = attr.style + if let AttrStyle::Outer = attr.style && let Some(path_span) = attr.path_span() + && !attr.span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, attr) { #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] diff --git a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes_without_reason.rs b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes_without_reason.rs index 5bf077990e1fe..d15863aa45d27 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes_without_reason.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes_without_reason.rs @@ -2,7 +2,7 @@ use super::{ALLOW_ATTRIBUTES_WITHOUT_REASON, Attribute}; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; use rustc_ast::{MetaItemInner, MetaItemKind}; -use rustc_lint::{EarlyContext, LintContext}; +use rustc_lint::{EarlyContext, LintContext as _}; use rustc_span::sym; use rustc_span::symbol::Symbol; diff --git a/src/tools/clippy/clippy_lints/src/attrs/blanket_clippy_restriction_lints.rs b/src/tools/clippy/clippy_lints/src/attrs/blanket_clippy_restriction_lints.rs index 4d64eec25d273..10519023fa905 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/blanket_clippy_restriction_lints.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/blanket_clippy_restriction_lints.rs @@ -3,7 +3,7 @@ use super::utils::extract_clippy_lint; use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then}; use clippy_utils::sym; use rustc_ast::MetaItemInner; -use rustc_lint::{EarlyContext, Level, LintContext}; +use rustc_lint::{EarlyContext, Level, LintContext as _}; use rustc_span::DUMMY_SP; use rustc_span::symbol::Symbol; diff --git a/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs index da9ace312f7d3..33f291e9875e7 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs @@ -1,6 +1,6 @@ use super::DUPLICATED_ATTRIBUTES; use clippy_utils::diagnostics::span_lint_and_then; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_ast::{Attribute, MetaItem}; use rustc_ast_pretty::pprust::path_to_string; use rustc_data_structures::fx::FxHashMap; diff --git a/src/tools/clippy/clippy_lints/src/attrs/mixed_attributes_style.rs b/src/tools/clippy/clippy_lints/src/attrs/mixed_attributes_style.rs index 851d605c36be5..c9cbf29f2b670 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/mixed_attributes_style.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/mixed_attributes_style.rs @@ -2,7 +2,7 @@ use super::MIXED_ATTRIBUTES_STYLE; use clippy_utils::diagnostics::span_lint; use rustc_ast::{AttrKind, AttrStyle, Attribute, SyntheticAttr}; use rustc_data_structures::fx::FxHashSet; -use rustc_lint::{EarlyContext, LintContext}; +use rustc_lint::{EarlyContext, LintContext as _}; use rustc_span::source_map::SourceMap; use rustc_span::{SourceFile, Span, Symbol}; use std::sync::Arc; @@ -29,12 +29,10 @@ impl From<&AttrKind> for SimpleAttrKind { .collect::>(); Self::Normal(path_symbols) }, - AttrKind::Synthetic(synthetic) => { - match &**synthetic { - SyntheticAttr::CfgTrace(_) => Self::CfgTrace, - SyntheticAttr::CfgAttrTrace(_) => Self::CfgAttrTrace, - } - } + AttrKind::Synthetic(synthetic) => match &**synthetic { + SyntheticAttr::CfgTrace(_) => Self::CfgTrace, + SyntheticAttr::CfgAttrTrace(_) => Self::CfgAttrTrace, + }, AttrKind::DocComment(..) => Self::Doc, } } diff --git a/src/tools/clippy/clippy_lints/src/attrs/mod.rs b/src/tools/clippy/clippy_lints/src/attrs/mod.rs index 2833619814cc3..8fbe42a24d597 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/mod.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/mod.rs @@ -19,7 +19,7 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::msrvs::{self, Msrv, MsrvStack}; use rustc_ast::{self as ast, AttrArgs, AttrKind, Attribute, MetaItemInner, MetaItemKind}; use rustc_hir::{ImplItem, ImplItemKind, Item, ItemKind, TraitFn, TraitItem, TraitItemKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::sym; use utils::is_lint_level; @@ -506,7 +506,7 @@ pub struct Attributes { impl Attributes { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } @@ -548,9 +548,7 @@ pub struct EarlyAttributes { impl EarlyAttributes { pub fn new(conf: &'static Conf) -> Self { - Self { - msrv: MsrvStack::new(conf.msrv), - } + Self { msrv: conf.msrv.into() } } } @@ -570,9 +568,7 @@ pub struct PostExpansionEarlyAttributes { impl PostExpansionEarlyAttributes { pub fn new(conf: &'static Conf) -> Self { - Self { - msrv: MsrvStack::new(conf.msrv), - } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/attrs/non_minimal_cfg.rs b/src/tools/clippy/clippy_lints/src/attrs/non_minimal_cfg.rs index 91e2689a14731..b2b112cc9cf4f 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/non_minimal_cfg.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/non_minimal_cfg.rs @@ -1,6 +1,6 @@ use super::{Attribute, NON_MINIMAL_CFG}; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_ast::{MetaItemInner, MetaItemKind}; use rustc_errors::Applicability; use rustc_lint::EarlyContext; diff --git a/src/tools/clippy/clippy_lints/src/attrs/unnecessary_clippy_cfg.rs b/src/tools/clippy/clippy_lints/src/attrs/unnecessary_clippy_cfg.rs index 4c97c03471aa9..9e9fbb2c52582 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/unnecessary_clippy_cfg.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/unnecessary_clippy_cfg.rs @@ -1,7 +1,7 @@ use super::{Attribute, UNNECESSARY_CLIPPY_CFG}; use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_sugg}; -use clippy_utils::source::SpanExt; -use itertools::Itertools; +use clippy_utils::source::SpanExt as _; +use itertools::Itertools as _; use rustc_ast::AttrStyle; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, Level}; diff --git a/src/tools/clippy/clippy_lints/src/attrs/useless_attribute.rs b/src/tools/clippy/clippy_lints/src/attrs/useless_attribute.rs index 60cdcd4a85817..de8d8402fc3fa 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/useless_attribute.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/useless_attribute.rs @@ -1,19 +1,16 @@ use super::USELESS_ATTRIBUTE; use super::utils::{is_lint_level, is_word, namespace_and_lint}; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::{SpanExt, first_line_of_span}; +use clippy_utils::source::{SpanExt as _, first_line_of_span}; use clippy_utils::sym; use rustc_ast::{Attribute, Item, ItemKind}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, LintContext}; +use rustc_lint::{EarlyContext, LintContext as _}; pub(super) fn check(cx: &EarlyContext<'_>, item: &Item, attrs: &[Attribute]) { let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use)); for attr in attrs { - if attr.span.in_external_macro(cx.sess().source_map()) { - return; - } if let Some(lint_list) = &attr.meta_item_list() && attr.name().is_some_and(is_lint_level) { @@ -72,9 +69,10 @@ pub(super) fn check(cx: &EarlyContext<'_>, item: &Item, attrs: &[Attribute]) { _ => {}, } } - let line_span = first_line_of_span(cx, attr.span); - if let Some(src) = line_span.get_text(cx) + if !attr.span.in_external_macro(cx.sess().source_map()) + && let line_span = first_line_of_span(cx, attr.span) + && let Some(src) = line_span.get_text(cx) && src.contains("#[") { #[expect(clippy::collapsible_span_lint_calls)] diff --git a/src/tools/clippy/clippy_lints/src/bit_width.rs b/src/tools/clippy/clippy_lints/src/bit_width.rs index 3403d55494734..1f31de3393d71 100644 --- a/src/tools/clippy/clippy_lints/src/bit_width.rs +++ b/src/tools/clippy/clippy_lints/src/bit_width.rs @@ -5,7 +5,7 @@ use clippy_utils::source::snippet_with_context; use clippy_utils::{is_from_proc_macro, sym}; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, QPath}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::{self, Ty}; use rustc_session::impl_lint_pass; @@ -93,7 +93,7 @@ pub struct ManualBitWidth { impl ManualBitWidth { pub fn new(conf: &Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/block_scrutinee.rs b/src/tools/clippy/clippy_lints/src/block_scrutinee.rs new file mode 100644 index 0000000000000..0d0a8ba3b60a3 --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/block_scrutinee.rs @@ -0,0 +1,111 @@ +use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::source::{indent_of, snippet}; +use rustc_errors::Applicability; +use rustc_hir::{BlockCheckMode, Expr, ExprKind, LoopSource}; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_session::declare_lint_pass; +use rustc_span::edition::Edition; + +declare_clippy_lint! { + /// ### What it does + /// Warns when a match, if let, or while let scrutinee is wrapped in a block. + /// This lint only triggers on the 2021 edition and older. + /// + /// ### Why is this bad? + /// It is unusual to write `{ expr }` when you could just have written + /// `expr`, and it is unlikely that anyone would write that for any reason + /// other than wanting temporaries in `expr` to be dropped before executing + /// the body of the `match`/`if let`/`while` statement. However, prior to + /// the 2024 edition, wrapping the scrutinee in a block did not drop + /// temporaries before the body executes. + /// + /// ### Example + /// ```rust,ignore + /// if let Some(x) = { my_function() } { .. } + /// ``` + #[clippy::version = "1.98.0"] + pub BLOCK_SCRUTINEE, + suspicious, + "warns when the scrutinee is wrapped in a block in older editions" +} + +declare_lint_pass!(BlockScrutinee => [BLOCK_SCRUTINEE]); + +impl<'tcx> LateLintPass<'tcx> for BlockScrutinee { + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { + if cx.tcx.sess.edition() >= Edition::Edition2024 { + return; + } + + let (scrutinee, keyword_fallback) = match expr.kind { + ExprKind::Match(scrutinee, _, _) => (scrutinee, "`match`"), + ExprKind::Let(let_expr) => (let_expr.init, "`if let` / `while let`"), + _ => return, + }; + + if scrutinee.span.from_expansion() || expr.span.from_expansion() { + return; + } + + if let ExprKind::Block(block, _) = scrutinee.kind + && matches!(block.rules, BlockCheckMode::DefaultBlock) + && block.stmts.is_empty() + && let Some(inner_expr) = block.expr + { + let inner_snippet = snippet(cx, inner_expr.span, ".."); + + let main_msg = "this scrutinee is wrapped in a block"; + + span_lint_and_then(cx, BLOCK_SCRUTINEE, scrutinee.span, main_msg, |diag| { + let mut keyword = keyword_fallback; + let mut outer_span = expr.span; + + if let ExprKind::Let(_) = expr.kind { + keyword = "`if let`"; + for (_, node) in cx.tcx.hir_parent_iter(expr.hir_id) { + if let rustc_hir::Node::Expr(e) = node { + if let ExprKind::If(..) = e.kind { + if keyword == "`if let`" { + outer_span = e.span; + } + } else if let ExprKind::Loop(_, _, LoopSource::While, _) = e.kind { + keyword = "`while let`"; + outer_span = e.span; + break; + } + } else if matches!(node, rustc_hir::Node::Item(..) | rustc_hir::Node::ImplItem(..)) { + break; + } + } + } + + diag.note(format!( + "temporary values in this block-wrapped scrutinee will be dropped after the body of the {keyword} statement" + )); + + diag.note("starting with the 2024 edition, temporaries within a block's final expression are dropped immediately at the end of the block"); + + let suggestion_msg = format!("to drop temporaries after the surrounding {keyword}, remove the block"); + + diag.span_suggestion( + scrutinee.span, + suggestion_msg, + inner_snippet.to_string(), + Applicability::MaybeIncorrect, + ); + + let indent = indent_of(cx, outer_span).unwrap_or(0); + let pad = " ".repeat(indent); + + diag.multipart_suggestion( + "to drop temporaries early, move them to a separate local binding (or update your `Cargo.toml` to the 2024 edition)", + vec![ + (outer_span.shrink_to_lo(), format!("let res = {inner_snippet};\n{pad}")), + (scrutinee.span, "res".to_string()), + ], + Applicability::MaybeIncorrect, + ); + }); + } + } +} diff --git a/src/tools/clippy/clippy_lints/src/blocks_in_conditions.rs b/src/tools/clippy/clippy_lints/src/blocks_in_conditions.rs index 10fe1a4174f89..305a1690e0d0f 100644 --- a/src/tools/clippy/clippy_lints/src/blocks_in_conditions.rs +++ b/src/tools/clippy/clippy_lints/src/blocks_in_conditions.rs @@ -1,9 +1,9 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_block_with_applicability; -use clippy_utils::{contains_return, higher, is_from_proc_macro}; +use clippy_utils::{contains_return, higher, is_from_proc_macro, leaks_droppable_temporary}; use rustc_errors::Applicability; use rustc_hir::{BlockCheckMode, Expr, ExprKind, MatchSource}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; declare_clippy_lint! { @@ -53,7 +53,7 @@ const BRACED_EXPR_MESSAGE: &str = "omit braces around single expression conditio impl<'tcx> LateLintPass<'tcx> for BlocksInConditions { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if expr.span.in_external_macro(cx.sess().source_map()) { + if expr.span.from_expansion() { return; } @@ -83,7 +83,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInConditions { if let Some(ex) = &block.expr { // don't dig into the expression here, just suggest that they remove // the block - if expr.span.from_expansion() || ex.span.from_expansion() { + if ex.span.from_expansion() { return; } @@ -93,6 +93,14 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInConditions { return; } + // Don't lint if the block creates temporaries with significant drops that need + // to be dropped at the end of the block (e.g., MutexGuard). + // Removing the braces would extend the lifetime of these temporaries. + // #15112 + if leaks_droppable_temporary(cx, ex) { + return; + } + let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, @@ -106,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInConditions { } } else { let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span); - if span.from_expansion() || expr.span.from_expansion() || is_from_proc_macro(cx, cond) { + if span.from_expansion() || is_from_proc_macro(cx, cond) { return; } // move block higher diff --git a/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs b/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs index 2752430c92224..8119da8cfc65a 100644 --- a/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs +++ b/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs @@ -7,7 +7,7 @@ use clippy_utils::ty::{implements_trait, is_copy}; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, Lit}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::{self, Ty, Unnormalized}; use rustc_session::declare_lint_pass; use rustc_span::symbol::Ident; diff --git a/src/tools/clippy/clippy_lints/src/booleans.rs b/src/tools/clippy/clippy_lints/src/booleans.rs index 0184402198b33..8982585f75d77 100644 --- a/src/tools/clippy/clippy_lints/src/booleans.rs +++ b/src/tools/clippy/clippy_lints/src/booleans.rs @@ -2,15 +2,15 @@ use clippy_config::Conf; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then}; use clippy_utils::higher::has_let_expr; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::{SpanExt, snippet_with_context}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::{SpanExt as _, snippet_with_context}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::implements_trait; use clippy_utils::{eq_expr_value, sym}; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; -use rustc_hir::intravisit::{FnKind, Visitor, walk_expr}; use rustc_hir::attrs::RustcVersion; +use rustc_hir::intravisit::{FnKind, Visitor, walk_expr}; use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, UnOp}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; @@ -93,7 +93,7 @@ pub struct NonminimalBool { impl NonminimalBool { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs b/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs index 13ae80868d9b5..4c781da4ad1a6 100644 --- a/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs +++ b/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs @@ -1,6 +1,6 @@ use crate::reference::DEREF_ADDROF; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::ty::implements_trait; use clippy_utils::{ get_enclosing_closure, get_parent_expr, is_expr_temporary_value, is_from_proc_macro, is_lint_allowed, is_mutable, diff --git a/src/tools/clippy/clippy_lints/src/box_default.rs b/src/tools/clippy/clippy_lints/src/box_default.rs index 34b96b1d9d7a1..e509d2bf34083 100644 --- a/src/tools/clippy/clippy_lints/src/box_default.rs +++ b/src/tools/clippy/clippy_lints/src/box_default.rs @@ -1,13 +1,13 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::macro_backtrace; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::ty::expr_sig; use clippy_utils::{is_default_equivalent, sym}; use rustc_errors::Applicability; use rustc_hir::def::Res; -use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt, walk_ty}; +use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt as _, walk_ty}; use rustc_hir::{AmbigArg, Block, Expr, ExprKind, HirId, LangItem, LetStmt, Node, QPath, Ty, TyKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/cargo/lint_groups_priority.rs b/src/tools/clippy/clippy_lints/src/cargo/lint_groups_priority.rs index fbf5f72c53615..7c53a9e228145 100644 --- a/src/tools/clippy/clippy_lints/src/cargo/lint_groups_priority.rs +++ b/src/tools/clippy/clippy_lints/src/cargo/lint_groups_priority.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_lint::{LateContext, unerased_lint_store}; -use rustc_span::{BytePos, Pos, SourceFile, Span, SyntaxContext}; +use rustc_span::{BytePos, Pos as _, SourceFile, Span, SyntaxContext}; use std::ops::Range; use std::path::Path; use toml::Spanned; diff --git a/src/tools/clippy/clippy_lints/src/cargo/mod.rs b/src/tools/clippy/clippy_lints/src/cargo/mod.rs index 56eeefe45308f..4ff033f3bf6c7 100644 --- a/src/tools/clippy/clippy_lints/src/cargo/mod.rs +++ b/src/tools/clippy/clippy_lints/src/cargo/mod.rs @@ -17,7 +17,7 @@ use rustc_span::DUMMY_SP; declare_clippy_lint! { /// ### What it does /// Checks to see if all common metadata is defined in - /// `Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata + /// `Cargo.toml`. See: /// /// ### Why is this bad? /// It will be more difficult for users to discover the @@ -223,14 +223,14 @@ impl_lint_pass!(Cargo => [ ]); pub struct Cargo { - allowed_duplicate_crates: FxHashSet, + allowed_duplicate_crates: &'static FxHashSet, ignore_publish: bool, } impl Cargo { pub fn new(conf: &'static Conf) -> Self { Self { - allowed_duplicate_crates: conf.allowed_duplicate_crates.iter().cloned().collect(), + allowed_duplicate_crates: &conf.allowed_duplicate_crates, ignore_publish: conf.cargo_ignore_publish, } } @@ -272,7 +272,7 @@ impl LateLintPass<'_> for Cargo { { match MetadataCommand::new().exec() { Ok(metadata) => { - multiple_crate_versions::check(cx, &metadata, &self.allowed_duplicate_crates); + multiple_crate_versions::check(cx, &metadata, self.allowed_duplicate_crates); }, Err(e) => { for lint in WITH_DEPS_LINTS { diff --git a/src/tools/clippy/clippy_lints/src/cargo/multiple_crate_versions.rs b/src/tools/clippy/clippy_lints/src/cargo/multiple_crate_versions.rs index 805bf4623f1f1..ee523fd6a24ba 100644 --- a/src/tools/clippy/clippy_lints/src/cargo/multiple_crate_versions.rs +++ b/src/tools/clippy/clippy_lints/src/cargo/multiple_crate_versions.rs @@ -1,6 +1,6 @@ use cargo_metadata::{DependencyKind, Metadata, Node, Package, PackageId}; use clippy_utils::diagnostics::span_lint; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::LOCAL_CRATE; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs index f23e789cf5d64..376ff0a2c8272 100644 --- a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs +++ b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/casts/as_underscore.rs b/src/tools/clippy/clippy_lints/src/casts/as_underscore.rs index a73e48e5fd5d1..33ab43b2f95fb 100644 --- a/src/tools/clippy/clippy_lints/src/casts/as_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/casts/as_underscore.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_errors::Applicability; use rustc_hir::{Expr, Ty, TyKind}; use rustc_lint::LateContext; -use rustc_middle::ty::IsSuggestable; +use rustc_middle::ty::IsSuggestable as _; use super::AS_UNDERSCORE; diff --git a/src/tools/clippy/clippy_lints/src/casts/borrow_as_ptr.rs b/src/tools/clippy/clippy_lints/src/casts/borrow_as_ptr.rs index 51d9628fe330f..cb9f7f618d7f9 100644 --- a/src/tools/clippy/clippy_lints/src/casts/borrow_as_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/casts/borrow_as_ptr.rs @@ -24,6 +24,7 @@ pub(super) fn check<'tcx>( && !is_lint_allowed(cx, BORROW_AS_PTR, expr.hir_id) // Fix #9884 && !is_expr_temporary_value(cx, e) + && !expr.span.in_external_macro(cx.tcx.sess.source_map()) && !is_from_proc_macro(cx, expr) { let mut app = Applicability::MachineApplicable; diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs b/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs index d2bf6db751320..40e1040b685ec 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_in_const_context; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::sugg::Sugg; use clippy_utils::ty::is_isize_or_usize; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs b/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs index 69490fb23646d..a41f6b4cc0e99 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs @@ -3,7 +3,7 @@ use clippy_utils::ty::is_c_void; use clippy_utils::{get_parent_expr, is_hir_ty_cfg_dependant, sym}; use rustc_hir::{Expr, ExprKind, GenericArg}; use rustc_lint::LateContext; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{self, Ty}; use super::CAST_PTR_ALIGNMENT; @@ -36,6 +36,7 @@ fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_f // when casting from a ZST, we don't know enough to properly lint && !from_layout.is_zst() && !is_used_as_unaligned(cx, expr) + && !expr.span.in_external_macro(cx.tcx.sess.source_map()) { span_lint( cx, diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs b/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs index a5b295c88b1c7..8aeb728a2799f 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs @@ -4,7 +4,7 @@ use clippy_utils::source; use rustc_ast::Mutability; use rustc_hir::{Expr, ExprKind, Node}; use rustc_lint::LateContext; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{self, Ty, TypeAndMut}; use super::CAST_SLICE_DIFFERENT_SIZES; @@ -25,7 +25,12 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, msrv: Msrv) { let from_size = from_layout.size.bytes(); let to_size = to_layout.size.bytes(); - if from_size != to_size && from_size != 0 && to_size != 0 && msrv.meets(cx, msrvs::PTR_SLICE_RAW_PARTS) { + if from_size != to_size + && from_size != 0 + && to_size != 0 + && msrv.meets(cx, msrvs::PTR_SLICE_RAW_PARTS) + && !expr.span.in_external_macro(cx.tcx.sess.source_map()) + { span_lint_and_then( cx, CAST_SLICE_DIFFERENT_SIZES, diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_slice_from_raw_parts.rs b/src/tools/clippy/clippy_lints/src/casts/cast_slice_from_raw_parts.rs index bce7b4c69cc62..6b1fd971357c9 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_slice_from_raw_parts.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_slice_from_raw_parts.rs @@ -35,6 +35,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, && let ctxt = expr.span.ctxt() && cast_expr.span.ctxt() == ctxt && msrv.meets(cx, msrvs::PTR_SLICE_RAW_PARTS) + && !expr.span.in_external_macro(cx.tcx.sess.source_map()) { let func = match rpk { RawPartsKind::Immutable => "from_raw_parts", diff --git a/src/tools/clippy/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs b/src/tools/clippy/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs index 93a08d3a12d49..740326d2f9420 100644 --- a/src/tools/clippy/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs +++ b/src/tools/clippy/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs @@ -65,7 +65,8 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, if let ty::FnDef(def_id, generics) = cast_from.kind() && let Some(method_name) = cx.tcx.opt_item_name(*def_id) - && let Some((const_name, ty_name)) = get_const_name_and_ty_name(cx, method_name, *def_id, generics.no_bound_vars().unwrap().as_slice()) + && let Some((const_name, ty_name)) = + get_const_name_and_ty_name(cx, method_name, *def_id, generics.no_bound_vars().unwrap().as_slice()) { let mut applicability = Applicability::MaybeIncorrect; let from_snippet = snippet_with_applicability(cx, cast_expr.span, "..", &mut applicability); diff --git a/src/tools/clippy/clippy_lints/src/casts/manual_dangling_ptr.rs b/src/tools/clippy/clippy_lints/src/casts/manual_dangling_ptr.rs index 36d63ce63195b..2b1b3c1b96fd3 100644 --- a/src/tools/clippy/clippy_lints/src/casts/manual_dangling_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/casts/manual_dangling_ptr.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; -use clippy_utils::source::SpanExt; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; +use clippy_utils::source::SpanExt as _; use clippy_utils::{expr_or_init, std_or_core, sym}; use rustc_ast::LitKind; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/casts/mod.rs b/src/tools/clippy/clippy_lints/src/casts/mod.rs index de34b2691abc6..7876c4e291224 100644 --- a/src/tools/clippy/clippy_lints/src/casts/mod.rs +++ b/src/tools/clippy/clippy_lints/src/casts/mod.rs @@ -31,7 +31,7 @@ use clippy_config::Conf; use clippy_utils::is_hir_ty_cfg_dependant; use clippy_utils::msrvs::{self, Msrv}; use rustc_hir::{Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; declare_clippy_lint! { @@ -883,17 +883,16 @@ pub struct Casts { impl Casts { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } impl<'tcx> LateLintPass<'tcx> for Casts { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if expr.span.in_external_macro(cx.sess().source_map()) { - return; - } - if let ExprKind::Cast(cast_from_expr, cast_to_hir) = expr.kind { + if expr.span.in_external_macro(cx.sess().source_map()) { + return; + } if is_hir_ty_cfg_dependant(cx, cast_to_hir) { return; } diff --git a/src/tools/clippy/clippy_lints/src/casts/needless_type_cast.rs b/src/tools/clippy/clippy_lints/src/casts/needless_type_cast.rs index 5cfbffc6c3f66..09f72b18d18f0 100644 --- a/src/tools/clippy/clippy_lints/src/casts/needless_type_cast.rs +++ b/src/tools/clippy/clippy_lints/src/casts/needless_type_cast.rs @@ -8,7 +8,7 @@ use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{BlockCheckMode, Body, Expr, ExprKind, HirId, LetStmt, PatKind, StmtKind, UnsafeSource}; use rustc_lint::LateContext; -use rustc_middle::ty::{Ty, TypeVisitableExt}; +use rustc_middle::ty::{Ty, TypeVisitableExt as _}; use rustc_span::Span; use super::NEEDLESS_TYPE_CAST; diff --git a/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs b/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs index c0f13f5e57823..5f20efe2e3646 100644 --- a/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs +++ b/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs @@ -6,7 +6,7 @@ use clippy_utils::{std_or_core, sym}; use rustc_errors::Applicability; use rustc_hir::{self as hir, Expr, ExprKind, QPath}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, Ty, TypeVisitableExt as _}; use super::PTR_CAST_CONSTNESS; @@ -90,6 +90,7 @@ pub(super) fn check_null_ptr_cast_method(cx: &LateContext<'_>, expr: &Expr<'_>) && let mut app = Applicability::MachineApplicable && let sugg = snippet_with_applicability(cx, cast_from_expr.span, "_", &mut app) && let Some((_, after_lt)) = sugg.split_once("::<") + && !expr.span.in_external_macro(cx.tcx.sess.source_map()) { span_lint_and_sugg( cx, diff --git a/src/tools/clippy/clippy_lints/src/casts/ref_as_ptr.rs b/src/tools/clippy/clippy_lints/src/casts/ref_as_ptr.rs index aef04dc9f7f9a..b850f7f41ed33 100644 --- a/src/tools/clippy/clippy_lints/src/casts/ref_as_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/casts/ref_as_ptr.rs @@ -1,7 +1,9 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sugg::Sugg; -use clippy_utils::{ExprUseNode, get_expr_use_site, is_expr_temporary_value, std_or_core}; +use clippy_utils::{ + ExprUseNode, get_expr_use_site, is_expr_temporary_value, is_inside_always_const_context, std_or_core, +}; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, Mutability, Ty, TyKind}; use rustc_lint::LateContext; @@ -26,10 +28,10 @@ pub(super) fn check<'tcx>( { if let ExprKind::AddrOf(_, _, addr_inner) = cast_expr.kind && is_expr_temporary_value(cx, addr_inner) - && matches!( + && (matches!( get_expr_use_site(cx.tcx, cx.typeck_results(), expr.span.ctxt(), expr).use_node(cx), ExprUseNode::LetStmt(_) | ExprUseNode::ConstStatic(_) - ) + ) || is_inside_always_const_context(cx.tcx, expr.hir_id)) { return; } diff --git a/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs b/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs index c14bd056de393..c98fa1a5cba74 100644 --- a/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs +++ b/src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::numeric_literal::NumericLiteral; use clippy_utils::res::MaybeResPath as _; -use clippy_utils::source::{SpanExt, snippet, snippet_with_applicability}; +use clippy_utils::source::{SpanExt as _, snippet, snippet_with_applicability}; use clippy_utils::sugg::has_enclosing_paren; use clippy_utils::visitors::{Visitable, for_each_expr_without_closures}; use clippy_utils::{get_parent_expr, is_hir_ty_cfg_dependant, is_ty_alias, sym}; @@ -9,7 +9,7 @@ use rustc_ast::{LitFloatType, LitIntType, LitKind}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{Expr, ExprKind, FnRetTy, HirId, Lit, Node, Path, QPath, TyKind, UnOp}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::adjustment::Adjust; use rustc_middle::ty::{self, FloatTy, GenericArg, InferTy, Ty}; use rustc_span::Symbol; diff --git a/src/tools/clippy/clippy_lints/src/casts/zero_ptr.rs b/src/tools/clippy/clippy_lints/src/casts/zero_ptr.rs index 90290caf10bf7..7f63a7336b1b0 100644 --- a/src/tools/clippy/clippy_lints/src/casts/zero_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/casts/zero_ptr.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::{is_in_const_context, is_integer_literal, std_or_core}; use rustc_errors::Applicability; use rustc_hir::{Expr, Mutability, Ty, TyKind}; diff --git a/src/tools/clippy/clippy_lints/src/checked_conversions.rs b/src/tools/clippy/clippy_lints/src/checked_conversions.rs index c80930f0b443f..86ffa8fa58d45 100644 --- a/src/tools/clippy/clippy_lints/src/checked_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/checked_conversions.rs @@ -5,7 +5,7 @@ use clippy_utils::source::snippet_with_context; use clippy_utils::{SpanlessEq, is_in_const_context, is_integer_literal, sym}; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, QPath, TyKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::{Symbol, SyntaxContext}; @@ -42,7 +42,7 @@ pub struct CheckedConversions { impl CheckedConversions { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/cloned_ref_to_slice_refs.rs b/src/tools/clippy/clippy_lints/src/cloned_ref_to_slice_refs.rs index 24955ac3c6258..bc1e21c99faa2 100644 --- a/src/tools/clippy/clippy_lints/src/cloned_ref_to_slice_refs.rs +++ b/src/tools/clippy/clippy_lints/src/cloned_ref_to_slice_refs.rs @@ -3,7 +3,7 @@ use std::ops::ControlFlow; use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::sugg::Sugg; use clippy_utils::visitors::is_const_evaluatable; use clippy_utils::{is_in_const_context, is_mutable, sym}; @@ -51,18 +51,18 @@ declare_clippy_lint! { "cloning a reference for slice references" } -impl_lint_pass!(ClonedRefToSliceRefs<'_> => [CLONED_REF_TO_SLICE_REFS]); +impl_lint_pass!(ClonedRefToSliceRefs => [CLONED_REF_TO_SLICE_REFS]); -pub struct ClonedRefToSliceRefs<'a> { - msrv: &'a Msrv, +pub struct ClonedRefToSliceRefs { + msrv: Msrv, } -impl<'a> ClonedRefToSliceRefs<'a> { - pub fn new(conf: &'a Conf) -> Self { - Self { msrv: &conf.msrv } +impl ClonedRefToSliceRefs { + pub fn new(conf: &Conf) -> Self { + Self { msrv: conf.msrv.into() } } } -impl<'tcx> LateLintPass<'tcx> for ClonedRefToSliceRefs<'_> { +impl<'tcx> LateLintPass<'tcx> for ClonedRefToSliceRefs { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { // `&[foo.clone()]` expressions if let ExprKind::AddrOf(_, mutability, arr) = &expr.kind diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index c330ed3d5a0a4..81ff839408d34 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -1,13 +1,13 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::{IntoSpan, SpanExt}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::{IntoSpan as _, SpanExt as _}; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{LimitStack, get_async_fn_body, sym}; use core::ops::ControlFlow; use rustc_hir::intravisit::FnKind; use rustc_hir::{Attribute, Body, Expr, ExprKind, FnDecl}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; use rustc_span::def_id::LocalDefId; diff --git a/src/tools/clippy/clippy_lints/src/collapsible_if.rs b/src/tools/clippy/clippy_lints/src/collapsible_if.rs index 6def41b775d1d..cee21987ba3cb 100644 --- a/src/tools/clippy/clippy_lints/src/collapsible_if.rs +++ b/src/tools/clippy/clippy_lints/src/collapsible_if.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::msrvs::Msrv; -use clippy_utils::source::{IntoSpan as _, SpanExt, snippet, snippet_block_with_applicability}; +use clippy_utils::source::{IntoSpan as _, SpanExt as _, snippet, snippet_block_with_applicability}; use clippy_utils::{can_use_if_let_chains, span_contains_cfg, span_contains_non_whitespace, sym, tokenize_with_text}; use rustc_ast::{BinOpKind, MetaItemInner}; use rustc_errors::Applicability; @@ -89,7 +89,7 @@ pub struct CollapsibleIf { impl CollapsibleIf { pub fn new(conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), lint_commented_code: conf.lint_commented_code, } } @@ -336,7 +336,7 @@ fn span_extract_keyword(cx: &LateContext<'_>, span: Span, keyword: &str) -> Opti /// Peel the parentheses from an `if` expression, e.g. `((if true {} else {}))`. pub(super) fn peel_parens(cx: &LateContext<'_>, mut span: Span) -> (Span, Span, Span) { - use crate::rustc_span::Pos; + use crate::rustc_span::Pos as _; let start = span.shrink_to_lo(); let end = span.shrink_to_hi(); diff --git a/src/tools/clippy/clippy_lints/src/collection_is_never_read.rs b/src/tools/clippy/clippy_lints/src/collection_is_never_read.rs index 4ddd396c50ce4..5c70b0d880914 100644 --- a/src/tools/clippy/clippy_lints/src/collection_is_never_read.rs +++ b/src/tools/clippy/clippy_lints/src/collection_is_never_read.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::visitors::{Visitable, for_each_expr}; use clippy_utils::{get_enclosing_block, sym}; use core::ops::ControlFlow; diff --git a/src/tools/clippy/clippy_lints/src/dbg_macro.rs b/src/tools/clippy/clippy_lints/src/dbg_macro.rs index adc1c0a6c577c..62d59e95e6772 100644 --- a/src/tools/clippy/clippy_lints/src/dbg_macro.rs +++ b/src/tools/clippy/clippy_lints/src/dbg_macro.rs @@ -6,7 +6,7 @@ use clippy_utils::{is_in_test, sym}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{Closure, ClosureKind, CoroutineKind, Expr, ExprKind, LetStmt, LocalSource, Node, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::{Span, SyntaxContext}; diff --git a/src/tools/clippy/clippy_lints/src/declared_lints.rs b/src/tools/clippy/clippy_lints/src/declared_lints.rs index 83ab6e31d2b26..681b36cfb3607 100644 --- a/src/tools/clippy/clippy_lints/src/declared_lints.rs +++ b/src/tools/clippy/clippy_lints/src/declared_lints.rs @@ -11,6 +11,7 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[ crate::as_conversions::AS_CONVERSIONS_INFO, crate::asm_syntax::INLINE_ASM_X86_ATT_SYNTAX_INFO, crate::asm_syntax::INLINE_ASM_X86_INTEL_SYNTAX_INFO, + crate::assert_is_empty::ASSERT_IS_EMPTY_INFO, crate::assertions_on_constants::ASSERTIONS_ON_CONSTANTS_INFO, crate::assertions_on_result_states::ASSERTIONS_ON_RESULT_STATES_INFO, crate::assigning_clones::ASSIGNING_CLONES_INFO, @@ -35,6 +36,7 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[ crate::await_holding_invalid::AWAIT_HOLDING_REFCELL_REF_INFO, crate::bit_width::MANUAL_BIT_WIDTH_INFO, crate::bit_width::MISMATCHED_BIT_WIDTH_TYPE_INFO, + crate::block_scrutinee::BLOCK_SCRUTINEE_INFO, crate::blocks_in_conditions::BLOCKS_IN_CONDITIONS_INFO, crate::bool_assert_comparison::BOOL_ASSERT_COMPARISON_INFO, crate::bool_comparison::BOOL_COMPARISON_INFO, @@ -97,6 +99,7 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[ crate::default_instead_of_iter_empty::DEFAULT_INSTEAD_OF_ITER_EMPTY_INFO, crate::default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK_INFO, crate::default_union_representation::DEFAULT_UNION_REPRESENTATION_INFO, + crate::definition_in_module_root::DEFINITION_IN_MODULE_ROOT_INFO, crate::dereference::EXPLICIT_AUTO_DEREF_INFO, crate::dereference::EXPLICIT_DEREF_METHODS_INFO, crate::dereference::NEEDLESS_BORROW_INFO, @@ -592,6 +595,7 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[ crate::non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY_INFO, crate::non_std_lazy_statics::NON_STD_LAZY_STATICS_INFO, crate::non_zero_suggestions::NON_ZERO_SUGGESTIONS_INFO, + crate::nonnull_unchecked_on_box_ptr::NONNULL_UNCHECKED_ON_BOX_PTR_INFO, crate::nonstandard_macro_braces::NONSTANDARD_MACRO_BRACES_INFO, crate::octal_escapes::OCTAL_ESCAPES_INFO, crate::only_used_in_recursion::ONLY_USED_IN_RECURSION_INFO, @@ -684,6 +688,8 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[ crate::repeat_vec_with_capacity::REPEAT_VEC_WITH_CAPACITY_INFO, crate::replace_box::REPLACE_BOX_INFO, crate::reserve_after_initialization::RESERVE_AFTER_INITIALIZATION_INFO, + crate::rest_when_destructuring_struct::REST_PATTERN_ACCESSIBLE_FIELD_INFO, + crate::rest_when_destructuring_struct::UNNECESSARY_REST_PATTERN_INFO, crate::return_self_not_must_use::RETURN_SELF_NOT_MUST_USE_INFO, crate::returns::LET_AND_RETURN_INFO, crate::returns::NEEDLESS_RETURN_INFO, diff --git a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs index 649d8449e431b..abf2541fbb7be 100644 --- a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs +++ b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs @@ -8,7 +8,7 @@ use rustc_hir::{ Block, Body, ConstContext, Expr, ExprKind, FnRetTy, HirId, Lit, Pat, PatExpr, PatExprKind, PatKind, Stmt, StmtKind, StructTailExpr, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::{self, FloatTy, IntTy, PolyFnSig, Ty}; use rustc_session::declare_lint_pass; use std::iter; @@ -88,12 +88,12 @@ impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> { /// Check whether a passed literal has potential to cause fallback or not. fn check_lit(&self, lit: Lit, lit_ty: Ty<'tcx>, emit_hir_id: HirId) { - if !lit.span.in_external_macro(self.cx.sess().source_map()) - && matches!(self.ty_bounds.last(), Some(ExplicitTyBound(false))) + if matches!(self.ty_bounds.last(), Some(ExplicitTyBound(false))) && matches!( lit.node, LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) ) + && !lit.span.in_external_macro(self.cx.sess().source_map()) { let (suffix, is_float) = match lit_ty.kind() { ty::Int(IntTy::I32) => ("i32", false), diff --git a/src/tools/clippy/clippy_lints/src/default_union_representation.rs b/src/tools/clippy/clippy_lints/src/default_union_representation.rs index bfb246c5f848c..bd738b7f4cd86 100644 --- a/src/tools/clippy/clippy_lints/src/default_union_representation.rs +++ b/src/tools/clippy/clippy_lints/src/default_union_representation.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_hir::attrs::ReprAttr; use rustc_hir::{HirId, Item, ItemKind, find_attr}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{self, FieldDef}; use rustc_session::declare_lint_pass; diff --git a/src/tools/clippy/clippy_lints/src/definition_in_module_root.rs b/src/tools/clippy/clippy_lints/src/definition_in_module_root.rs new file mode 100644 index 0000000000000..4b454e282cc24 --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/definition_in_module_root.rs @@ -0,0 +1,161 @@ +use clippy_utils::diagnostics::span_lint_and_help; +use rustc_ast::ast::{self, Inline, ItemKind, ModKind}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; +use rustc_session::impl_lint_pass; +use rustc_span::{FileName, SourceFile, sym}; + +declare_clippy_lint! { + /// ### What it does + /// Checks for definitions (structs, functions, traits, etc.) in `mod.rs` + /// files. `lib.rs` and `main.rs` are not checked. + /// + /// ### Why restrict this? + /// `mod.rs` is well-suited to acting as a table of contents — listing + /// submodules and re-exports while leaving definitions to named files. + /// Naming each file after its primary definition keeps filenames + /// descriptive and unique, makes editor tabs and search results easier + /// to scan, and makes the filesystem tree mirror the module tree, so + /// the file layout is uniquely determined by the module structure. + /// + /// ### Example + /// ```ignore + /// // stuff/mod.rs + /// mod bar; + /// pub struct Foo { /* ... */ } + /// impl Foo { /* ... */ } + /// ``` + /// Use instead: + /// ```ignore + /// // stuff/mod.rs + /// mod bar; + /// mod foo; + /// pub use foo::Foo; + /// + /// // stuff/foo.rs + /// pub struct Foo { /* ... */ } + /// impl Foo { /* ... */ } + /// ``` + /// + /// ### Notes + /// This lint is most useful alongside `self_named_module_files`, which + /// requires `mod.rs` files; together they constrain `mod.rs` to + /// declarations only. Under `mod_module_files` (which forbids `mod.rs` + /// entirely) this lint has nothing to fire on. + /// + /// If a definition's name matches its parent module's name, moving it + /// produces `foo/foo.rs`, which `module_inception` flags — projects + /// in that situation typically also `allow(module_inception)`. + #[clippy::version = "1.99.0"] + pub DEFINITION_IN_MODULE_ROOT, + restriction, + "definitions in `mod.rs` should be in named files" +} + +impl_lint_pass!(DefinitionInModuleRoot => [DEFINITION_IN_MODULE_ROOT]); + +#[derive(Default)] +pub struct DefinitionInModuleRoot { + /// Stack tracking whether items at the current nesting level are in a + /// `mod.rs` file. When the stack is empty, we are at crate root depth + /// (not linted). + module_stack: Vec, +} + +impl EarlyLintPass for DefinitionInModuleRoot { + fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { + // Handle module items: push state for their children. + match &item.kind { + ItemKind::Mod(.., ModKind::Loaded(_, Inline::No { .. }, mod_spans, ..)) => { + let file = cx.sess().source_map().lookup_source_file(mod_spans.inner_span.lo()); + self.module_stack.push(is_mod_rs(&file)); + return; + }, + ItemKind::Mod(..) => { + // Inline module or unloaded — children are not in a root file. + self.module_stack.push(false); + return; + }, + _ => {}, + } + + // Skip items from macro expansion. + if item.span.from_expansion() { + return; + } + + // Only lint inside mod.rs files (not at crate root depth). + if !self.module_stack.last().copied().unwrap_or(false) { + return; + } + + let Some(kind) = definition_kind(item) else { + return; + }; + + let help = if let Some(ident) = item.kind.ident() { + format!("move {kind} `{ident}` to a dedicated file") + } else { + format!("move the {kind} to a dedicated file") + }; + + span_lint_and_help( + cx, + DEFINITION_IN_MODULE_ROOT, + item.span, + "definition in module root file", + None, + help, + ); + } + + fn check_item_post(&mut self, _: &EarlyContext<'_>, item: &ast::Item) { + if matches!(item.kind, ItemKind::Mod(..)) { + self.module_stack.pop(); + } + } +} + +/// Returns a human-readable kind string for flagged items, or `None` for +/// items that are allowed in root files (modules, imports, re-exports, +/// `#[macro_export]` macros). +fn definition_kind(item: &ast::Item) -> Option<&'static str> { + match &item.kind { + i @ (ItemKind::Struct(..) + | ItemKind::Enum(..) + | ItemKind::Union(..) + | ItemKind::Fn(..) + | ItemKind::Const(..) + | ItemKind::Static(..) + | ItemKind::Impl(..) + | ItemKind::Trait(..) + | ItemKind::TraitAlias(..) + | ItemKind::TyAlias(..) + | ItemKind::ForeignMod(..)) => Some(i.descr()), + i @ ItemKind::MacroDef(..) if !has_macro_export(item) => Some(i.descr()), + ItemKind::ExternCrate(..) + | ItemKind::Use(..) + | ItemKind::ConstBlock(..) + | ItemKind::Mod(..) + | ItemKind::GlobalAsm(..) + | ItemKind::MacCall(..) + | ItemKind::MacroDef(..) + | ItemKind::Delegation(..) + | ItemKind::DelegationMac(..) => None, + } +} + +/// Check if an item has `#[macro_export]`. +fn has_macro_export(item: &ast::Item) -> bool { + item.attrs.iter().any(|attr| attr.has_name(sym::macro_export)) +} + +/// Check if a source file is `mod.rs`. +fn is_mod_rs(file: &SourceFile) -> bool { + if let FileName::Real(name) = &file.name { + name.local_path() + .and_then(|p| p.file_name()) + .is_some_and(|n| n == "mod.rs") + } else { + false + } +} diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 42d9270a0bcb9..237c7dfdc770c 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::sugg::has_enclosing_paren; use clippy_utils::ty::{ @@ -12,14 +12,14 @@ use rustc_ast::util::parser::ExprPrecedence; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; -use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt, walk_ty}; +use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt as _, walk_ty}; use rustc_hir::{ self as hir, AmbigArg, BindingMode, Body, BodyId, BorrowKind, Expr, ExprKind, HirId, Item, MatchSource, Mutability, Node, OwnerId, Pat, PatKind, Path, QPath, TyKind, UnOp, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability}; -use rustc_middle::ty::{self, AssocTag, Ty, TyCtxt, TypeVisitableExt, TypeckResults, Unnormalized}; +use rustc_middle::ty::{self, AssocTag, Ty, TyCtxt, TypeVisitableExt as _, TypeckResults, Unnormalized}; use rustc_session::impl_lint_pass; use rustc_span::{Span, Symbol, SyntaxContext}; use std::borrow::Cow; @@ -905,7 +905,7 @@ impl TyCoercionStability { TyKind::View(ty, _) => { // FIXME(scrabsha): what are the semantics of view types here? Self::for_hir_ty(ty) - } + }, TyKind::UnsafeBinder(..) => Self::None, }; } diff --git a/src/tools/clippy/clippy_lints/src/derivable_impls.rs b/src/tools/clippy/clippy_lints/src/derivable_impls.rs index 9367f6a35e454..6f48713e3e7fc 100644 --- a/src/tools/clippy/clippy_lints/src/derivable_impls.rs +++ b/src/tools/clippy/clippy_lints/src/derivable_impls.rs @@ -64,7 +64,7 @@ pub struct DerivableImpls { impl DerivableImpls { pub fn new(conf: &'static Conf) -> Self { - DerivableImpls { msrv: conf.msrv } + DerivableImpls { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs b/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs index 1056929405035..51412cd1d8a6e 100644 --- a/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs +++ b/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs @@ -5,7 +5,7 @@ use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, HirId}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, ClauseKind, GenericParamDefKind, ParamEnv, TraitPredicate, Ty, TyCtxt, Upcast}; +use rustc_middle::ty::{self, ClauseKind, GenericParamDefKind, ParamEnv, TraitPredicate, Ty, TyCtxt, Upcast as _}; use rustc_span::{Span, sym}; use super::DERIVE_PARTIAL_EQ_WITHOUT_EQ; diff --git a/src/tools/clippy/clippy_lints/src/derive/mod.rs b/src/tools/clippy/clippy_lints/src/derive/mod.rs index d6f928d738cbd..96b1cb0890ac1 100644 --- a/src/tools/clippy/clippy_lints/src/derive/mod.rs +++ b/src/tools/clippy/clippy_lints/src/derive/mod.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use rustc_hir::def::Res; use rustc_hir::{Impl, Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/disallowed_methods.rs b/src/tools/clippy/clippy_lints/src/disallowed_methods.rs index e2fd71b7d990f..71c9c0c58ceb5 100644 --- a/src/tools/clippy/clippy_lints/src/disallowed_methods.rs +++ b/src/tools/clippy/clippy_lints/src/disallowed_methods.rs @@ -88,6 +88,9 @@ impl DisallowedMethods { impl<'tcx> LateLintPass<'tcx> for DisallowedMethods { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { + if self.disallowed.is_empty() { + return; + } if expr.span.desugaring_kind().is_some() { return; } diff --git a/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs b/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs index d013e453ecc0a..aeced9e72fb5e 100644 --- a/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs +++ b/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs @@ -2,9 +2,9 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint; use rustc_ast::ast; use rustc_data_structures::fx::FxHashSet; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; -use unicode_script::{Script, UnicodeScript}; +use unicode_script::{Script, UnicodeScript as _}; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/doc/broken_link.rs b/src/tools/clippy/clippy_lints/src/doc/broken_link.rs index 2fa41d83915a4..6c7eae0170d0c 100644 --- a/src/tools/clippy/clippy_lints/src/doc/broken_link.rs +++ b/src/tools/clippy/clippy_lints/src/doc/broken_link.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint; use rustc_lint::LateContext; use rustc_resolve::rustdoc::pulldown_cmark::BrokenLink as PullDownBrokenLink; use rustc_resolve::rustdoc::{DocFragment, source_span_for_markdown_range}; -use rustc_span::{BytePos, Pos, Span}; +use rustc_span::{BytePos, Pos as _, Span}; use super::DOC_BROKEN_LINK; diff --git a/src/tools/clippy/clippy_lints/src/doc/doc_paragraphs_missing_punctuation.rs b/src/tools/clippy/clippy_lints/src/doc/doc_paragraphs_missing_punctuation.rs index cafb33aaa8815..85772303d7431 100644 --- a/src/tools/clippy/clippy_lints/src/doc/doc_paragraphs_missing_punctuation.rs +++ b/src/tools/clippy/clippy_lints/src/doc/doc_paragraphs_missing_punctuation.rs @@ -54,13 +54,14 @@ fn is_missing_punctuation(doc_string: &str) -> Vec { let mut missing_punctuation = Vec::new(); let mut current_paragraph = None; let mut current_event_is_missing_punctuation = false; - + let mut current_event_is_image = false; for (event, offset) in Parser::new_ext(doc_string, main_body_opts() - Options::ENABLE_SMART_PUNCTUATION).into_offset_iter() { let last_event_was_missing_punctuation = current_event_is_missing_punctuation; current_event_is_missing_punctuation = false; - + let last_event_was_image = current_event_is_image; + current_event_is_image = false; match event { Event::Start(Tag::FootnoteDefinition(_) | Tag::Heading { .. } | Tag::HtmlBlock | Tag::Table(_)) => { no_report_depth += 1; @@ -82,7 +83,11 @@ fn is_missing_punctuation(doc_string: &str) -> Vec { no_report_depth -= 1; current_paragraph = None; }, - Event::InlineHtml(_) | Event::Start(Tag::Image { .. }) | Event::End(TagEnd::Image) => { + Event::InlineHtml(_) | Event::Start(Tag::Image { .. }) => { + current_paragraph = None; + }, + Event::End(TagEnd::Image) => { + current_event_is_image = true; current_paragraph = None; }, Event::End(TagEnd::Paragraph) => { @@ -94,7 +99,9 @@ fn is_missing_punctuation(doc_string: &str) -> Vec { Event::Code(..) | Event::Start(Tag::Link { .. }) | Event::End(TagEnd::Link) if no_report_depth == 0 && !offset.is_empty() => { - if trim_trailing_symbols(&doc_string[..offset.end]).ends_with(TERMINAL_PUNCTUATION_MARKS) { + if trim_trailing_symbols(&doc_string[..offset.end]).ends_with(TERMINAL_PUNCTUATION_MARKS) + || last_event_was_image + { current_paragraph = None; } else { current_paragraph = Some(MissingPunctuation::Fixable(offset.end)); diff --git a/src/tools/clippy/clippy_lints/src/doc/doc_suspicious_footnotes.rs b/src/tools/clippy/clippy_lints/src/doc/doc_suspicious_footnotes.rs index dfa6c96378644..39e53dbedb580 100644 --- a/src/tools/clippy/clippy_lints/src/doc/doc_suspicious_footnotes.rs +++ b/src/tools/clippy/clippy_lints/src/doc/doc_suspicious_footnotes.rs @@ -4,7 +4,7 @@ use rustc_ast::token::{CommentKind, DocFragmentKind}; use rustc_errors::Applicability; use rustc_hir::attrs::AttributeKind; use rustc_hir::{AttrStyle, Attribute}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use std::ops::Range; diff --git a/src/tools/clippy/clippy_lints/src/doc/lazy_continuation.rs b/src/tools/clippy/clippy_lints/src/doc/lazy_continuation.rs index cb9d68224dbb8..470d8e1304127 100644 --- a/src/tools/clippy/clippy_lints/src/doc/lazy_continuation.rs +++ b/src/tools/clippy/clippy_lints/src/doc/lazy_continuation.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_errors::Applicability; use rustc_lint::LateContext; use rustc_span::BytePos; diff --git a/src/tools/clippy/clippy_lints/src/doc/markdown.rs b/src/tools/clippy/clippy_lints/src/doc/markdown.rs index 69c3b9150c300..1969ae5ef6d58 100644 --- a/src/tools/clippy/clippy_lints/src/doc/markdown.rs +++ b/src/tools/clippy/clippy_lints/src/doc/markdown.rs @@ -3,7 +3,7 @@ use clippy_utils::source::snippet_with_applicability; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_lint::LateContext; -use rustc_span::{BytePos, Pos, Span}; +use rustc_span::{BytePos, Pos as _, Span}; use url::Url; use crate::doc::{DOC_MARKDOWN, Fragments}; diff --git a/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs b/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs index 4139df9cd7997..5a69a5e0d2e84 100644 --- a/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs +++ b/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs @@ -1,7 +1,7 @@ use super::{DocHeaders, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, MISSING_SAFETY_DOC, UNNECESSARY_SAFETY_DOC}; use clippy_utils::diagnostics::{span_lint, span_lint_and_note}; use clippy_utils::macros::{is_panic, root_macro_call_first_node}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::implements_trait_with_env; use clippy_utils::visitors::for_each_expr; use clippy_utils::{fulfill_or_allowed, is_doc_hidden, is_inside_always_const_context, method_chain_args, return_ty}; diff --git a/src/tools/clippy/clippy_lints/src/doc/mod.rs b/src/tools/clippy/clippy_lints/src/doc/mod.rs index 8fad6862ae9ba..790faab309d53 100644 --- a/src/tools/clippy/clippy_lints/src/doc/mod.rs +++ b/src/tools/clippy/clippy_lints/src/doc/mod.rs @@ -1,5 +1,3 @@ -#![allow(clippy::lint_without_lint_pass)] - use clippy_config::Conf; use clippy_utils::attrs::is_doc_hidden; use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_then}; @@ -7,7 +5,7 @@ use clippy_utils::{is_entrypoint_fn, is_trait_impl_item}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{Attribute, FieldDef, ImplItemKind, ItemKind, Node, Safety, TraitItemKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext as _}; use rustc_resolve::rustdoc::pulldown_cmark::Event::{ Code, DisplayMath, End, FootnoteReference, HardBreak, Html, InlineHtml, InlineMath, Rule, SoftBreak, Start, TaskListMarker, Text, @@ -346,12 +344,14 @@ declare_clippy_lint! { /// /// Returns a random number /// /// /// /// It was chosen by a fair dice roll + /// # fn foo() {} /// ``` /// Use instead: /// ```no_run /// /// Returns a random number. /// /// /// /// It was chosen by a fair dice roll. + /// # fn foo() {} /// ``` /// /// ### Terminal punctuation marks @@ -728,14 +728,14 @@ impl_lint_pass!(Documentation => [ ]); pub struct Documentation { - valid_idents: FxHashSet, + valid_idents: &'static FxHashSet, check_private_items: bool, } impl Documentation { pub fn new(conf: &'static Conf) -> Self { Self { - valid_idents: conf.doc_valid_idents.iter().cloned().collect(), + valid_idents: &conf.doc_valid_idents, check_private_items: conf.check_private_items, } } @@ -749,7 +749,7 @@ impl EarlyLintPass for Documentation { impl<'tcx> LateLintPass<'tcx> for Documentation { fn check_attributes(&mut self, cx: &LateContext<'tcx>, attrs: &'tcx [Attribute]) { - let Some(headers) = check_attrs(cx, &self.valid_idents, attrs) else { + let Some(headers) = check_attrs(cx, self.valid_idents, attrs) else { return; }; @@ -776,7 +776,8 @@ impl<'tcx> LateLintPass<'tcx> for Documentation { cx, item, attrs, - headers.first_paragraph_len, + headers.first_paragraph_text_len, + headers.first_paragraph_md_len, self.check_private_items, ); match item.kind { @@ -851,7 +852,8 @@ struct DocHeaders { safety: bool, errors: bool, panics: bool, - first_paragraph_len: usize, + first_paragraph_md_len: usize, + first_paragraph_text_len: usize, } /// Does some pre-processing on raw, desugared `#[doc]` attributes such as parsing them and @@ -1230,11 +1232,13 @@ fn check_doc<'a, Events: Iterator, Range { + if is_first_paragraph { + is_first_paragraph = false; + } if let End(TagEnd::Heading(_)) = event { in_heading = false; } @@ -1255,7 +1259,9 @@ fn check_doc<'a, Events: Iterator, Range, Range in_footnote_definition = true, End(TagEnd::FootnoteDefinition) => in_footnote_definition = false, Start(_) | End(_) // We don't care about other tags - | TaskListMarker(_) | Code(_) | Rule | InlineMath(..) | DisplayMath(..) => (), + | TaskListMarker(_) | Rule => (), SoftBreak | HardBreak => { + if is_first_paragraph { + headers.first_paragraph_text_len += 1; + } if !containers.is_empty() && !in_footnote_definition // Tabs aren't handled correctly vvvv @@ -1290,7 +1299,15 @@ fn check_doc<'a, Events: Iterator, Range { + if is_first_paragraph { + headers.first_paragraph_text_len += code.chars().count(); + } + } Text(text) => { + if is_first_paragraph { + headers.first_paragraph_text_len += text.chars().count(); + } paragraph_range.end = range.end; let range_ = range.clone(); ticks_unbalanced |= text.contains('`') diff --git a/src/tools/clippy/clippy_lints/src/doc/too_long_first_doc_paragraph.rs b/src/tools/clippy/clippy_lints/src/doc/too_long_first_doc_paragraph.rs index 8ba6e9d332ba8..0bafd63732a56 100644 --- a/src/tools/clippy/clippy_lints/src/doc/too_long_first_doc_paragraph.rs +++ b/src/tools/clippy/clippy_lints/src/doc/too_long_first_doc_paragraph.rs @@ -13,13 +13,14 @@ pub(super) fn check( cx: &LateContext<'_>, item: &Item<'_>, attrs: &[Attribute], - mut first_paragraph_len: usize, + first_paragraph_text_len: usize, + mut first_paragraph_md_len: usize, check_private_items: bool, ) { if !check_private_items && !cx.effective_visibilities.is_exported(item.owner_id.def_id) { return; } - if first_paragraph_len <= 200 + if first_paragraph_text_len <= 200 || !matches!( item.kind, // This is the list of items which can be documented AND are displayed on the module @@ -58,10 +59,10 @@ pub(super) fn check( } let len = doc.chars().count(); - if len >= first_paragraph_len { + if len >= first_paragraph_md_len { break; } - first_paragraph_len -= len; + first_paragraph_md_len -= len; } } diff --git a/src/tools/clippy/clippy_lints/src/double_parens.rs b/src/tools/clippy/clippy_lints/src/double_parens.rs index daf65e090f6ac..81ad33a75e2f3 100644 --- a/src/tools/clippy/clippy_lints/src/double_parens.rs +++ b/src/tools/clippy/clippy_lints/src/double_parens.rs @@ -1,8 +1,8 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::{SpanExt, snippet_with_applicability, snippet_with_context}; +use clippy_utils::source::{SpanExt as _, snippet_with_applicability, snippet_with_context}; use rustc_ast::ast::{Expr, ExprKind, MethodCall}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs index 5da76bc3095f2..080569c813911 100644 --- a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs +++ b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_must_use_func_call; -use clippy_utils::res::MaybeDef; -use clippy_utils::ty::{is_copy, is_must_use_ty}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::ty::{is_copy, opt_must_use_path}; use rustc_hir::{Arm, Expr, ExprKind, LangItem, Node}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; @@ -98,7 +98,7 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetRef { sym::mem_drop if !(arg_ty.needs_drop(cx.tcx, cx.typing_env()) || is_must_use_func_call(cx, arg) - || is_must_use_ty(cx, arg_ty) + || opt_must_use_path(cx, arg_ty).is_some() || drop_is_single_call_in_arm) => { (DROP_NON_DROP, DROP_NON_DROP_SUMMARY.into(), Some(arg.span)) diff --git a/src/tools/clippy/clippy_lints/src/duplicate_mod.rs b/src/tools/clippy/clippy_lints/src/duplicate_mod.rs index 4b7ffc09b820c..265721bb066d2 100644 --- a/src/tools/clippy/clippy_lints/src/duplicate_mod.rs +++ b/src/tools/clippy/clippy_lints/src/duplicate_mod.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_help; use rustc_ast::ast::{Crate, Inline, Item, ItemKind, ModKind}; use rustc_errors::MultiSpan; -use rustc_lint::{EarlyContext, EarlyLintPass, Level, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, Level, LintContext as _}; use rustc_middle::lint::UnstableLevelSpec; use rustc_session::impl_lint_pass; use rustc_span::{FileName, Span}; diff --git a/src/tools/clippy/clippy_lints/src/duration_suboptimal_units.rs b/src/tools/clippy/clippy_lints/src/duration_suboptimal_units.rs index b612d999f4787..bd6cd5fc46146 100644 --- a/src/tools/clippy/clippy_lints/src/duration_suboptimal_units.rs +++ b/src/tools/clippy/clippy_lints/src/duration_suboptimal_units.rs @@ -4,12 +4,12 @@ use clippy_config::Conf; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir::attrs::RustcVersion; use rustc_hir::{Expr, ExprKind, QPath}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::{self, TyCtxt, UintTy}; use rustc_session::impl_lint_pass; use rustc_span::Symbol; @@ -66,15 +66,16 @@ impl DurationSuboptimalUnits { if tcx.features().enabled(sym::duration_constructors) { units.extend(EXTENDED_UNITS); } - Self { msrv: conf.msrv, units } + Self { + msrv: conf.msrv.into(), + units, + } } } impl LateLintPass<'_> for DurationSuboptimalUnits { fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { - if !expr.span.in_external_macro(cx.sess().source_map()) - // Check if a function on std::time::Duration is called - && let ExprKind::Call(func, [arg]) = expr.kind + if let ExprKind::Call(func, [arg]) = expr.kind && let ExprKind::Path(QPath::TypeRelative(func_ty, func_name)) = func.kind && cx .typeck_results() @@ -98,6 +99,7 @@ impl LateLintPass<'_> for DurationSuboptimalUnits { // For expressions (e.g. `10 * 60`), always lint since the expression already // signals intent to compute a converted value. && (!matches!(arg.kind, ExprKind::Lit(_)) || promoted_value > 10) + && !expr.span.in_external_macro(cx.sess().source_map()) { span_lint_and_then( cx, @@ -110,7 +112,7 @@ impl LateLintPass<'_> for DurationSuboptimalUnits { (arg.span, promoted_value.to_string()), ]; diag.multipart_suggestion( - format!("try using {promoted_constructor}"), + format!("try using `Duration::{promoted_constructor}`"), suggestions, Applicability::MachineApplicable, ); diff --git a/src/tools/clippy/clippy_lints/src/else_if_without_else.rs b/src/tools/clippy/clippy_lints/src/else_if_without_else.rs index a38e853172f70..838b9063ef751 100644 --- a/src/tools/clippy/clippy_lints/src/else_if_without_else.rs +++ b/src/tools/clippy/clippy_lints/src/else_if_without_else.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_ast::ast::{Expr, ExprKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/empty_line_after.rs b/src/tools/clippy/clippy_lints/src/empty_line_after.rs index 834981a582832..c726fc5b6b0e9 100644 --- a/src/tools/clippy/clippy_lints/src/empty_line_after.rs +++ b/src/tools/clippy/clippy_lints/src/empty_line_after.rs @@ -1,14 +1,14 @@ use std::borrow::Cow; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::{SpanExt, snippet_indent}; +use clippy_utils::source::{SpanExt as _, snippet_indent}; use clippy_utils::tokenize_with_text; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_ast::token::CommentKind; use rustc_ast::{AssocItemKind, AttrKind, AttrStyle, Attribute, Crate, Item, ItemKind, ModKind, NodeId}; use rustc_errors::{Applicability, Diag, SuggestionStyle}; use rustc_lexer::TokenKind; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::{BytePos, ExpnKind, Ident, InnerSpan, Span, SpanData, Symbol, kw, sym}; diff --git a/src/tools/clippy/clippy_lints/src/endian_bytes.rs b/src/tools/clippy/clippy_lints/src/endian_bytes.rs index d76729047cdc5..dc2a323e8eb63 100644 --- a/src/tools/clippy/clippy_lints/src/endian_bytes.rs +++ b/src/tools/clippy/clippy_lints/src/endian_bytes.rs @@ -1,12 +1,12 @@ -use crate::Lint; use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::{is_lint_allowed, sym}; -use rustc_hir::{Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; -use rustc_middle::ty::Ty; +use core::ptr; +use rustc_errors::Applicability; +use rustc_hir::{Expr, ExprKind, QPath}; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_middle::ty; use rustc_session::declare_lint_pass; -use rustc_span::Symbol; -use std::fmt::Write; declare_clippy_lint! { /// ### What it does @@ -69,133 +69,67 @@ declare_lint_pass!(EndianBytes => [ LITTLE_ENDIAN_BYTES, ]); -const HOST_NAMES: [Symbol; 2] = [sym::from_ne_bytes, sym::to_ne_bytes]; -const LITTLE_NAMES: [Symbol; 2] = [sym::from_le_bytes, sym::to_le_bytes]; -const BIG_NAMES: [Symbol; 2] = [sym::from_be_bytes, sym::to_be_bytes]; - -#[derive(Clone, Debug)] -enum LintKind { - Host, - Little, - Big, -} - -#[derive(Clone, Copy, PartialEq)] -enum Prefix { +#[derive(Clone, Copy)] +enum Direction { From, To, } -impl LintKind { - fn allowed(&self, cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - is_lint_allowed(cx, self.as_lint(), expr.hir_id) - } - - fn as_lint(&self) -> &'static Lint { - match self { - LintKind::Host => HOST_ENDIAN_BYTES, - LintKind::Little => LITTLE_ENDIAN_BYTES, - LintKind::Big => BIG_ENDIAN_BYTES, - } - } - - fn as_name(&self, prefix: Prefix) -> Symbol { - let index = usize::from(prefix == Prefix::To); - - match self { - LintKind::Host => HOST_NAMES[index], - LintKind::Little => LITTLE_NAMES[index], - LintKind::Big => BIG_NAMES[index], - } - } -} - impl LateLintPass<'_> for EndianBytes { - fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { - let (prefix, name, ty_expr) = match expr.kind { - ExprKind::MethodCall(method_name, receiver, [], ..) => (Prefix::To, method_name.ident.name, receiver), - ExprKind::Call(function, ..) - if let ExprKind::Path(qpath) = function.kind - && let Some(def_id) = cx.qpath_res(&qpath, function.hir_id).opt_def_id() - && let Some(function_name) = cx.get_def_path(def_id).last() => - { - (Prefix::From, *function_name, expr) + fn check_expr(&mut self, cx: &LateContext<'_>, e: &Expr<'_>) { + let (sp, direction, lint, msg) = match e.kind { + // rustfmt wants to break each arm into one line per tuple element which + // really hurts readability. + #[rustfmt::skip] + ExprKind::MethodCall(seg, _, [], _) => match seg.ident.name { + sym::to_ne_bytes => (seg.ident.span, Direction::To, HOST_ENDIAN_BYTES, "use of `to_ne_bytes`"), + sym::to_le_bytes => (seg.ident.span, Direction::To, LITTLE_ENDIAN_BYTES, "use of `to_le_bytes`"), + sym::to_be_bytes => (seg.ident.span, Direction::To, BIG_ENDIAN_BYTES, "use of `to_be_bytes`"), + _ => return, + }, + #[rustfmt::skip] + ExprKind::Path(QPath::TypeRelative(_, seg)) => match seg.ident.name { + sym::from_ne_bytes => (seg.ident.span, Direction::From, HOST_ENDIAN_BYTES, "use of `from_ne_bytes`"), + sym::from_le_bytes => (seg.ident.span, Direction::From, LITTLE_ENDIAN_BYTES, "use of `from_le_bytes`"), + sym::from_be_bytes => (seg.ident.span, Direction::From, BIG_ENDIAN_BYTES, "use of `from_be_bytes`"), + sym::to_ne_bytes => (seg.ident.span, Direction::To, HOST_ENDIAN_BYTES, "use of `to_ne_bytes`"), + sym::to_le_bytes => (seg.ident.span, Direction::To, LITTLE_ENDIAN_BYTES, "use of `to_le_bytes`"), + sym::to_be_bytes => (seg.ident.span, Direction::To, BIG_ENDIAN_BYTES, "use of `to_be_bytes`"), + _ => return, }, _ => return, }; - if !expr.span.in_external_macro(cx.sess().source_map()) - && let ty = cx.typeck_results().expr_ty(ty_expr) - && ty.is_primitive_ty() + if let Some(ty) = cx.ty_based_def(e.hir_id).opt_parent(cx).opt_impl_ty(cx) + && let ty::Uint(_) | ty::Int(_) | ty::Float(_) = *ty.instantiate_identity().skip_normalization().kind() + // Only check where the name itself comes from. The point of the lints is to + // catch when the wrong byte order is used so we only care if the current crate + // decided on the byte order. Which crate actually assembled the path/call + // isn't relevant for these lints. + && !sp.in_external_macro(cx.tcx.sess.source_map()) { - maybe_lint_endian_bytes(cx, expr, prefix, name, ty); - } - } -} - -fn maybe_lint_endian_bytes(cx: &LateContext<'_>, expr: &Expr<'_>, prefix: Prefix, name: Symbol, ty: Ty<'_>) { - let ne = LintKind::Host.as_name(prefix); - let le = LintKind::Little.as_name(prefix); - let be = LintKind::Big.as_name(prefix); - - let (lint, other_lints) = match name { - name if name == ne => ((&LintKind::Host), [(&LintKind::Little), (&LintKind::Big)]), - name if name == le => ((&LintKind::Little), [(&LintKind::Host), (&LintKind::Big)]), - name if name == be => ((&LintKind::Big), [(&LintKind::Host), (&LintKind::Little)]), - _ => return, - }; - - span_lint_and_then( - cx, - lint.as_lint(), - expr.span, - format!( - "usage of the {}`{ty}::{}`{}", - if prefix == Prefix::From { "function " } else { "" }, - lint.as_name(prefix), - if prefix == Prefix::To { " method" } else { "" }, - ), - move |diag| { - // all lints disallowed, don't give help here - if [&[lint], other_lints.as_slice()] - .concat() - .iter() - .all(|lint| !lint.allowed(cx, expr)) - { - return; - } - - // ne_bytes and all other lints allowed - if lint.as_name(prefix) == ne && other_lints.iter().all(|lint| lint.allowed(cx, expr)) { - diag.help("specify the desired endianness explicitly"); - return; - } - - // le_bytes where ne_bytes allowed but be_bytes is not, or le_bytes where ne_bytes allowed but - // le_bytes is not - if (lint.as_name(prefix) == le || lint.as_name(prefix) == be) && LintKind::Host.allowed(cx, expr) { - diag.help("use the native endianness instead"); - return; - } - - let allowed_lints = other_lints.iter().filter(|lint| lint.allowed(cx, expr)); - let len = allowed_lints.clone().count(); - - let mut help_str = "use ".to_owned(); - - for (i, lint) in allowed_lints.enumerate() { - let only_one = len == 1; - if !only_one { - help_str.push_str("either of "); + span_lint_and_then(cx, lint, sp, msg, |diag| { + if !ptr::addr_eq(lint, HOST_ENDIAN_BYTES) && is_lint_allowed(cx, HOST_ENDIAN_BYTES, e.hir_id) { + let (msg, sugg) = match direction { + Direction::From => ("convert from native endian", "from_ne_bytes"), + Direction::To => ("convert to native endian", "to_ne_bytes"), + }; + diag.span_suggestion(sp, msg, sugg, Applicability::MaybeIncorrect); } - - write!(help_str, "`{ty}::{}` ", lint.as_name(prefix)).unwrap(); - - if i != len && !only_one { - help_str.push_str("or "); + if !ptr::addr_eq(lint, LITTLE_ENDIAN_BYTES) && is_lint_allowed(cx, LITTLE_ENDIAN_BYTES, e.hir_id) { + let (msg, sugg) = match direction { + Direction::From => ("convert from little endian", "from_le_bytes"), + Direction::To => ("convert to little endian", "to_le_bytes"), + }; + diag.span_suggestion(sp, msg, sugg, Applicability::MaybeIncorrect); } - } - help_str.push_str("instead"); - diag.help(help_str); - }, - ); + if !ptr::addr_eq(lint, BIG_ENDIAN_BYTES) && is_lint_allowed(cx, BIG_ENDIAN_BYTES, e.hir_id) { + let (msg, sugg) = match direction { + Direction::From => ("convert from big endian", "from_be_bytes"), + Direction::To => ("convert to big endian", "to_be_bytes"), + }; + diag.span_suggestion(sp, msg, sugg, Applicability::MaybeIncorrect); + } + }); + } + } } diff --git a/src/tools/clippy/clippy_lints/src/entry.rs b/src/tools/clippy/clippy_lints/src/entry.rs index 7e076713e3d0c..e75c8d713d046 100644 --- a/src/tools/clippy/clippy_lints/src/entry.rs +++ b/src/tools/clippy/clippy_lints/src/entry.rs @@ -6,7 +6,7 @@ use clippy_utils::{ SpanlessEq, can_move_expr_to_closure_no_visit, desugar_await, higher, is_expr_final_block_expr, is_expr_used_or_unified, paths, peel_hir_expr_while, span_contains_non_whitespace, sym, }; -use core::fmt::{self, Write}; +use core::fmt::{self, Write as _}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{Visitor, walk_body, walk_expr}; diff --git a/src/tools/clippy/clippy_lints/src/enum_clike.rs b/src/tools/clippy/clippy_lints/src/enum_clike.rs index bd92e7e850870..1313f42d7ff58 100644 --- a/src/tools/clippy/clippy_lints/src/enum_clike.rs +++ b/src/tools/clippy/clippy_lints/src/enum_clike.rs @@ -2,7 +2,7 @@ use clippy_utils::consts::{Constant, mir_to_const}; use clippy_utils::diagnostics::span_lint; use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::util::IntTypeExt; +use rustc_middle::ty::util::IntTypeExt as _; use rustc_middle::ty::{self, IntTy, UintTy}; use rustc_session::declare_lint_pass; diff --git a/src/tools/clippy/clippy_lints/src/equatable_if_let.rs b/src/tools/clippy/clippy_lints/src/equatable_if_let.rs index a92bfd45df0ce..aea06f2b0286c 100644 --- a/src/tools/clippy/clippy_lints/src/equatable_if_let.rs +++ b/src/tools/clippy/clippy_lints/src/equatable_if_let.rs @@ -4,7 +4,7 @@ use clippy_utils::source::snippet_with_context; use clippy_utils::ty::implements_trait; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, Pat, PatKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::Ty; use rustc_session::declare_lint_pass; @@ -105,7 +105,7 @@ impl<'tcx> LateLintPass<'tcx> for PatternEquality { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { if let ExprKind::Let(let_expr) = expr.kind && is_unary_pattern(let_expr.pat) - && !expr.span.in_external_macro(cx.sess().source_map()) + && !expr.span.from_expansion() && !let_expr.pat.span.from_expansion() && !let_expr.init.span.from_expansion() { diff --git a/src/tools/clippy/clippy_lints/src/error_impl_error.rs b/src/tools/clippy/clippy_lints/src/error_impl_error.rs index 4b7aaa34d1ad8..8fb0748823d14 100644 --- a/src/tools/clippy/clippy_lints/src/error_impl_error.rs +++ b/src/tools/clippy/clippy_lints/src/error_impl_error.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::{span_lint, span_lint_hir_and_then}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::sym; use clippy_utils::ty::implements_trait; use rustc_hir::def_id::{DefId, LocalDefId}; diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index e7df5fa020e34..a76fa0626ac5f 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -6,7 +6,7 @@ use rustc_hir::{Body, FnDecl, HirId, HirIdSet, PatKind, intravisit}; use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::FakeReadCause; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{self, TraitRef, Ty}; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 6248ba6e44da5..e1ad4649a5e3e 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -1,16 +1,17 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::higher::VecArgs; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::{snippet_opt, snippet_with_applicability}; use clippy_utils::usage::{local_used_after_expr, local_used_in}; use clippy_utils::{get_path_from_caller_to_method_type, is_adjusted, is_no_std_crate}; use rustc_errors::Applicability; use rustc_hir::{BindingMode, Expr, ExprKind, FnRetTy, GenericArgs, Param, PatKind, QPath, Safety, TyKind, find_attr}; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind}; use rustc_middle::ty::{ - self, Binder, ClosureKind, FnSig, GenericArg, GenericArgKind, List, Region, Ty, TypeVisitableExt, TypeckResults, + self, Binder, ClosureKind, FnSig, GenericArg, GenericArgKind, List, Region, Ty, TypeVisitableExt as _, + TypeckResults, }; use rustc_session::declare_lint_pass; use rustc_span::symbol::sym; diff --git a/src/tools/clippy/clippy_lints/src/excessive_nesting.rs b/src/tools/clippy/clippy_lints/src/excessive_nesting.rs index 58d00933a7851..0c88f3fd32285 100644 --- a/src/tools/clippy/clippy_lints/src/excessive_nesting.rs +++ b/src/tools/clippy/clippy_lints/src/excessive_nesting.rs @@ -4,7 +4,7 @@ use clippy_utils::source::snippet; use rustc_ast::node_id::NodeSet; use rustc_ast::visit::{Visitor, walk_block, walk_item}; use rustc_ast::{Block, Crate, Inline, Item, ItemKind, ModKind, NodeId}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/exit.rs b/src/tools/clippy/clippy_lints/src/exit.rs index 6030d53c3ad33..bc7b2041a77d5 100644 --- a/src/tools/clippy/clippy_lints/src/exit.rs +++ b/src/tools/clippy/clippy_lints/src/exit.rs @@ -69,6 +69,7 @@ impl<'tcx> LateLintPass<'tcx> for Exit { // in compilation contexts like --all-targets (which include --tests), you get false positives // because in a test context, main is not the entrypoint function && ident.name != sym::main + && !e.span.in_external_macro(cx.tcx.sess.source_map()) { span_lint(cx, EXIT, e.span, "usage of `process::exit`"); } diff --git a/src/tools/clippy/clippy_lints/src/explicit_write.rs b/src/tools/clippy/clippy_lints/src/explicit_write.rs index a85025a48e5a8..e66eac117cda7 100644 --- a/src/tools/clippy/clippy_lints/src/explicit_write.rs +++ b/src/tools/clippy/clippy_lints/src/explicit_write.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::{FormatArgsStorage, format_args_inputs_span}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{is_expn_of, is_in_test, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/extra_unused_type_parameters.rs b/src/tools/clippy/clippy_lints/src/extra_unused_type_parameters.rs index a6f80da5dab9c..070b0d2fb0c0a 100644 --- a/src/tools/clippy/clippy_lints/src/extra_unused_type_parameters.rs +++ b/src/tools/clippy/clippy_lints/src/extra_unused_type_parameters.rs @@ -8,7 +8,7 @@ use rustc_hir::{ AmbigArg, BodyId, ExprKind, GenericBound, GenericParam, GenericParamKind, Generics, ImplItem, ImplItemKind, Item, ItemKind, PredicateOrigin, Ty, WherePredicate, WherePredicateKind, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::hir::nested_filter; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index bd2bd66284648..a2d02b6747d7c 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::{is_panic, root_macro_call_first_node}; use clippy_utils::method_chain_args; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; diff --git a/src/tools/clippy/clippy_lints/src/float_literal.rs b/src/tools/clippy/clippy_lints/src/float_literal.rs index ab1f5b88bacee..481accb6ebbe1 100644 --- a/src/tools/clippy/clippy_lints/src/float_literal.rs +++ b/src/tools/clippy/clippy_lints/src/float_literal.rs @@ -64,7 +64,7 @@ declare_clippy_lint! { impl_lint_pass!(FloatLiteral => [EXCESSIVE_PRECISION, LOSSY_FLOAT_LITERAL]); pub struct FloatLiteral { - const_literal_digits_threshold: usize, + const_literal_digits_threshold: u32, } impl FloatLiteral { @@ -142,7 +142,7 @@ impl<'tcx> LateLintPass<'tcx> for FloatLiteral { ); } } else if digits > max as usize && count_digits(&float_str) < digits { - if digits >= self.const_literal_digits_threshold + if digits >= self.const_literal_digits_threshold as usize && matches!( get_expr_use_site(cx.tcx, cx.typeck_results(), expr.span.ctxt(), expr).use_node(cx), ExprUseNode::ConstStatic(_) @@ -158,7 +158,7 @@ impl<'tcx> LateLintPass<'tcx> for FloatLiteral { expr.span, "float has excessive precision", |diag| { - if digits >= self.const_literal_digits_threshold + if digits >= self.const_literal_digits_threshold as usize && let Some(let_stmt) = maybe_let_stmt(cx, expr) { diag.span_note(let_stmt.span, "consider making it a `const` item"); diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/lib.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/lib.rs index 3fa041f97802a..2e8af518d0cd7 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/lib.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/lib.rs @@ -5,13 +5,15 @@ use rustc_hir::{Expr, ExprKind, UnOp}; use rustc_lint::LateContext; use rustc_middle::ty; -// Adds type suffixes and parenthesis to method receivers if necessary +// Adds type suffixes and parenthesis to method receivers if necessary, and returns whether a suffix +// was added. pub(super) fn prepare_receiver_sugg<'a>( cx: &LateContext<'_>, mut expr: &'a Expr<'a>, app: &mut Applicability, -) -> Sugg<'a> { +) -> (Sugg<'a>, bool) { let mut suggestion = Sugg::hir_with_applicability(cx, expr, "_", app); + let mut suffix_was_added = false; if let ExprKind::Unary(UnOp::Neg, inner_expr) = expr.kind { expr = inner_expr; @@ -36,7 +38,8 @@ pub(super) fn prepare_receiver_sugg<'a>( Sugg::MaybeParen(_) | Sugg::UnOp(UnOp::Neg, _) => Sugg::MaybeParen(op), _ => Sugg::NonParen(op), }; + suffix_was_added = true; } - suggestion.maybe_paren() + (suggestion.maybe_paren(), suffix_was_added) } diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/ln1p.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/ln1p.rs index f37737c71aee1..d15547cf8082b 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/ln1p.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/ln1p.rs @@ -33,7 +33,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>) "ln(1 + x) can be computed more accurately", |diag| { let mut app = Applicability::MachineApplicable; - let recv = super::lib::prepare_receiver_sugg(cx, recv, &mut app); + let (recv, _) = super::lib::prepare_receiver_sugg(cx, recv, &mut app); diag.span_suggestion(expr.span, "consider using", format!("{recv}.ln_1p()"), app); }, ); diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mod.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mod.rs index 0833761b32dc7..82b08a9e7d212 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mod.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mod.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::{is_in_const_context, is_no_std_crate, sym}; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mul_add.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mul_add.rs index eb96e65638445..f5c3608696d5b 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mul_add.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/mul_add.rs @@ -1,10 +1,12 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::sugg::Sugg; -use clippy_utils::{get_parent_expr, has_ambiguous_literal_in_expr, sym}; +use clippy_utils::ty::expr_type_is_certain; +use clippy_utils::{get_parent_expr, sym}; use rustc_ast::AssignOpKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, PathSegment}; use rustc_lint::LateContext; +use rustc_middle::ty; use rustc_span::Spanned; use super::SUBOPTIMAL_FLOPS; @@ -65,24 +67,15 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) { return; } - // Check if any variable in the expression has an ambiguous type (could be f32 or f64) - // see: https://github.com/rust-lang/rust-clippy/issues/14897 - let has_ambiguous_type = |expr: &Expr<'_>| { - (matches!(expr.kind, ExprKind::Path(_)) || matches!(expr.kind, ExprKind::Call(_, _))) - && has_ambiguous_literal_in_expr(cx, expr) - }; - - let (recv, arg1, arg2, is_from_rhs) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) - && cx.typeck_results().expr_ty(lhs).is_floating_point() - && !has_ambiguous_type(inner_lhs) + let (recv, arg1, arg2, is_from_rhs, lhs_typ) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) + && let ty::Float(float_ty) = cx.typeck_results().expr_ty(lhs).kind() { - (inner_lhs, inner_rhs, lhs, true) + (inner_lhs, inner_rhs, lhs, true, float_ty) } else if !is_assign && let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) - && cx.typeck_results().expr_ty(rhs).is_floating_point() - && !has_ambiguous_type(inner_lhs) + && let ty::Float(float_ty) = cx.typeck_results().expr_ty(rhs).kind() { - (inner_lhs, inner_rhs, rhs, false) + (inner_lhs, inner_rhs, rhs, false, float_ty) } else { return; }; @@ -98,7 +91,9 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) { if let BinOpKind::Sub = op { -sugg } else { sugg } }; let mut app = Applicability::MachineApplicable; - let recv_sugg = super::lib::prepare_receiver_sugg(cx, recv, &mut app); + + let (recv_sugg, suffix_was_added) = super::lib::prepare_receiver_sugg(cx, recv, &mut app); + let (arg1, arg2) = if is_from_rhs { ( maybe_neg_sugg(arg1, &mut app), @@ -110,13 +105,21 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) { maybe_neg_sugg(arg2, &mut app), ) }; + + let mul_add_call = if suffix_was_added || expr_type_is_certain(cx, recv) { + format!("{recv_sugg}.mul_add({arg1}, {arg2})") + } else { + // If the receiver contains an ambiguous literal, we need to call `mul_add` with its inferred type. + format!("{}::mul_add({recv_sugg}, {arg1}, {arg2})", lhs_typ.name_str()) + }; + diag.span_suggestion( expr.span, "consider using", if is_assign { - format!("{arg2} = {recv_sugg}.mul_add({arg1}, {arg2})") + format!("{arg2} = {mul_add_call}") } else { - format!("{recv_sugg}.mul_add({arg1}, {arg2})") + mul_add_call }, app, ); diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/powf.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/powf.rs index 8e4a7388e7841..6ad6824083cd4 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/powf.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic/powf.rs @@ -54,7 +54,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>, "exponent for bases 2 and e can be computed more accurately", |diag| { let mut app = Applicability::MachineApplicable; - let recv = super::lib::prepare_receiver_sugg(cx, &args[0], &mut app); + let (recv, _) = super::lib::prepare_receiver_sugg(cx, &args[0], &mut app); diag.span_suggestion(expr.span, "consider using", format!("{recv}.{method}()"), app); }, ); diff --git a/src/tools/clippy/clippy_lints/src/format.rs b/src/tools/clippy/clippy_lints/src/format.rs index f13278d91ce7f..a045bada6d35a 100644 --- a/src/tools/clippy/clippy_lints/src/format.rs +++ b/src/tools/clippy/clippy_lints/src/format.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::{FormatArgsStorage, find_format_arg_expr, first_node_in_macro, matching_root_macro_call}; -use clippy_utils::source::{SpanExt, snippet_with_context}; +use clippy_utils::source::{SpanExt as _, snippet_with_context}; use clippy_utils::sugg::Sugg; use rustc_ast::{FormatArgsPiece, FormatOptions, FormatTrait}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index 826918dd22547..69fdf84dfe7d9 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/clippy_lints/src/format_args.rs @@ -9,11 +9,11 @@ use clippy_utils::macros::{ root_macro_call_first_node, }; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::{SpanExt, snippet, snippet_opt}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::{SpanExt as _, snippet, snippet_opt}; use clippy_utils::ty::implements_trait; use clippy_utils::{is_from_proc_macro, is_in_test, peel_hir_expr_while, sym, trait_ref_of_method}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_ast::FormatTrait::{Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex}; use rustc_ast::{ BorrowKind, FormatArgPosition, FormatArgPositionKind, FormatArgsPiece, FormatArgumentKind, FormatCount, @@ -24,13 +24,13 @@ use rustc_errors::Applicability; use rustc_errors::SuggestionStyle::{CompletelyHidden, ShowCode}; use rustc_hir::attrs::RustcVersion; use rustc_hir::{Expr, ExprKind, LangItem, find_attr}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind}; -use rustc_middle::ty::{self, GenericArg, List, TraitRef, Ty, TyCtxt, Unnormalized, Upcast}; +use rustc_middle::ty::{self, GenericArg, List, TraitRef, Ty, TyCtxt, Unnormalized, Upcast as _}; use rustc_session::impl_lint_pass; use rustc_span::edition::Edition::Edition2021; -use rustc_span::{BytePos, Pos, Span, Symbol}; -use rustc_trait_selection::infer::TyCtxtInferExt; +use rustc_span::{BytePos, Pos as _, Span, Symbol}; +use rustc_trait_selection::infer::TyCtxtInferExt as _; use rustc_trait_selection::traits::{Obligation, ObligationCause, Selection, SelectionContext}; declare_clippy_lint! { @@ -328,7 +328,7 @@ impl<'tcx> FormatArgs<'tcx> { let ty_msrv_map = make_ty_msrv_map(tcx); Self { format_args, - msrv: conf.msrv, + msrv: conf.msrv.into(), ignore_mixed: conf.allow_mixed_uninlined_format_args, ty_msrv_map, has_derived_debug: FxHashMap::default(), diff --git a/src/tools/clippy/clippy_lints/src/format_impl.rs b/src/tools/clippy/clippy_lints/src/format_impl.rs index 4d0a324a2a39c..850e0a1ab5441 100644 --- a/src/tools/clippy/clippy_lints/src/format_impl.rs +++ b/src/tools/clippy/clippy_lints/src/format_impl.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg}; use clippy_utils::macros::{FormatArgsStorage, find_format_arg_expr, is_format_macro, root_macro_call_first_node}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::{get_parent_as_impl, peel_ref_operators, sym}; use rustc_ast::{FormatArgsPiece, FormatTrait}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/format_push_string.rs b/src/tools/clippy/clippy_lints/src/format_push_string.rs index d5a7cffe9e6c8..9a092729762dd 100644 --- a/src/tools/clippy/clippy_lints/src/format_push_string.rs +++ b/src/tools/clippy/clippy_lints/src/format_push_string.rs @@ -1,11 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::{FormatArgsStorage, format_args_inputs_span, root_macro_call_first_node}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::{std_or_core, sym}; use rustc_errors::Applicability; use rustc_hir::{AssignOpKind, Expr, ExprKind, LangItem, MatchSource}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/formatting.rs b/src/tools/clippy/clippy_lints/src/formatting.rs index 87e290cf03579..39106e0fcd4cd 100644 --- a/src/tools/clippy/clippy_lints/src/formatting.rs +++ b/src/tools/clippy/clippy_lints/src/formatting.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note}; use clippy_utils::is_span_if; use clippy_utils::source::snippet_opt; use rustc_ast::ast::{BinOpKind, Block, Expr, ExprKind, StmtKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/four_forward_slashes.rs b/src/tools/clippy/clippy_lints/src/four_forward_slashes.rs index c64e742592080..0c27d18016f1e 100644 --- a/src/tools/clippy/clippy_lints/src/four_forward_slashes.rs +++ b/src/tools/clippy/clippy_lints/src/four_forward_slashes.rs @@ -1,9 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::SpanExt as _; -use itertools::Itertools; +use itertools::Itertools as _; +use rustc_ast::AttrStyle; use rustc_errors::Applicability; -use rustc_hir::Item; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::{Attribute, Item}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::Span; @@ -48,7 +50,19 @@ impl<'tcx> LateLintPass<'tcx> for FourForwardSlashes { .tcx .hir_attrs(item.hir_id()) .iter() - .filter(|i| i.is_doc_comment().is_some()) + // Only fold in OUTER doc comments. An inner doc (`//!`) inside the item's + // body lowers onto the item with `AttrStyle::Inner`; folding its span drags + // `end_line` down into the body, so the upward `////` scan then flags a + // regular comment there (see #16168). + .filter(|i| { + matches!( + i, + Attribute::Parsed(AttributeKind::DocComment { + style: AttrStyle::Outer, + .. + }) + ) + }) .fold(item.span.shrink_to_lo(), |span, attr| span.to(attr.span())); let (Some(file), _, _, end_line, _) = sm.span_to_location_info(span) else { return; diff --git a/src/tools/clippy/clippy_lints/src/from_over_into.rs b/src/tools/clippy/clippy_lints/src/from_over_into.rs index 7c2dc59f66d5b..55ce577b8ddd2 100644 --- a/src/tools/clippy/clippy_lints/src/from_over_into.rs +++ b/src/tools/clippy/clippy_lints/src/from_over_into.rs @@ -4,8 +4,8 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::span_is_local; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::SpanExt as _; use rustc_errors::Applicability; use rustc_hir::intravisit::{Visitor, walk_path}; use rustc_hir::{ @@ -60,7 +60,7 @@ pub struct FromOverInto { impl FromOverInto { pub fn new(conf: &'static Conf) -> Self { - FromOverInto { msrv: conf.msrv } + FromOverInto { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/from_raw_with_void_ptr.rs b/src/tools/clippy/clippy_lints/src/from_raw_with_void_ptr.rs index 5c6d6607a0aa2..b419b43190a21 100644 --- a/src/tools/clippy/clippy_lints/src/from_raw_with_void_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/from_raw_with_void_ptr.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::sym; use clippy_utils::ty::is_c_void; use rustc_hir::def_id::DefId; diff --git a/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs b/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs index df8a35d9658b0..5540c50906e2b 100644 --- a/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs +++ b/src/tools/clippy/clippy_lints/src/from_str_radix_10.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sugg::Sugg; use clippy_utils::{is_in_const_context, is_integer_literal, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/functions/mod.rs b/src/tools/clippy/clippy_lints/src/functions/mod.rs index 7c5fd760a7da8..3caabc609f570 100644 --- a/src/tools/clippy/clippy_lints/src/functions/mod.rs +++ b/src/tools/clippy/clippy_lints/src/functions/mod.rs @@ -25,7 +25,7 @@ declare_clippy_lint! { /// ### What it does /// Checks for a `#[must_use]` attribute without /// further information on functions and methods that return a type already - /// marked as `#[must_use]`. + /// considered as `#[must_use]`. /// /// ### Why is this bad? /// The attribute isn't needed. Not using the result @@ -39,6 +39,12 @@ declare_clippy_lint! { /// unimplemented!(); /// } /// ``` + /// + /// ### Note + /// The compiler may consider a type as being indirectly `#[must_use]`. For + /// example, although `Box<_>` itself is not `#[must_use]`, `Box` will be + /// considered `#[must_use]` if `T` is. + /// ``` #[clippy::version = "1.40.0"] pub DOUBLE_MUST_USE, style, @@ -525,7 +531,7 @@ impl Functions { .iter() .flat_map(|p| lookup_path_str(tcx, PathNS::Type, p)) .collect(), - msrv: conf.msrv, + msrv: conf.msrv.into(), } } } diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index 1dc23df6706ca..1b7db66366b87 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -1,17 +1,17 @@ -use clippy_utils::res::MaybeDef as _; use hir::FnSig; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::def_id::DefIdSet; use rustc_hir::{self as hir, Attribute, QPath, find_attr}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::unused::must_use::MustUsePath; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::{self, Ty}; use rustc_span::{Span, sym}; use clippy_utils::attrs::is_proc_macro; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_indent; -use clippy_utils::ty::is_must_use_ty; +use clippy_utils::ty::{describe_must_use_type, opt_must_use_path}; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{is_entrypoint_fn, return_ty, trait_ref_of_method}; use rustc_span::Symbol; @@ -161,11 +161,13 @@ fn check_needless_must_use( } }, ); - } else if reason.is_none() && is_must_use_ty(cx, return_ty(cx, item_id)) { + } else if reason.is_none() + && let Some(return_must_use_path) = opt_must_use_path(cx, return_ty(cx, item_id)) + { // Ignore async functions unless Future::Output type is a must_use type if sig.header.is_async() && let Some(future_ty) = cx.tcx.get_impl_future_output_ty(return_ty(cx, item_id)) - && !is_must_use_ty(cx, future_ty) + && opt_must_use_path(cx, future_ty).is_none() { return; } @@ -174,8 +176,18 @@ fn check_needless_must_use( cx, DOUBLE_MUST_USE, fn_header_span, - "this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]`", + "this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]`", |diag| { + // Add info about the reason why the return type is `#[must_use]` if it is a compound type. + if !matches!(return_must_use_path, MustUsePath::Def(..)) { + diag.span_note( + sig.decl.output.span(), + format!( + "the return type is {}", + describe_must_use_type(cx, &return_must_use_path) + ), + ); + } // When there are multiple attributes, it is not sufficient to simply make `must_use` empty, see // issue #12320. // FIXME(jdonszelmann): this used to give a machine-applicable fix. However, it was super fragile, @@ -206,7 +218,7 @@ fn check_must_use_candidate<'tcx>( || item_span.in_external_macro(cx.sess().source_map()) || returns_unit(decl) || !cx.effective_visibilities.is_exported(item_id.def_id) - || is_must_use_ty(cx, return_ty(cx, item_id)) + || opt_must_use_path(cx, return_ty(cx, item_id)).is_some() || item_span.from_expansion() || is_entrypoint_fn(cx, item_id.def_id.to_def_id()) { @@ -220,13 +232,6 @@ fn check_must_use_candidate<'tcx>( format!("#[must_use]\n{indent}"), Applicability::MachineApplicable, ); - if let Some(msg) = match return_ty(cx, item_id).opt_diag_name(cx) { - Some(sym::ControlFlow) => Some("`ControlFlow` as `C` when `B` is uninhabited"), - Some(sym::Result) => Some("`Result` as `T` when `E` is uninhabited"), - _ => None, - } { - diag.note(format!("a future version of Rust will treat {msg} wrt `#[must_use]`")); - } }); } diff --git a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs index c2dd6e681b002..7555a6719b6de 100644 --- a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs +++ b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use rustc_hir::{self as hir, HirId, HirIdSet, intravisit}; use rustc_lint::LateContext; use rustc_middle::ty; diff --git a/src/tools/clippy/clippy_lints/src/functions/ref_option.rs b/src/tools/clippy/clippy_lints/src/functions/ref_option.rs index 1727f50b521a6..1afec00f94792 100644 --- a/src/tools/clippy/clippy_lints/src/functions/ref_option.rs +++ b/src/tools/clippy/clippy_lints/src/functions/ref_option.rs @@ -6,14 +6,13 @@ use clippy_utils::{is_from_proc_macro, is_trait_impl_item}; use rustc_errors::Applicability; use rustc_hir::intravisit::FnKind; use rustc_hir::{self as hir, FnDecl, HirId}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::{self, Mutability, Ty}; use rustc_span::Span; use rustc_span::def_id::LocalDefId; fn check_ty<'a>(cx: &LateContext<'a>, param: &hir::Ty<'a>, param_ty: Ty<'a>, fixes: &mut Vec<(Span, String)>) { - if !param.span.in_external_macro(cx.sess().source_map()) - && let ty::Ref(_, opt_ty, Mutability::Not) = param_ty.kind() + if let ty::Ref(_, opt_ty, Mutability::Not) = param_ty.kind() && let Some(gen_ty) = option_arg_ty(cx, *opt_ty) && !gen_ty.is_ref() // Need to gen the original spans, so first parsing mid, and hir parsing afterward @@ -24,6 +23,7 @@ fn check_ty<'a>(cx: &LateContext<'a>, param: &hir::Ty<'a>, param_ty: Ty<'a>, fix args: [hir::GenericArg::Type(opt_ty)], .. }) = last.args + && !param.span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, param) { let lifetime = snippet(cx, lifetime.ident.span, ".."); diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index 816f2cac8429b..6a7013e0f1737 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -1,8 +1,8 @@ use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_errors::Diag; use rustc_hir as hir; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::{self, Ty}; use rustc_span::def_id::DefIdSet; use rustc_span::{Span, sym}; diff --git a/src/tools/clippy/clippy_lints/src/functions/too_many_lines.rs b/src/tools/clippy/clippy_lints/src/functions/too_many_lines.rs index a5fed9f03a620..9920f2e8f6b85 100644 --- a/src/tools/clippy/clippy_lints/src/functions/too_many_lines.rs +++ b/src/tools/clippy/clippy_lints/src/functions/too_many_lines.rs @@ -1,9 +1,9 @@ use clippy_utils::diagnostics::span_lint; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::FnKind; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_span::Span; use super::TOO_MANY_LINES; @@ -18,7 +18,7 @@ pub(super) fn check_fn( ) { // Closures must be contained in a parent body, which will be checked for `too_many_lines`. // Don't check closures for `too_many_lines` to avoid duplicated lints. - if matches!(kind, FnKind::Closure) || span.in_external_macro(cx.sess().source_map()) { + if matches!(kind, FnKind::Closure) || (span.from_expansion() && span.in_external_macro(cx.sess().source_map())) { return; } diff --git a/src/tools/clippy/clippy_lints/src/future_not_send.rs b/src/tools/clippy/clippy_lints/src/future_not_send.rs index f4a3e01bbe0d4..f58bd3ffaebab 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -4,17 +4,17 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::return_ty; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl}; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::print::PrintTraitRefExt; +use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{ - self, AliasTy, Binder, ClauseKind, PredicateKind, Ty, TyCtxt, TypeVisitable, TypeVisitableExt, TypeVisitor, - Unnormalized, + self, AliasTy, Binder, ClauseKind, PredicateKind, Ty, TyCtxt, TypeVisitable as _, TypeVisitableExt as _, + TypeVisitor, Unnormalized, }; use rustc_session::declare_lint_pass; use rustc_span::def_id::LocalDefId; use rustc_span::{Span, sym}; -use rustc_trait_selection::error_reporting::InferCtxtErrorExt; +use rustc_trait_selection::error_reporting::InferCtxtErrorExt as _; use rustc_trait_selection::traits::{self, FulfillmentError, ObligationCtxt}; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs index 38fda71fccf2f..d03fa1472e252 100644 --- a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs +++ b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{eq_expr_value, higher, sym}; use core::ops::ControlFlow; diff --git a/src/tools/clippy/clippy_lints/src/if_not_else.rs b/src/tools/clippy/clippy_lints/src/if_not_else.rs index ea1992d471312..9b904699b9afc 100644 --- a/src/tools/clippy/clippy_lints/src/if_not_else.rs +++ b/src/tools/clippy/clippy_lints/src/if_not_else.rs @@ -52,6 +52,7 @@ impl LateLintPass<'_> for IfNotElse { fn check_expr(&mut self, cx: &LateContext<'_>, e: &Expr<'_>) { if let ExprKind::If(cond, cond_inner, Some(els)) = e.kind && let ExprKind::Block(..) = els.kind + && !cond.span.from_expansion() { let (msg, help) = match cond.kind { ExprKind::Unary(UnOp::Not, _) => ( @@ -61,7 +62,7 @@ impl LateLintPass<'_> for IfNotElse { // Don't lint on `… != 0`, as these are likely to be bit tests. // For example, `if foo & 0x0F00 != 0 { … } else { … }` is already in the "proper" order. ExprKind::Binary(op, _, rhs) - if op.node == BinOpKind::Ne && !is_zero_integer_const(cx, rhs, e.span.ctxt()) => + if op.node == BinOpKind::Ne && !is_zero_integer_const(cx, rhs, cond.span.ctxt()) => { ( "unnecessary `!=` operation", diff --git a/src/tools/clippy/clippy_lints/src/if_then_some_else_none.rs b/src/tools/clippy/clippy_lints/src/if_then_some_else_none.rs index 2d5ccc0b82b71..32e69900a59f1 100644 --- a/src/tools/clippy/clippy_lints/src/if_then_some_else_none.rs +++ b/src/tools/clippy/clippy_lints/src/if_then_some_else_none.rs @@ -58,7 +58,7 @@ pub struct IfThenSomeElseNone { impl IfThenSomeElseNone { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/ifs/branches_sharing_code.rs b/src/tools/clippy/clippy_lints/src/ifs/branches_sharing_code.rs index 2701cdaa394da..ff4683349ad88 100644 --- a/src/tools/clippy/clippy_lints/src/ifs/branches_sharing_code.rs +++ b/src/tools/clippy/clippy_lints/src/ifs/branches_sharing_code.rs @@ -1,15 +1,18 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::{IntoSpan, SpanExt, first_line_of_span, indent_of, reindent_multiline, snippet}; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::{IntoSpan as _, SpanExt as _, first_line_of_span, indent_of, reindent_multiline, snippet}; use clippy_utils::ty::needs_ordered_drop; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{ ContainsName, HirEqInterExpr, SpanlessEq, capture_local_usage, get_enclosing_block, hash_expr, hash_stmt, + is_expr_final_block_expr, }; use core::iter; use core::ops::ControlFlow; use rustc_errors::Applicability; -use rustc_hir::{Block, Expr, ExprKind, HirId, HirIdSet, ItemKind, LetStmt, Node, Stmt, StmtKind, UseKind, intravisit}; +use rustc_hir::{ + Arm, Block, Expr, ExprKind, HirId, HirIdSet, ItemKind, LetStmt, Node, Stmt, StmtKind, UseKind, intravisit, +}; use rustc_lint::LateContext; use rustc_span::hygiene::walk_chain; use rustc_span::source_map::SourceMap; @@ -100,6 +103,111 @@ pub(super) fn check<'tcx>( }); } +/// Detects `match` expressions where every arm's body is a block ending in the same trailing +/// expression, so that expression can be hoisted out below the `match`. +/// +/// ```ignore +/// match mode { +/// Mode::A => { a(); Ok(()) } +/// Mode::B => { b(); Ok(()) } +/// } +/// ``` +/// can become +/// ```ignore +/// match mode { +/// Mode::A => a(), +/// Mode::B => b(), +/// } +/// Ok(()) +/// ``` +pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arms: &'tcx [Arm<'tcx>]) { + if arms.len() < 2 { + return; + } + + // We only move the shared expression after the `match`, so the `match` must be in tail position + // of its block. Cheapest, most selective check, so do it first. + if !is_expr_final_block_expr(cx.tcx, expr) { + return; + } + + // Each arm body must be a block with a trailing expression. + let mut blocks = Vec::with_capacity(arms.len()); + for arm in arms { + let ExprKind::Block(block, None) = arm.body.kind else { + return; + }; + let Some(tail) = block.expr else { + return; + }; + if block.span.from_expansion() || tail.span.from_expansion() { + return; + } + // Same drop-order concern for arm-locals dropped at the end of the arm. + let arm_local_needs_ordered_drop = block.stmts.iter().any(|stmt| { + matches!(stmt.kind, StmtKind::Let(l) if needs_ordered_drop(cx, cx.typeck_results().node_type(l.hir_id))) + }); + if arm_local_needs_ordered_drop { + return; + } + blocks.push((block, tail)); + } + + // All tails must be equal. This also rules out tails referencing an arm-local: those have a + // distinct `HirId` per arm and so never compare equal. + let first = blocks[0].1; + let mut eq = SpanlessEq::new(cx); + if !blocks[1..] + .iter() + .all(|&(_, t)| eq.eq_expr(SyntaxContext::root(), first, t)) + { + return; + } + + // Don't bother for a `()` tail: nothing worth moving. + if matches!(first.kind, ExprKind::Tup([])) { + return; + } + + // Require some code before the tail, else hoisting just leaves empty arms. + if blocks.iter().all(|(block, _)| block.stmts.is_empty()) { + return; + } + + span_lint_and_then( + cx, + BRANCHES_SHARING_CODE, + expr.span, + "all match arms end with the same expression", + |diag| { + let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0)); + let tail_snippet = snippet(cx, first.span, "..").into_owned(); + let mut suggestions: Vec<(Span, String)> = blocks + .iter() + .map(|&(block, tail)| { + // Drop the tail (and the whitespace before it) from each arm. + let span = match block.stmts.last() { + Some(last) => last.span.shrink_to_hi().to(tail.span), + None => tail.span, + }; + (span, String::new()) + }) + .collect(); + suggestions.push((expr.span.shrink_to_hi(), format!("\n{indent}{tail_snippet}"))); + // `Unspecified`, like the if/else end-suggestion: may need manual adjustment (e.g. a + // significant-drop temporary in the scrutinee), so don't auto-apply via `--fix`. + diag.multipart_suggestion( + "consider moving the shared expression after the `match`", + suggestions, + Applicability::Unspecified, + ); + diag.note( + "the suggestion may need adjustments to preserve drop order or to use the expression result correctly", + ); + }, + ); +} + struct BlockEq { /// The end of the range of equal stmts at the start. start_end_eq: usize, diff --git a/src/tools/clippy/clippy_lints/src/ifs/ifs_same_cond.rs b/src/tools/clippy/clippy_lints/src/ifs/ifs_same_cond.rs index ac010a9314b3c..fd9bbc1d7e7ab 100644 --- a/src/tools/clippy/clippy_lints/src/ifs/ifs_same_cond.rs +++ b/src/tools/clippy/clippy_lints/src/ifs/ifs_same_cond.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::ty::InteriorMut; use clippy_utils::{SpanlessEq, eq_expr_value, find_binding_init, hash_expr, search_same}; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/ifs/mod.rs b/src/tools/clippy/clippy_lints/src/ifs/mod.rs index 8a22d8935368d..8e693c3e0e701 100644 --- a/src/tools/clippy/clippy_lints/src/ifs/mod.rs +++ b/src/tools/clippy/clippy_lints/src/ifs/mod.rs @@ -13,8 +13,8 @@ mod same_functions_in_if_cond; declare_clippy_lint! { /// ### What it does - /// Checks if the `if` and `else` block contain shared code that can be - /// moved out of the blocks. + /// Checks if the blocks of an `if`/`else`, or the arms of a `match`, contain shared code that + /// can be moved out of the branches. /// /// ### Why is this bad? /// Duplicate code is less maintainable. @@ -39,6 +39,24 @@ declare_clippy_lint! { /// 42 /// }; /// ``` + /// + /// For a `match`, when every arm ends with the same expression it can be moved after the + /// `match`: + /// ```ignore + /// match mode { + /// Mode::A => { a(); Ok(()) } + /// Mode::B => { b(); Ok(()) } + /// } + /// ``` + /// + /// Use instead: + /// ```ignore + /// match mode { + /// Mode::A => { a(); } + /// Mode::B => { b(); } + /// } + /// Ok(()) + /// ``` #[clippy::version = "1.53.0"] pub BRANCHES_SHARING_CODE, nursery, @@ -168,7 +186,10 @@ impl<'tcx> CopyAndPaste<'tcx> { impl<'tcx> LateLintPass<'tcx> for CopyAndPaste<'tcx> { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if !expr.span.from_expansion() && matches!(expr.kind, ExprKind::If(..)) && !is_else_clause(cx.tcx, expr) { + if expr.span.from_expansion() { + return; + } + if matches!(expr.kind, ExprKind::If(..)) && !is_else_clause(cx.tcx, expr) { let (conds, blocks) = if_sequence(expr); ifs_same_cond::check(cx, &conds, &mut self.interior_mut); same_functions_in_if_cond::check(cx, &conds); @@ -177,6 +198,8 @@ impl<'tcx> LateLintPass<'tcx> for CopyAndPaste<'tcx> { if !all_same && conds.len() != blocks.len() { branches_sharing_code::check(cx, &conds, &blocks, expr); } + } else if let ExprKind::Match(_, arms, _) = expr.kind { + branches_sharing_code::check_match(cx, expr, arms); } } } diff --git a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs index 03a48bc08612a..758e3114089ef 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs @@ -1,9 +1,9 @@ use std::borrow::Cow; use std::collections::BTreeMap; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_errors::{Applicability, Diag}; -use rustc_hir::intravisit::{Visitor, VisitorExt, walk_body, walk_expr, walk_ty}; +use rustc_hir::intravisit::{Visitor, VisitorExt as _, walk_body, walk_expr, walk_ty}; use rustc_hir::{self as hir, AmbigArg, Body, Expr, ExprKind, GenericArg, Item, ItemKind, QPath, TyKind}; use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass}; @@ -13,7 +13,7 @@ use rustc_session::declare_lint_pass; use rustc_span::Span; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::{IntoSpan, SpanExt, snippet, snippet_with_context}; +use clippy_utils::source::{IntoSpan as _, SpanExt as _, snippet, snippet_with_context}; use clippy_utils::sym; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index 6ed478b2708a3..6494331846f0f 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -6,7 +6,7 @@ use core::ops::ControlFlow; use rustc_errors::Applicability; use rustc_hir::intravisit::FnKind; use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::def_id::LocalDefId; use rustc_span::{Span, SyntaxContext}; diff --git a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs index 4093ff9f4b2d8..9fb0409f012a6 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs @@ -90,7 +90,7 @@ pub struct ImplicitSaturatingSub { impl ImplicitSaturatingSub { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } @@ -104,7 +104,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { // Check if the conditional expression is a binary operation && let ExprKind::Binary(ref cond_op, cond_left, cond_right) = cond.kind { - check_with_condition(cx, expr, cond_op.node, cond_left, cond_right, then); + check_with_condition(cx, expr, cond_op.node, cond_left, cond_right, then, self.msrv); } else if let Some(higher::If { cond, then: if_block, @@ -309,6 +309,7 @@ fn check_with_condition<'tcx>( cond_left: &Expr<'tcx>, cond_right: &Expr<'tcx>, then: &Expr<'tcx>, + msrv: Msrv, ) { // Ensure that the binary operator is >, !=, or < if (BinOpKind::Ne == cond_op || BinOpKind::Gt == cond_op || BinOpKind::Lt == cond_op) @@ -342,6 +343,10 @@ fn check_with_condition<'tcx>( return; } + if is_in_const_context(cx) && !msrv.meets(cx, msrvs::SATURATING_SUB_CONST) { + return; + } + // Get the variable name let var_name = ares_path.segments[0].ident.name; match cond_num_val.kind { diff --git a/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs b/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs index 6620f89e6f67f..73467def31757 100644 --- a/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs +++ b/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs @@ -119,7 +119,7 @@ pub struct IncompatibleMsrv { impl IncompatibleMsrv { pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), availability_cache: FxHashMap::default(), check_in_tests: conf.check_incompatible_msrv_in_tests, std_crates: StdCrates::new(tcx), diff --git a/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs b/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs index b1f03babb9fa5..406445ff1f0a3 100644 --- a/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs +++ b/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs @@ -4,7 +4,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher::IfLet; use clippy_utils::is_lint_allowed; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::ty::is_copy; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::Applicability; @@ -64,7 +64,7 @@ impl IndexRefutableSlice { pub fn new(conf: &'static Conf) -> Self { Self { max_suggested_slice: conf.max_suggested_slice_pattern_length, - msrv: conf.msrv, + msrv: conf.msrv.into(), } } } diff --git a/src/tools/clippy/clippy_lints/src/ineffective_open_options.rs b/src/tools/clippy/clippy_lints/src/ineffective_open_options.rs index aae847031bf64..7c52b4b9e3648 100644 --- a/src/tools/clippy/clippy_lints/src/ineffective_open_options.rs +++ b/src/tools/clippy/clippy_lints/src/ineffective_open_options.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::{peel_blocks, peel_hir_expr_while, sym}; use rustc_ast::LitKind; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/infallible_try_from.rs b/src/tools/clippy/clippy_lints/src/infallible_try_from.rs index 7472ec0a2106b..3a5c833837736 100644 --- a/src/tools/clippy/clippy_lints/src/infallible_try_from.rs +++ b/src/tools/clippy/clippy_lints/src/infallible_try_from.rs @@ -59,7 +59,11 @@ impl<'tcx> LateLintPass<'tcx> for InfallibleTryFrom { .filter_by_name_unhygienic_and_kind(sym::Error, AssocTag::Type) { let ii_ty = cx.tcx.type_of(ii.def_id).instantiate_identity().skip_norm_wip(); - if !ii_ty.is_inhabited_from(cx.tcx, cx.tcx.parent_module_from_def_id(ii.def_id.expect_local()), cx.typing_env()) { + if !ii_ty.is_inhabited_from( + cx.tcx, + cx.tcx.parent_module_from_def_id(ii.def_id.expect_local()), + cx.typing_env(), + ) { let mut span = MultiSpan::from_span(cx.tcx.def_span(item.owner_id.to_def_id())); let ii_ty_span = cx .tcx diff --git a/src/tools/clippy/clippy_lints/src/infinite_iter.rs b/src/tools/clippy/clippy_lints/src/infinite_iter.rs index 8b0a4b4d78d9a..93372747ce7c3 100644 --- a/src/tools/clippy/clippy_lints/src/infinite_iter.rs +++ b/src/tools/clippy/clippy_lints/src/infinite_iter.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::implements_trait; use clippy_utils::{higher, sym}; use rustc_hir::{BorrowKind, Closure, Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs index afe2a1033ceeb..e01200329e8e2 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::implements_trait; use clippy_utils::{return_ty, trait_ref_of_method}; use rustc_abi::ExternAbi; diff --git a/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs b/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs index 2da13b57aec44..f2370a3392796 100644 --- a/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs +++ b/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::sugg::DiagExt; +use clippy_utils::sugg::DiagExt as _; use rustc_errors::Applicability; use rustc_hir::{TraitFn, TraitItem, TraitItemKind, find_attr}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/inline_trait_bounds.rs b/src/tools/clippy/clippy_lints/src/inline_trait_bounds.rs index 87e63e8732fe8..4babe0ce3fc9e 100644 --- a/src/tools/clippy/clippy_lints/src/inline_trait_bounds.rs +++ b/src/tools/clippy/clippy_lints/src/inline_trait_bounds.rs @@ -5,7 +5,7 @@ use rustc_ast::ast::{Fn, FnRetTy, GenericParam, GenericParamKind}; use rustc_ast::visit::{FnCtxt, FnKind}; use rustc_ast::{HasAttrs as _, NodeId}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/items_after_statements.rs b/src/tools/clippy/clippy_lints/src/items_after_statements.rs index 021d43cefdda6..afb8863f1b942 100644 --- a/src/tools/clippy/clippy_lints/src/items_after_statements.rs +++ b/src/tools/clippy/clippy_lints/src/items_after_statements.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_hir; use rustc_hir::{Block, ItemKind, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/items_after_test_module.rs b/src/tools/clippy/clippy_lints/src/items_after_test_module.rs index f83bcb3cf4076..979fa0c16600a 100644 --- a/src/tools/clippy/clippy_lints/src/items_after_test_module.rs +++ b/src/tools/clippy/clippy_lints/src/items_after_test_module.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::{fulfill_or_allowed, is_cfg_test, is_from_proc_macro}; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_hir::{HirId, Item, ItemKind, Mod}; diff --git a/src/tools/clippy/clippy_lints/src/iter_over_hash_type.rs b/src/tools/clippy/clippy_lints/src/iter_over_hash_type.rs index aec863af47717..1813d682dde56 100644 --- a/src/tools/clippy/clippy_lints/src/iter_over_hash_type.rs +++ b/src/tools/clippy/clippy_lints/src/iter_over_hash_type.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::higher::ForLoop; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; diff --git a/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs b/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs index fc0a725e06335..a7ba9755dba75 100644 --- a/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs +++ b/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs @@ -5,7 +5,7 @@ use clippy_utils::{get_parent_as_impl, sym}; use rustc_ast::Mutability; use rustc_errors::Applicability; use rustc_hir::{FnRetTy, ImplItemKind, ImplicitSelfKind, ItemKind, TyKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::{self, Ty}; use rustc_session::declare_lint_pass; @@ -205,13 +205,12 @@ impl {self_ty_without_ref} {{ _ => return, }; - if !item.span.in_external_macro(cx.sess().source_map()) - && let ImplItemKind::Fn(sig, _) = item.kind + if let ImplItemKind::Fn(sig, _) = item.kind && let FnRetTy::Return(ret) = sig.decl.output + && sig.decl.inputs.len() == 1 + && sig.decl.implicit_self() == expected_implicit_self && is_nameable_in_impl_trait(ret) && cx.tcx.generics_of(item_did).is_own_empty() - && sig.decl.implicit_self() == expected_implicit_self - && sig.decl.inputs.len() == 1 && let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id()) && imp.of_trait.is_none() && let sig = cx.tcx.liberate_late_bound_regions( @@ -235,6 +234,7 @@ impl {self_ty_without_ref} {{ // Only lint if the `IntoIterator` impl doesn't actually exist && !implements_trait(cx, ref_ty, into_iter_did, &[]) && is_ty_exported(cx, ref_ty.peel_refs()) + && !item.span.in_external_macro(cx.sess().source_map()) { let self_ty_snippet = format!("{borrow_prefix}{}", snippet(cx, imp.self_ty.span, "..")); diff --git a/src/tools/clippy/clippy_lints/src/large_const_arrays.rs b/src/tools/clippy/clippy_lints/src/large_const_arrays.rs index 9835c1decceee..a2acd54ba44f3 100644 --- a/src/tools/clippy/clippy_lints/src/large_const_arrays.rs +++ b/src/tools/clippy/clippy_lints/src/large_const_arrays.rs @@ -3,10 +3,10 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_errors::Applicability; use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{self, Ty, Unnormalized}; use rustc_session::impl_lint_pass; -use rustc_span::{BytePos, Pos, Span}; +use rustc_span::{BytePos, Pos as _, Span}; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs b/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs index 9b0b65cd02c7f..f304673ccecde 100644 --- a/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs +++ b/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs @@ -8,7 +8,7 @@ use clippy_utils::{is_from_proc_macro, sym}; use rustc_hir::{Expr, ExprKind, Item, ItemKind, Node}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/large_stack_frames.rs b/src/tools/clippy/clippy_lints/src/large_stack_frames.rs index 878a5bc7f8666..70c2ff94e08e1 100644 --- a/src/tools/clippy/clippy_lints/src/large_stack_frames.rs +++ b/src/tools/clippy/clippy_lints/src/large_stack_frames.rs @@ -2,7 +2,7 @@ use std::{fmt, ops}; use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::{fn_has_unsatisfiable_clauses, is_entrypoint_fn, is_in_test}; use rustc_errors::Diag; use rustc_hir::def_id::LocalDefId; @@ -147,7 +147,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeStackFrames { local_def_id: LocalDefId, ) { let def_id = local_def_id.to_def_id(); - // Building MIR for `fn`s with unsatisfiable clauses results in ICE. + // Building MIR for `fn`s with unsatisfiable preds results in ICE. if fn_has_unsatisfiable_clauses(cx, def_id) { return; } diff --git a/src/tools/clippy/clippy_lints/src/legacy_numeric_constants.rs b/src/tools/clippy/clippy_lints/src/legacy_numeric_constants.rs index 48e1414defadf..0b7aaa707eecc 100644 --- a/src/tools/clippy/clippy_lints/src/legacy_numeric_constants.rs +++ b/src/tools/clippy/clippy_lints/src/legacy_numeric_constants.rs @@ -1,13 +1,13 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::{is_from_proc_macro, sym}; use hir::def_id::DefId; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::{ExprKind, Item, ItemKind, QPath, UseKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Symbol; use rustc_span::symbol::kw; @@ -43,7 +43,7 @@ pub struct LegacyNumericConstants { impl LegacyNumericConstants { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/len_without_is_empty.rs b/src/tools/clippy/clippy_lints/src/len_without_is_empty.rs index d947fa77d80e7..0e80fc3242808 100644 --- a/src/tools/clippy/clippy_lints/src/len_without_is_empty.rs +++ b/src/tools/clippy/clippy_lints/src/len_without_is_empty.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::{fulfill_or_allowed, get_parent_as_impl, sym}; use rustc_data_structures::unord::UnordItems; use rustc_hir::def::Res; diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index cb0565ef60e5a..7718740eee36b 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -1,8 +1,8 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::Msrv; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; -use clippy_utils::source::{SpanExt, snippet_with_context}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; +use clippy_utils::source::{SpanExt as _, snippet_with_context}; use clippy_utils::sugg::{Sugg, has_enclosing_paren}; use clippy_utils::ty::implements_trait; use clippy_utils::{parent_item_name, peel_ref_operators, sym}; @@ -96,7 +96,7 @@ pub struct LenZero { impl LenZero { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/let_if_seq.rs b/src/tools/clippy/clippy_lints/src/let_if_seq.rs index dc7a916614be3..be65eaac3b5b8 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_context; use clippy_utils::visitors::is_local_used; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/let_underscore.rs b/src/tools/clippy/clippy_lints/src/let_underscore.rs index 3f8bd2223876f..97a79cfccb9e4 100644 --- a/src/tools/clippy/clippy_lints/src/let_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/let_underscore.rs @@ -1,9 +1,9 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::ty::{implements_trait, is_must_use_ty}; +use clippy_utils::ty::{describe_must_use_type, implements_trait, opt_must_use_path}; use clippy_utils::{is_from_proc_macro, is_must_use_func_call, paths}; use rustc_hir::{LetStmt, LocalSource, PatKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::{GenericArgKind, IsSuggestable}; +use rustc_middle::ty::{GenericArgKind, IsSuggestable as _}; use rustc_session::declare_lint_pass; use rustc_span::{BytePos, Span}; @@ -176,8 +176,7 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { diag.help("consider awaiting the future or dropping explicitly with `std::mem::drop`"); }, ); - } else if is_must_use_ty(cx, cx.typeck_results().expr_ty(init)) { - #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] + } else if let Some(must_use_path) = opt_must_use_path(cx, cx.typeck_results().expr_ty(init)) { span_lint_and_then( cx, LET_UNDERSCORE_MUST_USE, @@ -185,6 +184,11 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { "non-binding `let` on an expression with `#[must_use]` type", |diag| { diag.help("consider explicitly using expression value"); + let ty_span = local.ty.map_or(init.span, |ty| ty.span); + diag.span_note( + ty_span, + format!("type is {}", describe_must_use_type(cx, &must_use_path)), + ); }, ); } else if is_must_use_func_call(cx, init) { diff --git a/src/tools/clippy/clippy_lints/src/let_with_type_underscore.rs b/src/tools/clippy/clippy_lints/src/let_with_type_underscore.rs index 3f4b59382ca15..99d9b5d6011a4 100644 --- a/src/tools/clippy/clippy_lints/src/let_with_type_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/let_with_type_underscore.rs @@ -1,9 +1,9 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; -use clippy_utils::source::{IntoSpan, SpanExt}; +use clippy_utils::source::{IntoSpan as _, SpanExt as _}; use rustc_ast::{Local, TyKind}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index 974abc30db0fd..8b0765fb6c012 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -11,15 +11,11 @@ #![feature(stmt_expr_attributes)] #![feature(unwrap_infallible)] #![recursion_limit = "512"] -#![allow( - clippy::missing_docs_in_private_items, - clippy::must_use_candidate, - clippy::literal_string_with_formatting_args -)] +#![expect(clippy::literal_string_with_formatting_args, clippy::must_use_candidate)] #![warn( + rust_2018_idioms, trivial_casts, trivial_numeric_casts, - rust_2018_idioms, unused_lifetimes, unused_qualifications, rustc::internal @@ -69,6 +65,7 @@ mod arbitrary_source_item_ordering; mod arc_with_non_send_sync; mod as_conversions; mod asm_syntax; +mod assert_is_empty; mod assertions_on_constants; mod assertions_on_result_states; mod assigning_clones; @@ -76,6 +73,7 @@ mod async_yields_async; mod attrs; mod await_holding_invalid; mod bit_width; +mod block_scrutinee; mod blocks_in_conditions; mod bool_assert_comparison; mod bool_comparison; @@ -103,6 +101,7 @@ mod default_constructed_unit_structs; mod default_instead_of_iter_empty; mod default_numeric_fallback; mod default_union_representation; +mod definition_in_module_root; mod dereference; mod derivable_impls; mod derive; @@ -281,6 +280,7 @@ mod non_octal_unix_permissions; mod non_send_fields_in_send_ty; mod non_std_lazy_statics; mod non_zero_suggestions; +mod nonnull_unchecked_on_box_ptr; mod nonstandard_macro_braces; mod octal_escapes; mod only_used_in_recursion; @@ -326,6 +326,7 @@ mod regex; mod repeat_vec_with_capacity; mod replace_box; mod reserve_after_initialization; +mod rest_when_destructuring_struct; mod return_self_not_must_use; mod returns; mod same_length_and_capacity; @@ -412,20 +413,19 @@ mod zero_sized_map_values; mod zombie_processes; // end lints modules, do not remove this comment, it's used in `update_lints` -use clippy_config::{Conf, get_configuration_metadata, sanitize_explanation}; +use clippy_config::{Conf, sanitize_explanation}; use clippy_utils::macros::FormatArgsStorage; use rustc_data_structures::fx::FxHashSet; -use rustc_lint::{Lint, is_lint_pass_required}; +use rustc_lint::is_lint_pass_required; use rustc_middle::ty::TyCtxt; use utils::attr_collector::AttrStorage; pub fn explain(name: &str) -> i32 { - let target = format!("clippy::{}", name.to_ascii_uppercase()); - + let target = format!("clippy::{name}"); if let Some(info) = declared_lints::LINTS.iter().find(|info| info.lint.name == target) { println!("{}", sanitize_explanation(info.explanation)); // Check if the lint has configuration - let mut mdconf = get_configuration_metadata(); + let mut mdconf = Conf::get_metadata(); let name = name.to_ascii_lowercase(); mdconf.retain(|cconf| cconf.lints.contains(&&*name)); if !mdconf.is_empty() { @@ -456,6 +456,9 @@ pub fn register_lint_passes(store: &mut rustc_lint::LintStore, conf: &'static Co // Due to the architecture of the compiler, currently `cfg_attr` attributes on crate // level (i.e `#![cfg_attr(...)]`) will still be expanded even when using a pre-expansion pass. store.register_pre_expansion_lint_pass(Box::new(move || Box::new(attrs::EarlyAttributes::new(conf)))); + store.register_pre_expansion_lint_pass(Box::new(move || { + Box::new(nonstandard_macro_braces::MacroBraces::new(conf)) + })); let format_args_storage = FormatArgsStorage::default(); let attr_storage = AttrStorage::default(); @@ -537,6 +540,7 @@ rustc_lint::early_lint_methods!( CfgNotTest: cfg_not_test::CfgNotTest = cfg_not_test::CfgNotTest, EmptyLineAfter: empty_line_after::EmptyLineAfter = empty_line_after::EmptyLineAfter::new(), InlineTraitBounds: inline_trait_bounds::InlineTraitBounds = inline_trait_bounds::InlineTraitBounds::default(), + DefinitionInModuleRoot: definition_in_module_root::DefinitionInModuleRoot = definition_in_module_root::DefinitionInModuleRoot::default(), // add early passes here, used by `cargo dev new_lint` ]] ); @@ -566,6 +570,7 @@ rustc_lint::late_lint_methods!( UnnecessaryMutPassed: unnecessary_mut_passed::UnnecessaryMutPassed = unnecessary_mut_passed::UnnecessaryMutPassed, SignificantDropTightening: significant_drop_tightening::SignificantDropTightening<'tcx> = >::default(), LenZero: len_zero::LenZero = len_zero::LenZero::new(conf), + AssertIsEmpty: assert_is_empty::AssertIsEmpty = assert_is_empty::AssertIsEmpty, LenWithoutIsEmpty: len_without_is_empty::LenWithoutIsEmpty = len_without_is_empty::LenWithoutIsEmpty, Attributes: attrs::Attributes = attrs::Attributes::new(conf), BlocksInConditions: blocks_in_conditions::BlocksInConditions = blocks_in_conditions::BlocksInConditions, @@ -832,7 +837,7 @@ rustc_lint::late_lint_methods!( UnusedTraitNames: unused_trait_names::UnusedTraitNames = unused_trait_names::UnusedTraitNames::new(conf), ManualIgnoreCaseCmp: manual_ignore_case_cmp::ManualIgnoreCaseCmp = manual_ignore_case_cmp::ManualIgnoreCaseCmp, UnnecessaryLiteralBound: unnecessary_literal_bound::UnnecessaryLiteralBound = unnecessary_literal_bound::UnnecessaryLiteralBound, - ArbitrarySourceItemOrdering: arbitrary_source_item_ordering::ArbitrarySourceItemOrdering = arbitrary_source_item_ordering::ArbitrarySourceItemOrdering::new(conf), + ArbitrarySourceItemOrdering: arbitrary_source_item_ordering::ArbitrarySourceItemOrdering = arbitrary_source_item_ordering::ArbitrarySourceItemOrdering::new(tcx, conf), UselessConcat: useless_concat::UselessConcat = useless_concat::UselessConcat, UnneededStructPattern: unneeded_struct_pattern::UnneededStructPattern = unneeded_struct_pattern::UnneededStructPattern, UnnecessarySemicolon: unnecessary_semicolon::UnnecessarySemicolon = ::default(), @@ -840,7 +845,7 @@ rustc_lint::late_lint_methods!( ManualOptionAsSlice: manual_option_as_slice::ManualOptionAsSlice = manual_option_as_slice::ManualOptionAsSlice::new(conf), SingleOptionMap: single_option_map::SingleOptionMap = single_option_map::SingleOptionMap, RedundantTestPrefix: redundant_test_prefix::RedundantTestPrefix = redundant_test_prefix::RedundantTestPrefix, - ClonedRefToSliceRefs: cloned_ref_to_slice_refs::ClonedRefToSliceRefs<'tcx> = cloned_ref_to_slice_refs::ClonedRefToSliceRefs::new(conf), + ClonedRefToSliceRefs: cloned_ref_to_slice_refs::ClonedRefToSliceRefs = cloned_ref_to_slice_refs::ClonedRefToSliceRefs::new(conf), InfallibleTryFrom: infallible_try_from::InfallibleTryFrom = infallible_try_from::InfallibleTryFrom, CoerceContainerToAny: coerce_container_to_any::CoerceContainerToAny = coerce_container_to_any::CoerceContainerToAny, ToplevelRefArg: toplevel_ref_arg::ToplevelRefArg = toplevel_ref_arg::ToplevelRefArg, @@ -859,6 +864,9 @@ rustc_lint::late_lint_methods!( WithCapacityZero: with_capacity_zero::WithCapacityZero = with_capacity_zero::WithCapacityZero, RefPatterns: ref_patterns::RefPatterns = ref_patterns::RefPatterns, RedundantElse: redundant_else::RedundantElse = redundant_else::RedundantElse, + RestWhenDestructuringStruct: rest_when_destructuring_struct::RestWhenDestructuringStruct = rest_when_destructuring_struct::RestWhenDestructuringStruct, + BlockScrutinee: block_scrutinee::BlockScrutinee = block_scrutinee::BlockScrutinee, + NonnullUncheckedOnBoxPtr: nonnull_unchecked_on_box_ptr::NonnullUncheckedOnBoxPtr = nonnull_unchecked_on_box_ptr::NonnullUncheckedOnBoxPtr::new(conf), // add late passes here, used by `cargo dev new_lint` ]] ); diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index e55111136ec3e..8f2f8aaf7859f 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -2,15 +2,15 @@ use clippy_config::Conf; use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::{is_from_proc_macro, trait_ref_of_method}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_ast::visit::{try_visit, walk_list}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::Applicability; use rustc_hir::FnRetTy::Return; -use rustc_hir::intravisit::{IgnoreNested, NestedFilter}; use rustc_hir::intravisit::{ - Visitor, VisitorExt, walk_fn_decl, walk_generic_args, walk_generic_param, walk_generics, walk_impl_item_ref, - walk_param_bound, walk_poly_trait_ref, walk_trait_ref, walk_ty, walk_unambig_ty, walk_where_predicate, + IgnoreNested, NestedFilter, Visitor, VisitorExt as _, walk_fn_decl, walk_generic_args, walk_generic_param, + walk_generics, walk_impl_item_ref, walk_param_bound, walk_poly_trait_ref, walk_trait_ref, walk_ty, walk_unambig_ty, + walk_where_predicate, }; use rustc_hir::{ AmbigArg, BodyId, FnDecl, FnPtrTy, FnSig, GenericArg, GenericArgs, GenericBound, GenericParam, GenericParamKind, @@ -18,7 +18,7 @@ use rustc_hir::{ PolyTraitRef, PredicateOrigin, TraitFn, TraitItem, TraitItemKind, TraitRef, Ty, TyKind, WhereBoundPredicate, WherePredicate, WherePredicateKind, lang_items, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::hir::nested_filter as middle_nested_filter; use rustc_middle::ty::TyCtxt; use rustc_session::impl_lint_pass; @@ -136,7 +136,7 @@ pub struct Lifetimes { impl Lifetimes { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/literal_representation.rs b/src/tools/clippy/clippy_lints/src/literal_representation.rs index 4e7ff879ae590..f6e0fa784baa6 100644 --- a/src/tools/clippy/clippy_lints/src/literal_representation.rs +++ b/src/tools/clippy/clippy_lints/src/literal_representation.rs @@ -1,11 +1,11 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::numeric_literal::{NumericLiteral, Radix}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_ast::ast::{Expr, ExprKind, LitKind}; use rustc_ast::token; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; use std::iter; diff --git a/src/tools/clippy/clippy_lints/src/loops/char_indices_as_byte_indices.rs b/src/tools/clippy/clippy_lints/src/loops/char_indices_as_byte_indices.rs index f4d71d0524b22..9231f341b72aa 100644 --- a/src/tools/clippy/clippy_lints/src/loops/char_indices_as_byte_indices.rs +++ b/src/tools/clippy/clippy_lints/src/loops/char_indices_as_byte_indices.rs @@ -1,7 +1,7 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::visitors::for_each_expr; use clippy_utils::{eq_expr_value, higher, sym}; use rustc_errors::{Applicability, MultiSpan}; diff --git a/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs index daca78e344748..036d666d458bd 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_into_iter_loop.rs @@ -1,6 +1,6 @@ use super::EXPLICIT_INTO_ITER_LOOP; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_context; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs index a189bd7b717e9..37a0c4e13c0e2 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs @@ -1,7 +1,7 @@ use super::EXPLICIT_ITER_LOOP; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::sym; use clippy_utils::ty::{ diff --git a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs index d28029790732b..046aafbca195e 100644 --- a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs +++ b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs @@ -1,6 +1,6 @@ use super::FOR_KV_MAP; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::{snippet_with_applicability, walk_span_to_context}; use clippy_utils::{pat_is_wild, sugg}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/loops/infinite_loop.rs b/src/tools/clippy/clippy_lints/src/loops/infinite_loop.rs index dbd9deff1c2b6..404ff33838b15 100644 --- a/src/tools/clippy/clippy_lints/src/loops/infinite_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/infinite_loop.rs @@ -7,7 +7,7 @@ use rustc_hir::{ self as hir, Closure, ClosureKind, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind, FnRetTy, FnSig, Node, TyKind, }; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_span::sym; use super::INFINITE_LOOP; diff --git a/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs b/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs index 8a4644cdf5efd..8b85f9dde6c92 100644 --- a/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/iter_next_loop.rs @@ -1,6 +1,6 @@ use super::ITER_NEXT_LOOP; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/loops/manual_find.rs b/src/tools/clippy/clippy_lints/src/loops/manual_find.rs index d94dcfab23c73..d875af7691101 100644 --- a/src/tools/clippy/clippy_lints/src/loops/manual_find.rs +++ b/src/tools/clippy/clippy_lints/src/loops/manual_find.rs @@ -1,13 +1,12 @@ use super::MANUAL_FIND; use super::utils::make_iterator_snippet; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::implements_trait; use clippy_utils::usage::contains_return_break_continue_macro; -use clippy_utils::{as_some_expr, higher, peel_blocks_with_stmt}; +use clippy_utils::{as_some_expr, higher, is_none_expr, peel_blocks_with_stmt}; use rustc_errors::Applicability; -use rustc_hir::lang_items::LangItem; use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, Node, Pat, PatKind, Stmt, StmtKind}; use rustc_lint::LateContext; use rustc_span::Span; @@ -149,7 +148,7 @@ fn last_stmt_and_ret<'tcx>( && let Some((_, Node::Block(block))) = parent_iter.next() && let Some((last_stmt, last_ret)) = extract(block) && last_stmt.hir_id == node_hir - && last_ret.res(cx).ctor_parent(cx).is_lang_item(cx, LangItem::OptionNone) + && is_none_expr(cx, last_ret) && let Some((_, Node::Expr(_block))) = parent_iter.next() // This includes the function header && let Some((_, func)) = parent_iter.next() diff --git a/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs b/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs index 2c89afc739745..d0fdd2131307a 100644 --- a/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs +++ b/src/tools/clippy/clippy_lints/src/loops/manual_flatten.rs @@ -2,7 +2,7 @@ use super::MANUAL_FLATTEN; use super::utils::make_iterator_snippet; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::{indent_of, reindent_multiline, snippet_with_applicability}; use clippy_utils::visitors::is_local_used; use clippy_utils::{higher, is_refutable, peel_blocks_with_stmt, span_contains_comment}; diff --git a/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs b/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs index eb1987806416f..ec0c4fb23390b 100644 --- a/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs +++ b/src/tools/clippy/clippy_lints/src/loops/manual_memcpy.rs @@ -1,6 +1,6 @@ use super::{IncrementVisitor, InitializeVisitor, MANUAL_MEMCPY}; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet; use clippy_utils::sugg::Sugg; use clippy_utils::ty::is_copy; diff --git a/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs b/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs index ca8383070d70f..0052418ad088c 100644 --- a/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs @@ -1,6 +1,6 @@ use super::MISSING_SPIN_LOOP; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::std_or_core; use rustc_errors::Applicability; use rustc_hir::{Block, Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/loops/mod.rs b/src/tools/clippy/clippy_lints/src/loops/mod.rs index 017d795cd992b..64970ee87d031 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mod.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mod.rs @@ -27,7 +27,7 @@ mod while_let_on_iterator; use clippy_config::Conf; use clippy_utils::msrvs::Msrv; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::{higher, sym}; use rustc_ast::Label; use rustc_hir::{Expr, ExprKind, LoopSource, Pat}; @@ -850,7 +850,7 @@ pub struct Loops { impl Loops { pub fn new(conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), enforce_iter_loop_reborrow: conf.enforce_iter_loop_reborrow, } } diff --git a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs index 6ab7bb628eca5..10af083c195e2 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs @@ -1,6 +1,6 @@ use super::MUT_RANGE_BOUND; use clippy_utils::diagnostics::span_lint_and_note; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::{get_enclosing_block, higher}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{BindingMode, Expr, ExprKind, HirId, Node, PatKind}; diff --git a/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs b/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs index ba309d94608c4..5e133cb79ce96 100644 --- a/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs +++ b/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs @@ -1,7 +1,7 @@ use super::SAME_ITEM_PUSH; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::Msrv; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::ty::implements_trait; use clippy_utils::{msrvs, std_or_core, sym}; diff --git a/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs index edbf6e63e659f..917fe32610b5e 100644 --- a/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/single_element_loop.rs @@ -1,5 +1,5 @@ use super::SINGLE_ELEMENT_LOOP; -use clippy_utils::diagnostics::span_lint_and_sugg; +use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg}; use clippy_utils::source::{indent_of, snippet, snippet_with_applicability}; use clippy_utils::visitors::contains_break_or_continue; use rustc_ast::Mutability; @@ -17,82 +17,112 @@ pub(super) fn check<'tcx>( body: &'tcx Expr<'_>, expr: &'tcx Expr<'_>, ) { - let (arg_expression, prefix) = match arg.kind { + let Some((arg_expression, prefix)) = extract_single_element(cx, arg) else { + return; + }; + + if let ExprKind::Block(block, _) = body.kind + && (!block.stmts.is_empty() || block.expr.is_some()) + && !contains_break_or_continue(body) + { + emit_lint(cx, pat, arg, expr, arg_expression, prefix, block); + } +} + +fn extract_single_element<'tcx>( + cx: &LateContext<'tcx>, + arg: &'tcx Expr<'_>, +) -> Option<(&'tcx Expr<'tcx>, &'static str)> { + match arg.kind { ExprKind::AddrOf( BorrowKind::Ref, Mutability::Not, Expr { - kind: ExprKind::Array([arg]), + kind: ExprKind::Array([inner]), .. }, - ) => (arg, "&"), + ) => Some((inner, "&")), ExprKind::AddrOf( BorrowKind::Ref, Mutability::Mut, Expr { - kind: ExprKind::Array([arg]), + kind: ExprKind::Array([inner]), .. }, - ) => (arg, "&mut "), + ) => Some((inner, "&mut ")), ExprKind::MethodCall( method, Expr { - kind: ExprKind::Array([arg]), + kind: ExprKind::Array([inner]), .. }, [], _, - ) if method.ident.name == sym::iter => (arg, "&"), + ) if method.ident.name == sym::iter => Some((inner, "&")), ExprKind::MethodCall( method, Expr { - kind: ExprKind::Array([arg]), + kind: ExprKind::Array([inner]), .. }, [], _, - ) if method.ident.name == sym::iter_mut => (arg, "&mut "), + ) if method.ident.name == sym::iter_mut => Some((inner, "&mut ")), ExprKind::MethodCall( method, Expr { - kind: ExprKind::Array([arg]), + kind: ExprKind::Array([inner]), .. }, [], _, - ) if method.ident.name == sym::into_iter => (arg, ""), + ) if method.ident.name == sym::into_iter => Some((inner, "")), // Only check for arrays edition 2021 or later, as this case will trigger a compiler error otherwise. - ExprKind::Array([arg]) if cx.tcx.sess.edition() >= Edition::Edition2021 => (arg, ""), - _ => return, + ExprKind::Array([inner]) if cx.tcx.sess.edition() >= Edition::Edition2021 => Some((inner, "")), + _ => None, + } +} + +fn emit_lint<'tcx>( + cx: &LateContext<'tcx>, + pat: &'tcx Pat<'_>, + arg: &'tcx Expr<'_>, + expr: &'tcx Expr<'_>, + arg_expression: &'tcx Expr<'_>, + prefix: &str, + block: &rustc_hir::Block<'_>, +) { + let mut applicability = Applicability::MachineApplicable; + let mut pat_snip = snippet_with_applicability(cx, pat.span, "..", &mut applicability); + if matches!(pat.kind, PatKind::Or(..)) { + pat_snip = format!("({pat_snip})").into(); + } + let mut arg_snip = snippet_with_applicability(cx, arg_expression.span, "..", &mut applicability); + let mut block_str = snippet_with_applicability(cx, block.span, "..", &mut applicability).into_owned(); + block_str.remove(0); + block_str.pop(); + let indent = if let Some(first_stmt) = block.stmts.first() { + " ".repeat(indent_of(cx, first_stmt.span).unwrap_or(0)) + } else if let Some(block_expr) = block.expr { + " ".repeat(indent_of(cx, block_expr.span).unwrap_or(0)) + } else { + String::new() }; - if let ExprKind::Block(block, _) = body.kind - && !block.stmts.is_empty() - && !contains_break_or_continue(body) - { - let mut applicability = Applicability::MachineApplicable; - let mut pat_snip = snippet_with_applicability(cx, pat.span, "..", &mut applicability); - if matches!(pat.kind, PatKind::Or(..)) { - pat_snip = format!("({pat_snip})").into(); - } - let mut arg_snip = snippet_with_applicability(cx, arg_expression.span, "..", &mut applicability); - let mut block_str = snippet_with_applicability(cx, block.span, "..", &mut applicability).into_owned(); - block_str.remove(0); - block_str.pop(); - let indent = " ".repeat(indent_of(cx, block.stmts[0].span).unwrap_or(0)); - // Reference iterator from `&(mut) []` or `[].iter(_mut)()`. - if !prefix.is_empty() - && ( - // Precedence of internal expression is less than or equal to precedence of `&expr`. - cx.precedence(arg_expression) <= ExprPrecedence::Prefix || is_range_literal(arg_expression) - ) - { - arg_snip = format!("({arg_snip})").into(); - } + // Reference iterator from `&(mut) []` or `[].iter(_mut)()`. + if !prefix.is_empty() + && ( + // Precedence of internal expression is less than or equal to precedence of `&expr`. + cx.precedence(arg_expression) <= ExprPrecedence::Prefix || is_range_literal(arg_expression) + ) + { + arg_snip = format!("({arg_snip})").into(); + } - if clippy_utils::higher::Range::hir(cx, arg_expression).is_some() { + if let Some(range) = clippy_utils::higher::Range::hir(cx, arg_expression) { + if range.start.is_some() { + // Only suggest iterating over ranges that have a start value. let range_expr = snippet(cx, arg_expression.span, "?").to_string(); - let sugg = snippet(cx, arg_expression.span, ".."); span_lint_and_sugg( cx, @@ -104,15 +134,17 @@ pub(super) fn check<'tcx>( Applicability::Unspecified, ); } else { - span_lint_and_sugg( - cx, - SINGLE_ELEMENT_LOOP, - expr.span, - "for loop over a single element", - "try", - format!("{{\n{indent}let {pat_snip} = {prefix}{arg_snip};{block_str}}}"), - applicability, - ); + span_lint(cx, SINGLE_ELEMENT_LOOP, expr.span, "for loop over a single element"); } + } else { + span_lint_and_sugg( + cx, + SINGLE_ELEMENT_LOOP, + expr.span, + "for loop over a single element", + "try", + format!("{{\n{indent}let {pat_snip} = {prefix}{arg_snip};{block_str}}}"), + applicability, + ); } } diff --git a/src/tools/clippy/clippy_lints/src/loops/unused_enumerate_index.rs b/src/tools/clippy/clippy_lints/src/loops/unused_enumerate_index.rs index b80efdae9294c..3d46991d1c224 100644 --- a/src/tools/clippy/clippy_lints/src/loops/unused_enumerate_index.rs +++ b/src/tools/clippy/clippy_lints/src/loops/unused_enumerate_index.rs @@ -1,7 +1,7 @@ use super::UNUSED_ENUMERATE_INDEX; use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::{SpanExt, walk_span_to_context}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::{SpanExt as _, walk_span_to_context}; use clippy_utils::{expr_or_init, pat_is_wild, sym}; use rustc_errors::Applicability; use rustc_hir::{Closure, Expr, ExprKind, Pat, PatKind, TyKind}; diff --git a/src/tools/clippy/clippy_lints/src/loops/utils.rs b/src/tools/clippy/clippy_lints/src/loops/utils.rs index 81e868b3b7ba7..25a2ba93d9064 100644 --- a/src/tools/clippy/clippy_lints/src/loops/utils.rs +++ b/src/tools/clippy/clippy_lints/src/loops/utils.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::ty::{has_iter_method, implements_trait}; use clippy_utils::{get_parent_expr, is_integer_literal, sugg}; use rustc_ast::ast::{LitIntType, LitKind}; diff --git a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs index fc0789894cc2c..68b4865de4752 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs @@ -2,7 +2,7 @@ use std::ops::ControlFlow; use super::WHILE_LET_ON_ITERATOR; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::visitors::is_res_used; use clippy_utils::{as_some_pattern, get_enclosing_loop_or_multi_call_closure, higher, is_refutable}; diff --git a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs index 8ff6de283557f..2a68c582effc2 100644 --- a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs +++ b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs @@ -1,11 +1,11 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::is_lint_allowed; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{Visitor, walk_block, walk_expr, walk_stmt}; use rustc_hir::{BlockCheckMode, Expr, ExprKind, HirId, Stmt, UnsafeSource, find_attr}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::{Span, SyntaxContext}; use std::collections::BTreeMap; diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 6eda0fa257a98..e746ea9cbfc7b 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -4,7 +4,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{self as hir, AmbigArg, find_attr}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; use rustc_span::edition::Edition; diff --git a/src/tools/clippy/clippy_lints/src/manual_abs_diff.rs b/src/tools/clippy/clippy_lints/src/manual_abs_diff.rs index b3c2e93a077fc..d55a0d8fa86e6 100644 --- a/src/tools/clippy/clippy_lints/src/manual_abs_diff.rs +++ b/src/tools/clippy/clippy_lints/src/manual_abs_diff.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher::If; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sugg::Sugg; use clippy_utils::ty::peel_and_count_ty_refs; use clippy_utils::{eq_expr_value, peel_blocks, span_contains_comment, sym}; @@ -49,7 +49,7 @@ pub struct ManualAbsDiff { impl ManualAbsDiff { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_assert.rs b/src/tools/clippy/clippy_lints/src/manual_assert.rs index c77133130ba4d..2a0711d8ebbce 100644 --- a/src/tools/clippy/clippy_lints/src/manual_assert.rs +++ b/src/tools/clippy/clippy_lints/src/manual_assert.rs @@ -4,7 +4,7 @@ use clippy_utils::source::{indent_of, reindent_multiline}; use clippy_utils::{higher, is_else_clause, is_parent_stmt, peel_blocks_with_stmt, span_extract_comment, sugg}; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/manual_assert_eq.rs b/src/tools/clippy/clippy_lints/src/manual_assert_eq.rs index d1770d2e95a66..2f90a7fac474f 100644 --- a/src/tools/clippy/clippy_lints/src/manual_assert_eq.rs +++ b/src/tools/clippy/clippy_lints/src/manual_assert_eq.rs @@ -6,7 +6,7 @@ use clippy_utils::ty::implements_trait; use clippy_utils::{is_in_const_context, sym}; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs index 161834914b309..de07cea28bf56 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::{SpanExt, position_before_rarrow, snippet_block}; +use clippy_utils::source::{SpanExt as _, position_before_rarrow, snippet_block}; use rustc_errors::Applicability; use rustc_hir::intravisit::FnKind; use rustc_hir::{ diff --git a/src/tools/clippy/clippy_lints/src/manual_bits.rs b/src/tools/clippy/clippy_lints/src/manual_bits.rs index dd64381033d41..da0d9be1cb7fa 100644 --- a/src/tools/clippy/clippy_lints/src/manual_bits.rs +++ b/src/tools/clippy/clippy_lints/src/manual_bits.rs @@ -42,7 +42,7 @@ pub struct ManualBits { impl ManualBits { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_clamp.rs b/src/tools/clippy/clippy_lints/src/manual_clamp.rs index c81fa2e2b3b27..5f0414e4a269b 100644 --- a/src/tools/clippy/clippy_lints/src/manual_clamp.rs +++ b/src/tools/clippy/clippy_lints/src/manual_clamp.rs @@ -3,12 +3,12 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then}; use clippy_utils::higher::If; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::implements_trait; use clippy_utils::visitors::is_const_evaluatable; -use clippy_utils::{eq_expr_value, is_in_const_context, peel_blocks, peel_blocks_with_stmt, sym}; -use itertools::Itertools; +use clippy_utils::{eq_expr_value, is_in_const_context, is_integer_literal, peel_blocks, peel_blocks_with_stmt, sym}; +use itertools::Itertools as _; use rustc_errors::{Applicability, Diag}; use rustc_hir::def::Res; use rustc_hir::{Arm, BinOpKind, Block, Expr, ExprKind, HirId, PatKind, PathSegment, PrimTy, QPath, StmtKind}; @@ -97,7 +97,7 @@ pub struct ManualClamp { impl ManualClamp { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } @@ -718,6 +718,9 @@ fn is_clamp_meta_pattern<'tcx>( if exprs.iter().any(|e| peel_blocks(e).can_have_side_effects()) { return None; } + let first_bin = try_normalize_unsigned_eq_to_ord(cx, first_bin, first_expr).unwrap_or(*first_bin); + let second_bin = try_normalize_unsigned_eq_to_ord(cx, second_bin, second_expr).unwrap_or(*second_bin); + let (first_bin, second_bin) = (&first_bin, &second_bin); if !(is_ord_op(first_bin.op) && is_ord_op(second_bin.op)) { return None; } @@ -771,6 +774,47 @@ fn is_ord_op(op: BinOpKind) -> bool { matches!(op, BinOpKind::Ge | BinOpKind::Gt | BinOpKind::Le | BinOpKind::Lt) } +/// For unsigned integer types, `x == 0` is equivalent to `x < 1`. This normalizes such `==` +/// comparisons to `<` when the result expression evaluates to 1, enabling clamp detection for +/// patterns like: +/// +/// ```ignore +/// if x == 0 { x = 1; } else if x > y { x = y; } +/// ``` +fn try_normalize_unsigned_eq_to_ord<'tcx>( + cx: &LateContext<'tcx>, + bin: &BinaryOp<'tcx>, + result_expr: &'tcx Expr<'tcx>, +) -> Option> { + if bin.op != BinOpKind::Eq { + return None; + } + + // both sides of the expression have the same type, so checking either of them is sufficient + if !matches!(cx.typeck_results().expr_ty(bin.left).kind(), rustc_middle::ty::Uint(_)) { + return None; + } + + // Handles both `x == 0` and the Yoda notation `0 == x`. + let input = if is_integer_literal(bin.right, 0) { + bin.left + } else if is_integer_literal(bin.left, 0) { + bin.right + } else { + return None; + }; + + if is_integer_literal(result_expr, 1) { + Some(BinaryOp { + op: BinOpKind::Lt, + left: input, + right: result_expr, + }) + } else { + None + } +} + /// Really similar to Cow, but doesn't have a `Clone` requirement. #[derive(Debug)] enum MaybeBorrowedStmtKind<'a> { diff --git a/src/tools/clippy/clippy_lints/src/manual_float_methods.rs b/src/tools/clippy/clippy_lints/src/manual_float_methods.rs index de8edc03191fe..a7e79293738c7 100644 --- a/src/tools/clippy/clippy_lints/src/manual_float_methods.rs +++ b/src/tools/clippy/clippy_lints/src/manual_float_methods.rs @@ -3,13 +3,13 @@ use clippy_utils::consts::ConstEvalCtxt; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::SpanExt as _; use rustc_errors::Applicability; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_hir::{BinOpKind, Constness, Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, Lint, LintContext}; +use rustc_lint::{LateContext, LateLintPass, Lint, LintContext as _}; use rustc_middle::ty::TyCtxt; use rustc_session::impl_lint_pass; @@ -93,7 +93,7 @@ pub struct ManualFloatMethods { impl ManualFloatMethods { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_hash_one.rs b/src/tools/clippy/clippy_lints/src/manual_hash_one.rs index 33370194d4e7c..c8d220fa81fbc 100644 --- a/src/tools/clippy/clippy_lints/src/manual_hash_one.rs +++ b/src/tools/clippy/clippy_lints/src/manual_hash_one.rs @@ -1,8 +1,8 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; -use clippy_utils::source::SpanExt; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; +use clippy_utils::source::SpanExt as _; use clippy_utils::sym; use clippy_utils::visitors::{is_local_used, local_used_once}; use rustc_errors::Applicability; @@ -55,7 +55,7 @@ pub struct ManualHashOne { impl ManualHashOne { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_ignore_case_cmp.rs b/src/tools/clippy/clippy_lints/src/manual_ignore_case_cmp.rs index 1c20a8f81efbd..b214ace2e584f 100644 --- a/src/tools/clippy/clippy_lints/src/manual_ignore_case_cmp.rs +++ b/src/tools/clippy/clippy_lints/src/manual_ignore_case_cmp.rs @@ -1,6 +1,6 @@ use crate::manual_ignore_case_cmp::MatchType::{Literal, ToAscii}; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::sym; use rustc_ast::LitKind; diff --git a/src/tools/clippy/clippy_lints/src/manual_ilog2.rs b/src/tools/clippy/clippy_lints/src/manual_ilog2.rs index 2c368f15d6705..6aba536705290 100644 --- a/src/tools/clippy/clippy_lints/src/manual_ilog2.rs +++ b/src/tools/clippy/clippy_lints/src/manual_ilog2.rs @@ -7,7 +7,7 @@ use rustc_ast::LitKind; use rustc_data_structures::packed::Pu128; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty; use rustc_session::impl_lint_pass; @@ -45,16 +45,12 @@ pub struct ManualIlog2 { impl ManualIlog2 { pub fn new(conf: &Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } impl LateLintPass<'_> for ManualIlog2 { fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { - if expr.span.in_external_macro(cx.sess().source_map()) { - return; - } - match expr.kind { // `BIT_WIDTH - 1 - n.leading_zeros()` ExprKind::Binary(op, left, right) @@ -77,6 +73,7 @@ impl LateLintPass<'_> for ManualIlog2 { } && val == u128::from(bit_width) - 1 && self.msrv.meets(cx, msrvs::ILOG2) + && !expr.span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, expr) => { emit(cx, recv, expr); @@ -90,6 +87,7 @@ impl LateLintPass<'_> for ManualIlog2 { && let LitKind::Int(Pu128(2), _) = lit.node && cx.typeck_results().expr_ty_adjusted(recv).is_integral() /* no need to check MSRV here, as `ilog` and `ilog2` were introduced simultaneously */ + && !expr.span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, expr) => { emit(cx, recv, expr); diff --git a/src/tools/clippy/clippy_lints/src/manual_is_ascii_check.rs b/src/tools/clippy/clippy_lints/src/manual_is_ascii_check.rs index 996b00466de7d..8f8492c2676e6 100644 --- a/src/tools/clippy/clippy_lints/src/manual_is_ascii_check.rs +++ b/src/tools/clippy/clippy_lints/src/manual_is_ascii_check.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::matching_root_macro_call; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::sugg::Sugg; use clippy_utils::{higher, is_in_const_context, peel_ref_operators, sym}; use rustc_ast::LitKind::{Byte, Char}; @@ -66,7 +66,7 @@ pub struct ManualIsAsciiCheck { impl ManualIsAsciiCheck { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_is_power_of_two.rs b/src/tools/clippy/clippy_lints/src/manual_is_power_of_two.rs index 26e0a6e2a51f8..96942eb29b62f 100644 --- a/src/tools/clippy/clippy_lints/src/manual_is_power_of_two.rs +++ b/src/tools/clippy/clippy_lints/src/manual_is_power_of_two.rs @@ -43,7 +43,7 @@ pub struct ManualIsPowerOfTwo { impl ManualIsPowerOfTwo { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } fn build_sugg(&self, cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>) { diff --git a/src/tools/clippy/clippy_lints/src/manual_let_else.rs b/src/tools/clippy/clippy_lints/src/manual_let_else.rs index 8b92c3b8cbeb5..7bccc30b9e95c 100644 --- a/src/tools/clippy/clippy_lints/src/manual_let_else.rs +++ b/src/tools/clippy/clippy_lints/src/manual_let_else.rs @@ -2,7 +2,7 @@ use crate::question_mark::{QUESTION_MARK, QuestionMark}; use clippy_config::types::MatchLintBehaviour; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher::IfLetOrMatch; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::{is_lint_allowed, is_never_expr, is_wild, msrvs, pat_and_expr_can_be_question_mark, peel_blocks}; use rustc_ast::BindingMode; @@ -12,7 +12,7 @@ use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::{ Arm, BlockCheckMode, Expr, ExprKind, MatchSource, Pat, PatExpr, PatExprKind, PatKind, QPath, Stmt, StmtKind, }; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_span::Span; use rustc_span::symbol::{Symbol, sym}; use std::slice; diff --git a/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs b/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs index 47e98d68bc830..1db07ba04201c 100644 --- a/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs +++ b/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::{peel_hir_expr_refs, sym}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; @@ -41,7 +41,7 @@ pub struct ManualMainSeparatorStr { impl ManualMainSeparatorStr { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs b/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs index 84b30a40e1bde..b916a1f127d90 100644 --- a/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs +++ b/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then}; use clippy_utils::is_doc_hidden; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::snippet_indent; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; @@ -72,7 +72,7 @@ pub struct ManualNonExhaustive { impl ManualNonExhaustive { pub fn new(conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), constructed_enum_variants: FxHashSet::default(), potential_enums: Vec::new(), } diff --git a/src/tools/clippy/clippy_lints/src/manual_noop_waker.rs b/src/tools/clippy/clippy_lints/src/manual_noop_waker.rs index fb0e8a1d363f4..f6d119488cb69 100644 --- a/src/tools/clippy/clippy_lints/src/manual_noop_waker.rs +++ b/src/tools/clippy/clippy_lints/src/manual_noop_waker.rs @@ -45,7 +45,7 @@ pub struct ManualNoopWaker { impl ManualNoopWaker { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_option_as_slice.rs b/src/tools/clippy/clippy_lints/src/manual_option_as_slice.rs index a851f1ea48db4..d88bb232ac617 100644 --- a/src/tools/clippy/clippy_lints/src/manual_option_as_slice.rs +++ b/src/tools/clippy/clippy_lints/src/manual_option_as_slice.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::Msrv; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::{as_some_pattern, is_none_pattern, msrvs, peel_hir_expr_refs, sym}; use rustc_errors::Applicability; @@ -48,7 +48,7 @@ pub struct ManualOptionAsSlice { impl ManualOptionAsSlice { pub fn new(conf: &Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_pop_if.rs b/src/tools/clippy/clippy_lints/src/manual_pop_if.rs index f29403d1a9060..359bb594e4a12 100644 --- a/src/tools/clippy/clippy_lints/src/manual_pop_if.rs +++ b/src/tools/clippy/clippy_lints/src/manual_pop_if.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::visitors::{for_each_expr_without_closures, is_local_used}; use clippy_utils::{eq_expr_value, is_else_clause, is_lang_item_or_ctor, span_contains_non_whitespace, sym}; @@ -67,7 +67,7 @@ pub struct ManualPopIf { impl ManualPopIf { pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), binary_heap_pop_if_feature_enabled: tcx.features().enabled(sym::binary_heap_pop_if), } } diff --git a/src/tools/clippy/clippy_lints/src/manual_range_patterns.rs b/src/tools/clippy/clippy_lints/src/manual_range_patterns.rs index 94a3f2b1f15f9..00b5a194a4aac 100644 --- a/src/tools/clippy/clippy_lints/src/manual_range_patterns.rs +++ b/src/tools/clippy/clippy_lints/src/manual_range_patterns.rs @@ -1,10 +1,10 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_ast::LitKind; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{PatExpr, PatExprKind, PatKind, RangeEnd}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::{DUMMY_SP, Span}; diff --git a/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs b/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs index 3ee92dca5303c..eea2553615a6f 100644 --- a/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs +++ b/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs @@ -3,11 +3,11 @@ use clippy_utils::consts::{ConstEvalCtxt, FullInt}; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_in_const_context; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_context; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, Node, TyKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::SyntaxContext; @@ -43,7 +43,7 @@ pub struct ManualRemEuclid { impl ManualRemEuclid { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_retain.rs b/src/tools/clippy/clippy_lints/src/manual_retain.rs index bc2e67de99d85..780dfa30846e1 100644 --- a/src/tools/clippy/clippy_lints/src/manual_retain.rs +++ b/src/tools/clippy/clippy_lints/src/manual_retain.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet; use clippy_utils::{SpanlessEq, sym}; use rustc_errors::Applicability; @@ -52,7 +52,7 @@ pub struct ManualRetain { impl ManualRetain { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs b/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs index f99a4bd186906..f7aadff342bb7 100644 --- a/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs +++ b/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs @@ -47,7 +47,7 @@ pub struct ManualSliceSizeCalculation { impl ManualSliceSizeCalculation { pub fn new(conf: &Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_strip.rs b/src/tools/clippy/clippy_lints/src/manual_strip.rs index eaa6539653af3..953ff9f4b3967 100644 --- a/src/tools/clippy/clippy_lints/src/manual_strip.rs +++ b/src/tools/clippy/clippy_lints/src/manual_strip.rs @@ -57,7 +57,7 @@ pub struct ManualStrip { impl ManualStrip { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/manual_take.rs b/src/tools/clippy/clippy_lints/src/manual_take.rs index dec2a641231a0..b1eef9dd23c50 100644 --- a/src/tools/clippy/clippy_lints/src/manual_take.rs +++ b/src/tools/clippy/clippy_lints/src/manual_take.rs @@ -6,7 +6,7 @@ use clippy_utils::source::snippet_with_context; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{Block, Expr, ExprKind, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; declare_clippy_lint! { @@ -48,7 +48,7 @@ pub struct ManualTake { impl ManualTake { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs index 5089bd9e14e4a..86a175aa2a645 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::{snippet, snippet_with_applicability, snippet_with_context}; use clippy_utils::{iter_input_pats, method_chain_args}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/match_result_ok.rs b/src/tools/clippy/clippy_lints/src/match_result_ok.rs index 1ebbd209ae52d..ad4bc210463d9 100644 --- a/src/tools/clippy/clippy_lints/src/match_result_ok.rs +++ b/src/tools/clippy/clippy_lints/src/match_result_ok.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::{as_some_pattern, higher, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/matches/collapsible_match.rs b/src/tools/clippy/clippy_lints/src/matches/collapsible_match.rs index 2eb15928f25aa..6510af5db8541 100644 --- a/src/tools/clippy/clippy_lints/src/matches/collapsible_match.rs +++ b/src/tools/clippy/clippy_lints/src/matches/collapsible_match.rs @@ -1,15 +1,16 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::higher::{If, IfLetOrMatch}; use clippy_utils::msrvs::Msrv; -use clippy_utils::res::{MaybeDef, MaybeResPath}; -use clippy_utils::source::{IntoSpan, SpanExt, snippet}; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::{IntoSpan as _, SpanExt as _, snippet}; use clippy_utils::usage::mutated_variables; use clippy_utils::visitors::is_local_used; -use clippy_utils::{SpanlessEq, get_ref_operators, is_unit_expr, peel_blocks_with_stmt, peel_ref_operators}; +use clippy_utils::{ + SpanlessEq, get_ref_operators, is_none_pattern, is_unit_expr, peel_blocks_with_stmt, peel_ref_operators, +}; use rustc_ast::BorrowKind; use rustc_errors::{Applicability, MultiSpan}; -use rustc_hir::LangItem::OptionNone; -use rustc_hir::{Arm, Expr, ExprKind, HirId, HirIdSet, Pat, PatExpr, PatExprKind, PatKind}; +use rustc_hir::{Arm, Expr, ExprKind, HirId, HirIdSet, Pat, PatKind}; use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use rustc_lint::LateContext; use rustc_middle::mir::FakeReadCause; @@ -216,18 +217,7 @@ fn arm_is_wild_like(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool { if arm.guard.is_some() { return false; } - match arm.pat.kind { - PatKind::Binding(..) | PatKind::Wild => true, - PatKind::Expr(PatExpr { - kind: PatExprKind::Path(qpath), - hir_id, - .. - }) => cx - .qpath_res(qpath, *hir_id) - .ctor_parent(cx) - .is_lang_item(cx, OptionNone), - _ => false, - } + matches!(arm.pat.kind, PatKind::Binding(..) | PatKind::Wild) || is_none_pattern(cx, arm.pat) } fn find_pat_binding_and_is_innermost_parent_pat_struct(pat: &Pat<'_>, hir_id: HirId) -> (Option<(Ident, Span)>, bool) { diff --git a/src/tools/clippy/clippy_lints/src/matches/infallible_destructuring_match.rs b/src/tools/clippy/clippy_lints/src/matches/infallible_destructuring_match.rs index 84befc17b1206..520f4784c444c 100644 --- a/src/tools/clippy/clippy_lints/src/matches/infallible_destructuring_match.rs +++ b/src/tools/clippy/clippy_lints/src/matches/infallible_destructuring_match.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{peel_blocks, strip_pat_refs}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/matches/manual_filter.rs b/src/tools/clippy/clippy_lints/src/matches/manual_filter.rs index 9c2d60eb9c575..94a2910cef3b9 100644 --- a/src/tools/clippy/clippy_lints/src/matches/manual_filter.rs +++ b/src/tools/clippy/clippy_lints/src/matches/manual_filter.rs @@ -1,12 +1,11 @@ -use clippy_utils::as_some_expr; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::sugg::Sugg; use clippy_utils::ty::is_copy; use clippy_utils::visitors::contains_unsafe_block; +use clippy_utils::{as_some_expr, span_contains_comment}; use rustc_errors::Applicability; -use rustc_hir::LangItem::OptionNone; use rustc_hir::{Arm, Expr, ExprKind, HirId, Pat, PatKind}; use rustc_lint::LateContext; use rustc_span::{Span, SyntaxContext, sym}; @@ -74,10 +73,7 @@ fn is_some_expr(cx: &LateContext<'_>, target: HirId, ctxt: SyntaxContext, expr: } fn is_none_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - if let Some(inner_expr) = peels_blocks_incl_unsafe_opt(expr) { - return inner_expr.res(cx).ctor_parent(cx).is_lang_item(cx, OptionNone); - } - false + peels_blocks_incl_unsafe_opt(expr).is_some_and(|inner_expr| clippy_utils::is_none_expr(cx, inner_expr)) } // given the closure: `|| ` @@ -118,7 +114,13 @@ pub(crate) fn check_and_then_method<'tcx>( call_span, "manual implementation of `Option::filter`", |diag| { - let mut applicability = Applicability::MachineApplicable; + // A comment inside the replaced `and_then` closure (for example, one explaining the + // predicate) would be dropped by the rewrite, so don't auto-apply the fix then (#17376). + let mut applicability = if span_contains_comment(cx, call_span) { + Applicability::MaybeIncorrect + } else { + Applicability::MachineApplicable + }; let mut cond_snip = Sugg::hir_with_context(cx, some_expr.expr, expr_span_ctxt, "..", &mut applicability); diff --git a/src/tools/clippy/clippy_lints/src/matches/manual_map.rs b/src/tools/clippy/clippy_lints/src/matches/manual_map.rs index f111da60bbd5b..5e8d69a5b4e8b 100644 --- a/src/tools/clippy/clippy_lints/src/matches/manual_map.rs +++ b/src/tools/clippy/clippy_lints/src/matches/manual_map.rs @@ -2,7 +2,7 @@ use super::MANUAL_MAP; use super::manual_utils::{SomeExpr, check_with}; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use rustc_hir::LangItem::OptionSome; use rustc_hir::{Arm, Block, BlockCheckMode, Expr, ExprKind, Pat, UnsafeSource}; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/matches/manual_ok_err.rs b/src/tools/clippy/clippy_lints/src/matches/manual_ok_err.rs index abbf60019c5c0..c599099d3ce42 100644 --- a/src/tools/clippy/clippy_lints/src/matches/manual_ok_err.rs +++ b/src/tools/clippy/clippy_lints/src/matches/manual_ok_err.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::{indent_of, reindent_multiline}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::{option_arg_ty, peel_and_count_ty_refs}; diff --git a/src/tools/clippy/clippy_lints/src/matches/manual_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/matches/manual_unwrap_or.rs index e317056e29809..a5c61fafb514c 100644 --- a/src/tools/clippy/clippy_lints/src/matches/manual_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/matches/manual_unwrap_or.rs @@ -1,10 +1,10 @@ use clippy_utils::consts::ConstEvalCtxt; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _}; use clippy_utils::source::{SpanExt as _, indent_of, reindent_multiline}; use rustc_ast::{BindingMode, ByRef}; use rustc_errors::Applicability; use rustc_hir::def::Res; -use rustc_hir::{Arm, Expr, ExprKind, HirId, LangItem, Pat, PatExpr, PatExprKind, PatKind, QPath}; +use rustc_hir::{Arm, Expr, ExprKind, HirId, LangItem, Pat, PatKind, QPath}; use rustc_lint::LateContext; use rustc_middle::ty::{GenericArgKind, Ty}; use rustc_span::sym; @@ -13,7 +13,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::sugg::Sugg; use clippy_utils::ty::{expr_type_is_certain, implements_trait, is_copy}; use clippy_utils::usage::local_used_after_expr; -use clippy_utils::{is_default_equivalent, is_lint_allowed, peel_blocks, span_contains_comment}; +use clippy_utils::{is_default_equivalent, is_lint_allowed, is_none_pattern, peel_blocks, span_contains_comment}; use super::{MANUAL_UNWRAP_OR, MANUAL_UNWRAP_OR_DEFAULT}; @@ -34,20 +34,15 @@ fn get_some(cx: &LateContext<'_>, pat: &Pat<'_>) -> Option { } fn get_none<'tcx>(cx: &LateContext<'_>, arm: &Arm<'tcx>, allow_wildcard: bool) -> Option<&'tcx Expr<'tcx>> { - if let PatKind::Expr(PatExpr { kind: PatExprKind::Path(QPath::Resolved(_, path)), .. }) = arm.pat.kind - && let Some(def_id) = path.res.opt_def_id() - // Since it comes from a pattern binding, we need to get the parent to actually match - // against it. - && let Some(def_id) = cx.tcx.opt_parent(def_id) - && cx.tcx.lang_items().get(LangItem::OptionNone) == Some(def_id) - { + if is_none_pattern(cx, arm.pat) { Some(arm.body) - } else if let PatKind::TupleStruct(QPath::Resolved(_, path), _, _)= arm.pat.kind - && let Some(def_id) = path.res.opt_def_id() - // Since it comes from a pattern binding, we need to get the parent to actually match - // against it. - && let Some(def_id) = cx.tcx.opt_parent(def_id) - && cx.tcx.lang_items().get(LangItem::ResultErr) == Some(def_id) + } else if let PatKind::TupleStruct(QPath::Resolved(_, path), _, _) = arm.pat.kind + && (path.res) + .opt_def_id() + // Since it comes from a pattern binding, we need to get the parent to actually match + // against it. + .opt_parent(cx) + .is_lang_item(cx, LangItem::ResultErr) { Some(arm.body) } else if let PatKind::Wild = arm.pat.kind diff --git a/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs b/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs index 26fd936767aa7..aa91369a1f0cd 100644 --- a/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs +++ b/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs @@ -1,6 +1,6 @@ use crate::map_unit_fn::OPTION_MAP_UNIT_FN; use crate::matches::MATCH_AS_REF; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::{is_copy, is_unsafe_fn, peel_and_count_ty_refs}; diff --git a/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs b/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs index f500f21246bdb..df93f142fddaa 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_same_arms.rs @@ -1,17 +1,17 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::{SpanlessEq, fulfill_or_allowed, hash_expr, is_lint_allowed, search_same}; use core::cmp::Ordering; use core::{iter, slice}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_arena::DroplessArena; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{Arm, Expr, HirId, HirIdMap, HirIdMapEntry, HirIdSet, Pat, PatExpr, PatExprKind, PatKind, RangeEnd}; use rustc_lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::{self, TypeckResults}; use rustc_span::{ByteSymbol, ErrorGuaranteed, Span, Symbol, SyntaxContext}; diff --git a/src/tools/clippy/clippy_lints/src/matches/match_single_binding.rs b/src/tools/clippy/clippy_lints/src/matches/match_single_binding.rs index 3c0fad01835f6..2a15d732939c3 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_single_binding.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_single_binding.rs @@ -1,7 +1,7 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::macros::HirNode; +use clippy_utils::macros::HirNode as _; use clippy_utils::source::{indent_of, reindent_multiline, snippet, snippet_block_with_context, snippet_with_context}; use clippy_utils::{is_expr_identity_of_pat, is_refutable, peel_blocks}; use rustc_data_structures::fx::FxHashSet; diff --git a/src/tools/clippy/clippy_lints/src/matches/match_str_case_mismatch.rs b/src/tools/clippy/clippy_lints/src/matches/match_str_case_mismatch.rs index 3f8f2dc0e132d..874feb9b4b189 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_str_case_mismatch.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_str_case_mismatch.rs @@ -1,7 +1,7 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs b/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs index 69288e693e4b4..7abcf7690e0b4 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::{is_refutable, peel_hir_pat_refs, recurse_or_patterns}; use rustc_errors::Applicability; use rustc_hir::def::{CtorKind, DefKind, Res}; diff --git a/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs b/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs index 9fc9f9944465c..11ef63ac6c9b2 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs @@ -1,12 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_note; use clippy_utils::macros::{is_panic, root_macro_call}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::visitors::is_local_used; use clippy_utils::{is_in_const_context, is_wild, peel_blocks_with_stmt}; -use rustc_hir::{Arm, Expr, PatKind}; +use rustc_hir::{Arm, Expr, PatKind, intravisit}; use rustc_lint::LateContext; use rustc_span::symbol::{kw, sym}; -use rustc_hir::intravisit; use super::MATCH_WILD_ERR_ARM; @@ -20,7 +19,11 @@ pub(crate) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<' if ex_ty.is_diag_item(cx, sym::Result) { for arm in arms { if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind { - let path_str = rustc_hir_pretty::qpath_to_string(#[allow(trivial_casts)] &(&cx.tcx as &dyn intravisit::HirTyCtxt<'_>), path); + let path_str = rustc_hir_pretty::qpath_to_string( + #[allow(trivial_casts)] + &(&cx.tcx as &dyn intravisit::HirTyCtxt<'_>), + path, + ); if path_str == "Err" { let mut matching_wild = inner.iter().any(is_wild); let mut ident_bind_name = kw::Underscore; diff --git a/src/tools/clippy/clippy_lints/src/matches/mod.rs b/src/tools/clippy/clippy_lints/src/matches/mod.rs index 7b9d10cccfef0..0d2eb1653fc8b 100644 --- a/src/tools/clippy/clippy_lints/src/matches/mod.rs +++ b/src/tools/clippy/clippy_lints/src/matches/mod.rs @@ -26,13 +26,13 @@ mod wild_in_or_pats; use clippy_config::Conf; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::{ higher, is_direct_expn_of, is_in_const_context, is_lint_allowed, is_span_match, sym, tokenize_with_text, }; use rustc_hir::{Arm, Expr, ExprKind, LetStmt, MatchSource, Pat, PatKind}; use rustc_lexer::{TokenKind, is_whitespace}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; use rustc_span::Span; @@ -1045,7 +1045,7 @@ pub struct Matches { impl Matches { pub fn new(conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), infallible_destructuring_match_linted: false, } } @@ -1054,9 +1054,6 @@ impl Matches { impl<'tcx> LateLintPass<'tcx> for Matches { #[expect(clippy::too_many_lines)] fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if is_direct_expn_of(expr.span, sym::matches).is_none() && expr.span.in_external_macro(cx.sess().source_map()) { - return; - } let from_expansion = expr.span.from_expansion(); if let ExprKind::Match(ex, arms, source) = expr.kind { @@ -1066,6 +1063,9 @@ impl<'tcx> LateLintPass<'tcx> for Matches { redundant_pattern_match::check_match(cx, expr, ex, arms); redundant_pattern_match::check_matches_true(cx, expr, arm, ex); } + if expr.span.in_external_macro(cx.tcx.sess.source_map()) { + return; + } if source == MatchSource::Normal && !is_span_match(cx, expr.span) { return; @@ -1147,6 +1147,9 @@ impl<'tcx> LateLintPass<'tcx> for Matches { match_ref_pats::check(cx, ex, arms.iter().map(|el| el.pat), expr); } } else if let Some(if_let) = higher::IfLet::hir(cx, expr) { + if expr.span.in_external_macro(cx.tcx.sess.source_map()) { + return; + } collapsible_match::check_if_let( cx, if_let.let_span.ctxt(), @@ -1208,6 +1211,9 @@ impl<'tcx> LateLintPass<'tcx> for Matches { needless_match::check_if_let(cx, expr, &if_let); } } else { + if expr.span.in_external_macro(cx.tcx.sess.source_map()) { + return; + } if let Some(while_let) = higher::WhileLet::hir(expr) { significant_drop_in_scrutinee::check_while_let(cx, expr, while_let.let_expr, while_let.if_then); } diff --git a/src/tools/clippy/clippy_lints/src/matches/needless_match.rs b/src/tools/clippy/clippy_lints/src/matches/needless_match.rs index 0151aa8ef15ef..2f104e8d17d45 100644 --- a/src/tools/clippy/clippy_lints/src/matches/needless_match.rs +++ b/src/tools/clippy/clippy_lints/src/matches/needless_match.rs @@ -1,13 +1,13 @@ use super::NEEDLESS_MATCH; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::same_type_modulo_regions; use clippy_utils::{ - SpanlessEq, eq_expr_value, get_parent_expr_for_hir, higher, is_else_clause, over, peel_blocks_with_stmt, + SpanlessEq, eq_expr_value, get_parent_expr_for_hir, higher, is_else_clause, is_none_expr, over, + peel_blocks_with_stmt, }; use rustc_errors::Applicability; -use rustc_hir::LangItem::OptionNone; use rustc_hir::{ Arm, BindingMode, ByRef, Expr, ExprKind, ItemKind, Node, Pat, PatExpr, PatExprKind, PatKind, Path, QPath, }; @@ -108,8 +108,7 @@ fn check_if_let_inner(cx: &LateContext<'_>, ctxt: SyntaxContext, if_let: &higher } let let_expr_ty = cx.typeck_results().expr_ty(if_let.let_expr); if let_expr_ty.is_diag_item(cx, sym::Option) { - return else_expr.res(cx).ctor_parent(cx).is_lang_item(cx, OptionNone) - || eq_expr_value(cx, ctxt, if_let.let_expr, else_expr); + return is_none_expr(cx, else_expr) || eq_expr_value(cx, ctxt, if_let.let_expr, else_expr); } return eq_expr_value(cx, ctxt, if_let.let_expr, else_expr); } diff --git a/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs b/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs index fa8b6a65a2038..427921f38c79f 100644 --- a/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs +++ b/src/tools/clippy/clippy_lints/src/matches/redundant_guards.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::matching_root_macro_call; use clippy_utils::msrvs::Msrv; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet; use clippy_utils::visitors::{for_each_expr_without_closures, is_local_used}; use clippy_utils::{is_in_const_context, sym}; diff --git a/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs b/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs index b10c6c0ac5934..2a236cfa15979 100644 --- a/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs +++ b/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs @@ -1,19 +1,19 @@ use super::REDUNDANT_PATTERN_MATCHING; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::sugg::{Sugg, make_unop}; use clippy_utils::ty::needs_ordered_drop; use clippy_utils::visitors::{any_temporaries_need_ordered_drop, for_each_expr_without_closures}; -use clippy_utils::{higher, is_expn_of, sym}; +use clippy_utils::{get_parent_expr, higher, is_expn_of, sym}; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::LangItem::{self, OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk}; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::{Arm, Expr, ExprKind, Node, Pat, PatExpr, PatExprKind, PatKind, QPath, UnOp}; +use rustc_hir::{Arm, BinOpKind, Expr, ExprKind, Node, Pat, PatExpr, PatExprKind, PatKind, QPath, UnOp}; use rustc_lint::LateContext; use rustc_middle::ty::{self, GenericArgKind, Ty}; use rustc_span::{Span, Symbol, kw}; -use std::fmt::Write; +use std::fmt::Write as _; use std::ops::ControlFlow; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { @@ -312,6 +312,9 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op if let Some(guard) = maybe_guard { let guard = Sugg::hir_with_context(cx, guard, ctxt, "..", &mut app); let _ = write!(sugg, " && {}", guard.maybe_paren()); + if guard_sugg_needs_parens(cx, expr) { + sugg = format!("({sugg})"); + } } diag.span_suggestion_verbose(expr_span, format!("consider using `{good_method}`"), sugg, app); @@ -320,6 +323,20 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op } } +/// Whether the appended `&& guard` makes the suggestion bind looser than `expr`'s +/// parent, so the whole `recv.method() && guard` must be wrapped in parentheses. +fn guard_sugg_needs_parens(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { + let Some(parent) = get_parent_expr(cx, expr) else { + return false; + }; + match parent.kind { + ExprKind::Binary(op, ..) => !matches!(op.node, BinOpKind::And | BinOpKind::Or), + ExprKind::Unary(..) | ExprKind::AddrOf(..) | ExprKind::Cast(..) => true, + ExprKind::MethodCall(_, receiver, ..) => receiver.hir_id == expr.hir_id, + _ => false, + } +} + fn found_good_method<'tcx>( cx: &LateContext<'_>, arms: &'tcx [Arm<'tcx>; 2], diff --git a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs index ae7702105462f..db1e4f2717bd9 100644 --- a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs +++ b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs @@ -5,14 +5,14 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::{first_line_of_span, indent_of, snippet}; use clippy_utils::ty::{for_each_top_level_late_bound_region, is_copy}; use clippy_utils::{get_builtin_attr, is_lint_allowed, sym}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_ast::Mutability; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Applicability, Diag}; use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_hir::{Arm, Expr, ExprKind, MatchSource}; use rustc_lint::LateContext; -use rustc_middle::ty::{GenericArgKind, RegionKind, Ty, TypeVisitableExt}; +use rustc_middle::ty::{GenericArgKind, RegionKind, Ty, TypeVisitableExt as _}; use rustc_span::Span; use super::SIGNIFICANT_DROP_IN_SCRUTINEE; diff --git a/src/tools/clippy/clippy_lints/src/matches/single_match.rs b/src/tools/clippy/clippy_lints/src/matches/single_match.rs index 7c740ababb060..4a1e2090224d2 100644 --- a/src/tools/clippy/clippy_lints/src/matches/single_match.rs +++ b/src/tools/clippy/clippy_lints/src/matches/single_match.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::{ - SpanExt, expr_block, snippet, snippet_block_with_context, snippet_with_applicability, snippet_with_context, + SpanExt as _, expr_block, snippet, snippet_block_with_context, snippet_with_applicability, snippet_with_context, }; use clippy_utils::ty::{implements_trait, peel_and_count_ty_refs}; use clippy_utils::{is_lint_allowed, is_unit_expr, peel_blocks, peel_hir_pat_refs, peel_n_hir_expr_refs, sym}; diff --git a/src/tools/clippy/clippy_lints/src/matches/try_err.rs b/src/tools/clippy/clippy_lints/src/matches/try_err.rs index 401b8468135bc..81dc46a2fa992 100644 --- a/src/tools/clippy/clippy_lints/src/matches/try_err.rs +++ b/src/tools/clippy/clippy_lints/src/matches/try_err.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::get_parent_expr; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::option_arg_ty; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/mem_replace.rs b/src/tools/clippy/clippy_lints/src/mem_replace.rs index 0d417c25ef0e1..d189d1d8c8685 100644 --- a/src/tools/clippy/clippy_lints/src/mem_replace.rs +++ b/src/tools/clippy/clippy_lints/src/mem_replace.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::is_non_aggregate_primitive_type; @@ -292,7 +292,7 @@ pub struct MemReplace { impl MemReplace { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/methods/by_ref_peekable_peek.rs b/src/tools/clippy/clippy_lints/src/methods/by_ref_peekable_peek.rs index 1faaf2c9c8e43..e727a77d1ae27 100644 --- a/src/tools/clippy/clippy_lints/src/methods/by_ref_peekable_peek.rs +++ b/src/tools/clippy/clippy_lints/src/methods/by_ref_peekable_peek.rs @@ -1,6 +1,6 @@ -use crate::clippy_utils::res::MaybeTypeckRes; +use crate::clippy_utils::res::MaybeTypeckRes as _; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath as _}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sugg::Sugg; use clippy_utils::sym; use clippy_utils::ty::implements_trait; diff --git a/src/tools/clippy/clippy_lints/src/methods/bytecount.rs b/src/tools/clippy/clippy_lints/src/methods/bytecount.rs index 2ad7facf64d88..2a81abac4896a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bytecount.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bytecount.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::visitors::is_local_used; use clippy_utils::{peel_blocks, peel_ref_operators, strip_pat_refs, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs b/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs index 5abdd82f1cde2..abf551590573b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs b/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs index 0a3ea3005e72b..c0db96fd8becf 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bytes_nth.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs b/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs index b6694ad5148ba..894af02176954 100644 --- a/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs +++ b/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::{SpanExt, indent_of, reindent_multiline}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::{SpanExt as _, indent_of, reindent_multiline}; use clippy_utils::sym; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs b/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs index 4b0fc7eba8e34..046b616e81324 100644 --- a/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs +++ b/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::method_chain_args; -use clippy_utils::res::MaybeQPath; +use clippy_utils::res::MaybeQPath as _; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/chunks_exact_to_as_chunks.rs b/src/tools/clippy/clippy_lints/src/methods/chunks_exact_to_as_chunks.rs index ec9fbd4432ab0..04da7257a29ec 100644 --- a/src/tools/clippy/clippy_lints/src/methods/chunks_exact_to_as_chunks.rs +++ b/src/tools/clippy/clippy_lints/src/methods/chunks_exact_to_as_chunks.rs @@ -1,7 +1,7 @@ use super::CHUNKS_EXACT_TO_AS_CHUNKS; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::visitors::is_const_param_evaluatable; use clippy_utils::{get_expr_use_site, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/clear_with_drain.rs b/src/tools/clippy/clippy_lints/src/methods/clear_with_drain.rs index 0b6ead0747a80..6ef89788fbf82 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clear_with_drain.rs +++ b/src/tools/clippy/clippy_lints/src/methods/clear_with_drain.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::{is_full_collection_range, sym}; use rustc_errors::Applicability; use rustc_hir::{Expr, LangItem}; diff --git a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs index 18087bd96debf..f63ea13fd1c6d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs +++ b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs @@ -1,4 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; +use clippy_utils::peel_hir_expr_refs; use clippy_utils::source::snippet_with_context; use clippy_utils::ty::is_copy; use rustc_errors::Applicability; @@ -10,6 +11,51 @@ use rustc_middle::ty::print::with_forced_trimmed_paths; use super::CLONE_ON_COPY; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ParentIsSuffixExpr { + Yes, + No, + Return, +} + +fn check_parent_is_suffix_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> ParentIsSuffixExpr { + match cx.tcx.parent_hir_node(expr.hir_id) { + Node::Expr(parent) => match parent.kind { + // &*x is a nop, &x.clone() is not + ExprKind::AddrOf(..) => ParentIsSuffixExpr::Return, + // (*x).func() is useless, x.clone().func() can work in case func borrows self + ExprKind::MethodCall(_, self_arg, ..) + if expr.hir_id == self_arg.hir_id + && cx.typeck_results().expr_ty(expr) != cx.typeck_results().expr_ty_adjusted(expr) => + { + ParentIsSuffixExpr::Return + }, + // ? is a Call, makes sure not to rec *x?, but rather (*x)? + ExprKind::Call(hir_callee, [_]) => { + if matches!( + hir_callee.kind, + ExprKind::Path(qpath) + if cx.tcx.qpath_is_lang_item(qpath, rustc_hir::LangItem::TryTraitBranch) + ) { + ParentIsSuffixExpr::Yes + } else { + ParentIsSuffixExpr::No + } + }, + ExprKind::MethodCall(_, self_arg, ..) if expr.hir_id == self_arg.hir_id => ParentIsSuffixExpr::Yes, + ExprKind::Match(_, _, MatchSource::TryDesugar(_) | MatchSource::AwaitDesugar) + | ExprKind::Field(..) + | ExprKind::Index(..) => ParentIsSuffixExpr::Yes, + _ => ParentIsSuffixExpr::No, + }, + // local binding capturing a reference + Node::LetStmt(l) if matches!(l.pat.kind, PatKind::Binding(BindingMode(ByRef::Yes(..), _), ..)) => { + ParentIsSuffixExpr::Return + }, + _ => ParentIsSuffixExpr::No, + } +} + /// Checks for the `CLONE_ON_COPY` lint. pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>) { if cx @@ -33,46 +79,81 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>) return; // don't report clone_on_copy } - if is_copy(cx, ty) { - let parent_is_suffix_expr = match cx.tcx.parent_hir_node(expr.hir_id) { - Node::Expr(parent) => match parent.kind { - // &*x is a nop, &x.clone() is not - ExprKind::AddrOf(..) => return, - // (*x).func() is useless, x.clone().func() can work in case func borrows self - ExprKind::MethodCall(_, self_arg, ..) - if expr.hir_id == self_arg.hir_id && ty != cx.typeck_results().expr_ty_adjusted(expr) => - { - return; - }, - // ? is a Call, makes sure not to rec *x?, but rather (*x)? - ExprKind::Call(hir_callee, [_]) => matches!( - hir_callee.kind, - ExprKind::Path(qpath) - if cx.tcx.qpath_is_lang_item(qpath, rustc_hir::LangItem::TryTraitBranch) - ), - ExprKind::MethodCall(_, self_arg, ..) if expr.hir_id == self_arg.hir_id => true, - ExprKind::Match(_, _, MatchSource::TryDesugar(_) | MatchSource::AwaitDesugar) - | ExprKind::Field(..) - | ExprKind::Index(..) => true, - _ => false, - }, - // local binding capturing a reference - Node::LetStmt(l) if matches!(l.pat.kind, PatKind::Binding(BindingMode(ByRef::Yes(..), _), ..)) => { - return; - }, - _ => false, - }; + if !is_copy(cx, ty) { + return; + } + let check_res = check_parent_is_suffix_expr(cx, expr); + if check_res == ParentIsSuffixExpr::Return { + return; + } + + let mut app = Applicability::MachineApplicable; + let snip = snippet_with_context(cx, receiver.span, expr.span.ctxt(), "_", &mut app).0; + + let deref_count = arg_adjustments + .iter() + .take_while(|adj| matches!(adj.kind, Adjust::Deref(_))) + .count(); + let (help, sugg) = if deref_count == 0 { + ("try removing the `clone` call", snip.into()) + } else if check_res == ParentIsSuffixExpr::Yes { + ("try dereferencing it", format!("({}{snip})", "*".repeat(deref_count))) + } else { + ("try dereferencing it", format!("{}{snip}", "*".repeat(deref_count))) + }; + + span_lint_and_sugg( + cx, + CLONE_ON_COPY, + expr.span, + with_forced_trimmed_paths!(format!( + "using `clone` on type `{ty}` which implements the `Copy` trait" + )), + help, + sugg, + app, + ); +} + +pub(super) fn check_function(cx: &LateContext<'_>, expr: &Expr<'_>) { + let ExprKind::Call(func, args) = expr.kind else { return }; + + if let ExprKind::Path(qpath) = func.kind + && let Some(def_id) = cx.typeck_results().qpath_res(&qpath, func.hir_id).opt_def_id() + && cx.tcx.trait_of_assoc(def_id) == cx.tcx.lang_items().clone_trait() + && let [arg] = args + && let ty = cx.typeck_results().expr_ty(expr) + { + if !is_copy(cx, ty) { + return; + } + + let check_res = check_parent_is_suffix_expr(cx, expr); + if check_res == ParentIsSuffixExpr::Return { + return; + } + + // Peel the & operator in the argument. + let (peeled_arg, ref_count) = peel_hir_expr_refs(arg); let mut app = Applicability::MachineApplicable; - let snip = snippet_with_context(cx, receiver.span, expr.span.ctxt(), "_", &mut app).0; + let snip = snippet_with_context(cx, peeled_arg.span, func.span.ctxt(), "_", &mut app).0; + let arg_adjustments = cx.typeck_results().expr_adjustments(arg); let deref_count = arg_adjustments .iter() .take_while(|adj| matches!(adj.kind, Adjust::Deref(_))) - .count(); + .count() + - ref_count; + let (help, sugg) = if deref_count == 0 { - ("try removing the `clone` call", snip.into()) - } else if parent_is_suffix_expr { + if check_res == ParentIsSuffixExpr::Yes && snip.starts_with('*') { + ("try dereferencing it", format!("({snip})")) + } else { + ("try removing the `clone` call", snip.into()) + } + } else if check_res == ParentIsSuffixExpr::Yes { + // deref_count comes from the original argument `&x`, so we need to decrement `deref_count`. ("try dereferencing it", format!("({}{snip})", "*".repeat(deref_count))) } else { ("try dereferencing it", format!("{}{snip}", "*".repeat(deref_count))) diff --git a/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs b/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs index de32b0476d205..de3d4a0781a74 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/methods/clone_on_ref_ptr.rs @@ -4,7 +4,7 @@ use clippy_utils::ty::peel_and_count_ty_refs; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; -use rustc_middle::ty::{self, IsSuggestable}; +use rustc_middle::ty::{self, IsSuggestable as _}; use rustc_span::symbol::sym; use super::CLONE_ON_REF_PTR; diff --git a/src/tools/clippy/clippy_lints/src/methods/cloned_instead_of_copied.rs b/src/tools/clippy/clippy_lints/src/methods/cloned_instead_of_copied.rs index d80d6f7810f53..aecc3bf748ea5 100644 --- a/src/tools/clippy/clippy_lints/src/methods/cloned_instead_of_copied.rs +++ b/src/tools/clippy/clippy_lints/src/methods/cloned_instead_of_copied.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::ty::{get_iterator_item_ty, is_copy}; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/double_ended_iterator_last.rs b/src/tools/clippy/clippy_lints/src/methods/double_ended_iterator_last.rs index 8ba8264b713c4..e30082681756a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/double_ended_iterator_last.rs +++ b/src/tools/clippy/clippy_lints/src/methods/double_ended_iterator_last.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::ty::{has_non_owning_mutable_access, implements_trait}; use clippy_utils::{is_mutable, path_to_local_with_projections, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/drain_collect.rs b/src/tools/clippy/clippy_lints/src/methods/drain_collect.rs index 2b4b200904b2e..12e14bf25134d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/drain_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/drain_collect.rs @@ -1,6 +1,6 @@ use crate::methods::DRAIN_COLLECT; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet; use clippy_utils::{is_full_collection_range, std_or_core, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs index 97a03f9868b1d..609cab45d42d1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::{FormatArgsStorage, format_args_inputs_span, root_macro_call_first_node}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::visitors::for_each_expr; use clippy_utils::{contains_return, is_inside_always_const_context, peel_blocks, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/extend_with_drain.rs b/src/tools/clippy/clippy_lints/src/methods/extend_with_drain.rs index 829c1226a859e..af8128104f859 100644 --- a/src/tools/clippy/clippy_lints/src/methods/extend_with_drain.rs +++ b/src/tools/clippy/clippy_lints/src/methods/extend_with_drain.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs b/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs index 15f3adf3405e5..bd25f0a0011b6 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filetype_is_file.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::{get_parent_expr, sym}; use rustc_hir as hir; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map.rs index 9ddc3d1bf1d8e..f42b73fce6bdc 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::macros::{is_panic, matching_root_macro_call, root_macro_call}; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::source::{indent_of, reindent_multiline, snippet}; use clippy_utils::{SpanlessEq, higher, peel_blocks, sym}; use hir::{Body, HirId, MatchSource, Pat}; diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map_bool_then.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map_bool_then.rs index 419a7e0ed877d..00c7ca82d10dd 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map_bool_then.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map_bool_then.rs @@ -1,21 +1,20 @@ use super::FILTER_MAP_BOOL_THEN; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; -use clippy_utils::source::{SpanExt, snippet_with_context}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; +use clippy_utils::source::{SpanExt as _, snippet_with_context}; use clippy_utils::ty::is_copy; use clippy_utils::{CaptureKind, can_move_expr_to_closure, contains_return, is_from_proc_macro, peel_blocks, sym}; use rustc_ast::Mutability; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, HirId, Param, Pat}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::Binder; use rustc_middle::ty::adjustment::Adjust; use rustc_span::Span; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, arg: &Expr<'_>, call_span: Span) { - if !expr.span.in_external_macro(cx.sess().source_map()) - && cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::Iterator) + if cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::Iterator) && let ExprKind::Closure(closure) = arg.kind && let body = cx.tcx.hir_body(closure.body) && let value = peel_blocks(body.value) @@ -37,6 +36,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, arg: & && let then_body = peel_blocks(cx.tcx.hir_body(then_closure.body).value) && let Some(def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id) && cx.tcx.is_diagnostic_item(sym::bool_then, def_id) + && !expr.span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, expr) // Count the number of derefs needed to get to the bool because we need those in the suggestion && let needed_derefs = cx.typeck_results().expr_adjustments(recv) diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs index c6e30710eef90..8bc29315e647a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map_identity.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::{is_expr_identity_function, is_expr_untyped_identity_function}; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs index 9e55732830bc6..4eec1f30509b9 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map_next.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs b/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs index 043adb8434a0d..bc75b9d1c40e2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs +++ b/src/tools/clippy/clippy_lints/src/methods/flat_map_identity.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_expr_untyped_identity_function; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs b/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs index fb0e8f9d91b5a..3a185ac6f3a84 100644 --- a/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs +++ b/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/format_collect.rs b/src/tools/clippy/clippy_lints/src/methods/format_collect.rs index 7b2fe00d32188..b85e203e4d2e2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/format_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/format_collect.rs @@ -1,7 +1,7 @@ use super::FORMAT_COLLECT; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::{is_format_macro, root_macro_call_first_node}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_hir::{Expr, ExprKind, LangItem}; use rustc_lint::LateContext; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/methods/get_first.rs b/src/tools/clippy/clippy_lints/src/methods/get_first.rs index c3598eb59478a..f49aeabdf2193 100644 --- a/src/tools/clippy/clippy_lints/src/methods/get_first.rs +++ b/src/tools/clippy/clippy_lints/src/methods/get_first.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use rustc_ast::LitKind; diff --git a/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs b/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs index 768612d6bbdc1..fecd3c74fe7b2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs +++ b/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::sym; use clippy_utils::ty::{implements_trait, peel_and_count_ty_refs}; diff --git a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs index 374639985bee0..8e9781f668995 100644 --- a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use clippy_utils::ty::peel_and_count_ty_refs; diff --git a/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs b/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs index 194ddf45e6f11..7628665db116c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs +++ b/src/tools/clippy/clippy_lints/src/methods/inspect_for_each.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::{Span, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs b/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs index 5a062732721e5..297ec4f5427f9 100644 --- a/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::ty::has_iter_method; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/io_other_error.rs b/src/tools/clippy/clippy_lints/src/methods/io_other_error.rs index d9735f2941409..76830b359eee3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/io_other_error.rs +++ b/src/tools/clippy/clippy_lints/src/methods/io_other_error.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::{expr_or_init, sym}; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, QPath}; diff --git a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs index cfda39ed08ff1..3475a54f09858 100644 --- a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs +++ b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs @@ -1,17 +1,18 @@ use clippy_utils::consts::ConstEvalCtxt; use clippy_utils::diagnostics::span_lint; use clippy_utils::macros::{is_assert_macro, root_macro_call}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::{find_binding_init, get_parent_expr, is_inside_always_const_context}; use rustc_hir::{Expr, HirId, find_attr}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::LateContext; use super::CONST_IS_EMPTY; /// Expression whose initialization depend on a constant conditioned by a `#[cfg(…)]` directive will /// not trigger the lint. pub(super) fn check(cx: &LateContext<'_>, expr: &'_ Expr<'_>, receiver: &Expr<'_>) { - if expr.span.in_external_macro(cx.sess().source_map()) || !receiver.span.eq_ctxt(expr.span) { + let ctxt = expr.span.ctxt(); + if receiver.span.ctxt() != ctxt { return; } if let Some(parent) = get_parent_expr(cx, expr) @@ -23,10 +24,10 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &'_ Expr<'_>, receiver: &Expr<'_ return; } let init_expr = expr_or_init(cx, receiver); - if !receiver.span.eq_ctxt(init_expr.span) { - return; - } - if let Some(init_is_empty) = ConstEvalCtxt::new(cx).eval_is_empty(init_expr) { + if init_expr.span.ctxt() == ctxt + && let Some(init_is_empty) = ConstEvalCtxt::new(cx).eval_is_empty(init_expr) + && !ctxt.in_external_macro(cx.tcx.sess.source_map()) + { span_lint( cx, CONST_IS_EMPTY, diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs b/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs index 484d00e94f450..a0b4702f6688b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_cloned_collect.rs @@ -1,6 +1,6 @@ use crate::methods::utils::derefs_to_slice; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::get_iterator_item_ty; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_count.rs b/src/tools/clippy/clippy_lints/src/methods/iter_count.rs index 18278446bf610..b42ebab048f61 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_count.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_count.rs @@ -1,6 +1,6 @@ use super::utils::derefs_to_slice; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_filter.rs b/src/tools/clippy/clippy_lints/src/methods/iter_filter.rs index 3aa666145b86a..99d23a34cd95b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_filter.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_filter.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::ty::get_iterator_item_ty; use hir::ExprKind; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_kv_map.rs b/src/tools/clippy/clippy_lints/src/methods/iter_kv_map.rs index 283b9b5fc5b4c..f8a8277d82d71 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_kv_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_kv_map.rs @@ -1,7 +1,7 @@ use super::ITER_KV_MAP; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::{pat_is_wild, sym}; use rustc_hir::{Body, Expr, ExprKind, PatKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs b/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs index ff467cb63414d..6de87114fc991 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_next_slice.rs @@ -1,7 +1,7 @@ use super::ITER_NEXT_SLICE; use super::utils::derefs_to_slice; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{get_parent_expr, higher}; use rustc_ast::ast; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs b/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs index 6d1ee32e50269..0e11c248025a6 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_nth.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs b/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs index e0107b75e4142..3417d689c7ff2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_nth_zero.rs @@ -1,7 +1,7 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_lang_item_or_ctor; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_applicability; use hir::{LangItem, OwnerNode}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_out_of_bounds.rs b/src/tools/clippy/clippy_lints/src/methods/iter_out_of_bounds.rs index b0e805815bc9b..7ec9021af11d8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_out_of_bounds.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_out_of_bounds.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_note; use clippy_utils::higher::VecArgs; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::{expr_or_init, sym}; use rustc_ast::LitKind; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs b/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs index 661188c90ed61..918e68a092cba 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_skip_zero.rs b/src/tools/clippy/clippy_lints/src/methods/iter_skip_zero.rs index cae31e7c9606e..0f59367dc5f3e 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_skip_zero.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_skip_zero.rs @@ -1,7 +1,7 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_with_drain.rs b/src/tools/clippy/clippy_lints/src/methods/iter_with_drain.rs index 2ef09fa3f8d2c..782e703bc055f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_with_drain.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_with_drain.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::{is_full_collection_range, sym}; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs b/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs index 11dde2429adfa..289252a4bf0ad 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iterator_step_by_zero.rs @@ -1,6 +1,6 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/methods/join_absolute_paths.rs b/src/tools/clippy/clippy_lints/src/methods/join_absolute_paths.rs index fe3ca632d6e35..cc387fee1f318 100644 --- a/src/tools/clippy/clippy_lints/src/methods/join_absolute_paths.rs +++ b/src/tools/clippy/clippy_lints/src/methods/join_absolute_paths.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet; use clippy_utils::{expr_or_init, sym}; use rustc_ast::ast::{LitKind, StrStyle}; diff --git a/src/tools/clippy/clippy_lints/src/methods/lines_filter_map_ok.rs b/src/tools/clippy/clippy_lints/src/methods/lines_filter_map_ok.rs index baf5b6f93f637..607979719f894 100644 --- a/src/tools/clippy/clippy_lints/src/methods/lines_filter_map_ok.rs +++ b/src/tools/clippy/clippy_lints/src/methods/lines_filter_map_ok.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir::{Body, Closure, Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_clear.rs b/src/tools/clippy/clippy_lints/src/methods/manual_clear.rs index dbf1c85add55d..025788b83b5b9 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_clear.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_clear.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::{is_integer_literal, sym}; use rustc_errors::Applicability; use rustc_hir::{Expr, LangItem}; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_inspect.rs b/src/tools/clippy/clippy_lints/src/methods/manual_inspect.rs index 5ef8450da93bc..aff6477c32547 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_inspect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_inspect.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; -use clippy_utils::source::{IntoSpan, SpanExt}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; +use clippy_utils::source::{IntoSpan as _, SpanExt as _}; use clippy_utils::ty::get_field_by_name; use clippy_utils::visitors::{for_each_expr, for_each_expr_without_closures}; use clippy_utils::{ExprUseNode, get_expr_use_site, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_is_variant_and.rs b/src/tools/clippy/clippy_lints/src/methods/manual_is_variant_and.rs index 8a0da622982c6..bd2b1ba299185 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_is_variant_and.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_is_variant_and.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::sugg::Sugg; use clippy_utils::{SpanlessEq, get_parent_expr, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_next_back.rs b/src/tools/clippy/clippy_lints/src/methods/manual_next_back.rs index 221c7f08c923c..ddb67e3801aae 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_next_back.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_next_back.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::sym; use clippy_utils::ty::implements_trait; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs b/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs index 050b28b3babd7..b010f7a8996fa 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; -use clippy_utils::source::{SpanExt, indent_of, reindent_multiline}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _}; +use clippy_utils::source::{SpanExt as _, indent_of, reindent_multiline}; use rustc_errors::Applicability; use rustc_hir::LangItem::{ResultErr, ResultOk}; use rustc_hir::{Expr, ExprKind, PatKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_option_zip.rs b/src/tools/clippy/clippy_lints/src/methods/manual_option_zip.rs index 538f8a2fe93dc..e168beddf57b6 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_option_zip.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_option_zip.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::eager_or_lazy::switch_to_eager_eval; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::peel_blocks; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::usage::local_used_in; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_repeat_n.rs b/src/tools/clippy/clippy_lints/src/methods/manual_repeat_n.rs index 6f65fc48b38af..9520c7ad96cf4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_repeat_n.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_repeat_n.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::{snippet, snippet_with_context}; use clippy_utils::{fn_def_id, get_expr_use_site, std_or_core, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs b/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs index a3dd967bd77a9..742d7e1fbec72 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use rustc_ast::ast; @@ -8,7 +8,7 @@ use rustc_hir::def::Res; use rustc_hir::{self as hir, Expr}; use rustc_lint::LateContext; use rustc_middle::ty::Ty; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_span::Symbol; pub fn check_unwrap_or( diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs b/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs index 457549d1091c0..d04e224adf7af 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::sugg::Sugg; use clippy_utils::sym; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_try_fold.rs b/src/tools/clippy/clippy_lints/src/methods/manual_try_fold.rs index 6ef7abffb0b2f..69843d68c8bba 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_try_fold.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_try_fold.rs @@ -1,13 +1,13 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_from_proc_macro; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; -use clippy_utils::source::SpanExt; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; +use clippy_utils::source::SpanExt as _; use clippy_utils::ty::implements_trait; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{Expr, ExprKind}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_span::{Span, sym}; use super::MANUAL_TRY_FOLD; @@ -20,8 +20,7 @@ pub(super) fn check<'tcx>( fold_span: Span, msrv: Msrv, ) { - if !fold_span.in_external_macro(cx.sess().source_map()) - && cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::Iterator) + if cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::Iterator) && let init_ty = cx.typeck_results().expr_ty(init) && let Some(try_trait) = cx.tcx.lang_items().try_trait() && implements_trait(cx, init_ty, try_trait, &[]) @@ -30,6 +29,7 @@ pub(super) fn check<'tcx>( && let Res::Def(DefKind::Ctor(_, _), _) = cx.qpath_res(&qpath, path.hir_id) && let ExprKind::Closure(closure) = acc.kind && msrv.meets(cx, msrvs::ITERATOR_TRY_FOLD) + && !fold_span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, expr) && let Some(args_snip) = closure.fn_arg_span.and_then(|fn_arg_span| fn_arg_span.get_text(cx)) { diff --git a/src/tools/clippy/clippy_lints/src/methods/map_all_any_identity.rs b/src/tools/clippy/clippy_lints/src/methods/map_all_any_identity.rs index 14a9752d3bded..4ac9647f4141f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_all_any_identity.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_all_any_identity.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_expr_identity_function; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; -use clippy_utils::source::SpanExt; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; +use clippy_utils::source::SpanExt as _; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs index b88a0fe2a7775..f25cbb265c57f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::peel_blocks; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, should_call_clone_as_function}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs b/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs index 1112fbc2a1c74..6f556fe592af8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs b/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs index 96b8b9dc03227..9868d1a60d0a8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_hir::{CaptureBy, Closure, Expr, ExprKind, PatKind}; use rustc_lint::LateContext; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs b/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs index b654548cc2050..cb2880c8c7123 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::span_contains_comment; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/map_identity.rs b/src/tools/clippy/clippy_lints/src/methods/map_identity.rs index fa394526bdf1e..a4c084623e3b0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_identity.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_identity.rs @@ -1,11 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::is_copy; use clippy_utils::{is_expr_untyped_identity_function, is_mutable, path_to_local_with_projections}; use rustc_errors::Applicability; use rustc_hir::{self as hir, ExprKind, Node, PatKind}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_span::{Span, Symbol, sym}; use super::MAP_IDENTITY; diff --git a/src/tools/clippy/clippy_lints/src/methods/map_or_identity.rs b/src/tools/clippy/clippy_lints/src/methods/map_or_identity.rs index e4e5fa5420105..a43751b6f94cf 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_or_identity.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_or_identity.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_expr_identity_function; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs index ec6dccd4fe543..b58ceb263be22 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_unwrap_or.rs @@ -1,13 +1,14 @@ use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::is_none_expr; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::is_copy; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::intravisit::{Visitor, walk_expr, walk_path}; -use rustc_hir::{ExprKind, HirId, LangItem, Node, PatKind, Path, QPath}; +use rustc_hir::{ExprKind, HirId, Node, PatKind, Path, QPath}; use rustc_lint::LateContext; use rustc_middle::hir::nested_filter; use rustc_span::{Span, sym}; @@ -82,12 +83,7 @@ pub(super) fn check<'tcx>( let unwrap_snippet = snippet_with_applicability(cx, unwrap_arg.span, "..", &mut applicability); // lint message - let suggest_kind = if recv_ty_kind == sym::Option - && unwrap_arg - .basic_res() - .ctor_parent(cx) - .is_lang_item(cx, LangItem::OptionNone) - { + let suggest_kind = if recv_ty_kind == sym::Option && is_none_expr(cx, unwrap_arg) { SuggestedKind::AndThen } // is_some_and is stabilised && `unwrap_or` argument is false; suggest `is_some_and` instead diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index ddb2fba94bba9..3c26f07cd51df 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -158,11 +158,11 @@ use clippy_config::Conf; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::macros::FormatArgsStorage; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::{contains_return, iter_input_pats, peel_blocks, sym}; use rustc_data_structures::fx::FxHashSet; use rustc_hir::{self as hir, Expr, ExprKind, Node, Stmt, StmtKind, TraitItem, TraitItemKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::TraitRef; use rustc_session::impl_lint_pass; use rustc_span::{Span, Symbol}; @@ -5105,7 +5105,7 @@ impl Methods { Self { avoid_breaking_exported_api: conf.avoid_breaking_exported_api, - msrv: conf.msrv, + msrv: conf.msrv.into(), allow_expect_in_tests: conf.allow_expect_in_tests, allow_unwrap_in_tests: conf.allow_unwrap_in_tests, allow_expect_in_consts: conf.allow_expect_in_consts, @@ -5160,6 +5160,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { io_other_error::check(cx, expr, func, args, self.msrv); swap_with_temporary::check(cx, expr, func, args); ip_constant::check(cx, expr, func, args); + clone_on_copy::check_function(cx, expr); unwrap_expect_used::check_call( cx, expr, @@ -5230,11 +5231,9 @@ impl<'tcx> LateLintPass<'tcx> for Methods { } fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) { - if item.span.in_external_macro(cx.tcx.sess.source_map()) { - return; - } - - if let TraitItemKind::Fn(ref sig, _) = item.kind { + if let TraitItemKind::Fn(ref sig, _) = item.kind + && !item.span.in_external_macro(cx.tcx.sess.source_map()) + { if sig.decl.implicit_self().has_implicit_self() && let Some(first_arg_hir_ty) = sig.decl.inputs.first() && let Some(&first_arg_ty) = cx diff --git a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs index c9264e747b56d..4ef9169e4daf2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::expr_custom_deref_adjustment; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::peel_and_count_ty_refs; use rustc_errors::Applicability; use rustc_hir::{Expr, Mutability}; diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_as_bytes.rs b/src/tools/clippy/clippy_lints/src/methods/needless_as_bytes.rs index 22baad40b4496..6a20d401419ff 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_as_bytes.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_as_bytes.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sugg::Sugg; use rustc_errors::Applicability; use rustc_hir::{Expr, LangItem}; diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_character_iteration.rs b/src/tools/clippy/clippy_lints/src/methods/needless_character_iteration.rs index 20468784aae7a..aac4a344f5f99 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_character_iteration.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_character_iteration.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _}; use rustc_errors::Applicability; use rustc_hir::{Closure, Expr, ExprKind, HirId, StmtKind, UnOp}; use rustc_lint::LateContext; @@ -8,7 +8,7 @@ use rustc_span::Span; use super::NEEDLESS_CHARACTER_ITERATION; use super::utils::get_last_chain_binding_hir_id; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::{peel_blocks, sym}; fn peels_expr_ref<'a, 'tcx>(mut expr: &'a Expr<'tcx>) -> &'a Expr<'tcx> { diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs index e5acaf383fa0d..450df73542678 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs @@ -3,7 +3,7 @@ use std::ops::ControlFlow; use super::NEEDLESS_COLLECT; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then}; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::source::{snippet, snippet_with_applicability}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::{has_non_owning_mutable_access, make_normalized_projection, make_projection}; @@ -35,6 +35,10 @@ pub(super) fn check<'tcx>( return; // don't lint if the iterator has side effects } + if collect_turbofish_is_fully_concrete(collect_expr) { + return; // don't lint if turbofish on collect maybe the only thing anchoring the type + } + match cx.tcx.parent_hir_node(collect_expr.hir_id) { Node::Expr(parent) => { check_collect_into_intoiterator(cx, parent, collect_expr, call_span, iter_expr); @@ -230,6 +234,41 @@ fn check_collect_into_intoiterator<'tcx>( } } +/// Returns `true` if `collect_expr`'s turbofish is fully concrete (has +/// generic arguments and none of them are inference placeholders) +fn collect_turbofish_is_fully_concrete(collect_expr: &Expr<'_>) -> bool { + if let ExprKind::MethodCall(segment, ..) = collect_expr.kind + && let Some(args) = segment.args + && let [a] = args.args + { + generic_arg_is_fully_concrete(a) + } else { + false + } +} + +fn generic_arg_is_fully_concrete(arg: &rustc_hir::GenericArg<'_>) -> bool { + match arg { + rustc_hir::GenericArg::Infer(_) => false, + rustc_hir::GenericArg::Type(ty) => ty_is_fully_concrete(ty.as_unambig_ty()), + rustc_hir::GenericArg::Const(ct) => !matches!(ct.as_unambig_ct().kind, rustc_hir::ConstArgKind::Infer(..)), + rustc_hir::GenericArg::Lifetime(_) => true, + } +} + +fn ty_is_fully_concrete(ty: &rustc_hir::Ty<'_>) -> bool { + match &ty.kind { + rustc_hir::TyKind::Infer(..) => false, + rustc_hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)) => path.segments.iter().all(|seg| { + seg.args + .is_none_or(|a| a.args.iter().all(generic_arg_is_fully_concrete)) + }), + rustc_hir::TyKind::Ref(_, mut_ty) => ty_is_fully_concrete(mut_ty.ty), + rustc_hir::TyKind::Slice(ty) | rustc_hir::TyKind::Array(ty, _) => ty_is_fully_concrete(ty), + rustc_hir::TyKind::Tup(tys) => tys.iter().all(ty_is_fully_concrete), + _ => true, + } +} /// Checks if the given method call matches the expected signature of `([&[mut]] self) -> bool` fn is_is_empty_sig(cx: &LateContext<'_>, call_id: HirId) -> bool { cx.typeck_results().type_dependent_def_id(call_id).is_some_and(|id| { diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_option_as_deref.rs b/src/tools/clippy/clippy_lints/src/methods/needless_option_as_deref.rs index 7626cdb5a5fe8..b8e6a5f50d50b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_option_as_deref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_option_as_deref.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; -use clippy_utils::source::SpanExt; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; +use clippy_utils::source::SpanExt as _; use clippy_utils::sym; use clippy_utils::usage::local_used_after_expr; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_option_take.rs b/src/tools/clippy/clippy_lints/src/methods/needless_option_take.rs index 1622fdb88bd53..98cc7f4aeaf02 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_option_take.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_option_take.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, QPath}; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/no_effect_replace.rs b/src/tools/clippy/clippy_lints/src/methods/no_effect_replace.rs index 2afda2956beb6..667608cf992ef 100644 --- a/src/tools/clippy/clippy_lints/src/methods/no_effect_replace.rs +++ b/src/tools/clippy/clippy_lints/src/methods/no_effect_replace.rs @@ -1,6 +1,6 @@ use clippy_utils::SpanlessEq; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_ast::LitKind; use rustc_hir::{ExprKind, LangItem}; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs b/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs index 5f1cae130daed..4982506036ef6 100644 --- a/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::ty::has_debug_impl; use rustc_errors::Applicability; use rustc_hir as hir; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::{self, Ty}; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/methods/open_options.rs b/src/tools/clippy/clippy_lints/src/methods/open_options.rs index 3ce28e41e6b78..d4c52c56a1a80 100644 --- a/src/tools/clippy/clippy_lints/src/methods/open_options.rs +++ b/src/tools/clippy/clippy_lints/src/methods/open_options.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_data_structures::fx::FxHashMap; use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; diff --git a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_cloned.rs b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_cloned.rs index 156c624488eba..745c791e788d1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_cloned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_cloned.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs index a52f3c1be26e9..31f294ff27d37 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet; use clippy_utils::{peel_blocks, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs b/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs index 817388915f189..98c8e15756931 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_none_expr; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs index 7b2f2e9389e14..bf9c89e43de01 100644 --- a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs @@ -4,7 +4,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::eager_or_lazy::switch_to_lazy_eval; use clippy_utils::higher::VecArgs; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::ty::{expr_type_is_certain, implements_trait}; use clippy_utils::visitors::for_each_expr; @@ -142,6 +142,17 @@ fn check_unwrap_or_default( return false; } + // `Default` for raw pointers is only stable since 1.88.0, so the suggestion would not compile + // below that MSRV (#17379). Only reachable under `-Zbuild-std`, hence not covered by our UI + // tests against a precompiled `std` — removing this breaks no test, but does bring the false + // positive back for build-std users. + if let Some(call_expr) = call_expr + && cx.typeck_results().expr_ty(call_expr).is_raw_ptr() + && !msrv.meets(cx, msrvs::RAW_PTR_DEFAULT) + { + return false; + } + if !expr_type_is_certain(cx, receiver) { return false; } diff --git a/src/tools/clippy/clippy_lints/src/methods/or_then_unwrap.rs b/src/tools/clippy/clippy_lints/src/methods/or_then_unwrap.rs index 448ab621a7ce6..3be6e8b62ec99 100644 --- a/src/tools/clippy/clippy_lints/src/methods/or_then_unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/methods/or_then_unwrap.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::lang_items::LangItem; diff --git a/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs b/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs index 923e4ea4dd975..14b26aee49bf2 100644 --- a/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs +++ b/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/path_ends_with_ext.rs b/src/tools/clippy/clippy_lints/src/methods/path_ends_with_ext.rs index ffba244dcf61c..7e25c240e6d9b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/path_ends_with_ext.rs +++ b/src/tools/clippy/clippy_lints/src/methods/path_ends_with_ext.rs @@ -1,7 +1,7 @@ use super::PATH_ENDS_WITH_EXT; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet; use clippy_utils::sym; use rustc_ast::{LitKind, StrStyle}; @@ -9,7 +9,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; -use std::fmt::Write; +use std::fmt::Write as _; pub const DEFAULT_ALLOWED_DOTFILES: &[&str] = &[ "git", "svn", "gem", "npm", "vim", "env", "rnd", "ssh", "vnc", "smb", "nvm", "bin", diff --git a/src/tools/clippy/clippy_lints/src/methods/ptr_offset_by_literal.rs b/src/tools/clippy/clippy_lints/src/methods/ptr_offset_by_literal.rs index 25d7f05f9a10a..9b4617538ad4a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/ptr_offset_by_literal.rs +++ b/src/tools/clippy/clippy_lints/src/methods/ptr_offset_by_literal.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::sym; use rustc_ast::LitKind; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/range_zip_with_len.rs b/src/tools/clippy/clippy_lints/src/methods/range_zip_with_len.rs index b01adbf4d58af..20220f83620ec 100644 --- a/src/tools/clippy/clippy_lints/src/methods/range_zip_with_len.rs +++ b/src/tools/clippy/clippy_lints/src/methods/range_zip_with_len.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::{SpanExt as _, snippet_with_applicability}; use clippy_utils::{SpanlessEq, get_parent_expr, higher, is_integer_literal, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/read_line_without_trim.rs b/src/tools/clippy/clippy_lints/src/methods/read_line_without_trim.rs index a6dfbada53483..fd5764ba197c5 100644 --- a/src/tools/clippy/clippy_lints/src/methods/read_line_without_trim.rs +++ b/src/tools/clippy/clippy_lints/src/methods/read_line_without_trim.rs @@ -1,7 +1,7 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet; use clippy_utils::visitors::for_each_local_use_after_expr; use clippy_utils::{get_parent_expr, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/readonly_write_lock.rs b/src/tools/clippy/clippy_lints/src/methods/readonly_write_lock.rs index b89aa8dfb4db1..c3af145266483 100644 --- a/src/tools/clippy/clippy_lints/src/methods/readonly_write_lock.rs +++ b/src/tools/clippy/clippy_lints/src/methods/readonly_write_lock.rs @@ -1,7 +1,7 @@ use super::READONLY_WRITE_LOCK; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::mir::{enclosing_mir, visit_local_usage}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, Node, PatKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/repeat_once.rs b/src/tools/clippy/clippy_lints/src/methods/repeat_once.rs index 57a7254605f93..6fe19a932d545 100644 --- a/src/tools/clippy/clippy_lints/src/methods/repeat_once.rs +++ b/src/tools/clippy/clippy_lints/src/methods/repeat_once.rs @@ -1,6 +1,6 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir::{Expr, LangItem}; diff --git a/src/tools/clippy/clippy_lints/src/methods/result_map_or_else_none.rs b/src/tools/clippy/clippy_lints/src/methods/result_map_or_else_none.rs index d5477b9be4c1e..7cf30bb4e9c08 100644 --- a/src/tools/clippy/clippy_lints/src/methods/result_map_or_else_none.rs +++ b/src/tools/clippy/clippy_lints/src/methods/result_map_or_else_none.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::snippet; use clippy_utils::{is_none_expr, peel_blocks}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs b/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs index 8f47306c89479..404ad551919f5 100644 --- a/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs +++ b/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_errors::Applicability; use rustc_hir::{self as hir, Node}; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs b/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs index 8732eba6d4e87..9e9d53cabbb0d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs +++ b/src/tools/clippy/clippy_lints/src/methods/search_is_some.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::{snippet, snippet_with_applicability}; use clippy_utils::sugg::deref_closure_args; use clippy_utils::{is_receiver_of_method_call, strip_pat_refs, sym}; diff --git a/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs b/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs index 2452c499b9cee..2420d6de9540f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/skip_while_next.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/methods/sliced_string_as_bytes.rs b/src/tools/clippy/clippy_lints/src/methods/sliced_string_as_bytes.rs index fb124f3605b94..f581384ca5415 100644 --- a/src/tools/clippy/clippy_lints/src/methods/sliced_string_as_bytes.rs +++ b/src/tools/clippy/clippy_lints/src/methods/sliced_string_as_bytes.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, LangItem}; diff --git a/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs b/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs index 13782a492cbc5..6d319dcd1e678 100644 --- a/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs +++ b/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs @@ -1,7 +1,7 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::usage::local_used_after_expr; use clippy_utils::visitors::{Descend, for_each_expr}; diff --git a/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs b/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs index 1fc0633f4f959..f531abed813ce 100644 --- a/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs +++ b/src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{method_chain_args, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/string_lit_chars_any.rs b/src/tools/clippy/clippy_lints/src/methods/string_lit_chars_any.rs index 53c695e378476..a438873c9ee6d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/string_lit_chars_any.rs +++ b/src/tools/clippy/clippy_lints/src/methods/string_lit_chars_any.rs @@ -1,9 +1,9 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; -use clippy_utils::source::SpanExt; -use itertools::Itertools; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; +use clippy_utils::source::SpanExt as _; +use itertools::Itertools as _; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, Param, PatKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/suspicious_command_arg_space.rs b/src/tools/clippy/clippy_lints/src/methods/suspicious_command_arg_space.rs index b4ea2e62b3c1f..185baf592f2e1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/suspicious_command_arg_space.rs +++ b/src/tools/clippy/clippy_lints/src/methods/suspicious_command_arg_space.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_ast as ast; use rustc_errors::{Applicability, Diag}; diff --git a/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs b/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs index ece97c1f758c0..35cd23c49ecef 100644 --- a/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::expr_or_init; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::usage::mutated_variables; use rustc_hir as hir; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/suspicious_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/suspicious_to_owned.rs index 5d0fd6ca4c80f..c064e707404ca 100644 --- a/src/tools/clippy/clippy_lints/src/methods/suspicious_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/suspicious_to_owned.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/unbuffered_bytes.rs b/src/tools/clippy/clippy_lints/src/methods/unbuffered_bytes.rs index b86ba39d7b6c9..46d8c0771b68b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unbuffered_bytes.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unbuffered_bytes.rs @@ -1,6 +1,6 @@ use super::UNBUFFERED_BYTES; use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::sym; use clippy_utils::ty::implements_trait; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs b/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs index 5e247a50358e6..4c82c268405f3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs +++ b/src/tools/clippy/clippy_lints/src/methods/uninit_assumed_init.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::ty::is_uninit_value_valid_for_ty; use rustc_hir as hir; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/unit_hash.rs b/src/tools/clippy/clippy_lints/src/methods/unit_hash.rs index fb447a99abdce..57cfcc16c3695 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unit_hash.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unit_hash.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs index 54f3fe4105198..31f21492dfedd 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs @@ -1,13 +1,12 @@ use super::utils::clone_or_copy_needed; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::ty::{is_copy, option_arg_ty}; use clippy_utils::usage::mutated_variables; use clippy_utils::visitors::{Descend, for_each_expr_without_closures}; -use clippy_utils::{as_some_expr, sym}; +use clippy_utils::{as_some_expr, is_none_expr, sym}; use core::ops::ControlFlow; use rustc_hir as hir; -use rustc_hir::LangItem::{OptionNone, OptionSome}; use rustc_lint::LateContext; use rustc_span::Span; use std::fmt::Display; @@ -111,25 +110,18 @@ impl Display for Kind { // returns (found_mapping, found_filtering) fn check_expression<'tcx>(cx: &LateContext<'tcx>, arg_id: hir::HirId, expr: &'tcx hir::Expr<'_>) -> (bool, bool) { match expr.kind { - hir::ExprKind::Path(ref path) - if cx - .qpath_res(path, expr.hir_id) - .ctor_parent(cx) - .is_lang_item(cx, OptionNone) => - { + hir::ExprKind::Path(_) if is_none_expr(cx, expr) => { // None (false, true) }, - hir::ExprKind::Call(func, args) => { - if func.res(cx).ctor_parent(cx).is_lang_item(cx, OptionSome) { - if args[0].res_local_id() == Some(arg_id) { - // Some(arg_id) - return (false, false); - } + hir::ExprKind::Call(..) if let Some(found_arg) = as_some_expr(cx, expr) => { + if found_arg.res_local_id() == Some(arg_id) { + // Some(arg_id) + (false, false) + } else { // Some(not arg_id) - return (true, false); + (true, false) } - (true, true) }, hir::ExprKind::MethodCall(segment, recv, [arg], _) if segment.ident.name == sym::then_some diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_first_then_check.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_first_then_check.rs index 43dac249f7440..43421fd320680 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_first_then_check.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_first_then_check.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs index 15337082c03a5..12f1e25ca117b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_context; use clippy_utils::{DefinedTy, ExprUseNode, get_expr_use_site, peel_blocks, strip_pat_refs}; use rustc_ast::ast; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_get_then_check.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_get_then_check.rs index b622a219f35dc..f9d5e9cc6906a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_get_then_check.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_get_then_check.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::sym; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_iter_cloned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_iter_cloned.rs index 5b19c43f1b32f..841ff38b8e193 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_iter_cloned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_iter_cloned.rs @@ -1,13 +1,13 @@ use super::utils::clone_or_copy_needed; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher::ForLoop; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::ty::{get_iterator_item_ty, implements_trait}; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{can_mut_borrow_both, fn_def_id, get_parent_expr}; use core::ops::ControlFlow; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{BindingMode, Expr, ExprKind, Node, PatKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_join.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_join.rs index 3290bdd778243..193406942f3f8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_join.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_join.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, LangItem}; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs index 0b3c8146b9f76..3a60548feeb25 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_lazy_eval.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::{snippet, snippet_with_applicability}; use clippy_utils::{eager_or_lazy, is_from_proc_macro, usage}; use hir::FnRetTy; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_literal_unwrap.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_literal_unwrap.rs index fdd335c762013..ebba91a8a0296 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_literal_unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_literal_unwrap.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::{is_none_expr, last_path_segment, sym}; use rustc_errors::Applicability; use rustc_hir::{self as hir, AmbigArg}; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or.rs index b9af391843876..f8906bb23282d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or.rs @@ -3,7 +3,7 @@ use std::borrow::Cow; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::eager_or_lazy::switch_to_eager_eval; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sugg::{Sugg, make_binop}; use clippy_utils::ty::{implements_trait, is_copy}; use clippy_utils::visitors::is_local_used; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or_else.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or_else.rs index 7c1c31d2bd381..6ce11e6bba230 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or_else.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_map_or_else.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_expr_identity_function; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs index 60bc4de69237a..48333cd2d85f3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::std_or_core; use clippy_utils::sugg::Sugg; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index c454c9e87a3f2..2952d81a3b00c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -2,8 +2,8 @@ use super::implicit_clone::is_clone_like; use super::unnecessary_iter_cloned::{self, is_into_iter}; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::{SpanExt, snippet, snippet_with_context}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::{SpanExt as _, snippet, snippet_with_context}; use clippy_utils::ty::{get_iterator_item_ty, implements_trait, is_copy, peel_and_count_ty_refs}; use clippy_utils::visitors::find_all_ret_expressions; use clippy_utils::{fn_def_id, get_parent_expr, is_expr_temporary_value, return_ty, sym}; @@ -11,7 +11,7 @@ use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{BorrowKind, Expr, ExprKind, ItemKind, LangItem, Node}; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_lint::LateContext; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind, OverloadedDeref}; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_unwrap_unchecked.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_unwrap_unchecked.rs index 0a13bffa733e2..34bd124001a81 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_unwrap_unchecked.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_unwrap_unchecked.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeQPath; +use clippy_utils::res::MaybeQPath as _; use clippy_utils::ty::{option_or_result_arg_ty, same_type_modulo_regions}; use clippy_utils::{is_from_proc_macro, last_path_segment, over}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/unwrap_expect_used.rs b/src/tools/clippy/clippy_lints/src/methods/unwrap_expect_used.rs index ad7b0fc47cf3a..325d4f3c23318 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unwrap_expect_used.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unwrap_expect_used.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::is_never_like; use clippy_utils::{is_in_test, is_inside_always_const_context, is_lint_allowed}; use rustc_hir::Expr; diff --git a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs index 3737249a40cb0..2eac3ffba3246 100644 --- a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{implements_trait, peel_and_count_ty_refs, should_call_clone_as_function}; use clippy_utils::{get_parent_expr, peel_blocks, strip_pat_refs}; @@ -8,7 +8,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::{self as hir, LangItem, Node}; use rustc_lint::LateContext; use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind}; -use rustc_middle::ty::{Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor}; +use rustc_middle::ty::{Ty, TyCtxt, TypeSuperVisitable as _, TypeVisitable as _, TypeVisitor}; use rustc_span::{Span, Symbol, sym}; use core::ops::ControlFlow; diff --git a/src/tools/clippy/clippy_lints/src/methods/useless_nonzero_new_unchecked.rs b/src/tools/clippy/clippy_lints/src/methods/useless_nonzero_new_unchecked.rs index c6f54159c7a78..8054302c91be4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/useless_nonzero_new_unchecked.rs +++ b/src/tools/clippy/clippy_lints/src/methods/useless_nonzero_new_unchecked.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::is_inside_always_const_context; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::{Block, BlockCheckMode, Expr, ExprKind, Node, QPath, UnsafeSource}; diff --git a/src/tools/clippy/clippy_lints/src/methods/utils.rs b/src/tools/clippy/clippy_lints/src/methods/utils.rs index 33346d867ffee..9e7764fa19c80 100644 --- a/src/tools/clippy/clippy_lints/src/methods/utils.rs +++ b/src/tools/clippy/clippy_lints/src/methods/utils.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::{get_parent_expr, usage}; use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_hir::{BorrowKind, Expr, ExprKind, HirId, Mutability, Pat, QPath, Stmt, StmtKind}; diff --git a/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs b/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs index eed2ebebc0281..f6e57c5d1fd5f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs +++ b/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_ast::LitKind; use rustc_data_structures::packed::Pu128; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/verbose_file_reads.rs b/src/tools/clippy/clippy_lints/src/methods/verbose_file_reads.rs index b67e084a35332..fa967337e9421 100644 --- a/src/tools/clippy/clippy_lints/src/methods/verbose_file_reads.rs +++ b/src/tools/clippy/clippy_lints/src/methods/verbose_file_reads.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::sym; use rustc_hir::{Expr, ExprKind, QPath}; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/methods/waker_clone_wake.rs b/src/tools/clippy/clippy_lints/src/methods/waker_clone_wake.rs index bb26c2d935784..0506b4627c5a4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/waker_clone_wake.rs +++ b/src/tools/clippy/clippy_lints/src/methods/waker_clone_wake.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/methods/wrong_self_convention.rs b/src/tools/clippy/clippy_lints/src/methods/wrong_self_convention.rs index 439a1af93cadc..ade9509f1fa88 100644 --- a/src/tools/clippy/clippy_lints/src/methods/wrong_self_convention.rs +++ b/src/tools/clippy/clippy_lints/src/methods/wrong_self_convention.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::is_copy; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_lint::LateContext; use rustc_middle::ty::Ty; use rustc_span::{Span, Symbol}; diff --git a/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs b/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs index 941afb9e2a988..3efb267328984 100644 --- a/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs +++ b/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_middle::ty; diff --git a/src/tools/clippy/clippy_lints/src/min_ident_chars.rs b/src/tools/clippy/clippy_lints/src/min_ident_chars.rs index 2bb574ac113c9..b127eb14413fe 100644 --- a/src/tools/clippy/clippy_lints/src/min_ident_chars.rs +++ b/src/tools/clippy/clippy_lints/src/min_ident_chars.rs @@ -1,18 +1,18 @@ use clippy_config::Conf; -use clippy_utils::diagnostics::span_lint; +use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then}; use clippy_utils::is_from_proc_macro; +use core::iter; +use core::num::NonZero; use rustc_data_structures::fx::FxHashSet; -use rustc_hir::def::{DefKind, Res}; -use rustc_hir::intravisit::{Visitor, walk_item, walk_trait_item}; +use rustc_errors::pluralize; use rustc_hir::{ - GenericParamKind, HirId, Impl, ImplItem, ImplItemImplKind, ImplItemKind, Item, ItemKind, ItemLocalId, Node, Pat, - PatKind, TraitItem, UsePath, + FieldDef, HirId, ImplItem, ImplItemImplKind, ImplItemKind, Item, ItemKind, Node, Pat, PatKind, TraitFn, TraitItem, + TraitItemKind, UseKind, Variant, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; -use rustc_span::symbol::Ident; -use rustc_span::{Span, Symbol}; -use std::borrow::Cow; +use rustc_span::{Ident, Symbol}; +use std::borrow::Cow::{self, Borrowed, Owned}; declare_clippy_lint! { /// ### What it does @@ -49,235 +49,191 @@ declare_clippy_lint! { impl_lint_pass!(MinIdentChars => [MIN_IDENT_CHARS]); pub struct MinIdentChars { - allowed_idents_below_min_chars: FxHashSet, - min_ident_chars_threshold: u64, + allowed_idents_below_min_chars: &'static FxHashSet, + min_chars_threshold: u64, + /// The number of parameter bindings which still need to be skipped for the current + /// function. + /// + /// Impl trait functions have special rules are handled in `check_impl_item` since + /// they have special rules. This is used to signal to `check_pat` the number of parameter + current_fn_params_remaining: u32, + /// Whether to lint idents that have too few chars even when following trait declaration. + lint_trait_impl: bool, } impl MinIdentChars { pub fn new(conf: &'static Conf) -> Self { Self { - allowed_idents_below_min_chars: conf.allowed_idents_below_min_chars.iter().cloned().collect(), - min_ident_chars_threshold: conf.min_ident_chars_threshold, + allowed_idents_below_min_chars: &conf.allowed_idents_below_min_chars, + min_chars_threshold: conf.min_ident_chars_threshold, + current_fn_params_remaining: 0, + lint_trait_impl: conf.min_ident_chars_lint_trait_impl, } } #[expect(clippy::cast_possible_truncation)] - fn is_ident_too_short(&self, cx: &LateContext<'_>, str: &str, span: Span) -> bool { - !span.in_external_macro(cx.sess().source_map()) - && str.len() <= self.min_ident_chars_threshold as usize - && !str.starts_with('_') - && !str.is_empty() - && !self.allowed_idents_below_min_chars.contains(str) - } -} - -impl LateLintPass<'_> for MinIdentChars { - fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { - if self.min_ident_chars_threshold == 0 { - return; + fn check_sym(&self, s: Symbol) -> Option> { + let s = s.as_str(); + if s.len() / 4 <= self.min_chars_threshold as usize + && !s.starts_with('_') + && !self.allowed_idents_below_min_chars.contains(s) + && let len = s.chars().count() + && let Some(missing) = (self.min_chars_threshold as usize).checked_sub(len) + { + NonZero::new(missing + 1) + } else { + None } - - walk_item(&mut IdentVisitor { conf: self, cx }, item); } - fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) { - if self.min_ident_chars_threshold == 0 { - return; + fn lint_msg(&self, missing: NonZero) -> Cow<'static, str> { + if self.min_chars_threshold == 1 { + Borrowed("this identifier consists of only a single character") + } else { + let n = missing.get(); + Owned(format!("this identifier is {n} character{} too short", pluralize!(n))) } + } - // If the function is declared but not defined in a trait, check_pat isn't called so we need to - // check this explicitly - if matches!(&item.kind, rustc_hir::TraitItemKind::Fn(_, _)) { - let param_names = cx.tcx.fn_arg_idents(item.owner_id.to_def_id()); - for ident in param_names.iter().flatten() { - let str = ident.as_str(); - if self.is_ident_too_short(cx, str, ident.span) { - emit_min_ident_chars(self, cx, str, ident.span); + fn emit(&self, cx: &LateContext<'_>, ident: Ident, missing: NonZero) { + if !ident.span.in_external_macro(cx.tcx.sess.source_map()) && !is_from_proc_macro(cx, &ident) { + span_lint_and_then(cx, MIN_IDENT_CHARS, ident.span, self.lint_msg(missing), |diag| { + // FIXME(@Jarcho): Capture a span from the config and point to it here. + if self.min_chars_threshold != 1 { + diag.note_once(format!("the configured threshold is {}", self.min_chars_threshold)); } - } + }); } - - walk_trait_item(&mut IdentVisitor { conf: self, cx }, item); } - // This is necessary as `Node::Pat`s are not visited in `visit_id`. :/ - fn check_pat(&mut self, cx: &LateContext<'_>, pat: &Pat<'_>) { - if let PatKind::Binding(_, _, ident, ..) = pat.kind - && let str = ident.as_str() - && self.is_ident_too_short(cx, str, ident.span) - && is_not_in_trait_impl(cx, pat, ident) - { - emit_min_ident_chars(self, cx, str, ident.span); + fn emit_hir(&self, cx: &LateContext<'_>, id: HirId, ident: Ident, missing: NonZero) { + if !ident.span.in_external_macro(cx.tcx.sess.source_map()) && !is_from_proc_macro(cx, &ident) { + span_lint_hir_and_then(cx, MIN_IDENT_CHARS, id, ident.span, self.lint_msg(missing), |diag| { + diag.note_once(format!("the configured threshold is {}", self.min_chars_threshold)); + }); } } } -struct IdentVisitor<'cx, 'tcx> { - conf: &'cx MinIdentChars, - cx: &'cx LateContext<'tcx>, -} - -impl Visitor<'_> for IdentVisitor<'_, '_> { - fn visit_id(&mut self, hir_id: HirId) { - let Self { conf, cx } = *self; - // FIXME(#112534) Reimplementation of `find`, as it uses indexing, which can (and will in - // async functions, or really anything async) panic. This should probably be fixed on the - // rustc side, this is just a temporary workaround. - let node = if hir_id.local_id == ItemLocalId::from_u32(0) { - // In this case, we can just use `find`, `Owner`'s `node` field is private anyway so we can't - // reimplement it even if we wanted to - Some(cx.tcx.hir_node(hir_id)) - } else { - let owner = cx.tcx.hir_owner_nodes(hir_id.owner); - owner.nodes.get(hir_id.local_id).copied().map(|p| p.node) - }; - let Some(node) = node else { - return; - }; - let Some(ident) = node.ident() else { +impl LateLintPass<'_> for MinIdentChars { + fn check_item(&mut self, cx: &LateContext<'_>, i: &Item<'_>) { + if self.min_chars_threshold == 0 { return; - }; - - let str = ident.as_str(); - if conf.is_ident_too_short(cx, str, ident.span) { - // Check whether the node is part of a `impl` for a trait. - if matches!(cx.tcx.parent_hir_node(hir_id), Node::TraitRef(_)) { - return; - } - - // Check whether the node is part of a `use` statement. We don't want to emit a warning if the user - // has no control over the type. - let usenode = opt_as_use_node(node).or_else(|| { - cx.tcx - .hir_parent_iter(hir_id) - .find_map(|(_, node)| opt_as_use_node(node)) - }); - - // If the name of the identifier is the same as the one of the imported item, this means that we - // found a `use foo::bar`. We can early-return to not emit the warning. - // If however the identifier is different, this means it is an alias (`use foo::bar as baz`). In - // this case, we need to emit the warning for `baz`. - if let Some(imported_item_path) = usenode - // use `present_items` because it could be in any of type_ns, value_ns, macro_ns - && let Some(Res::Def(_, imported_item_defid)) = imported_item_path.res.value_ns - && cx.tcx.item_name(imported_item_defid).as_str() == str + } + let ident = match i.kind { + ItemKind::Const(ident, ..) + | ItemKind::Enum(ident, ..) + | ItemKind::ExternCrate(None, ident) + | ItemKind::Fn { ident, .. } + | ItemKind::Macro(ident, ..) + | ItemKind::Mod(ident, _) + | ItemKind::Static(_, ident, ..) + | ItemKind::Struct(ident, ..) + | ItemKind::Trait { ident, .. } + | ItemKind::TraitAlias(_, ident, ..) + | ItemKind::TyAlias(ident, ..) + | ItemKind::Union(ident, ..) => ident, + ItemKind::Use(path, UseKind::Single(ident)) + if path.segments.last().is_some_and(|p| p.ident.span != ident.span) => { - return; - } + ident + }, + + ItemKind::ExternCrate(..) + | ItemKind::ForeignMod { .. } + | ItemKind::GlobalAsm { .. } + | ItemKind::Impl(_) + | ItemKind::Use(..) => return, + }; + if let Some(missing) = self.check_sym(ident.name) + && !(matches!(i.kind, ItemKind::Fn { .. }) + && cx.tcx.codegen_fn_attrs(i.owner_id.def_id).contains_extern_indicator()) + { + self.emit(cx, ident, missing); + } + } - // `struct Array([T; N])` - // ^ ^ - if let Node::PathSegment(path) = node { - if let Res::Def(def_kind, ..) = path.res - && let DefKind::TyParam | DefKind::ConstParam = def_kind - { - return; - } - if matches!(path.res, Res::PrimTy(..)) || path.res.opt_def_id().is_some_and(|def_id| !def_id.is_local()) + fn check_trait_item(&mut self, cx: &LateContext<'_>, i: &TraitItem<'_>) { + if self.min_chars_threshold == 0 { + return; + } + if let TraitItemKind::Fn(_, TraitFn::Required(idents)) = i.kind { + for &ident in idents { + if let Some(ident) = ident + && let Some(missing) = self.check_sym(ident.name) { - return; + self.emit(cx, ident, missing); } } - // `struct Awa(T)` - // ^ - if let Node::GenericParam(generic_param) = node - && let GenericParamKind::Type { .. } = generic_param.kind - { - return; - } - - // `struct Array([T; N])` - // ^ - if let Node::GenericParam(generic_param) = node - && let GenericParamKind::Const { .. } = generic_param.kind - { - return; - } + } + if let Some(missing) = self.check_sym(i.ident.name) + && !(matches!(i.kind, TraitItemKind::Fn(_, TraitFn::Provided(_))) + && cx.tcx.codegen_fn_attrs(i.owner_id.def_id).contains_extern_indicator()) + { + self.emit(cx, i.ident, missing); + } + } - if is_from_proc_macro(cx, &ident) { - return; + fn check_impl_item(&mut self, cx: &LateContext<'_>, i: &ImplItem<'_>) { + if self.min_chars_threshold == 0 { + return; + } + // For trait impls only lint if the parameter names are different from the trait's or if the + // `min_ident_chars_lint_trait_impl` config item is active. + if let ImplItemImplKind::Trait { + trait_item_def_id: Ok(trait_item), + .. + } = i.impl_kind + && let ImplItemKind::Fn(_, body) = i.kind + { + let mut named_params_count = 0; + for (trait_ident, param) in iter::zip(cx.tcx.fn_arg_idents(trait_item), cx.tcx.hir_body(body).params) { + if let PatKind::Binding(_, _, ident, _) = param.pat.kind { + named_params_count += 1; + if trait_ident.is_none_or(|trait_ident| ident.name != trait_ident.name || self.lint_trait_impl) + && let Some(missing) = self.check_sym(ident.name) + { + self.emit_hir(cx, param.pat.hir_id, ident, missing); + } + } } - - emit_min_ident_chars(conf, cx, str, ident.span); + // Signal the number of parameters to skip to `check_pat`. + // This needs to be added since impl items can technically appear inside + // both the function signature and generic predicates. + self.current_fn_params_remaining += named_params_count; + } + if (!matches!(i.impl_kind, ImplItemImplKind::Trait { .. }) || self.lint_trait_impl) + && let Some(missing) = self.check_sym(i.ident.name) + && !(matches!(i.kind, ImplItemKind::Fn(..)) + && cx.tcx.codegen_fn_attrs(i.owner_id.def_id).contains_extern_indicator()) + { + self.emit(cx, i.ident, missing); } } -} - -fn emit_min_ident_chars(conf: &MinIdentChars, cx: &impl LintContext, ident: &str, span: Span) { - let help = if conf.min_ident_chars_threshold == 1 { - Cow::Borrowed("this ident consists of a single char") - } else { - Cow::Owned(format!( - "this ident is too short ({} <= {})", - ident.len(), - conf.min_ident_chars_threshold, - )) - }; - span_lint(cx, MIN_IDENT_CHARS, span, help); -} -/// Attempt to convert the node to an [`ItemKind::Use`] node. -/// -/// If it is, return the [`UsePath`] contained within. -fn opt_as_use_node(node: Node<'_>) -> Option<&'_ UsePath<'_>> { - if let Node::Item(item) = node - && let ItemKind::Use(path, _) = item.kind - { - Some(path) - } else { - None + fn check_field_def(&mut self, cx: &LateContext<'_>, f: &FieldDef<'_>) { + if let Some(missing) = self.check_sym(f.ident.name) { + self.emit(cx, f.ident, missing); + } } -} -/// Check if a pattern is a function param in an impl block for a trait and that the param name is -/// the same than in the trait definition. -fn is_not_in_trait_impl(cx: &LateContext<'_>, pat: &Pat<'_>, ident: Ident) -> bool { - let parent_node = cx.tcx.parent_hir_node(pat.hir_id); - if !matches!(parent_node, Node::Param(_)) { - return true; + fn check_variant(&mut self, cx: &LateContext<'_>, v: &Variant<'_>) { + if let Some(missing) = self.check_sym(v.ident.name) { + self.emit(cx, v.ident, missing); + } } - for (_, parent_node) in cx.tcx.hir_parent_iter(pat.hir_id) { - if let Node::ImplItem(impl_item) = parent_node - && matches!(impl_item.kind, ImplItemKind::Fn(_, _)) + fn check_pat(&mut self, cx: &LateContext<'_>, pat: &Pat<'_>) { + if let PatKind::Binding(_, _, ident, ..) = pat.kind + && self.min_chars_threshold != 0 { - let impl_parent_node = cx.tcx.parent_hir_node(impl_item.hir_id()); - if let Node::Item(parent_item) = impl_parent_node - && let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = &parent_item.kind - && let Some(name) = get_param_name(impl_item, cx, ident) + if self.current_fn_params_remaining != 0 + && let Node::Param(_) = cx.tcx.parent_hir_node(pat.hir_id) { - return name != ident.name; + self.current_fn_params_remaining -= 1; + } else if let Some(missing) = self.check_sym(ident.name) { + self.emit(cx, ident, missing); } - - return true; } } - - true -} - -fn get_param_name(impl_item: &ImplItem<'_>, cx: &LateContext<'_>, ident: Ident) -> Option { - if let ImplItemImplKind::Trait { - trait_item_def_id: Ok(trait_item_def_id), - .. - } = impl_item.impl_kind - { - let trait_param_names = cx.tcx.fn_arg_idents(trait_item_def_id); - - let ImplItemKind::Fn(_, body_id) = impl_item.kind else { - return None; - }; - - if let Some(param_index) = cx - .tcx - .hir_body_param_idents(body_id) - .position(|param_ident| param_ident.is_some_and(|param_ident| param_ident.span == ident.span)) - && let Some(trait_param_name) = trait_param_names.get(param_index) - && let Some(trait_param_ident) = trait_param_name - { - return Some(trait_param_ident.name); - } - } - - None } diff --git a/src/tools/clippy/clippy_lints/src/minmax.rs b/src/tools/clippy/clippy_lints/src/minmax.rs index 74da699e3c006..97dabf4fb5a66 100644 --- a/src/tools/clippy/clippy_lints/src/minmax.rs +++ b/src/tools/clippy/clippy_lints/src/minmax.rs @@ -1,6 +1,6 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::sym; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index 0bfb28d6b8bf4..6167fb0fa0c84 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -4,7 +4,7 @@ use clippy_utils::{SpanlessEq, fulfill_or_allowed, get_parent_expr, in_automatic use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::{BinOpKind, Expr, ExprKind, QPath, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/misc_early/mod.rs b/src/tools/clippy/clippy_lints/src/misc_early/mod.rs index 79e56b7de41f8..cdc78af6737b7 100644 --- a/src/tools/clippy/clippy_lints/src/misc_early/mod.rs +++ b/src/tools/clippy/clippy_lints/src/misc_early/mod.rs @@ -10,7 +10,7 @@ mod zero_prefixed_literal; use clippy_utils::source::snippet_opt; use rustc_ast::ast::{Expr, ExprKind, Generics, LitFloatType, LitIntType, LitKind, Pat}; use rustc_ast::token; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::Span; @@ -322,10 +322,6 @@ impl EarlyLintPass for MiscEarlyLints { } fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) { - if pat.span.in_external_macro(cx.sess().source_map()) { - return; - } - unneeded_field_pattern::check(cx, pat); redundant_pattern::check(cx, pat); redundant_at_rest_pattern::check(cx, pat); diff --git a/src/tools/clippy/clippy_lints/src/misc_early/redundant_at_rest_pattern.rs b/src/tools/clippy/clippy_lints/src/misc_early/redundant_at_rest_pattern.rs index f2cf93465c0d7..e4fcea5b2baf0 100644 --- a/src/tools/clippy/clippy_lints/src/misc_early/redundant_at_rest_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/misc_early/redundant_at_rest_pattern.rs @@ -1,16 +1,16 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use rustc_ast::{Pat, PatKind}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, LintContext}; +use rustc_lint::{EarlyContext, LintContext as _}; use super::REDUNDANT_AT_REST_PATTERN; pub(super) fn check(cx: &EarlyContext<'_>, pat: &Pat) { - if !pat.span.in_external_macro(cx.sess().source_map()) - && let PatKind::Slice(slice) = &pat.kind + if let PatKind::Slice(slice) = &pat.kind && let [one] = &**slice && let PatKind::Ident(annotation, ident, Some(rest)) = &one.kind && let PatKind::Rest = rest.kind + && !pat.span.in_external_macro(cx.sess().source_map()) { span_lint_and_sugg( cx, diff --git a/src/tools/clippy/clippy_lints/src/misc_early/redundant_pattern.rs b/src/tools/clippy/clippy_lints/src/misc_early/redundant_pattern.rs index 3cb51671aaf18..79bdd3814b70a 100644 --- a/src/tools/clippy/clippy_lints/src/misc_early/redundant_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/misc_early/redundant_pattern.rs @@ -1,13 +1,14 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use rustc_ast::ast::{Pat, PatKind}; use rustc_errors::Applicability; -use rustc_lint::EarlyContext; +use rustc_lint::{EarlyContext, LintContext as _}; use super::REDUNDANT_PATTERN; pub(super) fn check(cx: &EarlyContext<'_>, pat: &Pat) { if let PatKind::Ident(ann, ident, Some(ref right)) = pat.kind && let PatKind::Wild = right.kind + && !pat.span.in_external_macro(cx.sess().source_map()) { span_lint_and_sugg( cx, diff --git a/src/tools/clippy/clippy_lints/src/misc_early/unneeded_field_pattern.rs b/src/tools/clippy/clippy_lints/src/misc_early/unneeded_field_pattern.rs index 5bc437cf24f4c..96c4cedda7ed4 100644 --- a/src/tools/clippy/clippy_lints/src/misc_early/unneeded_field_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/misc_early/unneeded_field_pattern.rs @@ -1,8 +1,8 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; -use clippy_utils::source::SpanExt; -use itertools::Itertools; +use clippy_utils::source::SpanExt as _; +use itertools::Itertools as _; use rustc_ast::ast::{Pat, PatKind}; -use rustc_lint::EarlyContext; +use rustc_lint::{EarlyContext, LintContext as _}; use super::UNNEEDED_FIELD_PATTERN; @@ -22,21 +22,25 @@ pub(super) fn check(cx: &EarlyContext<'_>, pat: &Pat) { } } if !pfields.is_empty() && wilds == pfields.len() { - #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] - span_lint_and_then( - cx, - UNNEEDED_FIELD_PATTERN, - pat.span, - "all the struct fields are matched to a wildcard pattern, consider using `..`", - |diag| { - diag.help(format!("try with `{type_name} {{ .. }}` instead")); - }, - ); + if !pat.span.in_external_macro(cx.sess().source_map()) { + #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] + span_lint_and_then( + cx, + UNNEEDED_FIELD_PATTERN, + pat.span, + "all the struct fields are matched to a wildcard pattern, consider using `..`", + |diag| { + diag.help(format!("try with `{type_name} {{ .. }}` instead")); + }, + ); + } return; } if wilds > 0 { for field in pfields { - if let PatKind::Wild = field.pat.kind { + if let PatKind::Wild = field.pat.kind + && !field.span.in_external_macro(cx.sess().source_map()) + { wilds -= 1; if wilds > 0 { span_lint( diff --git a/src/tools/clippy/clippy_lints/src/misc_early/unneeded_wildcard_pattern.rs b/src/tools/clippy/clippy_lints/src/misc_early/unneeded_wildcard_pattern.rs index 897d720036ee9..3df4c7d82e376 100644 --- a/src/tools/clippy/clippy_lints/src/misc_early/unneeded_wildcard_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/misc_early/unneeded_wildcard_pattern.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use rustc_ast::ast::{Pat, PatFieldsRest, PatKind}; use rustc_errors::Applicability; -use rustc_lint::EarlyContext; +use rustc_lint::{EarlyContext, LintContext as _}; use rustc_span::Span; use super::UNNEEDED_WILDCARD_PATTERN; @@ -16,6 +16,7 @@ pub(super) fn check(cx: &EarlyContext<'_>, pat: &Pat) { .take_while(|pat| matches!(pat.kind, PatKind::Wild)) .enumerate() .last() + && !pat.span.in_external_macro(cx.sess().source_map()) { span_lint(cx, left_pat.span.until(patterns[rest_index].span), left_index == 0); } @@ -25,6 +26,7 @@ pub(super) fn check(cx: &EarlyContext<'_>, pat: &Pat) { .take_while(|pat| matches!(pat.kind, PatKind::Wild)) .enumerate() .last() + && !pat.span.in_external_macro(cx.sess().source_map()) { span_lint( cx, @@ -40,6 +42,9 @@ pub(super) fn check(cx: &EarlyContext<'_>, pat: &Pat) { .take_while(|patfield| matches!(patfield.pat.kind, PatKind::Wild)) .enumerate() .last() + // Only run if `rest_pattern_accessible_field` is Allow, as they otherwise will contradict each other. + && cx.get_lint_level_spec(crate::rest_when_destructuring_struct::REST_PATTERN_ACCESSIBLE_FIELD).is_allow() + && !pat.span.in_external_macro(cx.sess().source_map()) { // Unlike the tuples above, structs have patfields rather than patterns, and separate out the // `..` into a separate parameter. Also, the `..` can only be at the end of the pattern. diff --git a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs index 82f5961729aad..f590f708b5802 100644 --- a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs +++ b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs @@ -82,7 +82,7 @@ pub struct MissingConstForFn { impl MissingConstForFn { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } @@ -101,7 +101,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn { return; } - if span.in_external_macro(cx.tcx.sess.source_map()) || is_entrypoint_fn(cx, def_id.to_def_id()) { + if is_entrypoint_fn(cx, def_id.to_def_id()) { return; } @@ -153,7 +153,9 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn { return; } - if is_from_proc_macro(cx, &(&kind, body, hir_id, span)) { + if (span.from_expansion() && span.in_external_macro(cx.tcx.sess.source_map())) + || is_from_proc_macro(cx, &(&kind, body, hir_id, span)) + { return; } diff --git a/src/tools/clippy/clippy_lints/src/missing_const_for_thread_local.rs b/src/tools/clippy/clippy_lints/src/missing_const_for_thread_local.rs index d02b7fa68b75e..0c0548029f5e6 100644 --- a/src/tools/clippy/clippy_lints/src/missing_const_for_thread_local.rs +++ b/src/tools/clippy/clippy_lints/src/missing_const_for_thread_local.rs @@ -50,7 +50,7 @@ pub struct MissingConstForThreadLocal { impl MissingConstForThreadLocal { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/missing_enforced_import_rename.rs b/src/tools/clippy/clippy_lints/src/missing_enforced_import_rename.rs index 36a2a7f4b406c..c8e3226ea22e9 100644 --- a/src/tools/clippy/clippy_lints/src/missing_enforced_import_rename.rs +++ b/src/tools/clippy/clippy_lints/src/missing_enforced_import_rename.rs @@ -1,12 +1,12 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::paths::{PathNS, lookup_path_str}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::def_id::DefIdMap; use rustc_hir::{Item, ItemKind, UseKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::TyCtxt; use rustc_session::impl_lint_pass; use rustc_span::Symbol; diff --git a/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs b/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs index 657da09f5ca2b..6497e3283b392 100644 --- a/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs +++ b/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs @@ -1,7 +1,7 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sym; use clippy_utils::visitors::{Visitable, for_each_expr}; use rustc_ast::LitKind; diff --git a/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs b/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs index a024088c7baf8..218c7da2a03b4 100644 --- a/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs +++ b/src/tools/clippy/clippy_lints/src/missing_trait_methods.rs @@ -66,7 +66,7 @@ pub struct MissingTraitMethods { impl MissingTraitMethods { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs b/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs index 99561e60f725a..6cf3ce25a23b0 100644 --- a/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs +++ b/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; use clippy_utils::macros::root_macro_call_first_node; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::{get_parent_expr, sym}; use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_hir::{BinOpKind, Block, Expr, ExprKind, HirId, LetStmt, Node, Stmt, StmtKind}; diff --git a/src/tools/clippy/clippy_lints/src/module_style.rs b/src/tools/clippy/clippy_lints/src/module_style.rs index 9058968866e52..27f48cbf789c7 100644 --- a/src/tools/clippy/clippy_lints/src/module_style.rs +++ b/src/tools/clippy/clippy_lints/src/module_style.rs @@ -2,7 +2,7 @@ use clippy_utils::ast_utils::is_cfg_test; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet; use rustc_ast::ast::{self, Inline, ItemKind, ModKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::{FileName, Ident, SourceFile, Span, SyntaxContext, sym}; diff --git a/src/tools/clippy/clippy_lints/src/multiple_bound_locations.rs b/src/tools/clippy/clippy_lints/src/multiple_bound_locations.rs index a78f53188ba8b..2f0e404ad1a34 100644 --- a/src/tools/clippy/clippy_lints/src/multiple_bound_locations.rs +++ b/src/tools/clippy/clippy_lints/src/multiple_bound_locations.rs @@ -6,7 +6,7 @@ use rustc_session::declare_lint_pass; use rustc_span::Span; use clippy_utils::diagnostics::span_lint; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs b/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs index 7e96507a27b16..4e36e677dcea4 100644 --- a/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs +++ b/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs @@ -126,6 +126,48 @@ impl<'tcx> UnsafeExprCollector<'tcx> { unsafe_ops.sort_unstable(); unsafe_ops } + + fn visit_raw_addr_of(&mut self, inner: &'tcx hir::Expr<'tcx>) { + let mut base = inner; + let mut has_fields = false; + while let ExprKind::Field(prefix, _) = base.kind + && self.typeck_results.expr_adjustments(prefix).is_empty() + { + base = prefix; + has_fields = true; + } + + if has_fields { + return self.visit_expr(base); + } + + // Direct address-of operations under `&raw` do not read/write the place, so they are safe + // for mutable statics and raw pointer dereferences. + if let ExprKind::Path(QPath::Resolved( + _, + hir::Path { + res: + Res::Def( + DefKind::Static { + mutability: Mutability::Mut, + .. + }, + _, + ), + .. + }, + )) = base.kind + { + return; + } + if let ExprKind::Unary(UnOp::Deref, ptr_expr) = base.kind + && self.typeck_results.expr_ty(ptr_expr).is_raw_ptr() + { + return self.visit_expr(ptr_expr); + } + + self.visit_expr(base); + } } impl UnsafeExprCollector<'_> { @@ -157,13 +199,8 @@ impl<'tcx> Visitor<'tcx> for UnsafeExprCollector<'tcx> { ExprKind::InlineAsm(_) => self.insert_span(expr.span, "inline assembly used here"), - ExprKind::AddrOf(BorrowKind::Raw, _, mut inner) => { - while let ExprKind::Field(prefix, _) = inner.kind - && self.typeck_results.expr_adjustments(prefix).is_empty() - { - inner = prefix; - } - return self.visit_expr(inner); + ExprKind::AddrOf(BorrowKind::Raw, _, inner) => { + return self.visit_raw_addr_of(inner); }, ExprKind::Field(e, _) if self.typeck_results.expr_ty(e).is_union() => { diff --git a/src/tools/clippy/clippy_lints/src/mutex_atomic.rs b/src/tools/clippy/clippy_lints/src/mutex_atomic.rs index 6d9950579fb24..fb9b60c25f78f 100644 --- a/src/tools/clippy/clippy_lints/src/mutex_atomic.rs +++ b/src/tools/clippy/clippy_lints/src/mutex_atomic.rs @@ -1,11 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::{IntoSpan, SpanExt}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::{IntoSpan as _, SpanExt as _}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::ty_from_hir_ty; use rustc_errors::{Applicability, Diag}; use rustc_hir::{self as hir, Expr, ExprKind, Item, ItemKind, LetStmt, QPath}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::mir::Mutability; use rustc_middle::ty::{self, IntTy, Ty, UintTy}; use rustc_session::declare_lint_pass; diff --git a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs index b82c6c171e37f..7b5635f8555a0 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs @@ -10,7 +10,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{Body, Expr, ExprKind, Mutability, Path, QPath}; use rustc_index::bit_set::DenseBitSet; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::{Rvalue, StatementKind}; use rustc_middle::ty::{ @@ -74,7 +74,7 @@ impl NeedlessBorrowsForGenericArgs<'_> { pub fn new(conf: &'static Conf) -> Self { Self { possible_borrowers: Vec::new(), - msrv: conf.msrv, + msrv: conf.msrv.into(), } } } diff --git a/src/tools/clippy/clippy_lints/src/needless_continue.rs b/src/tools/clippy/clippy_lints/src/needless_continue.rs index d1d0d31ed91a5..0cdde66c69ca6 100644 --- a/src/tools/clippy/clippy_lints/src/needless_continue.rs +++ b/src/tools/clippy/clippy_lints/src/needless_continue.rs @@ -4,7 +4,7 @@ use clippy_utils::source::{indent_of, snippet_block, snippet_with_context}; use rustc_ast::Label; use rustc_errors::Applicability; use rustc_hir::{Block, Expr, ExprKind, HirId, LoopSource, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::{ExpnKind, Span}; diff --git a/src/tools/clippy/clippy_lints/src/needless_else.rs b/src/tools/clippy/clippy_lints/src/needless_else.rs index 299860ac1e037..69975618d3d8b 100644 --- a/src/tools/clippy/clippy_lints/src/needless_else.rs +++ b/src/tools/clippy/clippy_lints/src/needless_else.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::{IntoSpan, SpanExt}; +use clippy_utils::source::{IntoSpan as _, SpanExt as _}; use rustc_ast::ast::{Expr, ExprKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/needless_for_each.rs b/src/tools/clippy/clippy_lints/src/needless_for_each.rs index 55a5a16c00991..d20add9f57403 100644 --- a/src/tools/clippy/clippy_lints/src/needless_for_each.rs +++ b/src/tools/clippy/clippy_lints/src/needless_for_each.rs @@ -1,4 +1,4 @@ -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use rustc_errors::Applicability; use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_hir::{Block, BlockCheckMode, Closure, Expr, ExprKind, Stmt, StmtKind, TyKind}; diff --git a/src/tools/clippy/clippy_lints/src/needless_ifs.rs b/src/tools/clippy/clippy_lints/src/needless_ifs.rs index 48d15056f7291..b7dcd7a784f72 100644 --- a/src/tools/clippy/clippy_lints/src/needless_ifs.rs +++ b/src/tools/clippy/clippy_lints/src/needless_ifs.rs @@ -1,10 +1,10 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher::If; use clippy_utils::is_from_proc_macro; -use clippy_utils::source::{SpanExt, walk_span_to_context}; +use clippy_utils::source::{SpanExt as _, walk_span_to_context}; use rustc_errors::Applicability; use rustc_hir::{ExprKind, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/needless_late_init.rs b/src/tools/clippy/clippy_lints/src/needless_late_init.rs index 69184d1894025..874ff8410989c 100644 --- a/src/tools/clippy/clippy_lints/src/needless_late_init.rs +++ b/src/tools/clippy/clippy_lints/src/needless_late_init.rs @@ -1,6 +1,6 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::needs_ordered_drop; use clippy_utils::visitors::{for_each_expr, for_each_expr_without_closures, is_local_used}; diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index 34d86c1b60248..b0e11baa745a5 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath}; -use clippy_utils::source::{SpanExt, snippet}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; +use clippy_utils::source::{SpanExt as _, snippet}; use clippy_utils::ty::{implements_trait, implements_trait_with_env_from_iter, is_copy}; use clippy_utils::visitors::{Descend, for_each_expr_without_closures}; use clippy_utils::{is_self, peel_hir_ty_options, strip_pat_refs, sym}; @@ -14,7 +14,7 @@ use rustc_hir::{ use rustc_hir_typeck::expr_use_visitor as euv; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::FakeReadCause; -use rustc_middle::ty::{self, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, Ty, TypeVisitableExt as _}; use rustc_session::declare_lint_pass; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::kw; diff --git a/src/tools/clippy/clippy_lints/src/needless_question_mark.rs b/src/tools/clippy/clippy_lints/src/needless_question_mark.rs index 29c45168b61e5..933700f5f9e18 100644 --- a/src/tools/clippy/clippy_lints/src/needless_question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/needless_question_mark.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::MaybeQPath; +use clippy_utils::res::MaybeQPath as _; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{Block, Body, Expr, ExprKind, LangItem, MatchSource}; diff --git a/src/tools/clippy/clippy_lints/src/needless_update.rs b/src/tools/clippy/clippy_lints/src/needless_update.rs index 4a86c3720ca24..ed1f9ad194bc0 100644 --- a/src/tools/clippy/clippy_lints/src/needless_update.rs +++ b/src/tools/clippy/clippy_lints/src/needless_update.rs @@ -34,11 +34,10 @@ declare_clippy_lint! { /// /// Use instead: /// ```rust,ignore - /// // Missing field `z` /// Point { /// x: 1, /// y: 1, - /// ..zero_point + /// z: 1 /// }; /// ``` #[clippy::version = "pre 1.29.0"] diff --git a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs index 4f62ba2e58db2..cfe9fd284e453 100644 --- a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs +++ b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::ty::implements_trait; use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index 7a3c304a3ad3f..31479a4d08df3 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -1,12 +1,12 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::return_ty; use clippy_utils::source::{indent_of, reindent_multiline, snippet_with_applicability}; -use clippy_utils::sugg::DiagExt; +use clippy_utils::sugg::DiagExt as _; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::attrs::AttributeKind; use rustc_hir::{Attribute, HirIdSet}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::AssocKind; use rustc_session::impl_lint_pass; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/no_effect.rs b/src/tools/clippy/clippy_lints/src/no_effect.rs index e471d42679fc5..6afae7ac9850f 100644 --- a/src/tools/clippy/clippy_lints/src/no_effect.rs +++ b/src/tools/clippy/clippy_lints/src/no_effect.rs @@ -1,15 +1,17 @@ use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then}; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::ty::{expr_type_is_certain, has_drop}; -use clippy_utils::{in_automatically_derived, is_inside_always_const_context, is_lint_allowed, peel_blocks}; +use clippy_utils::{ + in_automatically_derived, is_from_proc_macro, is_inside_always_const_context, is_lint_allowed, peel_blocks, +}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{ BinOpKind, BlockCheckMode, Expr, ExprKind, HirId, HirIdMap, ItemKind, LocalSource, Node, PatKind, Stmt, StmtKind, StructTailExpr, UnsafeSource, is_range_literal, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; use std::ops::Deref; @@ -117,7 +119,7 @@ impl<'tcx> LateLintPass<'tcx> for NoEffect { } impl NoEffect { - fn check_no_effect(&mut self, cx: &LateContext<'_>, stmt: &Stmt<'_>) -> bool { + fn check_no_effect<'tcx>(&mut self, cx: &LateContext<'tcx>, stmt: &Stmt<'tcx>) -> bool { if let StmtKind::Semi(expr) = stmt.kind { // Covered by rustc `path_statements` lint if matches!(expr.kind, ExprKind::Path(_)) { @@ -184,11 +186,12 @@ impl NoEffect { && !matches!(local.source, LocalSource::AsyncFn) && let Some(init) = local.init && local.els.is_none() - && !local.pat.span.from_expansion() + && !local.span.from_expansion() && has_no_effect(cx, init) && let PatKind::Binding(_, hir_id, ident, _) = local.pat.kind && ident.name.to_ident_string().starts_with('_') && !in_automatically_derived(cx.tcx, local.hir_id) + && !is_from_proc_macro(cx, init) { if let Some(l) = self.local_bindings.last_mut() { l.push(hir_id); diff --git a/src/tools/clippy/clippy_lints/src/no_mangle_with_rust_abi.rs b/src/tools/clippy/clippy_lints/src/no_mangle_with_rust_abi.rs index 760a5a920542b..e03ea557b84f9 100644 --- a/src/tools/clippy/clippy_lints/src/no_mangle_with_rust_abi.rs +++ b/src/tools/clippy/clippy_lints/src/no_mangle_with_rust_abi.rs @@ -6,7 +6,7 @@ use rustc_hir::attrs::AttributeKind; use rustc_hir::{Attribute, Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; -use rustc_span::{BytePos, Pos}; +use rustc_span::{BytePos, Pos as _}; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/non_canonical_impls.rs b/src/tools/clippy/clippy_lints/src/non_canonical_impls.rs index 4729270d6a92d..60408adc31b62 100644 --- a/src/tools/clippy/clippy_lints/src/non_canonical_impls.rs +++ b/src/tools/clippy/clippy_lints/src/non_canonical_impls.rs @@ -1,12 +1,12 @@ use super::implicit_return::IMPLICIT_RETURN; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::ty::implements_trait; use clippy_utils::{is_from_proc_macro, is_lint_allowed, last_path_segment, std_or_core}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{Block, Body, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, LangItem, Stmt, StmtKind, UnOp}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::{TyCtxt, TypeckResults}; use rustc_session::impl_lint_pass; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 1a4dbf6c9c3d8..dda62d07174f8 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -31,12 +31,12 @@ use rustc_hir::{ ConstArgKind, ConstItemRhs, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, Node, StructTailExpr, TraitItem, TraitItemKind, UnOp, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::mir::{ConstValue, UnevaluatedConst}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind}; use rustc_middle::ty::{ - self, EarlyBinder, GenericArgs, GenericArgsRef, Instance, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, TypeckResults, - TypingEnv, Unnormalized, + self, EarlyBinder, GenericArgs, GenericArgsRef, Instance, Ty, TyCtxt, TypeFolder, TypeSuperFoldable as _, + TypeckResults, TypingEnv, Unnormalized, }; use rustc_session::impl_lint_pass; use rustc_span::DUMMY_SP; diff --git a/src/tools/clippy/clippy_lints/src/non_expressive_names.rs b/src/tools/clippy/clippy_lints/src/non_expressive_names.rs index 21ddefb249ca7..bbaf4c5c07af0 100644 --- a/src/tools/clippy/clippy_lints/src/non_expressive_names.rs +++ b/src/tools/clippy/clippy_lints/src/non_expressive_names.rs @@ -4,7 +4,7 @@ use rustc_ast::ast::{ self, Arm, AssocItem, AssocItemKind, Attribute, Block, FnDecl, Item, ItemKind, Local, Pat, PatKind, }; use rustc_ast::visit::{Visitor, walk_block, walk_expr, walk_pat}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{Span, sym}; diff --git a/src/tools/clippy/clippy_lints/src/non_octal_unix_permissions.rs b/src/tools/clippy/clippy_lints/src/non_octal_unix_permissions.rs index cf19cd9fc81d5..f726a7bc9ef60 100644 --- a/src/tools/clippy/clippy_lints/src/non_octal_unix_permissions.rs +++ b/src/tools/clippy/clippy_lints/src/non_octal_unix_permissions.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::{SpanExt, snippet_with_applicability}; +use clippy_utils::source::{SpanExt as _, snippet_with_applicability}; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/non_std_lazy_statics.rs b/src/tools/clippy/clippy_lints/src/non_std_lazy_statics.rs index 2755e3add760e..44c7ab4d226c7 100644 --- a/src/tools/clippy/clippy_lints/src/non_std_lazy_statics.rs +++ b/src/tools/clippy/clippy_lints/src/non_std_lazy_statics.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::{span_lint, span_lint_hir_and_then}; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::paths::{self, PathNS, find_crates, lookup_path_str}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::visitors::for_each_expr; use clippy_utils::{fn_def_id, is_no_std_crate, sym}; use rustc_data_structures::fx::FxIndexMap; @@ -10,7 +10,7 @@ use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId}; use rustc_hir::{self as hir, BodyId, Expr, ExprKind, HirId, Item, ItemKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; @@ -76,7 +76,7 @@ impl NonStdLazyStatic { #[must_use] pub fn new(conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), once_cell_crates: Vec::new(), sugg_map: FxIndexMap::default(), lazy_type_defs: FxIndexMap::default(), diff --git a/src/tools/clippy/clippy_lints/src/non_zero_suggestions.rs b/src/tools/clippy/clippy_lints/src/non_zero_suggestions.rs index 1b8ab1bdedf8a..b8d1147baeb71 100644 --- a/src/tools/clippy/clippy_lints/src/non_zero_suggestions.rs +++ b/src/tools/clippy/clippy_lints/src/non_zero_suggestions.rs @@ -52,7 +52,13 @@ impl<'tcx> LateLintPass<'tcx> for NonZeroSuggestions { if let ExprKind::Binary(op, _, rhs) = expr.kind && matches!(op.node, BinOpKind::Div | BinOpKind::Rem) { - check_non_zero_conversion(cx, rhs, Applicability::MachineApplicable); + // `Div>` and `Rem>` are only implemented for unsigned + // integer types; signed integer types do not have these impls, so suggesting + // `NonZeroI*::from(x)` as the divisor produces code that won't compile. + let rhs_ty = cx.typeck_results().expr_ty(rhs); + if matches!(rhs_ty.kind(), ty::Uint(_)) { + check_non_zero_conversion(cx, rhs, Applicability::MachineApplicable); + } } else { // Check if the parent expression is a binary operation let parent_is_binary = cx.tcx.hir_parent_iter(expr.hir_id).any(|(_, node)| { diff --git a/src/tools/clippy/clippy_lints/src/nonnull_unchecked_on_box_ptr.rs b/src/tools/clippy/clippy_lints/src/nonnull_unchecked_on_box_ptr.rs new file mode 100644 index 0000000000000..4ce51dffd6558 --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/nonnull_unchecked_on_box_ptr.rs @@ -0,0 +1,98 @@ +use clippy_config::Conf; +use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::msrvs::{self, Msrv}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; +use clippy_utils::source::snippet_with_context; +use clippy_utils::sym; +use clippy_utils::visitors::is_expr_unsafe; +use rustc_errors::Applicability; +use rustc_hir::{Block, BlockCheckMode, Expr, ExprKind, LangItem, Node, UnsafeSource}; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_session::impl_lint_pass; + +declare_clippy_lint! { + /// ### What it does + /// Checks for unsafe usage of `NonNull::new_unchecked(Box::into_raw(x))`, and suggests calling `NonNull::from_mut(Box::leak(x))` instead. + /// + /// ### Why is this bad? + /// `NonNull::new_unchecked` is an unsafe function, which we don't need to call at all if we can instead use a mutable reference. + /// + /// ### Example + /// ```no_run + /// use std::ptr::NonNull; + /// let one = Box::new(1); + /// let ptr = unsafe { NonNull::new_unchecked(Box::into_raw(one)) }; + /// ``` + /// Use instead: + /// ```no_run + /// use std::ptr::NonNull; + /// let one = Box::new(1); + /// let ptr = NonNull::from_mut(Box::leak(one)); + /// ``` + #[clippy::version = "1.98.0"] + pub NONNULL_UNCHECKED_ON_BOX_PTR, + complexity, + "using `NonNull::new_unchecked` with `Box::into_raw`, while `NonNull::from_mut` with `Box::leak` can be used instead" +} + +impl_lint_pass!(NonnullUncheckedOnBoxPtr => [NONNULL_UNCHECKED_ON_BOX_PTR]); + +pub struct NonnullUncheckedOnBoxPtr { + msrv: Msrv, +} + +impl NonnullUncheckedOnBoxPtr { + pub fn new(conf: &Conf) -> Self { + Self { msrv: conf.msrv.into() } + } +} + +impl<'tcx> LateLintPass<'tcx> for NonnullUncheckedOnBoxPtr { + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { + if !expr.span.from_expansion() + && let ExprKind::Call(nonnull_new_unchecked, [arg]) = expr.kind + && let ExprKind::Call(box_into_raw, [arg]) = arg.kind + && nonnull_new_unchecked + .ty_rel_def_if_named(cx, sym::new_unchecked) + .opt_parent(cx) + .opt_impl_ty(cx) + .is_diag_item(cx, sym::NonNull) + && box_into_raw + .ty_rel_def_if_named(cx, sym::into_raw) + .opt_parent(cx) + .opt_impl_ty(cx) + .is_lang_item(cx, LangItem::OwnedBox) + && self.msrv.meets(cx, msrvs::BOX_LEAK) + { + let ctxt = expr.span.ctxt(); + let span = match cx.tcx.parent_hir_node(expr.hir_id) { + Node::Block(&Block { + rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided), + span: unsafe_span, + stmts, + .. + }) if unsafe_span.ctxt() == ctxt && !is_expr_unsafe(cx, arg) && stmts.is_empty() => unsafe_span, + _ => expr.span, + }; + + span_lint_and_then( + cx, + NONNULL_UNCHECKED_ON_BOX_PTR, + span, + "use of `NonNull::new_unchecked` with `Box::into_raw`", + |diag| { + let mut app = Applicability::MachineApplicable; + let arg_name = snippet_with_context(cx, arg.span, ctxt, "_", &mut app).0; + + let sugg = if self.msrv.meets(cx, msrvs::NONNULL_FROM_MUT) { + format!("NonNull::from_mut(Box::leak({arg_name}))") + } else { + format!("NonNull::from(Box::leak({arg_name}))") + }; + + diag.span_suggestion(span, "try", sugg, app); + }, + ); + } + } +} diff --git a/src/tools/clippy/clippy_lints/src/nonstandard_macro_braces.rs b/src/tools/clippy/clippy_lints/src/nonstandard_macro_braces.rs index e601d54cc4eda..1052f13cd3b04 100644 --- a/src/tools/clippy/clippy_lints/src/nonstandard_macro_braces.rs +++ b/src/tools/clippy/clippy_lints/src/nonstandard_macro_braces.rs @@ -1,15 +1,17 @@ use clippy_config::Conf; use clippy_config::types::MacroMatcher; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::{SourceText, SpanExt}; use rustc_ast::ast; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_ast::token::{Delimiter, Token, TokenKind}; +use rustc_ast::tokenstream::{TokenStream, TokenTree}; +use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; -use rustc_hir::def_id::DefId; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::impl_lint_pass; use rustc_span::Span; -use rustc_span::hygiene::{ExpnKind, MacroKind}; + +use crate::rustc_lint::LintContext as _; +use clippy_utils::source::snippet_opt; declare_clippy_lint! { /// ### What it does @@ -29,127 +31,111 @@ declare_clippy_lint! { /// ``` #[clippy::version = "1.55.0"] pub NONSTANDARD_MACRO_BRACES, - nursery, + style, "check consistent use of braces in macro" } impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]); -struct MacroInfo { - callsite_span: Span, - callsite_snippet: SourceText, - old_open_brace: char, - braces: (char, char), -} - pub struct MacroBraces { - macro_braces: FxHashMap, - done: FxHashSet, + macro_braces: (FxHashMap, usize), + /// Spans for statement macro calls, they have special behaviour with semicolons + mac_stmt_spans: Vec, } impl MacroBraces { pub fn new(conf: &'static Conf) -> Self { Self { macro_braces: macro_braces(&conf.standard_macro_braces), - done: FxHashSet::default(), + mac_stmt_spans: Vec::new(), } } } impl EarlyLintPass for MacroBraces { - fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { - if let Some(MacroInfo { - callsite_span, - callsite_snippet, - braces, - .. - }) = is_offending_macro(cx, item.span, self) - { - emit_help(cx, &callsite_snippet, braces, callsite_span, false); - self.done.insert(callsite_span); - } - } - - fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) { - if let Some(MacroInfo { - callsite_span, - callsite_snippet, - braces, - old_open_brace, - }) = is_offending_macro(cx, stmt.span, self) + fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) { + if let Some(last_segment) = mac.path.segments.last() + && let name = last_segment.ident.as_str() + && let Some(&braces) = self.macro_braces.0.get(name) + && let Some(snip) = snippet_opt(cx.sess(), mac.span().with_lo(last_segment.span().lo())) + && let Some(macro_args_str) = &snip.strip_prefix(name).and_then(|snip| snip.strip_prefix('!')) + && let Some(old_open_brace @ ('{' | '(' | '[')) = macro_args_str.trim_start().chars().next() + && old_open_brace != braces.0 { - // if we turn `macro!{}` into `macro!()`/`macro![]`, we'll no longer get the implicit - // trailing semicolon, see #9913 - // NOTE: `stmt.kind != StmtKind::MacCall` because `EarlyLintPass` happens after macro expansion - let add_semi = matches!(stmt.kind, ast::StmtKind::Expr(..)) && old_open_brace == '{'; - emit_help(cx, &callsite_snippet, braces, callsite_span, add_semi); - self.done.insert(callsite_span); + // Semicolons added for statements that previously ended in braces, see issue #9913 + let add_semi = self.mac_stmt_spans.iter().any(|s| *s == mac.span()); + emit_help( + cx, + &snippet_opt(cx.sess(), mac.span()).unwrap(), + braces, + mac.span(), + add_semi, + ); } } - fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { - if let Some(MacroInfo { - callsite_span, - callsite_snippet, - braces, - .. - }) = is_offending_macro(cx, expr.span, self) + // See issue #9913 + fn check_stmt(&mut self, _: &EarlyContext<'_>, stmt: &ast::Stmt) { + if let ast::StmtKind::MacCall(mac_callstmt) = &stmt.kind + && let ast::MacCallStmt { + style: ast::MacStmtStyle::Braces, + .. + } = **mac_callstmt { - emit_help(cx, &callsite_snippet, braces, callsite_span, false); - self.done.insert(callsite_span); + self.mac_stmt_spans.push(mac_callstmt.mac.span()); } } - fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) { - if let Some(MacroInfo { - callsite_span, - braces, - callsite_snippet, - .. - }) = is_offending_macro(cx, ty.span, self) - { - emit_help(cx, &callsite_snippet, braces, callsite_span, false); - self.done.insert(callsite_span); + fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacroDef) { + fn check_ts(cx: &EarlyContext<'_>, ts: &TokenStream, macro_braces: &FxHashMap) { + for (i, current_token) in ts.iter().enumerate() { + if let TokenTree::Delimited(_, _, _, token_stream) = current_token { + // Peel extra braces and parenthesis in macros! + check_ts(cx, token_stream, macro_braces); + } else + // |-TokenKind::Bang + // v + // println! { "Hi" } + // ^^^^^^^ + // | ^^^^^^^^ Brackets always come 1 token after TokenKind::Bang + // ident_token + if let TokenTree::Token( + Token { + kind: TokenKind::Ident(ident_token, _), + span: ident_span, + }, + _, + ) = current_token + && let Some(bang_token) = ts.get(i + 1) + && let Some(macro_args_token) = ts.get(i + 2) + && let TokenTree::Token( + Token { + kind: TokenKind::Bang, .. + }, + _, + ) = *bang_token + && let TokenTree::Delimited(delim_span, _, delim, _) = macro_args_token + // Span from ident_token to brackets (so, the full macro call) + && let snip_span = ident_span.with_hi(delim_span.close.hi()) + && let Some(snip) = snippet_opt(cx, snip_span) + && let Some(&braces) = macro_braces.get(ident_token.as_str()) + && let Some(old_open_brace) = match delim { + Delimiter::Brace => Some('{'), + Delimiter::Parenthesis => Some('('), + Delimiter::Bracket => Some('['), + Delimiter::Invisible(_) => None, + } + && old_open_brace != braces.0 + { + emit_help(cx, &snip, braces, snip_span, false); + } + } } - } -} - -fn is_offending_macro(cx: &EarlyContext<'_>, span: Span, mac_braces: &MacroBraces) -> Option { - let unnested_or_local = |span: Span| { - !span.from_expansion() - || span - .macro_backtrace() - .last() - .is_some_and(|e| e.macro_def_id.is_some_and(DefId::is_local)) - }; - let mut ctxt = span.ctxt(); - while !ctxt.is_root() { - let expn_data = ctxt.outer_expn_data(); - if let ExpnKind::Macro(MacroKind::Bang, mac_name) = expn_data.kind - && let name = mac_name.as_str() - && let Some(&braces) = mac_braces.macro_braces.get(name) - && let Some(snip) = expn_data.call_site.get_text(cx) - // we must check only invocation sites - // https://github.com/rust-lang/rust-clippy/issues/7422 - && let Some(macro_args_str) = snip.strip_prefix(name).and_then(|snip| snip.strip_prefix('!')) - && let Some(old_open_brace @ ('{' | '(' | '[')) = macro_args_str.trim_start().chars().next() - && old_open_brace != braces.0 - && unnested_or_local(expn_data.call_site) - && !mac_braces.done.contains(&expn_data.call_site) - { - return Some(MacroInfo { - callsite_span: expn_data.call_site, - callsite_snippet: snip, - old_open_brace, - braces, - }); + if mac.macro_rules { + check_ts(cx, &mac.body.tokens, &self.macro_braces.0); } - - ctxt = expn_data.call_site.ctxt(); } - - None } fn emit_help(cx: &EarlyContext<'_>, snip: &str, (open, close): (char, char), span: Span, add_semi: bool) { @@ -171,17 +157,21 @@ fn emit_help(cx: &EarlyContext<'_>, snip: &str, (open, close): (char, char), spa } } -fn macro_braces(conf: &[MacroMatcher]) -> FxHashMap { +fn macro_braces(conf: &[MacroMatcher]) -> (FxHashMap, usize) { + // TODO: Use `Symbol`s here, instead of strings. let mut braces = FxHashMap::from_iter( [ - ("print", ('(', ')')), - ("println", ('(', ')')), + ("assert_matches", ('(', ')')), + ("cfg_select", ('{', '}')), + ("debug_assert_matches", ('(', ')')), + ("format", ('(', ')')), + ("format_args", ('(', ')')), ("eprint", ('(', ')')), ("eprintln", ('(', ')')), + ("print", ('(', ')')), + ("println", ('(', ')')), ("write", ('(', ')')), ("writeln", ('(', ')')), - ("format", ('(', ')')), - ("format_args", ('(', ')')), ("vec", ('[', ']')), ("matches", ('(', ')')), ] @@ -191,5 +181,17 @@ fn macro_braces(conf: &[MacroMatcher]) -> FxHashMap { for it in conf { braces.insert(it.name.clone(), it.braces); } - braces + + #[expect( + rustc::potential_query_instability, + reason = "iteration order does not matter for `.max()`" + )] + #[expect(clippy::redundant_closure_for_method_calls, reason = "Clarity")] + let max_len = braces + .keys() + .map(|macro_name| macro_name.len()) + .max() + .expect("`braces` is non-empty"); + + (braces, max_len) } diff --git a/src/tools/clippy/clippy_lints/src/octal_escapes.rs b/src/tools/clippy/clippy_lints/src/octal_escapes.rs index 5735c23a62ac8..a7c22dbefd060 100644 --- a/src/tools/clippy/clippy_lints/src/octal_escapes.rs +++ b/src/tools/clippy/clippy_lints/src/octal_escapes.rs @@ -1,11 +1,11 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_ast::token::LitKind; use rustc_ast::{Expr, ExprKind}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; -use rustc_span::{BytePos, Pos, SpanData}; +use rustc_span::{BytePos, Pos as _, SpanData}; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs index b1262e83d4e5a..1b80649eb5800 100644 --- a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs @@ -1,13 +1,13 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::get_expr_use_or_unification_node; -use clippy_utils::res::{MaybeQPath, MaybeResPath}; +use clippy_utils::res::{MaybeQPath as _, MaybeResPath as _}; use core::cell::Cell; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{ - Body, Expr, ExprKind, HirId, HirIdMap, ImplItem, ImplItemImplKind, ImplItemKind, Node, PatKind, - TraitItem, TraitItemKind, + Body, Expr, ExprKind, HirId, HirIdMap, ImplItem, ImplItemImplKind, ImplItemKind, Node, PatKind, TraitItem, + TraitItemKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, ConstKind, GenericArgKind, GenericArgsRef}; diff --git a/src/tools/clippy/clippy_lints/src/operators/arithmetic_side_effects.rs b/src/tools/clippy/clippy_lints/src/operators/arithmetic_side_effects.rs index 6891ecb0cf9d8..8728122414f0f 100644 --- a/src/tools/clippy/clippy_lints/src/operators/arithmetic_side_effects.rs +++ b/src/tools/clippy/clippy_lints/src/operators/arithmetic_side_effects.rs @@ -3,7 +3,7 @@ use crate::clippy_utils::res::MaybeQPath as _; use clippy_config::Conf; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::{expr_or_init, is_from_proc_macro, is_lint_allowed, peel_hir_expr_refs, peel_hir_expr_unary, sym}; use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -39,7 +39,7 @@ impl ArithmeticSideEffects { FxHashSet::from_iter(["str", "std::string::String"]), ), ]); - for (lhs, rhs) in &conf.arithmetic_side_effects_allowed_binary { + for [lhs, rhs] in &conf.arithmetic_side_effects_allowed_binary { allowed_binary.entry(lhs).or_default().insert(rhs); } for s in &conf.arithmetic_side_effects_allowed { diff --git a/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs b/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs index fa391fad589fe..6a4c56296cc5a 100644 --- a/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::Msrv; use clippy_utils::qualify_min_const_fn::is_stable_const_fn; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::ty::implements_trait; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{binop_traits, eq_expr_value, is_in_const_context, trait_ref_of_method}; diff --git a/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs b/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs index fa1ce43d53b42..968f6ad679b59 100644 --- a/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs +++ b/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeQPath; +use clippy_utils::res::MaybeQPath as _; use clippy_utils::source::snippet_with_context; use clippy_utils::sym; use clippy_utils::ty::{implements_trait, is_copy}; diff --git a/src/tools/clippy/clippy_lints/src/operators/const_comparisons.rs b/src/tools/clippy/clippy_lints/src/operators/const_comparisons.rs index 85128f9114e6b..8891577fc975d 100644 --- a/src/tools/clippy/clippy_lints/src/operators/const_comparisons.rs +++ b/src/tools/clippy/clippy_lints/src/operators/const_comparisons.rs @@ -1,11 +1,11 @@ -#![allow(clippy::match_same_arms)] +#![expect(clippy::match_same_arms)] use std::cmp::Ordering; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::LateContext; -use rustc_middle::ty::layout::HasTyCtxt; +use rustc_middle::ty::layout::HasTyCtxt as _; use rustc_middle::ty::{Ty, TypeckResults}; use rustc_span::{Span, Spanned}; diff --git a/src/tools/clippy/clippy_lints/src/operators/decimal_bitwise_operands.rs b/src/tools/clippy/clippy_lints/src/operators/decimal_bitwise_operands.rs index 08e56e4516c52..c35f18d7a610e 100644 --- a/src/tools/clippy/clippy_lints/src/operators/decimal_bitwise_operands.rs +++ b/src/tools/clippy/clippy_lints/src/operators/decimal_bitwise_operands.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::numeric_literal; use clippy_utils::numeric_literal::NumericLiteral; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_ast::LitKind; use rustc_data_structures::packed::Pu128; use rustc_hir::{BinOpKind, Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/operators/duration_subsec.rs b/src/tools/clippy/clippy_lints/src/operators/duration_subsec.rs index 4a1da7e07a888..a6329b02868c0 100644 --- a/src/tools/clippy/clippy_lints/src/operators/duration_subsec.rs +++ b/src/tools/clippy/clippy_lints/src/operators/duration_subsec.rs @@ -1,6 +1,6 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sym; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/operators/float_cmp.rs b/src/tools/clippy/clippy_lints/src/operators/float_cmp.rs index eb2353cfd90bf..98c4d53f4e088 100644 --- a/src/tools/clippy/clippy_lints/src/operators/float_cmp.rs +++ b/src/tools/clippy/clippy_lints/src/operators/float_cmp.rs @@ -1,14 +1,60 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::macros::{find_assert_eq_args, first_node_macro_backtrace, macro_backtrace}; use clippy_utils::sugg::Sugg; use clippy_utils::{parent_item_name, sym}; use rustc_errors::Applicability; +use rustc_hir::def_id::DefId; use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp}; use rustc_lint::LateContext; use rustc_middle::ty; +use rustc_span::SyntaxContext; use super::{FLOAT_CMP, FLOAT_CMP_CONST}; +pub(crate) fn check_assert<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { + if let Some(macro_call) = + first_node_macro_backtrace(cx, e).find(|macro_call| is_assert_eq_diag(cx, macro_call.def_id)) + && let Some((lhs, rhs, _)) = find_assert_eq_args(cx, e, macro_call.expn) + && is_float(cx, lhs) + { + let ecx = ConstEvalCtxt::new(cx); + let ctxt = macro_call.span.ctxt(); + + let has_const = is_float_const(&ecx, lhs, ctxt) || is_float_const(&ecx, rhs, ctxt); + if !has_const { + return; + } + + let is_comparing_arrays = is_array(cx, lhs) || is_array(cx, rhs); + let msg = if is_comparing_arrays { + "strict comparison of `f32` or `f64` constant arrays" + } else { + "strict comparison of `f32` or `f64` constant" + }; + + clippy_utils::diagnostics::span_lint(cx, FLOAT_CMP_CONST, macro_call.span, msg); + } +} + +fn is_float_const(ecx: &ConstEvalCtxt<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> bool { + match ecx.eval_with_source(expr, ctxt) { + Some((c, s)) if !is_allowed(&c) => !s.is_local(), + _ => false, + } +} + +fn is_assert_eq_diag(cx: &LateContext<'_>, def_id: DefId) -> bool { + matches!( + cx.tcx.get_diagnostic_name(def_id), + Some(sym::assert_eq_macro | sym::assert_ne_macro | sym::debug_assert_eq_macro | sym::debug_assert_ne_macro) + ) +} + +fn is_inside_assert_eq(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { + macro_backtrace(expr.span).any(|mc| is_assert_eq_diag(cx, mc.def_id)) +} + pub(crate) fn check<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, @@ -17,6 +63,12 @@ pub(crate) fn check<'tcx>( right: &'tcx Expr<'_>, ) { if (op == BinOpKind::Eq || op == BinOpKind::Ne) && is_float(cx, left) { + // Skip if inside assert_eq!/assert_ne! macro to avoid double-linting + // (handled by check_assert) + if is_inside_assert_eq(cx, expr) { + return; + } + let ecx = ConstEvalCtxt::new(cx); let ctxt = expr.span.ctxt(); let left_is_local = match ecx.eval_with_source(left, ctxt) { diff --git a/src/tools/clippy/clippy_lints/src/operators/integer_division.rs b/src/tools/clippy/clippy_lints/src/operators/integer_division.rs index 1620312474e99..f6c9276c16d02 100644 --- a/src/tools/clippy/clippy_lints/src/operators/integer_division.rs +++ b/src/tools/clippy/clippy_lints/src/operators/integer_division.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::symbol::sym; diff --git a/src/tools/clippy/clippy_lints/src/operators/invalid_upcast_comparisons.rs b/src/tools/clippy/clippy_lints/src/operators/invalid_upcast_comparisons.rs index b32848a323375..ce37e415413e1 100644 --- a/src/tools/clippy/clippy_lints/src/operators/invalid_upcast_comparisons.rs +++ b/src/tools/clippy/clippy_lints/src/operators/invalid_upcast_comparisons.rs @@ -1,7 +1,7 @@ use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::LateContext; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{self, IntTy, UintTy}; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/operators/manual_div_ceil.rs b/src/tools/clippy/clippy_lints/src/operators/manual_div_ceil.rs index 57f5a046cb061..8b267ba078440 100644 --- a/src/tools/clippy/clippy_lints/src/operators/manual_div_ceil.rs +++ b/src/tools/clippy/clippy_lints/src/operators/manual_div_ceil.rs @@ -1,8 +1,8 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::sugg::{Sugg, has_enclosing_paren}; -use clippy_utils::{SpanlessEq, sym}; +use clippy_utils::{eq_expr_value, sym}; use rustc_ast::{BinOpKind, LitIntType, LitKind, UnOp}; use rustc_data_structures::packed::Pu128; use rustc_errors::Applicability; @@ -29,7 +29,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, op: BinOpKind, lhs: & && inner_op.node == BinOpKind::Add && sub_op.node == BinOpKind::Sub && check_literal(sub_rhs) - && SpanlessEq::new(cx).eq_expr(ctxt, sub_lhs, rhs) + && eq_expr_value(cx, ctxt, sub_lhs, rhs) { build_suggestion(cx, expr, inner_lhs, rhs, &mut applicability); return; @@ -40,7 +40,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, op: BinOpKind, lhs: & && inner_op.node == BinOpKind::Add && sub_op.node == BinOpKind::Sub && check_literal(sub_rhs) - && SpanlessEq::new(cx).eq_expr(ctxt, sub_lhs, rhs) + && eq_expr_value(cx, ctxt, sub_lhs, rhs) { build_suggestion(cx, expr, inner_rhs, rhs, &mut applicability); return; @@ -51,7 +51,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, op: BinOpKind, lhs: & && inner_op.node == BinOpKind::Sub && add_op.node == BinOpKind::Add && check_literal(inner_rhs) - && SpanlessEq::new(cx).eq_expr(ctxt, add_rhs, rhs) + && eq_expr_value(cx, ctxt, add_rhs, rhs) { build_suggestion(cx, expr, add_lhs, rhs, &mut applicability); } @@ -77,7 +77,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, op: BinOpKind, lhs: & ExprKind::MethodCall(method, receiver, [next_multiple_of_arg], _) if method.ident.name == sym::next_multiple_of && check_int_ty(cx.typeck_results().expr_ty(receiver)) - && SpanlessEq::new(cx).eq_expr(ctxt, next_multiple_of_arg, rhs) => + && eq_expr_value(cx, ctxt, next_multiple_of_arg, rhs) => { // x.next_multiple_of(Y) / Y build_suggestion(cx, expr, receiver, rhs, &mut applicability); @@ -89,7 +89,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, op: BinOpKind, lhs: & .assoc_fn_parent(cx) .opt_impl_ty(cx) && check_int_ty(impl_ty_binder.skip_binder()) - && SpanlessEq::new(cx).eq_expr(ctxt, next_multiple_of_arg, rhs) + && eq_expr_value(cx, ctxt, next_multiple_of_arg, rhs) { build_suggestion(cx, expr, receiver, rhs, &mut applicability); } diff --git a/src/tools/clippy/clippy_lints/src/operators/manual_isolate_lowest_one.rs b/src/tools/clippy/clippy_lints/src/operators/manual_isolate_lowest_one.rs index f62514ce99a63..0a706bd166ff2 100644 --- a/src/tools/clippy/clippy_lints/src/operators/manual_isolate_lowest_one.rs +++ b/src/tools/clippy/clippy_lints/src/operators/manual_isolate_lowest_one.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::sugg::Sugg; use clippy_utils::sym; use rustc_ast::BinOpKind; diff --git a/src/tools/clippy/clippy_lints/src/operators/misrefactored_assign_op.rs b/src/tools/clippy/clippy_lints/src/operators/misrefactored_assign_op.rs index 8a2cdf430927b..105c012a7cc8f 100644 --- a/src/tools/clippy/clippy_lints/src/operators/misrefactored_assign_op.rs +++ b/src/tools/clippy/clippy_lints/src/operators/misrefactored_assign_op.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::{eq_expr_value, sugg}; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/operators/mod.rs b/src/tools/clippy/clippy_lints/src/operators/mod.rs index 120716edc203d..2ef361474c26d 100644 --- a/src/tools/clippy/clippy_lints/src/operators/mod.rs +++ b/src/tools/clippy/clippy_lints/src/operators/mod.rs @@ -1040,7 +1040,7 @@ impl Operators { arithmetic_context: numeric_arithmetic::Context::default(), verbose_bit_mask_threshold: conf.verbose_bit_mask_threshold, modulo_arithmetic_allow_comparison_to_zero: conf.allow_comparison_to_zero, - msrv: conf.msrv, + msrv: conf.msrv.into(), } } } @@ -1048,6 +1048,7 @@ impl Operators { impl<'tcx> LateLintPass<'tcx> for Operators { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { eq_op::check_assert(cx, e); + float_cmp::check_assert(cx, e); match e.kind { ExprKind::Binary(op, lhs, rhs) => { if !e.span.from_expansion() { diff --git a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs index 85cf483fce90d..2be50f811e88f 100644 --- a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs +++ b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs @@ -1,7 +1,7 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sugg::Sugg; use clippy_utils::ty::is_copy; use clippy_utils::{ diff --git a/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs index fa7a5d8feb380..08c316af42b00 100644 --- a/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs +++ b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::{is_panic, root_macro_call_first_node}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::visitors::{Descend, for_each_expr}; use clippy_utils::{is_inside_always_const_context, return_ty}; use core::ops::ControlFlow; diff --git a/src/tools/clippy/clippy_lints/src/partialeq_to_none.rs b/src/tools/clippy/clippy_lints/src/partialeq_to_none.rs index 72d2fdeda21c9..f219cd89d7e6f 100644 --- a/src/tools/clippy/clippy_lints/src/partialeq_to_none.rs +++ b/src/tools/clippy/clippy_lints/src/partialeq_to_none.rs @@ -1,8 +1,8 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeQPath}; -use clippy_utils::{peel_hir_expr_refs, peel_ref_operators, sugg}; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::{is_none_expr, peel_hir_expr_refs, peel_ref_operators, sugg}; use rustc_errors::Applicability; -use rustc_hir::{BinOpKind, Expr, ExprKind, LangItem}; +use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; use rustc_span::sym; @@ -56,14 +56,8 @@ impl<'tcx> LateLintPass<'tcx> for PartialeqToNone { }; // If the expression is a literal `Option::None` - let is_none_ctor = |expr: &Expr<'_>| { - !expr.span.from_expansion() - && peel_hir_expr_refs(expr) - .0 - .res(cx) - .ctor_parent(cx) - .is_lang_item(cx, LangItem::OptionNone) - }; + let is_none_ctor = + |expr: &Expr<'_>| !expr.span.from_expansion() && is_none_expr(cx, peel_hir_expr_refs(expr).0); let mut applicability = Applicability::MachineApplicable; diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index d8bff9e9f1703..fba3d43600df4 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -14,7 +14,7 @@ use rustc_hir::intravisit::FnKind; use rustc_hir::{BindingMode, Body, FnDecl, Impl, ItemKind, MutTy, Mutability, Node, PatKind, find_attr}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, PointerCoercion}; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{self, BoundVarIndexKind, RegionKind, TyCtxt}; use rustc_session::impl_lint_pass; use rustc_span::def_id::LocalDefId; diff --git a/src/tools/clippy/clippy_lints/src/pathbuf_init_then_push.rs b/src/tools/clippy/clippy_lints/src/pathbuf_init_then_push.rs index 473718c5419f1..4b8a3a5ef554f 100644 --- a/src/tools/clippy/clippy_lints/src/pathbuf_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/pathbuf_init_then_push.rs @@ -1,12 +1,12 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; -use clippy_utils::source::{SpanExt, snippet}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; +use clippy_utils::source::{SpanExt as _, snippet}; use clippy_utils::sym; use rustc_ast::{LitKind, StrStyle}; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, LetStmt, PatKind, QPath, Stmt, StmtKind, TyKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::{Span, Symbol}; diff --git a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs index 4197680dd0472..e328de609e8cf 100644 --- a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs +++ b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_hir::{ Body, Expr, ExprKind, FnDecl, LetExpr, LocalSource, Mutability, Pat, PatKind, Stmt, StmtKind, intravisit, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty; use rustc_session::declare_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/permissions_set_readonly_false.rs b/src/tools/clippy/clippy_lints/src/permissions_set_readonly_false.rs index a888ee5462949..00e6df84a51d3 100644 --- a/src/tools/clippy/clippy_lints/src/permissions_set_readonly_false.rs +++ b/src/tools/clippy/clippy_lints/src/permissions_set_readonly_false.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_ast::ast::LitKind; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/ptr/cmp_null.rs b/src/tools/clippy/clippy_lints/src/ptr/cmp_null.rs index 5e1c62316b7d3..903b560022a3f 100644 --- a/src/tools/clippy/clippy_lints/src/ptr/cmp_null.rs +++ b/src/tools/clippy/clippy_lints/src/ptr/cmp_null.rs @@ -1,6 +1,6 @@ use super::CMP_NULL; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sugg::Sugg; use clippy_utils::{is_lint_allowed, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs b/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs index e536eb97c9b84..4242b7f1f3224 100644 --- a/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs +++ b/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs @@ -1,17 +1,17 @@ use super::PTR_ARG; use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::{VEC_METHODS_SHADOWING_SLICE_METHODS, get_expr_use_or_unification_node, is_lint_allowed, sym}; use hir::LifetimeKind; use rustc_abi::ExternAbi; use rustc_errors::Applicability; use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_hir::{ - self as hir, AnonConst, BindingMode, Body, Expr, ExprKind, FnSig, GenericArg, HirId, HirIdMap, - Lifetime, Mutability, Node, OwnerId, Param, PatKind, QPath, TyKind, + self as hir, AnonConst, BindingMode, Body, Expr, ExprKind, FnSig, GenericArg, HirId, HirIdMap, Lifetime, + Mutability, Node, OwnerId, Param, PatKind, QPath, TyKind, }; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_infer::traits::{Obligation, ObligationCause}; use rustc_lint::LateContext; use rustc_middle::hir::nested_filter; @@ -136,7 +136,7 @@ struct RefPrefix { } impl fmt::Display for RefPrefix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use fmt::Write; + use fmt::Write as _; f.write_char('&')?; if !self.lt.is_anonymous() { self.lt.ident.fmt(f)?; @@ -149,7 +149,7 @@ impl fmt::Display for RefPrefix { struct DerefTyDisplay<'a, 'tcx>(&'a LateContext<'tcx>, &'a DerefTy<'tcx>); impl fmt::Display for DerefTyDisplay<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use std::fmt::Write; + use std::fmt::Write as _; match self.1 { DerefTy::Str => f.write_str("str"), DerefTy::Path => f.write_str("Path"), diff --git a/src/tools/clippy/clippy_lints/src/pub_underscore_fields.rs b/src/tools/clippy/clippy_lints/src/pub_underscore_fields.rs index 92d1bf505bfaf..f5a52187540d1 100644 --- a/src/tools/clippy/clippy_lints/src/pub_underscore_fields.rs +++ b/src/tools/clippy/clippy_lints/src/pub_underscore_fields.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_config::types::PubUnderscoreFieldsBehaviour; use clippy_utils::attrs::is_doc_hidden; use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sym::PhantomPinned; use rustc_hir::{FieldDef, Item, ItemKind, LangItem}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/question_mark.rs b/src/tools/clippy/clippy_lints/src/question_mark.rs index 7f95adba870d7..c4a6b25e89cd5 100644 --- a/src/tools/clippy/clippy_lints/src/question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/question_mark.rs @@ -4,15 +4,15 @@ use clippy_config::Conf; use clippy_config::types::MatchLintBehaviour; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _}; use clippy_utils::source::{indent_of, reindent_multiline, snippet_with_applicability, snippet_with_context}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::{implements_trait, is_copy}; use clippy_utils::usage::local_used_after_expr; use clippy_utils::{ eq_expr_value, fn_def_id_with_node_args, higher, is_else_clause, is_in_const_context, is_lint_allowed, - pat_and_expr_can_be_question_mark, peel_blocks, peel_blocks_with_stmt, span_contains_cfg, span_contains_comment, - sym, + is_none_expr, is_none_pattern, pat_and_expr_can_be_question_mark, peel_blocks, peel_blocks_with_stmt, + span_contains_cfg, span_contains_comment, sym, }; use rustc_errors::Applicability; use rustc_hir::LangItem::{self, OptionNone, OptionSome, ResultErr, ResultOk}; @@ -71,7 +71,7 @@ pub struct QuestionMark { impl QuestionMark { pub fn new(conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), matches_behaviour: conf.matches_for_let_else, try_block_depth_stack: Vec::new(), inferred_ret_closure_stack: 0, @@ -223,11 +223,13 @@ fn is_early_return(smbl: Symbol, cx: &LateContext<'_>, if_block: &IfBlockType<'_ // We only need to check `if let Some(x) = option` not `if let None = option`, // because the later one will be suggested as `if option.is_none()` thus causing conflict. res.ctor_parent(cx).is_lang_item(cx, OptionSome) - && matches!(if_else, Some(inner) if expr_return_none_or_err(smbl, cx, inner, let_expr, None)) + && if_else.is_some_and(|inner| expr_return_none_or_err(smbl, cx, inner, let_expr, None)) }, sym::Result => { (res.ctor_parent(cx).is_lang_item(cx, ResultOk) - && matches!(if_else, Some(inner) if expr_return_none_or_err(smbl, cx, inner, let_expr, Some(let_pat_sym)))) + && if_else.is_some_and(|inner| { + expr_return_none_or_err(smbl, cx, inner, let_expr, Some(let_pat_sym)) + })) || res.ctor_parent(cx).is_lang_item(cx, ResultErr) && expr_return_none_or_err(smbl, cx, if_then, let_expr, Some(let_pat_sym)) && if_else.is_none() @@ -418,10 +420,10 @@ fn check_arm_is_none_or_err<'tcx>(cx: &LateContext<'tcx>, mode: TryMode, arm: &A }, TryMode::Option => { // Check the pat is `None` - if arm.pat.res(cx).ctor_parent(cx).is_lang_item(cx, OptionNone) + if is_none_pattern(cx, arm.pat) // Check `=> return None` && let ExprKind::Ret(Some(ret_expr)) = arm_body.kind - && ret_expr.res(cx).ctor_parent(cx).is_lang_item(cx, OptionNone) + && is_none_expr(cx, ret_expr) && !ret_expr.span.from_expansion() { true diff --git a/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index f3ab0f82f224a..bd5d3c8980fdf 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/clippy_lints/src/ranges.rs @@ -2,8 +2,8 @@ use clippy_config::Conf; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; -use clippy_utils::source::{SpanExt, snippet, snippet_with_applicability}; +use clippy_utils::res::MaybeResPath as _; +use clippy_utils::source::{SpanExt as _, snippet, snippet_with_applicability}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::implements_trait; use clippy_utils::{ @@ -184,7 +184,7 @@ pub struct Ranges { impl Ranges { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/raw_strings.rs b/src/tools/clippy/clippy_lints/src/raw_strings.rs index 31c90c591b7c2..889dcc1fbc777 100644 --- a/src/tools/clippy/clippy_lints/src/raw_strings.rs +++ b/src/tools/clippy/clippy_lints/src/raw_strings.rs @@ -1,12 +1,12 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::{SpanExt, snippet_opt}; +use clippy_utils::source::{SpanExt as _, snippet_opt}; use rustc_ast::ast::{Expr, ExprKind}; use rustc_ast::token::LitKind; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; -use rustc_span::{BytePos, Pos, Span}; +use rustc_span::{BytePos, Pos as _, Span}; use std::iter::once; use std::ops::ControlFlow; diff --git a/src/tools/clippy/clippy_lints/src/redundant_clone.rs b/src/tools/clippy/clippy_lints/src/redundant_clone.rs index 579f9b8daffd5..eeef64de2cef6 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_clone.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_clone.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then}; use clippy_utils::mir::{LocalUsage, PossibleBorrowerMap, visit_local_usage}; -use clippy_utils::res::MaybeDef; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeDef as _; +use clippy_utils::source::SpanExt as _; use clippy_utils::ty::{has_drop, is_copy, peel_and_count_ty_refs}; use clippy_utils::{fn_has_unsatisfiable_clauses, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs b/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs index b8ede29802fd1..49d09c0e7c666 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_closure_call.rs @@ -4,11 +4,11 @@ use clippy_utils::sugg::Sugg; use hir::Param; use rustc_errors::Applicability; use rustc_hir as hir; -use rustc_hir::intravisit::{Visitor as HirVisitor, Visitor}; +use rustc_hir::intravisit::Visitor; use rustc_hir::{ CaptureBy, ClosureKind, CoroutineDesugaring, CoroutineKind, CoroutineSource, ExprKind, intravisit as hir_visit, }; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::hir::nested_filter; use rustc_middle::ty; use rustc_session::declare_lint_pass; diff --git a/src/tools/clippy/clippy_lints/src/redundant_else.rs b/src/tools/clippy/clippy_lints/src/redundant_else.rs index 148290b4faec4..cb7d7cfafa2d5 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_else.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_else.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::is_from_proc_macro; -use clippy_utils::source::{SpanExt, indent_of, reindent_multiline}; +use clippy_utils::source::{SpanExt as _, indent_of, reindent_multiline}; use rustc_errors::Applicability; use rustc_hir::{Block, Expr, ExprKind, MatchSource, Stmt, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/redundant_field_names.rs b/src/tools/clippy/clippy_lints/src/redundant_field_names.rs index 10793ccca97fd..69195ab28e487 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_field_names.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_field_names.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, MsrvStack}; use rustc_ast::ast::{Expr, ExprKind}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; declare_clippy_lint! { @@ -43,22 +43,15 @@ pub struct RedundantFieldNames { impl RedundantFieldNames { pub fn new(conf: &'static Conf) -> Self { - Self { - msrv: MsrvStack::new(conf.msrv), - } + Self { msrv: conf.msrv.into() } } } impl EarlyLintPass for RedundantFieldNames { fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { - if !self.msrv.meets(msrvs::FIELD_INIT_SHORTHAND) { - return; - } - - if expr.span.in_external_macro(cx.sess().source_map()) { - return; - } - if let ExprKind::Struct(ref se) = expr.kind { + if let ExprKind::Struct(ref se) = expr.kind + && self.msrv.meets(msrvs::FIELD_INIT_SHORTHAND) + { for field in &se.fields { if !field.is_shorthand && let ExprKind::Path(None, path) = &field.expr.kind @@ -66,6 +59,7 @@ impl EarlyLintPass for RedundantFieldNames { && segment.args.is_none() && segment.ident == field.ident && field.span.eq_ctxt(field.ident.span) + && !field.span.in_external_macro(cx.sess().source_map()) { span_lint_and_sugg( cx, diff --git a/src/tools/clippy/clippy_lints/src/redundant_locals.rs b/src/tools/clippy/clippy_lints/src/redundant_locals.rs index 13bd05511ec33..93f583f36e2ef 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_locals.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_locals.rs @@ -5,7 +5,7 @@ use rustc_ast::Mutability; use rustc_hir::def::Res; use rustc_hir::{BindingMode, ByRef, ExprKind, HirId, LetStmt, Node, Pat, PatKind, QPath}; use rustc_hir_typeck::expr_use_visitor::PlaceBase; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::UpvarCapture; use rustc_session::declare_lint_pass; use rustc_span::DesugaringKind; diff --git a/src/tools/clippy/clippy_lints/src/redundant_slicing.rs b/src/tools/clippy/clippy_lints/src/redundant_slicing.rs index dbad96fa9be49..f0a0e4220444f 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_slicing.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_slicing.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::get_parent_expr; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::ty::peel_and_count_ty_refs; use rustc_ast::util::parser::ExprPrecedence; diff --git a/src/tools/clippy/clippy_lints/src/redundant_static_lifetimes.rs b/src/tools/clippy/clippy_lints/src/redundant_static_lifetimes.rs index 35cfc37b133b2..49ac5ed279493 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_static_lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_static_lifetimes.rs @@ -42,9 +42,7 @@ pub struct RedundantStaticLifetimes { impl RedundantStaticLifetimes { pub fn new(conf: &'static Conf) -> Self { - Self { - msrv: MsrvStack::new(conf.msrv), - } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/regex.rs b/src/tools/clippy/clippy_lints/src/regex.rs index 837c29c08851b..9f929bb6d2b56 100644 --- a/src/tools/clippy/clippy_lints/src/regex.rs +++ b/src/tools/clippy/clippy_lints/src/regex.rs @@ -4,8 +4,8 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; use clippy_utils::paths; use clippy_utils::paths::PathLookup; -use clippy_utils::res::MaybeQPath; -use clippy_utils::source::SpanExt; +use clippy_utils::res::MaybeQPath as _; +use clippy_utils::source::SpanExt as _; use rustc_ast::ast::{LitKind, StrStyle}; use rustc_hir::def_id::DefIdMap; use rustc_hir::{BorrowKind, Expr, ExprKind, OwnerId}; diff --git a/src/tools/clippy/clippy_lints/src/repeat_vec_with_capacity.rs b/src/tools/clippy/clippy_lints/src/repeat_vec_with_capacity.rs index 637d9bf7af287..294c6d0bc1e8d 100644 --- a/src/tools/clippy/clippy_lints/src/repeat_vec_with_capacity.rs +++ b/src/tools/clippy/clippy_lints/src/repeat_vec_with_capacity.rs @@ -18,7 +18,7 @@ pub struct RepeatVecWithCapacity { impl RepeatVecWithCapacity { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/replace_box.rs b/src/tools/clippy/clippy_lints/src/replace_box.rs index 7b743746df2c1..95f2f8da2c647 100644 --- a/src/tools/clippy/clippy_lints/src/replace_box.rs +++ b/src/tools/clippy/clippy_lints/src/replace_box.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::implements_trait; use clippy_utils::{is_default_equivalent_call, local_is_initialized}; diff --git a/src/tools/clippy/clippy_lints/src/reserve_after_initialization.rs b/src/tools/clippy/clippy_lints/src/reserve_after_initialization.rs index b5503f6cdfb03..475b350047e78 100644 --- a/src/tools/clippy/clippy_lints/src/reserve_after_initialization.rs +++ b/src/tools/clippy/clippy_lints/src/reserve_after_initialization.rs @@ -1,12 +1,12 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher::{VecInitKind, get_vec_init_kind}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet; use clippy_utils::{is_from_proc_macro, sym}; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, LetStmt, PatKind, QPath, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/rest_when_destructuring_struct.rs b/src/tools/clippy/clippy_lints/src/rest_when_destructuring_struct.rs new file mode 100644 index 0000000000000..73772e5b52f08 --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/rest_when_destructuring_struct.rs @@ -0,0 +1,164 @@ +use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::is_from_proc_macro; +use rustc_errors::Applicability; +use rustc_lint::LateLintPass; +use rustc_middle::ty; +use rustc_session::declare_lint_pass; + +use std::fmt::Write as _; + +declare_clippy_lint! { + /// ### What it does + /// Disallow the use of rest patterns for accessible fields + /// + /// ### Why restrict this? + /// It might lead to unhandled fields when the struct changes. + /// + /// ### Example + /// ```no_run + /// struct S { + /// a: u8, + /// b: u8, + /// c: u8, + /// } + /// + /// let s = S { a: 1, b: 2, c: 3 }; + /// + /// let S { a, b, .. } = s; + /// ``` + /// Use instead: + /// ```no_run + /// struct S { + /// a: u8, + /// b: u8, + /// c: u8, + /// } + /// + /// let s = S { a: 1, b: 2, c: 3 }; + /// + /// let S { a, b, c: _ } = s; + /// ``` + #[clippy::version = "1.99.0"] + pub REST_PATTERN_ACCESSIBLE_FIELD, + restriction, + "rest pattern (`..`) used for accessible field" +} + +declare_clippy_lint! { + /// ### What it does + /// Disallow the use of rest patterns that don't capture any fields. + /// + /// ### Why restrict this? + /// It might lead to unhandled fields when the struct changes. + /// + /// ### Example + /// ```no_run + /// struct S { + /// a: u8, + /// b: u8, + /// c: u8, + /// } + /// + /// let s = S { a: 1, b: 2, c: 3 }; + /// + /// let S { a, b, c, .. } = s; + /// ``` + /// Use instead: + /// ```no_run + /// struct S { + /// a: u8, + /// b: u8, + /// c: u8, + /// } + /// + /// let s = S { a: 1, b: 2, c: 3 }; + /// + /// let S { a, b, c } = s; + /// ``` + #[clippy::version = "1.99.0"] + pub UNNECESSARY_REST_PATTERN, + restriction, + "unnecessary rest pattern (`..`) in destructuring expression" +} + +declare_lint_pass!(RestWhenDestructuringStruct => [ + REST_PATTERN_ACCESSIBLE_FIELD, + UNNECESSARY_REST_PATTERN, +]); + +impl<'tcx> LateLintPass<'tcx> for RestWhenDestructuringStruct { + fn check_pat(&mut self, cx: &rustc_lint::LateContext<'tcx>, pat: &'tcx rustc_hir::Pat<'tcx>) { + if let rustc_hir::PatKind::Struct(path, fields, Some(dotdot)) = pat.kind + && let qty = cx.typeck_results().qpath_res(&path, pat.hir_id) + && let ty = cx.typeck_results().pat_ty(pat) + && let ty::Adt(a, _) = ty.kind() + && let Some(vid) = qty.opt_def_id().map(|x| a.variant_index_with_id(x)) + && let Some(variant) = a.variants().get(vid) + { + let mut missing_suggestions = String::new(); + let mut needs_dotdot = variant.field_list_has_applicable_non_exhaustive(); + + for field in &variant.fields { + if field.vis.is_accessible_from(cx.tcx.parent_module(pat.hir_id), cx.tcx) { + if !fields.iter().any(|x| x.ident.name == field.name) { + if !missing_suggestions.is_empty() { + missing_suggestions.push_str(", "); + } + let _ = write!(missing_suggestions, "{}: _", field.name.as_str()); + } + } else { + needs_dotdot = true; + } + } + + // Filter out results from macros + if (missing_suggestions.is_empty() && needs_dotdot) + || pat.span.in_external_macro(cx.tcx.sess.source_map()) + || is_from_proc_macro(cx, pat) + { + return; + } + + if !missing_suggestions.is_empty() { + let suggestion_span = if needs_dotdot { + missing_suggestions.push_str(", "); + dotdot.shrink_to_lo() + } else { + dotdot + }; + + let message = if fields.is_empty() { + "consider explicitly ignoring fields with wildcard patterns (`x: _`)" + } else { + "consider explicitly ignoring remaining fields with wildcard patterns (`x: _`)" + }; + + span_lint_and_then( + cx, + REST_PATTERN_ACCESSIBLE_FIELD, + pat.span, + "struct destructuring with rest (`..`)", + |diag| { + diag.span_suggestion_verbose( + suggestion_span, + message, + &missing_suggestions, + Applicability::MachineApplicable, + ); + }, + ); + } else if !needs_dotdot { + let message = "consider removing the unnecessary rest pattern (`..`)"; + span_lint_and_then( + cx, + UNNECESSARY_REST_PATTERN, + pat.span, + "unnecessary rest pattern (`..`)", + |diag| { + diag.span_suggestion_verbose(dotdot, message, "", Applicability::MachineApplicable); + }, + ); + } + } + } +} diff --git a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs index 8c892b7085b7c..1bbef1115d0c6 100644 --- a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs +++ b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs @@ -1,10 +1,10 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::ty::is_must_use_ty; +use clippy_utils::ty::opt_must_use_path; use clippy_utils::{nth_arg, return_ty}; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl, OwnerId, TraitItem, TraitItemKind, find_attr}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::Span; @@ -68,9 +68,7 @@ declare_clippy_lint! { declare_lint_pass!(ReturnSelfNotMustUse => [RETURN_SELF_NOT_MUST_USE]); fn check_method(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_def: LocalDefId, span: Span, owner_id: OwnerId) { - if !span.in_external_macro(cx.sess().source_map()) - // If it comes from an external macro, better ignore it. - && decl.implicit_self().has_implicit_self() + if decl.implicit_self().has_implicit_self() // We only show this warning for public exported methods. && cx.effective_visibilities.is_exported(fn_def) // We don't want to emit this lint if the `#[must_use]` attribute is already there. @@ -86,8 +84,9 @@ fn check_method(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_def: LocalDefId, spa // For this check, we don't want to remove the reference on the returned type because if // there is one, we shouldn't emit a warning! && self_arg.peel_refs() == ret_ty - // If `Self` is already marked as `#[must_use]`, no need for the attribute here. - && !is_must_use_ty(cx, ret_ty) + // If `Self` is already considered as `#[must_use]`, no need for the attribute here. + && opt_must_use_path(cx, ret_ty).is_none() + && !span.in_external_macro(cx.sess().source_map()) { span_lint_and_help( cx, diff --git a/src/tools/clippy/clippy_lints/src/returns/let_and_return.rs b/src/tools/clippy/clippy_lints/src/returns/let_and_return.rs index c1a909fdde4e1..1041dadaf4d10 100644 --- a/src/tools/clippy/clippy_lints/src/returns/let_and_return.rs +++ b/src/tools/clippy/clippy_lints/src/returns/let_and_return.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_context; use clippy_utils::sugg::has_enclosing_paren; use clippy_utils::visitors::for_each_expr; @@ -7,7 +7,7 @@ use clippy_utils::{binary_expr_needs_parentheses, fn_def_id, span_contains_non_w use core::ops::ControlFlow; use rustc_errors::Applicability; use rustc_hir::{Block, Expr, PatKind, StmtKind}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::GenericArgKind; use rustc_span::edition::Edition; diff --git a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs index f3d6324e1885e..ad81b5efcfe13 100644 --- a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs +++ b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs @@ -8,9 +8,9 @@ use rustc_ast::MetaItemInner; use rustc_errors::Applicability; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, Expr, ExprKind, HirId, LangItem, MatchSource, StmtKind}; -use rustc_lint::{LateContext, Level, LintContext}; +use rustc_lint::{LateContext, Level, LintContext as _}; use rustc_middle::ty::{self, Ty}; -use rustc_span::{BytePos, Pos, Span}; +use rustc_span::{BytePos, Pos as _, Span}; use std::borrow::Cow; use std::fmt::Display; diff --git a/src/tools/clippy/clippy_lints/src/returns/needless_return_with_question_mark.rs b/src/tools/clippy/clippy_lints/src/returns/needless_return_with_question_mark.rs index e37ea9800ed0e..40e66220a0c94 100644 --- a/src/tools/clippy/clippy_lints/src/returns/needless_return_with_question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/returns/needless_return_with_question_mark.rs @@ -1,17 +1,16 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::{is_from_proc_macro, is_inside_let_else}; use rustc_errors::Applicability; use rustc_hir::LangItem::ResultErr; use rustc_hir::{Expr, ExprKind, HirId, MatchSource, Node, Stmt, StmtKind}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::adjustment::Adjust; use super::NEEDLESS_RETURN_WITH_QUESTION_MARK; pub(super) fn check_stmt<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { - if !stmt.span.in_external_macro(cx.sess().source_map()) - && let StmtKind::Semi(expr) = stmt.kind + if let StmtKind::Semi(expr) = stmt.kind && let ExprKind::Ret(Some(ret)) = expr.kind // return Err(...)? desugars to a match // over a Err(...).branch() @@ -28,6 +27,7 @@ pub(super) fn check_stmt<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { && !is_inside_let_else(cx.tcx, expr) && let [.., final_stmt] = block.stmts && (block.expr.is_some() || final_stmt.hir_id != stmt.hir_id) + && !stmt.span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, expr) && !stmt_needs_never_type(cx, stmt.hir_id) { diff --git a/src/tools/clippy/clippy_lints/src/same_length_and_capacity.rs b/src/tools/clippy/clippy_lints/src/same_length_and_capacity.rs index 1d5d960665ef6..fcd23619f9ed2 100644 --- a/src/tools/clippy/clippy_lints/src/same_length_and_capacity.rs +++ b/src/tools/clippy/clippy_lints/src/same_length_and_capacity.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::{eq_expr_value, sym}; use rustc_hir::{Expr, ExprKind, LangItem, QPath}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints/src/semicolon_block.rs b/src/tools/clippy/clippy_lints/src/semicolon_block.rs index 7fdc03891a889..583585282ac9e 100644 --- a/src/tools/clippy/clippy_lints/src/semicolon_block.rs +++ b/src/tools/clippy/clippy_lints/src/semicolon_block.rs @@ -1,9 +1,9 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_errors::Applicability; use rustc_hir::{Block, Expr, ExprKind, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs b/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs index 63237c655ef17..5a3a1191c63d8 100644 --- a/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs +++ b/src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_context; use rustc_errors::Applicability; use rustc_hir::{Block, ExprKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::{ExpnKind, MacroKind, Span}; diff --git a/src/tools/clippy/clippy_lints/src/set_contains_or_insert.rs b/src/tools/clippy/clippy_lints/src/set_contains_or_insert.rs index 03acfb22c6c82..e3057e72f9ea7 100644 --- a/src/tools/clippy/clippy_lints/src/set_contains_or_insert.rs +++ b/src/tools/clippy/clippy_lints/src/set_contains_or_insert.rs @@ -1,7 +1,7 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::visitors::for_each_expr; use clippy_utils::{SpanlessEq, higher, peel_hir_expr_while, sym}; use rustc_hir::{Expr, ExprKind, UnOp}; diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index a83cf9d9deefe..892c29f7fbf75 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -1,15 +1,15 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet; use clippy_utils::visitors::{Descend, Visitable, for_each_expr}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::Res; use rustc_hir::def_id::LocalDefId; use rustc_hir::{ - Block, Body, BodyOwnerKind, Expr, ExprKind, HirId, ItemLocalId, LetExpr, LocalSource, Node, - Pat, PatKind, QPath, UnOp, + Block, Body, BodyOwnerKind, Expr, ExprKind, HirId, ItemLocalId, LetExpr, LocalSource, Node, Pat, PatKind, QPath, + UnOp, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; diff --git a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs index 86b3387ae643f..0e762a795c7b0 100644 --- a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs +++ b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::{indent_of, snippet}; use clippy_utils::{expr_or_init, get_builtin_attr, peel_hir_expr_unary, sym}; use rustc_ast::BindingMode; diff --git a/src/tools/clippy/clippy_lints/src/single_call_fn.rs b/src/tools/clippy/clippy_lints/src/single_call_fn.rs index 4adcc1cac1237..8f0fed4d7d27c 100644 --- a/src/tools/clippy/clippy_lints/src/single_call_fn.rs +++ b/src/tools/clippy/clippy_lints/src/single_call_fn.rs @@ -5,7 +5,7 @@ use rustc_data_structures::fx::{FxIndexMap, IndexEntry}; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::{Expr, ExprKind, HirId, Node}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/single_char_lifetime_names.rs b/src/tools/clippy/clippy_lints/src/single_char_lifetime_names.rs index 595c75acf031f..d30b3fb2c6921 100644 --- a/src/tools/clippy/clippy_lints/src/single_char_lifetime_names.rs +++ b/src/tools/clippy/clippy_lints/src/single_char_lifetime_names.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_ast::ast::{GenericParam, GenericParamKind}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { @@ -41,13 +41,10 @@ declare_lint_pass!(SingleCharLifetimeNames => [SINGLE_CHAR_LIFETIME_NAMES]); impl EarlyLintPass for SingleCharLifetimeNames { fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &GenericParam) { - if param.ident.span.in_external_macro(cx.sess().source_map()) { - return; - } - if let GenericParamKind::Lifetime = param.kind && !param.is_placeholder && param.ident.as_str().len() <= 2 + && !param.ident.span.in_external_macro(cx.sess().source_map()) { #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/single_component_path_imports.rs b/src/tools/clippy/clippy_lints/src/single_component_path_imports.rs index 67c8710b80ec8..c1365d299ed2a 100644 --- a/src/tools/clippy/clippy_lints/src/single_component_path_imports.rs +++ b/src/tools/clippy/clippy_lints/src/single_component_path_imports.rs @@ -3,7 +3,7 @@ use rustc_ast::node_id::{NodeId, NodeMap}; use rustc_ast::visit::{Visitor, walk_expr}; use rustc_ast::{Crate, Expr, ExprKind, Item, ItemKind, MacroDef, ModKind, Ty, TyKind, UseTreeKind}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::edition::Edition; use rustc_span::symbol::kw; diff --git a/src/tools/clippy/clippy_lints/src/single_option_map.rs b/src/tools/clippy/clippy_lints/src/single_option_map.rs index 4556d287711fe..ba9a8368621f6 100644 --- a/src/tools/clippy/clippy_lints/src/single_option_map.rs +++ b/src/tools/clippy/clippy_lints/src/single_option_map.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::peel_blocks; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use rustc_hir::def::Res; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::FnKind; diff --git a/src/tools/clippy/clippy_lints/src/single_range_in_vec_init.rs b/src/tools/clippy/clippy_lints/src/single_range_in_vec_init.rs index e922f72330b3e..1de96df06baf8 100644 --- a/src/tools/clippy/clippy_lints/src/single_range_in_vec_init.rs +++ b/src/tools/clippy/clippy_lints/src/single_range_in_vec_init.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher::{Range, VecArgs}; use clippy_utils::macros::root_macro_call_first_node; -use clippy_utils::source::{SpanExt, snippet_with_context}; +use clippy_utils::source::{SpanExt as _, snippet_with_context}; use clippy_utils::ty::implements_trait; use clippy_utils::{is_no_std_crate, sym}; use rustc_ast::{LitIntType, LitKind, RangeLimits, UintTy}; diff --git a/src/tools/clippy/clippy_lints/src/size_of_ref.rs b/src/tools/clippy/clippy_lints/src/size_of_ref.rs index 0e78cf277c643..20ac318470568 100644 --- a/src/tools/clippy/clippy_lints/src/size_of_ref.rs +++ b/src/tools/clippy/clippy_lints/src/size_of_ref.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sym; use clippy_utils::ty::peel_and_count_ty_refs; use rustc_hir::{Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs b/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs index ce74a9bea57f7..445c39fa57275 100644 --- a/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs +++ b/src/tools/clippy/clippy_lints/src/slow_vector_initialization.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::matching_root_macro_call; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _}; use clippy_utils::sugg::Sugg; use clippy_utils::{SpanlessEq, get_enclosing_block, is_integer_literal, span_contains_comment, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs b/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs index 0f7cbd503bcd8..3f4ba4724e942 100644 --- a/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs +++ b/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs @@ -6,7 +6,7 @@ use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{Block, Body, HirId, Path, PathSegment, StabilityLevel, StableSince}; -use rustc_lint::{LateContext, LateLintPass, Lint, LintContext}; +use rustc_lint::{LateContext, LateLintPass, Lint, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::symbol::kw; use rustc_span::{Span, sym}; @@ -101,7 +101,7 @@ impl StdReexports { pub fn new(conf: &'static Conf) -> Self { Self { lint_points: Option::default(), - msrv: conf.msrv, + msrv: conf.msrv.into(), } } @@ -124,14 +124,14 @@ enum LintPoint { impl<'tcx> LateLintPass<'tcx> for StdReexports { fn check_path(&mut self, cx: &LateContext<'tcx>, path: &Path<'tcx>, _: HirId) { if let Res::Def(def_kind, def_id) = path.res + && !matches!(def_kind, DefKind::Macro(_)) && let Some(first_segment) = get_first_segment(path) + && let Res::Def(DefKind::Mod, crate_def_id) = first_segment.res + && crate_def_id.is_crate_root() && is_stable(cx, def_id, self.msrv) && !path.span.in_external_macro(cx.sess().source_map()) && !is_from_proc_macro(cx, &first_segment.ident) - && !matches!(def_kind, DefKind::Macro(_)) && let Some(last_segment) = path.segments.last() - && let Res::Def(DefKind::Mod, crate_def_id) = first_segment.res - && crate_def_id.is_crate_root() { let (lint, used_mod, replace_with) = match first_segment.ident.name { sym::std => match cx.tcx.crate_name(def_id.krate) { diff --git a/src/tools/clippy/clippy_lints/src/string_patterns.rs b/src/tools/clippy/clippy_lints/src/string_patterns.rs index 986429ec0829e..7d4461f030956 100644 --- a/src/tools/clippy/clippy_lints/src/string_patterns.rs +++ b/src/tools/clippy/clippy_lints/src/string_patterns.rs @@ -5,11 +5,11 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::eager_or_lazy::switch_to_eager_eval; use clippy_utils::macros::matching_root_macro_call; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::{snippet, str_literal_to_char_literal}; use clippy_utils::sym; use clippy_utils::visitors::{Descend, for_each_expr}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_ast::{BinOpKind, LitKind}; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, PatExprKind, PatKind}; @@ -83,7 +83,7 @@ pub struct StringPatterns { impl StringPatterns { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/strings.rs b/src/tools/clippy/clippy_lints/src/strings.rs index 2128ffb6d7d60..6cbbcc681f944 100644 --- a/src/tools/clippy/clippy_lints/src/strings.rs +++ b/src/tools/clippy/clippy_lints/src/strings.rs @@ -1,12 +1,12 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::{snippet, snippet_with_applicability, snippet_with_context}; use clippy_utils::{SpanlessEq, get_expr_use_or_unification_node, get_parent_expr, is_lint_allowed, method_calls, sym}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind, LangItem, Node}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty; use rustc_session::declare_lint_pass; diff --git a/src/tools/clippy/clippy_lints/src/strlen_on_c_strings.rs b/src/tools/clippy/clippy_lints/src/strlen_on_c_strings.rs index 0320f76f8772a..c784c1744743f 100644 --- a/src/tools/clippy/clippy_lints/src/strlen_on_c_strings.rs +++ b/src/tools/clippy/clippy_lints/src/strlen_on_c_strings.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::visitors::is_expr_unsafe; use clippy_utils::{match_libc_symbol, sym}; @@ -45,7 +45,7 @@ pub struct StrlenOnCStrings { impl StrlenOnCStrings { pub fn new(conf: &Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/suspicious_operation_groupings.rs b/src/tools/clippy/clippy_lints/src/suspicious_operation_groupings.rs index 02565198e4d2a..57f5fc903956d 100644 --- a/src/tools/clippy/clippy_lints/src/suspicious_operation_groupings.rs +++ b/src/tools/clippy/clippy_lints/src/suspicious_operation_groupings.rs @@ -539,7 +539,7 @@ fn ident_difference_expr_with_base_location( // then we should be able to change this function to do the correct traversal, // without needing to change the rest of the code. - #![allow(clippy::enum_glob_use)] + #[allow(clippy::enum_glob_use)] use ExprKind::*; match ( diff --git a/src/tools/clippy/clippy_lints/src/suspicious_xor_used_as_pow.rs b/src/tools/clippy/clippy_lints/src/suspicious_xor_used_as_pow.rs index e3d96245289ad..7ef7b1bc1d234 100644 --- a/src/tools/clippy/clippy_lints/src/suspicious_xor_used_as_pow.rs +++ b/src/tools/clippy/clippy_lints/src/suspicious_xor_used_as_pow.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; diff --git a/src/tools/clippy/clippy_lints/src/swap.rs b/src/tools/clippy/clippy_lints/src/swap.rs index 871c59d52659e..7abf789089852 100644 --- a/src/tools/clippy/clippy_lints/src/swap.rs +++ b/src/tools/clippy/clippy_lints/src/swap.rs @@ -1,17 +1,17 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::{snippet_indent, snippet_with_context}; use clippy_utils::sugg::Sugg; use clippy_utils::{can_mut_borrow_both, eq_expr_value, is_in_const_context, std_or_core, sym}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_data_structures::fx::FxIndexSet; use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_errors::Applicability; use rustc_hir::{AssignOpKind, Block, Expr, ExprKind, LetStmt, PatKind, QPath, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty; use rustc_session::declare_lint_pass; use rustc_span::symbol::Ident; diff --git a/src/tools/clippy/clippy_lints/src/swap_ptr_to_ref.rs b/src/tools/clippy/clippy_lints/src/swap_ptr_to_ref.rs index 4d7bb2cc1f988..e1b5e57432a76 100644 --- a/src/tools/clippy/clippy_lints/src/swap_ptr_to_ref.rs +++ b/src/tools/clippy/clippy_lints/src/swap_ptr_to_ref.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_with_context; use rustc_errors::Applicability; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, UnOp}; diff --git a/src/tools/clippy/clippy_lints/src/tabs_in_doc_comments.rs b/src/tools/clippy/clippy_lints/src/tabs_in_doc_comments.rs index af9e13dba36ec..4b928f33be67a 100644 --- a/src/tools/clippy/clippy_lints/src/tabs_in_doc_comments.rs +++ b/src/tools/clippy/clippy_lints/src/tabs_in_doc_comments.rs @@ -1,3 +1,5 @@ +use std::iter; + use clippy_utils::diagnostics::span_lint_and_sugg; use rustc_ast::ast; use rustc_errors::Applicability; @@ -94,57 +96,30 @@ impl EarlyLintPass for TabsInDocComments { /// /// scans the string for groups of tabs and returns the start(inclusive) and end positions /// (exclusive) of all groups -/// e.g. "sd\tasd\t\taa" will be converted to [(2, 3), (6, 8)] as +/// e.g. "sd\tasd\t\taa" will yield [(2, 3), (6, 8)] as /// 012 3456 7 89 /// ^-^ ^---^ -fn get_chunks_of_tabs(the_str: &str) -> Vec<(u32, u32)> { +fn get_chunks_of_tabs(the_str: &str) -> impl Iterator { let line_length_way_to_long = "doc comment longer than 2^32 chars"; - let mut spans: Vec<(u32, u32)> = vec![]; - let mut current_start: u32 = 0; - - // tracker to decide if the last group of tabs is not closed by a non-tab character - let mut is_active = false; - - // Note that we specifically need the char _byte_ indices here, not the positional indexes - // within the char array to deal with multi-byte characters properly. `char_indices` does - // exactly that. It provides an iterator over tuples of the form `(byte position, char)`. - let char_indices: Vec<_> = the_str.char_indices().collect(); - - if let [(_, '\t')] = char_indices.as_slice() { - return vec![(0, 1)]; - } - - for entry in char_indices.windows(2) { - match entry { - [(_, '\t'), (_, '\t')] => { - // either string starts with double tab, then we have to set it active, - // otherwise is_active is true anyway - is_active = true; - }, - [(_, _), (index_b, '\t')] => { - // as ['\t', '\t'] is excluded, this has to be a start of a tab group, - // set indices accordingly - is_active = true; - current_start = u32::try_from(*index_b).unwrap(); - }, - [(_, '\t'), (index_b, _)] => { - // this now has to be an end of the group, hence we have to push a new tuple - is_active = false; - spans.push((current_start, u32::try_from(*index_b).unwrap())); - }, - _ => {}, + let mut haystack = the_str.as_bytes(); + let mut offset = 0; + + iter::from_fn(move || { + if let Some(i) = memchr::memchr(b'\t', haystack) { + let len = 1 + haystack[i + 1..].iter().take_while(|&&x| x == b'\t').count(); + let start = offset + i; + let end = start + len; + haystack = &haystack[i + len..]; + offset = end; + Some(( + u32::try_from(start).expect(line_length_way_to_long), + u32::try_from(end).expect(line_length_way_to_long), + )) + } else { + haystack = &[]; + None } - } - - // only possible when tabs are at the end, insert last group - if is_active { - spans.push(( - current_start, - u32::try_from(char_indices.last().unwrap().0 + 1).expect(line_length_way_to_long), - )); - } - - spans + }) } #[cfg(test)] @@ -153,77 +128,77 @@ mod tests_for_get_chunks_of_tabs { #[test] fn test_unicode_han_string() { - let res = get_chunks_of_tabs(" \u{4f4d}\t"); + let res: Vec<_> = get_chunks_of_tabs(" \u{4f4d}\t").collect(); assert_eq!(res, vec![(4, 5)]); } #[test] fn test_empty_string() { - let res = get_chunks_of_tabs(""); + let res: Vec<_> = get_chunks_of_tabs("").collect(); assert_eq!(res, vec![]); } #[test] fn test_simple() { - let res = get_chunks_of_tabs("sd\t\t\taa"); + let res: Vec<_> = get_chunks_of_tabs("sd\t\t\taa").collect(); assert_eq!(res, vec![(2, 5)]); } #[test] fn test_only_t() { - let res = get_chunks_of_tabs("\t\t"); + let res: Vec<_> = get_chunks_of_tabs("\t\t").collect(); assert_eq!(res, vec![(0, 2)]); } #[test] fn test_only_one_t() { - let res = get_chunks_of_tabs("\t"); + let res: Vec<_> = get_chunks_of_tabs("\t").collect(); assert_eq!(res, vec![(0, 1)]); } #[test] fn test_double() { - let res = get_chunks_of_tabs("sd\tasd\t\taa"); + let res: Vec<_> = get_chunks_of_tabs("sd\tasd\t\taa").collect(); assert_eq!(res, vec![(2, 3), (6, 8)]); } #[test] fn test_start() { - let res = get_chunks_of_tabs("\t\taa"); + let res: Vec<_> = get_chunks_of_tabs("\t\taa").collect(); assert_eq!(res, vec![(0, 2)]); } #[test] fn test_end() { - let res = get_chunks_of_tabs("aa\t\t"); + let res: Vec<_> = get_chunks_of_tabs("aa\t\t").collect(); assert_eq!(res, vec![(2, 4)]); } #[test] fn test_start_single() { - let res = get_chunks_of_tabs("\taa"); + let res: Vec<_> = get_chunks_of_tabs("\taa").collect(); assert_eq!(res, vec![(0, 1)]); } #[test] fn test_end_single() { - let res = get_chunks_of_tabs("aa\t"); + let res: Vec<_> = get_chunks_of_tabs("aa\t").collect(); assert_eq!(res, vec![(2, 3)]); } #[test] fn test_no_tabs() { - let res = get_chunks_of_tabs("dsfs"); + let res: Vec<_> = get_chunks_of_tabs("dsfs").collect(); assert_eq!(res, vec![]); } diff --git a/src/tools/clippy/clippy_lints/src/tests_outside_test_module.rs b/src/tools/clippy/clippy_lints/src/tests_outside_test_module.rs index 3cd4fefffadf3..229b14ce41123 100644 --- a/src/tools/clippy/clippy_lints/src/tests_outside_test_module.rs +++ b/src/tools/clippy/clippy_lints/src/tests_outside_test_module.rs @@ -66,9 +66,9 @@ impl LateLintPass<'_> for TestsOutsideTestModule { cx, TESTS_OUTSIDE_TEST_MODULE, sp, - "this function marked with #[test] is outside a #[cfg(test)] module", + "this function marked with `#[test]` is outside a `#[cfg(test)]` module", |diag| { - diag.note("move it to a testing module marked with #[cfg(test)]"); + diag.note("move it to a testing module marked with `#[cfg(test)]`"); }, ); } diff --git a/src/tools/clippy/clippy_lints/src/time_subtraction.rs b/src/tools/clippy/clippy_lints/src/time_subtraction.rs index e906ee081346f..163abd3a630b0 100644 --- a/src/tools/clippy/clippy_lints/src/time_subtraction.rs +++ b/src/tools/clippy/clippy_lints/src/time_subtraction.rs @@ -4,7 +4,7 @@ use clippy_config::Conf; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_sugg, span_lint_and_then}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::sugg::Sugg; use clippy_utils::sym; use rustc_errors::Applicability; @@ -84,7 +84,7 @@ pub struct UncheckedTimeSubtraction { impl UncheckedTimeSubtraction { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs b/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs index 71c4172c98528..0a96a123c9597 100644 --- a/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs +++ b/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs @@ -1,7 +1,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{is_in_const_context, sym}; use rustc_errors::Applicability; @@ -43,7 +43,7 @@ pub(crate) struct ToDigitIsSome { impl ToDigitIsSome { pub(crate) fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/trait_bounds.rs b/src/tools/clippy/clippy_lints/src/trait_bounds.rs index 16cf0ecbc0bc7..73d9849b6d8b7 100644 --- a/src/tools/clippy/clippy_lints/src/trait_bounds.rs +++ b/src/tools/clippy/clippy_lints/src/trait_bounds.rs @@ -1,10 +1,10 @@ use clippy_config::Conf; use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg}; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::source::{SpanExt, snippet, snippet_with_applicability}; +use clippy_utils::source::{SpanExt as _, snippet, snippet_with_applicability}; use clippy_utils::{SpanlessEq, SpanlessHash, is_from_proc_macro}; use core::hash::{Hash, Hasher}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, IndexEntry}; use rustc_data_structures::unhash::UnhashMap; use rustc_errors::Applicability; @@ -100,7 +100,7 @@ impl TraitBounds { pub fn new(conf: &'static Conf) -> Self { Self { max_trait_bounds: conf.max_trait_bounds, - msrv: conf.msrv, + msrv: conf.msrv.into(), } } } diff --git a/src/tools/clippy/clippy_lints/src/transmute/mod.rs b/src/tools/clippy/clippy_lints/src/transmute/mod.rs index 4a150ba098e4b..77e9558dee426 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/mod.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/mod.rs @@ -493,7 +493,7 @@ pub struct Transmute { } impl Transmute { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } /// When transmuting, a struct containing a single field works like the field. diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_null_to_fn.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_null_to_fn.rs index e109b1c50e227..427e832913310 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_null_to_fn.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_null_to_fn.rs @@ -1,7 +1,7 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_integer_literal; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; use rustc_middle::ty::Ty; diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs index 036b16e3dc3d6..ff0f0218083ec 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ptr.rs @@ -5,7 +5,7 @@ use clippy_utils::sugg; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, Ty, TypeVisitableExt as _}; /// Checks for `transmute_ptr_to_ptr` lint. /// Returns `true` if it's triggered, otherwise returns `false`. diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs index ba107eed6b140..1edd7f8baea96 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs @@ -6,7 +6,7 @@ use clippy_utils::sugg; use rustc_errors::Applicability; use rustc_hir::{self as hir, Expr, GenericArg, Mutability, Path, TyKind}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, Ty, TypeVisitableExt as _}; /// Checks for `transmute_ptr_to_ref` lint. /// Returns `true` if it's triggered, otherwise returns `false`. diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmuting_null.rs b/src/tools/clippy/clippy_lints/src/transmute/transmuting_null.rs index c85a3155da8f7..55089fbf1bcac 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmuting_null.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmuting_null.rs @@ -1,6 +1,6 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant, FullInt, eval_int}; use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::sym; use rustc_hir::{ConstBlock, Expr, ExprKind}; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs b/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs index b898920baefc2..98be39522f3f3 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/useless_transmute.rs @@ -4,7 +4,7 @@ use clippy_utils::sugg; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, Ty, TypeVisitableExt as _}; /// Checks for `useless_transmute` lint. /// Returns `true` if it's triggered, otherwise returns `false`. diff --git a/src/tools/clippy/clippy_lints/src/tuple_array_conversions.rs b/src/tools/clippy/clippy_lints/src/tuple_array_conversions.rs index c12cb3846a540..f496082302fbc 100644 --- a/src/tools/clippy/clippy_lints/src/tuple_array_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/tuple_array_conversions.rs @@ -2,7 +2,7 @@ use arrayvec::ArrayVec; use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::visitors::{Visitable, for_each_expr}; use clippy_utils::{SpanlessEq, is_from_proc_macro}; use core::ops::ControlFlow::{Break, Continue}; @@ -53,7 +53,7 @@ pub struct TupleArrayConversions { } impl TupleArrayConversions { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/types/box_collection.rs b/src/tools/clippy/clippy_lints/src/types/box_collection.rs index b3fea7b5a32ac..246a54dd487dd 100644 --- a/src/tools/clippy/clippy_lints/src/types/box_collection.rs +++ b/src/tools/clippy/clippy_lints/src/types/box_collection.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::{qpath_generic_tys, sym}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, QPath}; diff --git a/src/tools/clippy/clippy_lints/src/types/option_option.rs b/src/tools/clippy/clippy_lints/src/types/option_option.rs index 6d57bb6ef3a0d..dbf7b475d110d 100644 --- a/src/tools/clippy/clippy_lints/src/types/option_option.rs +++ b/src/tools/clippy/clippy_lints/src/types/option_option.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::qpath_generic_tys; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, QPath}; diff --git a/src/tools/clippy/clippy_lints/src/types/owned_cow.rs b/src/tools/clippy/clippy_lints/src/types/owned_cow.rs index 0b8389b72c356..85a49253320eb 100644 --- a/src/tools/clippy/clippy_lints/src/types/owned_cow.rs +++ b/src/tools/clippy/clippy_lints/src/types/owned_cow.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet_opt; use clippy_utils::sym; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs b/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs index 81061ce1178b9..f056c56be5b3e 100644 --- a/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs +++ b/src/tools/clippy/clippy_lints/src/types/rc_buffer.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{qpath_generic_tys, sym}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/types/rc_mutex.rs b/src/tools/clippy/clippy_lints/src/types/rc_mutex.rs index e3d536822d5f8..43194aa448560 100644 --- a/src/tools/clippy/clippy_lints/src/types/rc_mutex.rs +++ b/src/tools/clippy/clippy_lints/src/types/rc_mutex.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::qpath_generic_tys; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, QPath}; use rustc_lint::LateContext; diff --git a/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs index dbae2cc335165..7de6cf69d02d3 100644 --- a/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs +++ b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs @@ -1,13 +1,13 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::qpath_generic_tys; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::{snippet, snippet_with_applicability}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, QPath, TyKind}; use rustc_hir_analysis::lower_ty; use rustc_lint::LateContext; -use rustc_middle::ty::TypeVisitableExt; +use rustc_middle::ty::TypeVisitableExt as _; use rustc_span::symbol::sym; use super::{REDUNDANT_ALLOCATION, utils}; diff --git a/src/tools/clippy/clippy_lints/src/types/type_complexity.rs b/src/tools/clippy/clippy_lints/src/types/type_complexity.rs index 52c6fda80973c..ca2977736e4c4 100644 --- a/src/tools/clippy/clippy_lints/src/types/type_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/types/type_complexity.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint; use rustc_abi::ExternAbi; -use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt, walk_ty}; +use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt as _, walk_ty}; use rustc_hir::{self as hir, AmbigArg, GenericParamKind, TyKind}; use rustc_lint::LateContext; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/types/vec_box.rs b/src/tools/clippy/clippy_lints/src/types/vec_box.rs index f13042a6fa6bf..539fa8505a109 100644 --- a/src/tools/clippy/clippy_lints/src/types/vec_box.rs +++ b/src/tools/clippy/clippy_lints/src/types/vec_box.rs @@ -6,8 +6,8 @@ use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, GenericArg, LangItem, QPath, TyKind}; use rustc_hir_analysis::lower_ty; use rustc_lint::LateContext; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::TypeVisitableExt as _; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_span::symbol::sym; use super::VEC_BOX; diff --git a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs index e63a524ff5dc0..d375758e45e81 100644 --- a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeQPath; +use clippy_utils::res::MaybeQPath as _; use clippy_utils::{expr_or_init, fn_def_id_with_node_args, sym}; use rustc_ast::BinOpKind; use rustc_data_structures::fx::FxHashMap; diff --git a/src/tools/clippy/clippy_lints/src/undocumented_unsafe_blocks.rs b/src/tools/clippy/clippy_lints/src/undocumented_unsafe_blocks.rs index d35139f2f6b9b..273ec4c824b5f 100644 --- a/src/tools/clippy/clippy_lints/src/undocumented_unsafe_blocks.rs +++ b/src/tools/clippy/clippy_lints/src/undocumented_unsafe_blocks.rs @@ -4,16 +4,16 @@ use std::sync::Arc; use clippy_config::Conf; use clippy_utils::consts::const_item_rhs_to_expr; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::is_lint_allowed; use clippy_utils::source::walk_span_to_context; use clippy_utils::visitors::{Descend, for_each_expr}; +use clippy_utils::{higher, is_lint_allowed}; use hir::HirId; use rustc_errors::Applicability; use rustc_hir::{self as hir, Block, BlockCheckMode, FnSig, Impl, ItemKind, Node, UnsafeSource}; use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; -use rustc_span::{BytePos, Pos, RelativeBytePos, Span, SyntaxContext}; +use rustc_span::{BytePos, Pos as _, RelativeBytePos, Span, SyntaxContext}; declare_clippy_lint! { /// ### What it does @@ -172,6 +172,9 @@ impl<'tcx> LateLintPass<'tcx> for UndocumentedUnsafeBlocks { else { return; }; + // Compound assignments are expanded into a safe block, but the safety + // comment apply to the undesugared assignment nevertheless. + let expr = higher::CompoundAssignment::hir(expr).map_or(expr, |c| c.init); if !is_lint_allowed(cx, UNNECESSARY_SAFETY_COMMENT, stmt.hir_id) && !stmt.span.in_external_macro(cx.tcx.sess.source_map()) && let HasSafetyComment::Yes(pos, _) = diff --git a/src/tools/clippy/clippy_lints/src/unicode.rs b/src/tools/clippy/clippy_lints/src/unicode.rs index 0c95c7f4859c8..3128bf1cc9755 100644 --- a/src/tools/clippy/clippy_lints/src/unicode.rs +++ b/src/tools/clippy/clippy_lints/src/unicode.rs @@ -8,7 +8,7 @@ use rustc_hir::{Expr, ExprKind, HirId}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; use rustc_span::Span; -use unicode_normalization::UnicodeNormalization; +use unicode_normalization::UnicodeNormalization as _; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/uninit_vec.rs b/src/tools/clippy/clippy_lints/src/uninit_vec.rs index 9449d44c009e5..4408e40c24788 100644 --- a/src/tools/clippy/clippy_lints/src/uninit_vec.rs +++ b/src/tools/clippy/clippy_lints/src/uninit_vec.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; use clippy_utils::higher::{VecInitKind, get_vec_init_kind}; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::ty::is_uninit_value_valid_for_ty; use clippy_utils::{SpanlessEq, is_integer_literal, is_lint_allowed, peel_hir_expr_while, sym}; use rustc_hir::{Block, Expr, ExprKind, HirId, PatKind, PathSegment, Stmt, StmtKind}; diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 66f5bad854027..49488c9da34a5 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -67,9 +67,7 @@ fn get_projection_pred<'tcx>( ) -> Option> { generics.clauses.iter().find_map(|(clause, _)| { if let ClauseKind::Projection(pred) = clause.kind().skip_binder() { - let projection_pred = cx - .tcx - .instantiate_bound_regions_with_erased(clause.kind().rebind(pred)); + let projection_pred = cx.tcx.instantiate_bound_regions_with_erased(clause.kind().rebind(pred)); if projection_pred.projection_term.args == trait_pred.trait_ref.args { return Some(projection_pred); } diff --git a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs index 8bb6ceb863a37..192cbecb3c46f 100644 --- a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs +++ b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs @@ -8,7 +8,7 @@ use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::{Visitor, walk_body, walk_expr}; use rustc_hir::{Expr, ExprKind, HirId, HirIdSet, LetStmt, MatchSource, Node, PatKind, QPath, TyKind}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs b/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs index b9d6c81a152b3..898af91e0cde2 100644 --- a/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs +++ b/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs @@ -1,7 +1,7 @@ use std::iter; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::{SpanExt, indent_of, reindent_multiline}; +use clippy_utils::source::{SpanExt as _, indent_of, reindent_multiline}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::expr_type_is_certain; use clippy_utils::{is_empty_block, is_expr_default, is_from_proc_macro}; diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_box_returns.rs b/src/tools/clippy/clippy_lints/src/unnecessary_box_returns.rs index 4112e1b6ca63f..fd40c607c50ad 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_box_returns.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_box_returns.rs @@ -4,7 +4,7 @@ use rustc_errors::Applicability; use rustc_hir::def_id::LocalDefId; use rustc_hir::{FnDecl, FnRetTy, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_session::impl_lint_pass; use rustc_span::Symbol; diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_literal_bound.rs b/src/tools/clippy/clippy_lints/src/unnecessary_literal_bound.rs index f3bee954fd57e..2ad86ace56e1b 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_literal_bound.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_literal_bound.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::def::Res; diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_map_on_constructor.rs b/src/tools/clippy/clippy_lints/src/unnecessary_map_on_constructor.rs index 6754c224e7e42..9f6212ebc16cc 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_map_on_constructor.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_map_on_constructor.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_mut_passed.rs b/src/tools/clippy/clippy_lints/src/unnecessary_mut_passed.rs index 43721fa252837..c75801583cd34 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_mut_passed.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_mut_passed.rs @@ -1,13 +1,12 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_errors::Applicability; -use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability}; +use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, intravisit}; +use rustc_hir_pretty::PpAnn; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty}; use rustc_session::declare_lint_pass; use std::iter; -use rustc_hir_pretty::PpAnn; -use rustc_hir::intravisit; declare_clippy_lint! { /// ### What it does @@ -48,19 +47,27 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed { match e.kind { ExprKind::Call(fn_expr, arguments) => { - if let ExprKind::Path(ref path) = fn_expr.kind { + if let ExprKind::Path(ref path) = fn_expr.kind + && arguments.iter().any(is_mut_ref_arg) + { check_arguments( cx, &mut arguments.iter(), cx.typeck_results().expr_ty(fn_expr), #[allow(trivial_casts)] - &rustc_hir_pretty::qpath_to_string(&(&cx.tcx as &dyn intravisit::HirTyCtxt<'_>) as &dyn PpAnn, path), + &|| { + rustc_hir_pretty::qpath_to_string( + &(&cx.tcx as &dyn intravisit::HirTyCtxt<'_>) as &dyn PpAnn, + path, + ) + }, "function", ); } }, ExprKind::MethodCall(path, receiver, arguments, _) - if let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) => + if iter::once(receiver).chain(arguments.iter()).any(is_mut_ref_arg) + && let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) => { let args = cx.typeck_results().node_args(e.hir_id); let method_type = cx.tcx.type_of(def_id).instantiate(cx.tcx, args).skip_norm_wip(); @@ -68,7 +75,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed { cx, &mut iter::once(receiver).chain(arguments.iter()), method_type, - path.ident.as_str(), + &|| path.ident.as_str().to_owned(), "method", ); }, @@ -77,11 +84,16 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed { } } +/// Only `&mut ...` arguments can lint, so the type and path lookups run only after one is found. +fn is_mut_ref_arg(argument: &Expr<'_>) -> bool { + matches!(argument.kind, ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _)) +} + fn check_arguments<'tcx>( cx: &LateContext<'tcx>, arguments: &mut dyn Iterator>, type_definition: Ty<'tcx>, - name: &str, + name: &dyn Fn() -> String, fn_kind: &str, ) { if type_definition.is_fn() { @@ -113,7 +125,7 @@ fn check_arguments<'tcx>( cx, UNNECESSARY_MUT_PASSED, argument.span, - format!("the {fn_kind} `{name}` doesn't need a mutable reference"), + format!("the {fn_kind} `{}` doesn't need a mutable reference", name()), |diag| { diag.span_suggestion_verbose(span_to_remove, "remove this `mut`", String::new(), applicability); }, diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_owned_empty_strings.rs b/src/tools/clippy/clippy_lints/src/unnecessary_owned_empty_strings.rs index 6960c006ab949..de24e7827593c 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_owned_empty_strings.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_owned_empty_strings.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs b/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs index 65a3c2f304af8..2d1df64a22c19 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet; use clippy_utils::ty::is_copy; use clippy_utils::{get_parent_expr, is_mutable}; diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index cecffaae69704..39b17e58b8e2a 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeQPath}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _}; use clippy_utils::source::snippet; use clippy_utils::visitors::find_all_ret_expressions; use clippy_utils::{contains_return, return_ty}; diff --git a/src/tools/clippy/clippy_lints/src/unnested_or_patterns.rs b/src/tools/clippy/clippy_lints/src/unnested_or_patterns.rs index 26b666e58b019..28f5e3b749940 100644 --- a/src/tools/clippy/clippy_lints/src/unnested_or_patterns.rs +++ b/src/tools/clippy/clippy_lints/src/unnested_or_patterns.rs @@ -1,4 +1,4 @@ -#![allow(clippy::wildcard_imports, clippy::enum_glob_use)] +#![allow(clippy::enum_glob_use, clippy::wildcard_imports)] use clippy_config::Conf; use clippy_utils::ast_utils::{eq_field_pat, eq_id, eq_maybe_qself, eq_pat, eq_path}; @@ -56,9 +56,7 @@ pub struct UnnestedOrPatterns { impl UnnestedOrPatterns { pub fn new(conf: &'static Conf) -> Self { - Self { - msrv: MsrvStack::new(conf.msrv), - } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs index ffce03cb5dbea..3a9aa8e5788e2 100644 --- a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs +++ b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::macros::{is_panic, root_macro_call_first_node}; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::{paths, peel_blocks, sym}; use hir::{ExprKind, HirId, PatKind}; use rustc_hir as hir; diff --git a/src/tools/clippy/clippy_lints/src/unused_peekable.rs b/src/tools/clippy/clippy_lints/src/unused_peekable.rs index 668663e4cf794..f8827b916635a 100644 --- a/src/tools/clippy/clippy_lints/src/unused_peekable.rs +++ b/src/tools/clippy/clippy_lints/src/unused_peekable.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::ty::peel_and_count_ty_refs; use clippy_utils::{fn_def_id, peel_ref_operators, sym}; use rustc_ast::Mutability; diff --git a/src/tools/clippy/clippy_lints/src/unused_result_ok.rs b/src/tools/clippy/clippy_lints/src/unused_result_ok.rs index c1dc64e0bbe8d..f33cd7f82ce4e 100644 --- a/src/tools/clippy/clippy_lints/src/unused_result_ok.rs +++ b/src/tools/clippy/clippy_lints/src/unused_result_ok.rs @@ -1,10 +1,10 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::source::snippet_with_context; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir::{ExprKind, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/unused_trait_names.rs b/src/tools/clippy/clippy_lints/src/unused_trait_names.rs index e09018284434f..8f6bacdd70ec3 100644 --- a/src/tools/clippy/clippy_lints/src/unused_trait_names.rs +++ b/src/tools/clippy/clippy_lints/src/unused_trait_names.rs @@ -53,7 +53,7 @@ pub struct UnusedTraitNames { impl UnusedTraitNames { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } diff --git a/src/tools/clippy/clippy_lints/src/unused_unit.rs b/src/tools/clippy/clippy_lints/src/unused_unit.rs index bb2ad9f92157c..c84a24a28e939 100644 --- a/src/tools/clippy/clippy_lints/src/unused_unit.rs +++ b/src/tools/clippy/clippy_lints/src/unused_unit.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::source::{SpanExt, position_before_rarrow}; +use clippy_utils::source::{SpanExt as _, position_before_rarrow}; use clippy_utils::{is_never_expr, is_unit_expr}; use rustc_ast::{Block, StmtKind}; use rustc_errors::Applicability; diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index d87289e1362dd..0e8939bc2d28e 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -4,7 +4,7 @@ use std::iter; use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::msrvs::Msrv; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::source::snippet; use clippy_utils::usage::is_potentially_local_place; use clippy_utils::{can_use_if_let_chains, higher, sym}; @@ -13,7 +13,7 @@ use rustc_errors::Applicability; use rustc_hir::intravisit::{FnKind, Visitor, walk_expr, walk_fn}; use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, Node, UnOp}; use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, Place, PlaceWithHirId}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::hir::nested_filter; use rustc_middle::hir::place::ProjectionKind; use rustc_middle::mir::FakeReadCause; @@ -88,7 +88,7 @@ pub(crate) struct Unwrap { impl Unwrap { pub fn new(conf: &'static Conf) -> Self { - Self { msrv: conf.msrv } + Self { msrv: conf.msrv.into() } } } @@ -428,11 +428,6 @@ impl<'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'_, 'tcx> { type NestedFilter = nested_filter::OnlyBodies; fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { - // Shouldn't lint when `expr` is in macro. - if expr.span.in_external_macro(self.cx.tcx.sess.source_map()) { - walk_expr(self, expr); - return; - } // Skip checking inside closures since they are visited through `Unwrap::check_fn()` already. if matches!(expr.kind, ExprKind::Closure(_)) { return; @@ -455,6 +450,7 @@ impl<'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'_, 'tcx> { && let span_ctxt = expr.span.ctxt() && unwrappable.branch.span.ctxt() == span_ctxt && unwrappable.check.span.ctxt() == span_ctxt + && !expr.span.in_external_macro(self.cx.tcx.sess.source_map()) { if call_to_unwrap == unwrappable.safe_to_unwrap { let unwrappable_variable_str = unwrappable.local.snippet(self.cx); diff --git a/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs b/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs index 15dc40af947ef..d1df36911b896 100644 --- a/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs +++ b/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use core::mem::replace; use rustc_errors::Applicability; use rustc_hir::{HirId, Item, ItemKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::symbol::Ident; diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 93d0870a30a21..c9340c2a0e615 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -7,7 +7,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::LocalDefId; -use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt, walk_ty}; +use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt as _, walk_ty}; use rustc_hir::{ self as hir, AmbigArg, Expr, ExprKind, FnRetTy, FnSig, GenericArgsParentheses, GenericParamKind, HirId, Impl, ImplItemImplKind, ImplItemKind, Item, ItemKind, Node, Pat, PatExpr, PatExprKind, PatKind, Path, QPath, Ty, TyKind, @@ -67,7 +67,7 @@ pub struct UseSelf { impl UseSelf { pub fn new(conf: &'static Conf) -> Self { Self { - msrv: conf.msrv, + msrv: conf.msrv.into(), stack: Vec::new(), recursive_self_in_type_definitions: conf.recursive_self_in_type_definitions, } diff --git a/src/tools/clippy/clippy_lints/src/useless_conversion.rs b/src/tools/clippy/clippy_lints/src/useless_conversion.rs index e2dd0a8d2f3dd..9226d3bcbf329 100644 --- a/src/tools/clippy/clippy_lints/src/useless_conversion.rs +++ b/src/tools/clippy/clippy_lints/src/useless_conversion.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::res::{MaybeDef, MaybeQPath, MaybeResPath, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeQPath as _, MaybeResPath as _, MaybeTypeckRes as _}; use clippy_utils::source::{snippet, snippet_with_context}; use clippy_utils::sugg::{DiagExt as _, Sugg}; use clippy_utils::ty::{is_copy, same_type_modulo_regions}; @@ -7,15 +7,15 @@ use clippy_utils::{get_parent_expr, is_ty_alias, sym}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{BindingMode, Expr, ExprKind, HirId, LangItem, MatchSource, Mutability, Node, PatKind}; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_infer::traits::Obligation; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::adjustment::{Adjust, AutoBorrow, AutoBorrowMutability}; -use rustc_middle::ty::{self, EarlyBinder, GenericArg, GenericArgsRef, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, EarlyBinder, GenericArg, GenericArgsRef, Ty, TypeVisitableExt as _}; use rustc_session::impl_lint_pass; use rustc_span::Span; -use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; +use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/useless_vec.rs b/src/tools/clippy/clippy_lints/src/useless_vec.rs index cdb757ed89e23..f1a3881be2fee 100644 --- a/src/tools/clippy/clippy_lints/src/useless_vec.rs +++ b/src/tools/clippy/clippy_lints/src/useless_vec.rs @@ -7,7 +7,7 @@ use clippy_config::Conf; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::ty::is_copy; use clippy_utils::visitors::for_each_local_use_after_expr; use clippy_utils::{VEC_METHODS_SHADOWING_SLICE_METHODS, get_parent_expr, higher, is_in_test, span_contains_comment}; @@ -15,7 +15,7 @@ use rustc_errors::Applicability; use rustc_hir::{BorrowKind, Expr, ExprKind, HirId, LetStmt, Mutability, Node, Pat, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::LayoutOf as _; use rustc_session::impl_lint_pass; use rustc_span::{DesugaringKind, Span}; @@ -50,7 +50,7 @@ impl UselessVec { pub fn new(conf: &'static Conf) -> Self { Self { too_large_for_stack: conf.too_large_for_stack, - msrv: conf.msrv, + msrv: conf.msrv.into(), span_to_state: BTreeMap::new(), allow_in_test: conf.allow_useless_vec_in_tests, } diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index 2bcf369fb3334..f82edb813d88c 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -1,6 +1,6 @@ use clippy_utils::res::MaybeQPath; use clippy_utils::{get_builtin_attr, higher, sym}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_ast::LitIntType; use rustc_ast::ast::{LitFloatType, LitKind}; use rustc_data_structures::fx::FxHashMap; diff --git a/src/tools/clippy/clippy_lints/src/utils/format_args_collector.rs b/src/tools/clippy/clippy_lints/src/utils/format_args_collector.rs index 6401b48f70b05..3cc06f40c2363 100644 --- a/src/tools/clippy/clippy_lints/src/utils/format_args_collector.rs +++ b/src/tools/clippy/clippy_lints/src/utils/format_args_collector.rs @@ -1,9 +1,9 @@ use clippy_utils::macros::FormatArgsStorage; -use clippy_utils::source::{SpanExt, walk_span_to_context}; +use clippy_utils::source::{SpanExt as _, walk_span_to_context}; use rustc_ast::{Crate, Expr, ExprKind, FormatArgs}; use rustc_data_structures::fx::FxHashMap; use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::source_map::SourceMap; use rustc_span::{Span, SpanData}; diff --git a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 414dc55b61ba8..18c9499b26f3b 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher::{VecInitKind, get_vec_init_kind}; -use clippy_utils::res::MaybeResPath; +use clippy_utils::res::MaybeResPath as _; use clippy_utils::source::snippet; use clippy_utils::visitors::for_each_local_use_after_expr; use clippy_utils::{get_parent_expr, sym}; @@ -8,7 +8,7 @@ use core::ops::ControlFlow; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, LetStmt, Mutability, PatKind, QPath, Stmt, StmtKind, UnOp}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; use rustc_span::{Span, Symbol}; diff --git a/src/tools/clippy/clippy_lints/src/visibility.rs b/src/tools/clippy/clippy_lints/src/visibility.rs index 9cefc54598b78..d1051b4498ccc 100644 --- a/src/tools/clippy/clippy_lints/src/visibility.rs +++ b/src/tools/clippy/clippy_lints/src/visibility.rs @@ -1,8 +1,8 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use rustc_ast::ast::{Item, VisibilityKind}; use rustc_errors::Applicability; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::declare_lint_pass; use rustc_span::Span; use rustc_span::symbol::kw; @@ -85,8 +85,8 @@ declare_lint_pass!(Visibility => [ impl EarlyLintPass for Visibility { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { - if !item.span.in_external_macro(cx.sess().source_map()) - && let VisibilityKind::Restricted { path, shorthand, .. } = &item.vis.kind + if let VisibilityKind::Restricted { path, shorthand, .. } = &item.vis.kind + && !item.span.in_external_macro(cx.sess().source_map()) { if **path == kw::SelfLower && !is_from_proc_macro(cx, item.vis.span) { span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/volatile_composites.rs b/src/tools/clippy/clippy_lints/src/volatile_composites.rs index 45177c7a86be6..e7eeade451724 100644 --- a/src/tools/clippy/clippy_lints/src/volatile_composites.rs +++ b/src/tools/clippy/clippy_lints/src/volatile_composites.rs @@ -1,10 +1,10 @@ use clippy_utils::diagnostics::span_lint; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{self, Ty, TypeVisitableExt}; +use rustc_middle::ty::layout::LayoutOf as _; +use rustc_middle::ty::{self, Ty, TypeVisitableExt as _}; use rustc_session::declare_lint_pass; declare_clippy_lint! { diff --git a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs index 19ab3789232cd..57a2c1e667cb7 100644 --- a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs +++ b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs @@ -6,7 +6,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{Item, ItemKind, PathSegment, UseKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty; use rustc_session::impl_lint_pass; use rustc_span::BytePos; @@ -104,14 +104,14 @@ impl_lint_pass!(WildcardImports => [ENUM_GLOB_USE, WILDCARD_IMPORTS]); pub struct WildcardImports { warn_on_all: bool, - allowed_segments: FxHashSet, + allowed_segments: &'static FxHashSet, } impl WildcardImports { pub fn new(conf: &'static Conf) -> Self { Self { warn_on_all: conf.warn_on_all_wildcard_imports, - allowed_segments: conf.allowed_wildcard_imports.iter().cloned().collect(), + allowed_segments: &conf.allowed_wildcard_imports, } } } @@ -123,9 +123,7 @@ impl LateLintPass<'_> for WildcardImports { } let module = cx.tcx.parent_module_from_def_id(item.owner_id.def_id); - if cx.tcx.local_visibility(item.owner_id.def_id) != ty::Visibility::Restricted(module) - && !self.warn_on_all - { + if cx.tcx.local_visibility(item.owner_id.def_id) != ty::Visibility::Restricted(module) && !self.warn_on_all { return; } if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind @@ -185,7 +183,7 @@ impl WildcardImports { fn check_exceptions(&self, cx: &LateContext<'_>, item: &Item<'_>, segments: &[PathSegment<'_>]) -> bool { item.span.from_expansion() || is_prelude_import(segments) - || is_allowed_via_config(segments, &self.allowed_segments) + || is_allowed_via_config(segments, self.allowed_segments) || (is_super_only_import(segments) && is_in_test(cx.tcx, item.hir_id())) } } diff --git a/src/tools/clippy/clippy_lints/src/with_capacity_zero.rs b/src/tools/clippy/clippy_lints/src/with_capacity_zero.rs index 26c09c9dc3a6b..62ab50bcde394 100644 --- a/src/tools/clippy/clippy_lints/src/with_capacity_zero.rs +++ b/src/tools/clippy/clippy_lints/src/with_capacity_zero.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::{fn_def_id, is_integer_literal, last_path_segment, span_contains_comment, sym}; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, LangItem}; diff --git a/src/tools/clippy/clippy_lints/src/write/empty_string.rs b/src/tools/clippy/clippy_lints/src/write/empty_string.rs index 31869e0d2cda9..21dae7f256076 100644 --- a/src/tools/clippy/clippy_lints/src/write/empty_string.rs +++ b/src/tools/clippy/clippy_lints/src/write/empty_string.rs @@ -4,7 +4,7 @@ use clippy_utils::source::{expand_past_previous_comma, snippet_opt}; use clippy_utils::{span_extract_comments, sym}; use rustc_ast::{FormatArgs, FormatArgsPiece}; use rustc_errors::Applicability; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use super::{PRINTLN_EMPTY_STRING, WRITELN_EMPTY_STRING}; diff --git a/src/tools/clippy/clippy_lints/src/write/literal.rs b/src/tools/clippy/clippy_lints/src/write/literal.rs index df31fad8615ed..48e275640804c 100644 --- a/src/tools/clippy/clippy_lints/src/write/literal.rs +++ b/src/tools/clippy/clippy_lints/src/write/literal.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::format_arg_removal_span; -use clippy_utils::source::SpanExt; +use clippy_utils::source::SpanExt as _; use clippy_utils::sym; use rustc_ast::token::LitKind; use rustc_ast::{ diff --git a/src/tools/clippy/clippy_lints/src/write/mod.rs b/src/tools/clippy/clippy_lints/src/write/mod.rs index 8d896046200b4..9937d1e0cad20 100644 --- a/src/tools/clippy/clippy_lints/src/write/mod.rs +++ b/src/tools/clippy/clippy_lints/src/write/mod.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::macros::{FormatArgsStorage, root_macro_call_first_node}; use clippy_utils::{is_in_test, sym}; use rustc_hir::{Expr, Impl, Item, ItemKind, OwnerId}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_session::impl_lint_pass; mod empty_string; diff --git a/src/tools/clippy/clippy_lints/src/write/with_newline.rs b/src/tools/clippy/clippy_lints/src/write/with_newline.rs index 15cc29818aec4..14e6e496f2cf4 100644 --- a/src/tools/clippy/clippy_lints/src/write/with_newline.rs +++ b/src/tools/clippy/clippy_lints/src/write/with_newline.rs @@ -1,10 +1,10 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::MacroCall; -use clippy_utils::source::{SpanExt, expand_past_previous_comma}; +use clippy_utils::source::{SpanExt as _, expand_past_previous_comma}; use clippy_utils::sym; use rustc_ast::{FormatArgs, FormatArgsPiece}; use rustc_errors::Applicability; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_span::BytePos; use super::{PRINT_WITH_NEWLINE, WRITE_WITH_NEWLINE}; diff --git a/src/tools/clippy/clippy_lints/src/zero_repeat_side_effects.rs b/src/tools/clippy/clippy_lints/src/zero_repeat_side_effects.rs index cb254cc156296..c1a7013827208 100644 --- a/src/tools/clippy/clippy_lints/src/zero_repeat_side_effects.rs +++ b/src/tools/clippy/clippy_lints/src/zero_repeat_side_effects.rs @@ -6,7 +6,7 @@ use rustc_data_structures::packed::Pu128; use rustc_errors::Applicability; use rustc_hir::{ConstArgKind, Expr, ExprKind, LetStmt, LocalSource, Node}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::{IsSuggestable, Ty}; +use rustc_middle::ty::{IsSuggestable as _, Ty}; use rustc_session::declare_lint_pass; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs index 94c2fb20d5f5c..bfbb6cc851296 100644 --- a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs +++ b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs @@ -1,10 +1,10 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::res::MaybeDef; +use clippy_utils::res::MaybeDef as _; use clippy_utils::ty::ty_from_hir_ty; use rustc_hir::{self as hir, AmbigArg, HirId, ItemKind, Node}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::layout::LayoutOf as _; -use rustc_middle::ty::{self, TypeVisitableExt}; +use rustc_middle::ty::{self, TypeVisitableExt as _}; use rustc_session::declare_lint_pass; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/zombie_processes.rs b/src/tools/clippy/clippy_lints/src/zombie_processes.rs index df2dcdbb9d067..68023209b34b0 100644 --- a/src/tools/clippy/clippy_lints/src/zombie_processes.rs +++ b/src/tools/clippy/clippy_lints/src/zombie_processes.rs @@ -1,6 +1,6 @@ use ControlFlow::{Break, Continue}; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeResPath}; +use clippy_utils::res::{MaybeDef as _, MaybeResPath as _}; use clippy_utils::{fn_def_id, get_enclosing_block, sym}; use rustc_ast::Mutability; use rustc_ast::visit::visit_opt; diff --git a/src/tools/clippy/clippy_lints_internal/Cargo.toml b/src/tools/clippy/clippy_lints_internal/Cargo.toml index 5498f63f51db8..8c12f0db61b5f 100644 --- a/src/tools/clippy/clippy_lints_internal/Cargo.toml +++ b/src/tools/clippy/clippy_lints_internal/Cargo.toml @@ -8,7 +8,6 @@ clippy_config = { path = "../clippy_config" } clippy_utils = { path = "../clippy_utils" } itertools = "0.15" regex = { version = "1.5" } -rustc-semver = "1.1" [package.metadata.rust-analyzer] # This crate uses #[feature(rustc_private)] diff --git a/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs b/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs index bac05acebf344..77a17110bf81a 100644 --- a/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs +++ b/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs @@ -7,7 +7,7 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{Span, SyntaxContext}; -use std::borrow::{Borrow, Cow}; +use std::borrow::{Borrow as _, Cow}; use crate::internal_paths; diff --git a/src/tools/clippy/clippy_lints_internal/src/lib.rs b/src/tools/clippy/clippy_lints_internal/src/lib.rs index 4931f8765bdd6..cda5d9df3f4b8 100644 --- a/src/tools/clippy/clippy_lints_internal/src/lib.rs +++ b/src/tools/clippy/clippy_lints_internal/src/lib.rs @@ -1,21 +1,18 @@ #![feature(rustc_private)] -#![allow( - clippy::missing_docs_in_private_items, - clippy::must_use_candidate, +#![expect( + clippy::missing_clippy_version_attribute, // None of these lints need a version. clippy::symbol_as_str )] #![warn( + rust_2018_idioms, trivial_casts, trivial_numeric_casts, - rust_2018_idioms, unused_lifetimes, unused_qualifications, rustc::internal )] // Disable this rustc lint for now, as it was also done in rustc #![allow(rustc::potential_query_instability)] -// None of these lints need a version. -#![allow(clippy::missing_clippy_version_attribute)] extern crate rustc_ast; extern crate rustc_attr_parsing; diff --git a/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs b/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs index 1225f42d56022..52f911b494fbb 100644 --- a/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs +++ b/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs @@ -4,7 +4,7 @@ use clippy_utils::source::snippet; use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir as hir; -use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint::{LateContext, LateLintPass, LintContext as _}; use rustc_middle::ty::{self, GenericArgKind}; use rustc_session::{declare_lint_pass, declare_tool_lint}; diff --git a/src/tools/clippy/clippy_lints_internal/src/produce_ice.rs b/src/tools/clippy/clippy_lints_internal/src/produce_ice.rs index 630843049da25..9beab9568abb5 100644 --- a/src/tools/clippy/clippy_lints_internal/src/produce_ice.rs +++ b/src/tools/clippy/clippy_lints_internal/src/produce_ice.rs @@ -1,6 +1,6 @@ use rustc_ast::ast::NodeId; use rustc_ast::visit::FnKind; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_lint::{EarlyContext, EarlyLintPass, LintContext as _}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints_internal/src/repeated_is_diagnostic_item.rs b/src/tools/clippy/clippy_lints_internal/src/repeated_is_diagnostic_item.rs index e0148c79477c0..a7599ae21350c 100644 --- a/src/tools/clippy/clippy_lints_internal/src/repeated_is_diagnostic_item.rs +++ b/src/tools/clippy/clippy_lints_internal/src/repeated_is_diagnostic_item.rs @@ -3,7 +3,7 @@ use std::ops::ControlFlow; use crate::internal_paths::MAYBE_DEF; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::res::{MaybeDef, MaybeTypeckRes}; +use clippy_utils::res::{MaybeDef as _, MaybeTypeckRes as _}; use clippy_utils::source::{snippet_indent, snippet_with_applicability}; use clippy_utils::visitors::for_each_expr; use clippy_utils::{eq_expr_value, if_sequence, sym}; diff --git a/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs b/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs index f2e8d3579d851..07bbe6aad645d 100644 --- a/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs +++ b/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs @@ -2,7 +2,7 @@ use crate::internal_paths; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::paths::{PathNS, lookup_path}; use clippy_utils::peel_ref_operators; -use clippy_utils::res::MaybeQPath; +use clippy_utils::res::MaybeQPath as _; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs b/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs index b68ebed713fcb..4f2dd8cfc8093 100644 --- a/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs +++ b/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::paths::PathLookup; use clippy_utils::sym; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl, Pat, PatKind, Stmt, StmtKind}; diff --git a/src/tools/clippy/clippy_utils/Cargo.toml b/src/tools/clippy/clippy_utils/Cargo.toml index c0beacf57878a..db6108cc9861e 100644 --- a/src/tools/clippy/clippy_utils/Cargo.toml +++ b/src/tools/clippy/clippy_utils/Cargo.toml @@ -14,7 +14,6 @@ arrayvec = { version = "0.7", default-features = false } itertools = "0.15" # FIXME(f16_f128): remove when no longer needed for parsing rustc_apfloat = "0.2.0" -serde = { version = "1.0", features = ["derive"] } [lints.rust.unexpected_cfgs] level = "warn" diff --git a/src/tools/clippy/clippy_utils/README.md b/src/tools/clippy/clippy_utils/README.md index 06e64040888d4..9aa097f8863ec 100644 --- a/src/tools/clippy/clippy_utils/README.md +++ b/src/tools/clippy/clippy_utils/README.md @@ -8,7 +8,7 @@ This crate is only guaranteed to build with this `nightly` toolchain: ``` -nightly-2026-07-09 +nightly-2026-08-07 ``` diff --git a/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs b/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs index 523e799ef2522..504a867335011 100644 --- a/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs @@ -2,7 +2,7 @@ //! //! - The `eq_foobar` functions test for semantic equality but ignores `NodeId`s and `Span`s. -#![allow(clippy::wildcard_imports, clippy::enum_glob_use)] +#![allow(clippy::enum_glob_use, clippy::wildcard_imports)] use crate::{both, over}; use rustc_ast::attr::data_structures::CfgEntry; diff --git a/src/tools/clippy/clippy_utils/src/attrs.rs b/src/tools/clippy/clippy_utils/src/attrs.rs index 7718afc5f0222..9feb723e7a443 100644 --- a/src/tools/clippy/clippy_utils/src/attrs.rs +++ b/src/tools/clippy/clippy_utils/src/attrs.rs @@ -1,6 +1,6 @@ //! Utility functions for attributes, including Clippy's built-in ones -use crate::source::SpanExt; +use crate::source::SpanExt as _; use crate::{sym, tokenize_with_text}; use rustc_ast::attr::AttributeExt; use rustc_errors::Applicability; @@ -10,7 +10,7 @@ use rustc_lint::LateContext; use rustc_middle::ty::{AdtDef, TyCtxt}; use rustc_session::Session; use rustc_span::{Span, Symbol}; -use std::str::FromStr; +use std::str::FromStr as _; /// Validates a single clippy attribute and emits errors for unknown or deprecated ones. pub fn check_clippy_attr(sess: &Session, attr: &A) { diff --git a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs index 412cdd41d0f2c..efdaef24478ba 100644 --- a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs +++ b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs @@ -16,15 +16,16 @@ use rustc_abi::ExternAbi; use rustc_ast as ast; use rustc_ast::AttrStyle; use rustc_ast::ast::{ - AttrKind, Attribute, GenericArgs, IntTy, LitIntType, LitKind, StrStyle, TraitObjectSyntax, UintTy, + AttrKind, Attribute, BindingMode, GenericArgs, IntTy, LitIntType, LitKind, StrStyle, TraitObjectSyntax, UintTy, }; use rustc_ast::token::CommentKind; use rustc_hir::intravisit::FnKind; use rustc_hir::{ Block, BlockCheckMode, Body, BoundConstness, BoundPolarity, Closure, Destination, Expr, ExprKind, FieldDef, FnHeader, FnRetTy, HirId, Impl, ImplItem, ImplItemImplKind, ImplItemKind, IsAuto, Item, ItemKind, Lit, LoopSource, - MatchSource, MutTy, Node, Path, PolyTraitRef, QPath, Safety, TraitBoundModifiers, TraitImplHeader, TraitItem, - TraitItemKind, TraitRef, Ty, TyKind, UnOp, UnsafeSource, Variant, VariantData, YieldSource, + MatchSource, MutTy, Node, PatExpr, PatExprKind, PatKind, Path, PolyTraitRef, QPath, Safety, TraitBoundModifiers, + TraitImplHeader, TraitItem, TraitItemKind, TraitRef, Ty, TyKind, UnOp, UnsafeSource, Variant, VariantData, + YieldSource, }; use rustc_lint::{EarlyContext, LateContext, LintContext}; use rustc_middle::ty::TyCtxt; @@ -591,6 +592,99 @@ fn ident_search_pat(ident: Ident) -> (Pat, Pat) { (Pat::Sym(ident.name), Pat::Sym(ident.name)) } +fn pat_search_pat(tcx: TyCtxt<'_>, pat: &rustc_hir::Pat<'_>) -> (Pat, Pat) { + match pat.kind { + // Tuple patterns cannot show up in proc-macro checks + PatKind::Missing | PatKind::Err(_) | PatKind::Tuple(_, _) => (Pat::Str(""), Pat::Str("")), + PatKind::Wild => (Pat::Sym(kw::Underscore), Pat::Sym(kw::Underscore)), + PatKind::Binding(binding_mode, _, ident, Some(end_pat)) => { + let start = if binding_mode == BindingMode::NONE { + ident_search_pat(ident).0 + } else { + Pat::Str(binding_mode.prefix_str()) + }; + + let (_, end) = pat_search_pat(tcx, end_pat); + (start, end) + }, + PatKind::Binding(binding_mode, _, ident, None) => { + let (s, end) = ident_search_pat(ident); + let start = if binding_mode == BindingMode::NONE { + s + } else { + Pat::Str(binding_mode.prefix_str()) + }; + + (start, end) + }, + PatKind::Struct(path, _, _) => { + let (start, _) = qpath_search_pat(&path); + (start, Pat::Str("}")) + }, + PatKind::TupleStruct(path, _, _) => { + let (start, _) = qpath_search_pat(&path); + // This pattern cannot show up in proc-macro checks + (start, Pat::Str("")) + }, + PatKind::Or(plist) => { + // documented invariant + debug_assert!(plist.len() >= 2); + let (start, _) = pat_search_pat(tcx, plist.first().unwrap()); + let (_, end) = pat_search_pat(tcx, plist.last().unwrap()); + (start, end) + }, + PatKind::Never => (Pat::Str("!"), Pat::Str("")), + PatKind::Box(p) => { + let (_, end) = pat_search_pat(tcx, p); + (Pat::Str("box"), end) + }, + PatKind::Deref(_) => (Pat::Str("deref!"), Pat::Str("")), + PatKind::Ref(p, _, _) => { + let (_, end) = pat_search_pat(tcx, p); + (Pat::Str("&"), end) + }, + PatKind::Expr(expr) => pat_expr_search_pat(expr), + PatKind::Guard(pat, guard) => { + let (start, _) = pat_search_pat(tcx, pat); + let (_, end) = expr_search_pat(tcx, guard); + (start, end) + }, + PatKind::Range(None, None, range) => match range { + rustc_hir::RangeEnd::Included => (Pat::Str("..="), Pat::Str("")), + rustc_hir::RangeEnd::Excluded => (Pat::Str(".."), Pat::Str("")), + }, + PatKind::Range(r_start, r_end, range) => { + let start = match r_start { + Some(e) => pat_expr_search_pat(e).0, + None => match range { + rustc_hir::RangeEnd::Included => Pat::Str("..="), + rustc_hir::RangeEnd::Excluded => Pat::Str(".."), + }, + }; + + let end = match r_end { + Some(e) => pat_expr_search_pat(e).1, + None => match range { + rustc_hir::RangeEnd::Included => Pat::Str("..="), + rustc_hir::RangeEnd::Excluded => Pat::Str(".."), + }, + }; + (start, end) + }, + PatKind::Slice(_, _, _) => (Pat::Str("["), Pat::Str("]")), + } +} + +fn pat_expr_search_pat(expr: &PatExpr<'_>) -> (Pat, Pat) { + match expr.kind { + PatExprKind::Lit { lit, negated } => { + let (start, end) = lit_search_pat(&lit.node); + if negated { (Pat::Str("!"), end) } else { (start, end) } + }, + PatExprKind::Path(path) => qpath_search_pat(&path), + } +} + pub trait WithSearchPat<'cx> { type Context: LintContext; fn search_pat(&self, cx: &Self::Context) -> (Pat, Pat); @@ -620,6 +714,7 @@ impl_with_search_pat!((_cx: LateContext<'tcx>, self: Ident) => ident_search_pat( impl_with_search_pat!((_cx: LateContext<'tcx>, self: Lit) => lit_search_pat(&self.node)); impl_with_search_pat!((_cx: LateContext<'tcx>, self: Path<'_>) => path_search_pat(self)); impl_with_search_pat!((_cx: LateContext<'tcx>, self: PolyTraitRef<'_>) => poly_trait_ref_search_pat(self)); +impl_with_search_pat!((cx: LateContext<'tcx>, self: rustc_hir::Pat<'_>) => pat_search_pat(cx.tcx, self)); impl_with_search_pat!((_cx: EarlyContext<'tcx>, self: Attribute) => attr_search_pat(self)); impl_with_search_pat!((_cx: EarlyContext<'tcx>, self: ast::Ty) => ast_ty_search_pat(self)); diff --git a/src/tools/clippy/clippy_utils/src/consts.rs b/src/tools/clippy/clippy_utils/src/consts.rs index cb04f4373ec4f..bcdc7754da6fa 100644 --- a/src/tools/clippy/clippy_utils/src/consts.rs +++ b/src/tools/clippy/clippy_utils/src/consts.rs @@ -4,12 +4,12 @@ //! executable MIR bodies, so we have to do this instead. #![expect(clippy::float_cmp)] -use crate::res::MaybeDef; -use crate::source::{SpanExt, walk_span_to_context}; +use crate::res::MaybeDef as _; +use crate::source::{SpanExt as _, walk_span_to_context}; use crate::{clip, is_direct_expn_of, sext, sym, unsext}; use rustc_abi::Size; -use rustc_apfloat::Float; +use rustc_apfloat::Float as _; use rustc_apfloat::ieee::{Half, Quad}; use rustc_ast::ast::{LitFloatType, LitKind}; use rustc_hir::def::{DefKind, Res}; diff --git a/src/tools/clippy/clippy_utils/src/higher.rs b/src/tools/clippy/clippy_utils/src/higher.rs index fe0f14d3f95ae..e4f508661dbfb 100644 --- a/src/tools/clippy/clippy_utils/src/higher.rs +++ b/src/tools/clippy/clippy_utils/src/higher.rs @@ -3,12 +3,14 @@ #![deny(clippy::missing_docs_in_private_items)] use crate::consts::{ConstEvalCtxt, Constant}; -use crate::res::MaybeDef; +use crate::res::MaybeDef as _; use crate::{is_expn_of, sym}; use rustc_ast::ast; -use rustc_hir as hir; -use rustc_hir::{Arm, Block, Expr, ExprKind, HirId, LoopSource, MatchSource, Node, Pat, QPath, StructTailExpr}; +use rustc_hir::{ + self as hir, Arm, Block, Expr, ExprKind, HirId, LetStmt, LocalSource, LoopSource, MatchSource, Node, Pat, QPath, + StructTailExpr, +}; use rustc_lint::LateContext; use rustc_span::{Span, symbol}; @@ -491,6 +493,54 @@ impl<'hir> WhileLet<'hir> { } } +/// A desugared compound assignment statement, such as in +/// `(a, b) = expr`. +pub struct CompoundAssignment<'hir> { + /// The individual assignees + pub assignees: Vec<&'hir Expr<'hir>>, + /// The initializatiojn expression + pub init: &'hir Expr<'hir>, +} + +impl<'hir> CompoundAssignment<'hir> { + /// Check if `expr` is a block which is an expansion of a compound assignment. + #[inline] + pub fn hir(expr: &'hir Expr<'_>) -> Option { + // A compound assignment is unsugared into a block which first assigns the RHS subexpressions to + // temporaries, then moves those temporaries to the assignment targets. By doing it this + // way, and since the moves cannot fail, the compound assignment either succeeds or not take + // place at all if, for example, one of the RHS subcomponent diverges. + if let ExprKind::Block( + Block { + stmts: [assign, rest @ ..], + expr: None, + .. + }, + None, + ) = expr.kind + && let hir::StmtKind::Let(LetStmt { + init: Some(init), + source: LocalSource::AssignDesugar, + .. + }) = assign.kind + { + let mut assignees = Vec::with_capacity(rest.len()); + for stmt in rest { + if let hir::StmtKind::Expr(expr) = stmt.kind + && let ExprKind::Assign(target, _, _) = expr.kind + { + assignees.push(target); + } else { + return None; + } + } + Some(CompoundAssignment { assignees, init }) + } else { + None + } + } +} + /// Converts a `hir` binary operator to the corresponding `ast` type. #[must_use] pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind { diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index e9695668d75c1..19388e6cd35dd 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -1,6 +1,6 @@ use crate::consts::ConstEvalCtxt; use crate::macros::macro_backtrace; -use crate::source::{SpanExt, SpanRange, walk_span_to_context}; +use crate::source::{SpanExt as _, SpanRange, walk_span_to_context}; use crate::{sym, tokenize_with_text}; use core::mem; use rustc_ast::ast; @@ -21,7 +21,7 @@ use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; use rustc_lint::LateContext; use rustc_middle::ty::TypeckResults; use rustc_span::{BytePos, ExpnKind, MacroKind, Symbol, SyntaxContext}; -use std::hash::{Hash, Hasher}; +use std::hash::{Hash as _, Hasher as _}; use std::ops::Range; use std::slice; diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 0458dfe4692f8..afaf4160e2c88 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -3,11 +3,11 @@ #![feature(rustc_private)] #![feature(unwrap_infallible)] #![recursion_limit = "512"] -#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate)] +#![expect(clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate)] #![warn( + rust_2018_idioms, trivial_casts, trivial_numeric_casts, - rust_2018_idioms, unused_lifetimes, unused_qualifications, rustc::internal @@ -77,7 +77,7 @@ use std::collections::hash_map::Entry; use std::iter::{once, repeat_n, zip}; use std::sync::{Mutex, OnceLock}; -use itertools::Itertools; +use itertools::Itertools as _; use rustc_abi::Integer; use rustc_ast::ast::{self, LitKind, RangeLimits}; use rustc_ast::{LitIntType, join_path_syms}; @@ -92,37 +92,35 @@ use rustc_hir::def_id::{DefId, LocalDefId, LocalModId}; use rustc_hir::definitions::{DefPath, DefPathData}; use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_hir::{ - self as hir, AnonConst, Arm, BindingMode, Block, BlockCheckMode, Body, ByRef, CRATE_HIR_ID, - Closure, ConstArg, ConstArgKind, CoroutineDesugaring, CoroutineKind, CoroutineSource, - Destination, Expr, ExprField, ExprKind, FieldDef, FnDecl, FnRetTy, GenericArg, GenericArgs, - HirId, HirIdMap, HirIdSet, Impl, ImplItem, ImplItemKind, Item, ItemKind, LangItem, LetStmt, - MatchSource, Mutability, Node, OwnerId, OwnerNode, Param, Pat, PatExpr, PatExprKind, PatKind, - Path, PathSegment, QPath, Stmt, StmtKind, TraitFn, TraitItem, TraitItemKind, TraitRef, TyKind, - UnOp, Variant, def, find_attr, + self as hir, AnonConst, Arm, BindingMode, Block, BlockCheckMode, Body, ByRef, CRATE_HIR_ID, Closure, ConstArg, + ConstArgKind, CoroutineDesugaring, CoroutineKind, CoroutineSource, Destination, Expr, ExprField, ExprKind, + FieldDef, FnDecl, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, HirIdSet, Impl, ImplItem, ImplItemKind, Item, + ItemKind, LangItem, LetStmt, MatchSource, Mutability, Node, OwnerId, OwnerNode, Param, Pat, PatExpr, PatExprKind, + PatKind, Path, PathSegment, QPath, Stmt, StmtKind, TraitFn, TraitItem, TraitItemKind, TraitRef, TyKind, UnOp, + Variant, def, find_attr, }; - use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; -use rustc_lint::{LateContext, Level, Lint, LintContext}; +use rustc_lint::{LateContext, Level, Lint, LintContext as _}; use rustc_middle::hir::nested_filter; use rustc_middle::hir::place::PlaceBase; use rustc_middle::mir::{AggregateKind, Operand, RETURN_PLACE, Rvalue, StatementKind, TerminatorKind}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, DerefAdjustKind, PointerCoercion}; -use rustc_middle::ty::layout::IntegerExt; +use rustc_middle::ty::layout::IntegerExt as _; use rustc_middle::ty::{ self as rustc_ty, Binder, BorrowKind, ClosureKind, EarlyBinder, GenericArgKind, GenericArgsRef, IntTy, Ty, TyCtxt, - TypeFlags, TypeVisitableExt, TypeckResults, UintTy, UpvarCapture, + TypeFlags, TypeVisitableExt as _, TypeckResults, UintTy, UpvarCapture, }; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::SourceMap; use rustc_span::symbol::{Ident, Symbol, kw}; use rustc_span::{InnerSpan, Span, SyntaxContext}; -use source::{SpanExt, walk_span_to_context}; +use source::{SpanExt as _, walk_span_to_context}; use visitors::{Visitable, for_each_unconsumed_temporary}; use crate::ast_utils::unordered_over; use crate::higher::Range; use crate::msrvs::Msrv; -use crate::res::{MaybeDef, MaybeQPath, MaybeResPath}; +use crate::res::{MaybeDef as _, MaybeResPath as _}; use crate::source::HasSourceMap; use crate::ty::{adt_and_variant_of_res, can_partially_move_ty, expr_sig, is_copy, is_recursively_primitive_type}; use crate::visitors::for_each_expr_without_closures; @@ -300,13 +298,13 @@ pub fn is_lang_item_or_ctor(cx: &LateContext<'_>, did: DefId, item: LangItem) -> /// Checks is `expr` is `None` pub fn is_none_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - expr.res(cx).ctor_parent(cx).is_lang_item(cx, OptionNone) + expr.basic_res().ctor_parent(cx).is_lang_item(cx, OptionNone) } /// If `expr` is `Some(inner)`, returns `inner` pub fn as_some_expr<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { if let ExprKind::Call(e, [arg]) = expr.kind - && e.res(cx).ctor_parent(cx).is_lang_item(cx, OptionSome) + && e.basic_res().ctor_parent(cx).is_lang_item(cx, OptionSome) { Some(arg) } else { @@ -2100,7 +2098,7 @@ pub fn fn_has_unsatisfiable_clauses(cx: &LateContext<'_>, did: DefId) -> bool { .clauses_of(did) .clauses .iter() - .filter_map(|(c, _)| if c.is_global() { Some(*c) } else { None }); + .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None }); traits::impossible_clauses(cx.tcx, traits::elaborate(cx.tcx, clauses).collect::>()) } @@ -3417,6 +3415,19 @@ pub fn leaks_droppable_temporary_with_limited_lifetime<'tcx>(cx: &LateContext<'t .is_break() } +/// Returns true if `expr` creates any temporary that has a significant drop and does not consume +/// it. +pub fn leaks_droppable_temporary<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { + for_each_unconsumed_temporary(cx, expr, |temporary_ty| { + if temporary_ty.has_significant_drop(cx.tcx, cx.typing_env()) { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }) + .is_break() +} + /// Returns true if the specified `expr` requires coercion, /// meaning that it either has a coercion or propagates a coercion from one of its sub expressions. /// diff --git a/src/tools/clippy/clippy_utils/src/macros.rs b/src/tools/clippy/clippy_utils/src/macros.rs index 76f9b50ca9f4f..c0b4a62cdb0b7 100644 --- a/src/tools/clippy/clippy_utils/src/macros.rs +++ b/src/tools/clippy/clippy_utils/src/macros.rs @@ -1,4 +1,4 @@ -#![allow(clippy::similar_names)] // `expr` and `expn` +#![expect(clippy::similar_names)] // `expr` and `expn` use std::cell::Cell; use std::sync::{Arc, OnceLock}; @@ -10,7 +10,7 @@ use arrayvec::ArrayVec; use rustc_ast::{FormatArgs, FormatArgument, FormatPlaceholder}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::{self as hir, Expr, ExprKind, HirId, Node, QPath}; -use rustc_lint::{LateContext, LintContext}; +use rustc_lint::{LateContext, LintContext as _}; use rustc_span::def_id::DefId; use rustc_span::hygiene::{self, MacroKind, SyntaxContext}; use rustc_span::{BytePos, ExpnData, ExpnId, ExpnKind, Span, SpanData, Symbol}; diff --git a/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs b/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs index cbd55ce9b4351..dae6661c5ee1a 100644 --- a/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs +++ b/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs @@ -8,7 +8,7 @@ use rustc_middle::mir::visit::Visitor as _; use rustc_middle::mir::{self, Mutability}; use rustc_middle::ty::{self, TyCtxt, TypeVisitor}; use rustc_mir_dataflow::impls::MaybeStorageLive; -use rustc_mir_dataflow::{Analysis, ResultsCursor}; +use rustc_mir_dataflow::{Analysis as _, ResultsCursor}; use std::borrow::Cow; use std::ops::ControlFlow; diff --git a/src/tools/clippy/clippy_utils/src/msrvs.rs b/src/tools/clippy/clippy_utils/src/msrvs.rs index 1e78075009196..48819d53da771 100644 --- a/src/tools/clippy/clippy_utils/src/msrvs.rs +++ b/src/tools/clippy/clippy_utils/src/msrvs.rs @@ -3,14 +3,12 @@ use rustc_ast::Attribute; use rustc_ast::attr::AttributeExt; use rustc_attr_parsing::parse_version; use rustc_data_structures::smallvec::SmallVec; -use rustc_hir::def_id::DefId; use rustc_hir::attrs::RustcVersion; +use rustc_hir::def_id::DefId; use rustc_hir::{HirId, StabilityLevel, StableSince}; use rustc_lint::LateContext; use rustc_middle::ty::TyCtxt; use rustc_session::Session; -use rustc_span::Symbol; -use serde::Deserialize; use std::iter::once; use std::sync::atomic::{AtomicBool, Ordering}; @@ -27,9 +25,11 @@ macro_rules! msrv_aliases { // names may refer to stabilized feature flags or library items msrv_aliases! { 1,97,0 { ISOLATE_LOWEST_ONE, BIT_WIDTH } + 1,94,0 { EULER_GAMMA, GOLDEN_RATIO } 1,93,0 { VEC_DEQUE_POP_BACK_IF, VEC_DEQUE_POP_FRONT_IF } 1,91,0 { DURATION_FROM_MINUTES_HOURS } - 1,88,0 { LET_CHAINS, AS_CHUNKS } + 1,89,0 { NONNULL_FROM_MUT } + 1,88,0 { LET_CHAINS, AS_CHUNKS, RAW_PTR_DEFAULT } 1,87,0 { OS_STR_DISPLAY, INT_MIDPOINT, CONST_CHAR_IS_DIGIT, UNSIGNED_IS_MULTIPLE_OF, INTEGER_SIGN_CAST } 1,86,0 { VEC_POP_IF } 1,85,0 { UINT_FLOAT_MIDPOINT, CONST_SIZE_OF_VAL, WAKER_NOOP } @@ -82,7 +82,7 @@ msrv_aliases! { 1,29,0 { ITER_FLATTEN } 1,28,0 { FROM_BOOL, REPEAT_WITH, SLICE_FROM_REF } 1,27,0 { ITERATOR_TRY_FOLD, DOUBLE_ENDED_ITERATOR_RFIND, DURATION_FROM_NANOS_MICROS } - 1,26,0 { RANGE_INCLUSIVE, STRING_RETAIN, POINTER_ADD_SUB_METHODS } + 1,26,0 { RANGE_INCLUSIVE, STRING_RETAIN, POINTER_ADD_SUB_METHODS, BOX_LEAK } 1,24,0 { IS_ASCII_DIGIT, PTR_NULL } 1,18,0 { HASH_MAP_RETAIN, HASH_SET_RETAIN } 1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST, EXPECT_ERR } @@ -102,15 +102,10 @@ static SEEN_MSRV_ATTR: AtomicBool = AtomicBool::new(false); #[derive(Copy, Clone, Debug, Default)] pub struct Msrv(Option); -impl<'de> Deserialize<'de> for Msrv { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - let v = String::deserialize(deserializer)?; - parse_version(Symbol::intern(&v)) - .map(|v| Self(Some(v))) - .ok_or_else(|| serde::de::Error::custom("not a valid Rust version")) +impl From> for Msrv { + #[inline] + fn from(value: Option) -> Self { + Self(value) } } @@ -153,7 +148,6 @@ impl Msrv { pub fn meets(self, cx: &LateContext<'_>, required: RustcVersion) -> bool { self.current(cx).is_none_or(|msrv| msrv >= required) } - /// Checks if a required version from [this module](self) is met at the specified node /// /// If the crate being linted uses an `#[clippy::msrv]` attribute this will search the parent @@ -162,22 +156,6 @@ impl Msrv { self.at(tcx, node).is_none_or(|msrv| msrv >= required) } - pub fn read_cargo(&mut self, sess: &Session) { - let cargo_msrv = std::env::var("CARGO_PKG_RUST_VERSION") - .ok() - .and_then(|v| parse_version(Symbol::intern(&v))); - - match (self.0, cargo_msrv) { - (None, Some(cargo_msrv)) => self.0 = Some(cargo_msrv), - (Some(clippy_msrv), Some(cargo_msrv)) if clippy_msrv != cargo_msrv => { - sess.dcx().warn(format!( - "the MSRV in `clippy.toml` and `Cargo.toml` differ; using `{clippy_msrv}` from `clippy.toml`" - )); - }, - _ => {}, - } - } - pub fn is_stable(self, cx: &LateContext<'_>, def_id: DefId) -> bool { cx.tcx.lookup_stability(def_id).is_none_or(|stability| { if let StabilityLevel::Stable { since, .. } = stability.level { @@ -205,13 +183,16 @@ pub struct MsrvStack { stack: SmallVec<[RustcVersion; 2]>, } -impl MsrvStack { - pub fn new(initial: Msrv) -> Self { +impl From> for MsrvStack { + #[inline] + fn from(value: Option) -> Self { Self { - stack: SmallVec::from_iter(initial.0), + stack: SmallVec::from_iter(value), } } +} +impl MsrvStack { pub fn current(&self) -> Option { self.stack.last().copied() } diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index ca2cd7338d5a2..4acd0cb31412f 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -9,7 +9,7 @@ use rustc_const_eval::check_consts::ConstCx; use rustc_hir::attrs::RustcVersion; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, HirId, StableSince}; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_infer::traits::Obligation; use rustc_lint::LateContext; use rustc_middle::mir::{ diff --git a/src/tools/clippy/clippy_utils/src/res.rs b/src/tools/clippy/clippy_utils/src/res.rs index 59571a929887a..fdafebe00f477 100644 --- a/src/tools/clippy/clippy_utils/src/res.rs +++ b/src/tools/clippy/clippy_utils/src/res.rs @@ -339,6 +339,8 @@ impl<'tcx, T: Copy + MaybeQPath<'tcx>> MaybeQPath<'tcx> for &Option { /// A resolved path and the explicit `Self` type if there is one. type OptResPath<'tcx> = (Option<&'tcx hir::Ty<'tcx>>, Option<&'tcx Path<'tcx>>); +type OptTyRelPath<'tcx> = Option<(&'tcx hir::Ty<'tcx>, &'tcx PathSegment<'tcx>)>; + /// A HIR node which might be a `QPath::Resolved`. /// /// The following are resolved paths: @@ -354,6 +356,10 @@ pub trait MaybeResPath<'a>: Copy { /// type associated with it. fn opt_res_path(self) -> OptResPath<'a>; + /// If this node is a type relative path gets both the type and the final + /// segments of the path. + fn opt_ty_rel_path(self) -> OptTyRelPath<'a>; + /// If this node is a resolved path gets it's resolution. Returns `Res::Err` /// otherwise. #[inline] @@ -391,6 +397,11 @@ impl<'a> MaybeResPath<'a> for &'a Path<'a> { (None, Some(self)) } + #[inline] + fn opt_ty_rel_path(self) -> OptTyRelPath<'a> { + None + } + #[inline] fn basic_res(self) -> &'a Res { &self.res @@ -404,6 +415,14 @@ impl<'a> MaybeResPath<'a> for &QPath<'a> { QPath::TypeRelative(..) => (None, None), } } + + #[inline] + fn opt_ty_rel_path(self) -> OptTyRelPath<'a> { + match *self { + QPath::TypeRelative(ty, seg) => Some((ty, seg)), + QPath::Resolved(..) => None, + } + } } impl<'a> MaybeResPath<'a> for &Expr<'a> { #[inline] @@ -413,6 +432,14 @@ impl<'a> MaybeResPath<'a> for &Expr<'a> { _ => (None, None), } } + + #[inline] + fn opt_ty_rel_path(self) -> OptTyRelPath<'a> { + match &self.kind { + ExprKind::Path(qpath) => qpath.opt_ty_rel_path(), + _ => None, + } + } } impl<'a> MaybeResPath<'a> for &PatExpr<'a> { #[inline] @@ -422,6 +449,14 @@ impl<'a> MaybeResPath<'a> for &PatExpr<'a> { PatExprKind::Lit { .. } => (None, None), } } + + #[inline] + fn opt_ty_rel_path(self) -> OptTyRelPath<'a> { + match &self.kind { + PatExprKind::Path(qpath) => qpath.opt_ty_rel_path(), + PatExprKind::Lit { .. } => None, + } + } } impl<'a, AmbigArg> MaybeResPath<'a> for &hir::Ty<'a, AmbigArg> { #[inline] @@ -431,6 +466,14 @@ impl<'a, AmbigArg> MaybeResPath<'a> for &hir::Ty<'a, AmbigArg> { _ => (None, None), } } + + #[inline] + fn opt_ty_rel_path(self) -> OptTyRelPath<'a> { + match &self.kind { + TyKind::Path(qpath) => qpath.opt_ty_rel_path(), + _ => None, + } + } } impl<'a> MaybeResPath<'a> for &Pat<'a> { #[inline] @@ -440,6 +483,14 @@ impl<'a> MaybeResPath<'a> for &Pat<'a> { _ => (None, None), } } + + #[inline] + fn opt_ty_rel_path(self) -> OptTyRelPath<'a> { + match self.kind { + PatKind::Expr(e) => e.opt_ty_rel_path(), + _ => None, + } + } } impl<'a, T: MaybeResPath<'a>> MaybeResPath<'a> for Option { #[inline] @@ -450,6 +501,11 @@ impl<'a, T: MaybeResPath<'a>> MaybeResPath<'a> for Option { } } + #[inline] + fn opt_ty_rel_path(self) -> OptTyRelPath<'a> { + self.and_then(T::opt_ty_rel_path) + } + #[inline] fn basic_res(self) -> &'a Res { self.map_or(&Res::Err, T::basic_res) diff --git a/src/tools/clippy/clippy_utils/src/source.rs b/src/tools/clippy/clippy_utils/src/source.rs index 171276f997d39..9110f6cbf6b4e 100644 --- a/src/tools/clippy/clippy_utils/src/source.rs +++ b/src/tools/clippy/clippy_utils/src/source.rs @@ -1,6 +1,6 @@ //! Utils for extracting, inspecting or transforming source code -#![allow(clippy::module_name_repetitions)] +#![expect(clippy::module_name_repetitions)] use std::sync::Arc; @@ -13,7 +13,7 @@ use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::source_map::{SourceMap, original_sp}; use rustc_span::{ - BytePos, DUMMY_SP, DesugaringKind, Pos, RelativeBytePos, SourceFile, SourceFileAndLine, Span, SpanData, + BytePos, DUMMY_SP, DesugaringKind, Pos as _, RelativeBytePos, SourceFile, SourceFileAndLine, Span, SpanData, SyntaxContext, hygiene, }; use std::borrow::Cow; diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index bedd7111e3ef7..b2c68821fec94 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -14,7 +14,7 @@ use rustc_lint::{EarlyContext, LateContext, LintContext}; use rustc_middle::hir::place::ProjectionKind; use rustc_middle::mir::{FakeReadCause, Mutability}; use rustc_middle::ty; -use rustc_span::{BytePos, CharPos, Pos, Span, SyntaxContext}; +use rustc_span::{BytePos, CharPos, Pos as _, Span, SyntaxContext}; use std::borrow::Cow; use std::fmt::{self, Display, Write as _}; use std::ops::{Add, Neg, Not, Sub}; diff --git a/src/tools/clippy/clippy_utils/src/sym.rs b/src/tools/clippy/clippy_utils/src/sym.rs index 5da94bfda5e6c..aaaf91f363abd 100644 --- a/src/tools/clippy/clippy_utils/src/sym.rs +++ b/src/tools/clippy/clippy_utils/src/sym.rs @@ -1,4 +1,4 @@ -#![allow(non_upper_case_globals)] +#![expect(non_upper_case_globals)] use rustc_span::symbol::PREDEFINED_SYMBOLS_COUNT; @@ -364,6 +364,7 @@ generate! { into_bytes, into_ok, into_owned, + into_raw, intrinsics_unaligned_volatile_load, intrinsics_unaligned_volatile_store, io, diff --git a/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index a62a1a594ea78..ba41fe5c41ec1 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/mod.rs @@ -1,39 +1,42 @@ //! Util methods for [`rustc_middle::ty`] -#![allow(clippy::module_name_repetitions)] +#![expect(clippy::module_name_repetitions)] use core::ops::ControlFlow; +use itertools::Itertools as _; use rustc_abi::{BackendRepr, FieldsShape, VariantIdx, Variants}; use rustc_ast::ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_errors::pluralize; use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::{Expr, FnDecl, LangItem, find_attr}; +use rustc_hir::{Expr, ExprKind, FnDecl, LangItem}; use rustc_hir_analysis::lower_ty; -use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::TyCtxtInferExt as _; use rustc_lint::LateContext; +use rustc_lint::unused::must_use::{IsTyMustUse, MustUsePath, is_ty_must_use}; use rustc_middle::mir::ConstValue; use rustc_middle::mir::interpret::Scalar; use rustc_middle::traits::EvaluationResult; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind}; -use rustc_middle::ty::layout::{LayoutError, LayoutOf, TyAndLayout}; +use rustc_middle::ty::layout::{LayoutError, LayoutOf as _, TyAndLayout}; use rustc_middle::ty::{ self, AdtDef, AliasTy, AssocItem, AssocTag, Binder, BoundRegion, BoundVarIndexKind, FnSig, GenericArg, GenericArgKind, GenericArgsRef, IntTy, ProjectionAliasTy, Region, RegionKind, TraitRef, Ty, TyCtxt, - TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, UintTy, Unnormalized, Upcast, VariantDef, - VariantDiscr, + TypeSuperVisitable as _, TypeVisitable, TypeVisitableExt as _, TypeVisitor, UintTy, Unnormalized, Upcast as _, + VariantDef, VariantDiscr, }; use rustc_span::symbol::Ident; use rustc_span::{DUMMY_SP, Span, Symbol}; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; -use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt; +use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt as _; use rustc_trait_selection::traits::{Obligation, ObligationCause}; use std::collections::hash_map::Entry; use std::{debug_assert_matches, iter, mem}; use crate::paths::{PathNS, lookup_path_str}; -use crate::res::{MaybeDef, MaybeQPath}; +use crate::res::{MaybeDef as _, MaybeQPath as _}; use crate::{over, sym}; mod type_certainty; @@ -319,54 +322,112 @@ pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { } } -// Returns whether the `ty` has `#[must_use]` attribute. If `ty` is a `Result`/`ControlFlow` -// whose `Err`/`Break` payload is an uninhabited type, the `Ok`/`Continue` payload type -// will be used instead. See . -pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { - match ty.kind() { - ty::Adt(adt, args) => match cx.tcx.get_diagnostic_name(adt.did()) { - Some(sym::Result) if args.type_at(1).is_privately_uninhabited(cx.tcx, cx.typing_env()) => { - is_must_use_ty(cx, args.type_at(0)) - }, - Some(sym::ControlFlow) if args.type_at(0).is_privately_uninhabited(cx.tcx, cx.typing_env()) => { - is_must_use_ty(cx, args.type_at(1)) - }, - _ => find_attr!(cx.tcx, adt.did(), MustUse { .. }), +/// Returns whether the `ty` has `#[must_use]` attribute, or acts like it does according to the +/// compiler determination. For example, if `ty` is a `Result`/`ControlFlow` whose `Err`/`Break` +/// payload is an uninhabited type, the `Ok`/`Continue` payload type will be used instead. +/// +/// The [`MustUsePath`] can be used to describe the type through [`describe_must_use_type`]. +pub fn opt_must_use_path<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option { + // `is_ty_must_use` requires an expression, whose `hir_id` will be used to determine whether + // certain types are visibly uninhabited from the module containing the expression. + // `cx.last_node_with_lint_attrs` is initialized to the crate/module `hir_id` when linting + // a new crate/module. If it is overriden, it is with an `hir_id` pertaining to the same + // create/module. We can use this in a dummy expression instead of asking all callers + // to provide a local `hir_id` which would not add more information. + let dummy_expr = Expr { + hir_id: cx.last_node_with_lint_attrs, + span: DUMMY_SP, + kind: ExprKind::Ret(None), + }; + match is_ty_must_use(cx, ty, &dummy_expr) { + IsTyMustUse::Yes(path) => Some(path), + _ => None, + } +} + +/// Describe a [`MustUsePath`] returned by [`opt_must_use_path`]. +pub fn describe_must_use_type(cx: &LateContext<'_>, path: &MustUsePath) -> String { + describe_must_use_type_inner(cx, path, "", "", 1) +} + +// This is a rip-off from the compiler's `rustc_lint/src/unused/must_use.rs` +fn describe_must_use_type_inner( + cx: &LateContext<'_>, + path: &MustUsePath, + descr_pre: &str, + descr_post: &str, + plural_len: usize, +) -> String { + let plural_suffix = pluralize!(plural_len); + + match path { + MustUsePath::Boxed(path) => { + let descr_pre = &format!("{descr_pre}boxed "); + describe_must_use_type_inner(cx, path, descr_pre, descr_post, plural_len) }, - ty::Foreign(did) => find_attr!(cx.tcx, *did, MustUse { .. }), - ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty, _) | ty::Ref(_, ty, _) => { - // for the Array case we don't need to care for the len == 0 case - // because we don't want to lint functions returning empty arrays - is_must_use_ty(cx, *ty) + MustUsePath::Pinned(path) => { + let descr_pre = &format!("{descr_pre}pinned "); + describe_must_use_type_inner(cx, path, descr_pre, descr_post, plural_len) }, - ty::Tuple(args) => args.iter().any(|ty| is_must_use_ty(cx, ty)), - ty::Alias( - _, - AliasTy { - kind: ty::Opaque { def_id }, - .. - }, - ) => { - for (predicate, _) in cx.tcx.explicit_item_self_bounds(*def_id).skip_binder() { - if let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() - && find_attr!(cx.tcx, trait_predicate.trait_ref.def_id, MustUse { .. }) - { - return true; + MustUsePath::Opaque(path) => { + let descr_pre = &format!("{descr_pre}implementer{plural_suffix} of "); + describe_must_use_type_inner(cx, path, descr_pre, descr_post, plural_len) + }, + MustUsePath::TraitObject(path) => { + let descr_post = &format!(" trait object{plural_suffix}{descr_post}"); + describe_must_use_type_inner(cx, path, descr_pre, descr_post, plural_len) + }, + MustUsePath::TupleElement(elems) => elems + .iter() + .map(|(index, path)| { + let descr_post = &format!(" in tuple element {index}"); + describe_must_use_type_inner(cx, path, descr_pre, descr_post, plural_len) + }) + .join(", "), + MustUsePath::Result(path) => { + let descr_post = &format!(" in a `Result` with an uninhabited error{descr_post}"); + describe_must_use_type_inner(cx, path, descr_pre, descr_post, plural_len) + }, + MustUsePath::ControlFlow(path) => { + let descr_post = &format!(" in a `ControlFlow` with an uninhabited break{descr_post}"); + describe_must_use_type_inner(cx, path, descr_pre, descr_post, plural_len) + }, + MustUsePath::Array(path, len) => { + let descr_pre = &format!("{descr_pre}array{plural_suffix} of "); + describe_must_use_type_inner( + cx, + path, + descr_pre, + descr_post, + plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)), + ) + }, + MustUsePath::Closure(_) => { + format!( + "{descr_pre}{} closure{plural_suffix}{descr_post}", + if plural_len == 1 { + "one".to_string() + } else { + plural_len.to_string() } - } - false + ) }, - ty::Dynamic(binder, _) => { - for predicate in *binder { - if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() - && find_attr!(cx.tcx, trait_ref.def_id, MustUse { .. }) - { - return true; + MustUsePath::Coroutine(_) => { + format!( + "{descr_pre}{} coroutine{plural_suffix}{descr_post}", + if plural_len == 1 { + "one".to_string() + } else { + plural_len.to_string() } - } - false + ) + }, + MustUsePath::Def(_, def_id, _) => { + format!( + "{descr_pre}`{}`{plural_suffix}{descr_post}", + cx.tcx.def_path_str(*def_id) + ) }, - _ => false, } } @@ -532,8 +593,9 @@ fn is_uninit_value_valid_for_layout<'tcx>(cx: &LateContext<'tcx>, layout: TyAndL match layout.layout.backend_repr { BackendRepr::Scalar(s) => s.is_uninit_valid(), BackendRepr::ScalarPair { a, b, .. } => a.is_uninit_valid() && b.is_uninit_valid(), - BackendRepr::SimdVector { element, count: _ } => element.is_uninit_valid(), - BackendRepr::SimdScalableVector { element, .. } => element.is_uninit_valid(), + BackendRepr::SimdVector { element, count: _ } | BackendRepr::SimdScalableVector { element, .. } => { + element.is_uninit_valid() + }, // Here validity is determined by the structural fields instead. BackendRepr::Memory { .. } => match &layout.layout.variants { Variants::Single { .. } => match &layout.layout.fields { @@ -1010,7 +1072,7 @@ pub fn adt_and_variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option< /// Comes up with an "at least" guesstimate for the type's size, not taking into /// account the layout of type parameters. pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 { - use rustc_middle::ty::layout::LayoutOf; + use rustc_middle::ty::layout::LayoutOf as _; match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) { (Ok(size), _) => size, (Err(_), ty::Tuple(list)) => list.iter().map(|t| approx_ty_size(cx, t)).sum(), @@ -1055,7 +1117,7 @@ pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 { #[cfg(debug_assertions)] /// Asserts that the given arguments match the generic parameters of the given item. fn assert_generic_args_match<'tcx>(tcx: TyCtxt<'tcx>, did: DefId, args: &[GenericArg<'tcx>]) { - use itertools::Itertools; + use itertools::Itertools as _; let g = tcx.generics_of(did); let parent = g.parent.map(|did| tcx.generics_of(did)); let count = g.parent_count + g.own_params.len(); diff --git a/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs index 5d8d30b910955..07ea49f3bb7a9 100644 --- a/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/type_certainty/mod.rs @@ -15,14 +15,14 @@ use crate::paths::{PathNS, lookup_path}; use rustc_ast::{LitFloatType, LitIntType, LitKind}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt, walk_qpath, walk_ty}; +use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt as _, walk_qpath, walk_ty}; use rustc_hir::{self as hir, AmbigArg, Expr, ExprKind, GenericArgs, HirId, Node, Param, PathSegment, QPath, TyKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, AdtDef, GenericArgKind, Ty}; use rustc_span::Span; mod certainty; -use certainty::{Certainty, Meet, join, meet}; +use certainty::{Certainty, Meet as _, join, meet}; pub fn expr_type_is_certain(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { expr_type_certainty(cx, expr, false).is_certain() diff --git a/src/tools/clippy/clippy_utils/src/usage.rs b/src/tools/clippy/clippy_utils/src/usage.rs index d644cd5a4aace..bc575701f6ee3 100644 --- a/src/tools/clippy/clippy_utils/src/usage.rs +++ b/src/tools/clippy/clippy_utils/src/usage.rs @@ -1,5 +1,5 @@ use crate::macros::root_macro_call_first_node; -use crate::res::MaybeResPath; +use crate::res::MaybeResPath as _; use crate::visitors::{Descend, Visitable, for_each_expr, for_each_expr_without_closures}; use crate::{self as utils, get_enclosing_loop_or_multi_call_closure, sym}; use core::ops::ControlFlow; diff --git a/src/tools/clippy/clippy_utils/src/visitors.rs b/src/tools/clippy/clippy_utils/src/visitors.rs index 85f983f836d23..1192d7353d123 100644 --- a/src/tools/clippy/clippy_utils/src/visitors.rs +++ b/src/tools/clippy/clippy_utils/src/visitors.rs @@ -1,10 +1,10 @@ use crate::get_enclosing_block; use crate::msrvs::Msrv; use crate::qualify_min_const_fn::is_stable_const_fn_at; -use crate::res::MaybeResPath; +use crate::res::MaybeResPath as _; use crate::ty::needs_ordered_drop; use core::ops::ControlFlow; -use rustc_ast::visit::{VisitorResult, try_visit}; +use rustc_ast::visit::{VisitorResult as _, try_visit}; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::intravisit::{self, Visitor, walk_block, walk_expr, walk_qpath}; use rustc_hir::{ diff --git a/src/tools/clippy/lintcheck/Cargo.toml b/src/tools/clippy/lintcheck/Cargo.toml index e4451af282732..0c5eaed8b5350 100644 --- a/src/tools/clippy/lintcheck/Cargo.toml +++ b/src/tools/clippy/lintcheck/Cargo.toml @@ -22,6 +22,6 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0.85" strip-ansi-escapes = "0.2.0" tar = "0.4.45" -toml = "0.9.7" +toml = "1.1" ureq = { version = "2.2", features = ["json"] } walkdir = "2.3" diff --git a/src/tools/clippy/lintcheck/src/driver.rs b/src/tools/clippy/lintcheck/src/driver.rs index 87ab14ba0cf83..7cbccdab58a48 100644 --- a/src/tools/clippy/lintcheck/src/driver.rs +++ b/src/tools/clippy/lintcheck/src/driver.rs @@ -1,6 +1,6 @@ use crate::recursive::{DriverInfo, deserialize_line, serialize_line}; -use std::io::{self, BufReader, Write}; +use std::io::{self, BufReader, Write as _}; use std::net::TcpStream; use std::process::{self, Command, Stdio}; use std::{env, mem}; diff --git a/src/tools/clippy/lintcheck/src/json.rs b/src/tools/clippy/lintcheck/src/json.rs index 79c1255c5ffe5..f39a7fef16183 100644 --- a/src/tools/clippy/lintcheck/src/json.rs +++ b/src/tools/clippy/lintcheck/src/json.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use std::{fmt, fs}; -use itertools::{EitherOrBoth, Itertools}; +use itertools::{EitherOrBoth, Itertools as _}; use serde::{Deserialize, Serialize}; use crate::ClippyWarning; diff --git a/src/tools/clippy/lintcheck/src/main.rs b/src/tools/clippy/lintcheck/src/main.rs index 6a9e6cab8957b..55eda5b4c33a1 100644 --- a/src/tools/clippy/lintcheck/src/main.rs +++ b/src/tools/clippy/lintcheck/src/main.rs @@ -7,17 +7,15 @@ #![feature(iter_collect_into)] #![warn( + rust_2018_idioms, trivial_casts, trivial_numeric_casts, - rust_2018_idioms, unused_lifetimes, unused_qualifications )] -#![allow( - clippy::collapsible_else_if, - clippy::needless_borrows_for_generic_args, - clippy::module_name_repetitions, - clippy::literal_string_with_formatting_args +#![expect( + clippy::literal_string_with_formatting_args, + clippy::needless_borrows_for_generic_args )] mod config; diff --git a/src/tools/clippy/lintcheck/src/popular_crates.rs b/src/tools/clippy/lintcheck/src/popular_crates.rs index ad8fc440c4240..c3170e46eaf9c 100644 --- a/src/tools/clippy/lintcheck/src/popular_crates.rs +++ b/src/tools/clippy/lintcheck/src/popular_crates.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::error::Error; -use std::fmt::Write; +use std::fmt::Write as _; use std::fs; use std::path::PathBuf; diff --git a/src/tools/clippy/lintcheck/src/recursive.rs b/src/tools/clippy/lintcheck/src/recursive.rs index 6406b2dcb643b..a236ec904ee51 100644 --- a/src/tools/clippy/lintcheck/src/recursive.rs +++ b/src/tools/clippy/lintcheck/src/recursive.rs @@ -7,7 +7,7 @@ use crate::ClippyWarning; use crate::input::RecursiveOptions; use std::collections::HashSet; -use std::io::{BufRead, BufReader, Read, Write}; +use std::io::{BufRead, BufReader, Read as _, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::{Arc, Mutex}; use std::thread; diff --git a/src/tools/clippy/rust-toolchain.toml b/src/tools/clippy/rust-toolchain.toml index d6306869ba743..3248684c4f59f 100644 --- a/src/tools/clippy/rust-toolchain.toml +++ b/src/tools/clippy/rust-toolchain.toml @@ -1,6 +1,6 @@ [toolchain] # begin autogenerated nightly -channel = "nightly-2026-07-09" +channel = "nightly-2026-08-07" # end autogenerated nightly components = ["cargo", "llvm-tools", "rust-src", "rust-std", "rustc", "rustc-dev", "rustfmt"] profile = "minimal" diff --git a/src/tools/clippy/src/driver.rs b/src/tools/clippy/src/driver.rs index ed217bc7c3f40..78b9b2cd8de39 100644 --- a/src/tools/clippy/src/driver.rs +++ b/src/tools/clippy/src/driver.rs @@ -1,8 +1,9 @@ #![feature(rustc_private)] -// warn on lints, that are included in `rust-lang/rust`s bootstrap -#![warn(rust_2018_idioms, unused_lifetimes)] -// warn on rustc internal lints -#![warn(rustc::internal)] +#![warn( + // warn on lints, that are included in `rust-lang/rust`s bootstrap + rust_2018_idioms, unused_lifetimes, + // and on rustc internal lints + rustc::internal)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) @@ -54,7 +55,7 @@ fn is_arg(argument: &str, key: &str) -> bool { #[test] fn test_arg_value() { - use std::ops::Not; + use std::ops::Not as _; let args = &["--bar=bar", "--foobar", "123", "--foo"].map(String::from); @@ -137,7 +138,6 @@ struct ClippyCallbacks { impl rustc_driver::Callbacks for ClippyCallbacks { #[expect(rustc::bad_opt_access, reason = "necessary in clippy driver to set `mir_opt_level`")] fn config(&mut self, config: &mut interface::Config) { - let conf_path = clippy_config::lookup_conf_file(); let previous = config.register_lints.take(); let clippy_args_var = self.clippy_args_var.take(); config.track_state = Some(Box::new(move |sess| { @@ -162,7 +162,7 @@ impl rustc_driver::Callbacks for ClippyCallbacks { list_builder.insert(clippy_lints::declared_lints::LINTS); list_builder.register(lint_store); - let conf = clippy_config::Conf::read(sess, &conf_path); + let conf = clippy_config::Conf::load(sess); clippy_lints::register_lint_passes(lint_store, conf); #[cfg(feature = "internal")] diff --git a/src/tools/clippy/src/main.rs b/src/tools/clippy/src/main.rs index 4b158c27ebbff..14a437fc874fe 100644 --- a/src/tools/clippy/src/main.rs +++ b/src/tools/clippy/src/main.rs @@ -115,12 +115,8 @@ impl ClippyCmd { .iter() .fold(String::new(), |s, arg| s + arg + "__CLIPPY_HACKERY__"); - // Currently, `CLIPPY_TERMINAL_WIDTH` is used only to format "unknown field" error messages. - let terminal_width = termize::dimensions().map_or(0, |(w, _)| w); - cmd.env("RUSTC_WORKSPACE_WRAPPER", Self::path()) .env("CLIPPY_ARGS", clippy_args) - .env("CLIPPY_TERMINAL_WIDTH", terminal_width.to_string()) .arg(self.cargo_subcommand) .args(&self.args); diff --git a/src/tools/clippy/tests/compile-test.rs b/src/tools/clippy/tests/compile-test.rs index e5933d7c7a3f1..a8a38e0d2c611 100644 --- a/src/tools/clippy/tests/compile-test.rs +++ b/src/tools/clippy/tests/compile-test.rs @@ -6,7 +6,7 @@ use askama::Template; use askama::filters::Safe; use cargo_metadata::Message; use cargo_metadata::diagnostic::{Applicability, Diagnostic}; -use clippy_config::ClippyConfiguration; +use clippy_config::ConfMetadata; use clippy_lints::declared_lints::LINTS; use clippy_lints::deprecated_lints::{DEPRECATED, DEPRECATED_VERSION, RENAMED}; use declare_clippy_lint::LintInfo; @@ -24,7 +24,7 @@ use ui_test::{Args, CommandBuilder, Config, Match, error_on_output_conflict}; use std::collections::{BTreeMap, HashMap}; use std::env::{self, set_var, var_os}; use std::ffi::{OsStr, OsString}; -use std::fmt::Write; +use std::fmt::Write as _; use std::path::{Path, PathBuf}; use std::sync::mpsc::{Sender, channel}; use std::{fs, iter, thread}; @@ -82,8 +82,9 @@ fn internal_extern_flags() -> Vec { .copied() .filter(|n| !crates.contains_key(n)) .collect(); - assert!( - not_found.is_empty(), + assert_eq!( + not_found, + [] as [&str; 0], "dependencies not found in depinfo: {not_found:?}\n\ help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\ help: Try adding to dev-dependencies in Cargo.toml\n\ @@ -540,7 +541,7 @@ impl DiagnosticCollector { } } - let configs = clippy_config::get_configuration_metadata(); + let configs = clippy_config::Conf::get_metadata(); let mut metadata: Vec = LINTS .iter() .map(|lint| LintMetadata::new(lint, &applicabilities, &configs)) @@ -612,7 +613,7 @@ struct LintMetadata { } impl LintMetadata { - fn new(lint: &LintInfo, applicabilities: &HashMap, configs: &[ClippyConfiguration]) -> Self { + fn new(lint: &LintInfo, applicabilities: &HashMap, configs: &[ConfMetadata]) -> Self { let name = lint.name_lower(); let applicability = applicabilities .get(&name) diff --git a/src/tools/clippy/tests/config-consistency.rs b/src/tools/clippy/tests/config-consistency.rs index 9e7ca26c7d400..f60d72a456875 100644 --- a/src/tools/clippy/tests/config-consistency.rs +++ b/src/tools/clippy/tests/config-consistency.rs @@ -18,7 +18,7 @@ fn config_consistency() { .iter() .map(|lint_info| lint_info.lint.name.strip_prefix("clippy::").unwrap().to_lowercase()) .collect(); - for conf in clippy_config::get_configuration_metadata() { + for conf in clippy_config::Conf::get_metadata() { for lint in conf.lints { assert!( lint_names.contains(*lint), diff --git a/src/tools/clippy/tests/config-metadata.rs b/src/tools/clippy/tests/config-metadata.rs index af9fe064dc708..0b978ce3d8a62 100644 --- a/src/tools/clippy/tests/config-metadata.rs +++ b/src/tools/clippy/tests/config-metadata.rs @@ -1,15 +1,18 @@ #![feature(rustc_private)] +#![allow(unused_extern_crates)] -use clippy_config::{ClippyConfiguration, get_configuration_metadata}; -use itertools::Itertools; +extern crate rustc_driver; + +use clippy_config::{Conf, ConfMetadata}; +use itertools::Itertools as _; use regex::Regex; use std::borrow::Cow; use std::{env, fs}; -fn metadata() -> impl Iterator { - get_configuration_metadata() +fn metadata() -> impl Iterator { + Conf::get_metadata() .into_iter() - .filter(|config| config.deprecation_reason.is_none()) + .filter(|config| config.renamed_to.is_none()) .filter(|config| !config.lints.is_empty()) } @@ -18,7 +21,9 @@ fn book() { let path = "book/src/lint_configuration.md"; let current = fs::read_to_string(path).unwrap(); - let configs = metadata().map(|conf| conf.to_markdown_paragraph()).join("\n"); + let configs = metadata() + .format_with("\n", |conf, f| f(&conf.display_markdown_paragraph())) + .to_string(); let expected = format!( r" src/edge_cases/mod.rs:13:1 + | +13 | pub struct AboveMod; + | ^^^^^^^^^^^^^^^^^^^^ + | + = help: move struct `AboveMod` to a dedicated file + = note: `-D clippy::definition-in-module-root` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::definition_in_module_root)]` + +error: definition in module root file + --> src/edge_cases/mod.rs:20:1 + | +20 | pub struct Foo; + | ^^^^^^^^^^^^^^^ + | + = help: move struct `Foo` to a dedicated file + +error: definition in module root file + --> src/edge_cases/mod.rs:23:1 + | +23 | pub struct Generic(T); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: move struct `Generic` to a dedicated file + +error: definition in module root file + --> src/edge_cases/mod.rs:24:1 + | +24 | / impl Generic { +25 | | pub fn new(t: T) -> Self { +26 | | Self(t) +27 | | } +28 | | } + | |_^ + | + = help: move the implementation to a dedicated file + +error: definition in module root file + --> src/edge_cases/mod.rs:31:1 + | +31 | pub async fn frob() {} + | ^^^^^^^^^^^^^^^^^^^^^^ + | + = help: move function `frob` to a dedicated file + +error: definition in module root file + --> src/edge_cases/mod.rs:34:1 + | +34 | / pub const fn cnst() -> u32 { +35 | | 0 +36 | | } + | |_^ + | + = help: move function `cnst` to a dedicated file + +error: definition in module root file + --> src/edge_cases/mod.rs:39:1 + | +39 | pub static FOO: u32 = 1; + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: move static item `FOO` to a dedicated file + +error: definition in module root file + --> src/edge_cases/mod.rs:43:1 + | +43 | / macro_rules! local_macro { +44 | | () => {}; +45 | | } + | |_^ + | + = help: move macro definition `local_macro` to a dedicated file + +error: definition in module root file + --> src/edge_cases/mod.rs:48:1 + | +48 | / pub trait WithDefault { +49 | | fn default_method(&self) -> u32 { +50 | | 42 +51 | | } +52 | | } + | |_^ + | + = help: move trait `WithDefault` to a dedicated file + +error: could not compile `fail-edge-cases` (lib) due to 9 previous errors diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/Cargo.toml b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/Cargo.toml new file mode 100644 index 0000000000000..450812cfec26f --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "fail-edge-cases" +version = "0.1.0" +edition = "2021" +publish = false diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/edge_cases/mod.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/edge_cases/mod.rs new file mode 100644 index 0000000000000..0e61bf50fd425 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/edge_cases/mod.rs @@ -0,0 +1,59 @@ +#![warn(clippy::definition_in_module_root)] + +// Case g: extern crate is a declaration → no fire. +extern crate alloc; + +// Case b: re-export of named item from sibling → no fire. +pub use super::other::Bar; + +// Case c: glob re-export → no fire. +pub use super::other::*; + +// Case j (top half): item right above `mod foo;` → fires. +pub struct AboveMod; + +// Case j: nested file module declaration → no fire (declaration only). +mod sub; + +// Case a: derive — struct fires once, derived impls do NOT fire (from_expansion). +#[derive(Clone, Debug)] +pub struct Foo; + +// Case d: generics — struct fires + impl block fires. +pub struct Generic(T); +impl Generic { + pub fn new(t: T) -> Self { + Self(t) + } +} + +// Case e: async fn fires as 'function'. +pub async fn frob() {} + +// Case f: const fn fires as 'function'. +pub const fn cnst() -> u32 { + 0 +} + +// Case h: static fires as 'static'. +pub static FOO: u32 = 1; + +// Case k: non-exported macro fires as 'macro'. +#[allow(unused_macros)] +macro_rules! local_macro { + () => {}; +} + +// Case l: trait with default method body fires once (not its inner items). +pub trait WithDefault { + fn default_method(&self) -> u32 { + 42 + } +} + +// Case i: inline module — children should NOT fire. +#[cfg(test)] +mod tests { + pub struct InsideInline; + pub fn t() {} +} diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/edge_cases/sub.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/edge_cases/sub.rs new file mode 100644 index 0000000000000..202b24fd77f99 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/edge_cases/sub.rs @@ -0,0 +1,6 @@ +// Sibling file referenced by `mod sub;` in edge_cases/mod.rs. +// Items here live in a non-mod.rs file → no fire even if they are definitions. +#[allow(dead_code)] +pub struct InSub; +#[allow(dead_code)] +pub fn in_sub() {} diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/lib.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/lib.rs new file mode 100644 index 0000000000000..09a5d92a57855 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/lib.rs @@ -0,0 +1,4 @@ +#![warn(clippy::definition_in_module_root)] + +pub mod edge_cases; +pub mod other; diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/other.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/other.rs new file mode 100644 index 0000000000000..b246a8a522470 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_edge_cases/src/other.rs @@ -0,0 +1,3 @@ +// Sibling module with items that the edge_cases mod.rs re-exports. +pub struct Bar; +pub fn helper() {} diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/Cargo.stderr b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/Cargo.stderr new file mode 100644 index 0000000000000..f2034397dec03 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/Cargo.stderr @@ -0,0 +1,64 @@ +error: definition in module root file + --> src/stuff/mod.rs:4:1 + | +4 | pub struct Foo; + | ^^^^^^^^^^^^^^^ + | + = help: move struct `Foo` to a dedicated file + = note: `-D clippy::definition-in-module-root` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::definition_in_module_root)]` + +error: definition in module root file + --> src/stuff/mod.rs:5:1 + | +5 | / pub enum Bar { +6 | | A, +7 | | B, +8 | | } + | |_^ + | + = help: move enum `Bar` to a dedicated file + +error: definition in module root file + --> src/stuff/mod.rs:9:1 + | +9 | pub fn baz() {} + | ^^^^^^^^^^^^^^^ + | + = help: move function `baz` to a dedicated file + +error: definition in module root file + --> src/stuff/mod.rs:10:1 + | +10 | pub const QUUX: u32 = 1; + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: move constant item `QUUX` to a dedicated file + +error: definition in module root file + --> src/stuff/mod.rs:11:1 + | +11 | pub trait Trait1 {} + | ^^^^^^^^^^^^^^^^^^^ + | + = help: move trait `Trait1` to a dedicated file + +error: definition in module root file + --> src/stuff/mod.rs:12:1 + | +12 | pub type Alias = std::result::Result; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: move type alias `Alias` to a dedicated file + +error: definition in module root file + --> src/stuff/mod.rs:13:1 + | +13 | / impl Foo { +14 | | pub fn method(&self) {} +15 | | } + | |_^ + | + = help: move the implementation to a dedicated file + +error: could not compile `fail-mod` (lib) due to 7 previous errors diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/Cargo.toml b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/Cargo.toml new file mode 100644 index 0000000000000..575ff58cadec5 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "fail-mod" +version = "0.1.0" +edition = "2021" +publish = false diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/src/lib.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/src/lib.rs new file mode 100644 index 0000000000000..3c232b85fae89 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/src/lib.rs @@ -0,0 +1,3 @@ +#![warn(clippy::definition_in_module_root)] + +pub mod stuff; diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/src/stuff/mod.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/src/stuff/mod.rs new file mode 100644 index 0000000000000..e52225e55856a --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_mod/src/stuff/mod.rs @@ -0,0 +1,21 @@ +#![warn(clippy::definition_in_module_root)] + +// Every definition kind should trigger the lint. +pub struct Foo; +pub enum Bar { + A, + B, +} +pub fn baz() {} +pub const QUUX: u32 = 1; +pub trait Trait1 {} +pub type Alias = std::result::Result; +impl Foo { + pub fn method(&self) {} +} + +// macro_export macros are allowed. +#[macro_export] +macro_rules! ok { + () => {}; +} diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/Cargo.stderr b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/Cargo.stderr new file mode 100644 index 0000000000000..1423f9145e99c --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/Cargo.stderr @@ -0,0 +1,19 @@ +error: definition in module root file + --> src/custom/mod.rs:1:1 + | +1 | pub struct Foo; + | ^^^^^^^^^^^^^^^ + | + = help: move struct `Foo` to a dedicated file + = note: `-D clippy::definition-in-module-root` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::definition_in_module_root)]` + +error: definition in module root file + --> src/custom/mod.rs:2:1 + | +2 | pub fn bar() {} + | ^^^^^^^^^^^^^^^ + | + = help: move function `bar` to a dedicated file + +error: could not compile `fail-path-attr` (lib) due to 2 previous errors diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/Cargo.toml b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/Cargo.toml new file mode 100644 index 0000000000000..3f57a420e2f64 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "fail-path-attr" +version = "0.1.0" +edition = "2021" +publish = false diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/src/custom/mod.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/src/custom/mod.rs new file mode 100644 index 0000000000000..b12603cbeac85 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/src/custom/mod.rs @@ -0,0 +1,2 @@ +pub struct Foo; +pub fn bar() {} diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/src/lib.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/src/lib.rs new file mode 100644 index 0000000000000..8e7cd55b614d9 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/fail_path_attr/src/lib.rs @@ -0,0 +1,5 @@ +#![warn(clippy::definition_in_module_root)] + +// #[path] to a mod.rs — definitions inside should still trigger. +#[path = "custom/mod.rs"] +pub mod things; diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_bin/Cargo.toml b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_bin/Cargo.toml new file mode 100644 index 0000000000000..757e4f2068c16 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_bin/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "pass-bin" +version = "0.1.0" +edition = "2021" +publish = false diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_bin/src/main.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_bin/src/main.rs new file mode 100644 index 0000000000000..4e7b641104da9 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_bin/src/main.rs @@ -0,0 +1,8 @@ +#![warn(clippy::definition_in_module_root)] + +// Definitions in main.rs are allowed — the lint only applies to mod.rs. +pub struct Foo; +pub fn bar() {} +pub const BAZ: u32 = 1; + +fn main() {} diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_lib_with_definitions/Cargo.toml b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_lib_with_definitions/Cargo.toml new file mode 100644 index 0000000000000..49d81d648aa27 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_lib_with_definitions/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "pass-lib-with-definitions" +version = "0.1.0" +edition = "2021" +publish = false diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_lib_with_definitions/src/lib.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_lib_with_definitions/src/lib.rs new file mode 100644 index 0000000000000..dbe20ce7bd27e --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_lib_with_definitions/src/lib.rs @@ -0,0 +1,12 @@ +#![warn(clippy::definition_in_module_root)] + +// Definitions in lib.rs are allowed — the lint only applies to mod.rs. +pub struct Foo; +pub enum Bar { + A, + B, +} +pub fn baz() {} +pub const QUUX: u32 = 1; +pub trait Trait1 {} +pub type Alias = std::result::Result; diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/Cargo.toml b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/Cargo.toml new file mode 100644 index 0000000000000..d1ab114ffa855 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "pass-path-attr" +version = "0.1.0" +edition = "2021" +publish = false diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/src/custom/impl.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/src/custom/impl.rs new file mode 100644 index 0000000000000..b12603cbeac85 --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/src/custom/impl.rs @@ -0,0 +1,2 @@ +pub struct Foo; +pub fn bar() {} diff --git a/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/src/lib.rs b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/src/lib.rs new file mode 100644 index 0000000000000..2dd719a87877d --- /dev/null +++ b/src/tools/clippy/tests/ui-cargo/definition_in_module_root/pass_path_attr/src/lib.rs @@ -0,0 +1,5 @@ +#![warn(clippy::definition_in_module_root)] + +// #[path] to a named file — definitions should not trigger. +#[path = "custom/impl.rs"] +pub mod things; diff --git a/src/tools/clippy/tests/ui-cargo/multiple_inherent_impl/config_fail/Cargo.stderr b/src/tools/clippy/tests/ui-cargo/multiple_inherent_impl/config_fail/Cargo.stderr index 51c46e4f97b2c..67cf26151f039 100644 --- a/src/tools/clippy/tests/ui-cargo/multiple_inherent_impl/config_fail/Cargo.stderr +++ b/src/tools/clippy/tests/ui-cargo/multiple_inherent_impl/config_fail/Cargo.stderr @@ -1,7 +1,9 @@ -error: error reading Clippy's configuration file: unknown variant `FooBar`, expected one of `crate`, `file`, `module` +error: expected one of: `crate`, `file`, `module` --> $DIR/tests/ui-cargo/multiple_inherent_impl/config_fail/clippy.toml:1:28 | 1 | inherent-impl-lint-scope = "FooBar" | ^^^^^^^^ + | + = note: possible values: `crate`, `file`, `module` error: could not compile `config_fail` (bin "config_fail") due to 1 previous error diff --git a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_crates.stderr b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_crates.stderr index d24b0cd616294..fbfc69f4c3077 100644 --- a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_crates.stderr +++ b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_crates.stderr @@ -1,5 +1,5 @@ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:14:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:15:13 | LL | let _ = std::path::is_separator(' '); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -11,31 +11,31 @@ LL | #![deny(clippy::absolute_paths)] | ^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:20:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:21:13 | LL | let _ = ::std::path::MAIN_SEPARATOR; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:25:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:26:13 | LL | let _ = std::collections::hash_map::HashMap::::new(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:28:31 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:29:31 | LL | let _: &std::path::Path = std::path::Path::new(""); | ^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:28:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:29:13 | LL | let _: &std::path::Path = std::path::Path::new(""); | ^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:43:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:44:13 | LL | let _ = std::option::Option::None::; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_long.stderr b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_long.stderr index 0cc6566af3a96..dd492f1294889 100644 --- a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_long.stderr +++ b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.allow_long.stderr @@ -1,5 +1,5 @@ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:25:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:26:13 | LL | let _ = std::collections::hash_map::HashMap::::new(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.default.stderr b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.default.stderr index 53aa9030e0dd5..1ee9ada35a055 100644 --- a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.default.stderr +++ b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.default.stderr @@ -1,5 +1,5 @@ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:14:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:15:13 | LL | let _ = std::path::is_separator(' '); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -11,67 +11,67 @@ LL | #![deny(clippy::absolute_paths)] | ^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:20:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:21:13 | LL | let _ = ::std::path::MAIN_SEPARATOR; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:25:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:26:13 | LL | let _ = std::collections::hash_map::HashMap::::new(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:28:31 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:29:31 | LL | let _: &std::path::Path = std::path::Path::new(""); | ^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:28:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:29:13 | LL | let _: &std::path::Path = std::path::Path::new(""); | ^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:37:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:38:13 | LL | let _ = ::core::clone::Clone::clone(&0i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:40:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:41:13 | LL | let _ = ::clone(&0i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:43:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:44:13 | LL | let _ = std::option::Option::None::; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:65:17 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:66:17 | LL | impl core::fmt::Display for X | ^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:70:18 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:71:18 | LL | where T: core::clone::Clone | ^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:65:32 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:66:32 | LL | impl core::fmt::Display for X | ^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:116:5 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:117:5 | LL | crate::m1::S | ^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.no_short.stderr b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.no_short.stderr index c94b7777f3e9f..e7fbef2c50abe 100644 --- a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.no_short.stderr +++ b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.no_short.stderr @@ -1,5 +1,5 @@ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:14:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:15:13 | LL | let _ = std::path::is_separator(' '); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -11,85 +11,85 @@ LL | #![deny(clippy::absolute_paths)] | ^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:20:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:21:13 | LL | let _ = ::std::path::MAIN_SEPARATOR; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:25:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:26:13 | LL | let _ = std::collections::hash_map::HashMap::::new(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:28:31 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:29:31 | LL | let _: &std::path::Path = std::path::Path::new(""); | ^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:28:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:29:13 | LL | let _: &std::path::Path = std::path::Path::new(""); | ^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:37:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:38:13 | LL | let _ = ::core::clone::Clone::clone(&0i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:40:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:41:13 | LL | let _ = ::clone(&0i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:43:13 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:44:13 | LL | let _ = std::option::Option::None::; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:65:17 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:66:17 | LL | impl core::fmt::Display for X | ^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:70:18 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:71:18 | LL | where T: core::clone::Clone | ^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:65:32 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:66:32 | LL | impl core::fmt::Display for X | ^^^^^^^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:113:10 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:114:10 | LL | const _: crate::S = { | ^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:114:9 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:115:9 | LL | let crate::S = m1::S; | ^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:116:5 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:117:5 | LL | crate::m1::S | ^^^^^^^^^^^^ error: consider bringing this path into scope with the `use` keyword - --> tests/ui-toml/absolute_paths/absolute_paths.rs:122:14 + --> tests/ui-toml/absolute_paths/absolute_paths.rs:123:14 | LL | let _ = ::clone(&m1::S); | ^^^^^^^^ diff --git a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.rs b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.rs index a3982b8f6540d..3c2d69e24c8d2 100644 --- a/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.rs +++ b/src/tools/clippy/tests/ui-toml/absolute_paths/absolute_paths.rs @@ -5,6 +5,7 @@ //@[allow_long] rustc-env:CLIPPY_CONF_DIR=tests/ui-toml/absolute_paths/allow_long //@[no_short] rustc-env:CLIPPY_CONF_DIR=tests/ui-toml/absolute_paths/no_short #![deny(clippy::absolute_paths)] +#![expect(clippy::clone_on_copy)] extern crate proc_macros; use proc_macros::{external, inline_macros, with_span}; diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order.rs b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order.rs new file mode 100644 index 0000000000000..03e0fbfa31d20 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order.rs @@ -0,0 +1,112 @@ +//@rustc-env:CLIPPY_CONF_DIR=tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order +//@check-pass +#![deny(clippy::arbitrary_source_item_ordering)] + +struct Languages; +struct Language; +struct Iter<'a, T>(&'a [&'a T]); + +impl<'a> Iterator for Iter<'a, Language> { + type Item = &'a Language; + fn next(&mut self) -> Option { + todo!() + } +} + +// Follows the trait definition order (but not alphabetical order): +// accepted, because either ordering is allowed in this mode. +impl<'a> IntoIterator for &'a Languages { + type Item = &'a Language; + type IntoIter = Iter<'a, Language>; + fn into_iter(self) -> Self::IntoIter { + todo!() + } +} + +struct AlsoLanguages; + +// Follows the alphabetical order (but not the trait definition order): +// also accepted in this mode. +impl<'a> IntoIterator for &'a AlsoLanguages { + type IntoIter = Iter<'a, Language>; + type Item = &'a Language; + fn into_iter(self) -> Self::IntoIter { + todo!() + } +} + +// Bare impls only have the alphabetical ordering to compare against. +struct BareImpl; +impl BareImpl { + fn a() {} + fn b() {} + fn c() {} +} + +// Default trait impl ordering. +trait WithDefault { + fn a() {} + fn b() {} + fn c() {} +} + +trait WithDefault2 { + fn a(); + fn b(); + fn c(); +} + +struct SkipMiddle; + +impl WithDefault for SkipMiddle { + fn a() {} + fn c() {} +} + +struct FullImpl; + +impl WithDefault for FullImpl { + fn a() {} + fn b() {} + fn c() {} +} + +impl WithDefault2 for FullImpl { + fn a() {} + fn b() {} + fn c() {} +} + +// Tests `const` in trait. +trait ConstTrait { + const A: bool; + const B: bool; + const C: bool; + fn method(); +} + +struct FullImpl3; + +impl ConstTrait for FullImpl3 { + const A: bool = true; + const B: bool = false; + const C: bool = true; + fn method() {} +} + +trait ConstTrait2 { + const A: bool = true; + const B: bool = false; + const C: bool = true; + fn method() {} +} + +struct SkipImpl; + +// Skips `B` `C`, keeps order of `A` and `C`. +impl ConstTrait2 for SkipImpl { + const A: bool = true; + fn method() {} +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs new file mode 100644 index 0000000000000..ff96d0669e119 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs @@ -0,0 +1,106 @@ +//@rustc-env:CLIPPY_CONF_DIR=tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order +#![deny(clippy::arbitrary_source_item_ordering)] + +// Trait definition order: b, a, c. Deliberately unordered to make the +// trait definition order differ from the alphabetical order; its own +// ordering check is not what this test is about. +#[allow(clippy::arbitrary_source_item_ordering)] +trait MixedOrder { + fn b(); + fn a(); + fn c(); +} + +struct WrongInBothOrders; + +// `c, a, b`: the pair (c, a) violates the alphabetical order, and in the +// trait definition `c` comes after `a`, so it violates both orderings. +impl MixedOrder for WrongInBothOrders { + fn c() {} + fn a() {} + //~^ arbitrary_source_item_ordering + fn b() {} +} + +trait WithDefault { + fn a() {} + fn b() {} + fn c() {} +} + +struct SkipMiddleFailed; + +impl WithDefault for SkipMiddleFailed { + fn c() {} + fn a() {} + //~^ arbitrary_source_item_ordering +} + +struct FullImplFailed; + +impl WithDefault for FullImplFailed { + fn c() {} + fn a() {} + //~^ arbitrary_source_item_ordering + fn b() {} +} + +trait WithDefault2 { + fn a(); + fn b(); + fn c(); +} + +struct FullImplFailed2; + +impl WithDefault2 for FullImplFailed2 { + fn b() {} + fn a() {} + //~^ arbitrary_source_item_ordering + fn c() {} +} + +// Bare impls fall back to the alphabetical check. +struct BareImpl; + +impl BareImpl { + fn b() {} + fn a() {} + //~^ arbitrary_source_item_ordering +} + +// Tests `const` in trait failed by invalid alphabetical order. +trait ConstTrait { + const A: bool; + const B: bool; + const C: bool; + fn method(); +} + +struct FullImplFailed3; + +impl ConstTrait for FullImplFailed3 { + const A: bool = true; + const C: bool = true; + const B: bool = false; + //~^ arbitrary_source_item_ordering + fn method() {} +} + +trait ConstTrait2 { + const A: bool = true; + const B: bool = false; + const C: bool = true; + fn method() {} +} + +struct SkipMiddleFailed2; + +impl ConstTrait2 for SkipMiddleFailed2 { + const C: bool = true; + const A: bool = true; + //~^ arbitrary_source_item_ordering + fn method() {} +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.stderr new file mode 100644 index 0000000000000..b0b8c9e483889 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.stderr @@ -0,0 +1,91 @@ +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:20:5 + | +LL | fn a() {} + | ^^^^^^ + | +note: should be placed before `c` + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:19:5 + | +LL | fn c() {} + | ^^^^^^ +note: the lint level is defined here + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:2:9 + | +LL | #![deny(clippy::arbitrary_source_item_ordering)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:35:5 + | +LL | fn a() {} + | ^^^^^^ + | +note: should be placed before `c` + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:34:5 + | +LL | fn c() {} + | ^^^^^^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:43:5 + | +LL | fn a() {} + | ^^^^^^ + | +note: should be placed before `c` + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:42:5 + | +LL | fn c() {} + | ^^^^^^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:58:5 + | +LL | fn a() {} + | ^^^^^^ + | +note: should be placed before `b` + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:57:5 + | +LL | fn b() {} + | ^^^^^^ + +error: incorrect ordering of items (must be alphabetically ordered) + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:68:8 + | +LL | fn a() {} + | ^ + | +note: should be placed before `b` + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:67:8 + | +LL | fn b() {} + | ^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:85:5 + | +LL | const B: bool = false; + | ^^^^^^^^^^^^^ + | +note: should be placed before `C` + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:84:5 + | +LL | const C: bool = true; + | ^^^^^^^^^^^^^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:101:5 + | +LL | const A: bool = true; + | ^^^^^^^^^^^^^ + | +note: should be placed before `C` + --> tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/alphabetical_or_trait_item_order_failed.rs:100:5 + | +LL | const C: bool = true; + | ^^^^^^^^^^^^^ + +error: aborting due to 7 previous errors + diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/clippy.toml b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/clippy.toml new file mode 100644 index 0000000000000..81ec9245db21b --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/alphabetical_or_trait_item_order/clippy.toml @@ -0,0 +1 @@ +trait-impl-item-order = "alphabetical_or_trait_item_ordering" diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_1.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_1.stderr index e441c7c1241c9..3c080d371eafd 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_1.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_1.stderr @@ -1,4 +1,4 @@ -error: error reading Clippy's configuration file: Some trait associated item kinds were configured more than once, or were missing, in the source ordering configuration. The trait associated item kinds are: [Const, Fn, Type] +error: Some trait associated item kinds were configured more than once, or were missing, in the source ordering configuration. The trait associated item kinds are: [Const, Fn, Type] --> $DIR/tests/ui-toml/arbitrary_source_item_ordering/bad_conf_1/clippy.toml:1:32 | LL | trait-assoc-item-kinds-order = ["fn", "type", "const", "type"] diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_2.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_2.stderr index 183f0b0331910..adb87d95f9dfc 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_2.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_2.stderr @@ -1,4 +1,4 @@ -error: error reading Clippy's configuration file: Some trait associated item kinds were configured more than once, or were missing, in the source ordering configuration. The trait associated item kinds are: [Const, Fn, Type] +error: Some trait associated item kinds were configured more than once, or were missing, in the source ordering configuration. The trait associated item kinds are: [Const, Fn, Type] --> $DIR/tests/ui-toml/arbitrary_source_item_ordering/bad_conf_2/clippy.toml:1:32 | LL | trait-assoc-item-kinds-order = ["const", "type"] diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_3.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_3.stderr index abf58dbd11010..e804ed8243491 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_3.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_3.stderr @@ -1,4 +1,4 @@ -error: error reading Clippy's configuration file: The category "Struct" was enabled more than once in the source ordering configuration. +error: The category "struct" was enabled more than once in the source ordering configuration. --> $DIR/tests/ui-toml/arbitrary_source_item_ordering/bad_conf_3/clippy.toml:1:24 | LL | source-item-ordering = ["enum", "impl", "module", "struct", "trait", "struct"] diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_4.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_4.stderr index c38c54ffeb0d5..9f182754088e9 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_4.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_4.stderr @@ -1,4 +1,4 @@ -error: error reading Clippy's configuration file: data did not match any variant of untagged enum StringOrVecOfString The available options for configuring an ordering within module item groups are: "all", "none", or a list of module item group names (as configured with the `module-item-order-groupings` configuration option). +error: expected a string or an array of strings --> $DIR/tests/ui-toml/arbitrary_source_item_ordering/bad_conf_4/clippy.toml:1:41 | LL | module-items-ordered-within-groupings = true diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_5.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_5.stderr index 7b1dafb6d0d5b..6f8563843296b 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_5.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_5.stderr @@ -1,4 +1,8 @@ -error: error reading Clippy's configuration file: unknown ordering group: `madules` was not specified in `module-items-ordered-within-groupings`, perhaps you meant `modules`? expected one of: `modules`, `use`, `macros`, `global_asm`, `UPPER_SNAKE_CASE`, `PascalCase`, `lower_snake_case` +error: unknown ordering group: `madules` was not specified in `module-items-ordered-within-groupings`, perhaps you meant `modules`? expected one of: `modules`, `use`, `macros`, `global_asm`, `UPPER_SNAKE_CASE`, `PascalCase`, `lower_snake_case` + --> $DIR/tests/ui-toml/arbitrary_source_item_ordering/bad_conf_5/clippy.toml:1:42 + | +LL | module-items-ordered-within-groupings = ["madules"] + | ^^^^^^^^^ error: aborting due to 1 previous error diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_6.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_6.stderr index 996cabeeed4a7..ecbc19b62f388 100644 --- a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_6.stderr +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/ordering_good.bad_conf_6.stderr @@ -1,4 +1,8 @@ -error: error reading Clippy's configuration file: unknown ordering group: `entirely garbled` was not specified in `module-items-ordered-within-groupings`, expected one of: `modules`, `use`, `macros`, `global_asm`, `UPPER_SNAKE_CASE`, `PascalCase`, `lower_snake_case` +error: unknown ordering group: `entirely garbled` was not specified in `module-items-ordered-within-groupings`, expected one of: `modules`, `use`, `macros`, `global_asm`, `UPPER_SNAKE_CASE`, `PascalCase`, `lower_snake_case` + --> $DIR/tests/ui-toml/arbitrary_source_item_ordering/bad_conf_6/clippy.toml:1:42 + | +LL | module-items-ordered-within-groupings = ["entirely garbled"] + | ^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/clippy.toml b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/clippy.toml new file mode 100644 index 0000000000000..33da8613cfa00 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/clippy.toml @@ -0,0 +1 @@ +trait-impl-item-order = "trait_item_ordering" diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order.rs b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order.rs new file mode 100644 index 0000000000000..31554937e9dd7 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order.rs @@ -0,0 +1,94 @@ +//@rustc-env:CLIPPY_CONF_DIR=tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order +//@check-pass +#![deny(clippy::arbitrary_source_item_ordering)] + +struct Languages; +struct Language; +struct Iter<'a, T>(&'a [&'a T]); + +impl<'a> Iterator for Iter<'a, Language> { + type Item = &'a Language; + fn next(&mut self) -> Option { + todo!() + } +} + +impl<'a> IntoIterator for &'a Languages { + type Item = &'a Language; + type IntoIter = Iter<'a, Language>; + fn into_iter(self) -> Self::IntoIter { + todo!() + } +} + +// Default trait impl ordering. +trait WithDefault { + fn a() {} + fn b() {} + fn c() {} +} + +struct SkipMiddle; + +impl WithDefault for SkipMiddle { + fn a() {} + fn c() {} +} + +struct FullImpl; + +impl WithDefault for FullImpl { + fn a() {} + fn b() {} + fn c() {} +} + +trait WithDefault2 { + fn a(); + fn b(); + fn c(); +} + +struct FullImpl2; + +impl WithDefault2 for FullImpl2 { + fn a() {} + fn b() {} + fn c() {} +} + +// Tests `const` in trait. +trait ConstTrait { + const A: bool; + const B: bool; + const C: bool; + fn method(); +} + +struct FullImpl3; + +// Tests `const` in trait without value. +impl ConstTrait for FullImpl3 { + const A: bool = true; + const B: bool = false; + const C: bool = true; + fn method() {} +} + +trait ConstTrait2 { + const A: bool = true; + const B: bool = false; + const C: bool = true; + fn method() {} +} + +struct SkipImpl; + +// Tests skipped `const` in trait. +impl ConstTrait2 for SkipImpl { + const A: bool = true; + const C: bool = true; + fn method() {} +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs new file mode 100644 index 0000000000000..510df33de322f --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs @@ -0,0 +1,105 @@ +//@revisions: trait_def +//@rustc-env:CLIPPY_CONF_DIR=tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order +#![deny(clippy::arbitrary_source_item_ordering)] + +// A trait whose definition order happens to be alphabetical. +trait AlphaOrder { + fn a(); + fn b(); + fn c(); +} + +struct WrongInBothOrders; + +// `a, c, b` violates both the alphabetical order and the trait +// definition order, so it is linted in every mode. +impl AlphaOrder for WrongInBothOrders { + fn a() {} + fn c() {} + fn b() {} + //~^ arbitrary_source_item_ordering +} + +trait AlphaOrder2 { + fn a() {} + fn b() {} + fn c() {} +} + +struct WrongInBothOrder2; + +impl AlphaOrder2 for WrongInBothOrder2 { + fn a() {} + fn c() {} + fn b() {} + //~^ arbitrary_source_item_ordering +} + +// Bare impls have no trait definition to compare against, so the +// trait_item_ordering mode falls back to the alphabetical check. +struct BareImpl; +impl BareImpl { + fn a() {} + fn c() {} + fn b() {} + //~^ arbitrary_source_item_ordering +} + +struct Languages; +struct Language; +struct Iter<'a, T>(&'a [&'a T]); + +impl<'a> Iterator for Iter<'a, Language> { + type Item = &'a Language; + fn next(&mut self) -> Option { + todo!() + } +} + +impl<'a> IntoIterator for &'a Languages { + fn into_iter(self) -> Self::IntoIter { + todo!() + } + type Item = &'a Language; + //~^ arbitrary_source_item_ordering + type IntoIter = Iter<'a, Language>; +} + +// Tests `const` in trait when failed by invalid trait definition order (e.g. Not in alphabetical +// order). +trait ConstTrait { + const A: bool; + const B: bool; + const C: bool; + fn method(); +} + +struct WrongInBothOrder3; + +impl ConstTrait for WrongInBothOrder3 { + const A: bool = true; + const C: bool = true; + const B: bool = false; + //~^ arbitrary_source_item_ordering + fn method() {} +} + +// Tests skipped trait which has `const` in trait failed by invalid trait definition order (e.g. Not +// in alphabetical order). +trait SkipConstTrait { + const A: bool = true; + const B: bool = false; + const C: bool = true; + fn method() {} +} + +struct WrongInBothOrder4; + +impl SkipConstTrait for WrongInBothOrder4 { + const C: bool = true; + const A: bool = true; + //~^ arbitrary_source_item_ordering + fn method() {} +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.trait_def.stderr b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.trait_def.stderr new file mode 100644 index 0000000000000..c70c3c9e7978f --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.trait_def.stderr @@ -0,0 +1,79 @@ +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:19:5 + | +LL | fn b() {} + | ^^^^^^ + | +note: should be placed before `c` + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:18:5 + | +LL | fn c() {} + | ^^^^^^ +note: the lint level is defined here + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:3:9 + | +LL | #![deny(clippy::arbitrary_source_item_ordering)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:34:5 + | +LL | fn b() {} + | ^^^^^^ + | +note: should be placed before `c` + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:33:5 + | +LL | fn c() {} + | ^^^^^^ + +error: incorrect ordering of items (must be alphabetically ordered) + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:44:8 + | +LL | fn b() {} + | ^ + | +note: should be placed before `c` + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:43:8 + | +LL | fn c() {} + | ^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:63:5 + | +LL | type Item = &'a Language; + | ^^^^^^^^^ + | +note: should be placed before `into_iter` + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:60:5 + | +LL | fn into_iter(self) -> Self::IntoIter { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:82:5 + | +LL | const B: bool = false; + | ^^^^^^^^^^^^^ + | +note: should be placed before `C` + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:81:5 + | +LL | const C: bool = true; + | ^^^^^^^^^^^^^ + +error: incorrect ordering of impl items (should follow the trait definition order) + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:100:5 + | +LL | const A: bool = true; + | ^^^^^^^^^^^^^ + | +note: should be placed before `C` + --> tests/ui-toml/arbitrary_source_item_ordering/trait_definition_order/trait_definition_order_failed.rs:99:5 + | +LL | const C: bool = true; + | ^^^^^^^^^^^^^ + +error: aborting due to 6 previous errors + diff --git a/src/tools/clippy/tests/ui-toml/await_holding_invalid_type_with_replacement/await_holding_invalid_type.stderr b/src/tools/clippy/tests/ui-toml/await_holding_invalid_type_with_replacement/await_holding_invalid_type.stderr index d0fce3614a145..e0e070f54cec7 100644 --- a/src/tools/clippy/tests/ui-toml/await_holding_invalid_type_with_replacement/await_holding_invalid_type.stderr +++ b/src/tools/clippy/tests/ui-toml/await_holding_invalid_type_with_replacement/await_holding_invalid_type.stderr @@ -1,8 +1,10 @@ -error: error reading Clippy's configuration file: replacement not allowed for this configuration - --> $DIR/tests/ui-toml/await_holding_invalid_type_with_replacement/clippy.toml:2:5 +error: unknown key + --> $DIR/tests/ui-toml/await_holding_invalid_type_with_replacement/clippy.toml:2:37 | LL | { path = "std::string::String", replacement = "std::net::Ipv4Addr" }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ + | + = note: possible values: `path`, `reason`, `allow-invalid` error: aborting due to 1 previous error diff --git a/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.rs b/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.rs index c69fcd300335f..354206ba1e86c 100644 --- a/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.rs +++ b/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.rs @@ -1,3 +1,4 @@ -//@error-in-other-file: error reading Clippy's configuration file: expected `.`, `=` +//@error-in-other-file: key with no value +//@error-in-other-file: invalid key-value pair fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.stderr b/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.stderr index eaf174b04b492..88e99343365fa 100644 --- a/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.stderr +++ b/src/tools/clippy/tests/ui-toml/bad_toml/conf_bad_toml.stderr @@ -1,8 +1,14 @@ -error: error reading Clippy's configuration file: expected `.`, `=` +error: key with no value, expected `=` --> $DIR/tests/ui-toml/bad_toml/clippy.toml:1:4 | LL | fn this_is_obviously(not: a, toml: file) { | ^ -error: aborting due to 1 previous error +error: invalid key-value pair, expected key + --> $DIR/tests/ui-toml/bad_toml/clippy.toml:2:1 + | +LL | } + | ^ + +error: aborting due to 2 previous errors diff --git a/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.rs b/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.rs index 688c92d8717d1..9aeaa55449e94 100644 --- a/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.rs +++ b/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.rs @@ -1,3 +1,3 @@ -//@error-in-other-file: invalid type: integer `42`, expected a sequence +//@error-in-other-file: expected an array fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.stderr b/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.stderr index 5cf22ac6a227c..cebbb086577e2 100644 --- a/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.stderr +++ b/src/tools/clippy/tests/ui-toml/bad_toml_type/conf_bad_type.stderr @@ -1,4 +1,4 @@ -error: error reading Clippy's configuration file: invalid type: integer `42`, expected a sequence +error: expected an array --> $DIR/tests/ui-toml/bad_toml_type/clippy.toml:1:20 | LL | disallowed-names = 42 diff --git a/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.rs b/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.rs index b28e46af0a467..79d2dd02ead51 100644 --- a/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.rs +++ b/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.rs @@ -1,3 +1,7 @@ +//@no-rustfix +//@error-in-other-file: use of a deprecated field +//@error-in-other-file: use of a deprecated field + fn main() {} #[warn(clippy::cognitive_complexity)] diff --git a/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.stderr b/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.stderr index 95b0508189e9c..f4db7ea4605ab 100644 --- a/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.stderr +++ b/src/tools/clippy/tests/ui-toml/conf_deprecated_key/conf_deprecated_key.stderr @@ -1,17 +1,17 @@ -warning: error reading Clippy's configuration file: deprecated field `cyclomatic-complexity-threshold`. Please use `cognitive-complexity-threshold` instead +warning: use of a deprecated field --> $DIR/tests/ui-toml/conf_deprecated_key/clippy.toml:2:1 | LL | cyclomatic-complexity-threshold = 2 - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use new name: `cognitive-complexity-threshold` -warning: error reading Clippy's configuration file: deprecated field `blacklisted-names`. Please use `disallowed-names` instead +warning: use of a deprecated field --> $DIR/tests/ui-toml/conf_deprecated_key/clippy.toml:3:1 | LL | blacklisted-names = [ "..", "wibble" ] - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^ help: use new name: `disallowed-names` error: the function has a cognitive complexity of (3/2) - --> tests/ui-toml/conf_deprecated_key/conf_deprecated_key.rs:4:4 + --> tests/ui-toml/conf_deprecated_key/conf_deprecated_key.rs:8:4 | LL | fn cognitive_complexity() { | ^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.rs b/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.rs index 187775545ed77..1a275e689276b 100644 --- a/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.rs +++ b/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.rs @@ -1,3 +1,3 @@ -//@error-in-other-file: duplicate key `cognitive-complexity-threshold` +//@error-in-other-file: duplicate key fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.stderr b/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.stderr index 9f11c94ded2bc..ce4c6ce36ee66 100644 --- a/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.stderr +++ b/src/tools/clippy/tests/ui-toml/duplicated_keys/duplicated_keys.stderr @@ -1,8 +1,8 @@ -error: error reading Clippy's configuration file: duplicate key `cognitive-complexity-threshold` in document root +error: duplicate key --> $DIR/tests/ui-toml/duplicated_keys/clippy.toml:2:1 | LL | cognitive-complexity-threshold = 4 - | ^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.rs b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.rs index b5a1f3def61e4..5654d3ae511dd 100644 --- a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.rs +++ b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.rs @@ -1,2 +1,5 @@ -//@error-in-other-file: +//@no-rustfix +//@error-in-other-file: duplicate key in document root +//@error-in-other-file: use of a deprecated field + fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.stderr b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.stderr index 80e700f514b57..5a737df9fef84 100644 --- a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.stderr +++ b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated/duplicated_keys.stderr @@ -1,14 +1,20 @@ -error: error reading Clippy's configuration file: duplicate field `cognitive_complexity_threshold` (provided as `cyclomatic_complexity_threshold`) +warning: use of a deprecated field --> $DIR/tests/ui-toml/duplicated_keys_deprecated/clippy.toml:3:1 | LL | cyclomatic-complexity-threshold = 3 - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use new name: `cognitive-complexity-threshold` -warning: error reading Clippy's configuration file: deprecated field `cyclomatic-complexity-threshold`. Please use `cognitive-complexity-threshold` instead +error: duplicate key in document root --> $DIR/tests/ui-toml/duplicated_keys_deprecated/clippy.toml:3:1 | LL | cyclomatic-complexity-threshold = 3 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: previous definition here + --> $DIR/tests/ui-toml/duplicated_keys_deprecated/clippy.toml:1:1 + | +LL | cognitive-complexity-threshold = 2 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error; 1 warning emitted diff --git a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.rs b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.rs index b5a1f3def61e4..5654d3ae511dd 100644 --- a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.rs +++ b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.rs @@ -1,2 +1,5 @@ -//@error-in-other-file: +//@no-rustfix +//@error-in-other-file: duplicate key in document root +//@error-in-other-file: use of a deprecated field + fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.stderr b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.stderr index 2ca1e35c74498..645f3d861afd2 100644 --- a/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.stderr +++ b/src/tools/clippy/tests/ui-toml/duplicated_keys_deprecated_2/duplicated_keys.stderr @@ -1,14 +1,20 @@ -error: error reading Clippy's configuration file: duplicate field `cognitive-complexity-threshold` - --> $DIR/tests/ui-toml/duplicated_keys_deprecated_2/clippy.toml:4:1 +warning: use of a deprecated field + --> $DIR/tests/ui-toml/duplicated_keys_deprecated_2/clippy.toml:2:1 | -LL | cognitive-complexity-threshold = 4 - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | cyclomatic-complexity-threshold = 3 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use new name: `cognitive-complexity-threshold` -warning: error reading Clippy's configuration file: deprecated field `cyclomatic-complexity-threshold`. Please use `cognitive-complexity-threshold` instead +error: duplicate key in document root --> $DIR/tests/ui-toml/duplicated_keys_deprecated_2/clippy.toml:2:1 | LL | cyclomatic-complexity-threshold = 3 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: previous definition here + --> $DIR/tests/ui-toml/duplicated_keys_deprecated_2/clippy.toml:4:1 + | +LL | cognitive-complexity-threshold = 4 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error; 1 warning emitted diff --git a/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.rs b/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.rs index 85e2fb8c797f8..af2b645fb8a8e 100644 --- a/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.rs +++ b/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.rs @@ -1,4 +1,4 @@ -//@error-in-other-file: not a valid Rust version +//@error-in-other-file: failed to parse rust version #![allow(clippy::redundant_clone)] diff --git a/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.stderr b/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.stderr index 62df5554ccede..da21b02a3b199 100644 --- a/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.stderr +++ b/src/tools/clippy/tests/ui-toml/invalid_min_rust_version/invalid_min_rust_version.stderr @@ -1,4 +1,4 @@ -error: error reading Clippy's configuration file: not a valid Rust version +error: failed to parse rust version --> $DIR/tests/ui-toml/invalid_min_rust_version/clippy.toml:1:8 | LL | msrv = "invalid.version" diff --git a/src/tools/clippy/tests/ui-toml/min_ident_chars/min_ident_chars.stderr b/src/tools/clippy/tests/ui-toml/min_ident_chars/min_ident_chars.stderr index be795f4daff24..5e5ffd3c98fd4 100644 --- a/src/tools/clippy/tests/ui-toml/min_ident_chars/min_ident_chars.stderr +++ b/src/tools/clippy/tests/ui-toml/min_ident_chars/min_ident_chars.stderr @@ -1,49 +1,50 @@ -error: this ident is too short (1 <= 3) +error: this identifier is 3 characters too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:6:41 | LL | use extern_types::{Aaa, LONGER, M, N as W}; | ^ | + = note: the configured threshold is 3 = note: `-D clippy::min-ident-chars` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::min_ident_chars)]` -error: this ident is too short (1 <= 3) +error: this identifier is 3 characters too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:9:11 | LL | pub const N: u32 = 0; | ^ -error: this ident is too short (3 <= 3) +error: this identifier is 1 character too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:15:5 | LL | aaa: Aaa, | ^^^ -error: this ident is too short (3 <= 3) +error: this identifier is 1 character too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:21:9 | LL | let vvv = 1; | ^^^ -error: this ident is too short (3 <= 3) +error: this identifier is 1 character too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:23:9 | LL | let uuu = 1; | ^^^ -error: this ident is too short (1 <= 3) +error: this identifier is 3 characters too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:25:14 | LL | let (mut a, mut b) = (1, 2); | ^ -error: this ident is too short (1 <= 3) +error: this identifier is 3 characters too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:25:21 | LL | let (mut a, mut b) = (1, 2); | ^ -error: this ident is too short (1 <= 3) +error: this identifier is 3 characters too short --> tests/ui-toml/min_ident_chars/min_ident_chars.rs:28:9 | LL | for i in 0..1000 {} diff --git a/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/clippy.toml b/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/clippy.toml new file mode 100644 index 0000000000000..a823740d71ef5 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/clippy.toml @@ -0,0 +1 @@ +min-ident-chars-lint-trait-impl = true diff --git a/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs b/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs new file mode 100644 index 0000000000000..786e0c1da0434 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs @@ -0,0 +1,24 @@ +#![warn(clippy::min_ident_chars)] + +trait ShortParams { + fn f(g: i32); + //~^ min_ident_chars + //~| min_ident_chars +} + +struct MyStruct; + +impl ShortParams for MyStruct { + fn f(g: i32) {} + //~^ min_ident_chars + //~| min_ident_chars +} + +impl core::fmt::Display for MyStruct { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + //~^ min_ident_chars + write!(f, "MyStruct") + } +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.stderr b/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.stderr new file mode 100644 index 0000000000000..b483a21f37b47 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.stderr @@ -0,0 +1,37 @@ +error: this identifier consists of only a single character + --> tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs:4:10 + | +LL | fn f(g: i32); + | ^ + | + = note: `-D clippy::min-ident-chars` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::min_ident_chars)]` + +error: this identifier consists of only a single character + --> tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs:4:8 + | +LL | fn f(g: i32); + | ^ + +error: this identifier consists of only a single character + --> tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs:12:10 + | +LL | fn f(g: i32) {} + | ^ + | + = note: the configured threshold is 1 + +error: this identifier consists of only a single character + --> tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs:12:8 + | +LL | fn f(g: i32) {} + | ^ + +error: this identifier consists of only a single character + --> tests/ui-toml/min_ident_chars_trait_impl/min_ident_chars.rs:18:19 + | +LL | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + | ^ + +error: aborting due to 5 previous errors + diff --git a/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.fixed b/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.fixed index 3683e826aa925..07d7bc55d9183 100644 --- a/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.fixed +++ b/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.fixed @@ -15,10 +15,11 @@ proc_macro_derive::foo_bar!(); #[rustfmt::skip] macro_rules! test { - () => { + () => {{ + //~v nonstandard_macro_braces vec![0, 0, 0] //~^ nonstandard_macro_braces - }; + }}; } #[rustfmt::skip] diff --git a/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs b/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs index c1779dceff172..9ec181c3fbd45 100644 --- a/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs +++ b/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs @@ -15,10 +15,11 @@ proc_macro_derive::foo_bar!(); #[rustfmt::skip] macro_rules! test { - () => { + () => {{ + //~v nonstandard_macro_braces vec!{0, 0, 0} //~^ nonstandard_macro_braces - }; + }}; } #[rustfmt::skip] diff --git a/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr b/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr index 2488f7fa01e5b..de6d5e7cc243d 100644 --- a/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr +++ b/src/tools/clippy/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr @@ -1,88 +1,91 @@ error: use of irregular braces for `vec!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:45:13 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:20:9 | -LL | let _ = vec! {1, 2, 3}; - | ^^^^^^^^^^^^^^ help: consider writing: `vec![1, 2, 3]` +LL | vec!{0, 0, 0} + | ^^^^^^^^^^^^^ help: consider writing: `vec![0, 0, 0]` | = note: `-D clippy::nonstandard-macro-braces` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::nonstandard_macro_braces)]` +error: use of irregular braces for `vec!` macro + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:46:13 + | +LL | let _ = vec! {1, 2, 3}; + | ^^^^^^^^^^^^^^ help: consider writing: `vec![1, 2, 3]` + error: use of irregular braces for `format!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:47:13 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:48:13 | LL | let _ = format!["ugh {} stop being such a good compiler", "hello"]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider writing: `format!("ugh {} stop being such a good compiler", "hello")` error: use of irregular braces for `matches!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:49:13 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:50:13 | LL | let _ = matches!{{}, ()}; | ^^^^^^^^^^^^^^^^ help: consider writing: `matches!({}, ())` error: use of irregular braces for `quote!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:51:13 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:52:13 | LL | let _ = quote!(let x = 1;); | ^^^^^^^^^^^^^^^^^^ help: consider writing: `quote!{let x = 1;}` error: use of irregular braces for `quote::quote!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:53:13 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:54:13 | LL | let _ = quote::quote!(match match match); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider writing: `quote::quote!{match match match}` -error: use of irregular braces for `vec!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:19:9 - | -LL | vec!{0, 0, 0} - | ^^^^^^^^^^^^^ help: consider writing: `vec![0, 0, 0]` -... -LL | let _ = test!(); // trigger when macro def is inside our own crate - | ------- in this macro invocation - | - = note: this error originates in the macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) - error: use of irregular braces for `type_pos!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:63:12 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:64:12 | LL | let _: type_pos!(usize) = vec![]; | ^^^^^^^^^^^^^^^^ help: consider writing: `type_pos![usize]` error: use of irregular braces for `eprint!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:66:5 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:67:5 | LL | eprint!("test if user config overrides defaults"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider writing: `eprint!["test if user config overrides defaults"]` error: use of irregular braces for `println!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:75:5 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:76:5 | LL | println! {"hello world"} | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider writing: `println!("hello world");` error: use of irregular braces for `println!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:83:5 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:84:5 | LL | println![]; | ^^^^^^^^^^ help: consider writing: `println!()` error: use of irregular braces for `println!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:85:5 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:86:5 | LL | println![""]; | ^^^^^^^^^^^^ help: consider writing: `println!("")` error: use of irregular braces for `println!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:87:5 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:88:5 | LL | println! {}; | ^^^^^^^^^^^ help: consider writing: `println!()` error: use of irregular braces for `println!` macro - --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:89:5 + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:90:5 | LL | println! {""}; | ^^^^^^^^^^^^^ help: consider writing: `println!("")` -error: aborting due to 13 previous errors +error: use of irregular braces for `vec!` macro + --> tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs:20:9 + | +LL | vec!{0, 0, 0} + | ^^^^^^^^^^^^^ help: consider writing: `vec![0, 0, 0]` + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 14 previous errors diff --git a/src/tools/clippy/tests/ui-toml/toml_invalid_path/conf_invalid_path.stderr b/src/tools/clippy/tests/ui-toml/toml_invalid_path/conf_invalid_path.stderr index 59a427dc99cae..f5126d88a9c60 100644 --- a/src/tools/clippy/tests/ui-toml/toml_invalid_path/conf_invalid_path.stderr +++ b/src/tools/clippy/tests/ui-toml/toml_invalid_path/conf_invalid_path.stderr @@ -1,36 +1,32 @@ warning: expected a macro, found a primitive type - --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:1:1 + --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:2:8 | -LL | / [[disallowed-macros]] -LL | | path = "bool" - | |_____________^ +LL | path = "bool" + | ^^^^^^ | = help: add `allow-invalid = true` to the entry to suppress this warning warning: `std::process::current_exe` does not refer to a reachable function - --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:4:1 + --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:5:8 | -LL | / [[disallowed-methods]] -LL | | path = "std::process::current_exe" - | |__________________________________^ +LL | path = "std::process::current_exe" + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: add `allow-invalid = true` to the entry to suppress this warning warning: `` does not refer to a reachable function - --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:7:1 + --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:8:8 | -LL | / [[disallowed-methods]] -LL | | path = "" - | |_________^ +LL | path = "" + | ^^ | = help: add `allow-invalid = true` to the entry to suppress this warning warning: expected a type, found a variant - --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:10:1 + --> $DIR/tests/ui-toml/toml_invalid_path/clippy.toml:11:8 | -LL | / [[disallowed-types]] -LL | | path = "std::result::Result::Err" - | |_________________________________^ +LL | path = "std::result::Result::Err" + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: add `allow-invalid = true` to the entry to suppress this warning diff --git a/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.rs b/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.rs index 9c770c31f6f8d..e18573e6c7b16 100644 --- a/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.rs +++ b/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.rs @@ -1,5 +1,5 @@ #[rustfmt::skip] -//@error-in-other-file: error reading Clippy's configuration file: data did not match any variant of untagged enum DisallowedPathEnum +//@error-in-other-file: unknown key fn main() { panic!(); } diff --git a/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.stderr b/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.stderr index b564709721d5c..1b4175d5cd4c9 100644 --- a/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.stderr +++ b/src/tools/clippy/tests/ui-toml/toml_unknown_config_struct_field/toml_unknown_config_struct_field.stderr @@ -1,8 +1,10 @@ -error: error reading Clippy's configuration file: data did not match any variant of untagged enum DisallowedPathEnum - --> $DIR/tests/ui-toml/toml_unknown_config_struct_field/clippy.toml:3:5 +error: unknown key + --> $DIR/tests/ui-toml/toml_unknown_config_struct_field/clippy.toml:3:28 | LL | { path = "std::panic", recommendation = "return a `std::result::Result::Error` instead" }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^ + | + = note: possible values: `path`, `reason`, `replacement`, `allow-invalid` error: aborting due to 1 previous error diff --git a/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.rs b/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.rs index 8d02924c9d93f..c9d951c337e78 100644 --- a/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.rs +++ b/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.rs @@ -1,6 +1,6 @@ //@no-rustfix -//@error-in-other-file: unknown field -//@error-in-other-file: error reading Clippy -//@error-in-other-file: error reading Clippy +//@error-in-other-file: unknown field name +//@error-in-other-file: unknown field name +//@error-in-other-file: unknown field name fn main() {} diff --git a/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr b/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr index 528e2f1089c04..bee9e63ef7428 100644 --- a/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr +++ b/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr @@ -1,106 +1,10 @@ -error: error reading Clippy's configuration file: unknown field `foobar`, expected one of - absolute-paths-allowed-crates - absolute-paths-max-segments - accept-comment-above-attributes - accept-comment-above-statement - allow-comparison-to-zero - allow-dbg-in-tests - allow-exact-repetitions - allow-expect-in-consts - allow-expect-in-tests - allow-indexing-slicing-in-tests - allow-large-stack-frames-in-tests - allow-mixed-uninlined-format-args - allow-one-hash-in-raw-strings - allow-panic-in-tests - allow-print-in-tests - allow-private-module-inception - allow-renamed-params-for - allow-unwrap-in-consts - allow-unwrap-in-tests - allow-unwrap-types - allow-useless-vec-in-tests - allowed-dotfiles - allowed-duplicate-crates - allowed-idents-below-min-chars - allowed-prefixes - allowed-scripts - allowed-wildcard-imports - arithmetic-side-effects-allowed - arithmetic-side-effects-allowed-binary - arithmetic-side-effects-allowed-unary - array-size-threshold - avoid-breaking-exported-api - await-holding-invalid-types - cargo-ignore-publish - check-grouped-late-init - check-incompatible-msrv-in-tests - check-inconsistent-struct-field-initializers - check-private-items - cognitive-complexity-threshold - const-literal-digits-threshold - disallowed-fields - disallowed-macros - disallowed-methods - disallowed-names - disallowed-types - doc-valid-idents - enable-raw-pointer-heuristic-for-send - enforce-iter-loop-reborrow - enforced-import-renames - enum-variant-name-threshold - enum-variant-size-threshold - excessive-nesting-threshold - future-size-threshold - ignore-interior-mutability - inherent-impl-lint-scope - large-error-ignored - large-error-threshold - lint-commented-code - literal-representation-threshold - matches-for-let-else - max-fn-params-bools - max-include-file-size - max-struct-bools - max-suggested-slice-pattern-length - max-trait-bounds - min-ident-chars-threshold - missing-docs-allow-unused - missing-docs-in-crate-items - module-item-order-groupings - module-items-ordered-within-groupings - msrv - pass-by-value-size-limit - pub-underscore-fields-behavior - recursive-self-in-type-definitions - semicolon-inside-block-ignore-singleline - semicolon-outside-block-ignore-multiline - single-char-binding-names-threshold - source-item-ordering - stack-size-threshold - standard-macro-braces - struct-field-name-threshold - suppress-restriction-lint-in-const - third-party - too-large-for-stack - too-many-arguments-threshold - too-many-lines-threshold - trait-assoc-item-kinds-order - trivial-copy-size-limit - type-complexity-threshold - unnecessary-box-size - unreadable-literal-lint-fractions - upper-case-acronyms-aggressive - vec-box-size-threshold - verbose-bit-mask-threshold - warn-on-all-wildcard-imports - warn-unsafe-macro-metavars-in-private-macros +error: unknown field name --> $DIR/tests/ui-toml/toml_unknown_key/clippy.toml:2:1 | LL | foobar = 42 | ^^^^^^ - -error: error reading Clippy's configuration file: unknown field `barfoo`, expected one of + | + = note: possible values: absolute-paths-allowed-crates absolute-paths-max-segments accept-comment-above-attributes @@ -166,6 +70,7 @@ error: error reading Clippy's configuration file: unknown field `barfoo`, expect max-struct-bools max-suggested-slice-pattern-length max-trait-bounds + min-ident-chars-lint-trait-impl min-ident-chars-threshold missing-docs-allow-unused missing-docs-in-crate-items @@ -183,11 +88,11 @@ error: error reading Clippy's configuration file: unknown field `barfoo`, expect standard-macro-braces struct-field-name-threshold suppress-restriction-lint-in-const - third-party too-large-for-stack too-many-arguments-threshold too-many-lines-threshold trait-assoc-item-kinds-order + trait-impl-item-order trivial-copy-size-limit type-complexity-threshold unnecessary-box-size @@ -197,112 +102,19 @@ error: error reading Clippy's configuration file: unknown field `barfoo`, expect verbose-bit-mask-threshold warn-on-all-wildcard-imports warn-unsafe-macro-metavars-in-private-macros + third-party + +error: unknown field name --> $DIR/tests/ui-toml/toml_unknown_key/clippy.toml:4:1 | LL | barfoo = 53 | ^^^^^^ -error: error reading Clippy's configuration file: unknown field `allow_mixed_uninlined_format_args`, expected one of - absolute-paths-allowed-crates - absolute-paths-max-segments - accept-comment-above-attributes - accept-comment-above-statement - allow-comparison-to-zero - allow-dbg-in-tests - allow-exact-repetitions - allow-expect-in-consts - allow-expect-in-tests - allow-indexing-slicing-in-tests - allow-large-stack-frames-in-tests - allow-mixed-uninlined-format-args - allow-one-hash-in-raw-strings - allow-panic-in-tests - allow-print-in-tests - allow-private-module-inception - allow-renamed-params-for - allow-unwrap-in-consts - allow-unwrap-in-tests - allow-unwrap-types - allow-useless-vec-in-tests - allowed-dotfiles - allowed-duplicate-crates - allowed-idents-below-min-chars - allowed-prefixes - allowed-scripts - allowed-wildcard-imports - arithmetic-side-effects-allowed - arithmetic-side-effects-allowed-binary - arithmetic-side-effects-allowed-unary - array-size-threshold - avoid-breaking-exported-api - await-holding-invalid-types - cargo-ignore-publish - check-grouped-late-init - check-incompatible-msrv-in-tests - check-inconsistent-struct-field-initializers - check-private-items - cognitive-complexity-threshold - const-literal-digits-threshold - disallowed-fields - disallowed-macros - disallowed-methods - disallowed-names - disallowed-types - doc-valid-idents - enable-raw-pointer-heuristic-for-send - enforce-iter-loop-reborrow - enforced-import-renames - enum-variant-name-threshold - enum-variant-size-threshold - excessive-nesting-threshold - future-size-threshold - ignore-interior-mutability - inherent-impl-lint-scope - large-error-ignored - large-error-threshold - lint-commented-code - literal-representation-threshold - matches-for-let-else - max-fn-params-bools - max-include-file-size - max-struct-bools - max-suggested-slice-pattern-length - max-trait-bounds - min-ident-chars-threshold - missing-docs-allow-unused - missing-docs-in-crate-items - module-item-order-groupings - module-items-ordered-within-groupings - msrv - pass-by-value-size-limit - pub-underscore-fields-behavior - recursive-self-in-type-definitions - semicolon-inside-block-ignore-singleline - semicolon-outside-block-ignore-multiline - single-char-binding-names-threshold - source-item-ordering - stack-size-threshold - standard-macro-braces - struct-field-name-threshold - suppress-restriction-lint-in-const - third-party - too-large-for-stack - too-many-arguments-threshold - too-many-lines-threshold - trait-assoc-item-kinds-order - trivial-copy-size-limit - type-complexity-threshold - unnecessary-box-size - unreadable-literal-lint-fractions - upper-case-acronyms-aggressive - vec-box-size-threshold - verbose-bit-mask-threshold - warn-on-all-wildcard-imports - warn-unsafe-macro-metavars-in-private-macros +error: unknown field name --> $DIR/tests/ui-toml/toml_unknown_key/clippy.toml:7:1 | LL | allow_mixed_uninlined_format_args = true - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: perhaps you meant: `allow-mixed-uninlined-format-args` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: did you mean: `allow-mixed-uninlined-format-args` error: aborting due to 3 previous errors diff --git a/src/tools/clippy/tests/ui-toml/toml_unloaded_crate/conf_unloaded_crate.stderr b/src/tools/clippy/tests/ui-toml/toml_unloaded_crate/conf_unloaded_crate.stderr index e5fd548b26df4..cdb6a3fe65eb7 100644 --- a/src/tools/clippy/tests/ui-toml/toml_unloaded_crate/conf_unloaded_crate.stderr +++ b/src/tools/clippy/tests/ui-toml/toml_unloaded_crate/conf_unloaded_crate.stderr @@ -1,18 +1,16 @@ warning: `regex::Regex::new_` does not refer to a reachable function - --> $DIR/tests/ui-toml/toml_unloaded_crate/clippy.toml:3:1 + --> $DIR/tests/ui-toml/toml_unloaded_crate/clippy.toml:4:8 | -LL | / [[disallowed-methods]] -LL | | path = "regex::Regex::new_" - | |___________________________^ +LL | path = "regex::Regex::new_" + | ^^^^^^^^^^^^^^^^^^^^ | = help: add `allow-invalid = true` to the entry to suppress this warning warning: `regex::Regex_::new` does not refer to a reachable function - --> $DIR/tests/ui-toml/toml_unloaded_crate/clippy.toml:6:1 + --> $DIR/tests/ui-toml/toml_unloaded_crate/clippy.toml:7:8 | -LL | / [[disallowed-methods]] -LL | | path = "regex::Regex_::new" - | |___________________________^ +LL | path = "regex::Regex_::new" + | ^^^^^^^^^^^^^^^^^^^^ | = help: add `allow-invalid = true` to the entry to suppress this warning diff --git a/src/tools/clippy/tests/ui/approx_const.rs b/src/tools/clippy/tests/ui/approx_const.rs index fc493421a165c..1771b162e6c55 100644 --- a/src/tools/clippy/tests/ui/approx_const.rs +++ b/src/tools/clippy/tests/ui/approx_const.rs @@ -107,6 +107,22 @@ fn main() { let no_tau = 6.3; + let my_euler_gamma = 0.577215664901533; + //~^ approx_constant + + let almost_euler_gamma = 0.5772; + //~^ approx_constant + + let no_euler_gamma = 0.577; + + let my_golden_ratio = 1.618033988749895; + //~^ approx_constant + + let almost_golden_ratio = 1.6180; + //~^ approx_constant + + let no_almost_golden_ratio = 1.618; + // issue #15194 #[allow(clippy::excessive_precision)] let x: f64 = 3.1415926535897932384626433832; diff --git a/src/tools/clippy/tests/ui/approx_const.stderr b/src/tools/clippy/tests/ui/approx_const.stderr index 32a3517ff2e41..dc5efab9d6397 100644 --- a/src/tools/clippy/tests/ui/approx_const.stderr +++ b/src/tools/clippy/tests/ui/approx_const.stderr @@ -184,8 +184,40 @@ LL | let almost_tau = 6.28; | = help: consider using the constant directly +error: approximate value of `f{32, 64}::consts::EULER_GAMMA` found + --> tests/ui/approx_const.rs:110:26 + | +LL | let my_euler_gamma = 0.577215664901533; + | ^^^^^^^^^^^^^^^^^ + | + = help: consider using the constant directly + +error: approximate value of `f{32, 64}::consts::EULER_GAMMA` found + --> tests/ui/approx_const.rs:113:30 + | +LL | let almost_euler_gamma = 0.5772; + | ^^^^^^ + | + = help: consider using the constant directly + +error: approximate value of `f{32, 64}::consts::GOLDEN_RATIO` found + --> tests/ui/approx_const.rs:118:27 + | +LL | let my_golden_ratio = 1.618033988749895; + | ^^^^^^^^^^^^^^^^^ + | + = help: consider using the constant directly + +error: approximate value of `f{32, 64}::consts::GOLDEN_RATIO` found + --> tests/ui/approx_const.rs:121:31 + | +LL | let almost_golden_ratio = 1.6180; + | ^^^^^^ + | + = help: consider using the constant directly + error: approximate value of `f{32, 64}::consts::PI` found - --> tests/ui/approx_const.rs:112:18 + --> tests/ui/approx_const.rs:128:18 | LL | let x: f64 = 3.1415926535897932384626433832; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -193,7 +225,7 @@ LL | let x: f64 = 3.1415926535897932384626433832; = help: consider using the constant directly error: approximate value of `f{32, 64}::consts::PI` found - --> tests/ui/approx_const.rs:116:18 + --> tests/ui/approx_const.rs:132:18 | LL | let _: f64 = 003.14159265358979311599796346854418516159057617187500; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -201,7 +233,7 @@ LL | let _: f64 = 003.14159265358979311599796346854418516159057617187500; = help: consider using the constant directly error: approximate value of `f{32, 64}::consts::FRAC_1_SQRT_2` found - --> tests/ui/approx_const.rs:119:32 + --> tests/ui/approx_const.rs:135:32 | LL | let almost_frac_1_sqrt_2 = 00.70711; | ^^^^^^^^ @@ -209,12 +241,12 @@ LL | let almost_frac_1_sqrt_2 = 00.70711; = help: consider using the constant directly error: approximate value of `f{32, 64}::consts::FRAC_1_SQRT_2` found - --> tests/ui/approx_const.rs:122:32 + --> tests/ui/approx_const.rs:138:32 | LL | let almost_frac_1_sqrt_2 = 00.707_11; | ^^^^^^^^^ | = help: consider using the constant directly -error: aborting due to 27 previous errors +error: aborting due to 31 previous errors diff --git a/src/tools/clippy/tests/ui/assert_is_empty.fixed b/src/tools/clippy/tests/ui/assert_is_empty.fixed new file mode 100644 index 0000000000000..4b15274d41ed5 --- /dev/null +++ b/src/tools/clippy/tests/ui/assert_is_empty.fixed @@ -0,0 +1,112 @@ +#![warn(clippy::assert_is_empty)] +#![expect(clippy::needless_ifs, clippy::useless_vec)] +#![allow(clippy::const_is_empty)] + +fn main() { + let vec = vec![1, 2, 3]; + assert_eq!(vec, [] as [i32; 0]); + //~^ assert_is_empty + assert_ne!(vec, [] as [i32; 0]); + //~^ assert_is_empty + debug_assert_eq!(vec, [] as [i32; 0]); + //~^ assert_is_empty + debug_assert_ne!(vec, [] as [i32; 0]); + //~^ assert_is_empty + + let vec_ref = &vec; + assert_eq!(vec_ref.as_slice(), []); + //~^ assert_is_empty + assert_ne!(vec_ref.as_slice(), []); + //~^ assert_is_empty + + let vec_mut_ref = &mut vec![1, 2, 3]; + assert_eq!(vec_mut_ref.as_slice(), []); + //~^ assert_is_empty + + let slice: &[i32] = &[1, 2, 3]; + assert_eq!(slice, []); + //~^ assert_is_empty + assert_ne!(slice, []); + //~^ assert_is_empty + + let array = [1, 2, 3]; + assert_eq!(array.as_slice(), []); + //~^ assert_is_empty + assert_ne!(array.as_slice(), []); + //~^ assert_is_empty + + let array_ref = &array; + assert_eq!(array_ref.as_slice(), []); + //~^ assert_is_empty + + let string = String::from("foo"); + assert_eq!(string, ""); + //~^ assert_is_empty + assert_ne!(string, ""); + //~^ assert_is_empty + + let str_ref = "foo"; + assert_eq!(str_ref, ""); + //~^ assert_is_empty + assert_ne!(str_ref, ""); + //~^ assert_is_empty + + // Don't lint: has assert message. + assert!(vec.is_empty(), "items should be empty"); + assert!(!vec.is_empty(), "items should not be empty"); + assert!(vec.is_empty(), "unexpected values: {vec:?}"); + assert!(!vec.is_empty(), "unexpected values: {vec:?}"); + + // Common chained assertion shape. The first assertion can hide the value + // that the second assertion would otherwise help diagnose. + let items = vec!["baz"]; + assert_ne!(items, [] as [&str; 0]); + //~^ assert_is_empty + assert_eq!(items[0], "bar"); + + // Don't lint: the outer `assert!` is written here, but the condition comes + // from a macro expansion. Rewriting the expanded condition span would make + // the suggestion point at generated code rather than source code. + macro_rules! is_empty { + ($value:expr) => { + $value.is_empty() + }; + } + assert!(is_empty!(vec)); + + // Don't lint: the `assert!` itself comes from a macro expansion. The lint + // only rewrites assert calls that are present at the call site. + macro_rules! assert_empty { + ($value:expr) => { + assert!($value.is_empty()) + }; + } + assert_empty!(vec); + + // Don't lint: not an assert macro. + if vec.is_empty() {} + if !vec.is_empty() {} + + // Don't lint: maps do not have a compact empty literal suggestion. This is + // a conservative call; comparing against `HashMap::new()` may be worth + // revisiting if the type inference cost and constructor path are acceptable + // for aliases, custom hashers, and similar map types. + let map = std::collections::HashMap::::new(); + assert!(map.is_empty()); + assert!(!map.is_empty()); + + // Don't lint: assert_eq! would require Debug and PartialEq for the element type. + struct NotDebugOrPartialEq; + let not_debug_or_partial_eq = vec![NotDebugOrPartialEq]; + assert!(not_debug_or_partial_eq.is_empty()); + + #[derive(Debug)] + struct NotPartialEq; + let not_partial_eq = vec![NotPartialEq]; + assert!(not_partial_eq.is_empty()); + + #[derive(PartialEq)] + struct NotDebug; + let not_debug = vec![NotDebug]; + assert!(not_debug.is_empty()); +} diff --git a/src/tools/clippy/tests/ui/assert_is_empty.rs b/src/tools/clippy/tests/ui/assert_is_empty.rs new file mode 100644 index 0000000000000..8545e1a186353 --- /dev/null +++ b/src/tools/clippy/tests/ui/assert_is_empty.rs @@ -0,0 +1,112 @@ +#![warn(clippy::assert_is_empty)] +#![expect(clippy::needless_ifs, clippy::useless_vec)] +#![allow(clippy::const_is_empty)] + +fn main() { + let vec = vec![1, 2, 3]; + assert!(vec.is_empty()); + //~^ assert_is_empty + assert!(!vec.is_empty()); + //~^ assert_is_empty + debug_assert!(vec.is_empty()); + //~^ assert_is_empty + debug_assert!(!vec.is_empty()); + //~^ assert_is_empty + + let vec_ref = &vec; + assert!(vec_ref.is_empty()); + //~^ assert_is_empty + assert!(!vec_ref.is_empty()); + //~^ assert_is_empty + + let vec_mut_ref = &mut vec![1, 2, 3]; + assert!(vec_mut_ref.is_empty()); + //~^ assert_is_empty + + let slice: &[i32] = &[1, 2, 3]; + assert!(slice.is_empty()); + //~^ assert_is_empty + assert!(!slice.is_empty()); + //~^ assert_is_empty + + let array = [1, 2, 3]; + assert!(array.is_empty()); + //~^ assert_is_empty + assert!(!array.is_empty()); + //~^ assert_is_empty + + let array_ref = &array; + assert!(array_ref.is_empty()); + //~^ assert_is_empty + + let string = String::from("foo"); + assert!(string.is_empty()); + //~^ assert_is_empty + assert!(!string.is_empty()); + //~^ assert_is_empty + + let str_ref = "foo"; + assert!(str_ref.is_empty()); + //~^ assert_is_empty + assert!(!str_ref.is_empty()); + //~^ assert_is_empty + + // Don't lint: has assert message. + assert!(vec.is_empty(), "items should be empty"); + assert!(!vec.is_empty(), "items should not be empty"); + assert!(vec.is_empty(), "unexpected values: {vec:?}"); + assert!(!vec.is_empty(), "unexpected values: {vec:?}"); + + // Common chained assertion shape. The first assertion can hide the value + // that the second assertion would otherwise help diagnose. + let items = vec!["baz"]; + assert!(!items.is_empty()); + //~^ assert_is_empty + assert_eq!(items[0], "bar"); + + // Don't lint: the outer `assert!` is written here, but the condition comes + // from a macro expansion. Rewriting the expanded condition span would make + // the suggestion point at generated code rather than source code. + macro_rules! is_empty { + ($value:expr) => { + $value.is_empty() + }; + } + assert!(is_empty!(vec)); + + // Don't lint: the `assert!` itself comes from a macro expansion. The lint + // only rewrites assert calls that are present at the call site. + macro_rules! assert_empty { + ($value:expr) => { + assert!($value.is_empty()) + }; + } + assert_empty!(vec); + + // Don't lint: not an assert macro. + if vec.is_empty() {} + if !vec.is_empty() {} + + // Don't lint: maps do not have a compact empty literal suggestion. This is + // a conservative call; comparing against `HashMap::new()` may be worth + // revisiting if the type inference cost and constructor path are acceptable + // for aliases, custom hashers, and similar map types. + let map = std::collections::HashMap::::new(); + assert!(map.is_empty()); + assert!(!map.is_empty()); + + // Don't lint: assert_eq! would require Debug and PartialEq for the element type. + struct NotDebugOrPartialEq; + let not_debug_or_partial_eq = vec![NotDebugOrPartialEq]; + assert!(not_debug_or_partial_eq.is_empty()); + + #[derive(Debug)] + struct NotPartialEq; + let not_partial_eq = vec![NotPartialEq]; + assert!(not_partial_eq.is_empty()); + + #[derive(PartialEq)] + struct NotDebug; + let not_debug = vec![NotDebug]; + assert!(not_debug.is_empty()); +} diff --git a/src/tools/clippy/tests/ui/assert_is_empty.stderr b/src/tools/clippy/tests/ui/assert_is_empty.stderr new file mode 100644 index 0000000000000..36316c1baec89 --- /dev/null +++ b/src/tools/clippy/tests/ui/assert_is_empty.stderr @@ -0,0 +1,208 @@ +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:7:5 + | +LL | assert!(vec.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `-D clippy::assert-is-empty` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::assert_is_empty)]` +help: use `assert_eq!` to show the value on failure + | +LL - assert!(vec.is_empty()); +LL + assert_eq!(vec, [] as [i32; 0]); + | + +error: used `assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:9:5 + | +LL | assert!(!vec.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_ne!` to show the value on failure + | +LL - assert!(!vec.is_empty()); +LL + assert_ne!(vec, [] as [i32; 0]); + | + +error: used `debug_assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:11:5 + | +LL | debug_assert!(vec.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `debug_assert_eq!` to show the value on failure + | +LL - debug_assert!(vec.is_empty()); +LL + debug_assert_eq!(vec, [] as [i32; 0]); + | + +error: used `debug_assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:13:5 + | +LL | debug_assert!(!vec.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `debug_assert_ne!` to show the value on failure + | +LL - debug_assert!(!vec.is_empty()); +LL + debug_assert_ne!(vec, [] as [i32; 0]); + | + +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:17:5 + | +LL | assert!(vec_ref.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_eq!` to show the value on failure + | +LL - assert!(vec_ref.is_empty()); +LL + assert_eq!(vec_ref.as_slice(), []); + | + +error: used `assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:19:5 + | +LL | assert!(!vec_ref.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_ne!` to show the value on failure + | +LL - assert!(!vec_ref.is_empty()); +LL + assert_ne!(vec_ref.as_slice(), []); + | + +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:23:5 + | +LL | assert!(vec_mut_ref.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_eq!` to show the value on failure + | +LL - assert!(vec_mut_ref.is_empty()); +LL + assert_eq!(vec_mut_ref.as_slice(), []); + | + +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:27:5 + | +LL | assert!(slice.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_eq!` to show the value on failure + | +LL - assert!(slice.is_empty()); +LL + assert_eq!(slice, []); + | + +error: used `assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:29:5 + | +LL | assert!(!slice.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_ne!` to show the value on failure + | +LL - assert!(!slice.is_empty()); +LL + assert_ne!(slice, []); + | + +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:33:5 + | +LL | assert!(array.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_eq!` to show the value on failure + | +LL - assert!(array.is_empty()); +LL + assert_eq!(array.as_slice(), []); + | + +error: used `assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:35:5 + | +LL | assert!(!array.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_ne!` to show the value on failure + | +LL - assert!(!array.is_empty()); +LL + assert_ne!(array.as_slice(), []); + | + +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:39:5 + | +LL | assert!(array_ref.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_eq!` to show the value on failure + | +LL - assert!(array_ref.is_empty()); +LL + assert_eq!(array_ref.as_slice(), []); + | + +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:43:5 + | +LL | assert!(string.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_eq!` to show the value on failure + | +LL - assert!(string.is_empty()); +LL + assert_eq!(string, ""); + | + +error: used `assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:45:5 + | +LL | assert!(!string.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_ne!` to show the value on failure + | +LL - assert!(!string.is_empty()); +LL + assert_ne!(string, ""); + | + +error: used `assert!` to check that a value is empty + --> tests/ui/assert_is_empty.rs:49:5 + | +LL | assert!(str_ref.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_eq!` to show the value on failure + | +LL - assert!(str_ref.is_empty()); +LL + assert_eq!(str_ref, ""); + | + +error: used `assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:51:5 + | +LL | assert!(!str_ref.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_ne!` to show the value on failure + | +LL - assert!(!str_ref.is_empty()); +LL + assert_ne!(str_ref, ""); + | + +error: used `assert!` to check that a value is not empty + --> tests/ui/assert_is_empty.rs:63:5 + | +LL | assert!(!items.is_empty()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use `assert_ne!` to show the value on failure + | +LL - assert!(!items.is_empty()); +LL + assert_ne!(items, [] as [&str; 0]); + | + +error: aborting due to 17 previous errors + diff --git a/src/tools/clippy/tests/ui/auxiliary/non-exhaustive-struct.rs b/src/tools/clippy/tests/ui/auxiliary/non-exhaustive-struct.rs new file mode 100644 index 0000000000000..ed28cc0ebd45a --- /dev/null +++ b/src/tools/clippy/tests/ui/auxiliary/non-exhaustive-struct.rs @@ -0,0 +1,13 @@ +#[non_exhaustive] +#[derive(Default)] +pub struct NonExhaustiveStruct { + pub field1: i32, + pub field2: i32, + _private: i32, +} + +#[non_exhaustive] +#[derive(Default)] +pub struct NonExhaustiveStructNoPrivateFields { + pub field: i32, +} diff --git a/src/tools/clippy/tests/ui/big_endian_bytes.1.fixed b/src/tools/clippy/tests/ui/big_endian_bytes.1.fixed new file mode 100644 index 0000000000000..138899d4cc6e4 --- /dev/null +++ b/src/tools/clippy/tests/ui/big_endian_bytes.1.fixed @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::big_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_ne_bytes(); //~ big_endian_bytes + let _ = 0u16.to_ne_bytes(); //~ big_endian_bytes + let _ = 0u32.to_ne_bytes(); //~ big_endian_bytes + let _ = 0u64.to_ne_bytes(); //~ big_endian_bytes + let _ = 0u128.to_ne_bytes(); //~ big_endian_bytes + let _ = 0usize.to_ne_bytes(); //~ big_endian_bytes + + let _ = 0i8.to_ne_bytes(); //~ big_endian_bytes + let _ = 0i16.to_ne_bytes(); //~ big_endian_bytes + let _ = 0i32.to_ne_bytes(); //~ big_endian_bytes + let _ = 0i64.to_ne_bytes(); //~ big_endian_bytes + let _ = 0i128.to_ne_bytes(); //~ big_endian_bytes + let _ = 0isize.to_ne_bytes(); //~ big_endian_bytes + + let _ = 0f16.to_ne_bytes(); //~ big_endian_bytes + let _ = 0f32.to_ne_bytes(); //~ big_endian_bytes + let _ = 0f64.to_ne_bytes(); //~ big_endian_bytes + let _ = 0f128.to_ne_bytes(); //~ big_endian_bytes + + let _ = u8::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = u16::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = u32::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = u64::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = u128::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = usize::from_ne_bytes([0; _]); //~ big_endian_bytes + + let _ = i8::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = i16::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = i32::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = i64::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = i128::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = isize::from_ne_bytes([0; _]); //~ big_endian_bytes + + let _ = f16::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = f32::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = f64::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = f128::from_ne_bytes([0; _]); //~ big_endian_bytes + }; + + { + let _ = u8::from_ne_bytes; //~ big_endian_bytes + let _ = u8::to_ne_bytes; //~ big_endian_bytes + } + + #[warn(clippy::host_endian_bytes)] + { + let _ = 0u8.to_le_bytes(); //~ big_endian_bytes + let _ = 0i8.to_le_bytes(); //~ big_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = i8::from_le_bytes([0; _]); //~ big_endian_bytes + }; + + #[warn(clippy::little_endian_bytes)] + { + let _ = 0u8.to_ne_bytes(); //~ big_endian_bytes + let _ = 0i8.to_ne_bytes(); //~ big_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = i8::from_ne_bytes([0; _]); //~ big_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_ne_bytes(); //~ big_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = 0u8.$to_ne_bytes(); //~ big_endian_bytes + let _ = u8::$from_ne_bytes([0; _]); //~ big_endian_bytes + }} + + external! { + let _ = 0u8.to_be_bytes(); + let _ = u8::from_be_bytes([0; _]); + let _ = 0u8.$to_ne_bytes(); //~ big_endian_bytes + let _ = u8::$from_ne_bytes([0; _]); //~ big_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/big_endian_bytes.2.fixed b/src/tools/clippy/tests/ui/big_endian_bytes.2.fixed new file mode 100644 index 0000000000000..3adcb7ae37821 --- /dev/null +++ b/src/tools/clippy/tests/ui/big_endian_bytes.2.fixed @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::big_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_le_bytes(); //~ big_endian_bytes + let _ = 0u16.to_le_bytes(); //~ big_endian_bytes + let _ = 0u32.to_le_bytes(); //~ big_endian_bytes + let _ = 0u64.to_le_bytes(); //~ big_endian_bytes + let _ = 0u128.to_le_bytes(); //~ big_endian_bytes + let _ = 0usize.to_le_bytes(); //~ big_endian_bytes + + let _ = 0i8.to_le_bytes(); //~ big_endian_bytes + let _ = 0i16.to_le_bytes(); //~ big_endian_bytes + let _ = 0i32.to_le_bytes(); //~ big_endian_bytes + let _ = 0i64.to_le_bytes(); //~ big_endian_bytes + let _ = 0i128.to_le_bytes(); //~ big_endian_bytes + let _ = 0isize.to_le_bytes(); //~ big_endian_bytes + + let _ = 0f16.to_le_bytes(); //~ big_endian_bytes + let _ = 0f32.to_le_bytes(); //~ big_endian_bytes + let _ = 0f64.to_le_bytes(); //~ big_endian_bytes + let _ = 0f128.to_le_bytes(); //~ big_endian_bytes + + let _ = u8::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = u16::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = u32::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = u64::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = u128::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = usize::from_le_bytes([0; _]); //~ big_endian_bytes + + let _ = i8::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = i16::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = i32::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = i64::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = i128::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = isize::from_le_bytes([0; _]); //~ big_endian_bytes + + let _ = f16::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = f32::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = f64::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = f128::from_le_bytes([0; _]); //~ big_endian_bytes + }; + + { + let _ = u8::from_le_bytes; //~ big_endian_bytes + let _ = u8::to_le_bytes; //~ big_endian_bytes + } + + #[warn(clippy::host_endian_bytes)] + { + let _ = 0u8.to_le_bytes(); //~ big_endian_bytes + let _ = 0i8.to_le_bytes(); //~ big_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = i8::from_le_bytes([0; _]); //~ big_endian_bytes + }; + + #[warn(clippy::little_endian_bytes)] + { + let _ = 0u8.to_ne_bytes(); //~ big_endian_bytes + let _ = 0i8.to_ne_bytes(); //~ big_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ big_endian_bytes + let _ = i8::from_ne_bytes([0; _]); //~ big_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_le_bytes(); //~ big_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ big_endian_bytes + let _ = 0u8.$to_le_bytes(); //~ big_endian_bytes + let _ = u8::$from_le_bytes([0; _]); //~ big_endian_bytes + }} + + external! { + let _ = 0u8.to_be_bytes(); + let _ = u8::from_be_bytes([0; _]); + let _ = 0u8.$to_le_bytes(); //~ big_endian_bytes + let _ = u8::$from_le_bytes([0; _]); //~ big_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/big_endian_bytes.rs b/src/tools/clippy/tests/ui/big_endian_bytes.rs new file mode 100644 index 0000000000000..b0116f35e8c19 --- /dev/null +++ b/src/tools/clippy/tests/ui/big_endian_bytes.rs @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::big_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_be_bytes(); //~ big_endian_bytes + let _ = 0u16.to_be_bytes(); //~ big_endian_bytes + let _ = 0u32.to_be_bytes(); //~ big_endian_bytes + let _ = 0u64.to_be_bytes(); //~ big_endian_bytes + let _ = 0u128.to_be_bytes(); //~ big_endian_bytes + let _ = 0usize.to_be_bytes(); //~ big_endian_bytes + + let _ = 0i8.to_be_bytes(); //~ big_endian_bytes + let _ = 0i16.to_be_bytes(); //~ big_endian_bytes + let _ = 0i32.to_be_bytes(); //~ big_endian_bytes + let _ = 0i64.to_be_bytes(); //~ big_endian_bytes + let _ = 0i128.to_be_bytes(); //~ big_endian_bytes + let _ = 0isize.to_be_bytes(); //~ big_endian_bytes + + let _ = 0f16.to_be_bytes(); //~ big_endian_bytes + let _ = 0f32.to_be_bytes(); //~ big_endian_bytes + let _ = 0f64.to_be_bytes(); //~ big_endian_bytes + let _ = 0f128.to_be_bytes(); //~ big_endian_bytes + + let _ = u8::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = u16::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = u32::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = u64::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = u128::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = usize::from_be_bytes([0; _]); //~ big_endian_bytes + + let _ = i8::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = i16::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = i32::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = i64::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = i128::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = isize::from_be_bytes([0; _]); //~ big_endian_bytes + + let _ = f16::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = f32::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = f64::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = f128::from_be_bytes([0; _]); //~ big_endian_bytes + }; + + { + let _ = u8::from_be_bytes; //~ big_endian_bytes + let _ = u8::to_be_bytes; //~ big_endian_bytes + } + + #[warn(clippy::host_endian_bytes)] + { + let _ = 0u8.to_be_bytes(); //~ big_endian_bytes + let _ = 0i8.to_be_bytes(); //~ big_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = i8::from_be_bytes([0; _]); //~ big_endian_bytes + }; + + #[warn(clippy::little_endian_bytes)] + { + let _ = 0u8.to_be_bytes(); //~ big_endian_bytes + let _ = 0i8.to_be_bytes(); //~ big_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = i8::from_be_bytes([0; _]); //~ big_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_be_bytes(); //~ big_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ big_endian_bytes + let _ = 0u8.$to_be_bytes(); //~ big_endian_bytes + let _ = u8::$from_be_bytes([0; _]); //~ big_endian_bytes + }} + + external! { + let _ = 0u8.to_be_bytes(); + let _ = u8::from_be_bytes([0; _]); + let _ = 0u8.$to_be_bytes(); //~ big_endian_bytes + let _ = u8::$from_be_bytes([0; _]); //~ big_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/big_endian_bytes.stderr b/src/tools/clippy/tests/ui/big_endian_bytes.stderr new file mode 100644 index 0000000000000..6c01b2c086531 --- /dev/null +++ b/src/tools/clippy/tests/ui/big_endian_bytes.stderr @@ -0,0 +1,734 @@ +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:12:21 + | +LL | let _ = 0u8.to_be_bytes(); + | ^^^^^^^^^^^ + | + = note: `-D clippy::big-endian-bytes` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::big_endian_bytes)]` +help: convert to native endian + | +LL - let _ = 0u8.to_be_bytes(); +LL + let _ = 0u8.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u8.to_be_bytes(); +LL + let _ = 0u8.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:13:22 + | +LL | let _ = 0u16.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u16.to_be_bytes(); +LL + let _ = 0u16.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u16.to_be_bytes(); +LL + let _ = 0u16.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:14:22 + | +LL | let _ = 0u32.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u32.to_be_bytes(); +LL + let _ = 0u32.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u32.to_be_bytes(); +LL + let _ = 0u32.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:15:22 + | +LL | let _ = 0u64.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u64.to_be_bytes(); +LL + let _ = 0u64.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u64.to_be_bytes(); +LL + let _ = 0u64.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:16:23 + | +LL | let _ = 0u128.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u128.to_be_bytes(); +LL + let _ = 0u128.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u128.to_be_bytes(); +LL + let _ = 0u128.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:17:24 + | +LL | let _ = 0usize.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0usize.to_be_bytes(); +LL + let _ = 0usize.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0usize.to_be_bytes(); +LL + let _ = 0usize.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:19:21 + | +LL | let _ = 0i8.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i8.to_be_bytes(); +LL + let _ = 0i8.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0i8.to_be_bytes(); +LL + let _ = 0i8.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:20:22 + | +LL | let _ = 0i16.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i16.to_be_bytes(); +LL + let _ = 0i16.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0i16.to_be_bytes(); +LL + let _ = 0i16.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:21:22 + | +LL | let _ = 0i32.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i32.to_be_bytes(); +LL + let _ = 0i32.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0i32.to_be_bytes(); +LL + let _ = 0i32.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:22:22 + | +LL | let _ = 0i64.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i64.to_be_bytes(); +LL + let _ = 0i64.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0i64.to_be_bytes(); +LL + let _ = 0i64.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:23:23 + | +LL | let _ = 0i128.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i128.to_be_bytes(); +LL + let _ = 0i128.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0i128.to_be_bytes(); +LL + let _ = 0i128.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:24:24 + | +LL | let _ = 0isize.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0isize.to_be_bytes(); +LL + let _ = 0isize.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0isize.to_be_bytes(); +LL + let _ = 0isize.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:26:22 + | +LL | let _ = 0f16.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f16.to_be_bytes(); +LL + let _ = 0f16.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0f16.to_be_bytes(); +LL + let _ = 0f16.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:27:22 + | +LL | let _ = 0f32.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f32.to_be_bytes(); +LL + let _ = 0f32.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0f32.to_be_bytes(); +LL + let _ = 0f32.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:28:22 + | +LL | let _ = 0f64.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f64.to_be_bytes(); +LL + let _ = 0f64.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0f64.to_be_bytes(); +LL + let _ = 0f64.to_le_bytes(); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:29:23 + | +LL | let _ = 0f128.to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f128.to_be_bytes(); +LL + let _ = 0f128.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0f128.to_be_bytes(); +LL + let _ = 0f128.to_le_bytes(); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:31:21 + | +LL | let _ = u8::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::from_be_bytes([0; _]); +LL + let _ = u8::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u8::from_be_bytes([0; _]); +LL + let _ = u8::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:32:22 + | +LL | let _ = u16::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u16::from_be_bytes([0; _]); +LL + let _ = u16::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u16::from_be_bytes([0; _]); +LL + let _ = u16::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:33:22 + | +LL | let _ = u32::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u32::from_be_bytes([0; _]); +LL + let _ = u32::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u32::from_be_bytes([0; _]); +LL + let _ = u32::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:34:22 + | +LL | let _ = u64::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u64::from_be_bytes([0; _]); +LL + let _ = u64::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u64::from_be_bytes([0; _]); +LL + let _ = u64::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:35:23 + | +LL | let _ = u128::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u128::from_be_bytes([0; _]); +LL + let _ = u128::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u128::from_be_bytes([0; _]); +LL + let _ = u128::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:36:24 + | +LL | let _ = usize::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = usize::from_be_bytes([0; _]); +LL + let _ = usize::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = usize::from_be_bytes([0; _]); +LL + let _ = usize::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:38:21 + | +LL | let _ = i8::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i8::from_be_bytes([0; _]); +LL + let _ = i8::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = i8::from_be_bytes([0; _]); +LL + let _ = i8::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:39:22 + | +LL | let _ = i16::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i16::from_be_bytes([0; _]); +LL + let _ = i16::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = i16::from_be_bytes([0; _]); +LL + let _ = i16::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:40:22 + | +LL | let _ = i32::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i32::from_be_bytes([0; _]); +LL + let _ = i32::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = i32::from_be_bytes([0; _]); +LL + let _ = i32::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:41:22 + | +LL | let _ = i64::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i64::from_be_bytes([0; _]); +LL + let _ = i64::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = i64::from_be_bytes([0; _]); +LL + let _ = i64::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:42:23 + | +LL | let _ = i128::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i128::from_be_bytes([0; _]); +LL + let _ = i128::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = i128::from_be_bytes([0; _]); +LL + let _ = i128::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:43:24 + | +LL | let _ = isize::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = isize::from_be_bytes([0; _]); +LL + let _ = isize::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = isize::from_be_bytes([0; _]); +LL + let _ = isize::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:45:22 + | +LL | let _ = f16::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f16::from_be_bytes([0; _]); +LL + let _ = f16::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = f16::from_be_bytes([0; _]); +LL + let _ = f16::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:46:22 + | +LL | let _ = f32::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f32::from_be_bytes([0; _]); +LL + let _ = f32::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = f32::from_be_bytes([0; _]); +LL + let _ = f32::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:47:22 + | +LL | let _ = f64::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f64::from_be_bytes([0; _]); +LL + let _ = f64::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = f64::from_be_bytes([0; _]); +LL + let _ = f64::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:48:23 + | +LL | let _ = f128::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f128::from_be_bytes([0; _]); +LL + let _ = f128::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = f128::from_be_bytes([0; _]); +LL + let _ = f128::from_le_bytes([0; _]); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:52:21 + | +LL | let _ = u8::from_be_bytes; + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::from_be_bytes; +LL + let _ = u8::from_ne_bytes; + | +help: convert from little endian + | +LL - let _ = u8::from_be_bytes; +LL + let _ = u8::from_le_bytes; + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:53:21 + | +LL | let _ = u8::to_be_bytes; + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = u8::to_be_bytes; +LL + let _ = u8::to_ne_bytes; + | +help: convert to little endian + | +LL - let _ = u8::to_be_bytes; +LL + let _ = u8::to_le_bytes; + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:58:21 + | +LL | let _ = 0u8.to_be_bytes(); + | ^^^^^^^^^^^ help: convert to little endian: `to_le_bytes` + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:59:21 + | +LL | let _ = 0i8.to_be_bytes(); + | ^^^^^^^^^^^ help: convert to little endian: `to_le_bytes` + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:60:21 + | +LL | let _ = u8::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from little endian: `from_le_bytes` + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:61:21 + | +LL | let _ = i8::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from little endian: `from_le_bytes` + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:66:21 + | +LL | let _ = 0u8.to_be_bytes(); + | ^^^^^^^^^^^ help: convert to native endian: `to_ne_bytes` + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:67:21 + | +LL | let _ = 0i8.to_be_bytes(); + | ^^^^^^^^^^^ help: convert to native endian: `to_ne_bytes` + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:68:21 + | +LL | let _ = u8::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from native endian: `from_ne_bytes` + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:69:21 + | +LL | let _ = i8::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from native endian: `from_ne_bytes` + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:74:25 + | +LL | let _ = 0u8.to_be_bytes(); + | ^^^^^^^^^^^ + | + = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) +help: convert to native endian + | +LL - let _ = 0u8.to_be_bytes(); +LL + let _ = 0u8.to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u8.to_be_bytes(); +LL + let _ = 0u8.to_le_bytes(); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:75:25 + | +LL | let _ = u8::from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | + = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) +help: convert from native endian + | +LL - let _ = u8::from_be_bytes([0; _]); +LL + let _ = u8::from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u8::from_be_bytes([0; _]); +LL + let _ = u8::from_le_bytes([0; _]); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:76:26 + | +LL | let _ = 0u8.$to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u8.$to_be_bytes(); +LL + let _ = 0u8.$to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u8.$to_be_bytes(); +LL + let _ = 0u8.$to_le_bytes(); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:77:26 + | +LL | let _ = u8::$from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::$from_be_bytes([0; _]); +LL + let _ = u8::$from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u8::$from_be_bytes([0; _]); +LL + let _ = u8::$from_le_bytes([0; _]); + | + +error: use of `to_be_bytes` + --> tests/ui/big_endian_bytes.rs:83:26 + | +LL | let _ = 0u8.$to_be_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u8.$to_be_bytes(); +LL + let _ = 0u8.$to_ne_bytes(); + | +help: convert to little endian + | +LL - let _ = 0u8.$to_be_bytes(); +LL + let _ = 0u8.$to_le_bytes(); + | + +error: use of `from_be_bytes` + --> tests/ui/big_endian_bytes.rs:84:26 + | +LL | let _ = u8::$from_be_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::$from_be_bytes([0; _]); +LL + let _ = u8::$from_ne_bytes([0; _]); + | +help: convert from little endian + | +LL - let _ = u8::$from_be_bytes([0; _]); +LL + let _ = u8::$from_le_bytes([0; _]); + | + +error: aborting due to 48 previous errors + diff --git a/src/tools/clippy/tests/ui/block_scrutinee.1.fixed b/src/tools/clippy/tests/ui/block_scrutinee.1.fixed new file mode 100644 index 0000000000000..3f123e54783fe --- /dev/null +++ b/src/tools/clippy/tests/ui/block_scrutinee.1.fixed @@ -0,0 +1,59 @@ +//@ edition: 2021 +#![warn(clippy::block_scrutinee)] +#![allow(clippy::blocks_in_conditions)] + +fn my_function() -> Option { + Some(1) +} + +fn main() { + if let Some(x) = my_function() { + //~^ ERROR: this scrutinee is wrapped in a block + let _ = x; + } + + match my_function() { + //~^ ERROR: this scrutinee is wrapped in a block + Some(1) => println!("one"), + Some(_) => println!("other"), + None => println!("none"), + } + + let mut v = vec![1, 2, 3]; + while let Some(x) = v.pop() { + //~^ ERROR: this scrutinee is wrapped in a block + let _ = x; + } + + if let Some(x) = my_function() { + let _ = x; + } + + if let Some(x) = { + let _y = 2; + my_function() + } { + let _ = x; + } + + //~v ERROR: this scrutinee is wrapped in a block + if let Some(x) = v.pop() { + let _ = x; + } + + macro_rules! get_val { + () => {{ my_function() }}; + } + if let Some(x) = get_val!() { + let _ = x; + } + + // Test that `unsafe` blocks are ignored + unsafe fn my_unsafe_fn() -> Option { + Some(1) + } + + if let Some(x) = unsafe { my_unsafe_fn() } { + let _ = x; + } +} diff --git a/src/tools/clippy/tests/ui/block_scrutinee.2.fixed b/src/tools/clippy/tests/ui/block_scrutinee.2.fixed new file mode 100644 index 0000000000000..6eed53831bf69 --- /dev/null +++ b/src/tools/clippy/tests/ui/block_scrutinee.2.fixed @@ -0,0 +1,63 @@ +//@ edition: 2021 +#![warn(clippy::block_scrutinee)] +#![allow(clippy::blocks_in_conditions)] + +fn my_function() -> Option { + Some(1) +} + +fn main() { + let res = my_function(); + if let Some(x) = res { + //~^ ERROR: this scrutinee is wrapped in a block + let _ = x; + } + + let res = my_function(); + match res { + //~^ ERROR: this scrutinee is wrapped in a block + Some(1) => println!("one"), + Some(_) => println!("other"), + None => println!("none"), + } + + let mut v = vec![1, 2, 3]; + let res = v.pop(); + while let Some(x) = res { + //~^ ERROR: this scrutinee is wrapped in a block + let _ = x; + } + + if let Some(x) = my_function() { + let _ = x; + } + + if let Some(x) = { + let _y = 2; + my_function() + } { + let _ = x; + } + + //~v ERROR: this scrutinee is wrapped in a block + let res = v.pop(); + if let Some(x) = res { + let _ = x; + } + + macro_rules! get_val { + () => {{ my_function() }}; + } + if let Some(x) = get_val!() { + let _ = x; + } + + // Test that `unsafe` blocks are ignored + unsafe fn my_unsafe_fn() -> Option { + Some(1) + } + + if let Some(x) = unsafe { my_unsafe_fn() } { + let _ = x; + } +} diff --git a/src/tools/clippy/tests/ui/block_scrutinee.rs b/src/tools/clippy/tests/ui/block_scrutinee.rs new file mode 100644 index 0000000000000..1f9ad4d3015e4 --- /dev/null +++ b/src/tools/clippy/tests/ui/block_scrutinee.rs @@ -0,0 +1,62 @@ +//@ edition: 2021 +#![warn(clippy::block_scrutinee)] +#![allow(clippy::blocks_in_conditions)] + +fn my_function() -> Option { + Some(1) +} + +fn main() { + if let Some(x) = { my_function() } { + //~^ ERROR: this scrutinee is wrapped in a block + let _ = x; + } + + match { my_function() } { + //~^ ERROR: this scrutinee is wrapped in a block + Some(1) => println!("one"), + Some(_) => println!("other"), + None => println!("none"), + } + + let mut v = vec![1, 2, 3]; + while let Some(x) = { v.pop() } { + //~^ ERROR: this scrutinee is wrapped in a block + let _ = x; + } + + if let Some(x) = my_function() { + let _ = x; + } + + if let Some(x) = { + let _y = 2; + my_function() + } { + let _ = x; + } + + //~v ERROR: this scrutinee is wrapped in a block + if let Some(x) = { + // We are popping a value + v.pop() + } { + let _ = x; + } + + macro_rules! get_val { + () => {{ my_function() }}; + } + if let Some(x) = get_val!() { + let _ = x; + } + + // Test that `unsafe` blocks are ignored + unsafe fn my_unsafe_fn() -> Option { + Some(1) + } + + if let Some(x) = unsafe { my_unsafe_fn() } { + let _ = x; + } +} diff --git a/src/tools/clippy/tests/ui/block_scrutinee.stderr b/src/tools/clippy/tests/ui/block_scrutinee.stderr new file mode 100644 index 0000000000000..bb3b7e2a4e26f --- /dev/null +++ b/src/tools/clippy/tests/ui/block_scrutinee.stderr @@ -0,0 +1,87 @@ +error: this scrutinee is wrapped in a block + --> tests/ui/block_scrutinee.rs:10:22 + | +LL | if let Some(x) = { my_function() } { + | ^^^^^^^^^^^^^^^^^ + | + = note: temporary values in this block-wrapped scrutinee will be dropped after the body of the `if let` statement + = note: starting with the 2024 edition, temporaries within a block's final expression are dropped immediately at the end of the block + = note: `-D clippy::block-scrutinee` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::block_scrutinee)]` +help: to drop temporaries after the surrounding `if let`, remove the block + | +LL - if let Some(x) = { my_function() } { +LL + if let Some(x) = my_function() { + | +help: to drop temporaries early, move them to a separate local binding (or update your `Cargo.toml` to the 2024 edition) + | +LL ~ let res = my_function(); +LL ~ if let Some(x) = res { + | + +error: this scrutinee is wrapped in a block + --> tests/ui/block_scrutinee.rs:15:11 + | +LL | match { my_function() } { + | ^^^^^^^^^^^^^^^^^ + | + = note: temporary values in this block-wrapped scrutinee will be dropped after the body of the `match` statement + = note: starting with the 2024 edition, temporaries within a block's final expression are dropped immediately at the end of the block +help: to drop temporaries after the surrounding `match`, remove the block + | +LL - match { my_function() } { +LL + match my_function() { + | +help: to drop temporaries early, move them to a separate local binding (or update your `Cargo.toml` to the 2024 edition) + | +LL ~ let res = my_function(); +LL ~ match res { + | + +error: this scrutinee is wrapped in a block + --> tests/ui/block_scrutinee.rs:23:25 + | +LL | while let Some(x) = { v.pop() } { + | ^^^^^^^^^^^ + | + = note: temporary values in this block-wrapped scrutinee will be dropped after the body of the `while let` statement + = note: starting with the 2024 edition, temporaries within a block's final expression are dropped immediately at the end of the block +help: to drop temporaries after the surrounding `while let`, remove the block + | +LL - while let Some(x) = { v.pop() } { +LL + while let Some(x) = v.pop() { + | +help: to drop temporaries early, move them to a separate local binding (or update your `Cargo.toml` to the 2024 edition) + | +LL ~ let res = v.pop(); +LL ~ while let Some(x) = res { + | + +error: this scrutinee is wrapped in a block + --> tests/ui/block_scrutinee.rs:40:22 + | +LL | if let Some(x) = { + | ______________________^ +LL | | // We are popping a value +LL | | v.pop() +LL | | } { + | |_____^ + | + = note: temporary values in this block-wrapped scrutinee will be dropped after the body of the `if let` statement + = note: starting with the 2024 edition, temporaries within a block's final expression are dropped immediately at the end of the block +help: to drop temporaries after the surrounding `if let`, remove the block + | +LL - if let Some(x) = { +LL - // We are popping a value +LL - v.pop() +LL - } { +LL + if let Some(x) = v.pop() { + | +help: to drop temporaries early, move them to a separate local binding (or update your `Cargo.toml` to the 2024 edition) + | +LL ~ let res = v.pop(); +LL ~ if let Some(x) = res { + | + +error: aborting due to 4 previous errors + diff --git a/src/tools/clippy/tests/ui/block_scrutinee_2024.rs b/src/tools/clippy/tests/ui/block_scrutinee_2024.rs new file mode 100644 index 0000000000000..e3b3a7b42d59c --- /dev/null +++ b/src/tools/clippy/tests/ui/block_scrutinee_2024.rs @@ -0,0 +1,28 @@ +//@ edition: 2024 +//@ check-pass +#![warn(clippy::block_scrutinee)] +#![allow(clippy::blocks_in_conditions)] + +fn my_function() -> Option { + Some(1) +} + +fn main() { + // This should NOT trigger the lint on the 2024 edition + if let Some(x) = { my_function() } { + let _ = x; + } + + // This should NOT trigger the lint on the 2024 edition + match { my_function() } { + Some(1) => println!("one"), + Some(_) => println!("other"), + None => println!("none"), + } + + // This should NOT trigger the lint on the 2024 edition + let mut v = vec![1, 2, 3]; + while let Some(x) = { v.pop() } { + let _ = x; + } +} diff --git a/src/tools/clippy/tests/ui/blocks_in_conditions.fixed b/src/tools/clippy/tests/ui/blocks_in_conditions.fixed index b4cf6eb90d980..c72cdcdebfe3f 100644 --- a/src/tools/clippy/tests/ui/blocks_in_conditions.fixed +++ b/src/tools/clippy/tests/ui/blocks_in_conditions.fixed @@ -109,4 +109,66 @@ fn in_closure() { } } +fn issue_15112() { + { + let v = std::sync::Mutex::new(0); + match { *v.lock().unwrap() } { + 1 => { + todo!() + }, + 2 => { + todo!() + }, + _ => {}, + } + } + + { + // No Drop impl, so braces should be removed + struct Foo; + + impl Foo { + fn foo(&self) -> i32 { + 0 + } + } + + match Foo.foo() { + //~^ ERROR: omit braces around single expression condition + 1 => { + todo!() + }, + 2 => { + todo!() + }, + _ => {}, + } + } + + { + // Drop impl, so braces should be kept + struct Bar; + + impl Drop for Bar { + fn drop(&mut self) {} + } + + impl Bar { + fn bar(&self) -> i32 { + 0 + } + } + + match { Bar.bar() } { + 1 => { + todo!() + }, + 2 => { + todo!() + }, + _ => {}, + } + } +} + fn main() {} diff --git a/src/tools/clippy/tests/ui/blocks_in_conditions.rs b/src/tools/clippy/tests/ui/blocks_in_conditions.rs index 8fb6cc7c2387d..e37ef9fe290a7 100644 --- a/src/tools/clippy/tests/ui/blocks_in_conditions.rs +++ b/src/tools/clippy/tests/ui/blocks_in_conditions.rs @@ -109,4 +109,66 @@ fn in_closure() { } } +fn issue_15112() { + { + let v = std::sync::Mutex::new(0); + match { *v.lock().unwrap() } { + 1 => { + todo!() + }, + 2 => { + todo!() + }, + _ => {}, + } + } + + { + // No Drop impl, so braces should be removed + struct Foo; + + impl Foo { + fn foo(&self) -> i32 { + 0 + } + } + + match { Foo.foo() } { + //~^ ERROR: omit braces around single expression condition + 1 => { + todo!() + }, + 2 => { + todo!() + }, + _ => {}, + } + } + + { + // Drop impl, so braces should be kept + struct Bar; + + impl Drop for Bar { + fn drop(&mut self) {} + } + + impl Bar { + fn bar(&self) -> i32 { + 0 + } + } + + match { Bar.bar() } { + 1 => { + todo!() + }, + 2 => { + todo!() + }, + _ => {}, + } + } +} + fn main() {} diff --git a/src/tools/clippy/tests/ui/blocks_in_conditions.stderr b/src/tools/clippy/tests/ui/blocks_in_conditions.stderr index 01409560f7dbe..c8745628dd977 100644 --- a/src/tools/clippy/tests/ui/blocks_in_conditions.stderr +++ b/src/tools/clippy/tests/ui/blocks_in_conditions.stderr @@ -25,5 +25,11 @@ error: omit braces around single expression condition LL | if { true } { 6 } else { 10 } | ^^^^^^^^ help: try: `true` -error: aborting due to 2 previous errors +error: omit braces around single expression condition + --> tests/ui/blocks_in_conditions.rs:136:15 + | +LL | match { Foo.foo() } { + | ^^^^^^^^^^^^^ help: try: `Foo.foo()` + +error: aborting due to 3 previous errors diff --git a/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.fixed b/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.fixed new file mode 100644 index 0000000000000..bacecea1a876b --- /dev/null +++ b/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.fixed @@ -0,0 +1,153 @@ +#![deny(clippy::branches_sharing_code)] +#![allow(clippy::let_and_return)] + +enum Mode { + Kill, + Table, + List, +} + +fn kill() {} +fn table() {} +fn list() {} + +// Every arm ends in `Ok(())`: the shared tail can be hoisted out below the `match`. +fn shared_tail(mode: Mode) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + Mode::Kill => { + kill(); + }, + Mode::Table => { + table(); + }, + Mode::List => { + list(); + }, + } + Ok(()) +} + +// Shared tail even though one arm has an early `return`. +fn shared_tail_with_return(mode: Mode, skip: bool) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + Mode::Kill => { + if skip { + return Ok(()); + } + kill(); + }, + _ => { + table(); + }, + } + Ok(()) +} + +// No lint: the trailing expressions differ. +fn different_tail(mode: Mode) -> Result { + match mode { + Mode::Kill => { + kill(); + Ok(1) + }, + Mode::Table => { + table(); + Ok(2) + }, + Mode::List => Ok(3), + } +} + +// No lint: the tail references a binding introduced inside the arm. +fn refs_local(x: Option) -> i32 { + match x { + Some(v) => { + kill(); + v + }, + None => { + table(); + 0 + }, + } +} + +// No lint: the `match` value is bound, so the tail cannot simply be moved after it. +fn value_used(mode: Mode) -> Result<(), ()> { + let res = match mode { + Mode::Kill => { + kill(); + Ok(()) + }, + _ => { + table(); + Ok(()) + }, + }; + res +} + +struct Guard; + +impl Drop for Guard { + fn drop(&mut self) {} +} + +// No lint: an arm-local binding has a non-trivial `Drop`. Hoisting the tail would drop the guard +// before the moved expression runs, changing observable drop order. +fn arm_local_drop(mode: Mode) -> Result<(), ()> { + match mode { + Mode::Kill => { + let _g = Guard; + kill(); + Ok(()) + }, + _ => { + table(); + Ok(()) + }, + } +} + +// Comments inside the arm bodies, including right before the shared tail. +fn comments_in_arm_body(mode: Mode) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + Mode::Kill => { + // kill it + kill(); + }, + Mode::Table => { + // table it + table(); + }, + Mode::List => { + list(); + }, + } + Ok(()) +} + +// Comments before the `=>` of each arm. +fn comments_before_fat_arrow(mode: Mode) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + // killing time + Mode::Kill => { + kill(); + }, + // table time + Mode::Table => { + table(); + }, + // list time + Mode::List => { + list(); + }, + } + Ok(()) +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.rs b/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.rs new file mode 100644 index 0000000000000..38160e2fc0001 --- /dev/null +++ b/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.rs @@ -0,0 +1,162 @@ +#![deny(clippy::branches_sharing_code)] +#![allow(clippy::let_and_return)] + +enum Mode { + Kill, + Table, + List, +} + +fn kill() {} +fn table() {} +fn list() {} + +// Every arm ends in `Ok(())`: the shared tail can be hoisted out below the `match`. +fn shared_tail(mode: Mode) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + Mode::Kill => { + kill(); + Ok(()) + }, + Mode::Table => { + table(); + Ok(()) + }, + Mode::List => { + list(); + Ok(()) + }, + } +} + +// Shared tail even though one arm has an early `return`. +fn shared_tail_with_return(mode: Mode, skip: bool) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + Mode::Kill => { + if skip { + return Ok(()); + } + kill(); + Ok(()) + }, + _ => { + table(); + Ok(()) + }, + } +} + +// No lint: the trailing expressions differ. +fn different_tail(mode: Mode) -> Result { + match mode { + Mode::Kill => { + kill(); + Ok(1) + }, + Mode::Table => { + table(); + Ok(2) + }, + Mode::List => Ok(3), + } +} + +// No lint: the tail references a binding introduced inside the arm. +fn refs_local(x: Option) -> i32 { + match x { + Some(v) => { + kill(); + v + }, + None => { + table(); + 0 + }, + } +} + +// No lint: the `match` value is bound, so the tail cannot simply be moved after it. +fn value_used(mode: Mode) -> Result<(), ()> { + let res = match mode { + Mode::Kill => { + kill(); + Ok(()) + }, + _ => { + table(); + Ok(()) + }, + }; + res +} + +struct Guard; + +impl Drop for Guard { + fn drop(&mut self) {} +} + +// No lint: an arm-local binding has a non-trivial `Drop`. Hoisting the tail would drop the guard +// before the moved expression runs, changing observable drop order. +fn arm_local_drop(mode: Mode) -> Result<(), ()> { + match mode { + Mode::Kill => { + let _g = Guard; + kill(); + Ok(()) + }, + _ => { + table(); + Ok(()) + }, + } +} + +// Comments inside the arm bodies, including right before the shared tail. +fn comments_in_arm_body(mode: Mode) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + Mode::Kill => { + // kill it + kill(); + // done killing + Ok(()) + }, + Mode::Table => { + // table it + table(); + Ok(()) + }, + Mode::List => { + list(); + // list it, then return + Ok(()) + }, + } +} + +// Comments before the `=>` of each arm. +fn comments_before_fat_arrow(mode: Mode) -> Result<(), ()> { + //~v branches_sharing_code + match mode { + // killing time + Mode::Kill => { + kill(); + Ok(()) + }, + // table time + Mode::Table => { + table(); + Ok(()) + }, + // list time + Mode::List => { + list(); + Ok(()) + }, + } +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.stderr b/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.stderr new file mode 100644 index 0000000000000..e7fa9f1b0d65b --- /dev/null +++ b/src/tools/clippy/tests/ui/branches_sharing_code/shared_match_tail.stderr @@ -0,0 +1,115 @@ +error: all match arms end with the same expression + --> tests/ui/branches_sharing_code/shared_match_tail.rs:17:5 + | +LL | / match mode { +LL | | Mode::Kill => { +LL | | kill(); +LL | | Ok(()) +... | +LL | | }, +LL | | } + | |_____^ + | + = note: the suggestion may need adjustments to preserve drop order or to use the expression result correctly +note: the lint level is defined here + --> tests/ui/branches_sharing_code/shared_match_tail.rs:1:9 + | +LL | #![deny(clippy::branches_sharing_code)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +help: consider moving the shared expression after the `match` + | +LL ~ kill(); +LL | }, +LL | Mode::Table => { +LL ~ table(); +LL | }, +LL | Mode::List => { +LL ~ list(); +LL | }, +LL ~ } +LL + Ok(()) + | + +error: all match arms end with the same expression + --> tests/ui/branches_sharing_code/shared_match_tail.rs:36:5 + | +LL | / match mode { +LL | | Mode::Kill => { +LL | | if skip { +LL | | return Ok(()); +... | +LL | | }, +LL | | } + | |_____^ + | + = note: the suggestion may need adjustments to preserve drop order or to use the expression result correctly +help: consider moving the shared expression after the `match` + | +LL ~ kill(); +LL | }, +LL | _ => { +LL ~ table(); +LL | }, +LL ~ } +LL + Ok(()) + | + +error: all match arms end with the same expression + --> tests/ui/branches_sharing_code/shared_match_tail.rs:120:5 + | +LL | / match mode { +LL | | Mode::Kill => { +LL | | // kill it +LL | | kill(); +... | +LL | | }, +LL | | } + | |_____^ + | + = note: the suggestion may need adjustments to preserve drop order or to use the expression result correctly +help: consider moving the shared expression after the `match` + | +LL ~ kill(); +LL | }, +LL | Mode::Table => { +LL | // table it +LL ~ table(); +LL | }, +LL | Mode::List => { +LL ~ list(); +LL | }, +LL ~ } +LL + Ok(()) + | + +error: all match arms end with the same expression + --> tests/ui/branches_sharing_code/shared_match_tail.rs:143:5 + | +LL | / match mode { +LL | | // killing time +LL | | Mode::Kill => { +LL | | kill(); +... | +LL | | }, +LL | | } + | |_____^ + | + = note: the suggestion may need adjustments to preserve drop order or to use the expression result correctly +help: consider moving the shared expression after the `match` + | +LL ~ kill(); +LL | }, +LL | // table time +LL | Mode::Table => { +LL ~ table(); +LL | }, +LL | // list time +LL | Mode::List => { +LL ~ list(); +LL | }, +LL ~ } +LL + Ok(()) + | + +error: aborting due to 4 previous errors + diff --git a/src/tools/clippy/tests/ui/clone_on_copy.fixed b/src/tools/clippy/tests/ui/clone_on_copy.fixed index c93050bdc4130..ad0a4343146a9 100644 --- a/src/tools/clippy/tests/ui/clone_on_copy.fixed +++ b/src/tools/clippy/tests/ui/clone_on_copy.fixed @@ -90,6 +90,12 @@ mod issue3052 { let a = A; let _: E = *****a; //~^ clone_on_copy + let _: E = *****a; + //~^ clone_on_copy + let _: E = *****a; + //~^ clone_on_copy + let _: E = *****a; + //~^ clone_on_copy let _: E = *****a; } @@ -100,13 +106,23 @@ fn issue4348() { ch.is_ascii() } - let mut x = 43; - let _ = &x.clone(); // ok, getting a ref 'a'.clone().make_ascii_uppercase(); // ok, clone and then mutate is_ascii('z'); //~^ clone_on_copy } +fn issue16969() { + let mut x = 43; + let _ = &x.clone(); + + let _ = &mut x.clone(); + + let mut y = &42; + let _ = &y.clone(); + + let _ = &mut y.clone(); +} + #[expect(clippy::vec_init_then_push)] fn issue5436() { let mut vec = Vec::new(); @@ -116,8 +132,152 @@ fn issue5436() { fn issue9277() -> Option { let opt: &Option = &None; - let value = (*opt)?; // operator precedence needed (*opt)? - // - //~^^ clone_on_copy + // operator precedence needed (*opt)? + let value = (*opt)?; + //~^ clone_on_copy None } + +mod ufcs_clone_on_copy { + use std::cell::RefCell; + + fn is_ascii(ch: char) -> bool { + ch.is_ascii() + } + + #[derive(Clone, Copy)] + struct Foo; + impl Foo { + fn clone(&self) -> u32 { + 0 + } + } + + macro_rules! m { + ($e:expr) => {{ $e }}; + } + + #[derive(Clone, Copy)] + struct Bar { + field: i32, + } + + struct Wrap([u32; 2]); + impl core::ops::Deref for Wrap { + type Target = [u32; 2]; + fn deref(&self) -> &[u32; 2] { + &self.0 + } + } + + fn foo(_x: &i32) {} + + fn main() { + let mut x = 42_i32; + + let vec = vec![1]; + let _ = Vec::clone(&vec); // ok, not a Copy type + let _ = Clone::clone(&vec); // ok, not a Copy type + let opt_vec = Some(vec![1]); + let _ = Option::clone(&opt_vec); // ok, not a Copy type + let _ = Clone::clone(&opt_vec); // ok, not a Copy type + + let _ = x; + //~^ clone_on_copy + let _ = x; + //~^ clone_on_copy + let _ = x; + //~^ clone_on_copy + + let ref_ref = &&42_i32; + // Clone::clone(ref_ref) and <&i32 as Clone>::clone(ref_ref) both return &i32, so it should be + // linted. + let _ = *ref_ref; + //~^ clone_on_copy + let _ = *ref_ref; + //~^ clone_on_copy + + let imm_ref = &mut 43_i32; + let _ = *imm_ref; + //~^ clone_on_copy + let _ = *imm_ref; + //~^ clone_on_copy + let _ = *imm_ref; + //~^ clone_on_copy + + let x_ref = &mut x; + let _ = *x_ref; + //~^ clone_on_copy + let _ = *x_ref; + //~^ clone_on_copy + let _ = *x_ref; + //~^ clone_on_copy + + let _ = x.rotate_left(1); + //~^ clone_on_copy + let _ = x.rotate_left(1); + //~^ clone_on_copy + let _ = x.rotate_left(1); + //~^ clone_on_copy + + char::clone(&'a').make_ascii_uppercase(); // ok, clone and then mutate + Clone::clone(&'a').make_ascii_uppercase(); // ok, clone and then mutate + ::clone(&'a').make_ascii_uppercase(); // ok, clone and then mutate + + is_ascii('z'); + //~^ clone_on_copy + is_ascii('z'); + //~^ clone_on_copy + is_ascii('z'); + //~^ clone_on_copy + + let _ = Foo::clone(&Foo); // ok, this is not the clone trait + + let _ = m!(42); + //~^ clone_on_copy + + let rc = RefCell::new(0); + let _ = *rc.borrow(); + //~^ clone_on_copy + + let bar = Bar { field: 0 }; + let _ = bar.field; + //~^ clone_on_copy + + let array = [0, 0]; + let _ = array[0]; + //~^ clone_on_copy + + let wrapped = Wrap([0, 0]); + let _ = (*wrapped)[0]; + //~^ clone_on_copy + + let _: &i32 = &i32::clone(&x); + let _: &i32 = &Clone::clone(&x); + let _: &i32 = &::clone(&x); + + let _: &mut i32 = &mut i32::clone(&x); + let _: &mut i32 = &mut Clone::clone(&x); + let _: &mut i32 = &mut ::clone(&x); + + let ref _y = i32::clone(&x); // ok, binds by reference + let ref _y = Clone::clone(&x); // ok, binds by reference + let ref mut _y = ::clone(&x); // ok, binds by reference + + foo(&i32::clone(&x)); + foo(&Clone::clone(&x)); + foo(&::clone(&x)); + } + + fn option_clone_on_copy() -> Option { + let opt: &Option = &Some(0); + + let _ = (*opt)?; + //~^ clone_on_copy + let _ = (*opt)?; + //~^ clone_on_copy + let _ = (*opt)?; + //~^ clone_on_copy + None + } +} diff --git a/src/tools/clippy/tests/ui/clone_on_copy.rs b/src/tools/clippy/tests/ui/clone_on_copy.rs index 3f46eb88559f4..d5371eda0fcb8 100644 --- a/src/tools/clippy/tests/ui/clone_on_copy.rs +++ b/src/tools/clippy/tests/ui/clone_on_copy.rs @@ -90,6 +90,12 @@ mod issue3052 { let a = A; let _: E = a.clone(); //~^ clone_on_copy + let _: E = E::clone(&a); + //~^ clone_on_copy + let _: E = Clone::clone(&a); + //~^ clone_on_copy + let _: E = ::clone(&a); + //~^ clone_on_copy let _: E = *****a; } @@ -100,13 +106,23 @@ fn issue4348() { ch.is_ascii() } - let mut x = 43; - let _ = &x.clone(); // ok, getting a ref 'a'.clone().make_ascii_uppercase(); // ok, clone and then mutate is_ascii('z'.clone()); //~^ clone_on_copy } +fn issue16969() { + let mut x = 43; + let _ = &x.clone(); + + let _ = &mut x.clone(); + + let mut y = &42; + let _ = &y.clone(); + + let _ = &mut y.clone(); +} + #[expect(clippy::vec_init_then_push)] fn issue5436() { let mut vec = Vec::new(); @@ -116,8 +132,152 @@ fn issue5436() { fn issue9277() -> Option { let opt: &Option = &None; - let value = opt.clone()?; // operator precedence needed (*opt)? - // - //~^^ clone_on_copy + // operator precedence needed (*opt)? + let value = opt.clone()?; + //~^ clone_on_copy None } + +mod ufcs_clone_on_copy { + use std::cell::RefCell; + + fn is_ascii(ch: char) -> bool { + ch.is_ascii() + } + + #[derive(Clone, Copy)] + struct Foo; + impl Foo { + fn clone(&self) -> u32 { + 0 + } + } + + macro_rules! m { + ($e:expr) => {{ $e }}; + } + + #[derive(Clone, Copy)] + struct Bar { + field: i32, + } + + struct Wrap([u32; 2]); + impl core::ops::Deref for Wrap { + type Target = [u32; 2]; + fn deref(&self) -> &[u32; 2] { + &self.0 + } + } + + fn foo(_x: &i32) {} + + fn main() { + let mut x = 42_i32; + + let vec = vec![1]; + let _ = Vec::clone(&vec); // ok, not a Copy type + let _ = Clone::clone(&vec); // ok, not a Copy type + let opt_vec = Some(vec![1]); + let _ = Option::clone(&opt_vec); // ok, not a Copy type + let _ = Clone::clone(&opt_vec); // ok, not a Copy type + + let _ = i32::clone(&x); + //~^ clone_on_copy + let _ = Clone::clone(&x); + //~^ clone_on_copy + let _ = ::clone(&x); + //~^ clone_on_copy + + let ref_ref = &&42_i32; + // Clone::clone(ref_ref) and <&i32 as Clone>::clone(ref_ref) both return &i32, so it should be + // linted. + let _ = Clone::clone(ref_ref); + //~^ clone_on_copy + let _ = <&i32 as Clone>::clone(ref_ref); + //~^ clone_on_copy + + let imm_ref = &mut 43_i32; + let _ = i32::clone(&*imm_ref); + //~^ clone_on_copy + let _ = Clone::clone(&*imm_ref); + //~^ clone_on_copy + let _ = ::clone(&*imm_ref); + //~^ clone_on_copy + + let x_ref = &mut x; + let _ = i32::clone(&*x_ref); + //~^ clone_on_copy + let _ = Clone::clone(&*x_ref); + //~^ clone_on_copy + let _ = ::clone(&*x_ref); + //~^ clone_on_copy + + let _ = i32::clone(&x).rotate_left(1); + //~^ clone_on_copy + let _ = Clone::clone(&x).rotate_left(1); + //~^ clone_on_copy + let _ = ::clone(&x).rotate_left(1); + //~^ clone_on_copy + + char::clone(&'a').make_ascii_uppercase(); // ok, clone and then mutate + Clone::clone(&'a').make_ascii_uppercase(); // ok, clone and then mutate + ::clone(&'a').make_ascii_uppercase(); // ok, clone and then mutate + + is_ascii(char::clone(&'z')); + //~^ clone_on_copy + is_ascii(Clone::clone(&'z')); + //~^ clone_on_copy + is_ascii(::clone(&'z')); + //~^ clone_on_copy + + let _ = Foo::clone(&Foo); // ok, this is not the clone trait + + let _ = Clone::clone(&m!(42)); + //~^ clone_on_copy + + let rc = RefCell::new(0); + let _ = Clone::clone(&*rc.borrow()); + //~^ clone_on_copy + + let bar = Bar { field: 0 }; + let _ = Clone::clone(&bar).field; + //~^ clone_on_copy + + let array = [0, 0]; + let _ = Clone::clone(&array)[0]; + //~^ clone_on_copy + + let wrapped = Wrap([0, 0]); + let _ = Clone::clone(&*wrapped)[0]; + //~^ clone_on_copy + + let _: &i32 = &i32::clone(&x); + let _: &i32 = &Clone::clone(&x); + let _: &i32 = &::clone(&x); + + let _: &mut i32 = &mut i32::clone(&x); + let _: &mut i32 = &mut Clone::clone(&x); + let _: &mut i32 = &mut ::clone(&x); + + let ref _y = i32::clone(&x); // ok, binds by reference + let ref _y = Clone::clone(&x); // ok, binds by reference + let ref mut _y = ::clone(&x); // ok, binds by reference + + foo(&i32::clone(&x)); + foo(&Clone::clone(&x)); + foo(&::clone(&x)); + } + + fn option_clone_on_copy() -> Option { + let opt: &Option = &Some(0); + + let _ = Option::clone(opt)?; + //~^ clone_on_copy + let _ = Clone::clone(opt)?; + //~^ clone_on_copy + let _ = as Clone>::clone(opt)?; + //~^ clone_on_copy + None + } +} diff --git a/src/tools/clippy/tests/ui/clone_on_copy.stderr b/src/tools/clippy/tests/ui/clone_on_copy.stderr index 0198f8e42430c..c1bf811529029 100644 --- a/src/tools/clippy/tests/ui/clone_on_copy.stderr +++ b/src/tools/clippy/tests/ui/clone_on_copy.stderr @@ -43,23 +43,191 @@ error: using `clone` on type `E` which implements the `Copy` trait LL | let _: E = a.clone(); | ^^^^^^^^^ help: try dereferencing it: `*****a` +error: using `clone` on type `E` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:93:20 + | +LL | let _: E = E::clone(&a); + | ^^^^^^^^^^^^ help: try dereferencing it: `*****a` + +error: using `clone` on type `E` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:95:20 + | +LL | let _: E = Clone::clone(&a); + | ^^^^^^^^^^^^^^^^ help: try dereferencing it: `*****a` + +error: using `clone` on type `E` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:97:20 + | +LL | let _: E = ::clone(&a); + | ^^^^^^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `*****a` + error: using `clone` on type `char` which implements the `Copy` trait - --> tests/ui/clone_on_copy.rs:106:14 + --> tests/ui/clone_on_copy.rs:110:14 | LL | is_ascii('z'.clone()); | ^^^^^^^^^^^ help: try removing the `clone` call: `'z'` error: using `clone` on type `i32` which implements the `Copy` trait - --> tests/ui/clone_on_copy.rs:113:14 + --> tests/ui/clone_on_copy.rs:129:14 | LL | vec.push(42.clone()); | ^^^^^^^^^^ help: try removing the `clone` call: `42` error: using `clone` on type `Option` which implements the `Copy` trait - --> tests/ui/clone_on_copy.rs:119:17 + --> tests/ui/clone_on_copy.rs:136:17 | -LL | let value = opt.clone()?; // operator precedence needed (*opt)? +LL | let value = opt.clone()?; | ^^^^^^^^^^^ help: try dereferencing it: `(*opt)` -error: aborting due to 10 previous errors +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:185:17 + | +LL | let _ = i32::clone(&x); + | ^^^^^^^^^^^^^^ help: try removing the `clone` call: `x` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:187:17 + | +LL | let _ = Clone::clone(&x); + | ^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `x` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:189:17 + | +LL | let _ = ::clone(&x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `x` + +error: using `clone` on type `&i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:195:17 + | +LL | let _ = Clone::clone(ref_ref); + | ^^^^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `*ref_ref` + +error: using `clone` on type `&i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:197:17 + | +LL | let _ = <&i32 as Clone>::clone(ref_ref); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `*ref_ref` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:201:17 + | +LL | let _ = i32::clone(&*imm_ref); + | ^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `*imm_ref` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:203:17 + | +LL | let _ = Clone::clone(&*imm_ref); + | ^^^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `*imm_ref` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:205:17 + | +LL | let _ = ::clone(&*imm_ref); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `*imm_ref` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:209:17 + | +LL | let _ = i32::clone(&*x_ref); + | ^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `*x_ref` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:211:17 + | +LL | let _ = Clone::clone(&*x_ref); + | ^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `*x_ref` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:213:17 + | +LL | let _ = ::clone(&*x_ref); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `*x_ref` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:216:17 + | +LL | let _ = i32::clone(&x).rotate_left(1); + | ^^^^^^^^^^^^^^ help: try removing the `clone` call: `x` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:218:17 + | +LL | let _ = Clone::clone(&x).rotate_left(1); + | ^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `x` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:220:17 + | +LL | let _ = ::clone(&x).rotate_left(1); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `x` + +error: using `clone` on type `char` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:227:18 + | +LL | is_ascii(char::clone(&'z')); + | ^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `'z'` + +error: using `clone` on type `char` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:229:18 + | +LL | is_ascii(Clone::clone(&'z')); + | ^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `'z'` + +error: using `clone` on type `char` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:231:18 + | +LL | is_ascii(::clone(&'z')); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `'z'` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:236:17 + | +LL | let _ = Clone::clone(&m!(42)); + | ^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `m!(42)` + +error: using `clone` on type `i32` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:240:17 + | +LL | let _ = Clone::clone(&*rc.borrow()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `*rc.borrow()` + +error: using `clone` on type `Bar` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:244:17 + | +LL | let _ = Clone::clone(&bar).field; + | ^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `bar` + +error: using `clone` on type `[i32; 2]` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:248:17 + | +LL | let _ = Clone::clone(&array)[0]; + | ^^^^^^^^^^^^^^^^^^^^ help: try removing the `clone` call: `array` + +error: using `clone` on type `[u32; 2]` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:252:17 + | +LL | let _ = Clone::clone(&*wrapped)[0]; + | ^^^^^^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `(*wrapped)` + +error: using `clone` on type `Option` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:275:17 + | +LL | let _ = Option::clone(opt)?; + | ^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `(*opt)` + +error: using `clone` on type `Option` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:277:17 + | +LL | let _ = Clone::clone(opt)?; + | ^^^^^^^^^^^^^^^^^ help: try dereferencing it: `(*opt)` + +error: using `clone` on type `Option` which implements the `Copy` trait + --> tests/ui/clone_on_copy.rs:279:17 + | +LL | let _ = as Clone>::clone(opt)?; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `(*opt)` + +error: aborting due to 38 previous errors diff --git a/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.fixed b/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.fixed index c7ebe17c4b94c..2ba43cb6b588d 100644 --- a/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.fixed +++ b/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.fixed @@ -1,6 +1,6 @@ #![feature(float_minimum_maximum)] #![warn(clippy::confusing_method_to_numeric_cast)] -#![allow(function_casts_as_integer, deprecated)] +#![allow(deprecated, function_casts_as_integer)] fn main() { let _ = u16::MAX as usize; //~ confusing_method_to_numeric_cast diff --git a/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.rs b/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.rs index 00f8858551533..ec423e9a0b638 100644 --- a/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.rs +++ b/src/tools/clippy/tests/ui/confusing_method_to_numeric_cast.rs @@ -1,6 +1,6 @@ #![feature(float_minimum_maximum)] #![warn(clippy::confusing_method_to_numeric_cast)] -#![allow(function_casts_as_integer, deprecated)] +#![allow(deprecated, function_casts_as_integer)] fn main() { let _ = u16::max as usize; //~ confusing_method_to_numeric_cast diff --git a/src/tools/clippy/tests/ui/doc/doc_paragraph_missing_punctuation_split_16169.rs b/src/tools/clippy/tests/ui/doc/doc_paragraph_missing_punctuation_split_16169.rs index c01b0c90b120e..f85855b648b04 100644 --- a/src/tools/clippy/tests/ui/doc/doc_paragraph_missing_punctuation_split_16169.rs +++ b/src/tools/clippy/tests/ui/doc/doc_paragraph_missing_punctuation_split_16169.rs @@ -9,5 +9,4 @@ pub fn dont_warn_inner_outer() { /// #[inline] ///w -pub fn dont_warn_split_by_attr() { -} +pub fn dont_warn_split_by_attr() {} diff --git a/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.fixed b/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.fixed index faabbb381318e..e45403636d303 100644 --- a/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.fixed +++ b/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.fixed @@ -181,3 +181,11 @@ struct BlockDocComment; #[doc = ""] /// ``` struct DocAttribute; + +// Should not trigger when given simply an image which is also a link. +/// [![git]](https://github.com/rust-lang/rust) +/// +/// [git]: https://rustfoundation.org/wp-content/uploads/2024/07/cropped-rust-lang-logo-black-270x270.png +fn rust_is_cool() ->i32{ + 1 +} diff --git a/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.rs b/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.rs index 9821115601a65..82273e2c8fbf4 100644 --- a/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.rs +++ b/src/tools/clippy/tests/ui/doc/doc_paragraphs_missing_punctuation.rs @@ -181,3 +181,11 @@ struct BlockDocComment; #[doc = ""] /// ``` struct DocAttribute; + +// Should not trigger when given simply an image which is also a link. +/// [![git]](https://github.com/rust-lang/rust) +/// +/// [git]: https://rustfoundation.org/wp-content/uploads/2024/07/cropped-rust-lang-logo-black-270x270.png +fn rust_is_cool() ->i32{ + 1 +} diff --git a/src/tools/clippy/tests/ui/double_must_use.stderr b/src/tools/clippy/tests/ui/double_must_use.stderr index 89189bcc49fef..edb56104e6f24 100644 --- a/src/tools/clippy/tests/ui/double_must_use.stderr +++ b/src/tools/clippy/tests/ui/double_must_use.stderr @@ -1,4 +1,4 @@ -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use.rs:8:1 | LL | #[must_use] @@ -10,7 +10,7 @@ LL | pub fn must_use_result() -> Result<(), ()> { = note: `-D clippy::double-must-use` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::double_must_use)]` -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use.rs:15:1 | LL | #[must_use] @@ -18,9 +18,14 @@ LL | #[must_use] LL | pub fn must_use_tuple() -> (Result<(), ()>, u8) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | +note: the return type is `std::result::Result` in tuple element 0 + --> tests/ui/double_must_use.rs:15:28 + | +LL | pub fn must_use_tuple() -> (Result<(), ()>, u8) { + | ^^^^^^^^^^^^^^^^^^^^ = note: alternatively, you may add an explicit reason to the `must_use` attribute -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use.rs:22:1 | LL | #[must_use] @@ -28,9 +33,14 @@ LL | #[must_use] LL | pub fn must_use_array() -> [Result<(), ()>; 1] { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | +note: the return type is array of `std::result::Result`s + --> tests/ui/double_must_use.rs:22:28 + | +LL | pub fn must_use_array() -> [Result<(), ()>; 1] { + | ^^^^^^^^^^^^^^^^^^^ = note: alternatively, you may add an explicit reason to the `must_use` attribute -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use.rs:40:1 | LL | #[must_use] @@ -38,9 +48,14 @@ LL | #[must_use] LL | async fn async_must_use_result() -> Result<(), ()> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | +note: the return type is implementer of `std::future::Future` + --> tests/ui/double_must_use.rs:40:37 + | +LL | async fn async_must_use_result() -> Result<(), ()> { + | ^^^^^^^^^^^^^^ = note: alternatively, you may add an explicit reason to the `must_use` attribute -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use.rs:55:1 | LL | #[must_use] @@ -48,9 +63,14 @@ LL | #[must_use] LL | pub fn must_use_result_with_uninhabited_2() -> Result { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | +note: the return type is `T` in a `Result` with an uninhabited error + --> tests/ui/double_must_use.rs:55:48 + | +LL | pub fn must_use_result_with_uninhabited_2() -> Result { + | ^^^^^^^^^^^^ = note: alternatively, you may add an explicit reason to the `must_use` attribute -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use.rs:66:1 | LL | #[must_use] @@ -58,6 +78,11 @@ LL | #[must_use] LL | pub fn must_use_controlflow_with_uninhabited_2() -> ControlFlow { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | +note: the return type is `T` in a `ControlFlow` with an uninhabited break + --> tests/ui/double_must_use.rs:66:53 + | +LL | pub fn must_use_controlflow_with_uninhabited_2() -> ControlFlow { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: alternatively, you may add an explicit reason to the `must_use` attribute error: aborting due to 6 previous errors diff --git a/src/tools/clippy/tests/ui/double_must_use_unfixable.stderr b/src/tools/clippy/tests/ui/double_must_use_unfixable.stderr index ce3de9e36de88..5d9c02e5d6cea 100644 --- a/src/tools/clippy/tests/ui/double_must_use_unfixable.stderr +++ b/src/tools/clippy/tests/ui/double_must_use_unfixable.stderr @@ -1,4 +1,4 @@ -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use_unfixable.rs:6:1 | LL | pub fn issue_12320() -> Result<(), ()> { @@ -13,7 +13,7 @@ LL | #[cfg_attr(all(), must_use, deprecated)] = note: `-D clippy::double-must-use` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::double_must_use)]` -error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` +error: this function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]` --> tests/ui/double_must_use_unfixable.rs:12:1 | LL | pub fn issue_12320_2() -> Result<(), ()> { diff --git a/src/tools/clippy/tests/ui/duration_suboptimal_units.stderr b/src/tools/clippy/tests/ui/duration_suboptimal_units.stderr index f106005c2bbc5..0d1ee48b36df1 100644 --- a/src/tools/clippy/tests/ui/duration_suboptimal_units.stderr +++ b/src/tools/clippy/tests/ui/duration_suboptimal_units.stderr @@ -6,7 +6,7 @@ LL | let dur = Duration::from_secs(60 * 3); | = note: `-D clippy::duration-suboptimal-units` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::duration_suboptimal_units)]` -help: try using from_mins +help: try using `Duration::from_mins` | LL - let dur = Duration::from_secs(60 * 3); LL + let dur = Duration::from_mins(3); @@ -18,7 +18,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_secs(10 * 60); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_mins +help: try using `Duration::from_mins` | LL - let dur = Duration::from_secs(10 * 60); LL + let dur = Duration::from_mins(10); @@ -30,7 +30,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_mins(24 * 60); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - let dur = Duration::from_mins(24 * 60); LL + let dur = Duration::from_hours(24); @@ -42,7 +42,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_millis(5 * 1000); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_secs +help: try using `Duration::from_secs` | LL - let dur = Duration::from_millis(5 * 1000); LL + let dur = Duration::from_secs(5); @@ -54,7 +54,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_nanos(13 * 60 * 60 * 1_000 * 1_000 * 1_000); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - let dur = Duration::from_nanos(13 * 60 * 60 * 1_000 * 1_000 * 1_000); LL + let dur = Duration::from_hours(13); @@ -66,7 +66,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_millis(1000 * 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_secs +help: try using `Duration::from_secs` | LL - let dur = Duration::from_millis(1000 * 5); LL + let dur = Duration::from_secs(5); @@ -78,7 +78,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_millis(11000); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_secs +help: try using `Duration::from_secs` | LL - let dur = Duration::from_millis(11000); LL + let dur = Duration::from_secs(11); @@ -90,7 +90,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_secs(39600); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - let dur = Duration::from_secs(39600); LL + let dur = Duration::from_hours(11); @@ -102,7 +102,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_secs(3 * 60); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_mins +help: try using `Duration::from_mins` | LL - let dur = Duration::from_secs(3 * 60); LL + let dur = Duration::from_mins(3); @@ -114,7 +114,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_mins(24 * 60); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - let dur = Duration::from_mins(24 * 60); LL + let dur = Duration::from_hours(24); @@ -126,7 +126,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | std::time::Duration::from_secs(12 * 60); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_mins +help: try using `Duration::from_mins` | LL - std::time::Duration::from_secs(12 * 60); LL + std::time::Duration::from_mins(12); @@ -138,7 +138,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | assert_eq!(Duration::from_secs(60 * 60), Duration::from_mins(6)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - assert_eq!(Duration::from_secs(60 * 60), Duration::from_mins(6)); LL + assert_eq!(Duration::from_hours(1), Duration::from_mins(6)); @@ -154,7 +154,7 @@ LL | let dur = mac!(duration); | -------------- in this macro invocation | = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) -help: try using from_mins +help: try using `Duration::from_mins` | LL - Duration::from_secs(60 * 5) LL + Duration::from_mins(5) @@ -166,7 +166,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | _ = Duration::from_secs(67_768_040_922_076_800); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - _ = Duration::from_secs(67_768_040_922_076_800); LL + _ = Duration::from_hours(18824455811688); @@ -178,7 +178,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_millis(20_000); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_secs +help: try using `Duration::from_secs` | LL - let dur = Duration::from_millis(20_000); LL + let dur = Duration::from_secs(20); @@ -190,7 +190,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_mins(720); | ^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - let dur = Duration::from_mins(720); LL + let dur = Duration::from_hours(12); @@ -202,7 +202,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_secs(660); | ^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_mins +help: try using `Duration::from_mins` | LL - let dur = Duration::from_secs(660); LL + let dur = Duration::from_mins(11); @@ -214,7 +214,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_secs(60 * 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_mins +help: try using `Duration::from_mins` | LL - let dur = Duration::from_secs(60 * 5); LL + let dur = Duration::from_mins(5); @@ -226,7 +226,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_mins(60 * 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - let dur = Duration::from_mins(60 * 2); LL + let dur = Duration::from_hours(2); @@ -238,7 +238,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_mins(60 * 24); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_hours +help: try using `Duration::from_hours` | LL - let dur = Duration::from_mins(60 * 24); LL + let dur = Duration::from_hours(24); diff --git a/src/tools/clippy/tests/ui/duration_suboptimal_units_days_weeks.stderr b/src/tools/clippy/tests/ui/duration_suboptimal_units_days_weeks.stderr index 8e8dbfe13fc95..7e3dd0fbfab7c 100644 --- a/src/tools/clippy/tests/ui/duration_suboptimal_units_days_weeks.stderr +++ b/src/tools/clippy/tests/ui/duration_suboptimal_units_days_weeks.stderr @@ -6,7 +6,7 @@ LL | let dur = Duration::from_secs(6000); | = note: `-D clippy::duration-suboptimal-units` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::duration_suboptimal_units)]` -help: try using from_mins +help: try using `Duration::from_mins` | LL - let dur = Duration::from_secs(6000); LL + let dur = Duration::from_mins(100); @@ -18,7 +18,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_hours(24000); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_days +help: try using `Duration::from_days` | LL - let dur = Duration::from_hours(24000); LL + let dur = Duration::from_days(1000); @@ -30,7 +30,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_nanos(13 * 7 * 24 * 60 * 60 * 1_000 * 1_000 * 1_000); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_weeks +help: try using `Duration::from_weeks` | LL - let dur = Duration::from_nanos(13 * 7 * 24 * 60 * 60 * 1_000 * 1_000 * 1_000); LL + let dur = Duration::from_weeks(13); @@ -42,7 +42,7 @@ error: constructing a `Duration` using a smaller unit when a larger unit would b LL | let dur = Duration::from_hours(24 * 7); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: try using from_weeks +help: try using `Duration::from_weeks` | LL - let dur = Duration::from_hours(24 * 7); LL + let dur = Duration::from_weeks(1); diff --git a/src/tools/clippy/tests/ui/endian_bytes.rs b/src/tools/clippy/tests/ui/endian_bytes.rs deleted file mode 100644 index 9d3e25300a6c7..0000000000000 --- a/src/tools/clippy/tests/ui/endian_bytes.rs +++ /dev/null @@ -1,214 +0,0 @@ -#![expect(clippy::diverging_sub_expression)] -#![no_main] - -// FIXME(f16_f128): add these types when `{to_from}_*_bytes` are available - -macro_rules! fn_body { - () => { - 2u8.to_ne_bytes(); - //~^ host_endian_bytes - 2i8.to_ne_bytes(); - //~^ host_endian_bytes - 2u16.to_ne_bytes(); - //~^ host_endian_bytes - 2i16.to_ne_bytes(); - //~^ host_endian_bytes - 2u32.to_ne_bytes(); - //~^ host_endian_bytes - 2i32.to_ne_bytes(); - //~^ host_endian_bytes - 2u64.to_ne_bytes(); - //~^ host_endian_bytes - 2i64.to_ne_bytes(); - //~^ host_endian_bytes - 2u128.to_ne_bytes(); - //~^ host_endian_bytes - 2i128.to_ne_bytes(); - //~^ host_endian_bytes - 2.0f32.to_ne_bytes(); - //~^ host_endian_bytes - 2.0f64.to_ne_bytes(); - //~^ host_endian_bytes - 2usize.to_ne_bytes(); - //~^ host_endian_bytes - 2isize.to_ne_bytes(); - //~^ host_endian_bytes - u8::from_ne_bytes(todo!()); - //~^ host_endian_bytes - i8::from_ne_bytes(todo!()); - //~^ host_endian_bytes - u16::from_ne_bytes(todo!()); - //~^ host_endian_bytes - i16::from_ne_bytes(todo!()); - //~^ host_endian_bytes - u32::from_ne_bytes(todo!()); - //~^ host_endian_bytes - i32::from_ne_bytes(todo!()); - //~^ host_endian_bytes - u64::from_ne_bytes(todo!()); - //~^ host_endian_bytes - i64::from_ne_bytes(todo!()); - //~^ host_endian_bytes - u128::from_ne_bytes(todo!()); - //~^ host_endian_bytes - i128::from_ne_bytes(todo!()); - //~^ host_endian_bytes - usize::from_ne_bytes(todo!()); - //~^ host_endian_bytes - isize::from_ne_bytes(todo!()); - //~^ host_endian_bytes - f32::from_ne_bytes(todo!()); - //~^ host_endian_bytes - f64::from_ne_bytes(todo!()); - //~^ host_endian_bytes - - 2u8.to_le_bytes(); - //~^ little_endian_bytes - 2i8.to_le_bytes(); - //~^ little_endian_bytes - 2u16.to_le_bytes(); - //~^ little_endian_bytes - 2i16.to_le_bytes(); - //~^ little_endian_bytes - 2u32.to_le_bytes(); - //~^ little_endian_bytes - 2i32.to_le_bytes(); - //~^ little_endian_bytes - 2u64.to_le_bytes(); - //~^ little_endian_bytes - 2i64.to_le_bytes(); - //~^ little_endian_bytes - 2u128.to_le_bytes(); - //~^ little_endian_bytes - 2i128.to_le_bytes(); - //~^ little_endian_bytes - 2.0f32.to_le_bytes(); - //~^ little_endian_bytes - 2.0f64.to_le_bytes(); - //~^ little_endian_bytes - 2usize.to_le_bytes(); - //~^ little_endian_bytes - 2isize.to_le_bytes(); - //~^ little_endian_bytes - u8::from_le_bytes(todo!()); - //~^ little_endian_bytes - i8::from_le_bytes(todo!()); - //~^ little_endian_bytes - u16::from_le_bytes(todo!()); - //~^ little_endian_bytes - i16::from_le_bytes(todo!()); - //~^ little_endian_bytes - u32::from_le_bytes(todo!()); - //~^ little_endian_bytes - i32::from_le_bytes(todo!()); - //~^ little_endian_bytes - u64::from_le_bytes(todo!()); - //~^ little_endian_bytes - i64::from_le_bytes(todo!()); - //~^ little_endian_bytes - u128::from_le_bytes(todo!()); - //~^ little_endian_bytes - i128::from_le_bytes(todo!()); - //~^ little_endian_bytes - usize::from_le_bytes(todo!()); - //~^ little_endian_bytes - isize::from_le_bytes(todo!()); - //~^ little_endian_bytes - f32::from_le_bytes(todo!()); - //~^ little_endian_bytes - f64::from_le_bytes(todo!()); - //~^ little_endian_bytes - }; -} - -// bless breaks if I use fn_body too much (oops) -macro_rules! fn_body_smol { - () => { - 2u8.to_ne_bytes(); - //~^ host_endian_bytes - //~| host_endian_bytes - //~| host_endian_bytes - //~| host_endian_bytes - //~| host_endian_bytes - u8::from_ne_bytes(todo!()); - //~^ host_endian_bytes - //~| host_endian_bytes - //~| host_endian_bytes - //~| host_endian_bytes - //~| host_endian_bytes - - 2u8.to_le_bytes(); - //~^ little_endian_bytes - //~| little_endian_bytes - //~| little_endian_bytes - //~| little_endian_bytes - //~| little_endian_bytes - u8::from_le_bytes(todo!()); - //~^ little_endian_bytes - //~| little_endian_bytes - //~| little_endian_bytes - //~| little_endian_bytes - //~| little_endian_bytes - - 2u8.to_be_bytes(); - //~^ big_endian_bytes - //~| big_endian_bytes - //~| big_endian_bytes - //~| big_endian_bytes - //~| big_endian_bytes - u8::from_be_bytes(todo!()); - //~^ big_endian_bytes - //~| big_endian_bytes - //~| big_endian_bytes - //~| big_endian_bytes - //~| big_endian_bytes - }; -} - -#[rustfmt::skip] -#[warn(clippy::host_endian_bytes)] -fn host() { fn_body!(); } - -#[rustfmt::skip] -#[warn(clippy::little_endian_bytes)] -fn little() { fn_body!(); } - -#[rustfmt::skip] -#[warn(clippy::big_endian_bytes)] -fn big() { fn_body!(); } - -#[rustfmt::skip] -#[warn(clippy::host_endian_bytes)] -#[warn(clippy::big_endian_bytes)] -fn host_encourage_little() { fn_body_smol!(); } - -#[rustfmt::skip] -#[warn(clippy::host_endian_bytes)] -#[warn(clippy::little_endian_bytes)] -fn host_encourage_big() { fn_body_smol!(); } - -#[rustfmt::skip] -#[warn(clippy::host_endian_bytes)] -#[warn(clippy::little_endian_bytes)] -#[warn(clippy::big_endian_bytes)] -fn no_help() { fn_body_smol!(); } - -#[rustfmt::skip] -#[warn(clippy::little_endian_bytes)] -#[warn(clippy::big_endian_bytes)] -fn little_encourage_host() { fn_body_smol!(); } - -#[rustfmt::skip] -#[warn(clippy::host_endian_bytes)] -#[warn(clippy::little_endian_bytes)] -fn little_encourage_big() { fn_body_smol!(); } - -#[rustfmt::skip] -#[warn(clippy::big_endian_bytes)] -#[warn(clippy::little_endian_bytes)] -fn big_encourage_host() { fn_body_smol!(); } - -#[rustfmt::skip] -#[warn(clippy::host_endian_bytes)] -#[warn(clippy::big_endian_bytes)] -fn big_encourage_little() { fn_body_smol!(); } diff --git a/src/tools/clippy/tests/ui/endian_bytes.stderr b/src/tools/clippy/tests/ui/endian_bytes.stderr deleted file mode 100644 index f1f27dca8db2b..0000000000000 --- a/src/tools/clippy/tests/ui/endian_bytes.stderr +++ /dev/null @@ -1,1034 +0,0 @@ -error: usage of the `u8::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:8:9 - | -LL | 2u8.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: `-D clippy::host-endian-bytes` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::host_endian_bytes)]` - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i8::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:10:9 - | -LL | 2i8.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u16::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:12:9 - | -LL | 2u16.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i16::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:14:9 - | -LL | 2i16.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u32::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:16:9 - | -LL | 2u32.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i32::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:18:9 - | -LL | 2i32.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u64::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:20:9 - | -LL | 2u64.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i64::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:22:9 - | -LL | 2i64.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u128::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:24:9 - | -LL | 2u128.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i128::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:26:9 - | -LL | 2i128.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `f32::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:28:9 - | -LL | 2.0f32.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `f64::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:30:9 - | -LL | 2.0f64.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `usize::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:32:9 - | -LL | 2usize.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `isize::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:34:9 - | -LL | 2isize.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_ne_bytes` - --> tests/ui/endian_bytes.rs:36:9 - | -LL | u8::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i8::from_ne_bytes` - --> tests/ui/endian_bytes.rs:38:9 - | -LL | i8::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u16::from_ne_bytes` - --> tests/ui/endian_bytes.rs:40:9 - | -LL | u16::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i16::from_ne_bytes` - --> tests/ui/endian_bytes.rs:42:9 - | -LL | i16::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u32::from_ne_bytes` - --> tests/ui/endian_bytes.rs:44:9 - | -LL | u32::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i32::from_ne_bytes` - --> tests/ui/endian_bytes.rs:46:9 - | -LL | i32::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u64::from_ne_bytes` - --> tests/ui/endian_bytes.rs:48:9 - | -LL | u64::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i64::from_ne_bytes` - --> tests/ui/endian_bytes.rs:50:9 - | -LL | i64::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u128::from_ne_bytes` - --> tests/ui/endian_bytes.rs:52:9 - | -LL | u128::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i128::from_ne_bytes` - --> tests/ui/endian_bytes.rs:54:9 - | -LL | i128::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `usize::from_ne_bytes` - --> tests/ui/endian_bytes.rs:56:9 - | -LL | usize::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `isize::from_ne_bytes` - --> tests/ui/endian_bytes.rs:58:9 - | -LL | isize::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `f32::from_ne_bytes` - --> tests/ui/endian_bytes.rs:60:9 - | -LL | f32::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `f64::from_ne_bytes` - --> tests/ui/endian_bytes.rs:62:9 - | -LL | f64::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host() { fn_body!(); } - | ---------- in this macro invocation - | - = help: specify the desired endianness explicitly - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_le_bytes` method - --> tests/ui/endian_bytes.rs:65:9 - | -LL | 2u8.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: `-D clippy::little-endian-bytes` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::little_endian_bytes)]` - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i8::to_le_bytes` method - --> tests/ui/endian_bytes.rs:67:9 - | -LL | 2i8.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u16::to_le_bytes` method - --> tests/ui/endian_bytes.rs:69:9 - | -LL | 2u16.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i16::to_le_bytes` method - --> tests/ui/endian_bytes.rs:71:9 - | -LL | 2i16.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u32::to_le_bytes` method - --> tests/ui/endian_bytes.rs:73:9 - | -LL | 2u32.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i32::to_le_bytes` method - --> tests/ui/endian_bytes.rs:75:9 - | -LL | 2i32.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u64::to_le_bytes` method - --> tests/ui/endian_bytes.rs:77:9 - | -LL | 2u64.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i64::to_le_bytes` method - --> tests/ui/endian_bytes.rs:79:9 - | -LL | 2i64.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u128::to_le_bytes` method - --> tests/ui/endian_bytes.rs:81:9 - | -LL | 2u128.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `i128::to_le_bytes` method - --> tests/ui/endian_bytes.rs:83:9 - | -LL | 2i128.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `f32::to_le_bytes` method - --> tests/ui/endian_bytes.rs:85:9 - | -LL | 2.0f32.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `f64::to_le_bytes` method - --> tests/ui/endian_bytes.rs:87:9 - | -LL | 2.0f64.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `usize::to_le_bytes` method - --> tests/ui/endian_bytes.rs:89:9 - | -LL | 2usize.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `isize::to_le_bytes` method - --> tests/ui/endian_bytes.rs:91:9 - | -LL | 2isize.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_le_bytes` - --> tests/ui/endian_bytes.rs:93:9 - | -LL | u8::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i8::from_le_bytes` - --> tests/ui/endian_bytes.rs:95:9 - | -LL | i8::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u16::from_le_bytes` - --> tests/ui/endian_bytes.rs:97:9 - | -LL | u16::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i16::from_le_bytes` - --> tests/ui/endian_bytes.rs:99:9 - | -LL | i16::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u32::from_le_bytes` - --> tests/ui/endian_bytes.rs:101:9 - | -LL | u32::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i32::from_le_bytes` - --> tests/ui/endian_bytes.rs:103:9 - | -LL | i32::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u64::from_le_bytes` - --> tests/ui/endian_bytes.rs:105:9 - | -LL | u64::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i64::from_le_bytes` - --> tests/ui/endian_bytes.rs:107:9 - | -LL | i64::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u128::from_le_bytes` - --> tests/ui/endian_bytes.rs:109:9 - | -LL | u128::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `i128::from_le_bytes` - --> tests/ui/endian_bytes.rs:111:9 - | -LL | i128::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `usize::from_le_bytes` - --> tests/ui/endian_bytes.rs:113:9 - | -LL | usize::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `isize::from_le_bytes` - --> tests/ui/endian_bytes.rs:115:9 - | -LL | isize::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `f32::from_le_bytes` - --> tests/ui/endian_bytes.rs:117:9 - | -LL | f32::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `f64::from_le_bytes` - --> tests/ui/endian_bytes.rs:119:9 - | -LL | f64::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little() { fn_body!(); } - | ---------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:127:9 - | -LL | 2u8.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_le_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_ne_bytes` - --> tests/ui/endian_bytes.rs:133:9 - | -LL | u8::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_le_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_be_bytes` method - --> tests/ui/endian_bytes.rs:153:9 - | -LL | 2u8.to_be_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_le_bytes` instead - = note: `-D clippy::big-endian-bytes` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::big_endian_bytes)]` - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_be_bytes` - --> tests/ui/endian_bytes.rs:159:9 - | -LL | u8::from_be_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_le_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:127:9 - | -LL | 2u8.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_ne_bytes` - --> tests/ui/endian_bytes.rs:133:9 - | -LL | u8::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_le_bytes` method - --> tests/ui/endian_bytes.rs:140:9 - | -LL | 2u8.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_le_bytes` - --> tests/ui/endian_bytes.rs:146:9 - | -LL | u8::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn host_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:127:9 - | -LL | 2u8.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn no_help() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_ne_bytes` - --> tests/ui/endian_bytes.rs:133:9 - | -LL | u8::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn no_help() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_le_bytes` method - --> tests/ui/endian_bytes.rs:140:9 - | -LL | 2u8.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn no_help() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_le_bytes` - --> tests/ui/endian_bytes.rs:146:9 - | -LL | u8::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn no_help() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_be_bytes` method - --> tests/ui/endian_bytes.rs:153:9 - | -LL | 2u8.to_be_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn no_help() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_be_bytes` - --> tests/ui/endian_bytes.rs:159:9 - | -LL | u8::from_be_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn no_help() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_le_bytes` method - --> tests/ui/endian_bytes.rs:140:9 - | -LL | 2u8.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_le_bytes` - --> tests/ui/endian_bytes.rs:146:9 - | -LL | u8::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_be_bytes` method - --> tests/ui/endian_bytes.rs:153:9 - | -LL | 2u8.to_be_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_be_bytes` - --> tests/ui/endian_bytes.rs:159:9 - | -LL | u8::from_be_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:127:9 - | -LL | 2u8.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_ne_bytes` - --> tests/ui/endian_bytes.rs:133:9 - | -LL | u8::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_le_bytes` method - --> tests/ui/endian_bytes.rs:140:9 - | -LL | 2u8.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_le_bytes` - --> tests/ui/endian_bytes.rs:146:9 - | -LL | u8::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn little_encourage_big() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_be_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_le_bytes` method - --> tests/ui/endian_bytes.rs:140:9 - | -LL | 2u8.to_le_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_le_bytes` - --> tests/ui/endian_bytes.rs:146:9 - | -LL | u8::from_le_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_be_bytes` method - --> tests/ui/endian_bytes.rs:153:9 - | -LL | 2u8.to_be_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_be_bytes` - --> tests/ui/endian_bytes.rs:159:9 - | -LL | u8::from_be_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_host() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use the native endianness instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_ne_bytes` method - --> tests/ui/endian_bytes.rs:127:9 - | -LL | 2u8.to_ne_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_le_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_ne_bytes` - --> tests/ui/endian_bytes.rs:133:9 - | -LL | u8::from_ne_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_le_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the `u8::to_be_bytes` method - --> tests/ui/endian_bytes.rs:153:9 - | -LL | 2u8.to_be_bytes(); - | ^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::to_le_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: usage of the function `u8::from_be_bytes` - --> tests/ui/endian_bytes.rs:159:9 - | -LL | u8::from_be_bytes(todo!()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn big_encourage_little() { fn_body_smol!(); } - | --------------- in this macro invocation - | - = help: use `u8::from_le_bytes` instead - = note: this error originates in the macro `fn_body_smol` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: aborting due to 86 previous errors - diff --git a/src/tools/clippy/tests/ui/exit1.rs b/src/tools/clippy/tests/ui/exit1.rs index be8752cc7d8e2..a172848df51d5 100644 --- a/src/tools/clippy/tests/ui/exit1.rs +++ b/src/tools/clippy/tests/ui/exit1.rs @@ -1,3 +1,4 @@ +//@aux-build: proc_macros.rs #![warn(clippy::exit)] fn not_main() { @@ -14,3 +15,21 @@ fn main() { not_main(); std::process::exit(1); } + +fn issue17082() { + macro_rules! mac { + ($x:expr) => {{ + $x; + }}; + (ex $x:expr) => {{ + std::process::exit($x); + //~^ exit + }}; + } + mac!(std::process::exit(1)); + //~^ exit + mac!(ex 1); + proc_macros::external! { + std::process::exit(1); + } +} diff --git a/src/tools/clippy/tests/ui/exit1.stderr b/src/tools/clippy/tests/ui/exit1.stderr index 2158314b7c7b1..9398d2f7f4399 100644 --- a/src/tools/clippy/tests/ui/exit1.stderr +++ b/src/tools/clippy/tests/ui/exit1.stderr @@ -1,5 +1,5 @@ error: usage of `process::exit` - --> tests/ui/exit1.rs:5:9 + --> tests/ui/exit1.rs:6:9 | LL | std::process::exit(4); | ^^^^^^^^^^^^^^^^^^^^^ @@ -7,5 +7,22 @@ LL | std::process::exit(4); = note: `-D clippy::exit` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::exit)]` -error: aborting due to 1 previous error +error: usage of `process::exit` + --> tests/ui/exit1.rs:29:10 + | +LL | mac!(std::process::exit(1)); + | ^^^^^^^^^^^^^^^^^^^^^ + +error: usage of `process::exit` + --> tests/ui/exit1.rs:25:13 + | +LL | std::process::exit($x); + | ^^^^^^^^^^^^^^^^^^^^^^ +... +LL | mac!(ex 1); + | ---------- in this macro invocation + | + = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 3 previous errors diff --git a/src/tools/clippy/tests/ui/float_cmp_const.rs b/src/tools/clippy/tests/ui/float_cmp_const.rs index 512963e971f0a..5aaf49b4da2bb 100644 --- a/src/tools/clippy/tests/ui/float_cmp_const.rs +++ b/src/tools/clippy/tests/ui/float_cmp_const.rs @@ -47,6 +47,17 @@ fn main() { ONE != f32::INFINITY; ONE == f32::NEG_INFINITY; + // assert_eq with const floats + assert_eq!(ONE, 1.0); + //~^ float_cmp_const + + assert_ne!(ONE, 2.0); + //~^ float_cmp_const + + let local = 0.9; + assert_eq!(local, ONE); + //~^ float_cmp_const + // no errors, but will warn clippy::float_cmp if '#![allow(float_cmp)]' above is removed let w = 1.1; v == w; diff --git a/src/tools/clippy/tests/ui/float_cmp_const.stderr b/src/tools/clippy/tests/ui/float_cmp_const.stderr index 482a55a54be69..ade1880a7491f 100644 --- a/src/tools/clippy/tests/ui/float_cmp_const.stderr +++ b/src/tools/clippy/tests/ui/float_cmp_const.stderr @@ -43,11 +43,29 @@ error: strict comparison of `f32` or `f64` constant LL | v != ONE; | ^^^^^^^^ help: consider comparing them within some margin of error: `(v - ONE).abs() > error_margin` +error: strict comparison of `f32` or `f64` constant + --> tests/ui/float_cmp_const.rs:51:5 + | +LL | assert_eq!(ONE, 1.0); + | ^^^^^^^^^^^^^^^^^^^^ + +error: strict comparison of `f32` or `f64` constant + --> tests/ui/float_cmp_const.rs:54:5 + | +LL | assert_ne!(ONE, 2.0); + | ^^^^^^^^^^^^^^^^^^^^ + +error: strict comparison of `f32` or `f64` constant + --> tests/ui/float_cmp_const.rs:58:5 + | +LL | assert_eq!(local, ONE); + | ^^^^^^^^^^^^^^^^^^^^^^ + error: strict comparison of `f32` or `f64` constant arrays - --> tests/ui/float_cmp_const.rs:68:5 + --> tests/ui/float_cmp_const.rs:79:5 | LL | NON_ZERO_ARRAY == NON_ZERO_ARRAY2; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 8 previous errors +error: aborting due to 11 previous errors diff --git a/src/tools/clippy/tests/ui/floating_point_mul_add.fixed b/src/tools/clippy/tests/ui/floating_point_mul_add.fixed index a4841d309d569..3e60b9efe5b0c 100644 --- a/src/tools/clippy/tests/ui/floating_point_mul_add.fixed +++ b/src/tools/clippy/tests/ui/floating_point_mul_add.fixed @@ -72,32 +72,46 @@ fn _issue11831() { fn _issue14897() { let x = 1.0; - let _ = x * 2.0 + 0.5; // should not suggest mul_add - let _ = 0.5 + x * 2.0; // should not suggest mul_add - let _ = 0.5 + x * 1.2; // should not suggest mul_add - let _ = 1.2 + x * 1.2; // should not suggest mul_add + let _ = f64::mul_add(x, 2.0, 0.5); + //~^ suboptimal_flops + + let x = 1.0; + let _ = f64::mul_add(x, 2.0, 0.5); + //~^ suboptimal_flops + let _ = f64::mul_add(x, 1.2, 0.5); + //~^ suboptimal_flops + let _ = f64::mul_add(x, 1.2, 1.2); + //~^ suboptimal_flops let x = -1.0; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = f64::mul_add(x, 1.2, 0.5); + //~^ suboptimal_flops let x = { 4.0 }; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = f64::mul_add(x, 1.2, 0.5); + //~^ suboptimal_flops let x = if 1 > 2 { 1.0 } else { 2.0 }; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = f64::mul_add(x, 1.2, 0.5); + //~^ suboptimal_flops let x = 2.4 + 1.2; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = f64::mul_add(x, 1.2, 0.5); + //~^ suboptimal_flops let f = || 4.0; let x = f(); - let _ = 0.5 + f() * 1.2; // should not suggest mul_add - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = f64::mul_add(f(), 1.2, 0.5); + //~^ suboptimal_flops + + let _ = f64::mul_add(x, 1.2, 0.5); + //~^ suboptimal_flops let x = 0.1; let y = x; let z = y; - let _ = 0.5 + z * 1.2; // should not suggest mul_add + let _ = f64::mul_add(z, 1.2, 0.5); + //~^ suboptimal_flops let _ = 2.0f64.mul_add(x, 0.5); //~^ suboptimal_flops @@ -125,3 +139,40 @@ fn issue16573() { a = b.mul_add(-c, a); //~^ suboptimal_flops } + +fn issue16954() { + let k = 2.0_f32; + + let k3 = k * k * k; + let y = k3 + 0.1; + let _ = y.mul_add(-0.3, 1.0); + //~^ suboptimal_flops + + let k3 = k * k * k; + let y = k3 + 0.1_f32; + let _ = y.mul_add(-0.3, 1.0); + //~^ suboptimal_flops + + let k3 = k * k * k; + let y: f32 = k3 + 0.1; + let _ = y.mul_add(-0.3, 1.0); + //~^ suboptimal_flops + + const OFFSET: f32 = 0.1; + let k3 = k * k * k; + let y = k3 + OFFSET; + let _ = y.mul_add(-0.3, 1.0); + //~^ suboptimal_flops + + let x = 0.1; + let y = 0.2; + let z = 0.3; + let _ = f32::mul_add(y, z, x); + //~^ suboptimal_flops + let _ = f32::mul_add(y, z, x); + //~^ suboptimal_flops + + let a: f32 = 0.1; + let _ = a.mul_add(z, y); + //~^ suboptimal_flops +} diff --git a/src/tools/clippy/tests/ui/floating_point_mul_add.rs b/src/tools/clippy/tests/ui/floating_point_mul_add.rs index c048653a41238..13625b4bb9ce5 100644 --- a/src/tools/clippy/tests/ui/floating_point_mul_add.rs +++ b/src/tools/clippy/tests/ui/floating_point_mul_add.rs @@ -72,32 +72,46 @@ fn _issue11831() { fn _issue14897() { let x = 1.0; - let _ = x * 2.0 + 0.5; // should not suggest mul_add - let _ = 0.5 + x * 2.0; // should not suggest mul_add - let _ = 0.5 + x * 1.2; // should not suggest mul_add - let _ = 1.2 + x * 1.2; // should not suggest mul_add + let _ = x * 2.0 + 0.5; + //~^ suboptimal_flops + + let x = 1.0; + let _ = 0.5 + x * 2.0; + //~^ suboptimal_flops + let _ = 0.5 + x * 1.2; + //~^ suboptimal_flops + let _ = 1.2 + x * 1.2; + //~^ suboptimal_flops let x = -1.0; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = 0.5 + x * 1.2; + //~^ suboptimal_flops let x = { 4.0 }; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = 0.5 + x * 1.2; + //~^ suboptimal_flops let x = if 1 > 2 { 1.0 } else { 2.0 }; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = 0.5 + x * 1.2; + //~^ suboptimal_flops let x = 2.4 + 1.2; - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = 0.5 + x * 1.2; + //~^ suboptimal_flops let f = || 4.0; let x = f(); - let _ = 0.5 + f() * 1.2; // should not suggest mul_add - let _ = 0.5 + x * 1.2; // should not suggest mul_add + let _ = 0.5 + f() * 1.2; + //~^ suboptimal_flops + + let _ = 0.5 + x * 1.2; + //~^ suboptimal_flops let x = 0.1; let y = x; let z = y; - let _ = 0.5 + z * 1.2; // should not suggest mul_add + let _ = 0.5 + z * 1.2; + //~^ suboptimal_flops let _ = 0.5 + 2.0 * x; //~^ suboptimal_flops @@ -125,3 +139,40 @@ fn issue16573() { a -= b * c; //~^ suboptimal_flops } + +fn issue16954() { + let k = 2.0_f32; + + let k3 = k * k * k; + let y = k3 + 0.1; + let _ = 1.0 - y * 0.3; + //~^ suboptimal_flops + + let k3 = k * k * k; + let y = k3 + 0.1_f32; + let _ = 1.0 - y * 0.3; + //~^ suboptimal_flops + + let k3 = k * k * k; + let y: f32 = k3 + 0.1; + let _ = 1.0 - y * 0.3; + //~^ suboptimal_flops + + const OFFSET: f32 = 0.1; + let k3 = k * k * k; + let y = k3 + OFFSET; + let _ = 1.0 - y * 0.3; + //~^ suboptimal_flops + + let x = 0.1; + let y = 0.2; + let z = 0.3; + let _ = x + y * z; + //~^ suboptimal_flops + let _ = y * z + x; + //~^ suboptimal_flops + + let a: f32 = 0.1; + let _ = y + a * z; + //~^ suboptimal_flops +} diff --git a/src/tools/clippy/tests/ui/floating_point_mul_add.stderr b/src/tools/clippy/tests/ui/floating_point_mul_add.stderr index b14d0585f2c96..f74a874c3351f 100644 --- a/src/tools/clippy/tests/ui/floating_point_mul_add.stderr +++ b/src/tools/clippy/tests/ui/floating_point_mul_add.stderr @@ -81,46 +81,154 @@ LL | let _ = a - (b * u as f64); | ^^^^^^^^^^^^^^^^^^ help: consider using: `b.mul_add(-(u as f64), a)` error: multiply and add expressions may be calculated more efficiently and accurately - --> tests/ui/floating_point_mul_add.rs:102:13 + --> tests/ui/floating_point_mul_add.rs:75:13 + | +LL | let _ = x * 2.0 + 0.5; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 2.0, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:79:13 + | +LL | let _ = 0.5 + x * 2.0; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 2.0, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:81:13 + | +LL | let _ = 0.5 + x * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:83:13 + | +LL | let _ = 1.2 + x * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 1.2, 1.2)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:87:13 + | +LL | let _ = 0.5 + x * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:91:13 + | +LL | let _ = 0.5 + x * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:95:13 + | +LL | let _ = 0.5 + x * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:99:13 + | +LL | let _ = 0.5 + x * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:104:13 + | +LL | let _ = 0.5 + f() * 1.2; + | ^^^^^^^^^^^^^^^ help: consider using: `f64::mul_add(f(), 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:107:13 + | +LL | let _ = 0.5 + x * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(x, 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:113:13 + | +LL | let _ = 0.5 + z * 1.2; + | ^^^^^^^^^^^^^ help: consider using: `f64::mul_add(z, 1.2, 0.5)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:116:13 | LL | let _ = 0.5 + 2.0 * x; | ^^^^^^^^^^^^^ help: consider using: `2.0f64.mul_add(x, 0.5)` error: multiply and add expressions may be calculated more efficiently and accurately - --> tests/ui/floating_point_mul_add.rs:104:13 + --> tests/ui/floating_point_mul_add.rs:118:13 | LL | let _ = 2.0 * x + 0.5; | ^^^^^^^^^^^^^ help: consider using: `2.0f64.mul_add(x, 0.5)` error: multiply and add expressions may be calculated more efficiently and accurately - --> tests/ui/floating_point_mul_add.rs:107:13 + --> tests/ui/floating_point_mul_add.rs:121:13 | LL | let _ = x + 2.0 * 4.0; | ^^^^^^^^^^^^^ help: consider using: `2.0f64.mul_add(4.0, x)` error: multiply and add expressions may be calculated more efficiently and accurately - --> tests/ui/floating_point_mul_add.rs:111:13 + --> tests/ui/floating_point_mul_add.rs:125:13 | LL | let _ = y * 2.0 + 0.5; | ^^^^^^^^^^^^^ help: consider using: `y.mul_add(2.0, 0.5)` error: multiply and add expressions may be calculated more efficiently and accurately - --> tests/ui/floating_point_mul_add.rs:113:13 + --> tests/ui/floating_point_mul_add.rs:127:13 | LL | let _ = 1.0 * 2.0 + 0.5; | ^^^^^^^^^^^^^^^ help: consider using: `1.0f64.mul_add(2.0, 0.5)` error: multiply and add expressions may be calculated more efficiently and accurately - --> tests/ui/floating_point_mul_add.rs:122:5 + --> tests/ui/floating_point_mul_add.rs:136:5 | LL | a += b * c; | ^^^^^^^^^^ help: consider using: `a = b.mul_add(c, a)` error: multiply and add expressions may be calculated more efficiently and accurately - --> tests/ui/floating_point_mul_add.rs:125:5 + --> tests/ui/floating_point_mul_add.rs:139:5 | LL | a -= b * c; | ^^^^^^^^^^ help: consider using: `a = b.mul_add(-c, a)` -error: aborting due to 20 previous errors +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:148:13 + | +LL | let _ = 1.0 - y * 0.3; + | ^^^^^^^^^^^^^ help: consider using: `y.mul_add(-0.3, 1.0)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:153:13 + | +LL | let _ = 1.0 - y * 0.3; + | ^^^^^^^^^^^^^ help: consider using: `y.mul_add(-0.3, 1.0)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:158:13 + | +LL | let _ = 1.0 - y * 0.3; + | ^^^^^^^^^^^^^ help: consider using: `y.mul_add(-0.3, 1.0)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:164:13 + | +LL | let _ = 1.0 - y * 0.3; + | ^^^^^^^^^^^^^ help: consider using: `y.mul_add(-0.3, 1.0)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:170:13 + | +LL | let _ = x + y * z; + | ^^^^^^^^^ help: consider using: `f32::mul_add(y, z, x)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:172:13 + | +LL | let _ = y * z + x; + | ^^^^^^^^^ help: consider using: `f32::mul_add(y, z, x)` + +error: multiply and add expressions may be calculated more efficiently and accurately + --> tests/ui/floating_point_mul_add.rs:176:13 + | +LL | let _ = y + a * z; + | ^^^^^^^^^ help: consider using: `a.mul_add(z, y)` + +error: aborting due to 38 previous errors diff --git a/src/tools/clippy/tests/ui/four_forward_slashes.fixed b/src/tools/clippy/tests/ui/four_forward_slashes.fixed index 43cded6446faf..2a860a493c5bd 100644 --- a/src/tools/clippy/tests/ui/four_forward_slashes.fixed +++ b/src/tools/clippy/tests/ui/four_forward_slashes.fixed @@ -47,3 +47,10 @@ with_span! { //// don't lint me bozo fn f() {} } + +// Regression test for #16168: an inner doc comment (`//!`) inside the body must not +// drag the `////` scan down into the body and flag a regular comment there. +fn inner_doc() { + //// I am not a doc comment! + //! inner doc comment +} diff --git a/src/tools/clippy/tests/ui/four_forward_slashes.rs b/src/tools/clippy/tests/ui/four_forward_slashes.rs index 4ff0c3afab491..2aeffb1931b35 100644 --- a/src/tools/clippy/tests/ui/four_forward_slashes.rs +++ b/src/tools/clippy/tests/ui/four_forward_slashes.rs @@ -47,3 +47,10 @@ with_span! { //// don't lint me bozo fn f() {} } + +// Regression test for #16168: an inner doc comment (`//!`) inside the body must not +// drag the `////` scan down into the body and flag a regular comment there. +fn inner_doc() { + //// I am not a doc comment! + //! inner doc comment +} diff --git a/src/tools/clippy/tests/ui/host_endian_bytes.1.fixed b/src/tools/clippy/tests/ui/host_endian_bytes.1.fixed new file mode 100644 index 0000000000000..d5f005c352a19 --- /dev/null +++ b/src/tools/clippy/tests/ui/host_endian_bytes.1.fixed @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::host_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_le_bytes(); //~ host_endian_bytes + let _ = 0u16.to_le_bytes(); //~ host_endian_bytes + let _ = 0u32.to_le_bytes(); //~ host_endian_bytes + let _ = 0u64.to_le_bytes(); //~ host_endian_bytes + let _ = 0u128.to_le_bytes(); //~ host_endian_bytes + let _ = 0usize.to_le_bytes(); //~ host_endian_bytes + + let _ = 0i8.to_le_bytes(); //~ host_endian_bytes + let _ = 0i16.to_le_bytes(); //~ host_endian_bytes + let _ = 0i32.to_le_bytes(); //~ host_endian_bytes + let _ = 0i64.to_le_bytes(); //~ host_endian_bytes + let _ = 0i128.to_le_bytes(); //~ host_endian_bytes + let _ = 0isize.to_le_bytes(); //~ host_endian_bytes + + let _ = 0f16.to_le_bytes(); //~ host_endian_bytes + let _ = 0f32.to_le_bytes(); //~ host_endian_bytes + let _ = 0f64.to_le_bytes(); //~ host_endian_bytes + let _ = 0f128.to_le_bytes(); //~ host_endian_bytes + + let _ = u8::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = u16::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = u32::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = u64::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = u128::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = usize::from_le_bytes([0; _]); //~ host_endian_bytes + + let _ = i8::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = i16::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = i32::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = i64::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = i128::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = isize::from_le_bytes([0; _]); //~ host_endian_bytes + + let _ = f16::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = f32::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = f64::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = f128::from_le_bytes([0; _]); //~ host_endian_bytes + }; + + { + let _ = u8::from_le_bytes; //~ host_endian_bytes + let _ = u8::to_le_bytes; //~ host_endian_bytes + } + + #[warn(clippy::big_endian_bytes)] + { + let _ = 0u8.to_le_bytes(); //~ host_endian_bytes + let _ = 0i8.to_le_bytes(); //~ host_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = i8::from_le_bytes([0; _]); //~ host_endian_bytes + }; + + #[warn(clippy::little_endian_bytes)] + { + let _ = 0u8.to_be_bytes(); //~ host_endian_bytes + let _ = 0i8.to_be_bytes(); //~ host_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = i8::from_be_bytes([0; _]); //~ host_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_le_bytes(); //~ host_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = 0u8.$to_le_bytes(); //~ host_endian_bytes + let _ = u8::$from_le_bytes([0; _]); //~ host_endian_bytes + }} + + external! { + let _ = 0u8.to_ne_bytes(); + let _ = u8::from_ne_bytes([0; _]); + let _ = 0u8.$to_le_bytes(); //~ host_endian_bytes + let _ = u8::$from_le_bytes([0; _]); //~ host_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/host_endian_bytes.2.fixed b/src/tools/clippy/tests/ui/host_endian_bytes.2.fixed new file mode 100644 index 0000000000000..4d75defb8e237 --- /dev/null +++ b/src/tools/clippy/tests/ui/host_endian_bytes.2.fixed @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::host_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_be_bytes(); //~ host_endian_bytes + let _ = 0u16.to_be_bytes(); //~ host_endian_bytes + let _ = 0u32.to_be_bytes(); //~ host_endian_bytes + let _ = 0u64.to_be_bytes(); //~ host_endian_bytes + let _ = 0u128.to_be_bytes(); //~ host_endian_bytes + let _ = 0usize.to_be_bytes(); //~ host_endian_bytes + + let _ = 0i8.to_be_bytes(); //~ host_endian_bytes + let _ = 0i16.to_be_bytes(); //~ host_endian_bytes + let _ = 0i32.to_be_bytes(); //~ host_endian_bytes + let _ = 0i64.to_be_bytes(); //~ host_endian_bytes + let _ = 0i128.to_be_bytes(); //~ host_endian_bytes + let _ = 0isize.to_be_bytes(); //~ host_endian_bytes + + let _ = 0f16.to_be_bytes(); //~ host_endian_bytes + let _ = 0f32.to_be_bytes(); //~ host_endian_bytes + let _ = 0f64.to_be_bytes(); //~ host_endian_bytes + let _ = 0f128.to_be_bytes(); //~ host_endian_bytes + + let _ = u8::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = u16::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = u32::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = u64::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = u128::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = usize::from_be_bytes([0; _]); //~ host_endian_bytes + + let _ = i8::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = i16::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = i32::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = i64::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = i128::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = isize::from_be_bytes([0; _]); //~ host_endian_bytes + + let _ = f16::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = f32::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = f64::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = f128::from_be_bytes([0; _]); //~ host_endian_bytes + }; + + { + let _ = u8::from_be_bytes; //~ host_endian_bytes + let _ = u8::to_be_bytes; //~ host_endian_bytes + } + + #[warn(clippy::big_endian_bytes)] + { + let _ = 0u8.to_le_bytes(); //~ host_endian_bytes + let _ = 0i8.to_le_bytes(); //~ host_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ host_endian_bytes + let _ = i8::from_le_bytes([0; _]); //~ host_endian_bytes + }; + + #[warn(clippy::little_endian_bytes)] + { + let _ = 0u8.to_be_bytes(); //~ host_endian_bytes + let _ = 0i8.to_be_bytes(); //~ host_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = i8::from_be_bytes([0; _]); //~ host_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_be_bytes(); //~ host_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ host_endian_bytes + let _ = 0u8.$to_be_bytes(); //~ host_endian_bytes + let _ = u8::$from_be_bytes([0; _]); //~ host_endian_bytes + }} + + external! { + let _ = 0u8.to_ne_bytes(); + let _ = u8::from_ne_bytes([0; _]); + let _ = 0u8.$to_be_bytes(); //~ host_endian_bytes + let _ = u8::$from_be_bytes([0; _]); //~ host_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/host_endian_bytes.rs b/src/tools/clippy/tests/ui/host_endian_bytes.rs new file mode 100644 index 0000000000000..d1f978da2f9a9 --- /dev/null +++ b/src/tools/clippy/tests/ui/host_endian_bytes.rs @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::host_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_ne_bytes(); //~ host_endian_bytes + let _ = 0u16.to_ne_bytes(); //~ host_endian_bytes + let _ = 0u32.to_ne_bytes(); //~ host_endian_bytes + let _ = 0u64.to_ne_bytes(); //~ host_endian_bytes + let _ = 0u128.to_ne_bytes(); //~ host_endian_bytes + let _ = 0usize.to_ne_bytes(); //~ host_endian_bytes + + let _ = 0i8.to_ne_bytes(); //~ host_endian_bytes + let _ = 0i16.to_ne_bytes(); //~ host_endian_bytes + let _ = 0i32.to_ne_bytes(); //~ host_endian_bytes + let _ = 0i64.to_ne_bytes(); //~ host_endian_bytes + let _ = 0i128.to_ne_bytes(); //~ host_endian_bytes + let _ = 0isize.to_ne_bytes(); //~ host_endian_bytes + + let _ = 0f16.to_ne_bytes(); //~ host_endian_bytes + let _ = 0f32.to_ne_bytes(); //~ host_endian_bytes + let _ = 0f64.to_ne_bytes(); //~ host_endian_bytes + let _ = 0f128.to_ne_bytes(); //~ host_endian_bytes + + let _ = u8::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = u16::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = u32::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = u64::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = u128::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = usize::from_ne_bytes([0; _]); //~ host_endian_bytes + + let _ = i8::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = i16::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = i32::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = i64::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = i128::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = isize::from_ne_bytes([0; _]); //~ host_endian_bytes + + let _ = f16::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = f32::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = f64::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = f128::from_ne_bytes([0; _]); //~ host_endian_bytes + }; + + { + let _ = u8::from_ne_bytes; //~ host_endian_bytes + let _ = u8::to_ne_bytes; //~ host_endian_bytes + } + + #[warn(clippy::big_endian_bytes)] + { + let _ = 0u8.to_ne_bytes(); //~ host_endian_bytes + let _ = 0i8.to_ne_bytes(); //~ host_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = i8::from_ne_bytes([0; _]); //~ host_endian_bytes + }; + + #[warn(clippy::little_endian_bytes)] + { + let _ = 0u8.to_ne_bytes(); //~ host_endian_bytes + let _ = 0i8.to_ne_bytes(); //~ host_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = i8::from_ne_bytes([0; _]); //~ host_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_ne_bytes(); //~ host_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ host_endian_bytes + let _ = 0u8.$to_ne_bytes(); //~ host_endian_bytes + let _ = u8::$from_ne_bytes([0; _]); //~ host_endian_bytes + }} + + external! { + let _ = 0u8.to_ne_bytes(); + let _ = u8::from_ne_bytes([0; _]); + let _ = 0u8.$to_ne_bytes(); //~ host_endian_bytes + let _ = u8::$from_ne_bytes([0; _]); //~ host_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/host_endian_bytes.stderr b/src/tools/clippy/tests/ui/host_endian_bytes.stderr new file mode 100644 index 0000000000000..a00126ea5ac3e --- /dev/null +++ b/src/tools/clippy/tests/ui/host_endian_bytes.stderr @@ -0,0 +1,734 @@ +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:12:21 + | +LL | let _ = 0u8.to_ne_bytes(); + | ^^^^^^^^^^^ + | + = note: `-D clippy::host-endian-bytes` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::host_endian_bytes)]` +help: convert to little endian + | +LL - let _ = 0u8.to_ne_bytes(); +LL + let _ = 0u8.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.to_ne_bytes(); +LL + let _ = 0u8.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:13:22 + | +LL | let _ = 0u16.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0u16.to_ne_bytes(); +LL + let _ = 0u16.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u16.to_ne_bytes(); +LL + let _ = 0u16.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:14:22 + | +LL | let _ = 0u32.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0u32.to_ne_bytes(); +LL + let _ = 0u32.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u32.to_ne_bytes(); +LL + let _ = 0u32.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:15:22 + | +LL | let _ = 0u64.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0u64.to_ne_bytes(); +LL + let _ = 0u64.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u64.to_ne_bytes(); +LL + let _ = 0u64.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:16:23 + | +LL | let _ = 0u128.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0u128.to_ne_bytes(); +LL + let _ = 0u128.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u128.to_ne_bytes(); +LL + let _ = 0u128.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:17:24 + | +LL | let _ = 0usize.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0usize.to_ne_bytes(); +LL + let _ = 0usize.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0usize.to_ne_bytes(); +LL + let _ = 0usize.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:19:21 + | +LL | let _ = 0i8.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0i8.to_ne_bytes(); +LL + let _ = 0i8.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i8.to_ne_bytes(); +LL + let _ = 0i8.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:20:22 + | +LL | let _ = 0i16.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0i16.to_ne_bytes(); +LL + let _ = 0i16.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i16.to_ne_bytes(); +LL + let _ = 0i16.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:21:22 + | +LL | let _ = 0i32.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0i32.to_ne_bytes(); +LL + let _ = 0i32.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i32.to_ne_bytes(); +LL + let _ = 0i32.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:22:22 + | +LL | let _ = 0i64.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0i64.to_ne_bytes(); +LL + let _ = 0i64.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i64.to_ne_bytes(); +LL + let _ = 0i64.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:23:23 + | +LL | let _ = 0i128.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0i128.to_ne_bytes(); +LL + let _ = 0i128.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i128.to_ne_bytes(); +LL + let _ = 0i128.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:24:24 + | +LL | let _ = 0isize.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0isize.to_ne_bytes(); +LL + let _ = 0isize.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0isize.to_ne_bytes(); +LL + let _ = 0isize.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:26:22 + | +LL | let _ = 0f16.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0f16.to_ne_bytes(); +LL + let _ = 0f16.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f16.to_ne_bytes(); +LL + let _ = 0f16.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:27:22 + | +LL | let _ = 0f32.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0f32.to_ne_bytes(); +LL + let _ = 0f32.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f32.to_ne_bytes(); +LL + let _ = 0f32.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:28:22 + | +LL | let _ = 0f64.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0f64.to_ne_bytes(); +LL + let _ = 0f64.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f64.to_ne_bytes(); +LL + let _ = 0f64.to_be_bytes(); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:29:23 + | +LL | let _ = 0f128.to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0f128.to_ne_bytes(); +LL + let _ = 0f128.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f128.to_ne_bytes(); +LL + let _ = 0f128.to_be_bytes(); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:31:21 + | +LL | let _ = u8::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u8::from_ne_bytes([0; _]); +LL + let _ = u8::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::from_ne_bytes([0; _]); +LL + let _ = u8::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:32:22 + | +LL | let _ = u16::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u16::from_ne_bytes([0; _]); +LL + let _ = u16::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u16::from_ne_bytes([0; _]); +LL + let _ = u16::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:33:22 + | +LL | let _ = u32::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u32::from_ne_bytes([0; _]); +LL + let _ = u32::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u32::from_ne_bytes([0; _]); +LL + let _ = u32::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:34:22 + | +LL | let _ = u64::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u64::from_ne_bytes([0; _]); +LL + let _ = u64::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u64::from_ne_bytes([0; _]); +LL + let _ = u64::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:35:23 + | +LL | let _ = u128::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u128::from_ne_bytes([0; _]); +LL + let _ = u128::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u128::from_ne_bytes([0; _]); +LL + let _ = u128::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:36:24 + | +LL | let _ = usize::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = usize::from_ne_bytes([0; _]); +LL + let _ = usize::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = usize::from_ne_bytes([0; _]); +LL + let _ = usize::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:38:21 + | +LL | let _ = i8::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = i8::from_ne_bytes([0; _]); +LL + let _ = i8::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i8::from_ne_bytes([0; _]); +LL + let _ = i8::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:39:22 + | +LL | let _ = i16::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = i16::from_ne_bytes([0; _]); +LL + let _ = i16::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i16::from_ne_bytes([0; _]); +LL + let _ = i16::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:40:22 + | +LL | let _ = i32::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = i32::from_ne_bytes([0; _]); +LL + let _ = i32::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i32::from_ne_bytes([0; _]); +LL + let _ = i32::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:41:22 + | +LL | let _ = i64::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = i64::from_ne_bytes([0; _]); +LL + let _ = i64::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i64::from_ne_bytes([0; _]); +LL + let _ = i64::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:42:23 + | +LL | let _ = i128::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = i128::from_ne_bytes([0; _]); +LL + let _ = i128::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i128::from_ne_bytes([0; _]); +LL + let _ = i128::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:43:24 + | +LL | let _ = isize::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = isize::from_ne_bytes([0; _]); +LL + let _ = isize::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = isize::from_ne_bytes([0; _]); +LL + let _ = isize::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:45:22 + | +LL | let _ = f16::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = f16::from_ne_bytes([0; _]); +LL + let _ = f16::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f16::from_ne_bytes([0; _]); +LL + let _ = f16::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:46:22 + | +LL | let _ = f32::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = f32::from_ne_bytes([0; _]); +LL + let _ = f32::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f32::from_ne_bytes([0; _]); +LL + let _ = f32::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:47:22 + | +LL | let _ = f64::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = f64::from_ne_bytes([0; _]); +LL + let _ = f64::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f64::from_ne_bytes([0; _]); +LL + let _ = f64::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:48:23 + | +LL | let _ = f128::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = f128::from_ne_bytes([0; _]); +LL + let _ = f128::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f128::from_ne_bytes([0; _]); +LL + let _ = f128::from_be_bytes([0; _]); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:52:21 + | +LL | let _ = u8::from_ne_bytes; + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u8::from_ne_bytes; +LL + let _ = u8::from_le_bytes; + | +help: convert from big endian + | +LL - let _ = u8::from_ne_bytes; +LL + let _ = u8::from_be_bytes; + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:53:21 + | +LL | let _ = u8::to_ne_bytes; + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = u8::to_ne_bytes; +LL + let _ = u8::to_le_bytes; + | +help: convert to big endian + | +LL - let _ = u8::to_ne_bytes; +LL + let _ = u8::to_be_bytes; + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:58:21 + | +LL | let _ = 0u8.to_ne_bytes(); + | ^^^^^^^^^^^ help: convert to little endian: `to_le_bytes` + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:59:21 + | +LL | let _ = 0i8.to_ne_bytes(); + | ^^^^^^^^^^^ help: convert to little endian: `to_le_bytes` + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:60:21 + | +LL | let _ = u8::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from little endian: `from_le_bytes` + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:61:21 + | +LL | let _ = i8::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from little endian: `from_le_bytes` + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:66:21 + | +LL | let _ = 0u8.to_ne_bytes(); + | ^^^^^^^^^^^ help: convert to big endian: `to_be_bytes` + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:67:21 + | +LL | let _ = 0i8.to_ne_bytes(); + | ^^^^^^^^^^^ help: convert to big endian: `to_be_bytes` + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:68:21 + | +LL | let _ = u8::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from big endian: `from_be_bytes` + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:69:21 + | +LL | let _ = i8::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from big endian: `from_be_bytes` + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:74:25 + | +LL | let _ = 0u8.to_ne_bytes(); + | ^^^^^^^^^^^ + | + = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) +help: convert to little endian + | +LL - let _ = 0u8.to_ne_bytes(); +LL + let _ = 0u8.to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.to_ne_bytes(); +LL + let _ = 0u8.to_be_bytes(); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:75:25 + | +LL | let _ = u8::from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | + = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) +help: convert from little endian + | +LL - let _ = u8::from_ne_bytes([0; _]); +LL + let _ = u8::from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::from_ne_bytes([0; _]); +LL + let _ = u8::from_be_bytes([0; _]); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:76:26 + | +LL | let _ = 0u8.$to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0u8.$to_ne_bytes(); +LL + let _ = 0u8.$to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.$to_ne_bytes(); +LL + let _ = 0u8.$to_be_bytes(); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:77:26 + | +LL | let _ = u8::$from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u8::$from_ne_bytes([0; _]); +LL + let _ = u8::$from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::$from_ne_bytes([0; _]); +LL + let _ = u8::$from_be_bytes([0; _]); + | + +error: use of `to_ne_bytes` + --> tests/ui/host_endian_bytes.rs:83:26 + | +LL | let _ = 0u8.$to_ne_bytes(); + | ^^^^^^^^^^^ + | +help: convert to little endian + | +LL - let _ = 0u8.$to_ne_bytes(); +LL + let _ = 0u8.$to_le_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.$to_ne_bytes(); +LL + let _ = 0u8.$to_be_bytes(); + | + +error: use of `from_ne_bytes` + --> tests/ui/host_endian_bytes.rs:84:26 + | +LL | let _ = u8::$from_ne_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from little endian + | +LL - let _ = u8::$from_ne_bytes([0; _]); +LL + let _ = u8::$from_le_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::$from_ne_bytes([0; _]); +LL + let _ = u8::$from_be_bytes([0; _]); + | + +error: aborting due to 48 previous errors + diff --git a/src/tools/clippy/tests/ui/if_not_else.fixed b/src/tools/clippy/tests/ui/if_not_else.fixed index a29847f0cf978..9c01cb62ac77b 100644 --- a/src/tools/clippy/tests/ui/if_not_else.fixed +++ b/src/tools/clippy/tests/ui/if_not_else.fixed @@ -93,3 +93,71 @@ fn issue15924() { println!(":)"); } } + +mod issue17373 { + macro_rules! ht_is_packed { + ($ht:expr) => { + ($ht).u & 4 != 0 + }; + } + struct HashTable { + u: u32, + } + impl HashTable { + fn check(&mut self) { + if ht_is_packed!(self) { + println!("Packed"); + } else { + println!("Not packed"); + } + } + } + + macro_rules! is_active { + ($x:expr) => { + ($x).state != 3 + }; + } + struct Widget { + state: u32, + } + impl Widget { + fn check(&self) { + if is_active!(self) { + println!("active"); + } else { + println!("inactive"); + } + } + } + + macro_rules! not_ready { + ($x:expr) => { + !($x).ready + }; + } + struct Task { + ready: bool, + } + impl Task { + fn check(&self) { + if not_ready!(self) { + println!("waiting"); + } else { + println!("go"); + } + } + } + + macro_rules! wrap_if { + ($cond:expr, $t:block, $e:block) => { + if $cond $t else $e + }; + } + fn wrap_if_macro() { + let x = 0; + fn a() {} + fn b() {} + wrap_if!(x != 0, { a() }, { b() }); + } +} diff --git a/src/tools/clippy/tests/ui/if_not_else.rs b/src/tools/clippy/tests/ui/if_not_else.rs index 4ae11d6ad90ea..9d7da2dac37a4 100644 --- a/src/tools/clippy/tests/ui/if_not_else.rs +++ b/src/tools/clippy/tests/ui/if_not_else.rs @@ -93,3 +93,71 @@ fn issue15924() { println!(":("); } } + +mod issue17373 { + macro_rules! ht_is_packed { + ($ht:expr) => { + ($ht).u & 4 != 0 + }; + } + struct HashTable { + u: u32, + } + impl HashTable { + fn check(&mut self) { + if ht_is_packed!(self) { + println!("Packed"); + } else { + println!("Not packed"); + } + } + } + + macro_rules! is_active { + ($x:expr) => { + ($x).state != 3 + }; + } + struct Widget { + state: u32, + } + impl Widget { + fn check(&self) { + if is_active!(self) { + println!("active"); + } else { + println!("inactive"); + } + } + } + + macro_rules! not_ready { + ($x:expr) => { + !($x).ready + }; + } + struct Task { + ready: bool, + } + impl Task { + fn check(&self) { + if not_ready!(self) { + println!("waiting"); + } else { + println!("go"); + } + } + } + + macro_rules! wrap_if { + ($cond:expr, $t:block, $e:block) => { + if $cond $t else $e + }; + } + fn wrap_if_macro() { + let x = 0; + fn a() {} + fn b() {} + wrap_if!(x != 0, { a() }, { b() }); + } +} diff --git a/src/tools/clippy/tests/ui/implicit_saturating_sub.fixed b/src/tools/clippy/tests/ui/implicit_saturating_sub.fixed index c7ab65cbb0151..7756541224a39 100644 --- a/src/tools/clippy/tests/ui/implicit_saturating_sub.fixed +++ b/src/tools/clippy/tests/ui/implicit_saturating_sub.fixed @@ -278,3 +278,23 @@ fn wrongly_unmangled_macros() { let b = 20u64; let _ = test_big!(a).saturating_sub(test_little!(b)); } + +#[clippy::msrv = "1.46.0"] +pub const fn const_msrv_too_low(mut x: u32) -> u32 { + if x != 0 { + x -= 1; + } + x +} + +#[clippy::msrv = "1.47.0"] +pub const fn const_msrv_ok(mut x: u32) -> u32 { + x = x.saturating_sub(1); + x +} + +#[clippy::msrv = "1.46.0"] +pub fn nonconst_msrv_low(mut x: u32) -> u32 { + x = x.saturating_sub(1); + x +} diff --git a/src/tools/clippy/tests/ui/implicit_saturating_sub.rs b/src/tools/clippy/tests/ui/implicit_saturating_sub.rs index 1371928e15b5d..72f6e719ae1c2 100644 --- a/src/tools/clippy/tests/ui/implicit_saturating_sub.rs +++ b/src/tools/clippy/tests/ui/implicit_saturating_sub.rs @@ -357,3 +357,29 @@ fn wrongly_unmangled_macros() { 0 }; } + +#[clippy::msrv = "1.46.0"] +pub const fn const_msrv_too_low(mut x: u32) -> u32 { + if x != 0 { + x -= 1; + } + x +} + +#[clippy::msrv = "1.47.0"] +pub const fn const_msrv_ok(mut x: u32) -> u32 { + if x != 0 { + //~^ implicit_saturating_sub + x -= 1; + } + x +} + +#[clippy::msrv = "1.46.0"] +pub fn nonconst_msrv_low(mut x: u32) -> u32 { + if x != 0 { + //~^ implicit_saturating_sub + x -= 1; + } + x +} diff --git a/src/tools/clippy/tests/ui/implicit_saturating_sub.stderr b/src/tools/clippy/tests/ui/implicit_saturating_sub.stderr index c7a4330603a29..bb099e6288a6b 100644 --- a/src/tools/clippy/tests/ui/implicit_saturating_sub.stderr +++ b/src/tools/clippy/tests/ui/implicit_saturating_sub.stderr @@ -256,5 +256,23 @@ LL | | 0 LL | | }; | |_____^ help: replace it with: `test_big!(a).saturating_sub(test_little!(b))` -error: aborting due to 29 previous errors +error: implicitly performing saturating subtraction + --> tests/ui/implicit_saturating_sub.rs:371:5 + | +LL | / if x != 0 { +LL | | +LL | | x -= 1; +LL | | } + | |_____^ help: try: `x = x.saturating_sub(1);` + +error: implicitly performing saturating subtraction + --> tests/ui/implicit_saturating_sub.rs:380:5 + | +LL | / if x != 0 { +LL | | +LL | | x -= 1; +LL | | } + | |_____^ help: try: `x = x.saturating_sub(1);` + +error: aborting due to 31 previous errors diff --git a/src/tools/clippy/tests/ui/legacy_numeric_constants.fixed b/src/tools/clippy/tests/ui/legacy_numeric_constants.fixed index 206e4c5a062a0..98f26d62ab84c 100644 --- a/src/tools/clippy/tests/ui/legacy_numeric_constants.fixed +++ b/src/tools/clippy/tests/ui/legacy_numeric_constants.fixed @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs #![warn(clippy::legacy_numeric_constants)] -#![expect(renamed_and_removed_lints, clippy::no_effect, clippy::useless_attribute, deprecated)] +#![expect(deprecated, renamed_and_removed_lints, clippy::no_effect, clippy::useless_attribute)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/legacy_numeric_constants.rs b/src/tools/clippy/tests/ui/legacy_numeric_constants.rs index 891291c99a3df..98f860130947f 100644 --- a/src/tools/clippy/tests/ui/legacy_numeric_constants.rs +++ b/src/tools/clippy/tests/ui/legacy_numeric_constants.rs @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs #![warn(clippy::legacy_numeric_constants)] -#![expect(renamed_and_removed_lints, clippy::no_effect, clippy::useless_attribute, deprecated)] +#![expect(deprecated, renamed_and_removed_lints, clippy::no_effect, clippy::useless_attribute)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/let_underscore_must_use.rs b/src/tools/clippy/tests/ui/let_underscore_must_use.rs index 37dac4f9a2b05..78f0104496cf4 100644 --- a/src/tools/clippy/tests/ui/let_underscore_must_use.rs +++ b/src/tools/clippy/tests/ui/let_underscore_must_use.rs @@ -96,6 +96,9 @@ fn main() { let _ = if true { Ok(()) } else { Err(()) }; //~^ let_underscore_must_use + let _: Result<(), ()> = if true { Ok(()) } else { Err(()) }; + //~^ let_underscore_must_use + let a = Result::<(), ()>::Ok(()); let _ = a.is_ok(); diff --git a/src/tools/clippy/tests/ui/let_underscore_must_use.stderr b/src/tools/clippy/tests/ui/let_underscore_must_use.stderr index 23e929b5bf895..5a0790d6e1c69 100644 --- a/src/tools/clippy/tests/ui/let_underscore_must_use.stderr +++ b/src/tools/clippy/tests/ui/let_underscore_must_use.stderr @@ -15,6 +15,11 @@ LL | let _ = g(); | ^^^^^^^^^^^^ | = help: consider explicitly using expression value +note: type is `std::result::Result` + --> tests/ui/let_underscore_must_use.rs:70:13 + | +LL | let _ = g(); + | ^^^ error: non-binding `let` on a result of a `#[must_use]` function --> tests/ui/let_underscore_must_use.rs:74:5 @@ -39,6 +44,11 @@ LL | let _ = s.g(); | ^^^^^^^^^^^^^^ | = help: consider explicitly using expression value +note: type is `std::result::Result` + --> tests/ui/let_underscore_must_use.rs:82:13 + | +LL | let _ = s.g(); + | ^^^^^ error: non-binding `let` on a result of a `#[must_use]` function --> tests/ui/let_underscore_must_use.rs:87:5 @@ -55,6 +65,11 @@ LL | let _ = S::p(); | ^^^^^^^^^^^^^^^ | = help: consider explicitly using expression value +note: type is `std::result::Result` + --> tests/ui/let_underscore_must_use.rs:90:13 + | +LL | let _ = S::p(); + | ^^^^^^ error: non-binding `let` on a result of a `#[must_use]` function --> tests/ui/let_underscore_must_use.rs:93:5 @@ -71,9 +86,27 @@ LL | let _ = if true { Ok(()) } else { Err(()) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider explicitly using expression value +note: type is `std::result::Result` + --> tests/ui/let_underscore_must_use.rs:96:13 + | +LL | let _ = if true { Ok(()) } else { Err(()) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: non-binding `let` on an expression with `#[must_use]` type + --> tests/ui/let_underscore_must_use.rs:99:5 + | +LL | let _: Result<(), ()> = if true { Ok(()) } else { Err(()) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider explicitly using expression value +note: type is `std::result::Result` + --> tests/ui/let_underscore_must_use.rs:99:12 + | +LL | let _: Result<(), ()> = if true { Ok(()) } else { Err(()) }; + | ^^^^^^^^^^^^^^ error: non-binding `let` on a result of a `#[must_use]` function - --> tests/ui/let_underscore_must_use.rs:101:5 + --> tests/ui/let_underscore_must_use.rs:104:5 | LL | let _ = a.is_ok(); | ^^^^^^^^^^^^^^^^^^ @@ -81,28 +114,43 @@ LL | let _ = a.is_ok(); = help: consider explicitly using function result error: non-binding `let` on an expression with `#[must_use]` type - --> tests/ui/let_underscore_must_use.rs:104:5 + --> tests/ui/let_underscore_must_use.rs:107:5 | LL | let _ = a.map(|_| ()); | ^^^^^^^^^^^^^^^^^^^^^^ | = help: consider explicitly using expression value +note: type is `std::result::Result` + --> tests/ui/let_underscore_must_use.rs:107:13 + | +LL | let _ = a.map(|_| ()); + | ^^^^^^^^^^^^^ error: non-binding `let` on an expression with `#[must_use]` type - --> tests/ui/let_underscore_must_use.rs:107:5 + --> tests/ui/let_underscore_must_use.rs:110:5 | LL | let _ = a; | ^^^^^^^^^^ | = help: consider explicitly using expression value +note: type is `std::result::Result` + --> tests/ui/let_underscore_must_use.rs:110:13 + | +LL | let _ = a; + | ^ error: non-binding `let` on an expression with `#[must_use]` type - --> tests/ui/let_underscore_must_use.rs:120:5 + --> tests/ui/let_underscore_must_use.rs:123:5 | LL | let _ = Result::<_, std::convert::Infallible>::Ok(T); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider explicitly using expression value +note: type is `main::T` in a `Result` with an uninhabited error + --> tests/ui/let_underscore_must_use.rs:123:13 + | +LL | let _ = Result::<_, std::convert::Infallible>::Ok(T); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 13 previous errors +error: aborting due to 14 previous errors diff --git a/src/tools/clippy/tests/ui/little_endian_bytes.1.fixed b/src/tools/clippy/tests/ui/little_endian_bytes.1.fixed new file mode 100644 index 0000000000000..674d4169cea6a --- /dev/null +++ b/src/tools/clippy/tests/ui/little_endian_bytes.1.fixed @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::little_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_ne_bytes(); //~ little_endian_bytes + let _ = 0u16.to_ne_bytes(); //~ little_endian_bytes + let _ = 0u32.to_ne_bytes(); //~ little_endian_bytes + let _ = 0u64.to_ne_bytes(); //~ little_endian_bytes + let _ = 0u128.to_ne_bytes(); //~ little_endian_bytes + let _ = 0usize.to_ne_bytes(); //~ little_endian_bytes + + let _ = 0i8.to_ne_bytes(); //~ little_endian_bytes + let _ = 0i16.to_ne_bytes(); //~ little_endian_bytes + let _ = 0i32.to_ne_bytes(); //~ little_endian_bytes + let _ = 0i64.to_ne_bytes(); //~ little_endian_bytes + let _ = 0i128.to_ne_bytes(); //~ little_endian_bytes + let _ = 0isize.to_ne_bytes(); //~ little_endian_bytes + + let _ = 0f16.to_ne_bytes(); //~ little_endian_bytes + let _ = 0f32.to_ne_bytes(); //~ little_endian_bytes + let _ = 0f64.to_ne_bytes(); //~ little_endian_bytes + let _ = 0f128.to_ne_bytes(); //~ little_endian_bytes + + let _ = u8::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = u16::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = u32::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = u64::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = u128::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = usize::from_ne_bytes([0; _]); //~ little_endian_bytes + + let _ = i8::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = i16::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = i32::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = i64::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = i128::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = isize::from_ne_bytes([0; _]); //~ little_endian_bytes + + let _ = f16::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = f32::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = f64::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = f128::from_ne_bytes([0; _]); //~ little_endian_bytes + }; + + { + let _ = u8::from_ne_bytes; //~ little_endian_bytes + let _ = u8::to_ne_bytes; //~ little_endian_bytes + } + + #[warn(clippy::big_endian_bytes)] + { + let _ = 0u8.to_ne_bytes(); //~ little_endian_bytes + let _ = 0i8.to_ne_bytes(); //~ little_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = i8::from_ne_bytes([0; _]); //~ little_endian_bytes + }; + + #[warn(clippy::host_endian_bytes)] + { + let _ = 0u8.to_be_bytes(); //~ little_endian_bytes + let _ = 0i8.to_be_bytes(); //~ little_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = i8::from_be_bytes([0; _]); //~ little_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_ne_bytes(); //~ little_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = 0u8.$to_ne_bytes(); //~ little_endian_bytes + let _ = u8::$from_ne_bytes([0; _]); //~ little_endian_bytes + }} + + external! { + let _ = 0u8.to_le_bytes(); + let _ = u8::from_le_bytes([0; _]); + let _ = 0u8.$to_ne_bytes(); //~ little_endian_bytes + let _ = u8::$from_ne_bytes([0; _]); //~ little_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/little_endian_bytes.2.fixed b/src/tools/clippy/tests/ui/little_endian_bytes.2.fixed new file mode 100644 index 0000000000000..d286e417c72e8 --- /dev/null +++ b/src/tools/clippy/tests/ui/little_endian_bytes.2.fixed @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::little_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_be_bytes(); //~ little_endian_bytes + let _ = 0u16.to_be_bytes(); //~ little_endian_bytes + let _ = 0u32.to_be_bytes(); //~ little_endian_bytes + let _ = 0u64.to_be_bytes(); //~ little_endian_bytes + let _ = 0u128.to_be_bytes(); //~ little_endian_bytes + let _ = 0usize.to_be_bytes(); //~ little_endian_bytes + + let _ = 0i8.to_be_bytes(); //~ little_endian_bytes + let _ = 0i16.to_be_bytes(); //~ little_endian_bytes + let _ = 0i32.to_be_bytes(); //~ little_endian_bytes + let _ = 0i64.to_be_bytes(); //~ little_endian_bytes + let _ = 0i128.to_be_bytes(); //~ little_endian_bytes + let _ = 0isize.to_be_bytes(); //~ little_endian_bytes + + let _ = 0f16.to_be_bytes(); //~ little_endian_bytes + let _ = 0f32.to_be_bytes(); //~ little_endian_bytes + let _ = 0f64.to_be_bytes(); //~ little_endian_bytes + let _ = 0f128.to_be_bytes(); //~ little_endian_bytes + + let _ = u8::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = u16::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = u32::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = u64::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = u128::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = usize::from_be_bytes([0; _]); //~ little_endian_bytes + + let _ = i8::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = i16::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = i32::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = i64::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = i128::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = isize::from_be_bytes([0; _]); //~ little_endian_bytes + + let _ = f16::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = f32::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = f64::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = f128::from_be_bytes([0; _]); //~ little_endian_bytes + }; + + { + let _ = u8::from_be_bytes; //~ little_endian_bytes + let _ = u8::to_be_bytes; //~ little_endian_bytes + } + + #[warn(clippy::big_endian_bytes)] + { + let _ = 0u8.to_ne_bytes(); //~ little_endian_bytes + let _ = 0i8.to_ne_bytes(); //~ little_endian_bytes + let _ = u8::from_ne_bytes([0; _]); //~ little_endian_bytes + let _ = i8::from_ne_bytes([0; _]); //~ little_endian_bytes + }; + + #[warn(clippy::host_endian_bytes)] + { + let _ = 0u8.to_be_bytes(); //~ little_endian_bytes + let _ = 0i8.to_be_bytes(); //~ little_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = i8::from_be_bytes([0; _]); //~ little_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_be_bytes(); //~ little_endian_bytes + let _ = u8::from_be_bytes([0; _]); //~ little_endian_bytes + let _ = 0u8.$to_be_bytes(); //~ little_endian_bytes + let _ = u8::$from_be_bytes([0; _]); //~ little_endian_bytes + }} + + external! { + let _ = 0u8.to_le_bytes(); + let _ = u8::from_le_bytes([0; _]); + let _ = 0u8.$to_be_bytes(); //~ little_endian_bytes + let _ = u8::$from_be_bytes([0; _]); //~ little_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/little_endian_bytes.rs b/src/tools/clippy/tests/ui/little_endian_bytes.rs new file mode 100644 index 0000000000000..e280f8952d73c --- /dev/null +++ b/src/tools/clippy/tests/ui/little_endian_bytes.rs @@ -0,0 +1,87 @@ +//@ aux-build:proc_macros.rs + +#![warn(clippy::little_endian_bytes)] +#![feature(f16, f128)] + +extern crate proc_macros; +use proc_macros::{external, inline_macros}; + +#[inline_macros] +fn main() { + { + let _ = 0u8.to_le_bytes(); //~ little_endian_bytes + let _ = 0u16.to_le_bytes(); //~ little_endian_bytes + let _ = 0u32.to_le_bytes(); //~ little_endian_bytes + let _ = 0u64.to_le_bytes(); //~ little_endian_bytes + let _ = 0u128.to_le_bytes(); //~ little_endian_bytes + let _ = 0usize.to_le_bytes(); //~ little_endian_bytes + + let _ = 0i8.to_le_bytes(); //~ little_endian_bytes + let _ = 0i16.to_le_bytes(); //~ little_endian_bytes + let _ = 0i32.to_le_bytes(); //~ little_endian_bytes + let _ = 0i64.to_le_bytes(); //~ little_endian_bytes + let _ = 0i128.to_le_bytes(); //~ little_endian_bytes + let _ = 0isize.to_le_bytes(); //~ little_endian_bytes + + let _ = 0f16.to_le_bytes(); //~ little_endian_bytes + let _ = 0f32.to_le_bytes(); //~ little_endian_bytes + let _ = 0f64.to_le_bytes(); //~ little_endian_bytes + let _ = 0f128.to_le_bytes(); //~ little_endian_bytes + + let _ = u8::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = u16::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = u32::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = u64::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = u128::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = usize::from_le_bytes([0; _]); //~ little_endian_bytes + + let _ = i8::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = i16::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = i32::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = i64::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = i128::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = isize::from_le_bytes([0; _]); //~ little_endian_bytes + + let _ = f16::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = f32::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = f64::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = f128::from_le_bytes([0; _]); //~ little_endian_bytes + }; + + { + let _ = u8::from_le_bytes; //~ little_endian_bytes + let _ = u8::to_le_bytes; //~ little_endian_bytes + } + + #[warn(clippy::big_endian_bytes)] + { + let _ = 0u8.to_le_bytes(); //~ little_endian_bytes + let _ = 0i8.to_le_bytes(); //~ little_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = i8::from_le_bytes([0; _]); //~ little_endian_bytes + }; + + #[warn(clippy::host_endian_bytes)] + { + let _ = 0u8.to_le_bytes(); //~ little_endian_bytes + let _ = 0i8.to_le_bytes(); //~ little_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = i8::from_le_bytes([0; _]); //~ little_endian_bytes + }; + + { + inline! {{ + let _ = 0u8.to_le_bytes(); //~ little_endian_bytes + let _ = u8::from_le_bytes([0; _]); //~ little_endian_bytes + let _ = 0u8.$to_le_bytes(); //~ little_endian_bytes + let _ = u8::$from_le_bytes([0; _]); //~ little_endian_bytes + }} + + external! { + let _ = 0u8.to_le_bytes(); + let _ = u8::from_le_bytes([0; _]); + let _ = 0u8.$to_le_bytes(); //~ little_endian_bytes + let _ = u8::$from_le_bytes([0; _]); //~ little_endian_bytes + } + } +} diff --git a/src/tools/clippy/tests/ui/little_endian_bytes.stderr b/src/tools/clippy/tests/ui/little_endian_bytes.stderr new file mode 100644 index 0000000000000..986b54ca1c422 --- /dev/null +++ b/src/tools/clippy/tests/ui/little_endian_bytes.stderr @@ -0,0 +1,734 @@ +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:12:21 + | +LL | let _ = 0u8.to_le_bytes(); + | ^^^^^^^^^^^ + | + = note: `-D clippy::little-endian-bytes` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::little_endian_bytes)]` +help: convert to native endian + | +LL - let _ = 0u8.to_le_bytes(); +LL + let _ = 0u8.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.to_le_bytes(); +LL + let _ = 0u8.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:13:22 + | +LL | let _ = 0u16.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u16.to_le_bytes(); +LL + let _ = 0u16.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u16.to_le_bytes(); +LL + let _ = 0u16.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:14:22 + | +LL | let _ = 0u32.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u32.to_le_bytes(); +LL + let _ = 0u32.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u32.to_le_bytes(); +LL + let _ = 0u32.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:15:22 + | +LL | let _ = 0u64.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u64.to_le_bytes(); +LL + let _ = 0u64.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u64.to_le_bytes(); +LL + let _ = 0u64.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:16:23 + | +LL | let _ = 0u128.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u128.to_le_bytes(); +LL + let _ = 0u128.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u128.to_le_bytes(); +LL + let _ = 0u128.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:17:24 + | +LL | let _ = 0usize.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0usize.to_le_bytes(); +LL + let _ = 0usize.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0usize.to_le_bytes(); +LL + let _ = 0usize.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:19:21 + | +LL | let _ = 0i8.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i8.to_le_bytes(); +LL + let _ = 0i8.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i8.to_le_bytes(); +LL + let _ = 0i8.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:20:22 + | +LL | let _ = 0i16.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i16.to_le_bytes(); +LL + let _ = 0i16.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i16.to_le_bytes(); +LL + let _ = 0i16.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:21:22 + | +LL | let _ = 0i32.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i32.to_le_bytes(); +LL + let _ = 0i32.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i32.to_le_bytes(); +LL + let _ = 0i32.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:22:22 + | +LL | let _ = 0i64.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i64.to_le_bytes(); +LL + let _ = 0i64.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i64.to_le_bytes(); +LL + let _ = 0i64.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:23:23 + | +LL | let _ = 0i128.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0i128.to_le_bytes(); +LL + let _ = 0i128.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0i128.to_le_bytes(); +LL + let _ = 0i128.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:24:24 + | +LL | let _ = 0isize.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0isize.to_le_bytes(); +LL + let _ = 0isize.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0isize.to_le_bytes(); +LL + let _ = 0isize.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:26:22 + | +LL | let _ = 0f16.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f16.to_le_bytes(); +LL + let _ = 0f16.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f16.to_le_bytes(); +LL + let _ = 0f16.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:27:22 + | +LL | let _ = 0f32.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f32.to_le_bytes(); +LL + let _ = 0f32.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f32.to_le_bytes(); +LL + let _ = 0f32.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:28:22 + | +LL | let _ = 0f64.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f64.to_le_bytes(); +LL + let _ = 0f64.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f64.to_le_bytes(); +LL + let _ = 0f64.to_be_bytes(); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:29:23 + | +LL | let _ = 0f128.to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0f128.to_le_bytes(); +LL + let _ = 0f128.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0f128.to_le_bytes(); +LL + let _ = 0f128.to_be_bytes(); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:31:21 + | +LL | let _ = u8::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::from_le_bytes([0; _]); +LL + let _ = u8::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::from_le_bytes([0; _]); +LL + let _ = u8::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:32:22 + | +LL | let _ = u16::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u16::from_le_bytes([0; _]); +LL + let _ = u16::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u16::from_le_bytes([0; _]); +LL + let _ = u16::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:33:22 + | +LL | let _ = u32::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u32::from_le_bytes([0; _]); +LL + let _ = u32::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u32::from_le_bytes([0; _]); +LL + let _ = u32::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:34:22 + | +LL | let _ = u64::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u64::from_le_bytes([0; _]); +LL + let _ = u64::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u64::from_le_bytes([0; _]); +LL + let _ = u64::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:35:23 + | +LL | let _ = u128::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u128::from_le_bytes([0; _]); +LL + let _ = u128::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u128::from_le_bytes([0; _]); +LL + let _ = u128::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:36:24 + | +LL | let _ = usize::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = usize::from_le_bytes([0; _]); +LL + let _ = usize::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = usize::from_le_bytes([0; _]); +LL + let _ = usize::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:38:21 + | +LL | let _ = i8::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i8::from_le_bytes([0; _]); +LL + let _ = i8::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i8::from_le_bytes([0; _]); +LL + let _ = i8::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:39:22 + | +LL | let _ = i16::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i16::from_le_bytes([0; _]); +LL + let _ = i16::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i16::from_le_bytes([0; _]); +LL + let _ = i16::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:40:22 + | +LL | let _ = i32::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i32::from_le_bytes([0; _]); +LL + let _ = i32::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i32::from_le_bytes([0; _]); +LL + let _ = i32::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:41:22 + | +LL | let _ = i64::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i64::from_le_bytes([0; _]); +LL + let _ = i64::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i64::from_le_bytes([0; _]); +LL + let _ = i64::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:42:23 + | +LL | let _ = i128::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = i128::from_le_bytes([0; _]); +LL + let _ = i128::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = i128::from_le_bytes([0; _]); +LL + let _ = i128::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:43:24 + | +LL | let _ = isize::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = isize::from_le_bytes([0; _]); +LL + let _ = isize::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = isize::from_le_bytes([0; _]); +LL + let _ = isize::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:45:22 + | +LL | let _ = f16::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f16::from_le_bytes([0; _]); +LL + let _ = f16::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f16::from_le_bytes([0; _]); +LL + let _ = f16::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:46:22 + | +LL | let _ = f32::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f32::from_le_bytes([0; _]); +LL + let _ = f32::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f32::from_le_bytes([0; _]); +LL + let _ = f32::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:47:22 + | +LL | let _ = f64::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f64::from_le_bytes([0; _]); +LL + let _ = f64::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f64::from_le_bytes([0; _]); +LL + let _ = f64::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:48:23 + | +LL | let _ = f128::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = f128::from_le_bytes([0; _]); +LL + let _ = f128::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = f128::from_le_bytes([0; _]); +LL + let _ = f128::from_be_bytes([0; _]); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:52:21 + | +LL | let _ = u8::from_le_bytes; + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::from_le_bytes; +LL + let _ = u8::from_ne_bytes; + | +help: convert from big endian + | +LL - let _ = u8::from_le_bytes; +LL + let _ = u8::from_be_bytes; + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:53:21 + | +LL | let _ = u8::to_le_bytes; + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = u8::to_le_bytes; +LL + let _ = u8::to_ne_bytes; + | +help: convert to big endian + | +LL - let _ = u8::to_le_bytes; +LL + let _ = u8::to_be_bytes; + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:58:21 + | +LL | let _ = 0u8.to_le_bytes(); + | ^^^^^^^^^^^ help: convert to native endian: `to_ne_bytes` + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:59:21 + | +LL | let _ = 0i8.to_le_bytes(); + | ^^^^^^^^^^^ help: convert to native endian: `to_ne_bytes` + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:60:21 + | +LL | let _ = u8::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from native endian: `from_ne_bytes` + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:61:21 + | +LL | let _ = i8::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from native endian: `from_ne_bytes` + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:66:21 + | +LL | let _ = 0u8.to_le_bytes(); + | ^^^^^^^^^^^ help: convert to big endian: `to_be_bytes` + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:67:21 + | +LL | let _ = 0i8.to_le_bytes(); + | ^^^^^^^^^^^ help: convert to big endian: `to_be_bytes` + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:68:21 + | +LL | let _ = u8::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from big endian: `from_be_bytes` + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:69:21 + | +LL | let _ = i8::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ help: convert from big endian: `from_be_bytes` + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:74:25 + | +LL | let _ = 0u8.to_le_bytes(); + | ^^^^^^^^^^^ + | + = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) +help: convert to native endian + | +LL - let _ = 0u8.to_le_bytes(); +LL + let _ = 0u8.to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.to_le_bytes(); +LL + let _ = 0u8.to_be_bytes(); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:75:25 + | +LL | let _ = u8::from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | + = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) +help: convert from native endian + | +LL - let _ = u8::from_le_bytes([0; _]); +LL + let _ = u8::from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::from_le_bytes([0; _]); +LL + let _ = u8::from_be_bytes([0; _]); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:76:26 + | +LL | let _ = 0u8.$to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u8.$to_le_bytes(); +LL + let _ = 0u8.$to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.$to_le_bytes(); +LL + let _ = 0u8.$to_be_bytes(); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:77:26 + | +LL | let _ = u8::$from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::$from_le_bytes([0; _]); +LL + let _ = u8::$from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::$from_le_bytes([0; _]); +LL + let _ = u8::$from_be_bytes([0; _]); + | + +error: use of `to_le_bytes` + --> tests/ui/little_endian_bytes.rs:83:26 + | +LL | let _ = 0u8.$to_le_bytes(); + | ^^^^^^^^^^^ + | +help: convert to native endian + | +LL - let _ = 0u8.$to_le_bytes(); +LL + let _ = 0u8.$to_ne_bytes(); + | +help: convert to big endian + | +LL - let _ = 0u8.$to_le_bytes(); +LL + let _ = 0u8.$to_be_bytes(); + | + +error: use of `from_le_bytes` + --> tests/ui/little_endian_bytes.rs:84:26 + | +LL | let _ = u8::$from_le_bytes([0; _]); + | ^^^^^^^^^^^^^ + | +help: convert from native endian + | +LL - let _ = u8::$from_le_bytes([0; _]); +LL + let _ = u8::$from_ne_bytes([0; _]); + | +help: convert from big endian + | +LL - let _ = u8::$from_le_bytes([0; _]); +LL + let _ = u8::$from_be_bytes([0; _]); + | + +error: aborting due to 48 previous errors + diff --git a/src/tools/clippy/tests/ui/manual_clamp.fixed b/src/tools/clippy/tests/ui/manual_clamp.fixed index 4cd6fe60f381b..5b3670d46bfba 100644 --- a/src/tools/clippy/tests/ui/manual_clamp.fixed +++ b/src/tools/clippy/tests/ui/manual_clamp.fixed @@ -410,6 +410,44 @@ fn msrv_1_50() { let _ = input.clamp(CONST_MIN, CONST_MAX); } +const CONST_U32_MAX: u32 = 100; + +fn eq_unsigned_zero_lint() { + // == 0 on unsigned with result 1: equivalent to < 1 + let mut x0: u32 = 5; + x0 = x0.clamp(1, CONST_U32_MAX); + + // Flipped: `0 == x` + let mut x1: u32 = 5; + x1 = x1.clamp(1, CONST_U32_MAX); + + // Two separate if statements + let mut x2: u32 = 5; + x2 = x2.clamp(1, CONST_U32_MAX); + + // if-elseif-else (value) pattern + let input: u32 = 5; + let x3 = input.clamp(1, CONST_U32_MAX); +} + +fn eq_unsigned_zero_no_lint() { + // Result is not 1, so == 0 doesn't cover all values < 5. + let mut x0: u32 = 5; + if x0 == 0 { + x0 = 5; + } else if x0 > CONST_U32_MAX { + x0 = CONST_U32_MAX; + } + + // Signed type: not applicable + let mut x1: i32 = 5; + if x1 == 0 { + x1 = 1; + } else if x1 > CONST_MAX { + x1 = CONST_MAX; + } +} + const fn _const() { let (input, min, max) = (0, -1, 2); let _ = if input < min { diff --git a/src/tools/clippy/tests/ui/manual_clamp.rs b/src/tools/clippy/tests/ui/manual_clamp.rs index f0613501a8e85..04de0677893fd 100644 --- a/src/tools/clippy/tests/ui/manual_clamp.rs +++ b/src/tools/clippy/tests/ui/manual_clamp.rs @@ -527,6 +527,67 @@ fn msrv_1_50() { }; } +const CONST_U32_MAX: u32 = 100; + +fn eq_unsigned_zero_lint() { + // == 0 on unsigned with result 1: equivalent to < 1 + let mut x0: u32 = 5; + if x0 == 0 { + //~^ manual_clamp + x0 = 1; + } else if x0 > CONST_U32_MAX { + x0 = CONST_U32_MAX; + } + + // Flipped: `0 == x` + let mut x1: u32 = 5; + if 0 == x1 { + //~^ manual_clamp + x1 = 1; + } else if x1 > CONST_U32_MAX { + x1 = CONST_U32_MAX; + } + + // Two separate if statements + let mut x2: u32 = 5; + if x2 == 0 { + //~^ manual_clamp + x2 = 1; + } + if x2 > CONST_U32_MAX { + x2 = CONST_U32_MAX; + } + + // if-elseif-else (value) pattern + let input: u32 = 5; + let x3 = if input == 0 { + //~^ manual_clamp + 1 + } else if input > CONST_U32_MAX { + CONST_U32_MAX + } else { + input + }; +} + +fn eq_unsigned_zero_no_lint() { + // Result is not 1, so == 0 doesn't cover all values < 5. + let mut x0: u32 = 5; + if x0 == 0 { + x0 = 5; + } else if x0 > CONST_U32_MAX { + x0 = CONST_U32_MAX; + } + + // Signed type: not applicable + let mut x1: i32 = 5; + if x1 == 0 { + x1 = 1; + } else if x1 > CONST_MAX { + x1 = CONST_MAX; + } +} + const fn _const() { let (input, min, max) = (0, -1, 2); let _ = if input < min { diff --git a/src/tools/clippy/tests/ui/manual_clamp.stderr b/src/tools/clippy/tests/ui/manual_clamp.stderr index 4876e2eb1cd1f..11568be6b22da 100644 --- a/src/tools/clippy/tests/ui/manual_clamp.stderr +++ b/src/tools/clippy/tests/ui/manual_clamp.stderr @@ -398,5 +398,59 @@ LL | | }; | = note: clamp will panic if max < min -error: aborting due to 35 previous errors +error: clamp-like pattern without using clamp function + --> tests/ui/manual_clamp.rs:553:5 + | +LL | / if x2 == 0 { +LL | | +LL | | x2 = 1; +... | +LL | | x2 = CONST_U32_MAX; +LL | | } + | |_____^ help: replace with clamp: `x2 = x2.clamp(1, CONST_U32_MAX);` + | + = note: clamp will panic if max < min + +error: clamp-like pattern without using clamp function + --> tests/ui/manual_clamp.rs:535:5 + | +LL | / if x0 == 0 { +LL | | +LL | | x0 = 1; +LL | | } else if x0 > CONST_U32_MAX { +LL | | x0 = CONST_U32_MAX; +LL | | } + | |_____^ help: replace with clamp: `x0 = x0.clamp(1, CONST_U32_MAX);` + | + = note: clamp will panic if max < min + +error: clamp-like pattern without using clamp function + --> tests/ui/manual_clamp.rs:544:5 + | +LL | / if 0 == x1 { +LL | | +LL | | x1 = 1; +LL | | } else if x1 > CONST_U32_MAX { +LL | | x1 = CONST_U32_MAX; +LL | | } + | |_____^ help: replace with clamp: `x1 = x1.clamp(1, CONST_U32_MAX);` + | + = note: clamp will panic if max < min + +error: clamp-like pattern without using clamp function + --> tests/ui/manual_clamp.rs:563:14 + | +LL | let x3 = if input == 0 { + | ______________^ +LL | | +LL | | 1 +LL | | } else if input > CONST_U32_MAX { +... | +LL | | input +LL | | }; + | |_____^ help: replace with clamp: `input.clamp(1, CONST_U32_MAX)` + | + = note: clamp will panic if max < min + +error: aborting due to 39 previous errors diff --git a/src/tools/clippy/tests/ui/manual_div_ceil.fixed b/src/tools/clippy/tests/ui/manual_div_ceil.fixed index db46f67208914..24b1cd98b9696 100644 --- a/src/tools/clippy/tests/ui/manual_div_ceil.fixed +++ b/src/tools/clippy/tests/ui/manual_div_ceil.fixed @@ -143,3 +143,15 @@ fn issue_16219() { let z = MyStruct(x); let _ = z.next_multiple_of(8) / 8; } + +fn side_effects() { + use core::hint::black_box; + + // No lint: each expression calls `black_box` twice, while the suggested + // `div_ceil` expression would only call it once. + let _ = (33 + (black_box(4) - 1)) / black_box(4); + let _ = ((black_box(4) - 1) + 33) / black_box(4); + let _ = (33 + black_box(4) - 1) / black_box(4); + let _ = 33_u32.next_multiple_of(black_box(4)) / black_box(4); + let _ = u32::next_multiple_of(33, black_box(4)) / black_box(4); +} diff --git a/src/tools/clippy/tests/ui/manual_div_ceil.rs b/src/tools/clippy/tests/ui/manual_div_ceil.rs index d60ecaa2af7a3..4a86a44247e67 100644 --- a/src/tools/clippy/tests/ui/manual_div_ceil.rs +++ b/src/tools/clippy/tests/ui/manual_div_ceil.rs @@ -143,3 +143,15 @@ fn issue_16219() { let z = MyStruct(x); let _ = z.next_multiple_of(8) / 8; } + +fn side_effects() { + use core::hint::black_box; + + // No lint: each expression calls `black_box` twice, while the suggested + // `div_ceil` expression would only call it once. + let _ = (33 + (black_box(4) - 1)) / black_box(4); + let _ = ((black_box(4) - 1) + 33) / black_box(4); + let _ = (33 + black_box(4) - 1) / black_box(4); + let _ = 33_u32.next_multiple_of(black_box(4)) / black_box(4); + let _ = u32::next_multiple_of(33, black_box(4)) / black_box(4); +} diff --git a/src/tools/clippy/tests/ui/manual_filter_unfixable.rs b/src/tools/clippy/tests/ui/manual_filter_unfixable.rs new file mode 100644 index 0000000000000..0212e2fbd4504 --- /dev/null +++ b/src/tools/clippy/tests/ui/manual_filter_unfixable.rs @@ -0,0 +1,15 @@ +//@no-rustfix: the suggestion drops the closure's comment, so it is not machine-applicable + +#![warn(clippy::manual_filter)] + +fn issue17376(opt: Option) { + // Rewriting to `filter` would drop the comment below, so the suggestion must not be + // machine-applicable here. Otherwise `clippy --fix` would silently eat the comment (#17376). + opt.and_then(|x| { + //~^ manual_filter + // keep this explanation + if x < 10 { Some(x) } else { None } + }); +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui/manual_filter_unfixable.stderr b/src/tools/clippy/tests/ui/manual_filter_unfixable.stderr new file mode 100644 index 0000000000000..00b267e97ac48 --- /dev/null +++ b/src/tools/clippy/tests/ui/manual_filter_unfixable.stderr @@ -0,0 +1,16 @@ +error: manual implementation of `Option::filter` + --> tests/ui/manual_filter_unfixable.rs:8:9 + | +LL | opt.and_then(|x| { + | _________^ +LL | | +LL | | // keep this explanation +LL | | if x < 10 { Some(x) } else { None } +LL | | }); + | |______^ help: try: `filter(|&x| x < 10)` + | + = note: `-D clippy::manual-filter` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::manual_filter)]` + +error: aborting due to 1 previous error + diff --git a/src/tools/clippy/tests/ui/manual_saturating_arithmetic.fixed b/src/tools/clippy/tests/ui/manual_saturating_arithmetic.fixed index 66b3f161b2444..2d2b696004ff9 100644 --- a/src/tools/clippy/tests/ui/manual_saturating_arithmetic.fixed +++ b/src/tools/clippy/tests/ui/manual_saturating_arithmetic.fixed @@ -1,5 +1,5 @@ #![warn(clippy::manual_saturating_arithmetic)] -#![allow(clippy::legacy_numeric_constants, deprecated)] +#![allow(deprecated, clippy::legacy_numeric_constants)] fn main() { let _ = 1u32.saturating_add(1); diff --git a/src/tools/clippy/tests/ui/manual_saturating_arithmetic.rs b/src/tools/clippy/tests/ui/manual_saturating_arithmetic.rs index 1a64ee90c0674..c4fbc6a769d3c 100644 --- a/src/tools/clippy/tests/ui/manual_saturating_arithmetic.rs +++ b/src/tools/clippy/tests/ui/manual_saturating_arithmetic.rs @@ -1,5 +1,5 @@ #![warn(clippy::manual_saturating_arithmetic)] -#![allow(clippy::legacy_numeric_constants, deprecated)] +#![allow(deprecated, clippy::legacy_numeric_constants)] fn main() { let _ = 1u32.checked_add(1).unwrap_or(u32::max_value()); diff --git a/src/tools/clippy/tests/ui/min_ident_chars.rs b/src/tools/clippy/tests/ui/min_ident_chars.rs index 298798be7a1e6..c9348b545cb39 100644 --- a/src/tools/clippy/tests/ui/min_ident_chars.rs +++ b/src/tools/clippy/tests/ui/min_ident_chars.rs @@ -1,7 +1,7 @@ //@aux-build:proc_macros.rs #![warn(clippy::min_ident_chars)] #![expect(irrefutable_let_patterns, nonstandard_style)] -#![allow(clippy::struct_field_names)] +#![allow(non_local_definitions, clippy::struct_field_names)] extern crate proc_macros; use proc_macros::{external, with_span}; @@ -173,3 +173,38 @@ impl D for Issue13396 { } fn long(long: i32) {} } + +const _: () = { + trait A { + //~^ min_ident_chars + fn f(h: [u32; 0]); + //~^ min_ident_chars + //~| min_ident_chars + } + impl A for () { + fn f( + h: [u32; { + impl A for u32 { + fn f( + h: [u32; { + impl A for i32 { + fn f(h: [u32; 0]) { + let h = 0; //~ min_ident_chars + } + } + let h = 0; //~ min_ident_chars + 0 + }], + ) { + let h = 0; //~ min_ident_chars + } + } + let h = 0; //~ min_ident_chars + 0 + }], + ) { + let h = 0; //~ min_ident_chars + } + } + let h = 0; //~ min_ident_chars +}; diff --git a/src/tools/clippy/tests/ui/min_ident_chars.stderr b/src/tools/clippy/tests/ui/min_ident_chars.stderr index 36bf89e79f004..07082bbc82936 100644 --- a/src/tools/clippy/tests/ui/min_ident_chars.stderr +++ b/src/tools/clippy/tests/ui/min_ident_chars.stderr @@ -1,4 +1,4 @@ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:9:8 | LL | struct A { @@ -7,269 +7,325 @@ LL | struct A { = note: `-D clippy::min-ident-chars` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::min_ident_chars)]` -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:11:5 | LL | a: u32, | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:14:5 | LL | A: u32, | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:16:5 | LL | I: u32, | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:20:8 | LL | struct B(u32); | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:23:8 | LL | struct O { | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:25:5 | LL | o: u32, | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:31:6 | LL | enum C { | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:33:5 | LL | D, | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:35:5 | LL | E, | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:37:5 | LL | F, | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:52:11 | LL | const A: u32 = 0; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:54:10 | LL | type A; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:56:8 | LL | fn a() {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:71:9 | LL | let h = 1; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:73:9 | LL | let e = 2; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:75:9 | LL | let l = 3; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:77:9 | LL | let l = 4; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:79:9 | LL | let o = 6; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:84:10 | LL | let (h, o, w) = (1, 2, 3); | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:84:13 | LL | let (h, o, w) = (1, 2, 3); | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:87:10 | LL | for (a, (r, e)) in (0..1000).enumerate().enumerate() {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:87:14 | LL | for (a, (r, e)) in (0..1000).enumerate().enumerate() {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:87:17 | LL | for (a, (r, e)) in (0..1000).enumerate().enumerate() {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:92:16 | LL | while let (d, o, _i, n, g) = (true, true, false, false, true) {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:92:19 | LL | while let (d, o, _i, n, g) = (true, true, false, false, true) {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:92:29 | LL | while let (d, o, _i, n, g) = (true, true, false, false, true) {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:99:9 | LL | let o = 1; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:101:9 | LL | let o = O { o }; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:116:4 | LL | fn b() {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:118:21 | LL | fn wrong_pythagoras(a: f32, b: f32) -> f32 { | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:118:29 | LL | fn wrong_pythagoras(a: f32, b: f32) -> f32 { | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:137:19 | LL | fn fmt(&self, g: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ^ + | + = note: the configured threshold is 1 -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:144:14 | LL | let a = |f: i8| f; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:144:9 | LL | let a = |f: i8| f; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:149:7 | LL | trait D { | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:151:10 | LL | fn f(g: i32); | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:151:8 | LL | fn f(g: i32); | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:156:8 | LL | fn g(arg: i8) { | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:158:12 | LL | fn c(d: u8) {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:158:14 | LL | fn c(d: u8) {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:166:12 | LL | fn h() {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:168:18 | LL | fn inner(a: i32) {} | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:170:18 | LL | let a = |f: String| f; | ^ -error: this ident consists of a single char +error: this identifier consists of only a single character --> tests/ui/min_ident_chars.rs:170:13 | LL | let a = |f: String| f; | ^ -error: aborting due to 45 previous errors +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:178:11 + | +LL | trait A { + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:180:14 + | +LL | fn f(h: [u32; 0]); + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:180:12 + | +LL | fn f(h: [u32; 0]); + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:192:41 + | +LL | ... let h = 0; + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:195:33 + | +LL | ... let h = 0; + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:199:29 + | +LL | let h = 0; + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:202:21 + | +LL | let h = 0; + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:206:17 + | +LL | let h = 0; + | ^ + +error: this identifier consists of only a single character + --> tests/ui/min_ident_chars.rs:209:9 + | +LL | let h = 0; + | ^ + +error: aborting due to 54 previous errors diff --git a/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.rs b/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.rs index 5d51c47eeed91..a3bad4f148ce8 100644 --- a/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.rs +++ b/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.rs @@ -445,4 +445,69 @@ fn issue16116() { } } +fn issue17453() { + static mut GLOBAL_INT: u32 = 5; + + // no lint: taking a raw pointer to a mutable static is safe, only not_very_safe is unsafe + fn set_global_int() { + unsafe { + not_very_safe(); + let _ = &raw mut GLOBAL_INT; + } + } + + // no lint: taking a raw pointer to a dereferenced raw pointer is safe, only not_very_safe is unsafe + fn reborrow_raw(value: *mut u32) { + unsafe { + not_very_safe(); + let _ = &raw mut *value; + } + } + + // lint: two unsaves are: + // 1. taking a raw pointer to a **dereferenced** raw pointer with field access + // 2. not_very_safe + #[derive(Clone, Copy)] + struct S { + x: u32, + } + fn reborrow_raw_field(value: *mut S) { + unsafe { + //~^ multiple_unsafe_ops_per_block + not_very_safe(); + let _ = &raw mut (*value).x; + } + } + + struct Nested { + s: S, + } + + // no lint: nested field access on a safe base under &raw is safe, only not_very_safe is unsafe + fn safe_nested(mut value: Nested) { + unsafe { + not_very_safe(); + let _ = &raw mut value.s.x; + } + } + + // lint: nested field access on a mutable static under &raw is unsafe, plus not_very_safe + static mut GLOBAL_STRUCT: Nested = Nested { s: S { x: 5 } }; + fn unsafe_nested_static() { + unsafe { + //~^ multiple_unsafe_ops_per_block + not_very_safe(); + let _ = &raw mut GLOBAL_STRUCT.s.x; + } + } + + // lint: nested field access on a raw pointer deref under &raw is unsafe, plus not_very_safe + fn unsafe_nested_raw(ptr: *mut Nested) { + unsafe { + //~^ multiple_unsafe_ops_per_block + not_very_safe(); + let _ = &raw mut (*ptr).s.x; + } + } +} fn main() {} diff --git a/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.stderr b/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.stderr index 185225bd28c84..f659c6b670ad5 100644 --- a/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.stderr +++ b/src/tools/clippy/tests/ui/multiple_unsafe_ops_per_block.stderr @@ -524,5 +524,68 @@ note: unsafe function call occurs here LL | unsafe_with_arg!(foo()); | ^^^^^ -error: aborting due to 24 previous errors +error: this `unsafe` block contains 2 unsafe operations, expected only one + --> tests/ui/multiple_unsafe_ops_per_block.rs:475:9 + | +LL | / unsafe { +LL | | +LL | | not_very_safe(); +LL | | let _ = &raw mut (*value).x; +LL | | } + | |_________^ + | +note: raw pointer dereference occurs here + --> tests/ui/multiple_unsafe_ops_per_block.rs:478:30 + | +LL | let _ = &raw mut (*value).x; + | ^^^^^^^^ +note: unsafe function call occurs here + --> tests/ui/multiple_unsafe_ops_per_block.rs:477:13 + | +LL | not_very_safe(); + | ^^^^^^^^^^^^^^^ + +error: this `unsafe` block contains 2 unsafe operations, expected only one + --> tests/ui/multiple_unsafe_ops_per_block.rs:497:9 + | +LL | / unsafe { +LL | | +LL | | not_very_safe(); +LL | | let _ = &raw mut GLOBAL_STRUCT.s.x; +LL | | } + | |_________^ + | +note: access of a mutable static occurs here + --> tests/ui/multiple_unsafe_ops_per_block.rs:500:30 + | +LL | let _ = &raw mut GLOBAL_STRUCT.s.x; + | ^^^^^^^^^^^^^ +note: unsafe function call occurs here + --> tests/ui/multiple_unsafe_ops_per_block.rs:499:13 + | +LL | not_very_safe(); + | ^^^^^^^^^^^^^^^ + +error: this `unsafe` block contains 2 unsafe operations, expected only one + --> tests/ui/multiple_unsafe_ops_per_block.rs:506:9 + | +LL | / unsafe { +LL | | +LL | | not_very_safe(); +LL | | let _ = &raw mut (*ptr).s.x; +LL | | } + | |_________^ + | +note: raw pointer dereference occurs here + --> tests/ui/multiple_unsafe_ops_per_block.rs:509:30 + | +LL | let _ = &raw mut (*ptr).s.x; + | ^^^^^^ +note: unsafe function call occurs here + --> tests/ui/multiple_unsafe_ops_per_block.rs:508:13 + | +LL | not_very_safe(); + | ^^^^^^^^^^^^^^^ + +error: aborting due to 27 previous errors diff --git a/src/tools/clippy/tests/ui/must_use_candidates.fixed b/src/tools/clippy/tests/ui/must_use_candidates.fixed index 226fafccddced..8aac045cad089 100644 --- a/src/tools/clippy/tests/ui/must_use_candidates.fixed +++ b/src/tools/clippy/tests/ui/must_use_candidates.fixed @@ -105,12 +105,20 @@ pub fn main() -> std::process::ExitCode { //~v must_use_candidate #[must_use] -pub fn result_uninhabited() -> Result { +pub fn result_uninhabited_1() -> Result { todo!() } -//~v must_use_candidate #[must_use] -pub fn controlflow_uninhabited() -> std::ops::ControlFlow { +pub struct T; + +// Do not lint, `T` is `#[must_use]`, so the `Result` also is. +pub fn result_uninhabited_2() -> Result { + todo!() +} + +// Do not lint: even though `Box` itself is not `#[must_use]`, if the content is (which is +// the case of `T`), the compiler will treat the box as a `#[must_use]` type already. +pub fn with_box() -> Box { todo!() } diff --git a/src/tools/clippy/tests/ui/must_use_candidates.rs b/src/tools/clippy/tests/ui/must_use_candidates.rs index f9b6c2986504c..d0e2dbd3d62de 100644 --- a/src/tools/clippy/tests/ui/must_use_candidates.rs +++ b/src/tools/clippy/tests/ui/must_use_candidates.rs @@ -99,11 +99,20 @@ pub fn main() -> std::process::ExitCode { } //~v must_use_candidate -pub fn result_uninhabited() -> Result { +pub fn result_uninhabited_1() -> Result { todo!() } -//~v must_use_candidate -pub fn controlflow_uninhabited() -> std::ops::ControlFlow { +#[must_use] +pub struct T; + +// Do not lint, `T` is `#[must_use]`, so the `Result` also is. +pub fn result_uninhabited_2() -> Result { + todo!() +} + +// Do not lint: even though `Box` itself is not `#[must_use]`, if the content is (which is +// the case of `T`), the compiler will treat the box as a `#[must_use]` type already. +pub fn with_box() -> Box { todo!() } diff --git a/src/tools/clippy/tests/ui/must_use_candidates.stderr b/src/tools/clippy/tests/ui/must_use_candidates.stderr index 24fda87cd16aa..9f6beaf19595d 100644 --- a/src/tools/clippy/tests/ui/must_use_candidates.stderr +++ b/src/tools/clippy/tests/ui/must_use_candidates.stderr @@ -63,28 +63,14 @@ LL | pub fn arcd(_x: Arc) -> bool { error: this function could have a `#[must_use]` attribute --> tests/ui/must_use_candidates.rs:102:8 | -LL | pub fn result_uninhabited() -> Result { - | ^^^^^^^^^^^^^^^^^^ +LL | pub fn result_uninhabited_1() -> Result { + | ^^^^^^^^^^^^^^^^^^^^ | - = note: a future version of Rust will treat `Result` as `T` when `E` is uninhabited wrt `#[must_use]` help: add the attribute | LL + #[must_use] -LL | pub fn result_uninhabited() -> Result { +LL | pub fn result_uninhabited_1() -> Result { | -error: this function could have a `#[must_use]` attribute - --> tests/ui/must_use_candidates.rs:107:8 - | -LL | pub fn controlflow_uninhabited() -> std::ops::ControlFlow { - | ^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: a future version of Rust will treat `ControlFlow` as `C` when `B` is uninhabited wrt `#[must_use]` -help: add the attribute - | -LL + #[must_use] -LL | pub fn controlflow_uninhabited() -> std::ops::ControlFlow { - | - -error: aborting due to 7 previous errors +error: aborting due to 6 previous errors diff --git a/src/tools/clippy/tests/ui/needless_collect.fixed b/src/tools/clippy/tests/ui/needless_collect.fixed index ca25395e375bc..a7df03ff3ef1e 100644 --- a/src/tools/clippy/tests/ui/needless_collect.fixed +++ b/src/tools/clippy/tests/ui/needless_collect.fixed @@ -198,10 +198,6 @@ mod issue8055_regression { } } - #[expect( - clippy::needless_collect, - reason = "FIXME: proposed fix cannot determine type, see issue #17315" - )] fn foo() { Foo { inner: [].iter(), diff --git a/src/tools/clippy/tests/ui/needless_collect.rs b/src/tools/clippy/tests/ui/needless_collect.rs index 4fafa2e9adf6b..b46c41068b2be 100644 --- a/src/tools/clippy/tests/ui/needless_collect.rs +++ b/src/tools/clippy/tests/ui/needless_collect.rs @@ -198,10 +198,6 @@ mod issue8055_regression { } } - #[expect( - clippy::needless_collect, - reason = "FIXME: proposed fix cannot determine type, see issue #17315" - )] fn foo() { Foo { inner: [].iter(), diff --git a/src/tools/clippy/tests/ui/needless_collect.stderr b/src/tools/clippy/tests/ui/needless_collect.stderr index 402a1fd19a7c7..caaaee7705454 100644 --- a/src/tools/clippy/tests/ui/needless_collect.stderr +++ b/src/tools/clippy/tests/ui/needless_collect.stderr @@ -122,7 +122,7 @@ LL | baz((0..10), (), ('a'..='z').collect::>()) | ^^^^^^^^^^^^^^^^^^^^ help: remove this call error: avoid using `collect()` when not needed - --> tests/ui/needless_collect.rs:224:26 + --> tests/ui/needless_collect.rs:220:26 | LL | let mut v = iter.collect::>(); | ^^^^^^^ @@ -139,7 +139,7 @@ LL ~ iter.chain([1]).map(|x| x + 1).collect() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect.rs:236:26 + --> tests/ui/needless_collect.rs:232:26 | LL | let mut v = iter.collect::>(); | ^^^^^^^ @@ -157,7 +157,7 @@ LL ~ iter.chain([1, 2]).map(|x| x + 1).collect() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect.rs:244:26 + --> tests/ui/needless_collect.rs:240:26 | LL | let mut v = iter.collect::>(); | ^^^^^^^ @@ -174,7 +174,7 @@ LL ~ iter.chain([1]).map(|x| x + 1).collect() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect.rs:264:27 + --> tests/ui/needless_collect.rs:260:27 | LL | let mut ll = iter.collect::>(); | ^^^^^^^ @@ -191,7 +191,7 @@ LL ~ iter.chain(s).map(|x| x + 1).collect() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect.rs:271:26 + --> tests/ui/needless_collect.rs:267:26 | LL | let mut v = iter.collect::>(); | ^^^^^^^ @@ -209,7 +209,7 @@ LL ~ [1, 2].into_iter().chain(iter).map(|x| x + 1).collect() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect.rs:282:26 + --> tests/ui/needless_collect.rs:278:26 | LL | let mut v = iter.collect::>(); | ^^^^^^^ diff --git a/src/tools/clippy/tests/ui/no_effect.rs b/src/tools/clippy/tests/ui/no_effect.rs index b4eea30f74b17..1a53586428a8a 100644 --- a/src/tools/clippy/tests/ui/no_effect.rs +++ b/src/tools/clippy/tests/ui/no_effect.rs @@ -1,3 +1,5 @@ +//@aux-build:proc_macros.rs + #![feature(fn_traits, unboxed_closures)] #![warn(clippy::no_effect_underscore_binding)] #![expect( @@ -8,6 +10,9 @@ clippy::useless_vec )] +extern crate proc_macros; + +use proc_macros::{external, with_span}; use std::fmt::Display; use std::ops::{Neg, Shl}; @@ -274,3 +279,20 @@ fn issue14592() { }; }; } + +fn issue17430(value: i32) { + // Should not lint: the `let` binding is generated by an external/proc macro even though the + // bound identifier keeps its original span (as happens with `#[no_panic]`). + external! { + let $_produced = 1; + } + with_span! { + span + let $_produced = 1; + } + // Should not lint: here the initializer keeps its original span, so only checking the whole + // `let` statement's span (rather than just the pattern's) catches the generated binding. + external! { + let $_produced = $value; + } +} diff --git a/src/tools/clippy/tests/ui/no_effect.stderr b/src/tools/clippy/tests/ui/no_effect.stderr index 58a9380cbfdeb..751b0512d9d11 100644 --- a/src/tools/clippy/tests/ui/no_effect.stderr +++ b/src/tools/clippy/tests/ui/no_effect.stderr @@ -1,5 +1,5 @@ error: statement with no effect - --> tests/ui/no_effect.rs:115:5 + --> tests/ui/no_effect.rs:120:5 | LL | 0; | ^^ @@ -8,139 +8,139 @@ LL | 0; = help: to override `-D warnings` add `#[allow(clippy::no_effect)]` error: statement with no effect - --> tests/ui/no_effect.rs:118:5 + --> tests/ui/no_effect.rs:123:5 | LL | Tuple(0); | ^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:121:5 + --> tests/ui/no_effect.rs:126:5 | LL | Struct { field: 0 }; | ^^^^^^^^^^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:124:5 + --> tests/ui/no_effect.rs:129:5 | LL | Struct { ..s }; | ^^^^^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:127:5 + --> tests/ui/no_effect.rs:132:5 | LL | Union { a: 0 }; | ^^^^^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:130:5 + --> tests/ui/no_effect.rs:135:5 | LL | Enum::Tuple(0); | ^^^^^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:133:5 + --> tests/ui/no_effect.rs:138:5 | LL | Enum::Struct { field: 0 }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:136:5 + --> tests/ui/no_effect.rs:141:5 | LL | 5 + 6; | ^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:139:5 + --> tests/ui/no_effect.rs:144:5 | LL | *&42; | ^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:142:5 + --> tests/ui/no_effect.rs:147:5 | LL | &6; | ^^^ error: statement with no effect - --> tests/ui/no_effect.rs:145:5 + --> tests/ui/no_effect.rs:150:5 | LL | (5, 6, 7); | ^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:148:5 + --> tests/ui/no_effect.rs:153:5 | LL | ..; | ^^^ error: statement with no effect - --> tests/ui/no_effect.rs:151:5 + --> tests/ui/no_effect.rs:156:5 | LL | 5..; | ^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:154:5 + --> tests/ui/no_effect.rs:159:5 | LL | ..5; | ^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:157:5 + --> tests/ui/no_effect.rs:162:5 | LL | 5..6; | ^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:160:5 + --> tests/ui/no_effect.rs:165:5 | LL | 5..=6; | ^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:163:5 + --> tests/ui/no_effect.rs:168:5 | LL | [42, 55]; | ^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:166:5 + --> tests/ui/no_effect.rs:171:5 | LL | [42, 55][1]; | ^^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:169:5 + --> tests/ui/no_effect.rs:174:5 | LL | (42, 55).1; | ^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:172:5 + --> tests/ui/no_effect.rs:177:5 | LL | [42; 55]; | ^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:175:5 + --> tests/ui/no_effect.rs:180:5 | LL | [42; 55][13]; | ^^^^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:179:5 + --> tests/ui/no_effect.rs:184:5 | LL | || x += 5; | ^^^^^^^^^^ error: statement with no effect - --> tests/ui/no_effect.rs:183:5 + --> tests/ui/no_effect.rs:188:5 | LL | FooString { s: s }; | ^^^^^^^^^^^^^^^^^^^ error: binding to `_` prefixed variable with no side-effect - --> tests/ui/no_effect.rs:186:9 + --> tests/ui/no_effect.rs:191:9 | LL | let _unused = 1; | ^^^^^^^ @@ -149,19 +149,19 @@ LL | let _unused = 1; = help: to override `-D warnings` add `#[allow(clippy::no_effect_underscore_binding)]` error: binding to `_` prefixed variable with no side-effect - --> tests/ui/no_effect.rs:189:9 + --> tests/ui/no_effect.rs:194:9 | LL | let _penguin = || println!("Some helpful closure"); | ^^^^^^^^ error: binding to `_` prefixed variable with no side-effect - --> tests/ui/no_effect.rs:192:9 + --> tests/ui/no_effect.rs:197:9 | LL | let _duck = Struct { field: 0 }; | ^^^^^ error: binding to `_` prefixed variable with no side-effect - --> tests/ui/no_effect.rs:195:9 + --> tests/ui/no_effect.rs:200:9 | LL | let _cat = [2, 4, 6, 8][2]; | ^^^^ diff --git a/src/tools/clippy/tests/ui/non_canonical_clone_impl.fixed b/src/tools/clippy/tests/ui/non_canonical_clone_impl.fixed index 466a1304e72c5..7cbc8f8aa06f5 100644 --- a/src/tools/clippy/tests/ui/non_canonical_clone_impl.fixed +++ b/src/tools/clippy/tests/ui/non_canonical_clone_impl.fixed @@ -1,4 +1,5 @@ //@aux-build:proc_macro_derive.rs +//@aux-build:proc_macros.rs #![expect(clippy::clone_on_copy)] #![allow(clippy::assigning_clones)] #![no_main] diff --git a/src/tools/clippy/tests/ui/non_canonical_clone_impl.rs b/src/tools/clippy/tests/ui/non_canonical_clone_impl.rs index 5f815b567dfc7..58b2a3207efd4 100644 --- a/src/tools/clippy/tests/ui/non_canonical_clone_impl.rs +++ b/src/tools/clippy/tests/ui/non_canonical_clone_impl.rs @@ -1,4 +1,5 @@ //@aux-build:proc_macro_derive.rs +//@aux-build:proc_macros.rs #![expect(clippy::clone_on_copy)] #![allow(clippy::assigning_clones)] #![no_main] diff --git a/src/tools/clippy/tests/ui/non_canonical_clone_impl.stderr b/src/tools/clippy/tests/ui/non_canonical_clone_impl.stderr index 3741a7dcce860..98862b426ec5c 100644 --- a/src/tools/clippy/tests/ui/non_canonical_clone_impl.stderr +++ b/src/tools/clippy/tests/ui/non_canonical_clone_impl.stderr @@ -1,5 +1,5 @@ error: non-canonical implementation of `clone` on a `Copy` type - --> tests/ui/non_canonical_clone_impl.rs:12:29 + --> tests/ui/non_canonical_clone_impl.rs:13:29 | LL | fn clone(&self) -> Self { | _____________________________^ @@ -12,7 +12,7 @@ LL | | } = help: to override `-D warnings` add `#[allow(clippy::non_canonical_clone_impl)]` error: unnecessary implementation of `clone_from` on a `Copy` type - --> tests/ui/non_canonical_clone_impl.rs:17:5 + --> tests/ui/non_canonical_clone_impl.rs:18:5 | LL | / fn clone_from(&mut self, source: &Self) { LL | | @@ -22,7 +22,7 @@ LL | | } | |_____^ help: remove it error: non-canonical implementation of `clone` on a `Copy` type - --> tests/ui/non_canonical_clone_impl.rs:82:29 + --> tests/ui/non_canonical_clone_impl.rs:83:29 | LL | fn clone(&self) -> Self { | _____________________________^ @@ -32,7 +32,7 @@ LL | | } | |_____^ help: change this to: `{ *self }` error: unnecessary implementation of `clone_from` on a `Copy` type - --> tests/ui/non_canonical_clone_impl.rs:87:5 + --> tests/ui/non_canonical_clone_impl.rs:88:5 | LL | / fn clone_from(&mut self, source: &Self) { LL | | @@ -42,7 +42,7 @@ LL | | } | |_____^ help: remove it error: non-canonical implementation of `clone` on a `Copy` type - --> tests/ui/non_canonical_clone_impl.rs:121:37 + --> tests/ui/non_canonical_clone_impl.rs:122:37 | LL | fn clone(&self) -> Self { | _____________________________________^ @@ -54,7 +54,7 @@ LL | | } = note: this error originates in the macro `__inline_mac_mod_issue12788` (in Nightly builds, run with -Z macro-backtrace for more info) error: non-canonical implementation of `clone` on a `Copy` type - --> tests/ui/non_canonical_clone_impl.rs:160:29 + --> tests/ui/non_canonical_clone_impl.rs:161:29 | LL | fn clone(&self) -> Self { | _____________________________^ @@ -64,7 +64,7 @@ LL | | } | |_____^ help: change this to: `{ *self }` error: non-canonical implementation of `clone` on a `Copy` type - --> tests/ui/non_canonical_clone_impl.rs:187:33 + --> tests/ui/non_canonical_clone_impl.rs:188:33 | LL | fn clone(&self) -> Self { | _________________________________^ diff --git a/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.fixed b/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.fixed index aa23fd99ad77b..526497c781501 100644 --- a/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.fixed +++ b/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.fixed @@ -1,4 +1,5 @@ //@aux-build:proc_macro_derive.rs +//@aux-build:proc_macros.rs #![no_main] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.rs b/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.rs index da7f73f7c4bef..cff98810adebc 100644 --- a/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.rs +++ b/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.rs @@ -1,4 +1,5 @@ //@aux-build:proc_macro_derive.rs +//@aux-build:proc_macros.rs #![no_main] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.stderr b/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.stderr index 36f68ae897d3d..ffd0611497fa7 100644 --- a/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.stderr +++ b/src/tools/clippy/tests/ui/non_canonical_partial_ord_impl.stderr @@ -1,5 +1,5 @@ error: non-canonical implementation of `partial_cmp` on an `Ord` type - --> tests/ui/non_canonical_partial_ord_impl.rs:20:1 + --> tests/ui/non_canonical_partial_ord_impl.rs:21:1 | LL | / impl PartialOrd for A { LL | | @@ -20,7 +20,7 @@ LL + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp | error: non-canonical implementation of `partial_cmp` on an `Ord` type - --> tests/ui/non_canonical_partial_ord_impl.rs:55:1 + --> tests/ui/non_canonical_partial_ord_impl.rs:56:1 | LL | / impl PartialOrd for C { LL | | @@ -39,7 +39,7 @@ LL + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp | error: non-canonical implementation of `partial_cmp` on an `Ord` type - --> tests/ui/non_canonical_partial_ord_impl.rs:191:9 + --> tests/ui/non_canonical_partial_ord_impl.rs:192:9 | LL | / impl PartialOrd for A { LL | | @@ -59,7 +59,7 @@ LL + fn partial_cmp(&self, other: &Self) -> Option { Some( | error: non-canonical implementation of `partial_cmp` on an `Ord` type - --> tests/ui/non_canonical_partial_ord_impl.rs:271:1 + --> tests/ui/non_canonical_partial_ord_impl.rs:272:1 | LL | / impl PartialOrd for K { LL | | @@ -78,7 +78,7 @@ LL + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp | error: non-canonical implementation of `partial_cmp` on an `Ord` type - --> tests/ui/non_canonical_partial_ord_impl.rs:289:1 + --> tests/ui/non_canonical_partial_ord_impl.rs:290:1 | LL | / impl PartialOrd for L { LL | | diff --git a/src/tools/clippy/tests/ui/non_zero_suggestions.fixed b/src/tools/clippy/tests/ui/non_zero_suggestions.fixed index 4573896ecd673..b714a6cf6ede7 100644 --- a/src/tools/clippy/tests/ui/non_zero_suggestions.fixed +++ b/src/tools/clippy/tests/ui/non_zero_suggestions.fixed @@ -1,5 +1,5 @@ #![warn(clippy::non_zero_suggestions)] -use std::num::{NonZeroI8, NonZeroI16, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize}; +use std::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize}; fn main() { /// Positive test cases (lint should trigger) @@ -45,6 +45,12 @@ fn main() { let k: u64 = 300; let l = NonZeroU32::new(15).unwrap(); let r9 = k / NonZeroU64::from(l); + + // Signed integers in div/rem: must NOT trigger because i64 / NonZeroI64 is not in std + let s: i64 = 10; + let t = NonZeroI32::new(3).unwrap(); + let r10 = s / i64::from(t.get()); + let r11 = s % i64::from(t.get()); } // Additional function to test the lint in a different context diff --git a/src/tools/clippy/tests/ui/non_zero_suggestions.rs b/src/tools/clippy/tests/ui/non_zero_suggestions.rs index 3e7081e0c1c0c..0e4cd3cc36528 100644 --- a/src/tools/clippy/tests/ui/non_zero_suggestions.rs +++ b/src/tools/clippy/tests/ui/non_zero_suggestions.rs @@ -1,5 +1,5 @@ #![warn(clippy::non_zero_suggestions)] -use std::num::{NonZeroI8, NonZeroI16, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize}; +use std::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize}; fn main() { /// Positive test cases (lint should trigger) @@ -45,6 +45,12 @@ fn main() { let k: u64 = 300; let l = NonZeroU32::new(15).unwrap(); let r9 = k / NonZeroU64::from(l); + + // Signed integers in div/rem: must NOT trigger because i64 / NonZeroI64 is not in std + let s: i64 = 10; + let t = NonZeroI32::new(3).unwrap(); + let r10 = s / i64::from(t.get()); + let r11 = s % i64::from(t.get()); } // Additional function to test the lint in a different context diff --git a/src/tools/clippy/tests/ui/non_zero_suggestions.stderr b/src/tools/clippy/tests/ui/non_zero_suggestions.stderr index 7a57f7983be74..4b5a8a3fc6ff7 100644 --- a/src/tools/clippy/tests/ui/non_zero_suggestions.stderr +++ b/src/tools/clippy/tests/ui/non_zero_suggestions.stderr @@ -26,13 +26,13 @@ LL | let x = u64::from(NonZeroU32::new(5).unwrap().get()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `NonZeroU64::from(NonZeroU32::new(5).unwrap())` error: consider using `NonZeroU64::from()` for more efficient and type-safe conversion - --> tests/ui/non_zero_suggestions.rs:52:9 + --> tests/ui/non_zero_suggestions.rs:58:9 | LL | x / u64::from(y.get()) | ^^^^^^^^^^^^^^^^^^ help: replace with: `NonZeroU64::from(y)` error: consider using `NonZeroU64::from()` for more efficient and type-safe conversion - --> tests/ui/non_zero_suggestions.rs:62:22 + --> tests/ui/non_zero_suggestions.rs:68:22 | LL | self.value / u64::from(divisor.get()) | ^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `NonZeroU64::from(divisor)` diff --git a/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.fixed b/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.fixed new file mode 100644 index 0000000000000..746bd29764dc1 --- /dev/null +++ b/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.fixed @@ -0,0 +1,156 @@ +#![warn(clippy::nonnull_unchecked_on_box_ptr)] + +use std::ptr::NonNull; + +macro_rules! identity { + ($x:expr) => { + $x + }; +} + +macro_rules! weird { + ($x:expr) => {{ + let y = 1; + $x + }}; +} + +macro_rules! from_macro { + ($x:expr) => { + unsafe { NonNull::new_unchecked(Box::into_raw($x)) } + }; +} + +fn identity(x: T) -> T { + x +} + +unsafe fn unsafe_identity(x: T) -> T { + x +} + +fn lint() { + fn basic() { + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(identity(one))); + } + + fn qualifiers() { + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + { + use Box as Box2; + use NonNull as NonNull2; + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + } + + { + type Box2 = Box; + type NonNull2 = NonNull; + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + } + } + + fn macros() { + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + let one = Box::new(1); + let _ = identity!(NonNull::from_mut(Box::leak(one))); + + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(weird!(one))); + } + + fn keep_unsafe_block() { + let one = Box::new(1); + let _ = unsafe { + NonNull::from_mut(Box::leak(unsafe_identity(one))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let one = Box::new(1); + let _ = unsafe { + identity(NonNull::from_mut(Box::leak(one))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let one = Box::new(1); + let _ = unsafe { + unsafe_identity(NonNull::from_mut(Box::leak(one))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let _ = unsafe { + NonNull::from_mut(Box::leak(Box::new(std::num::NonZeroI32::new_unchecked(1)))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let _ = unsafe { + let one = Box::new(1); + NonNull::from_mut(Box::leak(one)) + //~^ nonnull_unchecked_on_box_ptr + }; + } +} + +fn no_lint() { + fn basic() { + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + let one = Box::new(1); + let _ = unsafe { NonNull::new_unchecked(identity(Box::into_raw(one))) }; + } + + // TODO? + fn does_not_check_expr_init() { + let one = Box::new(1); + let leaked = Box::into_raw(one); + let _ = unsafe { NonNull::new_unchecked(leaked) }; + + let one = Box::new(1); + let leaked = Box::leak(one); + let _ = NonNull::from_mut(leaked); + } + + fn macros() { + let one = Box::new(1); + let _ = from_macro!(one); + } +} + +#[clippy::msrv = "1.25"] +fn msrv_1_25() { + let one = Box::new(1); + let _ = unsafe { NonNull::new_unchecked(Box::into_raw(one)) }; +} + +#[clippy::msrv = "1.26"] +fn msrv_1_26() { + let one = Box::new(1); + let _ = NonNull::from(Box::leak(one)); +} + +#[clippy::msrv = "1.89"] +fn msrv_1_89() { + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.rs b/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.rs new file mode 100644 index 0000000000000..2acc5c9270c88 --- /dev/null +++ b/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.rs @@ -0,0 +1,195 @@ +#![warn(clippy::nonnull_unchecked_on_box_ptr)] + +use std::ptr::NonNull; + +macro_rules! identity { + ($x:expr) => { + $x + }; +} + +macro_rules! weird { + ($x:expr) => {{ + let y = 1; + $x + }}; +} + +macro_rules! from_macro { + ($x:expr) => { + unsafe { NonNull::new_unchecked(Box::into_raw($x)) } + }; +} + +fn identity(x: T) -> T { + x +} + +unsafe fn unsafe_identity(x: T) -> T { + x +} + +fn lint() { + fn basic() { + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(Box::into_raw(one)) + }; + + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(Box::into_raw(identity(one))) + }; + } + + fn qualifiers() { + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + std::ptr::NonNull::new_unchecked(std::boxed::Box::into_raw(one)) + }; + + { + use Box as Box2; + use NonNull as NonNull2; + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull2::new_unchecked(Box2::into_raw(one)) + }; + } + + { + type Box2 = Box; + type NonNull2 = NonNull; + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull2::new_unchecked(Box2::into_raw(one)) + }; + } + } + + fn macros() { + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(Box::into_raw(identity!(one))) + }; + + let one = Box::new(1); + let _ = identity!(unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(Box::into_raw(one)) + }); + + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + identity!(NonNull::new_unchecked(Box::into_raw(one))) + }; + + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(identity!(Box::into_raw(one))) + }; + + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(identity!(Box::into_raw(identity!(one)))) + }; + + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(Box::into_raw(weird!(one))) + }; + } + + fn keep_unsafe_block() { + let one = Box::new(1); + let _ = unsafe { + NonNull::new_unchecked(Box::into_raw(unsafe_identity(one))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let one = Box::new(1); + let _ = unsafe { + identity(NonNull::new_unchecked(Box::into_raw(one))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let one = Box::new(1); + let _ = unsafe { + unsafe_identity(NonNull::new_unchecked(Box::into_raw(one))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let _ = unsafe { + NonNull::new_unchecked(Box::into_raw(Box::new(std::num::NonZeroI32::new_unchecked(1)))) + //~^ nonnull_unchecked_on_box_ptr + }; + + let _ = unsafe { + let one = Box::new(1); + NonNull::new_unchecked(Box::into_raw(one)) + //~^ nonnull_unchecked_on_box_ptr + }; + } +} + +fn no_lint() { + fn basic() { + let one = Box::new(1); + let _ = NonNull::from_mut(Box::leak(one)); + + let one = Box::new(1); + let _ = unsafe { NonNull::new_unchecked(identity(Box::into_raw(one))) }; + } + + // TODO? + fn does_not_check_expr_init() { + let one = Box::new(1); + let leaked = Box::into_raw(one); + let _ = unsafe { NonNull::new_unchecked(leaked) }; + + let one = Box::new(1); + let leaked = Box::leak(one); + let _ = NonNull::from_mut(leaked); + } + + fn macros() { + let one = Box::new(1); + let _ = from_macro!(one); + } +} + +#[clippy::msrv = "1.25"] +fn msrv_1_25() { + let one = Box::new(1); + let _ = unsafe { NonNull::new_unchecked(Box::into_raw(one)) }; +} + +#[clippy::msrv = "1.26"] +fn msrv_1_26() { + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(Box::into_raw(one)) + }; +} + +#[clippy::msrv = "1.89"] +fn msrv_1_89() { + let one = Box::new(1); + let _ = unsafe { + //~^ nonnull_unchecked_on_box_ptr + NonNull::new_unchecked(Box::into_raw(one)) + }; +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.stderr b/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.stderr new file mode 100644 index 0000000000000..8d26914cde7b0 --- /dev/null +++ b/src/tools/clippy/tests/ui/nonnull_unchecked_on_box_ptr.stderr @@ -0,0 +1,165 @@ +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:35:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | NonNull::new_unchecked(Box::into_raw(one)) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(one))` + | + = note: `-D clippy::nonnull-unchecked-on-box-ptr` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::nonnull_unchecked_on_box_ptr)]` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:41:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | NonNull::new_unchecked(Box::into_raw(identity(one))) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(identity(one)))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:49:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | std::ptr::NonNull::new_unchecked(std::boxed::Box::into_raw(one)) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:58:21 + | +LL | let _ = unsafe { + | _____________________^ +LL | | +LL | | NonNull2::new_unchecked(Box2::into_raw(one)) +LL | | }; + | |_____________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:68:21 + | +LL | let _ = unsafe { + | _____________________^ +LL | | +LL | | NonNull2::new_unchecked(Box2::into_raw(one)) +LL | | }; + | |_____________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:77:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | NonNull::new_unchecked(Box::into_raw(identity!(one))) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:83:27 + | +LL | let _ = identity!(unsafe { + | ___________________________^ +LL | | +LL | | NonNull::new_unchecked(Box::into_raw(one)) +LL | | }); + | |_________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:89:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | identity!(NonNull::new_unchecked(Box::into_raw(one))) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:95:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | NonNull::new_unchecked(identity!(Box::into_raw(one))) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:101:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | NonNull::new_unchecked(identity!(Box::into_raw(identity!(one)))) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:107:17 + | +LL | let _ = unsafe { + | _________________^ +LL | | +LL | | NonNull::new_unchecked(Box::into_raw(weird!(one))) +LL | | }; + | |_________^ help: try: `NonNull::from_mut(Box::leak(weird!(one)))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:116:13 + | +LL | NonNull::new_unchecked(Box::into_raw(unsafe_identity(one))) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `NonNull::from_mut(Box::leak(unsafe_identity(one)))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:122:22 + | +LL | identity(NonNull::new_unchecked(Box::into_raw(one))) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:128:29 + | +LL | unsafe_identity(NonNull::new_unchecked(Box::into_raw(one))) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:133:13 + | +LL | NonNull::new_unchecked(Box::into_raw(Box::new(std::num::NonZeroI32::new_unchecked(1)))) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `NonNull::from_mut(Box::leak(Box::new(std::num::NonZeroI32::new_unchecked(1))))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:139:13 + | +LL | NonNull::new_unchecked(Box::into_raw(one)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:180:13 + | +LL | let _ = unsafe { + | _____________^ +LL | | +LL | | NonNull::new_unchecked(Box::into_raw(one)) +LL | | }; + | |_____^ help: try: `NonNull::from(Box::leak(one))` + +error: use of `NonNull::new_unchecked` with `Box::into_raw` + --> tests/ui/nonnull_unchecked_on_box_ptr.rs:189:13 + | +LL | let _ = unsafe { + | _____________^ +LL | | +LL | | NonNull::new_unchecked(Box::into_raw(one)) +LL | | }; + | |_____^ help: try: `NonNull::from_mut(Box::leak(one))` + +error: aborting due to 18 previous errors + diff --git a/src/tools/clippy/tests/ui/println_empty_string.fixed b/src/tools/clippy/tests/ui/println_empty_string.fixed index a735795df432a..32d46f07ac87d 100644 --- a/src/tools/clippy/tests/ui/println_empty_string.fixed +++ b/src/tools/clippy/tests/ui/println_empty_string.fixed @@ -1,5 +1,5 @@ #![warn(clippy::println_empty_string)] -#![expect(clippy::match_single_binding)] +#![expect(clippy::match_single_binding, clippy::nonstandard_macro_braces)] fn main() { println!(); diff --git a/src/tools/clippy/tests/ui/println_empty_string.rs b/src/tools/clippy/tests/ui/println_empty_string.rs index d081338f02a11..1d3912dc84c0b 100644 --- a/src/tools/clippy/tests/ui/println_empty_string.rs +++ b/src/tools/clippy/tests/ui/println_empty_string.rs @@ -1,5 +1,5 @@ #![warn(clippy::println_empty_string)] -#![expect(clippy::match_single_binding)] +#![expect(clippy::match_single_binding, clippy::nonstandard_macro_braces)] fn main() { println!(); diff --git a/src/tools/clippy/tests/ui/redundant_pattern_matching_option.fixed b/src/tools/clippy/tests/ui/redundant_pattern_matching_option.fixed index 8a6f1bb638765..20542cb294e56 100644 --- a/src/tools/clippy/tests/ui/redundant_pattern_matching_option.fixed +++ b/src/tools/clippy/tests/ui/redundant_pattern_matching_option.fixed @@ -23,6 +23,29 @@ fn issue_11174_edge_cases(boolean: bool, boolean2: bool, maybe_some: Option) { + let _ = !(opt.is_none() && a); + //~^ redundant_pattern_matching + let _ = &(opt.is_none() && a); + //~^ redundant_pattern_matching + let _ = (opt.is_none() && a) as u8; + //~^ redundant_pattern_matching + let _ = (opt.is_none() && a) == b; + //~^ redundant_pattern_matching + let _ = (opt.is_none() && a).then_some(1); + //~^ redundant_pattern_matching + let _ = opt.is_none() && a; + //~^ redundant_pattern_matching + if opt.is_none() && a {} + //~^ redundant_pattern_matching + let _ = opt.is_none() && a && b; + //~^ redundant_pattern_matching + let _ = opt.is_none() && a || b; + //~^ redundant_pattern_matching + let _ = b.then_some(opt.is_none() && a); + //~^ redundant_pattern_matching +} + fn main() { if None::<()>.is_none() {} //~^ redundant_pattern_matching diff --git a/src/tools/clippy/tests/ui/redundant_pattern_matching_option.rs b/src/tools/clippy/tests/ui/redundant_pattern_matching_option.rs index b2e087b5211c7..a91e4a77fcb1d 100644 --- a/src/tools/clippy/tests/ui/redundant_pattern_matching_option.rs +++ b/src/tools/clippy/tests/ui/redundant_pattern_matching_option.rs @@ -23,6 +23,29 @@ fn issue_11174_edge_cases(boolean: bool, boolean2: bool, maybe_some: Option) { + let _ = !matches!(opt, None if a); + //~^ redundant_pattern_matching + let _ = &matches!(opt, None if a); + //~^ redundant_pattern_matching + let _ = matches!(opt, None if a) as u8; + //~^ redundant_pattern_matching + let _ = matches!(opt, None if a) == b; + //~^ redundant_pattern_matching + let _ = matches!(opt, None if a).then_some(1); + //~^ redundant_pattern_matching + let _ = matches!(opt, None if a); + //~^ redundant_pattern_matching + if matches!(opt, None if a) {} + //~^ redundant_pattern_matching + let _ = matches!(opt, None if a) && b; + //~^ redundant_pattern_matching + let _ = matches!(opt, None if a) || b; + //~^ redundant_pattern_matching + let _ = b.then_some(matches!(opt, None if a)); + //~^ redundant_pattern_matching +} + fn main() { if let None = None::<()> {} //~^ redundant_pattern_matching diff --git a/src/tools/clippy/tests/ui/redundant_pattern_matching_option.stderr b/src/tools/clippy/tests/ui/redundant_pattern_matching_option.stderr index 32d00715440fa..782636af80828 100644 --- a/src/tools/clippy/tests/ui/redundant_pattern_matching_option.stderr +++ b/src/tools/clippy/tests/ui/redundant_pattern_matching_option.stderr @@ -25,7 +25,127 @@ LL + let _ = maybe_some.is_none() && (boolean || boolean2); // guard needs p | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:27:12 + --> tests/ui/redundant_pattern_matching_option.rs:27:14 + | +LL | let _ = !matches!(opt, None if a); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = !matches!(opt, None if a); +LL + let _ = !(opt.is_none() && a); + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:29:14 + | +LL | let _ = &matches!(opt, None if a); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = &matches!(opt, None if a); +LL + let _ = &(opt.is_none() && a); + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:31:13 + | +LL | let _ = matches!(opt, None if a) as u8; + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = matches!(opt, None if a) as u8; +LL + let _ = (opt.is_none() && a) as u8; + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:33:13 + | +LL | let _ = matches!(opt, None if a) == b; + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = matches!(opt, None if a) == b; +LL + let _ = (opt.is_none() && a) == b; + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:35:13 + | +LL | let _ = matches!(opt, None if a).then_some(1); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = matches!(opt, None if a).then_some(1); +LL + let _ = (opt.is_none() && a).then_some(1); + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:37:13 + | +LL | let _ = matches!(opt, None if a); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = matches!(opt, None if a); +LL + let _ = opt.is_none() && a; + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:39:8 + | +LL | if matches!(opt, None if a) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - if matches!(opt, None if a) {} +LL + if opt.is_none() && a {} + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:41:13 + | +LL | let _ = matches!(opt, None if a) && b; + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = matches!(opt, None if a) && b; +LL + let _ = opt.is_none() && a && b; + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:43:13 + | +LL | let _ = matches!(opt, None if a) || b; + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = matches!(opt, None if a) || b; +LL + let _ = opt.is_none() && a || b; + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:45:25 + | +LL | let _ = b.then_some(matches!(opt, None if a)); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `is_none()` + | +LL - let _ = b.then_some(matches!(opt, None if a)); +LL + let _ = b.then_some(opt.is_none() && a); + | + +error: redundant pattern matching + --> tests/ui/redundant_pattern_matching_option.rs:50:12 | LL | if let None = None::<()> {} | ^^^^ @@ -37,7 +157,7 @@ LL + if None::<()>.is_none() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:30:12 + --> tests/ui/redundant_pattern_matching_option.rs:53:12 | LL | if let Some(_) = Some(42) {} | ^^^^^^^ @@ -49,7 +169,7 @@ LL + if Some(42).is_some() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:33:12 + --> tests/ui/redundant_pattern_matching_option.rs:56:12 | LL | if let Some(_) = Some(42) { | ^^^^^^^ @@ -61,7 +181,7 @@ LL + if Some(42).is_some() { | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:40:15 + --> tests/ui/redundant_pattern_matching_option.rs:63:15 | LL | while let Some(_) = Some(42) {} | ^^^^^^^ @@ -73,7 +193,7 @@ LL + while Some(42).is_some() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:43:15 + --> tests/ui/redundant_pattern_matching_option.rs:66:15 | LL | while let None = Some(42) {} | ^^^^ @@ -85,7 +205,7 @@ LL + while Some(42).is_none() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:46:15 + --> tests/ui/redundant_pattern_matching_option.rs:69:15 | LL | while let None = None::<()> {} | ^^^^ @@ -97,7 +217,7 @@ LL + while None::<()>.is_none() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:50:15 + --> tests/ui/redundant_pattern_matching_option.rs:73:15 | LL | while let Some(_) = v.pop() { | ^^^^^^^ @@ -109,7 +229,7 @@ LL + while v.pop().is_some() { | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:59:5 + --> tests/ui/redundant_pattern_matching_option.rs:82:5 | LL | / match Some(42) { LL | | @@ -129,7 +249,7 @@ LL + Some(42).is_some(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:65:5 + --> tests/ui/redundant_pattern_matching_option.rs:88:5 | LL | / match None::<()> { LL | | @@ -149,7 +269,7 @@ LL + None::<()>.is_none(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:71:13 + --> tests/ui/redundant_pattern_matching_option.rs:94:13 | LL | let _ = match None::<()> { | _____________^ @@ -170,7 +290,7 @@ LL + let _ = None::<()>.is_none(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:78:20 + --> tests/ui/redundant_pattern_matching_option.rs:101:20 | LL | let _ = if let Some(_) = opt { true } else { false }; | ^^^^^^^ @@ -182,7 +302,7 @@ LL + let _ = if opt.is_some() { true } else { false }; | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:85:20 + --> tests/ui/redundant_pattern_matching_option.rs:108:20 | LL | let _ = if let Some(_) = gen_opt() { | ^^^^^^^ @@ -194,7 +314,7 @@ LL + let _ = if gen_opt().is_some() { | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:88:19 + --> tests/ui/redundant_pattern_matching_option.rs:111:19 | LL | } else if let None = gen_opt() { | ^^^^ @@ -206,7 +326,7 @@ LL + } else if gen_opt().is_none() { | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:95:12 + --> tests/ui/redundant_pattern_matching_option.rs:118:12 | LL | if let Some(..) = gen_opt() {} | ^^^^^^^^ @@ -218,7 +338,7 @@ LL + if gen_opt().is_some() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:111:12 + --> tests/ui/redundant_pattern_matching_option.rs:134:12 | LL | if let Some(_) = Some(42) {} | ^^^^^^^ @@ -230,7 +350,7 @@ LL + if Some(42).is_some() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:114:12 + --> tests/ui/redundant_pattern_matching_option.rs:137:12 | LL | if let None = None::<()> {} | ^^^^ @@ -242,7 +362,7 @@ LL + if None::<()>.is_none() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:117:15 + --> tests/ui/redundant_pattern_matching_option.rs:140:15 | LL | while let Some(_) = Some(42) {} | ^^^^^^^ @@ -254,7 +374,7 @@ LL + while Some(42).is_some() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:120:15 + --> tests/ui/redundant_pattern_matching_option.rs:143:15 | LL | while let None = None::<()> {} | ^^^^ @@ -266,7 +386,7 @@ LL + while None::<()>.is_none() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:123:5 + --> tests/ui/redundant_pattern_matching_option.rs:146:5 | LL | / match Some(42) { LL | | @@ -286,7 +406,7 @@ LL + Some(42).is_some(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:129:5 + --> tests/ui/redundant_pattern_matching_option.rs:152:5 | LL | / match None::<()> { LL | | @@ -306,7 +426,7 @@ LL + None::<()>.is_none(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:138:12 + --> tests/ui/redundant_pattern_matching_option.rs:161:12 | LL | if let None = *(&None::<()>) {} | ^^^^ @@ -318,7 +438,7 @@ LL + if (&None::<()>).is_none() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:140:12 + --> tests/ui/redundant_pattern_matching_option.rs:163:12 | LL | if let None = *&None::<()> {} | ^^^^ @@ -330,7 +450,7 @@ LL + if (&None::<()>).is_none() {} | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:147:5 + --> tests/ui/redundant_pattern_matching_option.rs:170:5 | LL | / match x { LL | | @@ -350,7 +470,7 @@ LL + x.is_some(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:153:5 + --> tests/ui/redundant_pattern_matching_option.rs:176:5 | LL | / match x { LL | | @@ -370,7 +490,7 @@ LL + x.is_none(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:159:5 + --> tests/ui/redundant_pattern_matching_option.rs:182:5 | LL | / match x { LL | | @@ -390,7 +510,7 @@ LL + x.is_none(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:165:5 + --> tests/ui/redundant_pattern_matching_option.rs:188:5 | LL | / match x { LL | | @@ -410,7 +530,7 @@ LL + x.is_some(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:181:13 + --> tests/ui/redundant_pattern_matching_option.rs:204:13 | LL | let _ = matches!(x, Some(_)); | ^^^^^^^^^^^^^^^^^^^^ @@ -422,7 +542,7 @@ LL + let _ = x.is_some(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:184:13 + --> tests/ui/redundant_pattern_matching_option.rs:207:13 | LL | let _ = matches!(x, None); | ^^^^^^^^^^^^^^^^^ @@ -434,7 +554,7 @@ LL + let _ = x.is_none(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:195:17 + --> tests/ui/redundant_pattern_matching_option.rs:218:17 | LL | let _ = matches!(*p, None); | ^^^^^^^^^^^^^^^^^^ @@ -446,7 +566,7 @@ LL + let _ = (*p).is_none(); | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:203:16 + --> tests/ui/redundant_pattern_matching_option.rs:226:16 | LL | if let Some(_) = x? { | ^^^^^^^ @@ -458,7 +578,7 @@ LL + if x?.is_some() { | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:223:16 + --> tests/ui/redundant_pattern_matching_option.rs:246:16 | LL | if let Some(_) = x.await { | ^^^^^^^ @@ -470,7 +590,7 @@ LL + if x.await.is_some() { | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:236:12 + --> tests/ui/redundant_pattern_matching_option.rs:259:12 | LL | if let Some(_) = (x! {}) {}; | ^^^^^^^ @@ -482,7 +602,7 @@ LL + if x! {}.is_some() {}; | error: redundant pattern matching - --> tests/ui/redundant_pattern_matching_option.rs:238:15 + --> tests/ui/redundant_pattern_matching_option.rs:261:15 | LL | while let Some(_) = (x! {}) {} | ^^^^^^^ @@ -493,5 +613,5 @@ LL - while let Some(_) = (x! {}) {} LL + while x! {}.is_some() {} | -error: aborting due to 35 previous errors +error: aborting due to 45 previous errors diff --git a/src/tools/clippy/tests/ui/ref_as_ptr.fixed b/src/tools/clippy/tests/ui/ref_as_ptr.fixed index d00a2fd693f64..75a97330c61d3 100644 --- a/src/tools/clippy/tests/ui/ref_as_ptr.fixed +++ b/src/tools/clippy/tests/ui/ref_as_ptr.fixed @@ -99,6 +99,11 @@ fn main() { let _ = &String::new() as *const _; let _ = &mut String::new() as *mut _; const FOO: *const String = &String::new() as *const _; + + // Regression test for #13910. + // This should not lint because the suggested replacement fails during + // const evaluation. + static mut REGRESSION: *mut i32 = &mut [42] as *mut [i32] as *mut i32; } #[clippy::msrv = "1.75"] diff --git a/src/tools/clippy/tests/ui/ref_as_ptr.rs b/src/tools/clippy/tests/ui/ref_as_ptr.rs index c9b87256290fa..e3b816d4a0457 100644 --- a/src/tools/clippy/tests/ui/ref_as_ptr.rs +++ b/src/tools/clippy/tests/ui/ref_as_ptr.rs @@ -99,6 +99,11 @@ fn main() { let _ = &String::new() as *const _; let _ = &mut String::new() as *mut _; const FOO: *const String = &String::new() as *const _; + + // Regression test for #13910. + // This should not lint because the suggested replacement fails during + // const evaluation. + static mut REGRESSION: *mut i32 = &mut [42] as *mut [i32] as *mut i32; } #[clippy::msrv = "1.75"] diff --git a/src/tools/clippy/tests/ui/ref_as_ptr.stderr b/src/tools/clippy/tests/ui/ref_as_ptr.stderr index 587e4fb809cdb..c7b2bdea3cd1b 100644 --- a/src/tools/clippy/tests/ui/ref_as_ptr.stderr +++ b/src/tools/clippy/tests/ui/ref_as_ptr.stderr @@ -218,67 +218,67 @@ LL | let _ = &*x as *const _; | ^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref(&*x)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:119:7 + --> tests/ui/ref_as_ptr.rs:124:7 | LL | f(val as *const i32); | ^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref::(val)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:121:7 + --> tests/ui/ref_as_ptr.rs:126:7 | LL | f(mut_val as *mut i32); | ^^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_mut::(mut_val)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:126:7 + --> tests/ui/ref_as_ptr.rs:131:7 | LL | f(val as *const _); | ^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref(val)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:128:7 + --> tests/ui/ref_as_ptr.rs:133:7 | LL | f(val as *const [u8]); | ^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref::<[u8]>(val)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:133:7 + --> tests/ui/ref_as_ptr.rs:138:7 | LL | f(val as *mut _); | ^^^^^^^^^^^^^ help: try: `std::ptr::from_mut(val)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:135:7 + --> tests/ui/ref_as_ptr.rs:140:7 | LL | f(val as *mut str); | ^^^^^^^^^^^^^^^ help: try: `std::ptr::from_mut::(val)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:143:9 + --> tests/ui/ref_as_ptr.rs:148:9 | LL | self.0 as *const _ as *const _ | ^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref(self.0)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:148:9 + --> tests/ui/ref_as_ptr.rs:153:9 | LL | self.0 as *const _ as *const _ | ^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref(self.0)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:157:9 + --> tests/ui/ref_as_ptr.rs:162:9 | LL | self.0 as *const _ as *const _ | ^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref(self.0)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:162:9 + --> tests/ui/ref_as_ptr.rs:167:9 | LL | self.0 as *const _ as *const _ | ^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_ref(self.0)` error: reference as raw pointer - --> tests/ui/ref_as_ptr.rs:167:9 + --> tests/ui/ref_as_ptr.rs:172:9 | LL | self.0 as *mut _ as *mut _ | ^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_mut(self.0)` diff --git a/src/tools/clippy/tests/ui/ref_binding_to_reference.fixed b/src/tools/clippy/tests/ui/ref_binding_to_reference.fixed new file mode 100644 index 0000000000000..0a16bed4a43b6 --- /dev/null +++ b/src/tools/clippy/tests/ui/ref_binding_to_reference.fixed @@ -0,0 +1,99 @@ +#![warn(clippy::ref_binding_to_reference)] +#![expect(clippy::explicit_auto_deref)] +#![allow(clippy::needless_borrowed_reference)] + +fn f1(_: &str) {} +macro_rules! m2 { + ($e:expr) => { + f1(*$e) + }; +} +macro_rules! m3 { + ($i:ident) => { + Some(ref $i) + }; +} + +fn main() { + let x = String::new(); + + // Ok, the pattern is from a macro + let _: &&String = match Some(&x) { + m3!(x) => x, + None => return, + }; + + // Err, reference to a &String + #[expect( + clippy::ref_binding_to_reference, + reason = "The suggestion doesn't compile, see https://github.com/rust-lang/rust-clippy/issues/17370" + )] + let _: &&String = match Some(&x) { + Some(ref x) => x, + None => return, + }; + + // Err, reference to a &String + #[expect( + clippy::ref_binding_to_reference, + reason = "The suggestion doesn't compile, see https://github.com/rust-lang/rust-clippy/issues/17370" + )] + let _: &&String = match Some(&x) { + Some(ref x) => { + f1(x); + f1(*x); + x + }, + None => return, + }; + + // Err, reference to a &String + match Some(&x) { + Some(x) => m2!(&x), + //~^ ref_binding_to_reference + None => return, + } + + // Err, reference to a &String + let _ = |&x: &&String| { + //~^ ref_binding_to_reference + + let _: &&String = &x; + }; +} + +// Err, reference to a &String +fn f2<'a>(&x: &&'a String) -> &'a String { + //~^ ref_binding_to_reference + + let _: &&String = &x; + x +} + +trait T1 { + // Err, reference to a &String + fn f(&x: &&String) { + //~^ ref_binding_to_reference + + let _: &&String = &x; + } +} + +struct S; +impl T1 for S { + // Err, reference to a &String + fn f(&x: &&String) { + //~^ ref_binding_to_reference + + let _: &&String = &x; + } +} + +fn check_expect_suppression() { + let x = String::new(); + #[expect(clippy::ref_binding_to_reference)] + let _: &&String = match Some(&x) { + Some(ref x) => x, + None => return, + }; +} diff --git a/src/tools/clippy/tests/ui/ref_binding_to_reference.rs b/src/tools/clippy/tests/ui/ref_binding_to_reference.rs index a0f0b7b46ea42..04d8c9e95cf33 100644 --- a/src/tools/clippy/tests/ui/ref_binding_to_reference.rs +++ b/src/tools/clippy/tests/ui/ref_binding_to_reference.rs @@ -1,7 +1,6 @@ -// FIXME: run-rustfix waiting on multi-span suggestions -//@no-rustfix #![warn(clippy::ref_binding_to_reference)] -#![expect(clippy::explicit_auto_deref, clippy::needless_borrowed_reference)] +#![expect(clippy::explicit_auto_deref)] +#![allow(clippy::needless_borrowed_reference)] fn f1(_: &str) {} macro_rules! m2 { @@ -25,17 +24,22 @@ fn main() { }; // Err, reference to a &String + #[expect( + clippy::ref_binding_to_reference, + reason = "The suggestion doesn't compile, see https://github.com/rust-lang/rust-clippy/issues/17370" + )] let _: &&String = match Some(&x) { Some(ref x) => x, - //~^ ref_binding_to_reference None => return, }; // Err, reference to a &String + #[expect( + clippy::ref_binding_to_reference, + reason = "The suggestion doesn't compile, see https://github.com/rust-lang/rust-clippy/issues/17370" + )] let _: &&String = match Some(&x) { Some(ref x) => { - //~^ ref_binding_to_reference - f1(x); f1(*x); x diff --git a/src/tools/clippy/tests/ui/ref_binding_to_reference.stderr b/src/tools/clippy/tests/ui/ref_binding_to_reference.stderr index d06ca7458527c..b16cccf6f2399 100644 --- a/src/tools/clippy/tests/ui/ref_binding_to_reference.stderr +++ b/src/tools/clippy/tests/ui/ref_binding_to_reference.stderr @@ -1,47 +1,19 @@ error: this pattern creates a reference to a reference - --> tests/ui/ref_binding_to_reference.rs:29:14 + --> tests/ui/ref_binding_to_reference.rs:52:14 | -LL | Some(ref x) => x, +LL | Some(ref x) => m2!(x), | ^^^^^ | = note: `-D clippy::ref-binding-to-reference` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::ref_binding_to_reference)]` help: try | -LL - Some(ref x) => x, -LL + Some(x) => &x, - | - -error: this pattern creates a reference to a reference - --> tests/ui/ref_binding_to_reference.rs:36:14 - | -LL | Some(ref x) => { - | ^^^^^ - | -help: try - | -LL ~ Some(x) => { -LL | -LL | -LL | f1(x); -LL ~ f1(x); -LL ~ &x - | - -error: this pattern creates a reference to a reference - --> tests/ui/ref_binding_to_reference.rs:48:14 - | -LL | Some(ref x) => m2!(x), - | ^^^^^ - | -help: try - | LL - Some(ref x) => m2!(x), LL + Some(x) => m2!(&x), | error: this pattern creates a reference to a reference - --> tests/ui/ref_binding_to_reference.rs:54:15 + --> tests/ui/ref_binding_to_reference.rs:58:15 | LL | let _ = |&ref x: &&String| { | ^^^^^ @@ -55,7 +27,7 @@ LL ~ let _: &&String = &x; | error: this pattern creates a reference to a reference - --> tests/ui/ref_binding_to_reference.rs:62:12 + --> tests/ui/ref_binding_to_reference.rs:66:12 | LL | fn f2<'a>(&ref x: &&'a String) -> &'a String { | ^^^^^ @@ -70,7 +42,7 @@ LL ~ x | error: this pattern creates a reference to a reference - --> tests/ui/ref_binding_to_reference.rs:71:11 + --> tests/ui/ref_binding_to_reference.rs:75:11 | LL | fn f(&ref x: &&String) { | ^^^^^ @@ -84,7 +56,7 @@ LL ~ let _: &&String = &x; | error: this pattern creates a reference to a reference - --> tests/ui/ref_binding_to_reference.rs:81:11 + --> tests/ui/ref_binding_to_reference.rs:85:11 | LL | fn f(&ref x: &&String) { | ^^^^^ @@ -97,5 +69,5 @@ LL | LL ~ let _: &&String = &x; | -error: aborting due to 7 previous errors +error: aborting due to 5 previous errors diff --git a/src/tools/clippy/tests/ui/rest_pattern_accessible_field.fixed b/src/tools/clippy/tests/ui/rest_pattern_accessible_field.fixed new file mode 100644 index 0000000000000..73d240bb2641a --- /dev/null +++ b/src/tools/clippy/tests/ui/rest_pattern_accessible_field.fixed @@ -0,0 +1,108 @@ +//@aux-build:proc_macros.rs +//@aux-build:non-exhaustive-struct.rs +#![warn(clippy::rest_pattern_accessible_field)] +#![deny(clippy::unneeded_wildcard_pattern)] + +use non_exhaustive_struct::{NonExhaustiveStruct, NonExhaustiveStructNoPrivateFields}; + +struct S { + a: u8, + b: u8, + c: u8, +} + +#[derive(Default)] +#[non_exhaustive] +struct LocalNonExhaustive { + field: i32, +} + +enum E { + A { a1: u8, a2: u8 }, + B { b1: u8, b2: u8 }, + C {}, +} + +mod m { + #[derive(Default)] + pub struct Sm { + pub a: u8, + pub(crate) b: u8, + c: u8, + } +} + +fn main() { + let s = S { a: 1, b: 2, c: 3 }; + + let S { a, b, c: _ } = s; + //~^ rest_pattern_accessible_field + + let S { c, a: _, b: _ } = s; + //~^ rest_pattern_accessible_field + + let S { a, b, c, .. } = s; + + S { a: _, b: _, c: _ } = S { a: 1, b: 2, c: 3 }; + //~^ rest_pattern_accessible_field + + let e = E::A { a1: 1, a2: 2 }; + + match e { + E::A { a1, a2 } => (), + E::B { b1: _, b2: _ } => (), + //~^ rest_pattern_accessible_field + E::C { .. } => (), + } + + match e { + E::A { a1: _, a2: _ } => (), + E::B { b1: _, b2: _ } => (), + //~^ rest_pattern_accessible_field + E::C {} => (), + } + + proc_macros::external! { + let s1 = S { a: 1, b: 2, c: 3 }; + let S { a, b, .. } = s1; + } + + proc_macros::with_span! { + span + let s2 = S { a: 1, b: 2, c: 3 }; + let S { a, b, .. } = s2; + } + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { field1: _, field2: _, .. } = ne; + //~^ rest_pattern_accessible_field + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { + field1: _, field2: _, .. + } = ne; + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { field: _, .. } = ne; + //~^ rest_pattern_accessible_field + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { field: _, .. } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _ } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _, .. } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _ } = ne; + //~^ rest_pattern_accessible_field + + use m::Sm; + + let Sm { a: _, b: _, .. } = Sm::default(); + //~^ rest_pattern_accessible_field + + let Sm { a: _, b: _, .. } = Sm::default(); +} diff --git a/src/tools/clippy/tests/ui/rest_pattern_accessible_field.rs b/src/tools/clippy/tests/ui/rest_pattern_accessible_field.rs new file mode 100644 index 0000000000000..b08563b6b0861 --- /dev/null +++ b/src/tools/clippy/tests/ui/rest_pattern_accessible_field.rs @@ -0,0 +1,108 @@ +//@aux-build:proc_macros.rs +//@aux-build:non-exhaustive-struct.rs +#![warn(clippy::rest_pattern_accessible_field)] +#![deny(clippy::unneeded_wildcard_pattern)] + +use non_exhaustive_struct::{NonExhaustiveStruct, NonExhaustiveStructNoPrivateFields}; + +struct S { + a: u8, + b: u8, + c: u8, +} + +#[derive(Default)] +#[non_exhaustive] +struct LocalNonExhaustive { + field: i32, +} + +enum E { + A { a1: u8, a2: u8 }, + B { b1: u8, b2: u8 }, + C {}, +} + +mod m { + #[derive(Default)] + pub struct Sm { + pub a: u8, + pub(crate) b: u8, + c: u8, + } +} + +fn main() { + let s = S { a: 1, b: 2, c: 3 }; + + let S { a, b, .. } = s; + //~^ rest_pattern_accessible_field + + let S { c, .. } = s; + //~^ rest_pattern_accessible_field + + let S { a, b, c, .. } = s; + + S { a: _, b: _, .. } = S { a: 1, b: 2, c: 3 }; + //~^ rest_pattern_accessible_field + + let e = E::A { a1: 1, a2: 2 }; + + match e { + E::A { a1, a2 } => (), + E::B { .. } => (), + //~^ rest_pattern_accessible_field + E::C { .. } => (), + } + + match e { + E::A { a1: _, a2: _ } => (), + E::B { b1: _, .. } => (), + //~^ rest_pattern_accessible_field + E::C {} => (), + } + + proc_macros::external! { + let s1 = S { a: 1, b: 2, c: 3 }; + let S { a, b, .. } = s1; + } + + proc_macros::with_span! { + span + let s2 = S { a: 1, b: 2, c: 3 }; + let S { a, b, .. } = s2; + } + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { field1: _, .. } = ne; + //~^ rest_pattern_accessible_field + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { + field1: _, field2: _, .. + } = ne; + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { .. } = ne; + //~^ rest_pattern_accessible_field + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { field: _, .. } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _ } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _, .. } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { .. } = ne; + //~^ rest_pattern_accessible_field + + use m::Sm; + + let Sm { .. } = Sm::default(); + //~^ rest_pattern_accessible_field + + let Sm { a: _, b: _, .. } = Sm::default(); +} diff --git a/src/tools/clippy/tests/ui/rest_pattern_accessible_field.stderr b/src/tools/clippy/tests/ui/rest_pattern_accessible_field.stderr new file mode 100644 index 0000000000000..79b8a98ed253f --- /dev/null +++ b/src/tools/clippy/tests/ui/rest_pattern_accessible_field.stderr @@ -0,0 +1,109 @@ +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:38:9 + | +LL | let S { a, b, .. } = s; + | ^^^^^^^^^^^^^^ + | + = note: `-D clippy::rest-pattern-accessible-field` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::rest_pattern_accessible_field)]` +help: consider explicitly ignoring remaining fields with wildcard patterns (`x: _`) + | +LL - let S { a, b, .. } = s; +LL + let S { a, b, c: _ } = s; + | + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:41:9 + | +LL | let S { c, .. } = s; + | ^^^^^^^^^^^ + | +help: consider explicitly ignoring remaining fields with wildcard patterns (`x: _`) + | +LL - let S { c, .. } = s; +LL + let S { c, a: _, b: _ } = s; + | + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:46:5 + | +LL | S { a: _, b: _, .. } = S { a: 1, b: 2, c: 3 }; + | ^^^^^^^^^^^^^^^^^^^^ + | +help: consider explicitly ignoring remaining fields with wildcard patterns (`x: _`) + | +LL - S { a: _, b: _, .. } = S { a: 1, b: 2, c: 3 }; +LL + S { a: _, b: _, c: _ } = S { a: 1, b: 2, c: 3 }; + | + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:53:9 + | +LL | E::B { .. } => (), + | ^^^^^^^^^^^ + | +help: consider explicitly ignoring fields with wildcard patterns (`x: _`) + | +LL - E::B { .. } => (), +LL + E::B { b1: _, b2: _ } => (), + | + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:60:9 + | +LL | E::B { b1: _, .. } => (), + | ^^^^^^^^^^^^^^^^^^ + | +help: consider explicitly ignoring remaining fields with wildcard patterns (`x: _`) + | +LL - E::B { b1: _, .. } => (), +LL + E::B { b1: _, b2: _ } => (), + | + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:77:9 + | +LL | let NonExhaustiveStruct { field1: _, .. } = ne; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider explicitly ignoring remaining fields with wildcard patterns (`x: _`) + | +LL | let NonExhaustiveStruct { field1: _, field2: _, .. } = ne; + | ++++++++++ + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:86:9 + | +LL | let NonExhaustiveStructNoPrivateFields { .. } = ne; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider explicitly ignoring fields with wildcard patterns (`x: _`) + | +LL | let NonExhaustiveStructNoPrivateFields { field: _, .. } = ne; + | +++++++++ + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:99:9 + | +LL | let LocalNonExhaustive { .. } = ne; + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider explicitly ignoring fields with wildcard patterns (`x: _`) + | +LL - let LocalNonExhaustive { .. } = ne; +LL + let LocalNonExhaustive { field: _ } = ne; + | + +error: struct destructuring with rest (`..`) + --> tests/ui/rest_pattern_accessible_field.rs:104:9 + | +LL | let Sm { .. } = Sm::default(); + | ^^^^^^^^^ + | +help: consider explicitly ignoring fields with wildcard patterns (`x: _`) + | +LL | let Sm { a: _, b: _, .. } = Sm::default(); + | +++++++++++ + +error: aborting due to 9 previous errors + diff --git a/src/tools/clippy/tests/ui/single_char_pattern.fixed b/src/tools/clippy/tests/ui/single_char_pattern.fixed index 9bf9d66304411..2b1f403b1f2c9 100644 --- a/src/tools/clippy/tests/ui/single_char_pattern.fixed +++ b/src/tools/clippy/tests/ui/single_char_pattern.fixed @@ -1,4 +1,3 @@ -#![allow(clippy::needless_raw_strings, clippy::needless_raw_string_hashes, unused_must_use)] #![warn(clippy::single_char_pattern)] use std::collections::HashSet; diff --git a/src/tools/clippy/tests/ui/single_char_pattern.rs b/src/tools/clippy/tests/ui/single_char_pattern.rs index 0560a848fe9de..a933e73edc10e 100644 --- a/src/tools/clippy/tests/ui/single_char_pattern.rs +++ b/src/tools/clippy/tests/ui/single_char_pattern.rs @@ -1,4 +1,3 @@ -#![allow(clippy::needless_raw_strings, clippy::needless_raw_string_hashes, unused_must_use)] #![warn(clippy::single_char_pattern)] use std::collections::HashSet; diff --git a/src/tools/clippy/tests/ui/single_char_pattern.stderr b/src/tools/clippy/tests/ui/single_char_pattern.stderr index aa4ba28884a8c..bf8bac0b00be5 100644 --- a/src/tools/clippy/tests/ui/single_char_pattern.stderr +++ b/src/tools/clippy/tests/ui/single_char_pattern.stderr @@ -1,5 +1,5 @@ error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:7:13 + --> tests/ui/single_char_pattern.rs:6:13 | LL | x.split("x"); | ^^^ help: consider using a `char`: `'x'` @@ -8,205 +8,205 @@ LL | x.split("x"); = help: to override `-D warnings` add `#[allow(clippy::single_char_pattern)]` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:19:23 + --> tests/ui/single_char_pattern.rs:18:23 | LL | x.split_inclusive("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:21:16 + --> tests/ui/single_char_pattern.rs:20:16 | LL | x.contains("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:23:19 + --> tests/ui/single_char_pattern.rs:22:19 | LL | x.starts_with("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:25:17 + --> tests/ui/single_char_pattern.rs:24:17 | LL | x.ends_with("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:27:12 + --> tests/ui/single_char_pattern.rs:26:12 | LL | x.find("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:29:13 + --> tests/ui/single_char_pattern.rs:28:13 | LL | x.rfind("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:31:14 + --> tests/ui/single_char_pattern.rs:30:14 | LL | x.rsplit("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:33:24 + --> tests/ui/single_char_pattern.rs:32:24 | LL | x.split_terminator("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:35:25 + --> tests/ui/single_char_pattern.rs:34:25 | LL | x.rsplit_terminator("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:37:17 + --> tests/ui/single_char_pattern.rs:36:17 | LL | x.splitn(2, "x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:39:18 + --> tests/ui/single_char_pattern.rs:38:18 | LL | x.rsplitn(2, "x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:41:18 + --> tests/ui/single_char_pattern.rs:40:18 | LL | x.split_once("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:43:19 + --> tests/ui/single_char_pattern.rs:42:19 | LL | x.rsplit_once("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:45:15 + --> tests/ui/single_char_pattern.rs:44:15 | LL | x.matches("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:47:16 + --> tests/ui/single_char_pattern.rs:46:16 | LL | x.rmatches("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:49:21 + --> tests/ui/single_char_pattern.rs:48:21 | LL | x.match_indices("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:51:22 + --> tests/ui/single_char_pattern.rs:50:22 | LL | x.rmatch_indices("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:53:26 + --> tests/ui/single_char_pattern.rs:52:26 | LL | x.trim_start_matches("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:55:24 + --> tests/ui/single_char_pattern.rs:54:24 | LL | x.trim_end_matches("x"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:57:15 + --> tests/ui/single_char_pattern.rs:56:15 | LL | x.replace("x", "y"); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:59:16 + --> tests/ui/single_char_pattern.rs:58:16 | LL | x.replacen("x", "y", 3); | ^^^ help: consider using a `char`: `'x'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:62:13 + --> tests/ui/single_char_pattern.rs:61:13 | LL | x.split("\n"); | ^^^^ help: consider using a `char`: `'\n'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:64:13 + --> tests/ui/single_char_pattern.rs:63:13 | LL | x.split("'"); | ^^^ help: consider using a `char`: `'\''` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:66:13 + --> tests/ui/single_char_pattern.rs:65:13 | LL | x.split("\'"); | ^^^^ help: consider using a `char`: `'\''` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:69:13 + --> tests/ui/single_char_pattern.rs:68:13 | LL | x.split("\""); | ^^^^ help: consider using a `char`: `'"'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:75:31 + --> tests/ui/single_char_pattern.rs:74:31 | LL | x.replace(';', ",").split(","); // issue #2978 | ^^^ help: consider using a `char`: `','` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:78:19 + --> tests/ui/single_char_pattern.rs:77:19 | LL | x.starts_with("\x03"); // issue #2996 | ^^^^^^ help: consider using a `char`: `'\x03'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:87:13 + --> tests/ui/single_char_pattern.rs:86:13 | LL | x.split(r"a"); | ^^^^ help: consider using a `char`: `'a'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:89:13 + --> tests/ui/single_char_pattern.rs:88:13 | LL | x.split(r#"a"#); | ^^^^^^ help: consider using a `char`: `'a'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:91:13 + --> tests/ui/single_char_pattern.rs:90:13 | LL | x.split(r###"a"###); | ^^^^^^^^^^ help: consider using a `char`: `'a'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:93:13 + --> tests/ui/single_char_pattern.rs:92:13 | LL | x.split(r###"'"###); | ^^^^^^^^^^ help: consider using a `char`: `'\''` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:95:13 + --> tests/ui/single_char_pattern.rs:94:13 | LL | x.split(r###"#"###); | ^^^^^^^^^^ help: consider using a `char`: `'#'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:98:13 + --> tests/ui/single_char_pattern.rs:97:13 | LL | x.split(r#"\"#); | ^^^^^^ help: consider using a `char`: `'\\'` error: single-character string constant used as pattern - --> tests/ui/single_char_pattern.rs:100:13 + --> tests/ui/single_char_pattern.rs:99:13 | LL | x.split(r"\"); | ^^^^ help: consider using a `char`: `'\\'` diff --git a/src/tools/clippy/tests/ui/single_component_path_imports.fixed b/src/tools/clippy/tests/ui/single_component_path_imports.fixed index 180a55813b19f..02a3d575e5b91 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports.fixed +++ b/src/tools/clippy/tests/ui/single_component_path_imports.fixed @@ -1,5 +1,4 @@ #![warn(clippy::single_component_path_imports)] -#![allow(unused_imports)] use core; @@ -31,13 +30,11 @@ fn main() { mod hello_mod { //~^ single_component_path_imports - #[allow(dead_code)] fn hello_mod() {} } mod hi_mod { use self::regex::{Regex, RegexSet}; use regex; - #[allow(dead_code)] fn hi_mod() {} } diff --git a/src/tools/clippy/tests/ui/single_component_path_imports.rs b/src/tools/clippy/tests/ui/single_component_path_imports.rs index 888c533c534c7..efd425abc4bf4 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports.rs +++ b/src/tools/clippy/tests/ui/single_component_path_imports.rs @@ -1,5 +1,4 @@ #![warn(clippy::single_component_path_imports)] -#![allow(unused_imports)] use core; @@ -32,13 +31,11 @@ fn main() { mod hello_mod { use regex; //~^ single_component_path_imports - #[allow(dead_code)] fn hello_mod() {} } mod hi_mod { use self::regex::{Regex, RegexSet}; use regex; - #[allow(dead_code)] fn hi_mod() {} } diff --git a/src/tools/clippy/tests/ui/single_component_path_imports.stderr b/src/tools/clippy/tests/ui/single_component_path_imports.stderr index f1c56b14358ff..d0c950c966608 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports.stderr +++ b/src/tools/clippy/tests/ui/single_component_path_imports.stderr @@ -1,5 +1,5 @@ error: this import is redundant - --> tests/ui/single_component_path_imports.rs:6:1 + --> tests/ui/single_component_path_imports.rs:5:1 | LL | use regex; | ^^^^^^^^^^ help: remove it entirely @@ -8,7 +8,7 @@ LL | use regex; = help: to override `-D warnings` add `#[allow(clippy::single_component_path_imports)]` error: this import is redundant - --> tests/ui/single_component_path_imports.rs:33:5 + --> tests/ui/single_component_path_imports.rs:32:5 | LL | use regex; | ^^^^^^^^^^ help: remove it entirely diff --git a/src/tools/clippy/tests/ui/single_component_path_imports_macro.rs b/src/tools/clippy/tests/ui/single_component_path_imports_macro.rs index f655ea482d1cf..991fcfbe8a3d6 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports_macro.rs +++ b/src/tools/clippy/tests/ui/single_component_path_imports_macro.rs @@ -1,7 +1,6 @@ //@ check-pass #![warn(clippy::single_component_path_imports)] -#![allow(unused_imports)] // #7106: use statements exporting a macro within a crate should not trigger lint // #7923: normal `use` statements of macros should also not trigger the lint diff --git a/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.rs b/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.rs index 77213bc482c39..32043bacc240d 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.rs +++ b/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.rs @@ -1,5 +1,4 @@ #![warn(clippy::single_component_path_imports)] -#![allow(unused_imports)] //@no-rustfix use regex; //~^ single_component_path_imports @@ -18,6 +17,5 @@ mod root_nested_use_mod { //~^ single_component_path_imports //~| single_component_path_imports - #[allow(dead_code)] fn root_nested_use_mod() {} } diff --git a/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.stderr b/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.stderr index 8eec877860e7e..59663f5a1e716 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.stderr +++ b/src/tools/clippy/tests/ui/single_component_path_imports_nested_first.stderr @@ -1,5 +1,5 @@ error: this import is redundant - --> tests/ui/single_component_path_imports_nested_first.rs:4:1 + --> tests/ui/single_component_path_imports_nested_first.rs:3:1 | LL | use regex; | ^^^^^^^^^^ help: remove it entirely @@ -8,7 +8,7 @@ LL | use regex; = help: to override `-D warnings` add `#[allow(clippy::single_component_path_imports)]` error: this import is redundant - --> tests/ui/single_component_path_imports_nested_first.rs:17:10 + --> tests/ui/single_component_path_imports_nested_first.rs:16:10 | LL | use {regex, serde}; | ^^^^^ @@ -16,7 +16,7 @@ LL | use {regex, serde}; = help: remove this import error: this import is redundant - --> tests/ui/single_component_path_imports_nested_first.rs:17:17 + --> tests/ui/single_component_path_imports_nested_first.rs:16:17 | LL | use {regex, serde}; | ^^^^^ diff --git a/src/tools/clippy/tests/ui/single_component_path_imports_self_after.rs b/src/tools/clippy/tests/ui/single_component_path_imports_self_after.rs index a0f2cf6908091..f9e85555a2623 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports_self_after.rs +++ b/src/tools/clippy/tests/ui/single_component_path_imports_self_after.rs @@ -1,7 +1,6 @@ //@ check-pass #![warn(clippy::single_component_path_imports)] -#![allow(unused_imports)] use self::regex::{Regex as xeger, RegexSet as tesxeger}; #[rustfmt::skip] diff --git a/src/tools/clippy/tests/ui/single_component_path_imports_self_before.rs b/src/tools/clippy/tests/ui/single_component_path_imports_self_before.rs index b80580da10c39..753fc67cdb295 100644 --- a/src/tools/clippy/tests/ui/single_component_path_imports_self_before.rs +++ b/src/tools/clippy/tests/ui/single_component_path_imports_self_before.rs @@ -1,7 +1,6 @@ //@ check-pass #![warn(clippy::single_component_path_imports)] -#![allow(unused_imports)] use regex; diff --git a/src/tools/clippy/tests/ui/single_element_loop.fixed b/src/tools/clippy/tests/ui/single_element_loop.fixed index 76c3cf56c11ec..26fe8e1a3e373 100644 --- a/src/tools/clippy/tests/ui/single_element_loop.fixed +++ b/src/tools/clippy/tests/ui/single_element_loop.fixed @@ -73,4 +73,11 @@ fn main() { //~^ single_element_loop let ptr: *const bool = std::ptr::null(); } + + for _ in 3..5 { + //~^ single_element_loop + if true { + println!("aaa"); + } + } } diff --git a/src/tools/clippy/tests/ui/single_element_loop.rs b/src/tools/clippy/tests/ui/single_element_loop.rs index 2eb928397b0a6..e05e9fb189933 100644 --- a/src/tools/clippy/tests/ui/single_element_loop.rs +++ b/src/tools/clippy/tests/ui/single_element_loop.rs @@ -69,4 +69,11 @@ fn main() { //~^ single_element_loop let ptr: *const bool = std::ptr::null(); } + + for _ in [3..5] { + //~^ single_element_loop + if true { + println!("aaa"); + } + } } diff --git a/src/tools/clippy/tests/ui/single_element_loop.stderr b/src/tools/clippy/tests/ui/single_element_loop.stderr index 639f8d2d1b98f..1fdc388eb34e5 100644 --- a/src/tools/clippy/tests/ui/single_element_loop.stderr +++ b/src/tools/clippy/tests/ui/single_element_loop.stderr @@ -106,5 +106,11 @@ LL + let ptr: *const bool = std::ptr::null(); LL + } | -error: aborting due to 8 previous errors +error: this loops only once with `_` being `3..5` + --> tests/ui/single_element_loop.rs:73:14 + | +LL | for _ in [3..5] { + | ^^^^^^ help: did you mean to iterate over the range instead?: `3..5` + +error: aborting due to 9 previous errors diff --git a/src/tools/clippy/tests/ui/single_element_loop_nofix.rs b/src/tools/clippy/tests/ui/single_element_loop_nofix.rs new file mode 100644 index 0000000000000..76f19f372bc40 --- /dev/null +++ b/src/tools/clippy/tests/ui/single_element_loop_nofix.rs @@ -0,0 +1,12 @@ +//@no-rustfix +#![warn(clippy::single_element_loop)] +#![allow(clippy::single_range_in_vec_init)] + +fn f(print: bool) { + for _ in [..5] { + //~^ single_element_loop + if print { + println!("Hello from f"); + } + } +} diff --git a/src/tools/clippy/tests/ui/single_element_loop_nofix.stderr b/src/tools/clippy/tests/ui/single_element_loop_nofix.stderr new file mode 100644 index 0000000000000..b3d3988f4ce33 --- /dev/null +++ b/src/tools/clippy/tests/ui/single_element_loop_nofix.stderr @@ -0,0 +1,16 @@ +error: for loop over a single element + --> tests/ui/single_element_loop_nofix.rs:6:5 + | +LL | / for _ in [..5] { +LL | | +LL | | if print { +LL | | println!("Hello from f"); +LL | | } +LL | | } + | |_____^ + | + = note: `-D clippy::single-element-loop` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::single_element_loop)]` + +error: aborting due to 1 previous error + diff --git a/src/tools/clippy/tests/ui/single_match.fixed b/src/tools/clippy/tests/ui/single_match.fixed index fe28674ec18e5..653c88c0f860d 100644 --- a/src/tools/clippy/tests/ui/single_match.fixed +++ b/src/tools/clippy/tests/ui/single_match.fixed @@ -1,13 +1,6 @@ //@require-annotations-for-level: WARN #![warn(clippy::single_match)] -#![allow( - unused, - clippy::uninlined_format_args, - clippy::needless_ifs, - clippy::redundant_guards, - clippy::redundant_pattern_matching, - clippy::manual_unwrap_or_default -)] +#![allow(clippy::redundant_pattern_matching)] fn dummy() {} fn single_match() { diff --git a/src/tools/clippy/tests/ui/single_match.rs b/src/tools/clippy/tests/ui/single_match.rs index 0f558cb5f786c..2b627781b9d07 100644 --- a/src/tools/clippy/tests/ui/single_match.rs +++ b/src/tools/clippy/tests/ui/single_match.rs @@ -1,13 +1,6 @@ //@require-annotations-for-level: WARN #![warn(clippy::single_match)] -#![allow( - unused, - clippy::uninlined_format_args, - clippy::needless_ifs, - clippy::redundant_guards, - clippy::redundant_pattern_matching, - clippy::manual_unwrap_or_default -)] +#![allow(clippy::redundant_pattern_matching)] fn dummy() {} fn single_match() { diff --git a/src/tools/clippy/tests/ui/single_match.stderr b/src/tools/clippy/tests/ui/single_match.stderr index ba8bc5af5a608..2cd9777a1ba9a 100644 --- a/src/tools/clippy/tests/ui/single_match.stderr +++ b/src/tools/clippy/tests/ui/single_match.stderr @@ -1,5 +1,5 @@ error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:16:5 + --> tests/ui/single_match.rs:9:5 | LL | / match x { LL | | Some(y) => { @@ -19,7 +19,7 @@ LL ~ }; | error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:25:5 + --> tests/ui/single_match.rs:18:5 | LL | / match x { ... | @@ -30,7 +30,7 @@ LL | | } = note: you might want to preserve the comments from inside the `match` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:36:5 + --> tests/ui/single_match.rs:29:5 | LL | / match z { LL | | (2..=3, 7..=9) => dummy(), @@ -39,7 +39,7 @@ LL | | }; | |_____^ help: try: `if let (2..=3, 7..=9) = z { dummy() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:66:5 + --> tests/ui/single_match.rs:59:5 | LL | / match x { LL | | Some(y) => dummy(), @@ -48,7 +48,7 @@ LL | | }; | |_____^ help: try: `if let Some(y) = x { dummy() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:72:5 + --> tests/ui/single_match.rs:65:5 | LL | / match y { LL | | Ok(y) => dummy(), @@ -57,7 +57,7 @@ LL | | }; | |_____^ help: try: `if let Ok(y) = y { dummy() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:80:5 + --> tests/ui/single_match.rs:73:5 | LL | / match c { LL | | Cow::Borrowed(..) => dummy(), @@ -66,7 +66,7 @@ LL | | }; | |_____^ help: try: `if let Cow::Borrowed(..) = c { dummy() }` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match.rs:102:5 + --> tests/ui/single_match.rs:95:5 | LL | / match x { LL | | "test" => println!(), @@ -75,7 +75,7 @@ LL | | } | |_____^ help: try: `if x == "test" { println!() }` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match.rs:116:5 + --> tests/ui/single_match.rs:109:5 | LL | / match x { LL | | Foo::A => println!(), @@ -84,7 +84,7 @@ LL | | } | |_____^ help: try: `if x == Foo::A { println!() }` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match.rs:123:5 + --> tests/ui/single_match.rs:116:5 | LL | / match x { LL | | FOO_C => println!(), @@ -93,7 +93,7 @@ LL | | } | |_____^ help: try: `if x == FOO_C { println!() }` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match.rs:129:5 + --> tests/ui/single_match.rs:122:5 | LL | / match &&x { LL | | Foo::A => println!(), @@ -102,7 +102,7 @@ LL | | } | |_____^ help: try: `if x == Foo::A { println!() }` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match.rs:136:5 + --> tests/ui/single_match.rs:129:5 | LL | / match &x { LL | | Foo::A => println!(), @@ -111,7 +111,7 @@ LL | | } | |_____^ help: try: `if x == &Foo::A { println!() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:154:5 + --> tests/ui/single_match.rs:147:5 | LL | / match x { LL | | Bar::A => println!(), @@ -120,7 +120,7 @@ LL | | } | |_____^ help: try: `if let Bar::A = x { println!() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:163:5 + --> tests/ui/single_match.rs:156:5 | LL | / match x { LL | | None => println!(), @@ -129,7 +129,7 @@ LL | | }; | |_____^ help: try: `if let None = x { println!() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:186:5 + --> tests/ui/single_match.rs:179:5 | LL | / match x { LL | | (Some(_), _) => {}, @@ -138,7 +138,7 @@ LL | | } | |_____^ help: try: `if let (Some(_), _) = x {}` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:193:5 + --> tests/ui/single_match.rs:186:5 | LL | / match x { LL | | (Some(E::V), _) => todo!(), @@ -147,7 +147,7 @@ LL | | } | |_____^ help: try: `if let (Some(E::V), _) = x { todo!() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:200:5 + --> tests/ui/single_match.rs:193:5 | LL | / match (Some(42), Some(E::V), Some(42)) { LL | | (.., Some(E::V), _) => {}, @@ -156,7 +156,7 @@ LL | | } | |_____^ help: try: `if let (.., Some(E::V), _) = (Some(42), Some(E::V), Some(42)) {}` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:273:5 + --> tests/ui/single_match.rs:266:5 | LL | / match bar { LL | | Some(v) => unsafe { @@ -176,7 +176,7 @@ LL + } } | error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:282:5 + --> tests/ui/single_match.rs:275:5 | LL | / match bar { LL | | #[rustfmt::skip] @@ -198,7 +198,7 @@ LL + } | error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:363:5 + --> tests/ui/single_match.rs:356:5 | LL | / match Ok::<_, u32>(Some(A)) { LL | | Ok(Some(A)) => println!(), @@ -207,7 +207,7 @@ LL | | } | |_____^ help: try: `if let Ok(Some(A)) = Ok::<_, u32>(Some(A)) { println!() }` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:379:5 + --> tests/ui/single_match.rs:372:5 | LL | / match &Some(A) { LL | | Some(A | B) => println!(), @@ -216,7 +216,7 @@ LL | | } | |_____^ help: try: `if let Some(A | B) = &Some(A) { println!() }` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match.rs:387:5 + --> tests/ui/single_match.rs:380:5 | LL | / match &s[0..3] { LL | | b"foo" => println!(), @@ -225,7 +225,7 @@ LL | | } | |_____^ help: try: `if &s[0..3] == b"foo" { println!() }` error: this pattern is irrefutable, `match` is useless - --> tests/ui/single_match.rs:402:5 + --> tests/ui/single_match.rs:395:5 | LL | / match DATA { LL | | DATA => println!(), @@ -234,7 +234,7 @@ LL | | } | |_____^ help: try: `println!();` error: this pattern is irrefutable, `match` is useless - --> tests/ui/single_match.rs:408:5 + --> tests/ui/single_match.rs:401:5 | LL | / match CONST_I32 { LL | | CONST_I32 => println!(), @@ -243,7 +243,7 @@ LL | | } | |_____^ help: try: `println!();` error: this pattern is irrefutable, `match` is useless - --> tests/ui/single_match.rs:415:5 + --> tests/ui/single_match.rs:408:5 | LL | / match i { LL | | i => { @@ -263,7 +263,7 @@ LL + } | error: this pattern is irrefutable, `match` is useless - --> tests/ui/single_match.rs:424:5 + --> tests/ui/single_match.rs:417:5 | LL | / match i { LL | | i => {}, @@ -272,7 +272,7 @@ LL | | } | |_____^ help: `match` expression can be removed error: this pattern is irrefutable, `match` is useless - --> tests/ui/single_match.rs:430:5 + --> tests/ui/single_match.rs:423:5 | LL | / match i { LL | | i => (), @@ -281,7 +281,7 @@ LL | | } | |_____^ help: `match` expression can be removed error: this pattern is irrefutable, `match` is useless - --> tests/ui/single_match.rs:436:5 + --> tests/ui/single_match.rs:429:5 | LL | / match CONST_I32 { LL | | CONST_I32 => println!(), @@ -290,7 +290,7 @@ LL | | } | |_____^ help: try: `println!();` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:444:5 + --> tests/ui/single_match.rs:437:5 | LL | / match x.pop() { LL | | // bla @@ -302,7 +302,7 @@ LL | | } = note: you might want to preserve the comments from inside the `match` error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:453:5 + --> tests/ui/single_match.rs:446:5 | LL | / match x.pop() { LL | | // bla @@ -322,7 +322,7 @@ LL + } | error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` - --> tests/ui/single_match.rs:479:5 + --> tests/ui/single_match.rs:472:5 | LL | / match mac!(some) { LL | | Some(u) => println!("{u}"), @@ -331,7 +331,7 @@ LL | | } | |_____^ help: try: `if let Some(u) = mac!(some) { println!("{u}") }` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match.rs:487:5 + --> tests/ui/single_match.rs:480:5 | LL | / match mac!(str) { LL | | "foo" => println!("eq"), diff --git a/src/tools/clippy/tests/ui/single_match_else.fixed b/src/tools/clippy/tests/ui/single_match_else.fixed index fde13fb90dbb2..db14fdc097d35 100644 --- a/src/tools/clippy/tests/ui/single_match_else.fixed +++ b/src/tools/clippy/tests/ui/single_match_else.fixed @@ -2,7 +2,7 @@ //@require-annotations-for-level: WARN #![warn(clippy::single_match_else)] -#![allow(unused, clippy::needless_return, clippy::no_effect, clippy::uninlined_format_args)] +#![expect(clippy::needless_return)] extern crate proc_macros; use proc_macros::with_span; diff --git a/src/tools/clippy/tests/ui/single_match_else.rs b/src/tools/clippy/tests/ui/single_match_else.rs index ca282200067ce..45225e260ae7f 100644 --- a/src/tools/clippy/tests/ui/single_match_else.rs +++ b/src/tools/clippy/tests/ui/single_match_else.rs @@ -2,7 +2,7 @@ //@require-annotations-for-level: WARN #![warn(clippy::single_match_else)] -#![allow(unused, clippy::needless_return, clippy::no_effect, clippy::uninlined_format_args)] +#![expect(clippy::needless_return)] extern crate proc_macros; use proc_macros::with_span; diff --git a/src/tools/clippy/tests/ui/single_match_else_deref_patterns.fixed b/src/tools/clippy/tests/ui/single_match_else_deref_patterns.fixed index 1743ae6bf5a7d..381a9efd7c1c3 100644 --- a/src/tools/clippy/tests/ui/single_match_else_deref_patterns.fixed +++ b/src/tools/clippy/tests/ui/single_match_else_deref_patterns.fixed @@ -1,13 +1,7 @@ #![feature(deref_patterns)] -#![allow( - incomplete_features, - clippy::eq_op, - clippy::op_ref, - clippy::deref_addrof, - clippy::borrow_deref_ref, - clippy::needless_ifs -)] -#![deny(clippy::single_match_else)] +#![warn(clippy::single_match_else)] +#![allow(clippy::eq_op, clippy::needless_ifs, clippy::op_ref)] +#![expect(clippy::borrow_deref_ref, clippy::deref_addrof)] fn string() { if *"" == *"" {} diff --git a/src/tools/clippy/tests/ui/single_match_else_deref_patterns.rs b/src/tools/clippy/tests/ui/single_match_else_deref_patterns.rs index d5cb8a24a609c..dbed5d38a6a34 100644 --- a/src/tools/clippy/tests/ui/single_match_else_deref_patterns.rs +++ b/src/tools/clippy/tests/ui/single_match_else_deref_patterns.rs @@ -1,13 +1,7 @@ #![feature(deref_patterns)] -#![allow( - incomplete_features, - clippy::eq_op, - clippy::op_ref, - clippy::deref_addrof, - clippy::borrow_deref_ref, - clippy::needless_ifs -)] -#![deny(clippy::single_match_else)] +#![warn(clippy::single_match_else)] +#![allow(clippy::eq_op, clippy::needless_ifs, clippy::op_ref)] +#![expect(clippy::borrow_deref_ref, clippy::deref_addrof)] fn string() { match *"" { diff --git a/src/tools/clippy/tests/ui/single_match_else_deref_patterns.stderr b/src/tools/clippy/tests/ui/single_match_else_deref_patterns.stderr index a47df55459be1..b55f57681f57f 100644 --- a/src/tools/clippy/tests/ui/single_match_else_deref_patterns.stderr +++ b/src/tools/clippy/tests/ui/single_match_else_deref_patterns.stderr @@ -1,5 +1,5 @@ error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:13:5 + --> tests/ui/single_match_else_deref_patterns.rs:7:5 | LL | / match *"" { LL | | @@ -13,7 +13,7 @@ LL | | } = help: to override `-D warnings` add `#[allow(clippy::single_match)]` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:19:5 + --> tests/ui/single_match_else_deref_patterns.rs:13:5 | LL | / match *&*&*&*"" { LL | | @@ -25,7 +25,7 @@ LL | | } = note: you might want to preserve the comments from inside the `match` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:25:5 + --> tests/ui/single_match_else_deref_patterns.rs:19:5 | LL | / match ***&&"" { LL | | @@ -37,7 +37,7 @@ LL | | } = note: you might want to preserve the comments from inside the `match` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:31:5 + --> tests/ui/single_match_else_deref_patterns.rs:25:5 | LL | / match *&*&*"" { LL | | @@ -49,7 +49,7 @@ LL | | } = note: you might want to preserve the comments from inside the `match` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:37:5 + --> tests/ui/single_match_else_deref_patterns.rs:31:5 | LL | / match **&&*"" { LL | | @@ -61,7 +61,7 @@ LL | | } = note: you might want to preserve the comments from inside the `match` error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:45:5 + --> tests/ui/single_match_else_deref_patterns.rs:39:5 | LL | / match &&&1 { LL | | &&&2 => unreachable!(), @@ -70,11 +70,8 @@ LL | | _ => { LL | | } | |_____^ | -note: the lint level is defined here - --> tests/ui/single_match_else_deref_patterns.rs:10:9 - | -LL | #![deny(clippy::single_match_else)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::single-match-else` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::single_match_else)]` help: try | LL ~ if &&&1 == &&&2 { unreachable!() } else { @@ -83,7 +80,7 @@ LL + } | error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:52:5 + --> tests/ui/single_match_else_deref_patterns.rs:46:5 | LL | / match &&&1 { LL | | &&2 => unreachable!(), @@ -100,7 +97,7 @@ LL + } | error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:59:5 + --> tests/ui/single_match_else_deref_patterns.rs:53:5 | LL | / match &&1 { LL | | &&2 => unreachable!(), @@ -117,7 +114,7 @@ LL + } | error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:66:5 + --> tests/ui/single_match_else_deref_patterns.rs:60:5 | LL | / match &&&1 { LL | | &2 => unreachable!(), @@ -134,7 +131,7 @@ LL + } | error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:73:5 + --> tests/ui/single_match_else_deref_patterns.rs:67:5 | LL | / match &&1 { LL | | &2 => unreachable!(), @@ -151,7 +148,7 @@ LL + } | error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:80:5 + --> tests/ui/single_match_else_deref_patterns.rs:74:5 | LL | / match &&&1 { LL | | 2 => unreachable!(), @@ -168,7 +165,7 @@ LL + } | error: you seem to be trying to use `match` for an equality check. Consider using `if` - --> tests/ui/single_match_else_deref_patterns.rs:87:5 + --> tests/ui/single_match_else_deref_patterns.rs:81:5 | LL | / match &&1 { LL | | 2 => unreachable!(), diff --git a/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.1.fixed b/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.1.fixed index 02a91e654a5cb..c154b6d416efd 100644 --- a/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.1.fixed +++ b/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.1.fixed @@ -5,8 +5,8 @@ // When feature(new_range) stabilizes, this should be converted to testing // old and new editions instead. #![cfg_attr(new_range, feature(new_range))] -#![allow(clippy::no_effect, clippy::unnecessary_operation, clippy::useless_vec, unused)] #![warn(clippy::single_range_in_vec_init)] +#![expect(clippy::no_effect, clippy::useless_vec)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.2.fixed b/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.2.fixed index afd183ab87ac3..bc9cc4eb4dfe5 100644 --- a/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.2.fixed +++ b/src/tools/clippy/tests/ui/single_range_in_vec_init.new_range.2.fixed @@ -5,8 +5,8 @@ // When feature(new_range) stabilizes, this should be converted to testing // old and new editions instead. #![cfg_attr(new_range, feature(new_range))] -#![allow(clippy::no_effect, clippy::unnecessary_operation, clippy::useless_vec, unused)] #![warn(clippy::single_range_in_vec_init)] +#![expect(clippy::no_effect, clippy::useless_vec)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.1.fixed b/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.1.fixed index 2e082cb7d7a90..60f113736202a 100644 --- a/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.1.fixed +++ b/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.1.fixed @@ -5,8 +5,8 @@ // When feature(new_range) stabilizes, this should be converted to testing // old and new editions instead. #![cfg_attr(new_range, feature(new_range))] -#![allow(clippy::no_effect, clippy::unnecessary_operation, clippy::useless_vec, unused)] #![warn(clippy::single_range_in_vec_init)] +#![expect(clippy::no_effect, clippy::useless_vec)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.2.fixed b/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.2.fixed index ab297ccfa819f..d338dd87bc779 100644 --- a/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.2.fixed +++ b/src/tools/clippy/tests/ui/single_range_in_vec_init.old_range.2.fixed @@ -5,8 +5,8 @@ // When feature(new_range) stabilizes, this should be converted to testing // old and new editions instead. #![cfg_attr(new_range, feature(new_range))] -#![allow(clippy::no_effect, clippy::unnecessary_operation, clippy::useless_vec, unused)] #![warn(clippy::single_range_in_vec_init)] +#![expect(clippy::no_effect, clippy::useless_vec)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/single_range_in_vec_init.rs b/src/tools/clippy/tests/ui/single_range_in_vec_init.rs index 8fdeac1fc9a0d..2bd15af26a93e 100644 --- a/src/tools/clippy/tests/ui/single_range_in_vec_init.rs +++ b/src/tools/clippy/tests/ui/single_range_in_vec_init.rs @@ -5,8 +5,8 @@ // When feature(new_range) stabilizes, this should be converted to testing // old and new editions instead. #![cfg_attr(new_range, feature(new_range))] -#![allow(clippy::no_effect, clippy::unnecessary_operation, clippy::useless_vec, unused)] #![warn(clippy::single_range_in_vec_init)] +#![expect(clippy::no_effect, clippy::useless_vec)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.rs b/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.rs index 3fe4d923441dd..9d4fa69ed90be 100644 --- a/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.rs +++ b/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.rs @@ -1,5 +1,4 @@ #![warn(clippy::size_of_in_element_count)] -#![allow(clippy::ptr_offset_with_cast)] use std::mem::{size_of, size_of_val}; use std::ptr::{copy, copy_nonoverlapping, write_bytes}; diff --git a/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.stderr b/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.stderr index 74be0d7773dff..c85c818679f2e 100644 --- a/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.stderr +++ b/src/tools/clippy/tests/ui/size_of_in_element_count/expressions.stderr @@ -1,5 +1,5 @@ error: found a count of bytes instead of a count of elements of `T` - --> tests/ui/size_of_in_element_count/expressions.rs:15:62 + --> tests/ui/size_of_in_element_count/expressions.rs:14:62 | LL | unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::() * SIZE) }; | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -9,7 +9,7 @@ LL | unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of:: = help: to override `-D warnings` add `#[allow(clippy::size_of_in_element_count)]` error: found a count of bytes instead of a count of elements of `T` - --> tests/ui/size_of_in_element_count/expressions.rs:19:62 + --> tests/ui/size_of_in_element_count/expressions.rs:18:62 | LL | unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), HALF_SIZE * size_of_val(&x[0]) * 2) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -17,7 +17,7 @@ LL | unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), HALF_SIZE * si = help: use a count of elements instead of a count of bytes, it already gets multiplied by the size of the type error: found a count of bytes instead of a count of elements of `T` - --> tests/ui/size_of_in_element_count/expressions.rs:23:47 + --> tests/ui/size_of_in_element_count/expressions.rs:22:47 | LL | unsafe { copy(x.as_ptr(), y.as_mut_ptr(), DOUBLE_SIZE * size_of::() / 2) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL | unsafe { copy(x.as_ptr(), y.as_mut_ptr(), DOUBLE_SIZE * size_of::( = help: use a count of elements instead of a count of bytes, it already gets multiplied by the size of the type error: found a count of bytes instead of a count of elements of `T` - --> tests/ui/size_of_in_element_count/expressions.rs:33:47 + --> tests/ui/size_of_in_element_count/expressions.rs:32:47 | LL | unsafe { copy(x.as_ptr(), y.as_mut_ptr(), DOUBLE_SIZE / (2 / size_of::())) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/size_of_in_element_count/functions.rs b/src/tools/clippy/tests/ui/size_of_in_element_count/functions.rs index afd12edec1edb..a8be9af099f3a 100644 --- a/src/tools/clippy/tests/ui/size_of_in_element_count/functions.rs +++ b/src/tools/clippy/tests/ui/size_of_in_element_count/functions.rs @@ -1,5 +1,5 @@ #![warn(clippy::size_of_in_element_count)] -#![allow(clippy::ptr_offset_with_cast)] +#![expect(clippy::ptr_offset_with_cast)] use std::mem::{size_of, size_of_val}; use std::ptr::{ diff --git a/src/tools/clippy/tests/ui/size_of_ref.rs b/src/tools/clippy/tests/ui/size_of_ref.rs index 9a6a9419f681e..068f3bd514397 100644 --- a/src/tools/clippy/tests/ui/size_of_ref.rs +++ b/src/tools/clippy/tests/ui/size_of_ref.rs @@ -1,4 +1,3 @@ -#![allow(unused)] #![warn(clippy::size_of_ref)] use std::mem::size_of_val; diff --git a/src/tools/clippy/tests/ui/size_of_ref.stderr b/src/tools/clippy/tests/ui/size_of_ref.stderr index 46af9f55deaf6..79b0ec837e2f9 100644 --- a/src/tools/clippy/tests/ui/size_of_ref.stderr +++ b/src/tools/clippy/tests/ui/size_of_ref.stderr @@ -1,5 +1,5 @@ error: argument to `size_of_val()` is a reference to a reference - --> tests/ui/size_of_ref.rs:13:5 + --> tests/ui/size_of_ref.rs:12:5 | LL | size_of_val(&&x); | ^^^^^^^^^^^^^^^^ @@ -9,7 +9,7 @@ LL | size_of_val(&&x); = help: to override `-D warnings` add `#[allow(clippy::size_of_ref)]` error: argument to `size_of_val()` is a reference to a reference - --> tests/ui/size_of_ref.rs:16:5 + --> tests/ui/size_of_ref.rs:15:5 | LL | size_of_val(&y); | ^^^^^^^^^^^^^^^ @@ -17,7 +17,7 @@ LL | size_of_val(&y); = help: dereference the argument to `size_of_val()` to get the size of the value instead of the size of the reference-type error: argument to `size_of_val()` is a reference to a reference - --> tests/ui/size_of_ref.rs:28:9 + --> tests/ui/size_of_ref.rs:27:9 | LL | std::mem::size_of_val(&self) + (std::mem::size_of::() * self.data.capacity()) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/skip_while_next.rs b/src/tools/clippy/tests/ui/skip_while_next.rs index 6dbb6a2ebb9af..7a176edaef10c 100644 --- a/src/tools/clippy/tests/ui/skip_while_next.rs +++ b/src/tools/clippy/tests/ui/skip_while_next.rs @@ -1,7 +1,7 @@ //@aux-build:option_helpers.rs #![warn(clippy::skip_while_next)] -#![allow(clippy::disallowed_names, clippy::useless_vec)] +#![expect(clippy::disallowed_names, clippy::useless_vec)] extern crate option_helpers; use option_helpers::IteratorFalsePositives; diff --git a/src/tools/clippy/tests/ui/sliced_string_as_bytes.fixed b/src/tools/clippy/tests/ui/sliced_string_as_bytes.fixed index b5576188b83f6..69347ea299cbf 100644 --- a/src/tools/clippy/tests/ui/sliced_string_as_bytes.fixed +++ b/src/tools/clippy/tests/ui/sliced_string_as_bytes.fixed @@ -1,4 +1,3 @@ -#![allow(unused)] #![warn(clippy::sliced_string_as_bytes)] use std::ops::{Index, Range}; diff --git a/src/tools/clippy/tests/ui/sliced_string_as_bytes.rs b/src/tools/clippy/tests/ui/sliced_string_as_bytes.rs index 58b8d92902942..15e5fd575c71c 100644 --- a/src/tools/clippy/tests/ui/sliced_string_as_bytes.rs +++ b/src/tools/clippy/tests/ui/sliced_string_as_bytes.rs @@ -1,4 +1,3 @@ -#![allow(unused)] #![warn(clippy::sliced_string_as_bytes)] use std::ops::{Index, Range}; diff --git a/src/tools/clippy/tests/ui/sliced_string_as_bytes.stderr b/src/tools/clippy/tests/ui/sliced_string_as_bytes.stderr index ae7f02781f4bb..3e4989ceae834 100644 --- a/src/tools/clippy/tests/ui/sliced_string_as_bytes.stderr +++ b/src/tools/clippy/tests/ui/sliced_string_as_bytes.stderr @@ -1,5 +1,5 @@ error: calling `as_bytes` after slicing a string - --> tests/ui/sliced_string_as_bytes.rs:28:17 + --> tests/ui/sliced_string_as_bytes.rs:27:17 | LL | let bytes = s[1..5].as_bytes(); | ^^^^^^^^^^^^^^^^^^ help: try: `&s.as_bytes()[1..5]` @@ -8,13 +8,13 @@ LL | let bytes = s[1..5].as_bytes(); = help: to override `-D warnings` add `#[allow(clippy::sliced_string_as_bytes)]` error: calling `as_bytes` after slicing a string - --> tests/ui/sliced_string_as_bytes.rs:30:17 + --> tests/ui/sliced_string_as_bytes.rs:29:17 | LL | let bytes = string[1..].as_bytes(); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&string.as_bytes()[1..]` error: calling `as_bytes` after slicing a string - --> tests/ui/sliced_string_as_bytes.rs:32:17 + --> tests/ui/sliced_string_as_bytes.rs:31:17 | LL | let bytes = "consectetur adipiscing"[..=5].as_bytes(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&"consectetur adipiscing".as_bytes()[..=5]` diff --git a/src/tools/clippy/tests/ui/slow_vector_initialization.fixed b/src/tools/clippy/tests/ui/slow_vector_initialization.fixed index a13be693e4ec2..8ef967882b651 100644 --- a/src/tools/clippy/tests/ui/slow_vector_initialization.fixed +++ b/src/tools/clippy/tests/ui/slow_vector_initialization.fixed @@ -1,4 +1,6 @@ -#![allow(clippy::useless_vec, clippy::manual_repeat_n)] +#![warn(clippy::slow_vector_initialization)] +#![allow(clippy::useless_vec)] +#![expect(clippy::manual_repeat_n)] use std::iter::repeat; diff --git a/src/tools/clippy/tests/ui/slow_vector_initialization.rs b/src/tools/clippy/tests/ui/slow_vector_initialization.rs index eda96d0a0f82a..637bbe09d6846 100644 --- a/src/tools/clippy/tests/ui/slow_vector_initialization.rs +++ b/src/tools/clippy/tests/ui/slow_vector_initialization.rs @@ -1,4 +1,6 @@ -#![allow(clippy::useless_vec, clippy::manual_repeat_n)] +#![warn(clippy::slow_vector_initialization)] +#![allow(clippy::useless_vec)] +#![expect(clippy::manual_repeat_n)] use std::iter::repeat; diff --git a/src/tools/clippy/tests/ui/slow_vector_initialization.stderr b/src/tools/clippy/tests/ui/slow_vector_initialization.stderr index 320f2cacf61b3..2876c6e1e534c 100644 --- a/src/tools/clippy/tests/ui/slow_vector_initialization.stderr +++ b/src/tools/clippy/tests/ui/slow_vector_initialization.stderr @@ -1,5 +1,5 @@ error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:10:20 + --> tests/ui/slow_vector_initialization.rs:12:20 | LL | let mut vec1 = Vec::with_capacity(len); | ____________________^ @@ -11,7 +11,7 @@ LL | | vec1.extend(repeat(0).take(len)); = help: to override `-D warnings` add `#[allow(clippy::slow_vector_initialization)]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:16:20 + --> tests/ui/slow_vector_initialization.rs:18:20 | LL | let mut vec2 = Vec::with_capacity(len - 10); | ____________________^ @@ -20,7 +20,7 @@ LL | | vec2.extend(repeat(0).take(len - 10)); | |_________________________________________^ help: consider replacing this with: `vec![0; len - 10]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:25:20 + --> tests/ui/slow_vector_initialization.rs:27:20 | LL | let mut vec4 = Vec::with_capacity(len); | ____________________^ @@ -29,7 +29,7 @@ LL | | vec4.extend(repeat(0).take(vec4.capacity())); | |________________________________________________^ help: consider replacing this with: `vec![0; len]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:37:27 + --> tests/ui/slow_vector_initialization.rs:39:27 | LL | let mut resized_vec = Vec::with_capacity(30); | ___________________________^ @@ -38,7 +38,7 @@ LL | | resized_vec.resize(30, 0); | |_____________________________^ help: consider replacing this with: `vec![0; 30]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:42:26 + --> tests/ui/slow_vector_initialization.rs:44:26 | LL | let mut extend_vec = Vec::with_capacity(30); | __________________________^ @@ -47,7 +47,7 @@ LL | | extend_vec.extend(repeat(0).take(30)); | |_________________________________________^ help: consider replacing this with: `vec![0; 30]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:51:20 + --> tests/ui/slow_vector_initialization.rs:53:20 | LL | let mut vec1 = Vec::with_capacity(len); | ____________________^ @@ -56,7 +56,7 @@ LL | | vec1.resize(len, 0); | |_______________________^ help: consider replacing this with: `vec![0; len]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:61:20 + --> tests/ui/slow_vector_initialization.rs:63:20 | LL | let mut vec3 = Vec::with_capacity(len - 10); | ____________________^ @@ -65,7 +65,7 @@ LL | | vec3.resize(len - 10, 0); | |____________________________^ help: consider replacing this with: `vec![0; len - 10]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:66:20 + --> tests/ui/slow_vector_initialization.rs:68:20 | LL | let mut vec4 = Vec::with_capacity(len); | ____________________^ @@ -74,7 +74,7 @@ LL | | vec4.resize(vec4.capacity(), 0); | |___________________________________^ help: consider replacing this with: `vec![0; len]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:72:12 + --> tests/ui/slow_vector_initialization.rs:74:12 | LL | vec1 = Vec::with_capacity(10); | ____________^ @@ -83,7 +83,7 @@ LL | | vec1.resize(10, 0); | |______________________^ help: consider replacing this with: `vec![0; 10]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:81:20 + --> tests/ui/slow_vector_initialization.rs:83:20 | LL | let mut vec1 = Vec::new(); | ____________________^ @@ -92,7 +92,7 @@ LL | | vec1.resize(len, 0); | |_______________________^ help: consider replacing this with: `vec![0; len]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:87:20 + --> tests/ui/slow_vector_initialization.rs:89:20 | LL | let mut vec3 = Vec::new(); | ____________________^ @@ -101,7 +101,7 @@ LL | | vec3.resize(len - 10, 0); | |____________________________^ help: consider replacing this with: `vec![0; len - 10]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:93:12 + --> tests/ui/slow_vector_initialization.rs:95:12 | LL | vec1 = Vec::new(); | ____________^ @@ -110,7 +110,7 @@ LL | | vec1.resize(10, 0); | |______________________^ help: consider replacing this with: `vec![0; 10]` error: slow zero-filling initialization - --> tests/ui/slow_vector_initialization.rs:98:12 + --> tests/ui/slow_vector_initialization.rs:100:12 | LL | vec1 = vec![]; | ____________^ diff --git a/src/tools/clippy/tests/ui/some_filter.fixed b/src/tools/clippy/tests/ui/some_filter.fixed index a214dec920d4e..938dc8514e2e9 100644 --- a/src/tools/clippy/tests/ui/some_filter.fixed +++ b/src/tools/clippy/tests/ui/some_filter.fixed @@ -1,5 +1,5 @@ #![warn(clippy::some_filter)] -#![allow(clippy::const_is_empty)] +#![expect(clippy::const_is_empty)] macro_rules! unchanged { ($result:expr) => { diff --git a/src/tools/clippy/tests/ui/some_filter.rs b/src/tools/clippy/tests/ui/some_filter.rs index eec797536a8f7..a121417356662 100644 --- a/src/tools/clippy/tests/ui/some_filter.rs +++ b/src/tools/clippy/tests/ui/some_filter.rs @@ -1,5 +1,5 @@ #![warn(clippy::some_filter)] -#![allow(clippy::const_is_empty)] +#![expect(clippy::const_is_empty)] macro_rules! unchanged { ($result:expr) => { diff --git a/src/tools/clippy/tests/ui/stable_sort_primitive.fixed b/src/tools/clippy/tests/ui/stable_sort_primitive.fixed index b4870ebad2b36..a29bc8e7c360c 100644 --- a/src/tools/clippy/tests/ui/stable_sort_primitive.fixed +++ b/src/tools/clippy/tests/ui/stable_sort_primitive.fixed @@ -1,5 +1,5 @@ #![warn(clippy::stable_sort_primitive)] -#![allow(clippy::useless_vec)] +#![expect(clippy::useless_vec)] fn main() { // positive examples diff --git a/src/tools/clippy/tests/ui/stable_sort_primitive.rs b/src/tools/clippy/tests/ui/stable_sort_primitive.rs index b3fe64efd6201..848898c56e0b8 100644 --- a/src/tools/clippy/tests/ui/stable_sort_primitive.rs +++ b/src/tools/clippy/tests/ui/stable_sort_primitive.rs @@ -1,5 +1,5 @@ #![warn(clippy::stable_sort_primitive)] -#![allow(clippy::useless_vec)] +#![expect(clippy::useless_vec)] fn main() { // positive examples diff --git a/src/tools/clippy/tests/ui/starts_ends_with.fixed b/src/tools/clippy/tests/ui/starts_ends_with.fixed index f2fab9217604b..88f422ed21229 100644 --- a/src/tools/clippy/tests/ui/starts_ends_with.fixed +++ b/src/tools/clippy/tests/ui/starts_ends_with.fixed @@ -1,4 +1,4 @@ -#![allow(clippy::needless_ifs, dead_code, unused_must_use, clippy::double_ended_iterator_last)] +#![warn(clippy::chars_last_cmp, clippy::chars_next_cmp)] fn main() {} diff --git a/src/tools/clippy/tests/ui/starts_ends_with.rs b/src/tools/clippy/tests/ui/starts_ends_with.rs index 1460d77a094dd..db4789244783b 100644 --- a/src/tools/clippy/tests/ui/starts_ends_with.rs +++ b/src/tools/clippy/tests/ui/starts_ends_with.rs @@ -1,4 +1,4 @@ -#![allow(clippy::needless_ifs, dead_code, unused_must_use, clippy::double_ended_iterator_last)] +#![warn(clippy::chars_last_cmp, clippy::chars_next_cmp)] fn main() {} diff --git a/src/tools/clippy/tests/ui/std_instead_of_core.fixed b/src/tools/clippy/tests/ui/std_instead_of_core.fixed index 3020ed5c6f39d..63d0e204d72fd 100644 --- a/src/tools/clippy/tests/ui/std_instead_of_core.fixed +++ b/src/tools/clippy/tests/ui/std_instead_of_core.fixed @@ -1,7 +1,7 @@ //@aux-build:proc_macro_derive.rs #![warn(clippy::std_instead_of_core)] -#![allow(unused_imports, deprecated)] +#![expect(deprecated)] extern crate alloc; @@ -69,7 +69,6 @@ fn alloc_instead_of_core() { mod std_in_proc_macro_derive { #[warn(clippy::alloc_instead_of_core)] - #[allow(unused)] #[derive(ImplStructWithStdDisplay)] struct B {} } diff --git a/src/tools/clippy/tests/ui/std_instead_of_core.rs b/src/tools/clippy/tests/ui/std_instead_of_core.rs index 49b4218aa8983..e5cde188bedd7 100644 --- a/src/tools/clippy/tests/ui/std_instead_of_core.rs +++ b/src/tools/clippy/tests/ui/std_instead_of_core.rs @@ -1,7 +1,7 @@ //@aux-build:proc_macro_derive.rs #![warn(clippy::std_instead_of_core)] -#![allow(unused_imports, deprecated)] +#![expect(deprecated)] extern crate alloc; @@ -69,7 +69,6 @@ fn alloc_instead_of_core() { mod std_in_proc_macro_derive { #[warn(clippy::alloc_instead_of_core)] - #[allow(unused)] #[derive(ImplStructWithStdDisplay)] struct B {} } diff --git a/src/tools/clippy/tests/ui/std_instead_of_core.stderr b/src/tools/clippy/tests/ui/std_instead_of_core.stderr index 0363852cf8d49..7045d44482114 100644 --- a/src/tools/clippy/tests/ui/std_instead_of_core.stderr +++ b/src/tools/clippy/tests/ui/std_instead_of_core.stderr @@ -86,25 +86,25 @@ LL | use alloc::slice::from_ref; = help: to override `-D warnings` add `#[allow(clippy::alloc_instead_of_core)]` error: used import from `std` instead of `core` - --> tests/ui/std_instead_of_core.rs:81:9 + --> tests/ui/std_instead_of_core.rs:80:9 | LL | std::intrinsics::copy(a, b, 1); | ^^^ help: consider importing the item from `core`: `core` error: used import from `std` instead of `core` - --> tests/ui/std_instead_of_core.rs:90:17 + --> tests/ui/std_instead_of_core.rs:89:17 | LL | fn msrv_1_77(_: std::net::IpAddr) {} | ^^^ help: consider importing the item from `core`: `core` error: used import from `std` instead of `core` - --> tests/ui/std_instead_of_core.rs:110:33 + --> tests/ui/std_instead_of_core.rs:109:33 | LL | fn issue13158_msrv_1_41(_: &dyn std::panic::UnwindSafe) {} | ^^^ help: consider importing the item from `core`: `core` error: used import from `std` instead of `core` - --> tests/ui/std_instead_of_core.rs:117:33 + --> tests/ui/std_instead_of_core.rs:116:33 | LL | fn issue13158_msrv_1_81(_: &dyn std::error::Error) {} | ^^^ help: consider importing the item from `core`: `core` diff --git a/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.rs b/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.rs index 66d834b5e4279..459db5e8944ae 100644 --- a/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.rs +++ b/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.rs @@ -1,6 +1,4 @@ -#![warn(clippy::std_instead_of_core)] -#![warn(clippy::std_instead_of_alloc)] -#![allow(unused_imports)] +#![warn(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] #[rustfmt::skip] fn issue14982() { diff --git a/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.stderr b/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.stderr index 6fa8f47a4d6f4..c79b3e48cad37 100644 --- a/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.stderr +++ b/src/tools/clippy/tests/ui/std_instead_of_core_unfixable.stderr @@ -1,5 +1,5 @@ error: used import from `std` instead of `core` - --> tests/ui/std_instead_of_core_unfixable.rs:7:43 + --> tests/ui/std_instead_of_core_unfixable.rs:5:43 | LL | use std::{collections::HashMap, hash::Hash}; | ^^^^ @@ -9,7 +9,7 @@ LL | use std::{collections::HashMap, hash::Hash}; = help: to override `-D warnings` add `#[allow(clippy::std_instead_of_core)]` error: used import from `std` instead of `core` - --> tests/ui/std_instead_of_core_unfixable.rs:13:22 + --> tests/ui/std_instead_of_core_unfixable.rs:11:22 | LL | use std::{error::Error, vec::Vec, fs::File}; | ^^^^^ @@ -17,7 +17,7 @@ LL | use std::{error::Error, vec::Vec, fs::File}; = help: consider importing the item from `core` error: used import from `std` instead of `alloc` - --> tests/ui/std_instead_of_core_unfixable.rs:13:34 + --> tests/ui/std_instead_of_core_unfixable.rs:11:34 | LL | use std::{error::Error, vec::Vec, fs::File}; | ^^^ @@ -27,7 +27,7 @@ LL | use std::{error::Error, vec::Vec, fs::File}; = help: to override `-D warnings` add `#[allow(clippy::std_instead_of_alloc)]` error: used import from `std` instead of `alloc` - --> tests/ui/std_instead_of_core_unfixable.rs:21:17 + --> tests/ui/std_instead_of_core_unfixable.rs:19:17 | LL | borrow::Cow, | ^^^ @@ -35,7 +35,7 @@ LL | borrow::Cow, = help: consider importing the item from `alloc` error: used import from `std` instead of `alloc` - --> tests/ui/std_instead_of_core_unfixable.rs:23:22 + --> tests/ui/std_instead_of_core_unfixable.rs:21:22 | LL | collections::BTreeSet, | ^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/string_lit_as_bytes.fixed b/src/tools/clippy/tests/ui/string_lit_as_bytes.fixed index 2a86dffbc7627..a913951961ba8 100644 --- a/src/tools/clippy/tests/ui/string_lit_as_bytes.fixed +++ b/src/tools/clippy/tests/ui/string_lit_as_bytes.fixed @@ -1,7 +1,7 @@ //@aux-build:macro_rules.rs -#![allow(clippy::needless_raw_string_hashes, dead_code, unused_variables)] #![warn(clippy::string_lit_as_bytes)] +#![expect(clippy::needless_raw_string_hashes)] #[macro_use] extern crate macro_rules; diff --git a/src/tools/clippy/tests/ui/string_lit_as_bytes.rs b/src/tools/clippy/tests/ui/string_lit_as_bytes.rs index 785d8f1e0f6ba..2e7f47dfcf651 100644 --- a/src/tools/clippy/tests/ui/string_lit_as_bytes.rs +++ b/src/tools/clippy/tests/ui/string_lit_as_bytes.rs @@ -1,7 +1,7 @@ //@aux-build:macro_rules.rs -#![allow(clippy::needless_raw_string_hashes, dead_code, unused_variables)] #![warn(clippy::string_lit_as_bytes)] +#![expect(clippy::needless_raw_string_hashes)] #[macro_use] extern crate macro_rules; diff --git a/src/tools/clippy/tests/ui/string_lit_chars_any.fixed b/src/tools/clippy/tests/ui/string_lit_chars_any.fixed index cf05a2c2e8356..e1dd36df5ec6c 100644 --- a/src/tools/clippy/tests/ui/string_lit_chars_any.fixed +++ b/src/tools/clippy/tests/ui/string_lit_chars_any.fixed @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs -#![allow(clippy::eq_op, clippy::needless_raw_string_hashes, clippy::no_effect, unused)] #![warn(clippy::string_lit_chars_any)] +#![expect(clippy::eq_op, clippy::no_effect)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/string_lit_chars_any.rs b/src/tools/clippy/tests/ui/string_lit_chars_any.rs index 22cfb784ed7d0..43197a438fa2b 100644 --- a/src/tools/clippy/tests/ui/string_lit_chars_any.rs +++ b/src/tools/clippy/tests/ui/string_lit_chars_any.rs @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs -#![allow(clippy::eq_op, clippy::needless_raw_string_hashes, clippy::no_effect, unused)] #![warn(clippy::string_lit_chars_any)] +#![expect(clippy::eq_op, clippy::no_effect)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/string_slice.rs b/src/tools/clippy/tests/ui/string_slice.rs index 0acc48c1f4121..b67d84bbea897 100644 --- a/src/tools/clippy/tests/ui/string_slice.rs +++ b/src/tools/clippy/tests/ui/string_slice.rs @@ -1,5 +1,5 @@ #![warn(clippy::string_slice)] -#![allow(clippy::no_effect)] +#![expect(clippy::no_effect)] use std::borrow::Cow; diff --git a/src/tools/clippy/tests/ui/strlen_on_c_strings.fixed b/src/tools/clippy/tests/ui/strlen_on_c_strings.fixed index 0cbf7cf76e852..30502cc350b9b 100644 --- a/src/tools/clippy/tests/ui/strlen_on_c_strings.fixed +++ b/src/tools/clippy/tests/ui/strlen_on_c_strings.fixed @@ -1,5 +1,5 @@ #![warn(clippy::strlen_on_c_strings)] -#![allow(clippy::manual_c_str_literals, clippy::boxed_local)] +#![expect(clippy::boxed_local, clippy::manual_c_str_literals)] use libc::strlen; use std::ffi::{CStr, CString}; diff --git a/src/tools/clippy/tests/ui/strlen_on_c_strings.rs b/src/tools/clippy/tests/ui/strlen_on_c_strings.rs index a4512553da5b1..1c828e8443aa8 100644 --- a/src/tools/clippy/tests/ui/strlen_on_c_strings.rs +++ b/src/tools/clippy/tests/ui/strlen_on_c_strings.rs @@ -1,5 +1,5 @@ #![warn(clippy::strlen_on_c_strings)] -#![allow(clippy::manual_c_str_literals, clippy::boxed_local)] +#![expect(clippy::boxed_local, clippy::manual_c_str_literals)] use libc::strlen; use std::ffi::{CStr, CString}; diff --git a/src/tools/clippy/tests/ui/struct_fields.rs b/src/tools/clippy/tests/ui/struct_fields.rs index e7ff2e6573b2a..be26e69ac7e47 100644 --- a/src/tools/clippy/tests/ui/struct_fields.rs +++ b/src/tools/clippy/tests/ui/struct_fields.rs @@ -1,7 +1,6 @@ //@aux-build:proc_macros.rs #![warn(clippy::struct_field_names)] -#![allow(unused)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/struct_fields.stderr b/src/tools/clippy/tests/ui/struct_fields.stderr index a5ff1b1259074..254498ad2eebc 100644 --- a/src/tools/clippy/tests/ui/struct_fields.stderr +++ b/src/tools/clippy/tests/ui/struct_fields.stderr @@ -1,5 +1,5 @@ error: field name ends with the struct's name - --> tests/ui/struct_fields.rs:10:5 + --> tests/ui/struct_fields.rs:9:5 | LL | field_data1: u8, | ^^^^^^^^^^^^^^^ @@ -8,13 +8,13 @@ LL | field_data1: u8, = help: to override `-D warnings` add `#[allow(clippy::struct_field_names)]` error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:20:5 + --> tests/ui/struct_fields.rs:19:5 | LL | data2_field: u8, | ^^^^^^^^^^^^^^^ error: all fields have the same postfix: `data` - --> tests/ui/struct_fields.rs:25:1 + --> tests/ui/struct_fields.rs:24:1 | LL | / struct StructData { LL | | @@ -27,7 +27,7 @@ LL | | } = help: remove the postfixes error: all fields have the same prefix: `data` - --> tests/ui/struct_fields.rs:32:1 + --> tests/ui/struct_fields.rs:31:1 | LL | / struct DataStruct { LL | | @@ -40,7 +40,7 @@ LL | | } = help: remove the prefixes error: all fields have the same prefix: `some_data` - --> tests/ui/struct_fields.rs:39:1 + --> tests/ui/struct_fields.rs:38:1 | LL | / struct DoublePrefix { LL | | @@ -53,7 +53,7 @@ LL | | } = help: remove the prefixes error: all fields have the same postfix: `some_data` - --> tests/ui/struct_fields.rs:46:1 + --> tests/ui/struct_fields.rs:45:1 | LL | / struct DoublePostfix { LL | | @@ -66,7 +66,7 @@ LL | | } = help: remove the postfixes error: all fields have the same postfix: `someData` - --> tests/ui/struct_fields.rs:54:1 + --> tests/ui/struct_fields.rs:53:1 | LL | / struct NotSnakeCase { LL | | @@ -79,7 +79,7 @@ LL | | } = help: remove the postfixes error: all fields have the same prefix: `someData` - --> tests/ui/struct_fields.rs:61:1 + --> tests/ui/struct_fields.rs:60:1 | LL | / struct NotSnakeCase2 { LL | | @@ -92,7 +92,7 @@ LL | | } = help: remove the prefixes error: all fields have the same prefix: `prefix` - --> tests/ui/struct_fields.rs:74:1 + --> tests/ui/struct_fields.rs:73:1 | LL | / struct NonCaps { LL | | @@ -105,7 +105,7 @@ LL | | } = help: remove the prefixes error: all fields have the same prefix: `_type` - --> tests/ui/struct_fields.rs:124:5 + --> tests/ui/struct_fields.rs:123:5 | LL | / struct DoLint { LL | | @@ -119,7 +119,7 @@ LL | | } = help: remove the prefixes error: all fields have the same prefix: `__type` - --> tests/ui/struct_fields.rs:132:5 + --> tests/ui/struct_fields.rs:131:5 | LL | / struct DoLint2 { LL | | @@ -133,7 +133,7 @@ LL | | } = help: remove the prefixes error: all fields have the same prefix: `___type` - --> tests/ui/struct_fields.rs:140:5 + --> tests/ui/struct_fields.rs:139:5 | LL | / struct DoLint3 { LL | | @@ -147,7 +147,7 @@ LL | | } = help: remove the prefixes error: all fields have the same postfix: `_` - --> tests/ui/struct_fields.rs:148:5 + --> tests/ui/struct_fields.rs:147:5 | LL | / struct DoLint4 { LL | | @@ -161,7 +161,7 @@ LL | | } = help: remove the postfixes error: all fields have the same postfix: `__` - --> tests/ui/struct_fields.rs:156:5 + --> tests/ui/struct_fields.rs:155:5 | LL | / struct DoLint5 { LL | | @@ -175,7 +175,7 @@ LL | | } = help: remove the postfixes error: all fields have the same postfix: `___` - --> tests/ui/struct_fields.rs:164:5 + --> tests/ui/struct_fields.rs:163:5 | LL | / struct DoLint6 { LL | | @@ -189,7 +189,7 @@ LL | | } = help: remove the postfixes error: all fields have the same postfix: `type` - --> tests/ui/struct_fields.rs:172:5 + --> tests/ui/struct_fields.rs:171:5 | LL | / struct DoLintToo { LL | | @@ -202,13 +202,13 @@ LL | | } = help: remove the postfixes error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:210:5 + --> tests/ui/struct_fields.rs:209:5 | LL | proxy: i32, | ^^^^^^^^^^ error: all fields have the same prefix: `some` - --> tests/ui/struct_fields.rs:226:13 + --> tests/ui/struct_fields.rs:225:13 | LL | / struct MacroStruct { LL | | @@ -225,7 +225,7 @@ LL | mk_struct!(); = note: this error originates in the macro `mk_struct` (in Nightly builds, run with -Z macro-backtrace for more info) error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:239:17 + --> tests/ui/struct_fields.rs:238:17 | LL | macrobaz_a: i32, | ^^^^^^^^^^^^^^^ @@ -236,7 +236,7 @@ LL | mk_struct2!(); = note: this error originates in the macro `mk_struct2` (in Nightly builds, run with -Z macro-backtrace for more info) error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:251:17 + --> tests/ui/struct_fields.rs:250:17 | LL | $field: i32, | ^^^^^^^^^^^ @@ -247,7 +247,7 @@ LL | mk_struct_with_names!(Foo, foo); = note: this error originates in the macro `mk_struct_with_names` (in Nightly builds, run with -Z macro-backtrace for more info) error: all fields have the same prefix: `some` - --> tests/ui/struct_fields.rs:291:13 + --> tests/ui/struct_fields.rs:290:13 | LL | / struct $struct_name { LL | | @@ -264,31 +264,31 @@ LL | mk_struct_full_def!(PrefixData, some_data, some_meta, some_other); = note: this error originates in the macro `mk_struct_full_def` (in Nightly builds, run with -Z macro-backtrace for more info) error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:339:5 + --> tests/ui/struct_fields.rs:338:5 | LL | use_foo: bool, | ^^^^^^^^^^^^^ error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:341:5 + --> tests/ui/struct_fields.rs:340:5 | LL | use_bar: bool, | ^^^^^^^^^^^^^ error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:343:5 + --> tests/ui/struct_fields.rs:342:5 | LL | use_baz: bool, | ^^^^^^^^^^^^^ error: field name starts with the struct's name - --> tests/ui/struct_fields.rs:349:5 + --> tests/ui/struct_fields.rs:348:5 | LL | pub_struct_field_named_after_struct: bool, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: all fields have the same prefix: `field` - --> tests/ui/struct_fields.rs:354:1 + --> tests/ui/struct_fields.rs:353:1 | LL | / pub struct PubStructFieldPrefix { LL | | diff --git a/src/tools/clippy/tests/ui/suspicious_arithmetic_impl.rs b/src/tools/clippy/tests/ui/suspicious_arithmetic_impl.rs index acd64ee79096b..5b5a370d81e25 100644 --- a/src/tools/clippy/tests/ui/suspicious_arithmetic_impl.rs +++ b/src/tools/clippy/tests/ui/suspicious_arithmetic_impl.rs @@ -1,5 +1,5 @@ -#![allow(clippy::legacy_numeric_constants, deprecated)] #![warn(clippy::suspicious_arithmetic_impl)] +#![expect(deprecated, clippy::legacy_numeric_constants)] use std::ops::{ Add, AddAssign, BitAnd, BitOr, BitOrAssign, BitXor, Div, DivAssign, Mul, MulAssign, Rem, Shl, Shr, Sub, }; diff --git a/src/tools/clippy/tests/ui/suspicious_command_arg_space.fixed b/src/tools/clippy/tests/ui/suspicious_command_arg_space.fixed index 0a0d90f75e573..5eae8e80add32 100644 --- a/src/tools/clippy/tests/ui/suspicious_command_arg_space.fixed +++ b/src/tools/clippy/tests/ui/suspicious_command_arg_space.fixed @@ -1,4 +1,5 @@ -#![allow(clippy::zombie_processes)] +#![warn(clippy::suspicious_command_arg_space)] +#![expect(clippy::zombie_processes)] fn main() { // Things it should warn about: std::process::Command::new("echo").args(["-n", "hello"]).spawn().unwrap(); diff --git a/src/tools/clippy/tests/ui/suspicious_command_arg_space.rs b/src/tools/clippy/tests/ui/suspicious_command_arg_space.rs index 78bdfbdf0cb6b..70547336773b8 100644 --- a/src/tools/clippy/tests/ui/suspicious_command_arg_space.rs +++ b/src/tools/clippy/tests/ui/suspicious_command_arg_space.rs @@ -1,4 +1,5 @@ -#![allow(clippy::zombie_processes)] +#![warn(clippy::suspicious_command_arg_space)] +#![expect(clippy::zombie_processes)] fn main() { // Things it should warn about: std::process::Command::new("echo").arg("-n hello").spawn().unwrap(); diff --git a/src/tools/clippy/tests/ui/suspicious_command_arg_space.stderr b/src/tools/clippy/tests/ui/suspicious_command_arg_space.stderr index 8952a3ffe4b8b..0509a7854803c 100644 --- a/src/tools/clippy/tests/ui/suspicious_command_arg_space.stderr +++ b/src/tools/clippy/tests/ui/suspicious_command_arg_space.stderr @@ -1,5 +1,5 @@ error: single argument that looks like it should be multiple arguments - --> tests/ui/suspicious_command_arg_space.rs:4:44 + --> tests/ui/suspicious_command_arg_space.rs:5:44 | LL | std::process::Command::new("echo").arg("-n hello").spawn().unwrap(); | ^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + std::process::Command::new("echo").args(["-n", "hello"]).spawn().unwrap | error: single argument that looks like it should be multiple arguments - --> tests/ui/suspicious_command_arg_space.rs:7:43 + --> tests/ui/suspicious_command_arg_space.rs:8:43 | LL | std::process::Command::new("cat").arg("--number file").spawn().unwrap(); | ^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/suspicious_doc_comments.fixed b/src/tools/clippy/tests/ui/suspicious_doc_comments.fixed index 3faa4b21ee414..c7d288095db35 100644 --- a/src/tools/clippy/tests/ui/suspicious_doc_comments.fixed +++ b/src/tools/clippy/tests/ui/suspicious_doc_comments.fixed @@ -1,4 +1,3 @@ -#![allow(unused)] #![warn(clippy::suspicious_doc_comments)] #![allow(clippy::empty_line_after_doc_comments)] diff --git a/src/tools/clippy/tests/ui/suspicious_doc_comments.rs b/src/tools/clippy/tests/ui/suspicious_doc_comments.rs index 4af6ed850c2bb..fdd93bae8f842 100644 --- a/src/tools/clippy/tests/ui/suspicious_doc_comments.rs +++ b/src/tools/clippy/tests/ui/suspicious_doc_comments.rs @@ -1,4 +1,3 @@ -#![allow(unused)] #![warn(clippy::suspicious_doc_comments)] #![allow(clippy::empty_line_after_doc_comments)] diff --git a/src/tools/clippy/tests/ui/suspicious_doc_comments.stderr b/src/tools/clippy/tests/ui/suspicious_doc_comments.stderr index df04d08537c91..bd04f5d23f3f1 100644 --- a/src/tools/clippy/tests/ui/suspicious_doc_comments.stderr +++ b/src/tools/clippy/tests/ui/suspicious_doc_comments.stderr @@ -1,5 +1,5 @@ error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:6:1 + --> tests/ui/suspicious_doc_comments.rs:5:1 | LL | ///! Fake module documentation. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + //! Fake module documentation. | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:11:5 + --> tests/ui/suspicious_doc_comments.rs:10:5 | LL | ///! This module contains useful functions. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + //! This module contains useful functions. | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:24:5 + --> tests/ui/suspicious_doc_comments.rs:23:5 | LL | / /**! This module contains useful functions. LL | | */ @@ -38,7 +38,7 @@ LL + */ | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:39:5 + --> tests/ui/suspicious_doc_comments.rs:38:5 | LL | / ///! This module LL | | @@ -55,7 +55,7 @@ LL ~ //! useful functions. | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:48:5 + --> tests/ui/suspicious_doc_comments.rs:47:5 | LL | / ///! a LL | | @@ -70,7 +70,7 @@ LL ~ //! b | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:57:5 + --> tests/ui/suspicious_doc_comments.rs:56:5 | LL | ///! a | ^^^^^^ @@ -82,7 +82,7 @@ LL + //! a | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:64:5 + --> tests/ui/suspicious_doc_comments.rs:63:5 | LL | / ///! a ... | @@ -98,7 +98,7 @@ LL ~ //! b | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:77:5 + --> tests/ui/suspicious_doc_comments.rs:76:5 | LL | ///! Very cool macro | ^^^^^^^^^^^^^^^^^^^^ @@ -110,7 +110,7 @@ LL + //! Very cool macro | error: this is an outer doc comment and does not apply to the parent module or crate - --> tests/ui/suspicious_doc_comments.rs:85:5 + --> tests/ui/suspicious_doc_comments.rs:84:5 | LL | ///! Huh. | ^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/suspicious_doc_comments_unfixable.rs b/src/tools/clippy/tests/ui/suspicious_doc_comments_unfixable.rs index 17c7cc15b170a..aa75c079692c7 100644 --- a/src/tools/clippy/tests/ui/suspicious_doc_comments_unfixable.rs +++ b/src/tools/clippy/tests/ui/suspicious_doc_comments_unfixable.rs @@ -1,5 +1,5 @@ -#![allow(unused, clippy::empty_line_after_doc_comments)] #![warn(clippy::suspicious_doc_comments)] +#![expect(clippy::empty_line_after_doc_comments)] //@no-rustfix ///! a //~^ suspicious_doc_comments diff --git a/src/tools/clippy/tests/ui/suspicious_else_formatting.rs b/src/tools/clippy/tests/ui/suspicious_else_formatting.rs index 8574cf1c20a1a..71fd9aac5fda3 100644 --- a/src/tools/clippy/tests/ui/suspicious_else_formatting.rs +++ b/src/tools/clippy/tests/ui/suspicious_else_formatting.rs @@ -1,11 +1,11 @@ //@aux-build:proc_macro_suspicious_else_formatting.rs -#![warn(clippy::suspicious_else_formatting, clippy::possible_missing_else)] -#![allow( +#![warn(clippy::possible_missing_else, clippy::suspicious_else_formatting)] +#![expect( clippy::if_same_then_else, clippy::let_unit_value, - clippy::needless_ifs, - clippy::needless_else + clippy::needless_else, + clippy::needless_ifs )] extern crate proc_macro_suspicious_else_formatting; diff --git a/src/tools/clippy/tests/ui/suspicious_map.rs b/src/tools/clippy/tests/ui/suspicious_map.rs index 86e48e29bb9e5..46bb3da56785c 100644 --- a/src/tools/clippy/tests/ui/suspicious_map.rs +++ b/src/tools/clippy/tests/ui/suspicious_map.rs @@ -1,5 +1,5 @@ -#![allow(clippy::map_with_unused_argument_over_ranges)] #![warn(clippy::suspicious_map)] +#![expect(clippy::map_with_unused_argument_over_ranges)] fn main() { let _ = (0..3).map(|x| x + 2).count(); diff --git a/src/tools/clippy/tests/ui/suspicious_operation_groupings.fixed b/src/tools/clippy/tests/ui/suspicious_operation_groupings.fixed index faaae77b87f89..1ad3b37a08ae0 100644 --- a/src/tools/clippy/tests/ui/suspicious_operation_groupings.fixed +++ b/src/tools/clippy/tests/ui/suspicious_operation_groupings.fixed @@ -1,5 +1,5 @@ #![warn(clippy::suspicious_operation_groupings)] -#![allow(dead_code, unused_parens, clippy::eq_op, clippy::manual_midpoint)] +#![expect(clippy::eq_op, clippy::manual_midpoint)] struct Vec3 { x: f64, diff --git a/src/tools/clippy/tests/ui/suspicious_operation_groupings.rs b/src/tools/clippy/tests/ui/suspicious_operation_groupings.rs index cd660b55ca85e..ff77f2e56463f 100644 --- a/src/tools/clippy/tests/ui/suspicious_operation_groupings.rs +++ b/src/tools/clippy/tests/ui/suspicious_operation_groupings.rs @@ -1,5 +1,5 @@ #![warn(clippy::suspicious_operation_groupings)] -#![allow(dead_code, unused_parens, clippy::eq_op, clippy::manual_midpoint)] +#![expect(clippy::eq_op, clippy::manual_midpoint)] struct Vec3 { x: f64, diff --git a/src/tools/clippy/tests/ui/suspicious_splitn.rs b/src/tools/clippy/tests/ui/suspicious_splitn.rs index 535f62c6bedee..4eab716bd8820 100644 --- a/src/tools/clippy/tests/ui/suspicious_splitn.rs +++ b/src/tools/clippy/tests/ui/suspicious_splitn.rs @@ -1,5 +1,4 @@ #![warn(clippy::suspicious_splitn)] -#![allow(clippy::needless_splitn)] fn main() { let _ = "a,b,c".splitn(3, ','); diff --git a/src/tools/clippy/tests/ui/suspicious_splitn.stderr b/src/tools/clippy/tests/ui/suspicious_splitn.stderr index 910c905bc990e..6ae19520673e8 100644 --- a/src/tools/clippy/tests/ui/suspicious_splitn.stderr +++ b/src/tools/clippy/tests/ui/suspicious_splitn.stderr @@ -1,5 +1,5 @@ error: `splitn` called with `0` splits - --> tests/ui/suspicious_splitn.rs:10:13 + --> tests/ui/suspicious_splitn.rs:9:13 | LL | let _ = "a,b".splitn(0, ','); | ^^^^^^^^^^^^^^^^^^^^ @@ -9,7 +9,7 @@ LL | let _ = "a,b".splitn(0, ','); = help: to override `-D warnings` add `#[allow(clippy::suspicious_splitn)]` error: `rsplitn` called with `0` splits - --> tests/ui/suspicious_splitn.rs:13:13 + --> tests/ui/suspicious_splitn.rs:12:13 | LL | let _ = "a,b".rsplitn(0, ','); | ^^^^^^^^^^^^^^^^^^^^^ @@ -17,7 +17,7 @@ LL | let _ = "a,b".rsplitn(0, ','); = note: the resulting iterator will always return `None` error: `splitn` called with `1` split - --> tests/ui/suspicious_splitn.rs:16:13 + --> tests/ui/suspicious_splitn.rs:15:13 | LL | let _ = "a,b".splitn(1, ','); | ^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL | let _ = "a,b".splitn(1, ','); = note: the resulting iterator will always return the entire string followed by `None` error: `splitn` called with `0` splits - --> tests/ui/suspicious_splitn.rs:19:13 + --> tests/ui/suspicious_splitn.rs:18:13 | LL | let _ = [0, 1, 2].splitn(0, |&x| x == 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -33,7 +33,7 @@ LL | let _ = [0, 1, 2].splitn(0, |&x| x == 1); = note: the resulting iterator will always return `None` error: `splitn_mut` called with `0` splits - --> tests/ui/suspicious_splitn.rs:22:13 + --> tests/ui/suspicious_splitn.rs:21:13 | LL | let _ = [0, 1, 2].splitn_mut(0, |&x| x == 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -41,7 +41,7 @@ LL | let _ = [0, 1, 2].splitn_mut(0, |&x| x == 1); = note: the resulting iterator will always return `None` error: `splitn` called with `1` split - --> tests/ui/suspicious_splitn.rs:25:13 + --> tests/ui/suspicious_splitn.rs:24:13 | LL | let _ = [0, 1, 2].splitn(1, |&x| x == 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL | let _ = [0, 1, 2].splitn(1, |&x| x == 1); = note: the resulting iterator will always return the entire slice followed by `None` error: `rsplitn_mut` called with `1` split - --> tests/ui/suspicious_splitn.rs:28:13 + --> tests/ui/suspicious_splitn.rs:27:13 | LL | let _ = [0, 1, 2].rsplitn_mut(1, |&x| x == 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -57,7 +57,7 @@ LL | let _ = [0, 1, 2].rsplitn_mut(1, |&x| x == 1); = note: the resulting iterator will always return the entire slice followed by `None` error: `splitn` called with `1` split - --> tests/ui/suspicious_splitn.rs:32:13 + --> tests/ui/suspicious_splitn.rs:31:13 | LL | let _ = "a,b".splitn(X + 1, ','); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -65,7 +65,7 @@ LL | let _ = "a,b".splitn(X + 1, ','); = note: the resulting iterator will always return the entire string followed by `None` error: `splitn` called with `0` splits - --> tests/ui/suspicious_splitn.rs:35:13 + --> tests/ui/suspicious_splitn.rs:34:13 | LL | let _ = "a,b".splitn(X, ','); | ^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/suspicious_to_owned.1.fixed b/src/tools/clippy/tests/ui/suspicious_to_owned.1.fixed index 6fd536a38ed1b..0b025e6188940 100644 --- a/src/tools/clippy/tests/ui/suspicious_to_owned.1.fixed +++ b/src/tools/clippy/tests/ui/suspicious_to_owned.1.fixed @@ -1,6 +1,5 @@ -#![warn(clippy::suspicious_to_owned)] -#![warn(clippy::implicit_clone)] -#![allow(clippy::redundant_clone)] +#![warn(clippy::implicit_clone, clippy::suspicious_to_owned)] +#![expect(clippy::redundant_clone)] use std::borrow::Cow; use std::ffi::{CStr, c_char}; diff --git a/src/tools/clippy/tests/ui/suspicious_to_owned.2.fixed b/src/tools/clippy/tests/ui/suspicious_to_owned.2.fixed index 841adf8ea274e..203a6368d7986 100644 --- a/src/tools/clippy/tests/ui/suspicious_to_owned.2.fixed +++ b/src/tools/clippy/tests/ui/suspicious_to_owned.2.fixed @@ -1,6 +1,5 @@ -#![warn(clippy::suspicious_to_owned)] -#![warn(clippy::implicit_clone)] -#![allow(clippy::redundant_clone)] +#![warn(clippy::implicit_clone, clippy::suspicious_to_owned)] +#![expect(clippy::redundant_clone)] use std::borrow::Cow; use std::ffi::{CStr, c_char}; diff --git a/src/tools/clippy/tests/ui/suspicious_to_owned.rs b/src/tools/clippy/tests/ui/suspicious_to_owned.rs index f59b3fd6ed0c0..c843ff6514b60 100644 --- a/src/tools/clippy/tests/ui/suspicious_to_owned.rs +++ b/src/tools/clippy/tests/ui/suspicious_to_owned.rs @@ -1,6 +1,5 @@ -#![warn(clippy::suspicious_to_owned)] -#![warn(clippy::implicit_clone)] -#![allow(clippy::redundant_clone)] +#![warn(clippy::implicit_clone, clippy::suspicious_to_owned)] +#![expect(clippy::redundant_clone)] use std::borrow::Cow; use std::ffi::{CStr, c_char}; diff --git a/src/tools/clippy/tests/ui/suspicious_to_owned.stderr b/src/tools/clippy/tests/ui/suspicious_to_owned.stderr index 5fda1ed1cc9c9..ae6cbfeb94ddb 100644 --- a/src/tools/clippy/tests/ui/suspicious_to_owned.stderr +++ b/src/tools/clippy/tests/ui/suspicious_to_owned.stderr @@ -1,5 +1,5 @@ error: this `to_owned` call clones the `Cow<'_, str>` itself and does not cause its contents to become owned - --> tests/ui/suspicious_to_owned.rs:16:13 + --> tests/ui/suspicious_to_owned.rs:15:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ @@ -17,7 +17,7 @@ LL + let _ = cow.clone(); | error: this `to_owned` call clones the `Cow<'_, [char; 3]>` itself and does not cause its contents to become owned - --> tests/ui/suspicious_to_owned.rs:28:13 + --> tests/ui/suspicious_to_owned.rs:27:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ @@ -33,7 +33,7 @@ LL + let _ = cow.clone(); | error: this `to_owned` call clones the `Cow<'_, Vec>` itself and does not cause its contents to become owned - --> tests/ui/suspicious_to_owned.rs:40:13 + --> tests/ui/suspicious_to_owned.rs:39:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + let _ = cow.clone(); | error: this `to_owned` call clones the `Cow<'_, str>` itself and does not cause its contents to become owned - --> tests/ui/suspicious_to_owned.rs:52:13 + --> tests/ui/suspicious_to_owned.rs:51:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ @@ -65,7 +65,7 @@ LL + let _ = cow.clone(); | error: implicitly cloning a `String` by calling `to_owned` on its dereferenced type - --> tests/ui/suspicious_to_owned.rs:68:13 + --> tests/ui/suspicious_to_owned.rs:67:13 | LL | let _ = String::from(moo).to_owned(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `String::from(moo).clone()` @@ -74,7 +74,7 @@ LL | let _ = String::from(moo).to_owned(); = help: to override `-D warnings` add `#[allow(clippy::implicit_clone)]` error: implicitly cloning a `Vec` by calling `to_owned` on its dereferenced type - --> tests/ui/suspicious_to_owned.rs:71:13 + --> tests/ui/suspicious_to_owned.rs:70:13 | LL | let _ = moos_vec.to_owned(); | ^^^^^^^^^^^^^^^^^^^ help: consider using: `moos_vec.clone()` diff --git a/src/tools/clippy/tests/ui/suspicious_unary_op_formatting.rs b/src/tools/clippy/tests/ui/suspicious_unary_op_formatting.rs index 19f8b231925b7..7a5d710c14599 100644 --- a/src/tools/clippy/tests/ui/suspicious_unary_op_formatting.rs +++ b/src/tools/clippy/tests/ui/suspicious_unary_op_formatting.rs @@ -1,5 +1,5 @@ #![warn(clippy::suspicious_unary_op_formatting)] -#![allow(clippy::needless_ifs)] +#![expect(clippy::needless_ifs)] #[rustfmt::skip] fn main() { diff --git a/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.rs b/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.rs index 40a8d8c366bac..55ca85480b551 100644 --- a/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.rs +++ b/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.rs @@ -1,6 +1,5 @@ -#![allow(unused)] #![warn(clippy::suspicious_xor_used_as_pow)] -#![allow(clippy::eq_op)] +#![expect(clippy::eq_op)] //@no-rustfix macro_rules! macro_test { () => { diff --git a/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.stderr b/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.stderr index efeafdb94acb8..2b6570bb0adfc 100644 --- a/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.stderr +++ b/src/tools/clippy/tests/ui/suspicious_xor_used_as_pow.stderr @@ -1,5 +1,5 @@ error: `^` is not the exponentiation operator - --> tests/ui/suspicious_xor_used_as_pow.rs:21:13 + --> tests/ui/suspicious_xor_used_as_pow.rs:20:13 | LL | let _ = 2 ^ 5; | ^^^^^ @@ -13,7 +13,7 @@ LL + let _ = 2.pow(5); | error: `^` is not the exponentiation operator - --> tests/ui/suspicious_xor_used_as_pow.rs:24:13 + --> tests/ui/suspicious_xor_used_as_pow.rs:23:13 | LL | let _ = 2i32 ^ 9i32; | ^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + let _ = 2i32.pow(9i32); | error: `^` is not the exponentiation operator - --> tests/ui/suspicious_xor_used_as_pow.rs:27:13 + --> tests/ui/suspicious_xor_used_as_pow.rs:26:13 | LL | let _ = 2i32 ^ 2i32; | ^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + let _ = 2i32.pow(2i32); | error: `^` is not the exponentiation operator - --> tests/ui/suspicious_xor_used_as_pow.rs:30:13 + --> tests/ui/suspicious_xor_used_as_pow.rs:29:13 | LL | let _ = 50i32 ^ 3i32; | ^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + let _ = 50i32.pow(3i32); | error: `^` is not the exponentiation operator - --> tests/ui/suspicious_xor_used_as_pow.rs:33:13 + --> tests/ui/suspicious_xor_used_as_pow.rs:32:13 | LL | let _ = 5i32 ^ 8i32; | ^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + let _ = 5i32.pow(8i32); | error: `^` is not the exponentiation operator - --> tests/ui/suspicious_xor_used_as_pow.rs:36:13 + --> tests/ui/suspicious_xor_used_as_pow.rs:35:13 | LL | let _ = 2i32 ^ 32i32; | ^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + let _ = 2i32.pow(32i32); | error: `^` is not the exponentiation operator - --> tests/ui/suspicious_xor_used_as_pow.rs:13:9 + --> tests/ui/suspicious_xor_used_as_pow.rs:12:9 | LL | 1 ^ 2 // should warn even if inside macro | ^^^^^ diff --git a/src/tools/clippy/tests/ui/swap.fixed b/src/tools/clippy/tests/ui/swap.fixed index 0d968e96ff794..98f2d0c746030 100644 --- a/src/tools/clippy/tests/ui/swap.fixed +++ b/src/tools/clippy/tests/ui/swap.fixed @@ -1,12 +1,11 @@ //@aux-build: macro_rules.rs -#![allow( +#![warn(clippy::almost_swapped, clippy::manual_swap)] +#![expect( clippy::disallowed_names, - clippy::no_effect, - clippy::redundant_clone, clippy::let_and_return, - clippy::useless_vec, - clippy::redundant_locals + clippy::redundant_locals, + clippy::useless_vec )] struct Foo(u32); diff --git a/src/tools/clippy/tests/ui/swap.rs b/src/tools/clippy/tests/ui/swap.rs index c78c320332fbc..a37753a007941 100644 --- a/src/tools/clippy/tests/ui/swap.rs +++ b/src/tools/clippy/tests/ui/swap.rs @@ -1,12 +1,11 @@ //@aux-build: macro_rules.rs -#![allow( +#![warn(clippy::almost_swapped, clippy::manual_swap)] +#![expect( clippy::disallowed_names, - clippy::no_effect, - clippy::redundant_clone, clippy::let_and_return, - clippy::useless_vec, - clippy::redundant_locals + clippy::redundant_locals, + clippy::useless_vec )] struct Foo(u32); diff --git a/src/tools/clippy/tests/ui/swap.stderr b/src/tools/clippy/tests/ui/swap.stderr index e730be40e3492..1fd1737d7aafd 100644 --- a/src/tools/clippy/tests/ui/swap.stderr +++ b/src/tools/clippy/tests/ui/swap.stderr @@ -1,5 +1,5 @@ error: this looks like you are swapping `bar.a` and `bar.b` manually - --> tests/ui/swap.rs:23:5 + --> tests/ui/swap.rs:22:5 | LL | / let temp = bar.a; LL | | @@ -12,7 +12,7 @@ LL | | bar.b = temp; = help: to override `-D warnings` add `#[allow(clippy::manual_swap)]` error: this looks like you are swapping elements of `foo` manually - --> tests/ui/swap.rs:36:5 + --> tests/ui/swap.rs:35:5 | LL | / let temp = foo[0]; LL | | @@ -21,7 +21,7 @@ LL | | foo[1] = temp; | |__________________^ help: try: `foo.swap(0, 1);` error: this looks like you are swapping elements of `foo` manually - --> tests/ui/swap.rs:46:5 + --> tests/ui/swap.rs:45:5 | LL | / let temp = foo[0]; LL | | @@ -30,7 +30,7 @@ LL | | foo[1] = temp; | |__________________^ help: try: `foo.swap(0, 1);` error: this looks like you are swapping elements of `foo` manually - --> tests/ui/swap.rs:66:5 + --> tests/ui/swap.rs:65:5 | LL | / let temp = foo[0]; LL | | @@ -39,7 +39,7 @@ LL | | foo[1] = temp; | |__________________^ help: try: `foo.swap(0, 1);` error: this looks like you are swapping `a` and `b` manually - --> tests/ui/swap.rs:78:5 + --> tests/ui/swap.rs:77:5 | LL | / a ^= b; LL | | @@ -48,7 +48,7 @@ LL | | a ^= b; | |___________^ help: try: `std::mem::swap(&mut a, &mut b);` error: this looks like you are swapping `bar.a` and `bar.b` manually - --> tests/ui/swap.rs:87:5 + --> tests/ui/swap.rs:86:5 | LL | / bar.a ^= bar.b; LL | | @@ -57,7 +57,7 @@ LL | | bar.a ^= bar.b; | |___________________^ help: try: `std::mem::swap(&mut bar.a, &mut bar.b);` error: this looks like you are swapping elements of `foo` manually - --> tests/ui/swap.rs:96:5 + --> tests/ui/swap.rs:95:5 | LL | / foo[0] ^= foo[1]; LL | | @@ -66,7 +66,7 @@ LL | | foo[0] ^= foo[1]; | |_____________________^ help: try: `foo.swap(0, 1);` error: this looks like you are swapping `foo[0][1]` and `bar[1][0]` manually - --> tests/ui/swap.rs:126:5 + --> tests/ui/swap.rs:125:5 | LL | / let temp = foo[0][1]; LL | | @@ -77,7 +77,7 @@ LL | | bar[1][0] = temp; = note: or maybe you should use `std::mem::replace`? error: this looks like you are swapping `a` and `b` manually - --> tests/ui/swap.rs:142:7 + --> tests/ui/swap.rs:141:7 | LL | ; let t = a; | _______^ @@ -89,7 +89,7 @@ LL | | b = t; = note: or maybe you should use `std::mem::replace`? error: this looks like you are swapping `c.0` and `a` manually - --> tests/ui/swap.rs:153:7 + --> tests/ui/swap.rs:152:7 | LL | ; let t = c.0; | _______^ @@ -101,7 +101,7 @@ LL | | a = t; = note: or maybe you should use `std::mem::replace`? error: this looks like you are swapping `b` and `a` manually - --> tests/ui/swap.rs:183:5 + --> tests/ui/swap.rs:182:5 | LL | / let t = b; LL | | @@ -112,7 +112,7 @@ LL | | a = t; = note: or maybe you should use `std::mem::replace`? error: this looks like you are trying to swap `a` and `b` - --> tests/ui/swap.rs:138:5 + --> tests/ui/swap.rs:137:5 | LL | / a = b; LL | | @@ -120,10 +120,11 @@ LL | | b = a; | |_________^ help: try: `std::mem::swap(&mut a, &mut b)` | = note: or maybe you should use `std::mem::replace`? - = note: `#[deny(clippy::almost_swapped)]` on by default + = note: `-D clippy::almost-swapped` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::almost_swapped)]` error: this looks like you are trying to swap `c.0` and `a` - --> tests/ui/swap.rs:149:5 + --> tests/ui/swap.rs:148:5 | LL | / c.0 = a; LL | | @@ -133,7 +134,7 @@ LL | | a = c.0; = note: or maybe you should use `std::mem::replace`? error: this looks like you are trying to swap `a` and `b` - --> tests/ui/swap.rs:158:5 + --> tests/ui/swap.rs:157:5 | LL | / let a = b; LL | | @@ -143,7 +144,7 @@ LL | | let b = a; = note: or maybe you should use `std::mem::replace`? error: this looks like you are trying to swap `d` and `c` - --> tests/ui/swap.rs:164:5 + --> tests/ui/swap.rs:163:5 | LL | / d = c; LL | | @@ -153,7 +154,7 @@ LL | | c = d; = note: or maybe you should use `std::mem::replace`? error: this looks like you are trying to swap `a` and `b` - --> tests/ui/swap.rs:169:5 + --> tests/ui/swap.rs:168:5 | LL | / let a = b; LL | | @@ -163,7 +164,7 @@ LL | | b = a; = note: or maybe you should use `std::mem::replace`? error: this looks like you are swapping `s.0.x` and `s.0.y` manually - --> tests/ui/swap.rs:219:5 + --> tests/ui/swap.rs:218:5 | LL | / let t = s.0.x; LL | | @@ -174,7 +175,7 @@ LL | | s.0.y = t; = note: or maybe you should use `std::mem::replace`? error: this looks like you are swapping elements of `test_slice!(foo)` manually - --> tests/ui/swap.rs:253:5 + --> tests/ui/swap.rs:252:5 | LL | / let temp = test_slice!(foo)[0]; LL | | diff --git a/src/tools/clippy/tests/ui/temporary_assignment.rs b/src/tools/clippy/tests/ui/temporary_assignment.rs index ac9ed5d05f8fd..fae3be08b49e0 100644 --- a/src/tools/clippy/tests/ui/temporary_assignment.rs +++ b/src/tools/clippy/tests/ui/temporary_assignment.rs @@ -1,5 +1,4 @@ #![warn(clippy::temporary_assignment)] -#![allow(clippy::needless_lifetimes)] use std::ops::{Deref, DerefMut}; diff --git a/src/tools/clippy/tests/ui/temporary_assignment.stderr b/src/tools/clippy/tests/ui/temporary_assignment.stderr index 5f6a540036302..7f8c859110c75 100644 --- a/src/tools/clippy/tests/ui/temporary_assignment.stderr +++ b/src/tools/clippy/tests/ui/temporary_assignment.stderr @@ -1,5 +1,5 @@ error: assignment to temporary - --> tests/ui/temporary_assignment.rs:48:5 + --> tests/ui/temporary_assignment.rs:47:5 | LL | Struct { field: 0 }.field = 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | Struct { field: 0 }.field = 1; = help: to override `-D warnings` add `#[allow(clippy::temporary_assignment)]` error: assignment to temporary - --> tests/ui/temporary_assignment.rs:51:5 + --> tests/ui/temporary_assignment.rs:50:5 | LL | / MultiStruct { LL | | @@ -18,13 +18,13 @@ LL | | .field = 1; | |______________^ error: assignment to temporary - --> tests/ui/temporary_assignment.rs:57:5 + --> tests/ui/temporary_assignment.rs:56:5 | LL | ArrayStruct { array: [0] }.array[0] = 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assignment to temporary - --> tests/ui/temporary_assignment.rs:60:5 + --> tests/ui/temporary_assignment.rs:59:5 | LL | (0, 0).0 = 1; | ^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/tests_outside_test_module.rs b/src/tools/clippy/tests/ui/tests_outside_test_module.rs index 35126c46af083..249240004cb5d 100644 --- a/src/tools/clippy/tests/ui/tests_outside_test_module.rs +++ b/src/tools/clippy/tests/ui/tests_outside_test_module.rs @@ -1,5 +1,4 @@ //@require-annotations-for-level: WARN -#![allow(unused)] #![warn(clippy::tests_outside_test_module)] fn main() { @@ -9,8 +8,8 @@ fn main() { // Should lint #[test] fn my_test() {} -//~^ ERROR: this function marked with #[test] is outside a #[cfg(test)] module -//~| NOTE: move it to a testing module marked with #[cfg(test)] +//~^ ERROR: this function marked with `#[test]` is outside a `#[cfg(test)]` module +//~| NOTE: move it to a testing module marked with `#[cfg(test)]` #[cfg(test)] mod tests { diff --git a/src/tools/clippy/tests/ui/tests_outside_test_module.stderr b/src/tools/clippy/tests/ui/tests_outside_test_module.stderr index 8602a63cc7a41..dc0d168b9658e 100644 --- a/src/tools/clippy/tests/ui/tests_outside_test_module.stderr +++ b/src/tools/clippy/tests/ui/tests_outside_test_module.stderr @@ -1,10 +1,10 @@ -error: this function marked with #[test] is outside a #[cfg(test)] module - --> tests/ui/tests_outside_test_module.rs:11:1 +error: this function marked with `#[test]` is outside a `#[cfg(test)]` module + --> tests/ui/tests_outside_test_module.rs:10:1 | LL | fn my_test() {} | ^^^^^^^^^^^^^^^ | - = note: move it to a testing module marked with #[cfg(test)] + = note: move it to a testing module marked with `#[cfg(test)]` = note: `-D clippy::tests-outside-test-module` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::tests_outside_test_module)]` diff --git a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.fixed b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.fixed index 7075aefd50b67..d2a07770f42e9 100644 --- a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.fixed +++ b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.fixed @@ -9,3 +9,13 @@ /// and probably spanning a many rows. Blablabla, it needs to be over /// 200 characters so I needed to write something longeeeeeeer. pub struct Foo; + +/// [A](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [very](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [short](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [summary](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com). +//~^ too_long_first_doc_paragraph +/// +//~^ too_long_first_doc_paragraph +/// A much longer explanation that goes into a lot more detail about +/// how the thing works, possibly with doclinks and so one, +/// and probably spanning a many rows. Blablabla, it needs to be over +/// 200 characters so I needed to write something longeeeeeeer. +pub struct Bar; diff --git a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.rs b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.rs index 844417d741ef8..ad01b0c3e8330 100644 --- a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.rs +++ b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.rs @@ -7,3 +7,11 @@ /// and probably spanning a many rows. Blablabla, it needs to be over /// 200 characters so I needed to write something longeeeeeeer. pub struct Foo; + +/// [A](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [very](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [short](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [summary](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com). +//~^ too_long_first_doc_paragraph +/// A much longer explanation that goes into a lot more detail about +/// how the thing works, possibly with doclinks and so one, +/// and probably spanning a many rows. Blablabla, it needs to be over +/// 200 characters so I needed to write something longeeeeeeer. +pub struct Bar; diff --git a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.stderr b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.stderr index bc2fbc2d14df6..f409b50e674d6 100644 --- a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.stderr +++ b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph-fix.stderr @@ -19,5 +19,24 @@ LL + /// LL + | -error: aborting due to 1 previous error +error: first doc comment paragraph is too long + --> tests/ui/too_long_first_doc_paragraph-fix.rs:11:1 + | +LL | / /// [A](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [very](https://foooooooooooooooooooooooooo... +LL | | +LL | | /// A much longer explanation that goes into a lot more detail about +LL | | /// how the thing works, possibly with doclinks and so one, +LL | | /// and probably spanning a many rows. Blablabla, it needs to be over +LL | | /// 200 characters so I needed to write something longeeeeeeer. + | |_^ + | +help: add an empty line + | +LL | /// [A](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [very](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [short](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) [summary](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com). +LL | +LL + /// +LL + + | + +error: aborting due to 2 previous errors diff --git a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.rs b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.rs index 49420841c88c7..e3dcc6f1f559b 100644 --- a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.rs +++ b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.rs @@ -68,6 +68,18 @@ fn f() {} /// Here's a second paragraph. It would be preferable to put the details here. pub fn issue_14274() {} +#[rustfmt::skip] +/// This doc comment contains two references: [this](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) +/// and [this](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com) +pub fn issue_13315() {} + +#[rustfmt::skip] +/// Some function. This doc-string paragraph is too long. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of [Lorem Ipsum](https://fooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.example.com). +//~^ too_long_first_doc_paragraph +/// +/// Here's a second paragraph. It would be preferable to put the details here. +pub fn issue_1331_warn() {} + fn main() { // test code goes here } diff --git a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.stderr b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.stderr index 949ada30dc97d..0c67bc945c19e 100644 --- a/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.stderr +++ b/src/tools/clippy/tests/ui/too_long_first_doc_paragraph.stderr @@ -48,5 +48,14 @@ LL | | /// LL | | /// Here's a second paragraph. It would be preferable to put the details here. | |_^ -error: aborting due to 4 previous errors +error: first doc comment paragraph is too long + --> tests/ui/too_long_first_doc_paragraph.rs:77:1 + | +LL | / /// Some function. This doc-string paragraph is too long. Lorem Ipsum is simply dummy text of the printing and typesetting industr... +LL | | +LL | | /// +LL | | /// Here's a second paragraph. It would be preferable to put the details here. + | |_^ + +error: aborting due to 5 previous errors diff --git a/src/tools/clippy/tests/ui/toplevel_ref_arg.fixed b/src/tools/clippy/tests/ui/toplevel_ref_arg.fixed index 11d4eaaefda02..d143a3cd625c3 100644 --- a/src/tools/clippy/tests/ui/toplevel_ref_arg.fixed +++ b/src/tools/clippy/tests/ui/toplevel_ref_arg.fixed @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs #![warn(clippy::toplevel_ref_arg)] -#![allow(clippy::uninlined_format_args, unused, clippy::useless_vec)] +#![expect(clippy::uninlined_format_args, clippy::useless_vec)] extern crate proc_macros; use proc_macros::{external, inline_macros}; diff --git a/src/tools/clippy/tests/ui/toplevel_ref_arg.rs b/src/tools/clippy/tests/ui/toplevel_ref_arg.rs index 957dd542f5a99..73d7b736f8a2e 100644 --- a/src/tools/clippy/tests/ui/toplevel_ref_arg.rs +++ b/src/tools/clippy/tests/ui/toplevel_ref_arg.rs @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs #![warn(clippy::toplevel_ref_arg)] -#![allow(clippy::uninlined_format_args, unused, clippy::useless_vec)] +#![expect(clippy::uninlined_format_args, clippy::useless_vec)] extern crate proc_macros; use proc_macros::{external, inline_macros}; diff --git a/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.rs b/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.rs index 87c84a7ee14ab..33f33d287a154 100644 --- a/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.rs +++ b/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.rs @@ -1,7 +1,6 @@ //@aux-build:proc_macros.rs #![warn(clippy::toplevel_ref_arg)] -#![allow(unused)] extern crate proc_macros; use proc_macros::{external, inline_macros}; diff --git a/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.stderr b/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.stderr index e17b2536874e0..828919b59ce22 100644 --- a/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.stderr +++ b/src/tools/clippy/tests/ui/toplevel_ref_arg_non_rustfix.stderr @@ -1,5 +1,5 @@ error: `ref` directly on a function parameter does not prevent taking ownership of the passed argument. Consider using a reference type instead - --> tests/ui/toplevel_ref_arg_non_rustfix.rs:9:15 + --> tests/ui/toplevel_ref_arg_non_rustfix.rs:8:15 | LL | fn the_answer(ref mut x: u8) { | ^^^^^^^^^ @@ -8,7 +8,7 @@ LL | fn the_answer(ref mut x: u8) { = help: to override `-D warnings` add `#[allow(clippy::toplevel_ref_arg)]` error: `ref` directly on a function parameter does not prevent taking ownership of the passed argument. Consider using a reference type instead - --> tests/ui/toplevel_ref_arg_non_rustfix.rs:21:24 + --> tests/ui/toplevel_ref_arg_non_rustfix.rs:20:24 | LL | fn fun_example(ref _x: usize) {} | ^^^^^^ diff --git a/src/tools/clippy/tests/ui/trailing_empty_array.rs b/src/tools/clippy/tests/ui/trailing_empty_array.rs index a8c3ffdb0dab3..c0ee31e55f600 100644 --- a/src/tools/clippy/tests/ui/trailing_empty_array.rs +++ b/src/tools/clippy/tests/ui/trailing_empty_array.rs @@ -1,5 +1,5 @@ #![warn(clippy::trailing_empty_array)] -#![allow(clippy::repr_packed_without_abi)] +#![expect(clippy::repr_packed_without_abi)] // Do lint: diff --git a/src/tools/clippy/tests/ui/trailing_zeros.fixed b/src/tools/clippy/tests/ui/trailing_zeros.fixed index 8c30b062fb183..cd4cd0f8cacb7 100644 --- a/src/tools/clippy/tests/ui/trailing_zeros.fixed +++ b/src/tools/clippy/tests/ui/trailing_zeros.fixed @@ -1,4 +1,3 @@ -#![allow(unused_parens)] #![warn(clippy::verbose_bit_mask)] fn main() { diff --git a/src/tools/clippy/tests/ui/trailing_zeros.rs b/src/tools/clippy/tests/ui/trailing_zeros.rs index 369a31557392c..c5038b612f6da 100644 --- a/src/tools/clippy/tests/ui/trailing_zeros.rs +++ b/src/tools/clippy/tests/ui/trailing_zeros.rs @@ -1,4 +1,3 @@ -#![allow(unused_parens)] #![warn(clippy::verbose_bit_mask)] fn main() { diff --git a/src/tools/clippy/tests/ui/trailing_zeros.stderr b/src/tools/clippy/tests/ui/trailing_zeros.stderr index 6f3e7aa1d762e..de951e2e75a26 100644 --- a/src/tools/clippy/tests/ui/trailing_zeros.stderr +++ b/src/tools/clippy/tests/ui/trailing_zeros.stderr @@ -1,5 +1,5 @@ error: bit mask could be simplified with a call to `trailing_zeros` - --> tests/ui/trailing_zeros.rs:6:13 + --> tests/ui/trailing_zeros.rs:5:13 | LL | let _ = (x & 0b1111 == 0); | ^^^^^^^^^^^^^^^^^ help: try: `x.trailing_zeros() >= 4` @@ -8,7 +8,7 @@ LL | let _ = (x & 0b1111 == 0); = help: to override `-D warnings` add `#[allow(clippy::verbose_bit_mask)]` error: bit mask could be simplified with a call to `trailing_zeros` - --> tests/ui/trailing_zeros.rs:9:13 + --> tests/ui/trailing_zeros.rs:8:13 | LL | let _ = x & 0b1_1111 == 0; | ^^^^^^^^^^^^^^^^^ help: try: `x.trailing_zeros() >= 5` diff --git a/src/tools/clippy/tests/ui/trait_duplication_in_bounds.fixed b/src/tools/clippy/tests/ui/trait_duplication_in_bounds.fixed index 959f5db112655..658880e81e2e3 100644 --- a/src/tools/clippy/tests/ui/trait_duplication_in_bounds.fixed +++ b/src/tools/clippy/tests/ui/trait_duplication_in_bounds.fixed @@ -1,5 +1,4 @@ -#![deny(clippy::trait_duplication_in_bounds)] -#![allow(unused)] +#![warn(clippy::trait_duplication_in_bounds)] #![feature(const_trait_impl)] use std::any::Any; diff --git a/src/tools/clippy/tests/ui/trait_duplication_in_bounds.rs b/src/tools/clippy/tests/ui/trait_duplication_in_bounds.rs index 9bfecf40fc03d..046a8ad8e597f 100644 --- a/src/tools/clippy/tests/ui/trait_duplication_in_bounds.rs +++ b/src/tools/clippy/tests/ui/trait_duplication_in_bounds.rs @@ -1,5 +1,4 @@ -#![deny(clippy::trait_duplication_in_bounds)] -#![allow(unused)] +#![warn(clippy::trait_duplication_in_bounds)] #![feature(const_trait_impl)] use std::any::Any; diff --git a/src/tools/clippy/tests/ui/trait_duplication_in_bounds.stderr b/src/tools/clippy/tests/ui/trait_duplication_in_bounds.stderr index 93488ea8e74db..fb3887d22517f 100644 --- a/src/tools/clippy/tests/ui/trait_duplication_in_bounds.stderr +++ b/src/tools/clippy/tests/ui/trait_duplication_in_bounds.stderr @@ -1,71 +1,68 @@ error: these bounds contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:7:15 + --> tests/ui/trait_duplication_in_bounds.rs:6:15 | LL | fn bad_foo(arg0: T, argo1: U) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Clone + Copy` | -note: the lint level is defined here - --> tests/ui/trait_duplication_in_bounds.rs:1:9 - | -LL | #![deny(clippy::trait_duplication_in_bounds)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::trait-duplication-in-bounds` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::trait_duplication_in_bounds)]` error: these where clauses contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:14:8 + --> tests/ui/trait_duplication_in_bounds.rs:13:8 | LL | T: Clone + Clone + Clone + Copy, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Clone + Copy` error: these bounds contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:43:26 + --> tests/ui/trait_duplication_in_bounds.rs:42:26 | LL | trait BadSelfTraitBound: Clone + Clone + Clone { | ^^^^^^^^^^^^^^^^^^^^^ help: try: `Clone` error: these where clauses contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:51:15 + --> tests/ui/trait_duplication_in_bounds.rs:50:15 | LL | Self: Clone + Clone + Clone; | ^^^^^^^^^^^^^^^^^^^^^ help: try: `Clone` error: these bounds contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:66:24 + --> tests/ui/trait_duplication_in_bounds.rs:65:24 | LL | trait BadTraitBound { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Clone + Copy` error: these where clauses contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:74:12 + --> tests/ui/trait_duplication_in_bounds.rs:73:12 | LL | T: Clone + Clone + Clone + Copy, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Clone + Copy` error: these bounds contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:108:19 + --> tests/ui/trait_duplication_in_bounds.rs:107:19 | LL | fn bad_generic + GenericTrait + GenericTrait>(arg0: T) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `GenericTrait + GenericTrait` error: these bounds contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:117:22 + --> tests/ui/trait_duplication_in_bounds.rs:116:22 | LL | fn qualified_path(arg0: T) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::clone::Clone + foo::Clone` error: this trait bound is already specified in trait declaration - --> tests/ui/trait_duplication_in_bounds.rs:126:33 + --> tests/ui/trait_duplication_in_bounds.rs:125:33 | LL | fn bad_trait_object(arg0: &(dyn Any + Send + Send)) { | ^^^^^^^^^^^^^^^^^ help: try: `Any + Send` error: these bounds contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:173:36 + --> tests/ui/trait_duplication_in_bounds.rs:172:36 | LL | const fn const_trait_bounds_bad() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `[const] ConstTrait` error: these where clauses contain repeated elements - --> tests/ui/trait_duplication_in_bounds.rs:180:8 + --> tests/ui/trait_duplication_in_bounds.rs:179:8 | LL | T: IntoIterator + IntoIterator, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `IntoIterator` diff --git a/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.rs b/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.rs index cf72ed844a78c..a519fb3651ef7 100644 --- a/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.rs +++ b/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.rs @@ -1,5 +1,5 @@ -#![deny(clippy::trait_duplication_in_bounds)] -#![allow(clippy::multiple_bound_locations)] +#![warn(clippy::trait_duplication_in_bounds)] +#![expect(clippy::multiple_bound_locations)] use std::collections::BTreeMap; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; diff --git a/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.stderr b/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.stderr index 546d39518e1fa..2a6c82efa92d5 100644 --- a/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.stderr +++ b/src/tools/clippy/tests/ui/trait_duplication_in_bounds_unfixable.stderr @@ -5,11 +5,8 @@ LL | fn bad_foo(arg0: T, arg1: Z) | ^^^^^ | = help: consider removing this trait bound -note: the lint level is defined here - --> tests/ui/trait_duplication_in_bounds_unfixable.rs:1:9 - | -LL | #![deny(clippy::trait_duplication_in_bounds)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::trait-duplication-in-bounds` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::trait_duplication_in_bounds)]` error: this trait bound is already specified in the where clause --> tests/ui/trait_duplication_in_bounds_unfixable.rs:7:23 diff --git a/src/tools/clippy/tests/ui/transmute.rs b/src/tools/clippy/tests/ui/transmute.rs index afb79deac20f8..36d794cedea11 100644 --- a/src/tools/clippy/tests/ui/transmute.rs +++ b/src/tools/clippy/tests/ui/transmute.rs @@ -1,13 +1,12 @@ #![feature(f128)] #![feature(f16)] -#![allow( - dead_code, - clippy::borrow_as_ptr, - unnecessary_transmutes, - integer_to_ptr_transmutes, - clippy::needless_lifetimes, - clippy::missing_transmute_annotations +#![warn( + clippy::crosspointer_transmute, + clippy::transmute_bytes_to_str, + clippy::transmute_int_to_bool, + clippy::useless_transmute )] +#![expect(integer_to_ptr_transmutes, clippy::needless_lifetimes)] //@no-rustfix extern crate core; @@ -23,7 +22,6 @@ fn my_vec() -> MyVec { } #[allow(clippy::needless_lifetimes, clippy::transmute_ptr_to_ptr)] -#[warn(clippy::useless_transmute)] unsafe fn _generic<'a, T, U: 'a>(t: &'a T) { unsafe { // FIXME: should lint @@ -42,7 +40,6 @@ unsafe fn _generic<'a, T, U: 'a>(t: &'a T) { } } -#[warn(clippy::useless_transmute)] fn useless() { unsafe { let _: Vec = core::mem::transmute(my_vec()); @@ -88,7 +85,6 @@ fn useless() { struct Usize(usize); -#[warn(clippy::crosspointer_transmute)] fn crosspointer() { let mut int: Usize = Usize(0); let int_const_ptr: *const Usize = &int as *const Usize; @@ -109,7 +105,6 @@ fn crosspointer() { } } -#[warn(clippy::transmute_int_to_bool)] fn int_to_bool() { let _: bool = unsafe { std::mem::transmute(0_u8) }; //~^ transmute_int_to_bool diff --git a/src/tools/clippy/tests/ui/transmute.stderr b/src/tools/clippy/tests/ui/transmute.stderr index 6f9a0b717fc90..0232d9ac04bbf 100644 --- a/src/tools/clippy/tests/ui/transmute.stderr +++ b/src/tools/clippy/tests/ui/transmute.stderr @@ -1,5 +1,5 @@ error: transmute from a reference to a pointer - --> tests/ui/transmute.rs:34:27 + --> tests/ui/transmute.rs:32:27 | LL | let _: *const T = core::mem::transmute(t); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `t as *const T` @@ -8,49 +8,49 @@ LL | let _: *const T = core::mem::transmute(t); = help: to override `-D warnings` add `#[allow(clippy::useless_transmute)]` error: transmute from a reference to a pointer - --> tests/ui/transmute.rs:37:25 + --> tests/ui/transmute.rs:35:25 | LL | let _: *mut T = core::mem::transmute(t); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `t as *const T as *mut T` error: transmute from a reference to a pointer - --> tests/ui/transmute.rs:40:27 + --> tests/ui/transmute.rs:38:27 | LL | let _: *const U = core::mem::transmute(t); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `t as *const T as *const U` error: transmute from a type (`std::vec::Vec`) to itself - --> tests/ui/transmute.rs:48:27 + --> tests/ui/transmute.rs:45:27 | LL | let _: Vec = core::mem::transmute(my_vec()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a type (`std::vec::Vec`) to itself - --> tests/ui/transmute.rs:51:27 + --> tests/ui/transmute.rs:48:27 | LL | let _: Vec = core::mem::transmute(my_vec()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a type (`std::vec::Vec`) to itself - --> tests/ui/transmute.rs:54:27 + --> tests/ui/transmute.rs:51:27 | LL | let _: Vec = std::mem::transmute(my_vec()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a type (`std::vec::Vec`) to itself - --> tests/ui/transmute.rs:57:27 + --> tests/ui/transmute.rs:54:27 | LL | let _: Vec = std::mem::transmute(my_vec()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a type (`std::vec::Vec`) to itself - --> tests/ui/transmute.rs:60:27 + --> tests/ui/transmute.rs:57:27 | LL | let _: Vec = my_transmute(my_vec()); | ^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a type (`*const Usize`) to the type that it points to (`Usize`) - --> tests/ui/transmute.rs:98:24 + --> tests/ui/transmute.rs:94:24 | LL | let _: Usize = core::mem::transmute(int_const_ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -59,25 +59,25 @@ LL | let _: Usize = core::mem::transmute(int_const_ptr); = help: to override `-D warnings` add `#[allow(clippy::crosspointer_transmute)]` error: transmute from a type (`*mut Usize`) to the type that it points to (`Usize`) - --> tests/ui/transmute.rs:101:24 + --> tests/ui/transmute.rs:97:24 | LL | let _: Usize = core::mem::transmute(int_mut_ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a type (`Usize`) to a pointer to that type (`*const Usize`) - --> tests/ui/transmute.rs:104:31 + --> tests/ui/transmute.rs:100:31 | LL | let _: *const Usize = core::mem::transmute(my_int()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a type (`Usize`) to a pointer to that type (`*mut Usize`) - --> tests/ui/transmute.rs:107:29 + --> tests/ui/transmute.rs:103:29 | LL | let _: *mut Usize = core::mem::transmute(my_int()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from a `u8` to a `bool` - --> tests/ui/transmute.rs:114:28 + --> tests/ui/transmute.rs:109:28 | LL | let _: bool = unsafe { std::mem::transmute(0_u8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `0_u8 != 0` @@ -86,7 +86,7 @@ LL | let _: bool = unsafe { std::mem::transmute(0_u8) }; = help: to override `-D warnings` add `#[allow(clippy::transmute_int_to_bool)]` error: transmute from a `&[u8]` to a `&str` - --> tests/ui/transmute.rs:121:28 + --> tests/ui/transmute.rs:116:28 | LL | let _: &str = unsafe { std::mem::transmute(B) }; | ^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8(B).unwrap()` @@ -95,19 +95,19 @@ LL | let _: &str = unsafe { std::mem::transmute(B) }; = help: to override `-D warnings` add `#[allow(clippy::transmute_bytes_to_str)]` error: transmute from a `&mut [u8]` to a `&mut str` - --> tests/ui/transmute.rs:124:32 + --> tests/ui/transmute.rs:119:32 | LL | let _: &mut str = unsafe { std::mem::transmute(mb) }; | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8_mut(mb).unwrap()` error: transmute from a `&[u8]` to a `&str` - --> tests/ui/transmute.rs:127:30 + --> tests/ui/transmute.rs:122:30 | LL | const _: &str = unsafe { std::mem::transmute(B) }; | ^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8_unchecked(B)` error: transmute from a `&[u8]` to a `&str` - --> tests/ui/transmute.rs:139:23 + --> tests/ui/transmute.rs:134:23 | LL | let _: &str = std::mem::transmute(take_ref!(b)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8(take_ref!(b)).unwrap()` diff --git a/src/tools/clippy/tests/ui/transmute_collection.rs b/src/tools/clippy/tests/ui/transmute_collection.rs index 74d7f5e38bf8d..31f62776467d6 100644 --- a/src/tools/clippy/tests/ui/transmute_collection.rs +++ b/src/tools/clippy/tests/ui/transmute_collection.rs @@ -1,5 +1,5 @@ #![warn(clippy::unsound_collection_transmute)] -#![allow(clippy::missing_transmute_annotations)] +#![expect(clippy::missing_transmute_annotations)] use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque}; use std::mem::{MaybeUninit, transmute}; diff --git a/src/tools/clippy/tests/ui/transmute_int_to_non_zero.fixed b/src/tools/clippy/tests/ui/transmute_int_to_non_zero.fixed index 273090fef3876..3072cd32f3900 100644 --- a/src/tools/clippy/tests/ui/transmute_int_to_non_zero.fixed +++ b/src/tools/clippy/tests/ui/transmute_int_to_non_zero.fixed @@ -1,5 +1,4 @@ #![warn(clippy::transmute_int_to_non_zero)] -#![allow(clippy::missing_transmute_annotations)] use core::num::NonZero; diff --git a/src/tools/clippy/tests/ui/transmute_int_to_non_zero.rs b/src/tools/clippy/tests/ui/transmute_int_to_non_zero.rs index f27bc9b42d426..446d3e632418b 100644 --- a/src/tools/clippy/tests/ui/transmute_int_to_non_zero.rs +++ b/src/tools/clippy/tests/ui/transmute_int_to_non_zero.rs @@ -1,5 +1,4 @@ #![warn(clippy::transmute_int_to_non_zero)] -#![allow(clippy::missing_transmute_annotations)] use core::num::NonZero; diff --git a/src/tools/clippy/tests/ui/transmute_int_to_non_zero.stderr b/src/tools/clippy/tests/ui/transmute_int_to_non_zero.stderr index 995ab11a5bc96..f43505c9e55f6 100644 --- a/src/tools/clippy/tests/ui/transmute_int_to_non_zero.stderr +++ b/src/tools/clippy/tests/ui/transmute_int_to_non_zero.stderr @@ -1,5 +1,5 @@ error: transmute from a `u8` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:19:35 + --> tests/ui/transmute_int_to_non_zero.rs:18:35 | LL | let _: NonZero = unsafe { std::mem::transmute(int_u8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_u8)` @@ -8,55 +8,55 @@ LL | let _: NonZero = unsafe { std::mem::transmute(int_u8) }; = help: to override `-D warnings` add `#[allow(clippy::transmute_int_to_non_zero)]` error: transmute from a `u16` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:22:36 + --> tests/ui/transmute_int_to_non_zero.rs:21:36 | LL | let _: NonZero = unsafe { std::mem::transmute(int_u16) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_u16)` error: transmute from a `u32` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:25:36 + --> tests/ui/transmute_int_to_non_zero.rs:24:36 | LL | let _: NonZero = unsafe { std::mem::transmute(int_u32) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_u32)` error: transmute from a `u64` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:28:36 + --> tests/ui/transmute_int_to_non_zero.rs:27:36 | LL | let _: NonZero = unsafe { std::mem::transmute(int_u64) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_u64)` error: transmute from a `u128` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:31:37 + --> tests/ui/transmute_int_to_non_zero.rs:30:37 | LL | let _: NonZero = unsafe { std::mem::transmute(int_u128) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_u128)` error: transmute from a `i8` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:34:35 + --> tests/ui/transmute_int_to_non_zero.rs:33:35 | LL | let _: NonZero = unsafe { std::mem::transmute(int_i8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_i8)` error: transmute from a `i16` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:37:36 + --> tests/ui/transmute_int_to_non_zero.rs:36:36 | LL | let _: NonZero = unsafe { std::mem::transmute(int_i16) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_i16)` error: transmute from a `i32` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:40:36 + --> tests/ui/transmute_int_to_non_zero.rs:39:36 | LL | let _: NonZero = unsafe { std::mem::transmute(int_i32) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_i32)` error: transmute from a `i64` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:43:36 + --> tests/ui/transmute_int_to_non_zero.rs:42:36 | LL | let _: NonZero = unsafe { std::mem::transmute(int_i64) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_i64)` error: transmute from a `i128` to a `NonZero` - --> tests/ui/transmute_int_to_non_zero.rs:46:37 + --> tests/ui/transmute_int_to_non_zero.rs:45:37 | LL | let _: NonZero = unsafe { std::mem::transmute(int_i128) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `NonZero::new_unchecked(int_i128)` diff --git a/src/tools/clippy/tests/ui/transmute_null_to_fn.rs b/src/tools/clippy/tests/ui/transmute_null_to_fn.rs index 9ce097d124ab8..f7ba6b6e7805b 100644 --- a/src/tools/clippy/tests/ui/transmute_null_to_fn.rs +++ b/src/tools/clippy/tests/ui/transmute_null_to_fn.rs @@ -1,7 +1,5 @@ -#![allow(dead_code)] #![warn(clippy::transmute_null_to_fn)] -#![allow(clippy::zero_ptr, clippy::missing_transmute_annotations)] -#![allow(clippy::manual_dangling_ptr)] +#![expect(clippy::manual_dangling_ptr, clippy::zero_ptr)] // Easy to lint because these only span one line. fn one_liners() { diff --git a/src/tools/clippy/tests/ui/transmute_null_to_fn.stderr b/src/tools/clippy/tests/ui/transmute_null_to_fn.stderr index b5b0d4ecc7c03..04ce23ca955a0 100644 --- a/src/tools/clippy/tests/ui/transmute_null_to_fn.stderr +++ b/src/tools/clippy/tests/ui/transmute_null_to_fn.stderr @@ -1,5 +1,5 @@ error: transmuting a known null pointer into a function pointer - --> tests/ui/transmute_null_to_fn.rs:9:23 + --> tests/ui/transmute_null_to_fn.rs:7:23 | LL | let _: fn() = std::mem::transmute(0 as *const ()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this transmute results in undefined behavior @@ -9,7 +9,7 @@ LL | let _: fn() = std::mem::transmute(0 as *const ()); = help: to override `-D warnings` add `#[allow(clippy::transmute_null_to_fn)]` error: transmuting a known null pointer into a function pointer - --> tests/ui/transmute_null_to_fn.rs:12:23 + --> tests/ui/transmute_null_to_fn.rs:10:23 | LL | let _: fn() = std::mem::transmute(std::ptr::null::<()>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this transmute results in undefined behavior @@ -17,7 +17,7 @@ LL | let _: fn() = std::mem::transmute(std::ptr::null::<()>()); = help: try wrapping your function pointer type in `Option` instead, and using `None` as a null pointer value error: transmuting a known null pointer into a function pointer - --> tests/ui/transmute_null_to_fn.rs:23:23 + --> tests/ui/transmute_null_to_fn.rs:21:23 | LL | let _: fn() = std::mem::transmute(ZPTR); | ^^^^^^^^^^^^^^^^^^^^^^^^^ this transmute results in undefined behavior @@ -25,7 +25,7 @@ LL | let _: fn() = std::mem::transmute(ZPTR); = help: try wrapping your function pointer type in `Option` instead, and using `None` as a null pointer value error: transmuting a known null pointer into a function pointer - --> tests/ui/transmute_null_to_fn.rs:33:23 + --> tests/ui/transmute_null_to_fn.rs:31:23 | LL | let _: fn() = std::mem::transmute(0 as *const u8 as *const ()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this transmute results in undefined behavior @@ -33,7 +33,7 @@ LL | let _: fn() = std::mem::transmute(0 as *const u8 as *const ()); = help: try wrapping your function pointer type in `Option` instead, and using `None` as a null pointer value error: transmuting a known null pointer into a function pointer - --> tests/ui/transmute_null_to_fn.rs:36:23 + --> tests/ui/transmute_null_to_fn.rs:34:23 | LL | let _: fn() = std::mem::transmute(std::ptr::null::<()>() as *const u8); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this transmute results in undefined behavior @@ -41,7 +41,7 @@ LL | let _: fn() = std::mem::transmute(std::ptr::null::<()>() as *const = help: try wrapping your function pointer type in `Option` instead, and using `None` as a null pointer value error: transmuting a known null pointer into a function pointer - --> tests/ui/transmute_null_to_fn.rs:39:23 + --> tests/ui/transmute_null_to_fn.rs:37:23 | LL | let _: fn() = std::mem::transmute(ZPTR as *const u8); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this transmute results in undefined behavior diff --git a/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.fixed b/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.fixed index caba277db754d..1fc0c315435bc 100644 --- a/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.fixed +++ b/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.fixed @@ -1,5 +1,4 @@ #![warn(clippy::transmute_ptr_to_ptr)] -#![allow(clippy::borrow_as_ptr, clippy::missing_transmute_annotations)] use std::mem::transmute; diff --git a/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.rs b/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.rs index b3c2baf29c361..d2fc34db21f02 100644 --- a/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.rs +++ b/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.rs @@ -1,5 +1,4 @@ #![warn(clippy::transmute_ptr_to_ptr)] -#![allow(clippy::borrow_as_ptr, clippy::missing_transmute_annotations)] use std::mem::transmute; diff --git a/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.stderr b/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.stderr index ba9e6df6c2d7c..aef67239eaf25 100644 --- a/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.stderr +++ b/src/tools/clippy/tests/ui/transmute_ptr_to_ptr.stderr @@ -1,5 +1,5 @@ error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:39:29 + --> tests/ui/transmute_ptr_to_ptr.rs:38:29 | LL | let _: *const f32 = transmute(ptr); | ^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let _: *const f32 = ptr.cast::(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:42:27 + --> tests/ui/transmute_ptr_to_ptr.rs:41:27 | LL | let _: *mut f32 = transmute(mut_ptr); | ^^^^^^^^^^^^^^^^^^ @@ -25,37 +25,37 @@ LL + let _: *mut f32 = mut_ptr.cast::(); | error: transmute from a reference to a reference - --> tests/ui/transmute_ptr_to_ptr.rs:46:23 + --> tests/ui/transmute_ptr_to_ptr.rs:45:23 | LL | let _: &f32 = transmute(&1u32); | ^^^^^^^^^^^^^^^^ help: try: `&*(&1u32 as *const u32 as *const f32)` error: transmute from a reference to a reference - --> tests/ui/transmute_ptr_to_ptr.rs:49:23 + --> tests/ui/transmute_ptr_to_ptr.rs:48:23 | LL | let _: &f32 = transmute(&1f64); | ^^^^^^^^^^^^^^^^ help: try: `&*(&1f64 as *const f64 as *const f32)` error: transmute from a reference to a reference - --> tests/ui/transmute_ptr_to_ptr.rs:54:27 + --> tests/ui/transmute_ptr_to_ptr.rs:53:27 | LL | let _: &mut f32 = transmute(&mut 1u32); | ^^^^^^^^^^^^^^^^^^^^ help: try: `&mut *(&mut 1u32 as *mut u32 as *mut f32)` error: transmute from a reference to a reference - --> tests/ui/transmute_ptr_to_ptr.rs:57:37 + --> tests/ui/transmute_ptr_to_ptr.rs:56:37 | LL | let _: &GenericParam = transmute(&GenericParam { t: 1u32 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&GenericParam { t: 1u32 } as *const GenericParam as *const GenericParam)` error: transmute from a reference to a reference - --> tests/ui/transmute_ptr_to_ptr.rs:61:27 + --> tests/ui/transmute_ptr_to_ptr.rs:60:27 | LL | let u8_ref: &u8 = transmute(u64_ref); | ^^^^^^^^^^^^^^^^^^ help: try: `&*(u64_ref as *const u64 as *const u8)` error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:64:29 + --> tests/ui/transmute_ptr_to_ptr.rs:63:29 | LL | let _: *const u32 = transmute(mut_ptr); | ^^^^^^^^^^^^^^^^^^ @@ -67,7 +67,7 @@ LL + let _: *const u32 = mut_ptr.cast_const(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:67:27 + --> tests/ui/transmute_ptr_to_ptr.rs:66:27 | LL | let _: *mut u32 = transmute(ptr); | ^^^^^^^^^^^^^^ @@ -79,7 +79,7 @@ LL + let _: *mut u32 = ptr.cast_mut(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:81:29 + --> tests/ui/transmute_ptr_to_ptr.rs:80:29 | LL | let _: *const f32 = transmute(Ptr(ptr)); | ^^^^^^^^^^^^^^^^^^^ @@ -91,7 +91,7 @@ LL + let _: *const f32 = Ptr(ptr).0.cast::(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:83:29 + --> tests/ui/transmute_ptr_to_ptr.rs:82:29 | LL | let _: *const f32 = transmute(PtrNamed { ptr }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -103,7 +103,7 @@ LL + let _: *const f32 = PtrNamed { ptr }.ptr.cast::(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:85:27 + --> tests/ui/transmute_ptr_to_ptr.rs:84:27 | LL | let _: *mut u32 = transmute(Ptr(ptr)); | ^^^^^^^^^^^^^^^^^^^ @@ -115,7 +115,7 @@ LL + let _: *mut u32 = Ptr(ptr).0.cast_mut(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:91:14 + --> tests/ui/transmute_ptr_to_ptr.rs:90:14 | LL | unsafe { transmute(v) } | ^^^^^^^^^^^^ @@ -127,7 +127,7 @@ LL + unsafe { v as *const &() } | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:108:28 + --> tests/ui/transmute_ptr_to_ptr.rs:107:28 | LL | let _: *const i8 = transmute(ptr); | ^^^^^^^^^^^^^^ @@ -139,7 +139,7 @@ LL + let _: *const i8 = ptr as *const i8; | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:110:28 + --> tests/ui/transmute_ptr_to_ptr.rs:109:28 | LL | let _: *const i8 = transmute(Ptr8(ptr)); | ^^^^^^^^^^^^^^^^^^^^ @@ -151,7 +151,7 @@ LL + let _: *const i8 = Ptr8(ptr).0 as *const i8; | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:118:28 + --> tests/ui/transmute_ptr_to_ptr.rs:117:28 | LL | let _: *const i8 = transmute(ptr); | ^^^^^^^^^^^^^^ @@ -163,7 +163,7 @@ LL + let _: *const i8 = ptr.cast::(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:126:26 + --> tests/ui/transmute_ptr_to_ptr.rs:125:26 | LL | let _: *mut u8 = transmute(ptr); | ^^^^^^^^^^^^^^ @@ -175,7 +175,7 @@ LL + let _: *mut u8 = ptr as *mut u8; | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:128:28 + --> tests/ui/transmute_ptr_to_ptr.rs:127:28 | LL | let _: *const u8 = transmute(mut_ptr); | ^^^^^^^^^^^^^^^^^^ @@ -187,7 +187,7 @@ LL + let _: *const u8 = mut_ptr as *const u8; | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:136:26 + --> tests/ui/transmute_ptr_to_ptr.rs:135:26 | LL | let _: *mut u8 = transmute(ptr); | ^^^^^^^^^^^^^^ @@ -199,7 +199,7 @@ LL + let _: *mut u8 = ptr.cast_mut(); | error: transmute from a pointer to a pointer - --> tests/ui/transmute_ptr_to_ptr.rs:138:28 + --> tests/ui/transmute_ptr_to_ptr.rs:137:28 | LL | let _: *const u8 = transmute(mut_ptr); | ^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/transmute_ptr_to_ref.fixed b/src/tools/clippy/tests/ui/transmute_ptr_to_ref.fixed index 8de47031a4009..2044c3b14acb7 100644 --- a/src/tools/clippy/tests/ui/transmute_ptr_to_ref.fixed +++ b/src/tools/clippy/tests/ui/transmute_ptr_to_ref.fixed @@ -1,9 +1,5 @@ #![warn(clippy::transmute_ptr_to_ref)] -#![allow( - clippy::match_single_binding, - clippy::unnecessary_cast, - clippy::missing_transmute_annotations -)] +#![allow(clippy::missing_transmute_annotations, clippy::unnecessary_cast)] fn ptr_to_ref(p: *const T, m: *mut T, o: *const U, om: *mut U) { unsafe { diff --git a/src/tools/clippy/tests/ui/transmute_ptr_to_ref.rs b/src/tools/clippy/tests/ui/transmute_ptr_to_ref.rs index 52fe669de9355..3982a6929cf6e 100644 --- a/src/tools/clippy/tests/ui/transmute_ptr_to_ref.rs +++ b/src/tools/clippy/tests/ui/transmute_ptr_to_ref.rs @@ -1,9 +1,5 @@ #![warn(clippy::transmute_ptr_to_ref)] -#![allow( - clippy::match_single_binding, - clippy::unnecessary_cast, - clippy::missing_transmute_annotations -)] +#![allow(clippy::missing_transmute_annotations, clippy::unnecessary_cast)] fn ptr_to_ref(p: *const T, m: *mut T, o: *const U, om: *mut U) { unsafe { diff --git a/src/tools/clippy/tests/ui/transmute_ptr_to_ref.stderr b/src/tools/clippy/tests/ui/transmute_ptr_to_ref.stderr index c0f0ca916761d..138eb94405446 100644 --- a/src/tools/clippy/tests/ui/transmute_ptr_to_ref.stderr +++ b/src/tools/clippy/tests/ui/transmute_ptr_to_ref.stderr @@ -1,5 +1,5 @@ error: transmute from a pointer type (`*const T`) to a reference type (`&T`) - --> tests/ui/transmute_ptr_to_ref.rs:10:21 + --> tests/ui/transmute_ptr_to_ref.rs:6:21 | LL | let _: &T = std::mem::transmute(p); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*p` @@ -8,241 +8,241 @@ LL | let _: &T = std::mem::transmute(p); = help: to override `-D warnings` add `#[allow(clippy::transmute_ptr_to_ref)]` error: transmute from a pointer type (`*mut T`) to a reference type (`&mut T`) - --> tests/ui/transmute_ptr_to_ref.rs:14:25 + --> tests/ui/transmute_ptr_to_ref.rs:10:25 | LL | let _: &mut T = std::mem::transmute(m); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&mut *m` error: transmute from a pointer type (`*mut T`) to a reference type (`&T`) - --> tests/ui/transmute_ptr_to_ref.rs:18:21 + --> tests/ui/transmute_ptr_to_ref.rs:14:21 | LL | let _: &T = std::mem::transmute(m); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*m` error: transmute from a pointer type (`*mut T`) to a reference type (`&mut T`) - --> tests/ui/transmute_ptr_to_ref.rs:22:25 + --> tests/ui/transmute_ptr_to_ref.rs:18:25 | LL | let _: &mut T = std::mem::transmute(p as *mut T); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&mut *(p as *mut T)` error: transmute from a pointer type (`*const U`) to a reference type (`&T`) - --> tests/ui/transmute_ptr_to_ref.rs:26:21 + --> tests/ui/transmute_ptr_to_ref.rs:22:21 | LL | let _: &T = std::mem::transmute(o); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(o as *const T)` error: transmute from a pointer type (`*mut U`) to a reference type (`&mut T`) - --> tests/ui/transmute_ptr_to_ref.rs:30:25 + --> tests/ui/transmute_ptr_to_ref.rs:26:25 | LL | let _: &mut T = std::mem::transmute(om); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&mut *(om as *mut T)` error: transmute from a pointer type (`*mut U`) to a reference type (`&T`) - --> tests/ui/transmute_ptr_to_ref.rs:34:21 + --> tests/ui/transmute_ptr_to_ref.rs:30:21 | LL | let _: &T = std::mem::transmute(om); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(om as *const T)` error: transmute from a pointer type (`*const i32`) to a reference type (`&issue1231::Foo<'_, u8>`) - --> tests/ui/transmute_ptr_to_ref.rs:46:32 + --> tests/ui/transmute_ptr_to_ref.rs:42:32 | LL | let _: &Foo = unsafe { std::mem::transmute::<_, &Foo<_>>(raw) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*raw.cast::>()` error: transmute from a pointer type (`*const i32`) to a reference type (`&issue1231::Foo<'_, &u8>`) - --> tests/ui/transmute_ptr_to_ref.rs:49:33 + --> tests/ui/transmute_ptr_to_ref.rs:45:33 | LL | let _: &Foo<&u8> = unsafe { std::mem::transmute::<_, &Foo<&_>>(raw) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*raw.cast::>()` error: transmute from a pointer type (`*const i32`) to a reference type (`&u8`) - --> tests/ui/transmute_ptr_to_ref.rs:54:14 + --> tests/ui/transmute_ptr_to_ref.rs:50:14 | LL | unsafe { std::mem::transmute::<_, Bar>(raw) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(raw as *const u8)` error: transmute from a pointer type (`*const u32`) to a reference type (`&i32`) - --> tests/ui/transmute_ptr_to_ref.rs:82:23 + --> tests/ui/transmute_ptr_to_ref.rs:78:23 | LL | let _: &i32 = std::mem::transmute(w); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(w.0 as *const i32)` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:84:23 + --> tests/ui/transmute_ptr_to_ref.rs:80:23 | LL | let _: &u32 = std::mem::transmute(w); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*w.0` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:86:24 + --> tests/ui/transmute_ptr_to_ref.rs:82:24 | LL | let _: &&u32 = core::mem::transmute(x); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*x.ptr.cast::<&u32>()` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:91:17 + --> tests/ui/transmute_ptr_to_ref.rs:87:17 | LL | let _ = std::mem::transmute::<_, &u32>(w); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*w.0.cast::()` error: transmute from a pointer type (`*const [&str]`) to a reference type (`&[&str]`) - --> tests/ui/transmute_ptr_to_ref.rs:93:26 + --> tests/ui/transmute_ptr_to_ref.rs:89:26 | LL | let _: &[&str] = core::mem::transmute(v); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(v.0 as *const [&str])` error: transmute from a pointer type (`*const [i32]`) to a reference type (`&[i32]`) - --> tests/ui/transmute_ptr_to_ref.rs:95:17 + --> tests/ui/transmute_ptr_to_ref.rs:91:17 | LL | let _ = std::mem::transmute::<_, &[i32]>(u); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(u.0 as *const [i32])` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:97:24 + --> tests/ui/transmute_ptr_to_ref.rs:93:24 | LL | let _: &&u32 = std::mem::transmute(y); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*y.0.cast::<&u32>()` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:99:23 + --> tests/ui/transmute_ptr_to_ref.rs:95:23 | LL | let _: &u32 = std::mem::transmute(w + w); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(w + w).0` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:107:18 + --> tests/ui/transmute_ptr_to_ref.rs:103:18 | LL | 0 => std::mem::transmute(x), | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*x.cast::<&u32>()` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:109:18 + --> tests/ui/transmute_ptr_to_ref.rs:105:18 | LL | 1 => std::mem::transmute(y), | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*y.cast::<&u32>()` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:111:18 + --> tests/ui/transmute_ptr_to_ref.rs:107:18 | LL | 2 => std::mem::transmute::<_, &&'b u32>(x), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*x.cast::<&'b u32>()` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:113:18 + --> tests/ui/transmute_ptr_to_ref.rs:109:18 | LL | _ => std::mem::transmute::<_, &&'b u32>(y), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*y.cast::<&'b u32>()` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:124:23 + --> tests/ui/transmute_ptr_to_ref.rs:120:23 | LL | let _: &u32 = std::mem::transmute(a); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*a` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:126:23 + --> tests/ui/transmute_ptr_to_ref.rs:122:23 | LL | let _: &u32 = std::mem::transmute::<_, &u32>(a); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*a.cast::()` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:129:18 + --> tests/ui/transmute_ptr_to_ref.rs:125:18 | LL | 0 => std::mem::transmute(x), | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*x.cast::<&u32>()` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:131:18 + --> tests/ui/transmute_ptr_to_ref.rs:127:18 | LL | _ => std::mem::transmute::<_, &&'b u32>(x), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*x.cast::<&'b u32>()` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:142:23 + --> tests/ui/transmute_ptr_to_ref.rs:138:23 | LL | let _: &u32 = std::mem::transmute(a); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*a` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:144:23 + --> tests/ui/transmute_ptr_to_ref.rs:140:23 | LL | let _: &u32 = std::mem::transmute::<_, &u32>(a); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(a as *const u32)` error: transmute from a pointer type (`*const u32`) to a reference type (`&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:146:17 + --> tests/ui/transmute_ptr_to_ref.rs:142:17 | LL | let _ = std::mem::transmute::<_, &u32>(Ptr(a)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(Ptr(a).0 as *const u32)` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:149:18 + --> tests/ui/transmute_ptr_to_ref.rs:145:18 | LL | 0 => std::mem::transmute(x), | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(x as *const () as *const &u32)` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:151:18 + --> tests/ui/transmute_ptr_to_ref.rs:147:18 | LL | 1 => std::mem::transmute::<_, &&'b u32>(x), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(x as *const () as *const &'b u32)` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:153:18 + --> tests/ui/transmute_ptr_to_ref.rs:149:18 | LL | 2 => std::mem::transmute(y), | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(y.0 as *const () as *const &u32)` error: transmute from a pointer type (`*const &u32`) to a reference type (`&&u32`) - --> tests/ui/transmute_ptr_to_ref.rs:155:18 + --> tests/ui/transmute_ptr_to_ref.rs:151:18 | LL | _ => std::mem::transmute::<_, &&'b u32>(y), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(y.0 as *const () as *const &'b u32)` error: transmute from a pointer type (`*const [i32]`) to a reference type (`&[u32]`) - --> tests/ui/transmute_ptr_to_ref.rs:165:17 + --> tests/ui/transmute_ptr_to_ref.rs:161:17 | LL | let _ = core::mem::transmute::<_, &[u32]>(ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(ptr as *const [u32])` error: transmute from a pointer type (`*const [i32]`) to a reference type (`&[u32]`) - --> tests/ui/transmute_ptr_to_ref.rs:167:25 + --> tests/ui/transmute_ptr_to_ref.rs:163:25 | LL | let _: &[u32] = core::mem::transmute(ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(ptr as *const [u32])` error: transmute from a pointer type (`*const [&str]`) to a reference type (`&[&[u8]]`) - --> tests/ui/transmute_ptr_to_ref.rs:171:17 + --> tests/ui/transmute_ptr_to_ref.rs:167:17 | LL | let _ = core::mem::transmute::<_, &[&[u8]]>(a_s_ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(a_s_ptr as *const [&[u8]])` error: transmute from a pointer type (`*const [&str]`) to a reference type (`&[&[u8]]`) - --> tests/ui/transmute_ptr_to_ref.rs:173:27 + --> tests/ui/transmute_ptr_to_ref.rs:169:27 | LL | let _: &[&[u8]] = core::mem::transmute(a_s_ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(a_s_ptr as *const [&[u8]])` error: transmute from a pointer type (`*const [i32]`) to a reference type (`&[i32]`) - --> tests/ui/transmute_ptr_to_ref.rs:177:17 + --> tests/ui/transmute_ptr_to_ref.rs:173:17 | LL | let _ = core::mem::transmute::<_, &[i32]>(ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(ptr as *const [i32])` error: transmute from a pointer type (`*const [i32]`) to a reference type (`&[i32]`) - --> tests/ui/transmute_ptr_to_ref.rs:179:25 + --> tests/ui/transmute_ptr_to_ref.rs:175:25 | LL | let _: &[i32] = core::mem::transmute(ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*ptr` error: transmute from a pointer type (`*const [&str]`) to a reference type (`&[&str]`) - --> tests/ui/transmute_ptr_to_ref.rs:183:17 + --> tests/ui/transmute_ptr_to_ref.rs:179:17 | LL | let _ = core::mem::transmute::<_, &[&str]>(a_s_ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(a_s_ptr as *const [&str])` error: transmute from a pointer type (`*const [&str]`) to a reference type (`&[&str]`) - --> tests/ui/transmute_ptr_to_ref.rs:185:26 + --> tests/ui/transmute_ptr_to_ref.rs:181:26 | LL | let _: &[&str] = core::mem::transmute(a_s_ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(a_s_ptr as *const [&str])` diff --git a/src/tools/clippy/tests/ui/transmute_ref_to_ref.fixed b/src/tools/clippy/tests/ui/transmute_ref_to_ref.fixed index 0ec59ea810aed..e369e18d77ecd 100644 --- a/src/tools/clippy/tests/ui/transmute_ref_to_ref.fixed +++ b/src/tools/clippy/tests/ui/transmute_ref_to_ref.fixed @@ -1,5 +1,5 @@ -#![deny(clippy::transmute_ptr_to_ptr)] -#![allow(dead_code, clippy::missing_transmute_annotations, clippy::cast_slice_different_sizes)] +#![warn(clippy::transmute_ptr_to_ptr)] +#![allow(clippy::cast_slice_different_sizes)] fn main() { unsafe { diff --git a/src/tools/clippy/tests/ui/transmute_ref_to_ref.rs b/src/tools/clippy/tests/ui/transmute_ref_to_ref.rs index 78f3d1fe0bb24..35177b40fbca5 100644 --- a/src/tools/clippy/tests/ui/transmute_ref_to_ref.rs +++ b/src/tools/clippy/tests/ui/transmute_ref_to_ref.rs @@ -1,5 +1,5 @@ -#![deny(clippy::transmute_ptr_to_ptr)] -#![allow(dead_code, clippy::missing_transmute_annotations, clippy::cast_slice_different_sizes)] +#![warn(clippy::transmute_ptr_to_ptr)] +#![allow(clippy::cast_slice_different_sizes)] fn main() { unsafe { diff --git a/src/tools/clippy/tests/ui/transmute_ref_to_ref.stderr b/src/tools/clippy/tests/ui/transmute_ref_to_ref.stderr index 13ee64574f7b9..222a5d7e80710 100644 --- a/src/tools/clippy/tests/ui/transmute_ref_to_ref.stderr +++ b/src/tools/clippy/tests/ui/transmute_ref_to_ref.stderr @@ -4,11 +4,8 @@ error: transmute from a reference to a reference LL | let bools: &[bool] = unsafe { std::mem::transmute(single_u64) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(single_u64 as *const [u64] as *const [bool])` | -note: the lint level is defined here - --> tests/ui/transmute_ref_to_ref.rs:1:9 - | -LL | #![deny(clippy::transmute_ptr_to_ptr)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::transmute-ptr-to-ptr` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::transmute_ptr_to_ptr)]` error: transmute from a reference to a reference --> tests/ui/transmute_ref_to_ref.rs:11:33 diff --git a/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.fixed b/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.fixed index 3a1c75f168546..319d305b5c1c6 100644 --- a/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.fixed +++ b/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.fixed @@ -1,5 +1,5 @@ -#![deny(clippy::transmute_ptr_to_ptr)] -#![allow(dead_code, clippy::missing_transmute_annotations, clippy::cast_slice_different_sizes)] +#![warn(clippy::transmute_ptr_to_ptr)] +#![allow(clippy::cast_slice_different_sizes)] #![feature(lang_items)] #![no_std] diff --git a/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.rs b/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.rs index 7ed885bbbb07e..1f6d01b7e6ebc 100644 --- a/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.rs +++ b/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.rs @@ -1,5 +1,5 @@ -#![deny(clippy::transmute_ptr_to_ptr)] -#![allow(dead_code, clippy::missing_transmute_annotations, clippy::cast_slice_different_sizes)] +#![warn(clippy::transmute_ptr_to_ptr)] +#![allow(clippy::cast_slice_different_sizes)] #![feature(lang_items)] #![no_std] diff --git a/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.stderr b/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.stderr index 136a9b21fb9e9..7c9b37f319cca 100644 --- a/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.stderr +++ b/src/tools/clippy/tests/ui/transmute_ref_to_ref_no_std.stderr @@ -4,11 +4,8 @@ error: transmute from a reference to a reference LL | let bools: &[bool] = unsafe { core::mem::transmute(single_u64) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(single_u64 as *const [u64] as *const [bool])` | -note: the lint level is defined here - --> tests/ui/transmute_ref_to_ref_no_std.rs:1:9 - | -LL | #![deny(clippy::transmute_ptr_to_ptr)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::transmute-ptr-to-ptr` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::transmute_ptr_to_ptr)]` error: transmute from a reference to a reference --> tests/ui/transmute_ref_to_ref_no_std.rs:23:33 diff --git a/src/tools/clippy/tests/ui/transmute_undefined_repr.rs b/src/tools/clippy/tests/ui/transmute_undefined_repr.rs index a449d6a4302f8..4a92f24af7ce1 100644 --- a/src/tools/clippy/tests/ui/transmute_undefined_repr.rs +++ b/src/tools/clippy/tests/ui/transmute_undefined_repr.rs @@ -1,10 +1,5 @@ #![warn(clippy::transmute_undefined_repr)] -#![allow( - clippy::unit_arg, - clippy::transmute_ptr_to_ref, - clippy::useless_transmute, - clippy::missing_transmute_annotations -)] +#![expect(clippy::transmute_ptr_to_ref, clippy::unit_arg)] use core::any::TypeId; use core::ffi::c_void; diff --git a/src/tools/clippy/tests/ui/transmute_undefined_repr.stderr b/src/tools/clippy/tests/ui/transmute_undefined_repr.stderr index a259ef784c782..4e208843f374e 100644 --- a/src/tools/clippy/tests/ui/transmute_undefined_repr.stderr +++ b/src/tools/clippy/tests/ui/transmute_undefined_repr.stderr @@ -1,5 +1,5 @@ error: transmute from `Ty2` which has an undefined layout - --> tests/ui/transmute_undefined_repr.rs:34:33 + --> tests/ui/transmute_undefined_repr.rs:29:33 | LL | let _: Ty2C = transmute(value::>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,13 +8,13 @@ LL | let _: Ty2C = transmute(value::>()); = help: to override `-D warnings` add `#[allow(clippy::transmute_undefined_repr)]` error: transmute into `Ty2` which has an undefined layout - --> tests/ui/transmute_undefined_repr.rs:38:32 + --> tests/ui/transmute_undefined_repr.rs:33:32 | LL | let _: Ty2 = transmute(value::>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmute from `Ty>` to `Ty2`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:47:32 + --> tests/ui/transmute_undefined_repr.rs:42:32 | LL | let _: Ty2 = transmute(value::>>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -22,7 +22,7 @@ LL | let _: Ty2 = transmute(value::>>()); = note: two instances of the same generic type (`Ty2`) may have different layouts error: transmute from `Ty2` to `Ty>`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:51:36 + --> tests/ui/transmute_undefined_repr.rs:46:36 | LL | let _: Ty> = transmute(value::>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -30,7 +30,7 @@ LL | let _: Ty> = transmute(value::>()); = note: two instances of the same generic type (`Ty2`) may have different layouts error: transmute from `Ty<&Ty2>` to `&Ty2`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:58:33 + --> tests/ui/transmute_undefined_repr.rs:53:33 | LL | let _: &Ty2 = transmute(value::>>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -38,7 +38,7 @@ LL | let _: &Ty2 = transmute(value::>>()); = note: two instances of the same generic type (`Ty2`) may have different layouts error: transmute from `&Ty2` to `Ty<&Ty2>`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:62:37 + --> tests/ui/transmute_undefined_repr.rs:57:37 | LL | let _: Ty<&Ty2> = transmute(value::<&Ty2>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -46,7 +46,7 @@ LL | let _: Ty<&Ty2> = transmute(value::<&Ty2>()); = note: two instances of the same generic type (`Ty2`) may have different layouts error: transmute from `std::boxed::Box>` to `&mut Ty2`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:91:45 + --> tests/ui/transmute_undefined_repr.rs:86:45 | LL | let _: &'static mut Ty2 = transmute(value::>>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -54,7 +54,7 @@ LL | let _: &'static mut Ty2 = transmute(value::` to `std::boxed::Box>`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:95:37 + --> tests/ui/transmute_undefined_repr.rs:90:37 | LL | let _: Box> = transmute(value::<&'static mut Ty2>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -62,7 +62,7 @@ LL | let _: Box> = transmute(value::<&'static mut Ty2` which has an undefined layout - --> tests/ui/transmute_undefined_repr.rs:191:39 + --> tests/ui/transmute_undefined_repr.rs:186:39 | LL | let _: *const Ty2 = transmute(value::<*const Ty2C>>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -70,7 +70,7 @@ LL | let _: *const Ty2 = transmute(value::<*const Ty2C` has an undefined layout error: transmute from `*const Ty2` which has an undefined layout - --> tests/ui/transmute_undefined_repr.rs:195:50 + --> tests/ui/transmute_undefined_repr.rs:190:50 | LL | let _: *const Ty2C> = transmute(value::<*const Ty2>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -78,7 +78,7 @@ LL | let _: *const Ty2C> = transmute(value::<*const T = note: the contained type `Ty2` has an undefined layout error: transmute from `std::vec::Vec>` to `std::vec::Vec>`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:241:35 + --> tests/ui/transmute_undefined_repr.rs:236:35 | LL | let _: Vec> = transmute(value::>>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -86,7 +86,7 @@ LL | let _: Vec> = transmute(value::>>()); = note: two instances of the same generic type (`Vec`) may have different layouts error: transmute from `std::vec::Vec>` to `std::vec::Vec>`, both of which have an undefined layout - --> tests/ui/transmute_undefined_repr.rs:245:35 + --> tests/ui/transmute_undefined_repr.rs:240:35 | LL | let _: Vec> = transmute(value::>>()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.fixed b/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.fixed index f332e02a2d327..44a2db2aba64c 100644 --- a/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.fixed +++ b/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.fixed @@ -1,9 +1,11 @@ -#![warn(clippy::transmutes_expressible_as_ptr_casts)] -// These two warnings currently cover the cases transmutes_expressible_as_ptr_casts -// would otherwise be responsible for -#![warn(clippy::useless_transmute)] -#![warn(clippy::transmute_ptr_to_ptr)] -#![allow(unused, clippy::borrow_as_ptr, clippy::missing_transmute_annotations)] +// `clippy::transmutes_ptr_to_ptr` and `clippy::useless_transmute` currently cover the cases +// `transmutes_expressible_as_ptr_casts` would otherwise be responsible for +#![warn( + clippy::transmute_ptr_to_ptr, + clippy::transmutes_expressible_as_ptr_casts, + clippy::useless_transmute +)] +#![expect(clippy::missing_transmute_annotations)] #![allow(function_casts_as_integer)] use std::mem::{size_of, transmute}; @@ -92,7 +94,7 @@ fn issue_10449() { } // Pointers cannot be cast to integers in const contexts -#[allow( +#[expect( ptr_to_integer_transmute_in_consts, reason = "This is tested in the compiler test suite" )] diff --git a/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.rs b/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.rs index c29a42ddca53b..80d47017852b7 100644 --- a/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.rs +++ b/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.rs @@ -1,9 +1,11 @@ -#![warn(clippy::transmutes_expressible_as_ptr_casts)] -// These two warnings currently cover the cases transmutes_expressible_as_ptr_casts -// would otherwise be responsible for -#![warn(clippy::useless_transmute)] -#![warn(clippy::transmute_ptr_to_ptr)] -#![allow(unused, clippy::borrow_as_ptr, clippy::missing_transmute_annotations)] +// `clippy::transmutes_ptr_to_ptr` and `clippy::useless_transmute` currently cover the cases +// `transmutes_expressible_as_ptr_casts` would otherwise be responsible for +#![warn( + clippy::transmute_ptr_to_ptr, + clippy::transmutes_expressible_as_ptr_casts, + clippy::useless_transmute +)] +#![expect(clippy::missing_transmute_annotations)] #![allow(function_casts_as_integer)] use std::mem::{size_of, transmute}; @@ -92,7 +94,7 @@ fn issue_10449() { } // Pointers cannot be cast to integers in const contexts -#[allow( +#[expect( ptr_to_integer_transmute_in_consts, reason = "This is tested in the compiler test suite" )] diff --git a/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.stderr b/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.stderr index 5ddc3de6a039f..bc0f0109886ad 100644 --- a/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.stderr +++ b/src/tools/clippy/tests/ui/transmutes_expressible_as_ptr_casts.stderr @@ -1,5 +1,5 @@ error: transmute from a pointer to a pointer - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:20:38 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:22:38 | LL | let _ptr_i8_transmute = unsafe { transmute::<*const i32, *const i8>(ptr_i32) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let _ptr_i8_transmute = unsafe { ptr_i32.cast::() }; | error: transmute from a pointer to a pointer - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:27:46 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:29:46 | LL | let _ptr_to_unsized_transmute = unsafe { transmute::<*const [i32], *const [u32]>(slice_ptr) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + let _ptr_to_unsized_transmute = unsafe { slice_ptr as *const [u32] }; | error: transmute from `*const i32` to `usize` which could be expressed as a pointer cast instead - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:34:50 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:36:50 | LL | let _usize_from_int_ptr_transmute = unsafe { transmute::<*const i32, usize>(ptr_i32) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `ptr_i32 as usize` @@ -34,7 +34,7 @@ LL | let _usize_from_int_ptr_transmute = unsafe { transmute::<*const i32, us = help: to override `-D warnings` add `#[allow(clippy::transmutes_expressible_as_ptr_casts)]` error: transmute from a reference to a pointer - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:41:41 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:43:41 | LL | let _array_ptr_transmute = unsafe { transmute::<&[i32; 4], *const [i32; 4]>(array_ref) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `array_ref as *const [i32; 4]` @@ -43,31 +43,31 @@ LL | let _array_ptr_transmute = unsafe { transmute::<&[i32; 4], *const [i32; = help: to override `-D warnings` add `#[allow(clippy::useless_transmute)]` error: transmute from `fn(usize) -> u8` to `*const usize` which could be expressed as a pointer cast instead - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:50:41 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:52:41 | LL | let _usize_ptr_transmute = unsafe { transmute:: u8, *const usize>(foo) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `foo as *const usize` error: transmute from `fn(usize) -> u8` to `usize` which could be expressed as a pointer cast instead - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:55:49 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:57:49 | LL | let _usize_from_fn_ptr_transmute = unsafe { transmute:: u8, usize>(foo) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `foo as usize` error: transmute from `*const u32` to `usize` which could be expressed as a pointer cast instead - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:59:36 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:61:36 | LL | let _usize_from_ref = unsafe { transmute::<*const u32, usize>(&1u32) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&1u32 as *const u32 as usize` error: transmute from a reference to a pointer - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:71:14 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:73:14 | LL | unsafe { transmute::<&[i32; 1], *const u8>(in_param) } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `in_param as *const [i32; 1] as *const u8` error: transmute from `fn()` to `*const u8` which could be expressed as a pointer cast instead - --> tests/ui/transmutes_expressible_as_ptr_casts.rs:90:28 + --> tests/ui/transmutes_expressible_as_ptr_casts.rs:92:28 | LL | let _x: u8 = unsafe { *std::mem::transmute::(f) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(f as *const u8)` diff --git a/src/tools/clippy/tests/ui/transmuting_null.rs b/src/tools/clippy/tests/ui/transmuting_null.rs index c2de798ab3082..b6ff746e98224 100644 --- a/src/tools/clippy/tests/ui/transmuting_null.rs +++ b/src/tools/clippy/tests/ui/transmuting_null.rs @@ -1,9 +1,6 @@ -#![allow(dead_code)] #![warn(clippy::transmuting_null)] -#![allow(clippy::zero_ptr)] +#![expect(clippy::manual_dangling_ptr, clippy::zero_ptr)] #![allow(clippy::transmute_ptr_to_ref)] -#![allow(clippy::eq_op, clippy::missing_transmute_annotations)] -#![allow(clippy::manual_dangling_ptr)] // Easy to lint because these only span one line. fn one_liners() { diff --git a/src/tools/clippy/tests/ui/transmuting_null.stderr b/src/tools/clippy/tests/ui/transmuting_null.stderr index 3c6c28f31d0db..c19dfcf9926b5 100644 --- a/src/tools/clippy/tests/ui/transmuting_null.stderr +++ b/src/tools/clippy/tests/ui/transmuting_null.stderr @@ -1,5 +1,5 @@ error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:11:23 + --> tests/ui/transmuting_null.rs:8:23 | LL | let _: &u64 = std::mem::transmute(0 as *const u64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,43 +8,43 @@ LL | let _: &u64 = std::mem::transmute(0 as *const u64); = help: to override `-D warnings` add `#[allow(clippy::transmuting_null)]` error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:14:23 + --> tests/ui/transmuting_null.rs:11:23 | LL | let _: &u64 = std::mem::transmute(std::ptr::null::()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:25:23 + --> tests/ui/transmuting_null.rs:22:23 | LL | let _: &u64 = std::mem::transmute(ZPTR); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:35:23 + --> tests/ui/transmuting_null.rs:32:23 | LL | let _: &u64 = std::mem::transmute(u64::MIN as *const u64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:42:23 + --> tests/ui/transmuting_null.rs:39:23 | LL | let _: &u64 = std::mem::transmute({ 0 as *const u64 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:45:23 + --> tests/ui/transmuting_null.rs:42:23 | LL | let _: &u64 = std::mem::transmute(const { u64::MIN as *const u64 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:52:23 + --> tests/ui/transmuting_null.rs:49:23 | LL | let _: &u64 = std::mem::transmute(std::ptr::without_provenance::(0)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: transmuting a known null pointer into a reference - --> tests/ui/transmuting_null.rs:55:23 + --> tests/ui/transmuting_null.rs:52:23 | LL | let _: &u64 = std::mem::transmute(std::ptr::without_provenance_mut::(0)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/trim_split_whitespace.fixed b/src/tools/clippy/tests/ui/trim_split_whitespace.fixed index 434e91b7d9530..b5f3dd0ffde0b 100644 --- a/src/tools/clippy/tests/ui/trim_split_whitespace.fixed +++ b/src/tools/clippy/tests/ui/trim_split_whitespace.fixed @@ -1,5 +1,5 @@ #![warn(clippy::trim_split_whitespace)] -#![allow(clippy::let_unit_value)] +#![expect(clippy::let_unit_value)] struct Custom; impl Custom { @@ -39,7 +39,6 @@ impl std::ops::Deref for DerefStrAndCustomSplit { } } impl DerefStrAndCustomSplit { - #[allow(dead_code)] fn split_whitespace(self) {} } diff --git a/src/tools/clippy/tests/ui/trim_split_whitespace.rs b/src/tools/clippy/tests/ui/trim_split_whitespace.rs index b939ecdfba854..80a113367f086 100644 --- a/src/tools/clippy/tests/ui/trim_split_whitespace.rs +++ b/src/tools/clippy/tests/ui/trim_split_whitespace.rs @@ -1,5 +1,5 @@ #![warn(clippy::trim_split_whitespace)] -#![allow(clippy::let_unit_value)] +#![expect(clippy::let_unit_value)] struct Custom; impl Custom { @@ -39,7 +39,6 @@ impl std::ops::Deref for DerefStrAndCustomSplit { } } impl DerefStrAndCustomSplit { - #[allow(dead_code)] fn split_whitespace(self) {} } diff --git a/src/tools/clippy/tests/ui/trim_split_whitespace.stderr b/src/tools/clippy/tests/ui/trim_split_whitespace.stderr index f242dd8021156..9ad0be5d41818 100644 --- a/src/tools/clippy/tests/ui/trim_split_whitespace.stderr +++ b/src/tools/clippy/tests/ui/trim_split_whitespace.stderr @@ -1,5 +1,5 @@ error: found call to `str::trim` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:61:23 + --> tests/ui/trim_split_whitespace.rs:60:23 | LL | let _ = " A B C ".trim().split_whitespace(); // should trigger lint | ^^^^^^^ help: remove `trim()` @@ -8,43 +8,43 @@ LL | let _ = " A B C ".trim().split_whitespace(); // should trigger lint = help: to override `-D warnings` add `#[allow(clippy::trim_split_whitespace)]` error: found call to `str::trim_start` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:64:23 + --> tests/ui/trim_split_whitespace.rs:63:23 | LL | let _ = " A B C ".trim_start().split_whitespace(); // should trigger lint | ^^^^^^^^^^^^^ help: remove `trim_start()` error: found call to `str::trim_end` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:67:23 + --> tests/ui/trim_split_whitespace.rs:66:23 | LL | let _ = " A B C ".trim_end().split_whitespace(); // should trigger lint | ^^^^^^^^^^^ help: remove `trim_end()` error: found call to `str::trim` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:72:37 + --> tests/ui/trim_split_whitespace.rs:71:37 | LL | let _ = (" A B C ").to_string().trim().split_whitespace(); // should trigger lint | ^^^^^^^ help: remove `trim()` error: found call to `str::trim_start` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:75:37 + --> tests/ui/trim_split_whitespace.rs:74:37 | LL | let _ = (" A B C ").to_string().trim_start().split_whitespace(); // should trigger lint | ^^^^^^^^^^^^^ help: remove `trim_start()` error: found call to `str::trim_end` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:78:37 + --> tests/ui/trim_split_whitespace.rs:77:37 | LL | let _ = (" A B C ").to_string().trim_end().split_whitespace(); // should trigger lint | ^^^^^^^^^^^ help: remove `trim_end()` error: found call to `str::trim` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:87:15 + --> tests/ui/trim_split_whitespace.rs:86:15 | LL | let _ = s.trim().split_whitespace(); // should trigger lint | ^^^^^^^ help: remove `trim()` error: found call to `str::trim` before `str::split_whitespace` - --> tests/ui/trim_split_whitespace.rs:97:15 + --> tests/ui/trim_split_whitespace.rs:96:15 | LL | let _ = s.trim().split_whitespace(); // should trigger lint | ^^^^^^^ help: remove `trim()` diff --git a/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.fixed b/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.fixed index 1a07f119398aa..637941ce950f5 100644 --- a/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.fixed +++ b/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.fixed @@ -1,14 +1,8 @@ //@normalize-stderr-test: "\(\d+ byte\)" -> "(N byte)" //@normalize-stderr-test: "\(limit: \d+ byte\)" -> "(limit: N byte)" -#![deny(clippy::trivially_copy_pass_by_ref)] -#![allow( - clippy::disallowed_names, - clippy::extra_unused_lifetimes, - clippy::needless_lifetimes, - clippy::needless_pass_by_ref_mut, - clippy::redundant_field_names, - clippy::uninlined_format_args -)] +#![warn(clippy::trivially_copy_pass_by_ref)] +#![allow(clippy::extra_unused_lifetimes)] +#![expect(clippy::disallowed_names, clippy::needless_lifetimes)] #[derive(Copy, Clone)] struct Foo(u32); diff --git a/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.rs b/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.rs index 07b1842bbf856..9cdfc32ec03ce 100644 --- a/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.rs +++ b/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.rs @@ -1,14 +1,8 @@ //@normalize-stderr-test: "\(\d+ byte\)" -> "(N byte)" //@normalize-stderr-test: "\(limit: \d+ byte\)" -> "(limit: N byte)" -#![deny(clippy::trivially_copy_pass_by_ref)] -#![allow( - clippy::disallowed_names, - clippy::extra_unused_lifetimes, - clippy::needless_lifetimes, - clippy::needless_pass_by_ref_mut, - clippy::redundant_field_names, - clippy::uninlined_format_args -)] +#![warn(clippy::trivially_copy_pass_by_ref)] +#![allow(clippy::extra_unused_lifetimes)] +#![expect(clippy::disallowed_names, clippy::needless_lifetimes)] #[derive(Copy, Clone)] struct Foo(u32); diff --git a/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.stderr b/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.stderr index 36247d3fe0b17..0a8bb545b5ddb 100644 --- a/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.stderr +++ b/src/tools/clippy/tests/ui/trivially_copy_pass_by_ref.stderr @@ -1,113 +1,110 @@ error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:54:11 + --> tests/ui/trivially_copy_pass_by_ref.rs:48:11 | LL | fn bad(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `u32` | -note: the lint level is defined here - --> tests/ui/trivially_copy_pass_by_ref.rs:3:9 - | -LL | #![deny(clippy::trivially_copy_pass_by_ref)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::trivially-copy-pass-by-ref` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::trivially_copy_pass_by_ref)]` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:54:20 + --> tests/ui/trivially_copy_pass_by_ref.rs:48:20 | LL | fn bad(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Foo` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:54:29 + --> tests/ui/trivially_copy_pass_by_ref.rs:48:29 | LL | fn bad(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Baz` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:64:12 + --> tests/ui/trivially_copy_pass_by_ref.rs:58:12 | LL | fn bad(&self, x: &u32, y: &Foo, z: &Baz) {} | ^^^^^ help: consider passing by value instead: `self` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:64:22 + --> tests/ui/trivially_copy_pass_by_ref.rs:58:22 | LL | fn bad(&self, x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `u32` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:64:31 + --> tests/ui/trivially_copy_pass_by_ref.rs:58:31 | LL | fn bad(&self, x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Foo` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:64:40 + --> tests/ui/trivially_copy_pass_by_ref.rs:58:40 | LL | fn bad(&self, x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Baz` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:70:16 + --> tests/ui/trivially_copy_pass_by_ref.rs:64:16 | LL | fn bad2(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `u32` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:70:25 + --> tests/ui/trivially_copy_pass_by_ref.rs:64:25 | LL | fn bad2(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Foo` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:70:34 + --> tests/ui/trivially_copy_pass_by_ref.rs:64:34 | LL | fn bad2(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Baz` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:75:35 + --> tests/ui/trivially_copy_pass_by_ref.rs:69:35 | LL | fn bad_issue7518(self, other: &Self) {} | ^^^^^ help: consider passing by value instead: `Self` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:88:16 + --> tests/ui/trivially_copy_pass_by_ref.rs:82:16 | LL | fn bad2(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `u32` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:88:25 + --> tests/ui/trivially_copy_pass_by_ref.rs:82:25 | LL | fn bad2(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Foo` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:88:34 + --> tests/ui/trivially_copy_pass_by_ref.rs:82:34 | LL | fn bad2(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `Baz` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:95:33 + --> tests/ui/trivially_copy_pass_by_ref.rs:89:33 | LL | fn trait_method(&self, foo: &Foo); | ^^^^ help: consider passing by value instead: `Foo` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:133:21 + --> tests/ui/trivially_copy_pass_by_ref.rs:127:21 | LL | fn foo_never(x: &i32) { | ^^^^ help: consider passing by value instead: `i32` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:139:15 + --> tests/ui/trivially_copy_pass_by_ref.rs:133:15 | LL | fn foo(x: &i32) { | ^^^^ help: consider passing by value instead: `i32` error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> tests/ui/trivially_copy_pass_by_ref.rs:165:36 + --> tests/ui/trivially_copy_pass_by_ref.rs:159:36 | LL | fn unrelated_lifetimes<'a, 'b>(_x: &'a u32, y: &'b u32) -> &'b u32 { | ^^^^^^^ help: consider passing by value instead: `u32` diff --git a/src/tools/clippy/tests/ui/try_err.fixed b/src/tools/clippy/tests/ui/try_err.fixed index bec366f4fd604..415cf50b1ddaa 100644 --- a/src/tools/clippy/tests/ui/try_err.fixed +++ b/src/tools/clippy/tests/ui/try_err.fixed @@ -1,11 +1,7 @@ //@aux-build:proc_macros.rs #![feature(try_blocks)] -#![deny(clippy::try_err)] -#![allow( - clippy::unnecessary_wraps, - clippy::needless_question_mark, - clippy::needless_return_with_question_mark -)] +#![warn(clippy::try_err)] +#![allow(clippy::needless_return_with_question_mark)] extern crate proc_macros; use proc_macros::{external, inline_macros}; diff --git a/src/tools/clippy/tests/ui/try_err.rs b/src/tools/clippy/tests/ui/try_err.rs index 9c10acd2ce0ad..362d1a63b82c8 100644 --- a/src/tools/clippy/tests/ui/try_err.rs +++ b/src/tools/clippy/tests/ui/try_err.rs @@ -1,11 +1,7 @@ //@aux-build:proc_macros.rs #![feature(try_blocks)] -#![deny(clippy::try_err)] -#![allow( - clippy::unnecessary_wraps, - clippy::needless_question_mark, - clippy::needless_return_with_question_mark -)] +#![warn(clippy::try_err)] +#![allow(clippy::needless_return_with_question_mark)] extern crate proc_macros; use proc_macros::{external, inline_macros}; diff --git a/src/tools/clippy/tests/ui/try_err.stderr b/src/tools/clippy/tests/ui/try_err.stderr index 3ca51e9d88915..0b4c5ec0c5a17 100644 --- a/src/tools/clippy/tests/ui/try_err.stderr +++ b/src/tools/clippy/tests/ui/try_err.stderr @@ -1,35 +1,32 @@ error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:22:9 + --> tests/ui/try_err.rs:18:9 | LL | Err(err)?; | ^^^^^^^^^ help: try: `return Err(err)` | -note: the lint level is defined here - --> tests/ui/try_err.rs:3:9 - | -LL | #![deny(clippy::try_err)] - | ^^^^^^^^^^^^^^^ + = note: `-D clippy::try-err` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::try_err)]` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:33:9 + --> tests/ui/try_err.rs:29:9 | LL | Err(err)?; | ^^^^^^^^^ help: try: `return Err(err.into())` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:54:17 + --> tests/ui/try_err.rs:50:17 | LL | Err(err)?; | ^^^^^^^^^ help: try: `return Err(err)` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:74:17 + --> tests/ui/try_err.rs:70:17 | LL | Err(err)?; | ^^^^^^^^^ help: try: `return Err(err.into())` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:95:23 + --> tests/ui/try_err.rs:91:23 | LL | Err(_) => Err(1)?, | ^^^^^^^ help: try: `return Err(1)` @@ -37,7 +34,7 @@ LL | Err(_) => Err(1)?, = note: this error originates in the macro `__inline_mac_fn_calling_macro` (in Nightly builds, run with -Z macro-backtrace for more info) error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:103:23 + --> tests/ui/try_err.rs:99:23 | LL | Err(_) => Err(inline!(1))?, | ^^^^^^^^^^^^^^^^ help: try: `return Err(inline!(1))` @@ -45,31 +42,31 @@ LL | Err(_) => Err(inline!(1))?, = note: this error originates in the macro `__inline_mac_fn_calling_macro` (in Nightly builds, run with -Z macro-backtrace for more info) error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:124:9 + --> tests/ui/try_err.rs:120:9 | LL | Err(inline!(inline!(String::from("aasdfasdfasdfa"))))?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `return Err(inline!(inline!(String::from("aasdfasdfasdfa"))))` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:132:9 + --> tests/ui/try_err.rs:128:9 | LL | Err(io::ErrorKind::WriteZero)? | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:135:9 + --> tests/ui/try_err.rs:131:9 | LL | Err(io::Error::new(io::ErrorKind::InvalidInput, "error"))? | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidInput, "error")))` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:144:9 + --> tests/ui/try_err.rs:140:9 | LL | Err(io::ErrorKind::NotFound)? | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `return Poll::Ready(Some(Err(io::ErrorKind::NotFound.into())))` error: returning an `Err(_)` with the `?` operator - --> tests/ui/try_err.rs:154:16 + --> tests/ui/try_err.rs:150:16 | LL | return Err(42)?; | ^^^^^^^^ help: try: `Err(42)` diff --git a/src/tools/clippy/tests/ui/tuple_array_conversions.rs b/src/tools/clippy/tests/ui/tuple_array_conversions.rs index 599019dca031d..40b1720af1299 100644 --- a/src/tools/clippy/tests/ui/tuple_array_conversions.rs +++ b/src/tools/clippy/tests/ui/tuple_array_conversions.rs @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs -#![allow(clippy::no_effect, clippy::useless_vec, unused)] #![warn(clippy::tuple_array_conversions)] +#![expect(clippy::no_effect, clippy::useless_vec)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/type_complexity.rs b/src/tools/clippy/tests/ui/type_complexity.rs index 9d145516d6107..fcc4e7757feb4 100644 --- a/src/tools/clippy/tests/ui/type_complexity.rs +++ b/src/tools/clippy/tests/ui/type_complexity.rs @@ -1,5 +1,5 @@ #![feature(associated_type_defaults)] -#![allow(clippy::needless_pass_by_value, clippy::vec_box, clippy::useless_vec)] +#![warn(clippy::type_complexity)] type Alias = Vec>>; // no warning here diff --git a/src/tools/clippy/tests/ui/type_repetition_in_bounds.rs b/src/tools/clippy/tests/ui/type_repetition_in_bounds.rs index e75678d5fd93e..b1041e3053430 100644 --- a/src/tools/clippy/tests/ui/type_repetition_in_bounds.rs +++ b/src/tools/clippy/tests/ui/type_repetition_in_bounds.rs @@ -1,9 +1,5 @@ -#![deny(clippy::type_repetition_in_bounds)] -#![allow( - clippy::extra_unused_type_parameters, - clippy::multiple_bound_locations, - clippy::needless_maybe_sized -)] +#![warn(clippy::type_repetition_in_bounds)] +#![expect(clippy::multiple_bound_locations, clippy::needless_maybe_sized)] use serde::Deserialize; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; diff --git a/src/tools/clippy/tests/ui/type_repetition_in_bounds.stderr b/src/tools/clippy/tests/ui/type_repetition_in_bounds.stderr index de1b14da1985f..562d486a82982 100644 --- a/src/tools/clippy/tests/ui/type_repetition_in_bounds.stderr +++ b/src/tools/clippy/tests/ui/type_repetition_in_bounds.stderr @@ -1,18 +1,15 @@ error: type `T` has already been used as a bound predicate - --> tests/ui/type_repetition_in_bounds.rs:14:5 + --> tests/ui/type_repetition_in_bounds.rs:10:5 | LL | T: Clone, | ^^^^^^^^ | = help: consider combining the bounds: `T: Copy + Clone` -note: the lint level is defined here - --> tests/ui/type_repetition_in_bounds.rs:1:9 - | -LL | #![deny(clippy::type_repetition_in_bounds)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::type-repetition-in-bounds` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::type_repetition_in_bounds)]` error: type `Self` has already been used as a bound predicate - --> tests/ui/type_repetition_in_bounds.rs:32:5 + --> tests/ui/type_repetition_in_bounds.rs:28:5 | LL | Self: Copy + Default + Ord, | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -20,7 +17,7 @@ LL | Self: Copy + Default + Ord, = help: consider combining the bounds: `Self: Clone + Copy + Default + Ord` error: type `T` has already been used as a bound predicate - --> tests/ui/type_repetition_in_bounds.rs:107:5 + --> tests/ui/type_repetition_in_bounds.rs:103:5 | LL | T: Clone, | ^^^^^^^^ @@ -28,7 +25,7 @@ LL | T: Clone, = help: consider combining the bounds: `T: ?Sized + Clone` error: type `T` has already been used as a bound predicate - --> tests/ui/type_repetition_in_bounds.rs:113:5 + --> tests/ui/type_repetition_in_bounds.rs:109:5 | LL | T: ?Sized, | ^^^^^^^^^ @@ -36,7 +33,7 @@ LL | T: ?Sized, = help: consider combining the bounds: `T: Clone + ?Sized` error: type `T` has already been used as a bound predicate - --> tests/ui/type_repetition_in_bounds.rs:139:9 + --> tests/ui/type_repetition_in_bounds.rs:135:9 | LL | T: Trait, Box<[String]>, bool> + 'static, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -44,7 +41,7 @@ LL | T: Trait, Box<[String]>, bool> + 'static, = help: consider combining the bounds: `T: ?Sized + Trait, Box<[String]>, bool> + 'static` error: type `K` has already been used as a bound predicate - --> tests/ui/type_repetition_in_bounds.rs:148:5 + --> tests/ui/type_repetition_in_bounds.rs:144:5 | LL | K: Clone, | ^^^^^^^^ @@ -52,7 +49,7 @@ LL | K: Clone, = help: consider combining the bounds: `K: 'a + Clone` error: type `Vec` has already been used as a bound predicate - --> tests/ui/type_repetition_in_bounds.rs:157:5 + --> tests/ui/type_repetition_in_bounds.rs:153:5 | LL | Vec: Clone, | ^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unconditional_recursion.rs b/src/tools/clippy/tests/ui/unconditional_recursion.rs index 20b4198d63926..fb4f7b5035785 100644 --- a/src/tools/clippy/tests/ui/unconditional_recursion.rs +++ b/src/tools/clippy/tests/ui/unconditional_recursion.rs @@ -1,9 +1,9 @@ #![warn(clippy::unconditional_recursion)] -#![allow( - clippy::partialeq_ne_impl, +#![expect( clippy::default_constructed_unit_structs, + clippy::needless_lifetimes, clippy::only_used_in_recursion, - clippy::needless_lifetimes + clippy::partialeq_ne_impl )] enum Foo { diff --git a/src/tools/clippy/tests/ui/unicode.fixed b/src/tools/clippy/tests/ui/unicode.fixed index 0a49b17005828..40e062955ef39 100644 --- a/src/tools/clippy/tests/ui/unicode.fixed +++ b/src/tools/clippy/tests/ui/unicode.fixed @@ -1,7 +1,6 @@ -#![allow(dead_code)] - -#[warn(clippy::invisible_characters)] fn zero() { + #![warn(clippy::invisible_characters)] + print!("Here >\u{200B}< is a ZWS, and \u{200B}another"); //~^ invisible_characters print!("This\u{200B}is\u{200B}fine"); @@ -13,15 +12,16 @@ fn zero() { print!("This\u{2060}is\u{2060}fine"); } -#[warn(clippy::unicode_not_nfc)] fn canon() { + #![warn(clippy::unicode_not_nfc)] + print!("̀àh?"); //~^ unicode_not_nfc print!("a\u{0300}h?"); // also ok } mod non_ascii_literal { - #![deny(clippy::non_ascii_literal)] + #![warn(clippy::non_ascii_literal)] fn uni() { print!("\u{dc}ben!"); @@ -43,8 +43,6 @@ mod non_ascii_literal { } mod issue_8263 { - #![deny(clippy::non_ascii_literal)] - // Re-allow for a single test #[test] #[allow(clippy::non_ascii_literal)] @@ -81,7 +79,7 @@ mod ascii_value_from_non_ascii_snippet { // The reverse: `file!()` produces an ASCII value (the file path), but the // literal's span covers the whole macro invocation, so the snippet is // non-ASCII and the lint must fire. Checking the value would miss it. - #![deny(clippy::non_ascii_literal)] + #![warn(clippy::non_ascii_literal)] macro_rules! with_location { ($($arg:tt)*) => { diff --git a/src/tools/clippy/tests/ui/unicode.rs b/src/tools/clippy/tests/ui/unicode.rs index f1a1ab290aecc..876a3fee201eb 100644 --- a/src/tools/clippy/tests/ui/unicode.rs +++ b/src/tools/clippy/tests/ui/unicode.rs @@ -1,7 +1,6 @@ -#![allow(dead_code)] - -#[warn(clippy::invisible_characters)] fn zero() { + #![warn(clippy::invisible_characters)] + print!("Here >​< is a ZWS, and ​another"); //~^ invisible_characters print!("This\u{200B}is\u{200B}fine"); @@ -13,15 +12,16 @@ fn zero() { print!("This\u{2060}is\u{2060}fine"); } -#[warn(clippy::unicode_not_nfc)] fn canon() { + #![warn(clippy::unicode_not_nfc)] + print!("̀àh?"); //~^ unicode_not_nfc print!("a\u{0300}h?"); // also ok } mod non_ascii_literal { - #![deny(clippy::non_ascii_literal)] + #![warn(clippy::non_ascii_literal)] fn uni() { print!("Üben!"); @@ -43,8 +43,6 @@ mod non_ascii_literal { } mod issue_8263 { - #![deny(clippy::non_ascii_literal)] - // Re-allow for a single test #[test] #[allow(clippy::non_ascii_literal)] @@ -81,7 +79,7 @@ mod ascii_value_from_non_ascii_snippet { // The reverse: `file!()` produces an ASCII value (the file path), but the // literal's span covers the whole macro invocation, so the snippet is // non-ASCII and the lint must fire. Checking the value would miss it. - #![deny(clippy::non_ascii_literal)] + #![warn(clippy::non_ascii_literal)] macro_rules! with_location { ($($arg:tt)*) => { diff --git a/src/tools/clippy/tests/ui/unicode.stderr b/src/tools/clippy/tests/ui/unicode.stderr index 32b0933913008..ea6d90f3c7f3c 100644 --- a/src/tools/clippy/tests/ui/unicode.stderr +++ b/src/tools/clippy/tests/ui/unicode.stderr @@ -1,5 +1,5 @@ error: invisible character detected - --> tests/ui/unicode.rs:5:12 + --> tests/ui/unicode.rs:4:12 | LL | print!("Here >​< is a ZWS, and ​another"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing the string with: `"Here >\u{200B}< is a ZWS, and \u{200B}another"` @@ -8,13 +8,13 @@ LL | print!("Here >​< is a ZWS, and ​another"); = help: to override `-D warnings` add `#[allow(clippy::invisible_characters)]` error: invisible character detected - --> tests/ui/unicode.rs:8:12 + --> tests/ui/unicode.rs:7:12 | LL | print!("Here >­< is a SHY, and ­another"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing the string with: `"Here >\u{AD}< is a SHY, and \u{AD}another"` error: invisible character detected - --> tests/ui/unicode.rs:11:12 + --> tests/ui/unicode.rs:10:12 | LL | print!("Here >⁠< is a WJ, and ⁠another"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing the string with: `"Here >\u{2060}< is a WJ, and \u{2060}another"` @@ -34,11 +34,8 @@ error: literal non-ASCII character detected LL | print!("Üben!"); | ^^^^^^^ help: consider replacing the string with: `"\u{dc}ben!"` | -note: the lint level is defined here - --> tests/ui/unicode.rs:24:13 - | -LL | #![deny(clippy::non_ascii_literal)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::non-ascii-literal` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::non_ascii_literal)]` error: literal non-ASCII character detected --> tests/ui/unicode.rs:34:36 @@ -53,28 +50,16 @@ LL | const _FULL_BLOCK: char = '▰'; | ^^^ help: consider replacing the string with: `'\u{25b0}'` error: literal non-ASCII character detected - --> tests/ui/unicode.rs:57:21 + --> tests/ui/unicode.rs:55:21 | LL | let _ = "悲しいかな、ここに日本語を書くことはできない。"; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing the string with: `"\u{60b2}\u{3057}\u{3044}\u{304b}\u{306a}\u{3001}\u{3053}\u{3053}\u{306b}\u{65e5}\u{672c}\u{8a9e}\u{3092}\u{66f8}\u{304f}\u{3053}\u{3068}\u{306f}\u{3067}\u{304d}\u{306a}\u{3044}\u{3002}"` - | -note: the lint level is defined here - --> tests/ui/unicode.rs:46:17 - | -LL | #![deny(clippy::non_ascii_literal)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: literal non-ASCII character detected - --> tests/ui/unicode.rs:93:9 + --> tests/ui/unicode.rs:91:9 | LL | with_location!("héllo"); | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider replacing the string with: `with_location!("h\u{e9}llo")` - | -note: the lint level is defined here - --> tests/ui/unicode.rs:84:13 - | -LL | #![deny(clippy::non_ascii_literal)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 9 previous errors diff --git a/src/tools/clippy/tests/ui/uninhabited_references.rs b/src/tools/clippy/tests/ui/uninhabited_references.rs index 9b3616ad51871..2351fb6a2c4e6 100644 --- a/src/tools/clippy/tests/ui/uninhabited_references.rs +++ b/src/tools/clippy/tests/ui/uninhabited_references.rs @@ -1,5 +1,4 @@ #![warn(clippy::uninhabited_references)] -#![allow(clippy::missing_transmute_annotations)] #![feature(never_type)] fn ret_uninh_ref() -> &'static std::convert::Infallible { diff --git a/src/tools/clippy/tests/ui/uninhabited_references.stderr b/src/tools/clippy/tests/ui/uninhabited_references.stderr index ac05ab5bb4d40..0d29816fc51d9 100644 --- a/src/tools/clippy/tests/ui/uninhabited_references.stderr +++ b/src/tools/clippy/tests/ui/uninhabited_references.stderr @@ -1,5 +1,5 @@ error: dereferencing a reference to an uninhabited type would be undefined behavior - --> tests/ui/uninhabited_references.rs:5:23 + --> tests/ui/uninhabited_references.rs:4:23 | LL | fn ret_uninh_ref() -> &'static std::convert::Infallible { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | fn ret_uninh_ref() -> &'static std::convert::Infallible { = help: to override `-D warnings` add `#[allow(clippy::uninhabited_references)]` error: dereferencing a reference to an uninhabited type would be undefined behavior - --> tests/ui/uninhabited_references.rs:12:30 + --> tests/ui/uninhabited_references.rs:11:30 | LL | fn $name(x: &$ty) -> &$ty { | ^^^^ @@ -19,7 +19,7 @@ LL | ret_something!(id_never, !); = note: this error originates in the macro `ret_something` (in Nightly builds, run with -Z macro-backtrace for more info) error: dereferencing a reference to an uninhabited type is undefined behavior - --> tests/ui/uninhabited_references.rs:14:14 + --> tests/ui/uninhabited_references.rs:13:14 | LL | &*x | ^^ @@ -30,7 +30,7 @@ LL | ret_something!(id_never, !); = note: this error originates in the macro `ret_something` (in Nightly builds, run with -Z macro-backtrace for more info) error: dereferencing a reference to an uninhabited type is undefined behavior - --> tests/ui/uninhabited_references.rs:25:13 + --> tests/ui/uninhabited_references.rs:24:13 | LL | let _ = *x; | ^^ diff --git a/src/tools/clippy/tests/ui/uninit.rs b/src/tools/clippy/tests/ui/uninit_assumed_init.rs similarity index 96% rename from src/tools/clippy/tests/ui/uninit.rs rename to src/tools/clippy/tests/ui/uninit_assumed_init.rs index f74248c8aea80..32d5a8cfc67cc 100644 --- a/src/tools/clippy/tests/ui/uninit.rs +++ b/src/tools/clippy/tests/ui/uninit_assumed_init.rs @@ -1,5 +1,6 @@ #![feature(stmt_expr_attributes)] -#![allow(clippy::let_unit_value, invalid_value)] +#![warn(clippy::uninit_assumed_init)] +#![expect(invalid_value)] use std::mem::MaybeUninit; diff --git a/src/tools/clippy/tests/ui/uninit.stderr b/src/tools/clippy/tests/ui/uninit_assumed_init.stderr similarity index 70% rename from src/tools/clippy/tests/ui/uninit.stderr rename to src/tools/clippy/tests/ui/uninit_assumed_init.stderr index d6f54dd61ca0e..3531d4eb2c389 100644 --- a/src/tools/clippy/tests/ui/uninit.stderr +++ b/src/tools/clippy/tests/ui/uninit_assumed_init.stderr @@ -1,19 +1,20 @@ error: this call for this type may be undefined behavior - --> tests/ui/uninit.rs:12:29 + --> tests/ui/uninit_assumed_init.rs:13:29 | LL | let _: usize = unsafe { MaybeUninit::uninit().assume_init() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: `#[deny(clippy::uninit_assumed_init)]` on by default + = note: `-D clippy::uninit-assumed-init` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::uninit_assumed_init)]` error: this call for this type may be undefined behavior - --> tests/ui/uninit.rs:34:29 + --> tests/ui/uninit_assumed_init.rs:35:29 | LL | let _: usize = unsafe { MaybeUninit::uninit().assume_init() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: this call for this type may be undefined behavior - --> tests/ui/uninit.rs:43:29 + --> tests/ui/uninit_assumed_init.rs:44:29 | LL | let _: T = unsafe { MaybeUninit::uninit().assume_init() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/uninlined_format_args.fixed b/src/tools/clippy/tests/ui/uninlined_format_args.fixed index 2e84bbc106ac8..8d4de4f5bda25 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args.fixed +++ b/src/tools/clippy/tests/ui/uninlined_format_args.fixed @@ -1,9 +1,8 @@ //@aux-build:proc_macros.rs #![warn(clippy::uninlined_format_args)] -#![allow(named_arguments_used_positionally, unused)] -#![allow( - clippy::eq_op, +#![allow(named_arguments_used_positionally)] +#![expect( clippy::format_in_format_args, clippy::print_literal, clippy::unnecessary_literal_unwrap diff --git a/src/tools/clippy/tests/ui/uninlined_format_args.rs b/src/tools/clippy/tests/ui/uninlined_format_args.rs index 4368ce864474a..0af948dd0a4fa 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args.rs +++ b/src/tools/clippy/tests/ui/uninlined_format_args.rs @@ -1,9 +1,8 @@ //@aux-build:proc_macros.rs #![warn(clippy::uninlined_format_args)] -#![allow(named_arguments_used_positionally, unused)] -#![allow( - clippy::eq_op, +#![allow(named_arguments_used_positionally)] +#![expect( clippy::format_in_format_args, clippy::print_literal, clippy::unnecessary_literal_unwrap diff --git a/src/tools/clippy/tests/ui/uninlined_format_args.stderr b/src/tools/clippy/tests/ui/uninlined_format_args.stderr index 45994fdc9588f..8fc35af75036c 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args.stderr +++ b/src/tools/clippy/tests/ui/uninlined_format_args.stderr @@ -1,5 +1,5 @@ error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:45:5 + --> tests/ui/uninlined_format_args.rs:44:5 | LL | println!("val='{}'", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + println!("val='{local_i32}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:47:5 + --> tests/ui/uninlined_format_args.rs:46:5 | LL | println!("val='{ }'", local_i32); // 3 spaces | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + println!("val='{local_i32}'"); // 3 spaces | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:50:5 + --> tests/ui/uninlined_format_args.rs:49:5 | LL | println!("val='{ }'", local_i32); // tab | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + println!("val='{local_i32}'"); // tab | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:53:5 + --> tests/ui/uninlined_format_args.rs:52:5 | LL | println!("val='{ }'", local_i32); // space+tab | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + println!("val='{local_i32}'"); // space+tab | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:56:5 + --> tests/ui/uninlined_format_args.rs:55:5 | LL | println!("val='{ }'", local_i32); // tab+space | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + println!("val='{local_i32}'"); // tab+space | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:59:5 + --> tests/ui/uninlined_format_args.rs:58:5 | LL | / println!( LL | | @@ -72,7 +72,7 @@ LL | | ); | |_____^ error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:65:5 + --> tests/ui/uninlined_format_args.rs:64:5 | LL | println!("{}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -84,7 +84,7 @@ LL + println!("{local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:67:5 + --> tests/ui/uninlined_format_args.rs:66:5 | LL | println!("{}", fn_arg); | ^^^^^^^^^^^^^^^^^^^^^^ @@ -96,7 +96,7 @@ LL + println!("{fn_arg}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:69:5 + --> tests/ui/uninlined_format_args.rs:68:5 | LL | println!("{:?}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -108,7 +108,7 @@ LL + println!("{local_i32:?}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:71:5 + --> tests/ui/uninlined_format_args.rs:70:5 | LL | println!("{:#?}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -120,7 +120,7 @@ LL + println!("{local_i32:#?}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:73:5 + --> tests/ui/uninlined_format_args.rs:72:5 | LL | println!("{:4}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -132,7 +132,7 @@ LL + println!("{local_i32:4}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:75:5 + --> tests/ui/uninlined_format_args.rs:74:5 | LL | println!("{:04}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -144,7 +144,7 @@ LL + println!("{local_i32:04}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:77:5 + --> tests/ui/uninlined_format_args.rs:76:5 | LL | println!("{:<3}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -156,7 +156,7 @@ LL + println!("{local_i32:<3}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:79:5 + --> tests/ui/uninlined_format_args.rs:78:5 | LL | println!("{:#010x}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -168,7 +168,7 @@ LL + println!("{local_i32:#010x}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:81:5 + --> tests/ui/uninlined_format_args.rs:80:5 | LL | println!("{:.1}", local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -180,7 +180,7 @@ LL + println!("{local_f64:.1}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:86:5 + --> tests/ui/uninlined_format_args.rs:85:5 | LL | println!("{} {}", local_i32, local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -192,7 +192,7 @@ LL + println!("{local_i32} {local_f64}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:89:5 + --> tests/ui/uninlined_format_args.rs:88:5 | LL | println!("{}", val); | ^^^^^^^^^^^^^^^^^^^ @@ -204,7 +204,7 @@ LL + println!("{val}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:91:5 + --> tests/ui/uninlined_format_args.rs:90:5 | LL | println!("{}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -216,7 +216,7 @@ LL + println!("{val}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:94:5 + --> tests/ui/uninlined_format_args.rs:93:5 | LL | println!("val='{\t }'", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -228,7 +228,7 @@ LL + println!("val='{local_i32}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:96:5 + --> tests/ui/uninlined_format_args.rs:95:5 | LL | println!("val='{\n }'", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -240,7 +240,7 @@ LL + println!("val='{local_i32}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:98:5 + --> tests/ui/uninlined_format_args.rs:97:5 | LL | println!("val='{local_i32}'", local_i32 = local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -252,7 +252,7 @@ LL + println!("val='{local_i32}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:100:5 + --> tests/ui/uninlined_format_args.rs:99:5 | LL | println!("val='{local_i32}'", local_i32 = fn_arg); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -264,7 +264,7 @@ LL + println!("val='{fn_arg}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:102:5 + --> tests/ui/uninlined_format_args.rs:101:5 | LL | println!("{0}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -276,7 +276,7 @@ LL + println!("{local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:104:5 + --> tests/ui/uninlined_format_args.rs:103:5 | LL | println!("{0:?}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -288,7 +288,7 @@ LL + println!("{local_i32:?}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:106:5 + --> tests/ui/uninlined_format_args.rs:105:5 | LL | println!("{0:#?}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -300,7 +300,7 @@ LL + println!("{local_i32:#?}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:108:5 + --> tests/ui/uninlined_format_args.rs:107:5 | LL | println!("{0:04}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -312,7 +312,7 @@ LL + println!("{local_i32:04}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:110:5 + --> tests/ui/uninlined_format_args.rs:109:5 | LL | println!("{0:<3}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -324,7 +324,7 @@ LL + println!("{local_i32:<3}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:112:5 + --> tests/ui/uninlined_format_args.rs:111:5 | LL | println!("{0:#010x}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -336,7 +336,7 @@ LL + println!("{local_i32:#010x}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:114:5 + --> tests/ui/uninlined_format_args.rs:113:5 | LL | println!("{0:.1}", local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -348,7 +348,7 @@ LL + println!("{local_f64:.1}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:116:5 + --> tests/ui/uninlined_format_args.rs:115:5 | LL | println!("{0} {0}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -360,7 +360,7 @@ LL + println!("{local_i32} {local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:118:5 + --> tests/ui/uninlined_format_args.rs:117:5 | LL | println!("{1} {} {0} {}", local_i32, local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -372,7 +372,7 @@ LL + println!("{local_f64} {local_i32} {local_i32} {local_f64}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:120:5 + --> tests/ui/uninlined_format_args.rs:119:5 | LL | println!("{0} {1}", local_i32, local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -384,7 +384,7 @@ LL + println!("{local_i32} {local_f64}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:122:5 + --> tests/ui/uninlined_format_args.rs:121:5 | LL | println!("{1} {0}", local_i32, local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -396,7 +396,7 @@ LL + println!("{local_f64} {local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:124:5 + --> tests/ui/uninlined_format_args.rs:123:5 | LL | println!("{1} {0} {1} {0}", local_i32, local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -408,7 +408,7 @@ LL + println!("{local_f64} {local_i32} {local_f64} {local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:127:5 + --> tests/ui/uninlined_format_args.rs:126:5 | LL | println!("{v}", v = local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -420,7 +420,7 @@ LL + println!("{local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:129:5 + --> tests/ui/uninlined_format_args.rs:128:5 | LL | println!("{local_i32:0$}", width); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -432,7 +432,7 @@ LL + println!("{local_i32:width$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:131:5 + --> tests/ui/uninlined_format_args.rs:130:5 | LL | println!("{local_i32:w$}", w = width); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -444,7 +444,7 @@ LL + println!("{local_i32:width$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:133:5 + --> tests/ui/uninlined_format_args.rs:132:5 | LL | println!("{local_i32:.0$}", prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -456,7 +456,7 @@ LL + println!("{local_i32:.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:135:5 + --> tests/ui/uninlined_format_args.rs:134:5 | LL | println!("{local_i32:.p$}", p = prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -468,7 +468,7 @@ LL + println!("{local_i32:.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:137:5 + --> tests/ui/uninlined_format_args.rs:136:5 | LL | println!("{:0$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -480,7 +480,7 @@ LL + println!("{val:val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:139:5 + --> tests/ui/uninlined_format_args.rs:138:5 | LL | println!("{0:0$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -492,7 +492,7 @@ LL + println!("{val:val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:141:5 + --> tests/ui/uninlined_format_args.rs:140:5 | LL | println!("{:0$.0$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -504,7 +504,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:143:5 + --> tests/ui/uninlined_format_args.rs:142:5 | LL | println!("{0:0$.0$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -516,7 +516,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:145:5 + --> tests/ui/uninlined_format_args.rs:144:5 | LL | println!("{0:0$.v$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -528,7 +528,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:147:5 + --> tests/ui/uninlined_format_args.rs:146:5 | LL | println!("{0:v$.0$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -540,7 +540,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:149:5 + --> tests/ui/uninlined_format_args.rs:148:5 | LL | println!("{v:0$.0$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -552,7 +552,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:151:5 + --> tests/ui/uninlined_format_args.rs:150:5 | LL | println!("{v:v$.0$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -564,7 +564,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:153:5 + --> tests/ui/uninlined_format_args.rs:152:5 | LL | println!("{v:0$.v$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -576,7 +576,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:155:5 + --> tests/ui/uninlined_format_args.rs:154:5 | LL | println!("{v:v$.v$}", v = val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -588,7 +588,7 @@ LL + println!("{val:val$.val$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:157:5 + --> tests/ui/uninlined_format_args.rs:156:5 | LL | println!("{:0$}", width); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -600,7 +600,7 @@ LL + println!("{width:width$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:159:5 + --> tests/ui/uninlined_format_args.rs:158:5 | LL | println!("{:1$}", local_i32, width); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -612,7 +612,7 @@ LL + println!("{local_i32:width$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:161:5 + --> tests/ui/uninlined_format_args.rs:160:5 | LL | println!("{:w$}", w = width); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -624,7 +624,7 @@ LL + println!("{width:width$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:163:5 + --> tests/ui/uninlined_format_args.rs:162:5 | LL | println!("{:w$}", local_i32, w = width); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -636,7 +636,7 @@ LL + println!("{local_i32:width$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:165:5 + --> tests/ui/uninlined_format_args.rs:164:5 | LL | println!("{:.0$}", prec); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -648,7 +648,7 @@ LL + println!("{prec:.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:167:5 + --> tests/ui/uninlined_format_args.rs:166:5 | LL | println!("{:.1$}", local_i32, prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -660,7 +660,7 @@ LL + println!("{local_i32:.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:169:5 + --> tests/ui/uninlined_format_args.rs:168:5 | LL | println!("{:.p$}", p = prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -672,7 +672,7 @@ LL + println!("{prec:.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:171:5 + --> tests/ui/uninlined_format_args.rs:170:5 | LL | println!("{:.p$}", local_i32, p = prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -684,7 +684,7 @@ LL + println!("{local_i32:.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:173:5 + --> tests/ui/uninlined_format_args.rs:172:5 | LL | println!("{:0$.1$}", width, prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -696,7 +696,7 @@ LL + println!("{width:width$.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:175:5 + --> tests/ui/uninlined_format_args.rs:174:5 | LL | println!("{:0$.w$}", width, w = prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -708,7 +708,7 @@ LL + println!("{width:width$.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:177:5 + --> tests/ui/uninlined_format_args.rs:176:5 | LL | println!("{:1$.2$}", local_f64, width, prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -720,7 +720,7 @@ LL + println!("{local_f64:width$.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:179:5 + --> tests/ui/uninlined_format_args.rs:178:5 | LL | println!("{:1$.2$} {0} {1} {2}", local_f64, width, prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -732,7 +732,7 @@ LL + println!("{local_f64:width$.prec$} {local_f64} {width} {prec}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:181:5 + --> tests/ui/uninlined_format_args.rs:180:5 | LL | / println!( LL | | @@ -742,7 +742,7 @@ LL | | ); | |_____^ error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:193:5 + --> tests/ui/uninlined_format_args.rs:192:5 | LL | println!("Width = {}, value with width = {:0$}", local_i32, local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -754,7 +754,7 @@ LL + println!("Width = {local_i32}, value with width = {local_f64:local_i32$ | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:195:5 + --> tests/ui/uninlined_format_args.rs:194:5 | LL | println!("{:w$.p$}", local_i32, w = width, p = prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -766,7 +766,7 @@ LL + println!("{local_i32:width$.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:197:5 + --> tests/ui/uninlined_format_args.rs:196:5 | LL | println!("{:w$.p$}", w = width, p = prec); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -778,7 +778,7 @@ LL + println!("{width:width$.prec$}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:217:5 + --> tests/ui/uninlined_format_args.rs:216:5 | LL | / println!( LL | | @@ -788,7 +788,7 @@ LL | | ); | |_____^ error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:223:5 + --> tests/ui/uninlined_format_args.rs:222:5 | LL | println!("{}", /* comment with a comma , in it */ val); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -800,7 +800,7 @@ LL + println!("{val}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:230:9 + --> tests/ui/uninlined_format_args.rs:229:9 | LL | panic!("p1 {}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -812,7 +812,7 @@ LL + panic!("p1 {local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:234:9 + --> tests/ui/uninlined_format_args.rs:233:9 | LL | panic!("p2 {0}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -824,7 +824,7 @@ LL + panic!("p2 {local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:238:9 + --> tests/ui/uninlined_format_args.rs:237:9 | LL | panic!("p3 {local_i32}", local_i32 = local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -836,7 +836,7 @@ LL + panic!("p3 {local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:257:5 + --> tests/ui/uninlined_format_args.rs:256:5 | LL | println!("expand='{}'", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -848,7 +848,7 @@ LL + println!("expand='{local_i32}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:360:5 + --> tests/ui/uninlined_format_args.rs:359:5 | LL | usr_println!(true, "val='{}'", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -860,7 +860,7 @@ LL + usr_println!(true, "val='{local_i32}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:362:5 + --> tests/ui/uninlined_format_args.rs:361:5 | LL | usr_println!(true, "{}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -872,7 +872,7 @@ LL + usr_println!(true, "{local_i32}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:364:5 + --> tests/ui/uninlined_format_args.rs:363:5 | LL | usr_println!(true, "{:#010x}", local_i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -884,7 +884,7 @@ LL + usr_println!(true, "{local_i32:#010x}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args.rs:366:5 + --> tests/ui/uninlined_format_args.rs:365:5 | LL | usr_println!(true, "{:.1}", local_f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.fixed b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.fixed index 6d0f76eaf2524..d44312129a13e 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.fixed +++ b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.fixed @@ -4,7 +4,6 @@ //@[edition2024] edition:2024 #![warn(clippy::uninlined_format_args)] -#![allow(clippy::literal_string_with_formatting_args)] fn main() { let var = 1; diff --git a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.stderr b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.stderr index 24afb3d35abee..4b154abac5bc0 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.stderr +++ b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2018.stderr @@ -1,5 +1,5 @@ error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:12:5 + --> tests/ui/uninlined_format_args_panic.rs:11:5 | LL | println!("val='{}'", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.fixed b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.fixed index ba741bfcd09d4..22b05c5422125 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.fixed +++ b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.fixed @@ -4,7 +4,6 @@ //@[edition2024] edition:2024 #![warn(clippy::uninlined_format_args)] -#![allow(clippy::literal_string_with_formatting_args)] fn main() { let var = 1; diff --git a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.stderr b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.stderr index dcf6747e2d649..a90998aaf06a2 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.stderr +++ b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2021.stderr @@ -1,5 +1,5 @@ error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:12:5 + --> tests/ui/uninlined_format_args_panic.rs:11:5 | LL | println!("val='{}'", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + println!("val='{var}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:16:9 + --> tests/ui/uninlined_format_args_panic.rs:15:9 | LL | panic!("p1 {}", var); | ^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + panic!("p1 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:21:9 + --> tests/ui/uninlined_format_args_panic.rs:20:9 | LL | panic!("p2 {0}", var); | ^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + panic!("p2 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:26:9 + --> tests/ui/uninlined_format_args_panic.rs:25:9 | LL | panic!("p3 {var}", var = var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + panic!("p3 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:38:5 + --> tests/ui/uninlined_format_args_panic.rs:37:5 | LL | assert!(var == 1, "p5 {}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + assert!(var == 1, "p5 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:41:5 + --> tests/ui/uninlined_format_args_panic.rs:40:5 | LL | debug_assert!(var == 1, "p6 {}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + debug_assert!(var == 1, "p6 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:47:9 + --> tests/ui/uninlined_format_args_panic.rs:46:9 | LL | core::panic!("p7 {}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + core::panic!("p7 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:52:9 + --> tests/ui/uninlined_format_args_panic.rs:51:9 | LL | core::panic!("p8 {0}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL + core::panic!("p8 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:57:9 + --> tests/ui/uninlined_format_args_panic.rs:56:9 | LL | core::panic!("p9 {var}", var = var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.fixed b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.fixed index ba741bfcd09d4..22b05c5422125 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.fixed +++ b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.fixed @@ -4,7 +4,6 @@ //@[edition2024] edition:2024 #![warn(clippy::uninlined_format_args)] -#![allow(clippy::literal_string_with_formatting_args)] fn main() { let var = 1; diff --git a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.stderr b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.stderr index dcf6747e2d649..a90998aaf06a2 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.stderr +++ b/src/tools/clippy/tests/ui/uninlined_format_args_panic.edition2024.stderr @@ -1,5 +1,5 @@ error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:12:5 + --> tests/ui/uninlined_format_args_panic.rs:11:5 | LL | println!("val='{}'", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + println!("val='{var}'"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:16:9 + --> tests/ui/uninlined_format_args_panic.rs:15:9 | LL | panic!("p1 {}", var); | ^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + panic!("p1 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:21:9 + --> tests/ui/uninlined_format_args_panic.rs:20:9 | LL | panic!("p2 {0}", var); | ^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + panic!("p2 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:26:9 + --> tests/ui/uninlined_format_args_panic.rs:25:9 | LL | panic!("p3 {var}", var = var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + panic!("p3 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:38:5 + --> tests/ui/uninlined_format_args_panic.rs:37:5 | LL | assert!(var == 1, "p5 {}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + assert!(var == 1, "p5 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:41:5 + --> tests/ui/uninlined_format_args_panic.rs:40:5 | LL | debug_assert!(var == 1, "p6 {}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + debug_assert!(var == 1, "p6 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:47:9 + --> tests/ui/uninlined_format_args_panic.rs:46:9 | LL | core::panic!("p7 {}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + core::panic!("p7 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:52:9 + --> tests/ui/uninlined_format_args_panic.rs:51:9 | LL | core::panic!("p8 {0}", var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL + core::panic!("p8 {var}"); | error: variables can be used directly in the `format!` string - --> tests/ui/uninlined_format_args_panic.rs:57:9 + --> tests/ui/uninlined_format_args_panic.rs:56:9 | LL | core::panic!("p9 {var}", var = var); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/uninlined_format_args_panic.rs b/src/tools/clippy/tests/ui/uninlined_format_args_panic.rs index 7ee17d8fb16e2..f151f5da959ed 100644 --- a/src/tools/clippy/tests/ui/uninlined_format_args_panic.rs +++ b/src/tools/clippy/tests/ui/uninlined_format_args_panic.rs @@ -4,7 +4,6 @@ //@[edition2024] edition:2024 #![warn(clippy::uninlined_format_args)] -#![allow(clippy::literal_string_with_formatting_args)] fn main() { let var = 1; diff --git a/src/tools/clippy/tests/ui/unit_arg.rs b/src/tools/clippy/tests/ui/unit_arg.rs index 3cba0735b3623..fa9851db3d10a 100644 --- a/src/tools/clippy/tests/ui/unit_arg.rs +++ b/src/tools/clippy/tests/ui/unit_arg.rs @@ -1,16 +1,10 @@ //@aux-build: proc_macros.rs //@no-rustfix: overlapping suggestions #![warn(clippy::unit_arg)] -#![allow(unused_must_use, unused_variables)] -#![allow( - clippy::let_unit_value, +#![expect( clippy::needless_question_mark, clippy::never_loop, clippy::no_effect, - clippy::or_fun_call, - clippy::self_named_constructors, - clippy::uninlined_format_args, - clippy::unnecessary_wraps, clippy::unused_unit )] @@ -124,7 +118,6 @@ fn question_mark() -> Result<(), ()> { Ok(()) } -#[allow(dead_code)] mod issue_2945 { fn unit_fn() -> Result<(), i32> { Ok(()) @@ -135,7 +128,6 @@ mod issue_2945 { } } -#[allow(dead_code)] fn returning_expr() -> Option<()> { Some(foo(1)) //~^ unit_arg diff --git a/src/tools/clippy/tests/ui/unit_arg.stderr b/src/tools/clippy/tests/ui/unit_arg.stderr index ed13108631574..26e35fa616d4d 100644 --- a/src/tools/clippy/tests/ui/unit_arg.stderr +++ b/src/tools/clippy/tests/ui/unit_arg.stderr @@ -1,5 +1,5 @@ error: passing a unit value to a function - --> tests/ui/unit_arg.rs:63:5 + --> tests/ui/unit_arg.rs:57:5 | LL | / foo({ LL | | @@ -24,7 +24,7 @@ LL ~ foo(()); | error: passing a unit value to a function - --> tests/ui/unit_arg.rs:67:5 + --> tests/ui/unit_arg.rs:61:5 | LL | foo(foo(1)); | ^^^^^^^^^^^ @@ -36,7 +36,7 @@ LL ~ foo(()); | error: passing a unit value to a function - --> tests/ui/unit_arg.rs:69:5 + --> tests/ui/unit_arg.rs:63:5 | LL | / foo({ LL | | @@ -61,7 +61,7 @@ LL ~ foo(()); | error: passing a unit value to a function - --> tests/ui/unit_arg.rs:75:5 + --> tests/ui/unit_arg.rs:69:5 | LL | / b.bar({ LL | | @@ -84,7 +84,7 @@ LL ~ b.bar(()); | error: passing unit values to a function - --> tests/ui/unit_arg.rs:79:5 + --> tests/ui/unit_arg.rs:73:5 | LL | taking_multiple_units(foo(0), foo(1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL ~ taking_multiple_units((), ()); | error: passing unit values to a function - --> tests/ui/unit_arg.rs:81:5 + --> tests/ui/unit_arg.rs:75:5 | LL | / taking_multiple_units(foo(0), { LL | | @@ -123,7 +123,7 @@ LL ~ taking_multiple_units((), ()); | error: passing unit values to a function - --> tests/ui/unit_arg.rs:86:5 + --> tests/ui/unit_arg.rs:80:5 | LL | / taking_multiple_units( LL | | @@ -162,7 +162,7 @@ LL ~ ); | error: passing a unit value to a function - --> tests/ui/unit_arg.rs:98:13 + --> tests/ui/unit_arg.rs:92:13 | LL | None.or(Some(foo(2))); | ^^^^^^^^^^^^ @@ -176,7 +176,7 @@ LL ~ }); | error: passing a unit value to a function - --> tests/ui/unit_arg.rs:102:5 + --> tests/ui/unit_arg.rs:96:5 | LL | foo(foo(())); | ^^^^^^^^^^^^ @@ -188,7 +188,7 @@ LL ~ foo(()); | error: passing a unit value to a function - --> tests/ui/unit_arg.rs:140:5 + --> tests/ui/unit_arg.rs:132:5 | LL | Some(foo(1)) | ^^^^^^^^^^^^ @@ -200,19 +200,19 @@ LL + Some(()) | error: passing a unit value to a function - --> tests/ui/unit_arg.rs:168:5 + --> tests/ui/unit_arg.rs:160:5 | LL | fn_take_unit(mac!(def)); | ^^^^^^^^^^^^^^^^^^^^^^^ error: passing a unit value to a function - --> tests/ui/unit_arg.rs:170:5 + --> tests/ui/unit_arg.rs:162:5 | LL | fn_take_unit(mac!(func Default::default)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: passing a unit value to a function - --> tests/ui/unit_arg.rs:172:5 + --> tests/ui/unit_arg.rs:164:5 | LL | fn_take_unit(mac!(nonempty_block Default::default())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unit_arg_fixable.fixed b/src/tools/clippy/tests/ui/unit_arg_fixable.fixed index 3bbc62ca0bca7..41af9263f9147 100644 --- a/src/tools/clippy/tests/ui/unit_arg_fixable.fixed +++ b/src/tools/clippy/tests/ui/unit_arg_fixable.fixed @@ -1,6 +1,4 @@ #![warn(clippy::unit_arg)] -#![allow(unused_must_use, unused_variables)] -#![allow(clippy::no_effect, clippy::uninlined_format_args)] use std::fmt::Debug; diff --git a/src/tools/clippy/tests/ui/unit_arg_fixable.rs b/src/tools/clippy/tests/ui/unit_arg_fixable.rs index 12d6cbcf61d92..02d39b0283013 100644 --- a/src/tools/clippy/tests/ui/unit_arg_fixable.rs +++ b/src/tools/clippy/tests/ui/unit_arg_fixable.rs @@ -1,6 +1,4 @@ #![warn(clippy::unit_arg)] -#![allow(unused_must_use, unused_variables)] -#![allow(clippy::no_effect, clippy::uninlined_format_args)] use std::fmt::Debug; diff --git a/src/tools/clippy/tests/ui/unit_arg_fixable.stderr b/src/tools/clippy/tests/ui/unit_arg_fixable.stderr index 9f6bc671bf55b..40eee8c2cc1c1 100644 --- a/src/tools/clippy/tests/ui/unit_arg_fixable.stderr +++ b/src/tools/clippy/tests/ui/unit_arg_fixable.stderr @@ -1,5 +1,5 @@ error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:16:5 + --> tests/ui/unit_arg_fixable.rs:14:5 | LL | foo({}); | ^^^^^^^ @@ -13,7 +13,7 @@ LL + foo(()); | error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:18:5 + --> tests/ui/unit_arg_fixable.rs:16:5 | LL | foo3({}, 2, 2); | ^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + foo3((), 2, 2); | error: passing unit values to a function - --> tests/ui/unit_arg_fixable.rs:20:5 + --> tests/ui/unit_arg_fixable.rs:18:5 | LL | taking_two_units({}, foo(0)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL ~ taking_two_units((), ()); | error: passing unit values to a function - --> tests/ui/unit_arg_fixable.rs:22:5 + --> tests/ui/unit_arg_fixable.rs:20:5 | LL | taking_three_units({}, foo(0), foo(1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -50,7 +50,7 @@ LL ~ taking_three_units((), (), ()); | error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:33:5 + --> tests/ui/unit_arg_fixable.rs:31:5 | LL | fn_take_unit(Default::default()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -62,7 +62,7 @@ LL + fn_take_unit(()); | error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:47:5 + --> tests/ui/unit_arg_fixable.rs:45:5 | LL | fn_take_unit(another_mac!()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -74,7 +74,7 @@ LL ~ fn_take_unit(()); | error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:49:5 + --> tests/ui/unit_arg_fixable.rs:47:5 | LL | fn_take_unit(another_mac!(1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -86,7 +86,7 @@ LL ~ fn_take_unit(()); | error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:58:5 + --> tests/ui/unit_arg_fixable.rs:56:5 | LL | fn_take_unit(mac!(nondef Default::default())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -98,7 +98,7 @@ LL + fn_take_unit(mac!(nondef ())); | error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:60:5 + --> tests/ui/unit_arg_fixable.rs:58:5 | LL | fn_take_unit(mac!(empty_block)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -110,7 +110,7 @@ LL ~ fn_take_unit(()); | error: passing a unit value to a function - --> tests/ui/unit_arg_fixable.rs:67:5 + --> tests/ui/unit_arg_fixable.rs:65:5 | LL | fn_take_unit(def()); | ^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unit_cmp.rs b/src/tools/clippy/tests/ui/unit_cmp.rs index 839987a474cd0..6e2ae4bc0fb0d 100644 --- a/src/tools/clippy/tests/ui/unit_cmp.rs +++ b/src/tools/clippy/tests/ui/unit_cmp.rs @@ -1,10 +1,5 @@ #![warn(clippy::unit_cmp)] -#![allow( - clippy::no_effect, - clippy::unnecessary_operation, - clippy::derive_partial_eq_without_eq, - clippy::needless_ifs -)] +#![expect(clippy::needless_ifs, clippy::no_effect)] #[derive(PartialEq)] pub struct ContainsUnit(()); // should be fine diff --git a/src/tools/clippy/tests/ui/unit_cmp.stderr b/src/tools/clippy/tests/ui/unit_cmp.stderr index 21aa9dce1510f..1ac151442ebc3 100644 --- a/src/tools/clippy/tests/ui/unit_cmp.stderr +++ b/src/tools/clippy/tests/ui/unit_cmp.stderr @@ -1,5 +1,5 @@ error: ==-comparison of unit values detected. This will always be true - --> tests/ui/unit_cmp.rs:17:8 + --> tests/ui/unit_cmp.rs:12:8 | LL | if { | ________^ @@ -15,7 +15,7 @@ LL | | } {} = help: to override `-D warnings` add `#[allow(clippy::unit_cmp)]` error: >-comparison of unit values detected. This will always be false - --> tests/ui/unit_cmp.rs:25:8 + --> tests/ui/unit_cmp.rs:20:8 | LL | if { | ________^ @@ -28,7 +28,7 @@ LL | | } {} | |_____^ error: `assert_eq` of unit values detected. This will always succeed - --> tests/ui/unit_cmp.rs:33:5 + --> tests/ui/unit_cmp.rs:28:5 | LL | / assert_eq!( LL | | @@ -39,7 +39,7 @@ LL | | ); | |_____^ error: `debug_assert_eq` of unit values detected. This will always succeed - --> tests/ui/unit_cmp.rs:42:5 + --> tests/ui/unit_cmp.rs:37:5 | LL | / debug_assert_eq!( LL | | @@ -50,7 +50,7 @@ LL | | ); | |_____^ error: `assert_ne` of unit values detected. This will always fail - --> tests/ui/unit_cmp.rs:52:5 + --> tests/ui/unit_cmp.rs:47:5 | LL | / assert_ne!( LL | | @@ -61,7 +61,7 @@ LL | | ); | |_____^ error: `debug_assert_ne` of unit values detected. This will always fail - --> tests/ui/unit_cmp.rs:61:5 + --> tests/ui/unit_cmp.rs:56:5 | LL | / debug_assert_ne!( LL | | @@ -72,7 +72,7 @@ LL | | ); | |_____^ error: `assert_eq` of unit values detected. This will always succeed - --> tests/ui/unit_cmp.rs:74:5 + --> tests/ui/unit_cmp.rs:69:5 | LL | / assert_eq!( LL | | @@ -84,7 +84,7 @@ LL | | ); | |_____^ error: `assert_eq` of unit values detected. This will always succeed - --> tests/ui/unit_cmp.rs:81:5 + --> tests/ui/unit_cmp.rs:76:5 | LL | assert_eq!(foo(), foo()); | ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unit_hash.fixed b/src/tools/clippy/tests/ui/unit_hash.fixed index 25c90e6ddc4c2..409c78f6c38cd 100644 --- a/src/tools/clippy/tests/ui/unit_hash.fixed +++ b/src/tools/clippy/tests/ui/unit_hash.fixed @@ -1,5 +1,4 @@ #![warn(clippy::unit_hash)] -#![allow(clippy::let_unit_value)] use std::collections::hash_map::DefaultHasher; use std::hash::Hash; diff --git a/src/tools/clippy/tests/ui/unit_hash.rs b/src/tools/clippy/tests/ui/unit_hash.rs index b04cca6adf2a5..f7e0b1d23ab26 100644 --- a/src/tools/clippy/tests/ui/unit_hash.rs +++ b/src/tools/clippy/tests/ui/unit_hash.rs @@ -1,5 +1,4 @@ #![warn(clippy::unit_hash)] -#![allow(clippy::let_unit_value)] use std::collections::hash_map::DefaultHasher; use std::hash::Hash; diff --git a/src/tools/clippy/tests/ui/unit_hash.stderr b/src/tools/clippy/tests/ui/unit_hash.stderr index d1cabf89f8e71..410cd149e1df6 100644 --- a/src/tools/clippy/tests/ui/unit_hash.stderr +++ b/src/tools/clippy/tests/ui/unit_hash.stderr @@ -1,5 +1,5 @@ error: this call to `hash` on the unit type will do nothing - --> tests/ui/unit_hash.rs:19:23 + --> tests/ui/unit_hash.rs:18:23 | LL | Foo::Empty => ().hash(&mut state), | ^^^^^^^^^^^^^^^^^^^ help: remove the call to `hash` or consider using: `0_u8.hash(&mut state)` @@ -9,7 +9,7 @@ LL | Foo::Empty => ().hash(&mut state), = help: to override `-D warnings` add `#[allow(clippy::unit_hash)]` error: this call to `hash` on the unit type will do nothing - --> tests/ui/unit_hash.rs:25:5 + --> tests/ui/unit_hash.rs:24:5 | LL | res.hash(&mut state); | ^^^^^^^^^^^^^^^^^^^^ help: remove the call to `hash` or consider using: `0_u8.hash(&mut state)` @@ -17,7 +17,7 @@ LL | res.hash(&mut state); = note: the implementation of `Hash` for `()` is a no-op error: this call to `hash` on the unit type will do nothing - --> tests/ui/unit_hash.rs:29:5 + --> tests/ui/unit_hash.rs:28:5 | LL | do_nothing().hash(&mut state); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove the call to `hash` or consider using: `0_u8.hash(&mut state)` diff --git a/src/tools/clippy/tests/ui/unit_return_expecting_ord.rs b/src/tools/clippy/tests/ui/unit_return_expecting_ord.rs index 74cd304726842..de067190fe389 100644 --- a/src/tools/clippy/tests/ui/unit_return_expecting_ord.rs +++ b/src/tools/clippy/tests/ui/unit_return_expecting_ord.rs @@ -1,7 +1,6 @@ #![warn(clippy::unit_return_expecting_ord)] -#![allow(clippy::needless_return)] +#![expect(clippy::needless_return, clippy::useless_vec)] #![allow(clippy::unused_unit)] -#![allow(clippy::useless_vec)] struct Struct { field: isize, diff --git a/src/tools/clippy/tests/ui/unit_return_expecting_ord.stderr b/src/tools/clippy/tests/ui/unit_return_expecting_ord.stderr index d5ce2fb0b51d9..548feada2117d 100644 --- a/src/tools/clippy/tests/ui/unit_return_expecting_ord.stderr +++ b/src/tools/clippy/tests/ui/unit_return_expecting_ord.stderr @@ -1,11 +1,11 @@ error: this closure returns the unit type which also implements Ord - --> tests/ui/unit_return_expecting_ord.rs:18:25 + --> tests/ui/unit_return_expecting_ord.rs:17:25 | LL | structs.sort_by_key(|s| { | ^^^ | help: probably caused by this trailing semicolon - --> tests/ui/unit_return_expecting_ord.rs:21:24 + --> tests/ui/unit_return_expecting_ord.rs:20:24 | LL | double(s.field); | ^ @@ -13,25 +13,25 @@ LL | double(s.field); = help: to override `-D warnings` add `#[allow(clippy::unit_return_expecting_ord)]` error: this closure returns the unit type which also implements PartialOrd - --> tests/ui/unit_return_expecting_ord.rs:24:30 + --> tests/ui/unit_return_expecting_ord.rs:23:30 | LL | structs.is_sorted_by_key(|s| { | ^^^ | help: probably caused by this trailing semicolon - --> tests/ui/unit_return_expecting_ord.rs:27:24 + --> tests/ui/unit_return_expecting_ord.rs:26:24 | LL | double(s.field); | ^ error: this closure returns the unit type which also implements PartialOrd - --> tests/ui/unit_return_expecting_ord.rs:29:30 + --> tests/ui/unit_return_expecting_ord.rs:28:30 | LL | structs.is_sorted_by_key(|s| { | ^^^ error: this closure returns the unit type which also implements Ord - --> tests/ui/unit_return_expecting_ord.rs:41:25 + --> tests/ui/unit_return_expecting_ord.rs:40:25 | LL | structs.sort_by_key(|s| unit(s.field)); | ^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_cast.fixed b/src/tools/clippy/tests/ui/unnecessary_cast.fixed index 9e07c52e82e67..1724d3d8c2f3b 100644 --- a/src/tools/clippy/tests/ui/unnecessary_cast.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_cast.fixed @@ -1,15 +1,14 @@ //@aux-build:extern_fake_libc.rs #![feature(const_trait_impl, const_ops)] #![warn(clippy::unnecessary_cast)] -#![allow( +#![expect( + nonstandard_style, clippy::borrow_as_ptr, clippy::identity_op, clippy::multiple_bound_locations, clippy::no_effect, clippy::nonstandard_macro_braces, - clippy::unnecessary_operation, - nonstandard_style, - unused + clippy::unnecessary_operation )] extern crate extern_fake_libc; @@ -102,7 +101,6 @@ fn main() { // macro version macro_rules! foo { ($a:ident, $b:ident) => { - #[allow(unused)] pub fn $a() -> $b { 1 as $b } @@ -169,7 +167,6 @@ fn main() { type I32Alias = i32; mod fixable { - #![allow(dead_code)] fn main() { // casting integer literal to float is unnecessary diff --git a/src/tools/clippy/tests/ui/unnecessary_cast.rs b/src/tools/clippy/tests/ui/unnecessary_cast.rs index 43d3e56e365a2..3c2ba9777a569 100644 --- a/src/tools/clippy/tests/ui/unnecessary_cast.rs +++ b/src/tools/clippy/tests/ui/unnecessary_cast.rs @@ -1,15 +1,14 @@ //@aux-build:extern_fake_libc.rs #![feature(const_trait_impl, const_ops)] #![warn(clippy::unnecessary_cast)] -#![allow( +#![expect( + nonstandard_style, clippy::borrow_as_ptr, clippy::identity_op, clippy::multiple_bound_locations, clippy::no_effect, clippy::nonstandard_macro_braces, - clippy::unnecessary_operation, - nonstandard_style, - unused + clippy::unnecessary_operation )] extern crate extern_fake_libc; @@ -102,7 +101,6 @@ fn main() { // macro version macro_rules! foo { ($a:ident, $b:ident) => { - #[allow(unused)] pub fn $a() -> $b { 1 as $b } @@ -169,7 +167,6 @@ fn main() { type I32Alias = i32; mod fixable { - #![allow(dead_code)] fn main() { // casting integer literal to float is unnecessary diff --git a/src/tools/clippy/tests/ui/unnecessary_cast.stderr b/src/tools/clippy/tests/ui/unnecessary_cast.stderr index 9807ae0341421..fd5c761efdad8 100644 --- a/src/tools/clippy/tests/ui/unnecessary_cast.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_cast.stderr @@ -1,5 +1,5 @@ error: casting raw pointers to the same type and constness is unnecessary (`*const T` -> `*const T`) - --> tests/ui/unnecessary_cast.rs:21:5 + --> tests/ui/unnecessary_cast.rs:20:5 | LL | ptr as *const T | ^^^^^^^^^^^^^^^ help: try: `ptr` @@ -8,427 +8,427 @@ LL | ptr as *const T = help: to override `-D warnings` add `#[allow(clippy::unnecessary_cast)]` error: casting integer literal to `i32` is unnecessary - --> tests/ui/unnecessary_cast.rs:57:5 + --> tests/ui/unnecessary_cast.rs:56:5 | LL | 1i32 as i32; | ^^^^^^^^^^^ help: try: `1_i32` error: casting float literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:59:5 + --> tests/ui/unnecessary_cast.rs:58:5 | LL | 1f32 as f32; | ^^^^^^^^^^^ help: try: `1_f32` error: casting to the same type is unnecessary (`bool` -> `bool`) - --> tests/ui/unnecessary_cast.rs:61:5 + --> tests/ui/unnecessary_cast.rs:60:5 | LL | false as bool; | ^^^^^^^^^^^^^ help: try: `false` error: casting integer literal to `i32` is unnecessary - --> tests/ui/unnecessary_cast.rs:65:5 + --> tests/ui/unnecessary_cast.rs:64:5 | LL | -1_i32 as i32; | ^^^^^^^^^^^^^ help: try: `-1_i32` error: casting integer literal to `i32` is unnecessary - --> tests/ui/unnecessary_cast.rs:67:5 + --> tests/ui/unnecessary_cast.rs:66:5 | LL | - 1_i32 as i32; | ^^^^^^^^^^^^^^ help: try: `- 1_i32` error: casting float literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:69:5 + --> tests/ui/unnecessary_cast.rs:68:5 | LL | -1f32 as f32; | ^^^^^^^^^^^^ help: try: `-1_f32` error: casting integer literal to `i32` is unnecessary - --> tests/ui/unnecessary_cast.rs:71:5 + --> tests/ui/unnecessary_cast.rs:70:5 | LL | 1_i32 as i32; | ^^^^^^^^^^^^ help: try: `1_i32` error: casting float literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:73:5 + --> tests/ui/unnecessary_cast.rs:72:5 | LL | 1_f32 as f32; | ^^^^^^^^^^^^ help: try: `1_f32` error: casting raw pointers to the same type and constness is unnecessary (`*const u8` -> `*const u8`) - --> tests/ui/unnecessary_cast.rs:76:22 + --> tests/ui/unnecessary_cast.rs:75:22 | LL | let _: *mut u8 = [1u8, 2].as_ptr() as *const u8 as *mut u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `[1u8, 2].as_ptr()` error: casting raw pointers to the same type and constness is unnecessary (`*const u8` -> `*const u8`) - --> tests/ui/unnecessary_cast.rs:79:5 + --> tests/ui/unnecessary_cast.rs:78:5 | LL | [1u8, 2].as_ptr() as *const u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `[1u8, 2].as_ptr()` error: casting raw pointers to the same type and constness is unnecessary (`*mut u8` -> `*mut u8`) - --> tests/ui/unnecessary_cast.rs:82:5 + --> tests/ui/unnecessary_cast.rs:81:5 | LL | [1u8, 2].as_mut_ptr() as *mut u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `[1u8, 2].as_mut_ptr()` error: casting raw pointers to the same type and constness is unnecessary (`*const u32` -> `*const u32`) - --> tests/ui/unnecessary_cast.rs:94:5 + --> tests/ui/unnecessary_cast.rs:93:5 | LL | owo::([1u32].as_ptr()) as *const u32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `owo::([1u32].as_ptr())` error: casting raw pointers to the same type and constness is unnecessary (`*const u8` -> `*const u8`) - --> tests/ui/unnecessary_cast.rs:96:5 + --> tests/ui/unnecessary_cast.rs:95:5 | LL | uwu::([1u32].as_ptr()) as *const u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `uwu::([1u32].as_ptr())` error: casting raw pointers to the same type and constness is unnecessary (`*const u32` -> `*const u32`) - --> tests/ui/unnecessary_cast.rs:99:5 + --> tests/ui/unnecessary_cast.rs:98:5 | LL | uwu::([1u32].as_ptr()) as *const u32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `uwu::([1u32].as_ptr())` error: casting to the same type is unnecessary (`u32` -> `u32`) - --> tests/ui/unnecessary_cast.rs:135:5 + --> tests/ui/unnecessary_cast.rs:133:5 | LL | aaa() as u32; | ^^^^^^^^^^^^ help: try: `aaa()` error: casting to the same type is unnecessary (`u32` -> `u32`) - --> tests/ui/unnecessary_cast.rs:138:5 + --> tests/ui/unnecessary_cast.rs:136:5 | LL | x as u32; | ^^^^^^^^ help: try: `x` error: casting to the same type is unnecessary (`u32` -> `u32`) - --> tests/ui/unnecessary_cast.rs:140:5 + --> tests/ui/unnecessary_cast.rs:138:5 | LL | bbb() as u32; | ^^^^^^^^^^^^ help: try: `bbb()` error: casting to the same type is unnecessary (`u32` -> `u32`) - --> tests/ui/unnecessary_cast.rs:143:5 + --> tests/ui/unnecessary_cast.rs:141:5 | LL | x as u32; | ^^^^^^^^ help: try: `x` error: casting integer literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:176:9 + --> tests/ui/unnecessary_cast.rs:173:9 | LL | 100 as f32; | ^^^^^^^^^^ help: try: `100_f32` error: casting integer literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:178:9 + --> tests/ui/unnecessary_cast.rs:175:9 | LL | 100 as f64; | ^^^^^^^^^^ help: try: `100_f64` error: casting integer literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:180:9 + --> tests/ui/unnecessary_cast.rs:177:9 | LL | 100_i32 as f64; | ^^^^^^^^^^^^^^ help: try: `100_f64` error: casting integer literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:182:17 + --> tests/ui/unnecessary_cast.rs:179:17 | LL | let _ = -100 as f32; | ^^^^^^^^^^^ help: try: `-100_f32` error: casting integer literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:184:17 + --> tests/ui/unnecessary_cast.rs:181:17 | LL | let _ = -100 as f64; | ^^^^^^^^^^^ help: try: `-100_f64` error: casting integer literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:186:17 + --> tests/ui/unnecessary_cast.rs:183:17 | LL | let _ = -100_i32 as f64; | ^^^^^^^^^^^^^^^ help: try: `-100_f64` error: casting float literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:188:9 + --> tests/ui/unnecessary_cast.rs:185:9 | LL | 100. as f32; | ^^^^^^^^^^^ help: try: `100_f32` error: casting float literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:190:9 + --> tests/ui/unnecessary_cast.rs:187:9 | LL | 100. as f64; | ^^^^^^^^^^^ help: try: `100_f64` error: casting integer literal to `u32` is unnecessary - --> tests/ui/unnecessary_cast.rs:203:9 + --> tests/ui/unnecessary_cast.rs:200:9 | LL | 1 as u32; | ^^^^^^^^ help: try: `1_u32` error: casting integer literal to `i32` is unnecessary - --> tests/ui/unnecessary_cast.rs:205:9 + --> tests/ui/unnecessary_cast.rs:202:9 | LL | 0x10 as i32; | ^^^^^^^^^^^ help: try: `0x10_i32` error: casting integer literal to `usize` is unnecessary - --> tests/ui/unnecessary_cast.rs:207:9 + --> tests/ui/unnecessary_cast.rs:204:9 | LL | 0b10 as usize; | ^^^^^^^^^^^^^ help: try: `0b10_usize` error: casting integer literal to `u16` is unnecessary - --> tests/ui/unnecessary_cast.rs:209:9 + --> tests/ui/unnecessary_cast.rs:206:9 | LL | 0o73 as u16; | ^^^^^^^^^^^ help: try: `0o73_u16` error: casting integer literal to `u32` is unnecessary - --> tests/ui/unnecessary_cast.rs:211:9 + --> tests/ui/unnecessary_cast.rs:208:9 | LL | 1_000_000_000 as u32; | ^^^^^^^^^^^^^^^^^^^^ help: try: `1_000_000_000_u32` error: casting float literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:214:9 + --> tests/ui/unnecessary_cast.rs:211:9 | LL | 1.0 as f64; | ^^^^^^^^^^ help: try: `1.0_f64` error: casting float literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:216:9 + --> tests/ui/unnecessary_cast.rs:213:9 | LL | 0.5 as f32; | ^^^^^^^^^^ help: try: `0.5_f32` error: casting integer literal to `i32` is unnecessary - --> tests/ui/unnecessary_cast.rs:221:17 + --> tests/ui/unnecessary_cast.rs:218:17 | LL | let _ = -1 as i32; | ^^^^^^^^^ help: try: `-1_i32` error: casting float literal to `f32` is unnecessary - --> tests/ui/unnecessary_cast.rs:223:17 + --> tests/ui/unnecessary_cast.rs:220:17 | LL | let _ = -1.0 as f32; | ^^^^^^^^^^^ help: try: `-1.0_f32` error: casting to the same type is unnecessary (`i32` -> `i32`) - --> tests/ui/unnecessary_cast.rs:230:18 + --> tests/ui/unnecessary_cast.rs:227:18 | LL | let _ = &(x as i32); | ^^^^^^^^^^ help: try: `{ x }` error: casting integer literal to `i32` is unnecessary - --> tests/ui/unnecessary_cast.rs:237:22 + --> tests/ui/unnecessary_cast.rs:234:22 | LL | let _: i32 = -(1) as i32; | ^^^^^^^^^^^ help: try: `-1_i32` error: casting integer literal to `i64` is unnecessary - --> tests/ui/unnecessary_cast.rs:240:22 + --> tests/ui/unnecessary_cast.rs:237:22 | LL | let _: i64 = -(1) as i64; | ^^^^^^^^^^^ help: try: `-1_i64` error: casting float literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:248:22 + --> tests/ui/unnecessary_cast.rs:245:22 | LL | let _: f64 = (-8.0 as f64).exp(); | ^^^^^^^^^^^^^ help: try: `(-8.0_f64)` error: casting float literal to `f64` is unnecessary - --> tests/ui/unnecessary_cast.rs:251:23 + --> tests/ui/unnecessary_cast.rs:248:23 | LL | let _: f64 = -(8.0 as f64).exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior | ^^^^^^^^^^^^ help: try: `8.0_f64` error: casting to the same type is unnecessary (`f32` -> `f32`) - --> tests/ui/unnecessary_cast.rs:261:20 + --> tests/ui/unnecessary_cast.rs:258:20 | LL | let _num = foo() as f32; | ^^^^^^^^^^^^ help: try: `foo()` error: casting to the same type is unnecessary (`usize` -> `usize`) - --> tests/ui/unnecessary_cast.rs:272:9 + --> tests/ui/unnecessary_cast.rs:269:9 | LL | (*x as usize).pow(2) | ^^^^^^^^^^^^^ help: try: `(*x)` error: casting to the same type is unnecessary (`usize` -> `usize`) - --> tests/ui/unnecessary_cast.rs:280:31 + --> tests/ui/unnecessary_cast.rs:277:31 | LL | assert_eq!(vec.len(), x as usize); | ^^^^^^^^^^ help: try: `x` error: casting to the same type is unnecessary (`i64` -> `i64`) - --> tests/ui/unnecessary_cast.rs:283:17 + --> tests/ui/unnecessary_cast.rs:280:17 | LL | let _ = (5i32 as i64 as i64).abs(); | ^^^^^^^^^^^^^^^^^^^^ help: try: `(5i32 as i64)` error: casting to the same type is unnecessary (`i64` -> `i64`) - --> tests/ui/unnecessary_cast.rs:286:17 + --> tests/ui/unnecessary_cast.rs:283:17 | LL | let _ = 5i32 as i64 as i64; | ^^^^^^^^^^^^^^^^^^ help: try: `5i32 as i64` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:565:24 + --> tests/ui/unnecessary_cast.rs:562:24 | LL | id::>(1.0_f64.pow_like(2) as f64 * &a).view(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:569:26 + --> tests/ui/unnecessary_cast.rs:566:26 | LL | s.id::>(1.0_f64.pow_like(2) as f64 * &a).view(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:573:26 + --> tests/ui/unnecessary_cast.rs:570:26 | LL | wrap::>(1.0_f64.pow_like(2) as f64 * &a).inner.view(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:577:28 + --> tests/ui/unnecessary_cast.rs:574:28 | LL | s.wrap::>(1.0_f64.pow_like(2) as f64 * &a).inner.view(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:593:31 + --> tests/ui/unnecessary_cast.rs:590:31 | LL | let _ = receiver.take(1.0_f64.pow_like_single_impl(2) as f64).abs(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like_single_impl(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:603:20 + --> tests/ui/unnecessary_cast.rs:600:20 | LL | let _ = id(1.0_f64.powi(2) as f64).abs(); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.powi(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:606:22 + --> tests/ui/unnecessary_cast.rs:603:22 | LL | let _ = wrap(1.0_f64.powi(2) as f64).inner.abs(); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.powi(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:609:22 + --> tests/ui/unnecessary_cast.rs:606:22 | LL | let _ = s.id(1.0_f64.powi(2) as f64).abs(); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.powi(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:612:24 + --> tests/ui/unnecessary_cast.rs:609:24 | LL | let _ = s.wrap(1.0_f64.powi(2) as f64).inner.abs(); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.powi(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:615:20 + --> tests/ui/unnecessary_cast.rs:612:20 | LL | let _ = id(1.0_f64.powi(2) as f64 * &a); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.powi(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:618:22 + --> tests/ui/unnecessary_cast.rs:615:22 | LL | let _ = s.id(1.0_f64.powi(2) as f64 * &a); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.powi(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:631:17 + --> tests/ui/unnecessary_cast.rs:628:17 | LL | let _ = 1.0_f64.pow_like(0.5) as f64; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like(0.5)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:634:17 + --> tests/ui/unnecessary_cast.rs:631:17 | LL | let _ = 1.0_f64.pow_like(2) as f64; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:637:17 + --> tests/ui/unnecessary_cast.rs:634:17 | LL | let _ = (1.0_f64.powi(2) as f64).abs(); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.powi(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:640:17 + --> tests/ui/unnecessary_cast.rs:637:17 | LL | let _ = ((Y + 2) as f64).abs(); | ^^^^^^^^^^^^^^^^ help: try: `((Y + 2))` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:643:18 + --> tests/ui/unnecessary_cast.rs:640:18 | LL | let _ = (1.0_f64.pow_like_single_impl(2) as f64 + 1.0_f64).abs(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like_single_impl(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:646:18 + --> tests/ui/unnecessary_cast.rs:643:18 | LL | let _ = (1.0_f64.pow_like_single_impl(2) as f64 + ONE).abs(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like_single_impl(2)` error: casting to the same type is unnecessary (`f64` -> `f64`) - --> tests/ui/unnecessary_cast.rs:649:18 + --> tests/ui/unnecessary_cast.rs:646:18 | LL | let _ = (1.0_f64.pow_like_single_impl(2) as f64 + one).abs(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1.0_f64.pow_like_single_impl(2)` error: casting raw pointers to the same type and constness is unnecessary (`*const *const u8` -> `*const *const u8`) - --> tests/ui/unnecessary_cast.rs:657:10 + --> tests/ui/unnecessary_cast.rs:654:10 | LL | *(&NONE as *const _ as *const _ as *const *const u8 as *const *const u8) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(&NONE as *const _ as *const _ as *const *const u8)` error: casting integer literal to `u64` is unnecessary - --> tests/ui/unnecessary_cast.rs:665:45 + --> tests/ui/unnecessary_cast.rs:662:45 | LL | assert!(0x7f_ff_ff_ff_ff_ff_ff_ffu64 == (!0 as u64).overflowing_shr(1_u32).0); | ^^^^^^^^^^^ help: try: `(!0_u64)` error: casting to the same type is unnecessary (`u64` -> `u64`) - --> tests/ui/unnecessary_cast.rs:667:45 + --> tests/ui/unnecessary_cast.rs:664:45 | LL | assert!(0x7f_ff_ff_ff_ff_ff_ff_ffu64 == (!0_u64 as u64).overflowing_shr(1_u32).0); | ^^^^^^^^^^^^^^^ help: try: `(!0_u64)` error: casting integer literal to `u64` is unnecessary - --> tests/ui/unnecessary_cast.rs:670:46 + --> tests/ui/unnecessary_cast.rs:667:46 | LL | assert!(0x7f_ff_ff_ff_ff_ff_ff_ffu64 == (!0 as u64 + 0).overflowing_shr(1_u32).0); | ^^^^^^^^^ help: try: `!0_u64` error: casting integer literal to `u64` is unnecessary - --> tests/ui/unnecessary_cast.rs:672:48 + --> tests/ui/unnecessary_cast.rs:669:48 | LL | assert!(0x7f_ff_ff_ff_ff_ff_ff_ffu64 == (!(0 as u64 + 0)).overflowing_shr(1_u32).0); | ^^^^^^^^ help: try: `0_u64` error: casting integer literal to `u64` is unnecessary - --> tests/ui/unnecessary_cast.rs:675:54 + --> tests/ui/unnecessary_cast.rs:672:54 | LL | assert!(0x7f_ff_ff_ff_ff_ff_ff_ffu64 == identity(!0 as u64).overflowing_shr(1_u32).0); | ^^^^^^^^^ help: try: `!0_u64` error: casting integer literal to `u64` is unnecessary - --> tests/ui/unnecessary_cast.rs:678:56 + --> tests/ui/unnecessary_cast.rs:675:56 | LL | assert!(0x7f_ff_ff_ff_ff_ff_ff_ffu64 == (!identity(0 as u64)).overflowing_shr(1_u32).0); | ^^^^^^^^ help: try: `0_u64` error: casting integer literal to `u64` is unnecessary - --> tests/ui/unnecessary_cast.rs:680:54 + --> tests/ui/unnecessary_cast.rs:677:54 | LL | assert!(0x7f_ff_ff_ff_ff_ff_ff_ffu64 == identity(!0 as u64 + 0).overflowing_shr(1_u32).0); | ^^^^^^^^^ help: try: `!0_u64` diff --git a/src/tools/clippy/tests/ui/unnecessary_clippy_cfg.rs b/src/tools/clippy/tests/ui/unnecessary_clippy_cfg.rs index 65f67df79131e..0de8ccdf82a22 100644 --- a/src/tools/clippy/tests/ui/unnecessary_clippy_cfg.rs +++ b/src/tools/clippy/tests/ui/unnecessary_clippy_cfg.rs @@ -1,7 +1,7 @@ //@no-rustfix -#![allow(clippy::duplicated_attributes)] #![warn(clippy::unnecessary_clippy_cfg)] +#![expect(clippy::duplicated_attributes)] #![cfg_attr(clippy, deny(clippy::non_minimal_cfg))] //~^ unnecessary_clippy_cfg #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] diff --git a/src/tools/clippy/tests/ui/unnecessary_filter_map.rs b/src/tools/clippy/tests/ui/unnecessary_filter_map.rs index 85582c399ce5f..c09293d9fef51 100644 --- a/src/tools/clippy/tests/ui/unnecessary_filter_map.rs +++ b/src/tools/clippy/tests/ui/unnecessary_filter_map.rs @@ -1,4 +1,5 @@ -#![allow(clippy::redundant_closure)] +#![warn(clippy::unnecessary_filter_map)] +#![expect(clippy::redundant_closure)] fn main() { let _ = (0..4).filter_map(|x| if x > 1 { Some(x) } else { None }); @@ -54,7 +55,6 @@ mod comment_483920107 { impl S { fn foo(&mut self, server_errors: Vec) { - #[allow(unused_variables)] let errors: Vec = server_errors .into_iter() .filter_map(|se| match se.severity() { diff --git a/src/tools/clippy/tests/ui/unnecessary_filter_map.stderr b/src/tools/clippy/tests/ui/unnecessary_filter_map.stderr index 8c33c08c267d5..f5d090f8be633 100644 --- a/src/tools/clippy/tests/ui/unnecessary_filter_map.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_filter_map.stderr @@ -1,5 +1,5 @@ error: this `.filter_map(..)` can be written more simply using `.filter(..)` - --> tests/ui/unnecessary_filter_map.rs:4:20 + --> tests/ui/unnecessary_filter_map.rs:5:20 | LL | let _ = (0..4).filter_map(|x| if x > 1 { Some(x) } else { None }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | let _ = (0..4).filter_map(|x| if x > 1 { Some(x) } else { None }); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_filter_map)]` error: this `.filter_map(..)` can be written more simply using `.filter(..)` - --> tests/ui/unnecessary_filter_map.rs:7:20 + --> tests/ui/unnecessary_filter_map.rs:8:20 | LL | let _ = (0..4).filter_map(|x| { | ____________________^ @@ -21,7 +21,7 @@ LL | | }); | |______^ error: this `.filter_map(..)` can be written more simply using `.filter(..)` - --> tests/ui/unnecessary_filter_map.rs:15:20 + --> tests/ui/unnecessary_filter_map.rs:16:20 | LL | let _ = (0..4).filter_map(|x| match x { | ____________________^ @@ -32,13 +32,13 @@ LL | | }); | |______^ error: this `.filter_map(..)` can be written more simply using `.map(..)` - --> tests/ui/unnecessary_filter_map.rs:21:20 + --> tests/ui/unnecessary_filter_map.rs:22:20 | LL | let _ = (0..4).filter_map(|x| Some(x + 1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: this call to `.filter_map(..)` is unnecessary - --> tests/ui/unnecessary_filter_map.rs:28:46 + --> tests/ui/unnecessary_filter_map.rs:29:46 | LL | let _ = vec![Some(10), None].into_iter().filter_map(|x| Some(x)); | ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_first_then_check.fixed b/src/tools/clippy/tests/ui/unnecessary_first_then_check.fixed index aa049eb33751b..38d3db0672449 100644 --- a/src/tools/clippy/tests/ui/unnecessary_first_then_check.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_first_then_check.fixed @@ -1,5 +1,6 @@ #![warn(clippy::unnecessary_first_then_check)] -#![allow(clippy::useless_vec, clippy::const_is_empty)] +#![allow(clippy::const_is_empty)] +#![expect(clippy::useless_vec)] fn main() { let s = [1, 2, 3]; diff --git a/src/tools/clippy/tests/ui/unnecessary_first_then_check.rs b/src/tools/clippy/tests/ui/unnecessary_first_then_check.rs index 4c2ac3ba40a21..d2a5d68d76096 100644 --- a/src/tools/clippy/tests/ui/unnecessary_first_then_check.rs +++ b/src/tools/clippy/tests/ui/unnecessary_first_then_check.rs @@ -1,5 +1,6 @@ #![warn(clippy::unnecessary_first_then_check)] -#![allow(clippy::useless_vec, clippy::const_is_empty)] +#![allow(clippy::const_is_empty)] +#![expect(clippy::useless_vec)] fn main() { let s = [1, 2, 3]; diff --git a/src/tools/clippy/tests/ui/unnecessary_first_then_check.stderr b/src/tools/clippy/tests/ui/unnecessary_first_then_check.stderr index 408b388ecf71a..a15c09204d48b 100644 --- a/src/tools/clippy/tests/ui/unnecessary_first_then_check.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_first_then_check.stderr @@ -1,5 +1,5 @@ error: unnecessary use of `first().is_some()` to check if slice is not empty - --> tests/ui/unnecessary_first_then_check.rs:6:19 + --> tests/ui/unnecessary_first_then_check.rs:7:19 | LL | let _: bool = s.first().is_some(); | ^^^^^^^^^^^^^^^^^^^ help: replace this with: `!s.is_empty()` @@ -8,37 +8,37 @@ LL | let _: bool = s.first().is_some(); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_first_then_check)]` error: unnecessary use of `first().is_none()` to check if slice is empty - --> tests/ui/unnecessary_first_then_check.rs:8:21 + --> tests/ui/unnecessary_first_then_check.rs:9:21 | LL | let _: bool = s.first().is_none(); | ^^^^^^^^^^^^^^^^^ help: replace this with: `is_empty()` error: unnecessary use of `first().is_some()` to check if slice is not empty - --> tests/ui/unnecessary_first_then_check.rs:12:19 + --> tests/ui/unnecessary_first_then_check.rs:13:19 | LL | let _: bool = v.first().is_some(); | ^^^^^^^^^^^^^^^^^^^ help: replace this with: `!v.is_empty()` error: unnecessary use of `first().is_some()` to check if slice is not empty - --> tests/ui/unnecessary_first_then_check.rs:16:19 + --> tests/ui/unnecessary_first_then_check.rs:17:19 | LL | let _: bool = n[0].first().is_some(); | ^^^^^^^^^^^^^^^^^^^^^^ help: replace this with: `!n[0].is_empty()` error: unnecessary use of `first().is_none()` to check if slice is empty - --> tests/ui/unnecessary_first_then_check.rs:18:24 + --> tests/ui/unnecessary_first_then_check.rs:19:24 | LL | let _: bool = n[0].first().is_none(); | ^^^^^^^^^^^^^^^^^ help: replace this with: `is_empty()` error: unnecessary use of `first().is_some()` to check if slice is not empty - --> tests/ui/unnecessary_first_then_check.rs:25:19 + --> tests/ui/unnecessary_first_then_check.rs:26:19 | LL | let _: bool = f[0].bar.first().is_some(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace this with: `!f[0].bar.is_empty()` error: unnecessary use of `first().is_none()` to check if slice is empty - --> tests/ui/unnecessary_first_then_check.rs:27:28 + --> tests/ui/unnecessary_first_then_check.rs:28:28 | LL | let _: bool = f[0].bar.first().is_none(); | ^^^^^^^^^^^^^^^^^ help: replace this with: `is_empty()` diff --git a/src/tools/clippy/tests/ui/unnecessary_fold.fixed b/src/tools/clippy/tests/ui/unnecessary_fold.fixed index a8370ed03b746..e0883b6ed58f1 100644 --- a/src/tools/clippy/tests/ui/unnecessary_fold.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_fold.fixed @@ -1,4 +1,4 @@ -#![allow(dead_code)] +#![warn(clippy::unnecessary_fold)] fn is_any(acc: bool, x: usize) -> bool { acc || x > 2 diff --git a/src/tools/clippy/tests/ui/unnecessary_fold.rs b/src/tools/clippy/tests/ui/unnecessary_fold.rs index f495da6e720ba..76b149bf5e2de 100644 --- a/src/tools/clippy/tests/ui/unnecessary_fold.rs +++ b/src/tools/clippy/tests/ui/unnecessary_fold.rs @@ -1,4 +1,4 @@ -#![allow(dead_code)] +#![warn(clippy::unnecessary_fold)] fn is_any(acc: bool, x: usize) -> bool { acc || x > 2 diff --git a/src/tools/clippy/tests/ui/unnecessary_iter_cloned.fixed b/src/tools/clippy/tests/ui/unnecessary_iter_cloned.fixed index 61f2e3745ad05..a2782bcd21635 100644 --- a/src/tools/clippy/tests/ui/unnecessary_iter_cloned.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_iter_cloned.fixed @@ -1,7 +1,6 @@ -#![allow(unused_assignments, clippy::uninlined_format_args)] #![warn(clippy::unnecessary_to_owned)] +#![expect(clippy::uninlined_format_args)] -#[allow(dead_code)] #[derive(Clone, Copy)] enum FileType { Account, @@ -74,7 +73,6 @@ fn check_files_ref(files: &[(FileType, &std::path::Path)]) -> bool { true } -#[allow(unused_assignments)] fn check_files_mut(files: &[(FileType, &std::path::Path)]) -> bool { for (mut t, path) in files.iter().copied() { t = FileType::PrivateKey; @@ -122,7 +120,6 @@ fn check_files_self_and_arg(files: &[(FileType, &std::path::Path)]) -> bool { true } -#[allow(unused_assignments)] fn check_files_mut_path_buf(files: &[(FileType, std::path::PathBuf)]) -> bool { for (mut t, path) in files.iter().cloned() { t = FileType::PrivateKey; diff --git a/src/tools/clippy/tests/ui/unnecessary_iter_cloned.rs b/src/tools/clippy/tests/ui/unnecessary_iter_cloned.rs index b90ca00a5fece..1225e6f94ec5a 100644 --- a/src/tools/clippy/tests/ui/unnecessary_iter_cloned.rs +++ b/src/tools/clippy/tests/ui/unnecessary_iter_cloned.rs @@ -1,7 +1,6 @@ -#![allow(unused_assignments, clippy::uninlined_format_args)] #![warn(clippy::unnecessary_to_owned)] +#![expect(clippy::uninlined_format_args)] -#[allow(dead_code)] #[derive(Clone, Copy)] enum FileType { Account, @@ -74,7 +73,6 @@ fn check_files_ref(files: &[(FileType, &std::path::Path)]) -> bool { true } -#[allow(unused_assignments)] fn check_files_mut(files: &[(FileType, &std::path::Path)]) -> bool { for (mut t, path) in files.iter().copied() { t = FileType::PrivateKey; @@ -122,7 +120,6 @@ fn check_files_self_and_arg(files: &[(FileType, &std::path::Path)]) -> bool { true } -#[allow(unused_assignments)] fn check_files_mut_path_buf(files: &[(FileType, std::path::PathBuf)]) -> bool { for (mut t, path) in files.iter().cloned() { t = FileType::PrivateKey; diff --git a/src/tools/clippy/tests/ui/unnecessary_iter_cloned.stderr b/src/tools/clippy/tests/ui/unnecessary_iter_cloned.stderr index d700446fce774..46099e4e2cfbc 100644 --- a/src/tools/clippy/tests/ui/unnecessary_iter_cloned.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_iter_cloned.stderr @@ -1,5 +1,5 @@ error: unnecessary use of `copied` - --> tests/ui/unnecessary_iter_cloned.rs:31:22 + --> tests/ui/unnecessary_iter_cloned.rs:30:22 | LL | for (t, path) in files.iter().copied() { | ^^^^^^^^^^^^^^^^^^^^^ @@ -14,7 +14,7 @@ LL ~ let other = match get_file_path(t) { | error: unnecessary use of `copied` - --> tests/ui/unnecessary_iter_cloned.rs:47:22 + --> tests/ui/unnecessary_iter_cloned.rs:46:22 | LL | for (t, path) in files.iter().copied() { | ^^^^^^^^^^^^^^^^^^^^^ @@ -27,7 +27,7 @@ LL ~ let other = match get_file_path(t) { | error: unnecessary use of `cloned` - --> tests/ui/unnecessary_iter_cloned.rs:179:18 + --> tests/ui/unnecessary_iter_cloned.rs:176:18 | LL | for c in v.iter().cloned() { | ^^^^^^^^^^^^^^^^^ @@ -39,7 +39,7 @@ LL + for c in v.iter() { | error: unnecessary use of `cloned` - --> tests/ui/unnecessary_iter_cloned.rs:188:18 + --> tests/ui/unnecessary_iter_cloned.rs:185:18 | LL | for c in v.iter().cloned() { | ^^^^^^^^^^^^^^^^^ @@ -53,7 +53,7 @@ LL ~ let ref_c = c; | error: unnecessary use of `cloned` - --> tests/ui/unnecessary_iter_cloned.rs:198:23 + --> tests/ui/unnecessary_iter_cloned.rs:195:23 | LL | for (i, c) in v.iter().cloned() { | ^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_join.fixed b/src/tools/clippy/tests/ui/unnecessary_join.fixed index dab09be7ebd09..2f846b7beff4c 100644 --- a/src/tools/clippy/tests/ui/unnecessary_join.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_join.fixed @@ -1,5 +1,5 @@ #![warn(clippy::unnecessary_join)] -#![allow(clippy::uninlined_format_args, clippy::useless_vec)] +#![expect(clippy::uninlined_format_args, clippy::useless_vec)] fn main() { // should be linted diff --git a/src/tools/clippy/tests/ui/unnecessary_join.rs b/src/tools/clippy/tests/ui/unnecessary_join.rs index e58b2696645a9..5dcc394f01570 100644 --- a/src/tools/clippy/tests/ui/unnecessary_join.rs +++ b/src/tools/clippy/tests/ui/unnecessary_join.rs @@ -1,5 +1,5 @@ #![warn(clippy::unnecessary_join)] -#![allow(clippy::uninlined_format_args, clippy::useless_vec)] +#![expect(clippy::uninlined_format_args, clippy::useless_vec)] fn main() { // should be linted diff --git a/src/tools/clippy/tests/ui/unnecessary_lazy_eval.fixed b/src/tools/clippy/tests/ui/unnecessary_lazy_eval.fixed index c8d6b1832a710..c178d41b8861d 100644 --- a/src/tools/clippy/tests/ui/unnecessary_lazy_eval.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_lazy_eval.fixed @@ -1,13 +1,7 @@ //@aux-build: proc_macros.rs #![warn(clippy::unnecessary_lazy_evaluations)] -#![allow(clippy::redundant_closure)] -#![allow(clippy::bind_instead_of_map)] -#![allow(clippy::map_identity)] -#![allow(clippy::needless_borrow)] -#![allow(clippy::unnecessary_literal_unwrap)] -#![allow(clippy::unit_arg)] -#![allow(arithmetic_overflow)] -#![allow(unconditional_panic)] +#![expect(clippy::bind_instead_of_map, clippy::needless_borrow, clippy::redundant_closure)] +#![allow(clippy::unit_arg, clippy::unnecessary_literal_unwrap)] use std::ops::Deref; @@ -252,7 +246,6 @@ fn issue11672_as() { //~^ unnecessary_lazy_evaluations } -#[allow(unused)] fn issue9485() { // should not lint, is in proc macro with_span!(span Some(42).unwrap_or_else(|| 2);); @@ -264,7 +257,7 @@ fn issue9422(x: usize) -> Option { } fn panicky_arithmetic_ops(x: usize, y: isize) { - #![allow(clippy::identity_op, clippy::eq_op)] + #![expect(clippy::eq_op, clippy::identity_op)] // See comments in `eager_or_lazy.rs` for the rules that this is meant to follow diff --git a/src/tools/clippy/tests/ui/unnecessary_lazy_eval.rs b/src/tools/clippy/tests/ui/unnecessary_lazy_eval.rs index 87e903c5bbb8c..33156b4cb986c 100644 --- a/src/tools/clippy/tests/ui/unnecessary_lazy_eval.rs +++ b/src/tools/clippy/tests/ui/unnecessary_lazy_eval.rs @@ -1,13 +1,7 @@ //@aux-build: proc_macros.rs #![warn(clippy::unnecessary_lazy_evaluations)] -#![allow(clippy::redundant_closure)] -#![allow(clippy::bind_instead_of_map)] -#![allow(clippy::map_identity)] -#![allow(clippy::needless_borrow)] -#![allow(clippy::unnecessary_literal_unwrap)] -#![allow(clippy::unit_arg)] -#![allow(arithmetic_overflow)] -#![allow(unconditional_panic)] +#![expect(clippy::bind_instead_of_map, clippy::needless_borrow, clippy::redundant_closure)] +#![allow(clippy::unit_arg, clippy::unnecessary_literal_unwrap)] use std::ops::Deref; @@ -252,7 +246,6 @@ fn issue11672_as() { //~^ unnecessary_lazy_evaluations } -#[allow(unused)] fn issue9485() { // should not lint, is in proc macro with_span!(span Some(42).unwrap_or_else(|| 2);); @@ -264,7 +257,7 @@ fn issue9422(x: usize) -> Option { } fn panicky_arithmetic_ops(x: usize, y: isize) { - #![allow(clippy::identity_op, clippy::eq_op)] + #![expect(clippy::eq_op, clippy::identity_op)] // See comments in `eager_or_lazy.rs` for the rules that this is meant to follow diff --git a/src/tools/clippy/tests/ui/unnecessary_lazy_eval.stderr b/src/tools/clippy/tests/ui/unnecessary_lazy_eval.stderr index 9b91b22f80d3a..93a751a1b15fa 100644 --- a/src/tools/clippy/tests/ui/unnecessary_lazy_eval.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_lazy_eval.stderr @@ -1,5 +1,5 @@ error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:83:13 + --> tests/ui/unnecessary_lazy_eval.rs:77:13 | LL | let _ = opt.unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let _ = opt.unwrap_or(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:85:13 + --> tests/ui/unnecessary_lazy_eval.rs:79:13 | LL | let _ = opt.unwrap_or_else(|| astronomers_pi); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + let _ = opt.unwrap_or(astronomers_pi); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:87:13 + --> tests/ui/unnecessary_lazy_eval.rs:81:13 | LL | let _ = opt.unwrap_or_else(|| ext_str.some_field); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + let _ = opt.unwrap_or(ext_str.some_field); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:90:13 + --> tests/ui/unnecessary_lazy_eval.rs:84:13 | LL | let _ = opt.and_then(|_| ext_opt); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + let _ = opt.and(ext_opt); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:92:13 + --> tests/ui/unnecessary_lazy_eval.rs:86:13 | LL | let _ = opt.or_else(|| ext_opt); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + let _ = opt.or(ext_opt); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:94:13 + --> tests/ui/unnecessary_lazy_eval.rs:88:13 | LL | let _ = opt.or_else(|| None); | ^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + let _ = opt.or(None); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:96:13 + --> tests/ui/unnecessary_lazy_eval.rs:90:13 | LL | let _ = opt.get_or_insert_with(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + let _ = opt.get_or_insert(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:98:13 + --> tests/ui/unnecessary_lazy_eval.rs:92:13 | LL | let _ = opt.ok_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL + let _ = opt.ok_or(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:100:13 + --> tests/ui/unnecessary_lazy_eval.rs:94:13 | LL | let _ = nested_tuple_opt.unwrap_or_else(|| Some((1, 2))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -109,7 +109,7 @@ LL + let _ = nested_tuple_opt.unwrap_or(Some((1, 2))); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:102:13 + --> tests/ui/unnecessary_lazy_eval.rs:96:13 | LL | let _ = cond.then(|| astronomers_pi); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -121,7 +121,7 @@ LL + let _ = cond.then_some(astronomers_pi); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:104:13 + --> tests/ui/unnecessary_lazy_eval.rs:98:13 | LL | let _ = true.then(|| -> _ {}); | ^^^^^^^^^^^^^^^^^^^^^ @@ -133,7 +133,7 @@ LL + let _ = true.then_some({}); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:106:13 + --> tests/ui/unnecessary_lazy_eval.rs:100:13 | LL | let _ = true.then(|| {}); | ^^^^^^^^^^^^^^^^ @@ -145,7 +145,7 @@ LL + let _ = true.then_some({}); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:111:13 + --> tests/ui/unnecessary_lazy_eval.rs:105:13 | LL | let _ = Some(1).unwrap_or_else(|| *r); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -157,7 +157,7 @@ LL + let _ = Some(1).unwrap_or(*r); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:114:13 + --> tests/ui/unnecessary_lazy_eval.rs:108:13 | LL | let _ = Some(1).unwrap_or_else(|| *b); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -169,7 +169,7 @@ LL + let _ = Some(1).unwrap_or(*b); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:117:13 + --> tests/ui/unnecessary_lazy_eval.rs:111:13 | LL | let _ = Some(1).as_ref().unwrap_or_else(|| &r); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -181,7 +181,7 @@ LL + let _ = Some(1).as_ref().unwrap_or(&r); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:119:13 + --> tests/ui/unnecessary_lazy_eval.rs:113:13 | LL | let _ = Some(1).as_ref().unwrap_or_else(|| &b); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -193,7 +193,7 @@ LL + let _ = Some(1).as_ref().unwrap_or(&b); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:123:13 + --> tests/ui/unnecessary_lazy_eval.rs:117:13 | LL | let _ = Some(10).unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -205,7 +205,7 @@ LL + let _ = Some(10).unwrap_or(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:125:13 + --> tests/ui/unnecessary_lazy_eval.rs:119:13 | LL | let _ = Some(10).and_then(|_| ext_opt); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -217,7 +217,7 @@ LL + let _ = Some(10).and(ext_opt); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:127:28 + --> tests/ui/unnecessary_lazy_eval.rs:121:28 | LL | let _: Option = None.or_else(|| ext_opt); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -229,7 +229,7 @@ LL + let _: Option = None.or(ext_opt); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:129:13 + --> tests/ui/unnecessary_lazy_eval.rs:123:13 | LL | let _ = None.get_or_insert_with(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -241,7 +241,7 @@ LL + let _ = None.get_or_insert(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:131:35 + --> tests/ui/unnecessary_lazy_eval.rs:125:35 | LL | let _: Result = None.ok_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^ @@ -253,7 +253,7 @@ LL + let _: Result = None.ok_or(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:133:28 + --> tests/ui/unnecessary_lazy_eval.rs:127:28 | LL | let _: Option = None.or_else(|| None); | ^^^^^^^^^^^^^^^^^^^^^ @@ -265,7 +265,7 @@ LL + let _: Option = None.or(None); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:137:13 + --> tests/ui/unnecessary_lazy_eval.rs:131:13 | LL | let _ = deep.0.unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -277,7 +277,7 @@ LL + let _ = deep.0.unwrap_or(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:139:13 + --> tests/ui/unnecessary_lazy_eval.rs:133:13 | LL | let _ = deep.0.and_then(|_| ext_opt); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -289,7 +289,7 @@ LL + let _ = deep.0.and(ext_opt); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:141:13 + --> tests/ui/unnecessary_lazy_eval.rs:135:13 | LL | let _ = deep.0.or_else(|| None); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -301,7 +301,7 @@ LL + let _ = deep.0.or(None); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:143:13 + --> tests/ui/unnecessary_lazy_eval.rs:137:13 | LL | let _ = deep.0.get_or_insert_with(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -313,7 +313,7 @@ LL + let _ = deep.0.get_or_insert(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:145:13 + --> tests/ui/unnecessary_lazy_eval.rs:139:13 | LL | let _ = deep.0.ok_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -325,7 +325,7 @@ LL + let _ = deep.0.ok_or(2); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:177:28 + --> tests/ui/unnecessary_lazy_eval.rs:171:28 | LL | let _: Option = None.or_else(|| Some(3)); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -337,7 +337,7 @@ LL + let _: Option = None.or(Some(3)); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:179:13 + --> tests/ui/unnecessary_lazy_eval.rs:173:13 | LL | let _ = deep.0.or_else(|| Some(3)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -349,7 +349,7 @@ LL + let _ = deep.0.or(Some(3)); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:181:13 + --> tests/ui/unnecessary_lazy_eval.rs:175:13 | LL | let _ = opt.or_else(|| Some(3)); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -361,7 +361,7 @@ LL + let _ = opt.or(Some(3)); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:188:13 + --> tests/ui/unnecessary_lazy_eval.rs:182:13 | LL | let _ = res2.unwrap_or_else(|_| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -373,7 +373,7 @@ LL + let _ = res2.unwrap_or(2); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:190:13 + --> tests/ui/unnecessary_lazy_eval.rs:184:13 | LL | let _ = res2.unwrap_or_else(|_| astronomers_pi); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -385,7 +385,7 @@ LL + let _ = res2.unwrap_or(astronomers_pi); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:192:13 + --> tests/ui/unnecessary_lazy_eval.rs:186:13 | LL | let _ = res2.unwrap_or_else(|_| ext_str.some_field); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -397,7 +397,7 @@ LL + let _ = res2.unwrap_or(ext_str.some_field); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:215:35 + --> tests/ui/unnecessary_lazy_eval.rs:209:35 | LL | let _: Result = res.and_then(|_| Err(2)); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -409,7 +409,7 @@ LL + let _: Result = res.and(Err(2)); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:217:35 + --> tests/ui/unnecessary_lazy_eval.rs:211:35 | LL | let _: Result = res.and_then(|_| Err(astronomers_pi)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -421,7 +421,7 @@ LL + let _: Result = res.and(Err(astronomers_pi)); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:219:35 + --> tests/ui/unnecessary_lazy_eval.rs:213:35 | LL | let _: Result = res.and_then(|_| Err(ext_str.some_field)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -433,7 +433,7 @@ LL + let _: Result = res.and(Err(ext_str.some_field)); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:222:35 + --> tests/ui/unnecessary_lazy_eval.rs:216:35 | LL | let _: Result = res.or_else(|_| Ok(2)); | ^^^^^^^^^^^^^^^^^^^^^^ @@ -445,7 +445,7 @@ LL + let _: Result = res.or(Ok(2)); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:224:35 + --> tests/ui/unnecessary_lazy_eval.rs:218:35 | LL | let _: Result = res.or_else(|_| Ok(astronomers_pi)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -457,7 +457,7 @@ LL + let _: Result = res.or(Ok(astronomers_pi)); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:226:35 + --> tests/ui/unnecessary_lazy_eval.rs:220:35 | LL | let _: Result = res.or_else(|_| Ok(ext_str.some_field)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -469,7 +469,7 @@ LL + let _: Result = res.or(Ok(ext_str.some_field)); | error: unnecessary closure used to substitute value for `Result::Err` - --> tests/ui/unnecessary_lazy_eval.rs:228:35 + --> tests/ui/unnecessary_lazy_eval.rs:222:35 | LL | let _: Result = res. | ___________________________________^ @@ -484,7 +484,7 @@ LL + or(Ok(ext_str.some_field)); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:245:13 + --> tests/ui/unnecessary_lazy_eval.rs:239:13 | LL | let _ = true.then(|| -> &[u8] { &[] }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -496,7 +496,7 @@ LL + let _ = true.then_some::<&[u8]>({ &[] }); | error: unnecessary closure used to substitute value for `Option::None` - --> tests/ui/unnecessary_lazy_eval.rs:251:13 + --> tests/ui/unnecessary_lazy_eval.rs:245:13 | LL | let _ = None.get_or_insert_with(|| -> &[u8] { &[] }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -508,7 +508,7 @@ LL + let _ = None.get_or_insert({ &[] } as &[u8]); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:271:14 + --> tests/ui/unnecessary_lazy_eval.rs:264:14 | LL | let _x = false.then(|| i32::MAX + 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -520,7 +520,7 @@ LL + let _x = false.then_some(i32::MAX + 1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:273:14 + --> tests/ui/unnecessary_lazy_eval.rs:266:14 | LL | let _x = false.then(|| i32::MAX * 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -532,7 +532,7 @@ LL + let _x = false.then_some(i32::MAX * 2); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:275:14 + --> tests/ui/unnecessary_lazy_eval.rs:268:14 | LL | let _x = false.then(|| i32::MAX - 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -544,7 +544,7 @@ LL + let _x = false.then_some(i32::MAX - 1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:277:14 + --> tests/ui/unnecessary_lazy_eval.rs:270:14 | LL | let _x = false.then(|| i32::MIN - 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -556,7 +556,7 @@ LL + let _x = false.then_some(i32::MIN - 1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:279:14 + --> tests/ui/unnecessary_lazy_eval.rs:272:14 | LL | let _x = false.then(|| (1 + 2 * 3 - 2 / 3 + 9) << 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -568,7 +568,7 @@ LL + let _x = false.then_some((1 + 2 * 3 - 2 / 3 + 9) << 2); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:281:14 + --> tests/ui/unnecessary_lazy_eval.rs:274:14 | LL | let _x = false.then(|| 255u8 << 7); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -580,7 +580,7 @@ LL + let _x = false.then_some(255u8 << 7); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:283:14 + --> tests/ui/unnecessary_lazy_eval.rs:276:14 | LL | let _x = false.then(|| 255u8 << 8); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -592,7 +592,7 @@ LL + let _x = false.then_some(255u8 << 8); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:285:14 + --> tests/ui/unnecessary_lazy_eval.rs:278:14 | LL | let _x = false.then(|| 255u8 >> 8); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -604,7 +604,7 @@ LL + let _x = false.then_some(255u8 >> 8); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:288:14 + --> tests/ui/unnecessary_lazy_eval.rs:281:14 | LL | let _x = false.then(|| i32::MAX + -1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -616,7 +616,7 @@ LL + let _x = false.then_some(i32::MAX + -1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:290:14 + --> tests/ui/unnecessary_lazy_eval.rs:283:14 | LL | let _x = false.then(|| -i32::MAX); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -628,7 +628,7 @@ LL + let _x = false.then_some(-i32::MAX); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:292:14 + --> tests/ui/unnecessary_lazy_eval.rs:285:14 | LL | let _x = false.then(|| -i32::MIN); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -640,7 +640,7 @@ LL + let _x = false.then_some(-i32::MIN); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:295:14 + --> tests/ui/unnecessary_lazy_eval.rs:288:14 | LL | let _x = false.then(|| 255 >> -7); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -652,7 +652,7 @@ LL + let _x = false.then_some(255 >> -7); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:297:14 + --> tests/ui/unnecessary_lazy_eval.rs:290:14 | LL | let _x = false.then(|| 255 << -1); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -664,7 +664,7 @@ LL + let _x = false.then_some(255 << -1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:299:14 + --> tests/ui/unnecessary_lazy_eval.rs:292:14 | LL | let _x = false.then(|| 1 / 0); | ^^^^^^^^^^^^^^^^^^^^ @@ -676,7 +676,7 @@ LL + let _x = false.then_some(1 / 0); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:301:14 + --> tests/ui/unnecessary_lazy_eval.rs:294:14 | LL | let _x = false.then(|| x << -1); | ^^^^^^^^^^^^^^^^^^^^^^ @@ -688,7 +688,7 @@ LL + let _x = false.then_some(x << -1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:303:14 + --> tests/ui/unnecessary_lazy_eval.rs:296:14 | LL | let _x = false.then(|| x << 2); | ^^^^^^^^^^^^^^^^^^^^^ @@ -700,7 +700,7 @@ LL + let _x = false.then_some(x << 2); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:313:14 + --> tests/ui/unnecessary_lazy_eval.rs:306:14 | LL | let _x = false.then(|| x / 0); | ^^^^^^^^^^^^^^^^^^^^ @@ -712,7 +712,7 @@ LL + let _x = false.then_some(x / 0); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:315:14 + --> tests/ui/unnecessary_lazy_eval.rs:308:14 | LL | let _x = false.then(|| x % 0); | ^^^^^^^^^^^^^^^^^^^^ @@ -724,7 +724,7 @@ LL + let _x = false.then_some(x % 0); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:318:14 + --> tests/ui/unnecessary_lazy_eval.rs:311:14 | LL | let _x = false.then(|| 1 / -1); | ^^^^^^^^^^^^^^^^^^^^^ @@ -736,7 +736,7 @@ LL + let _x = false.then_some(1 / -1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:320:14 + --> tests/ui/unnecessary_lazy_eval.rs:313:14 | LL | let _x = false.then(|| i32::MIN / -1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -748,7 +748,7 @@ LL + let _x = false.then_some(i32::MIN / -1); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:323:14 + --> tests/ui/unnecessary_lazy_eval.rs:316:14 | LL | let _x = false.then(|| i32::MIN / 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -760,7 +760,7 @@ LL + let _x = false.then_some(i32::MIN / 0); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:325:14 + --> tests/ui/unnecessary_lazy_eval.rs:318:14 | LL | let _x = false.then(|| 4 / 2); | ^^^^^^^^^^^^^^^^^^^^ @@ -772,7 +772,7 @@ LL + let _x = false.then_some(4 / 2); | error: unnecessary closure used with `bool::then` - --> tests/ui/unnecessary_lazy_eval.rs:333:14 + --> tests/ui/unnecessary_lazy_eval.rs:326:14 | LL | let _x = false.then(|| f1 + f2); | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_lazy_eval_unfixable.rs b/src/tools/clippy/tests/ui/unnecessary_lazy_eval_unfixable.rs index 7ceda40597942..c9b8890861a5d 100644 --- a/src/tools/clippy/tests/ui/unnecessary_lazy_eval_unfixable.rs +++ b/src/tools/clippy/tests/ui/unnecessary_lazy_eval_unfixable.rs @@ -1,5 +1,5 @@ #![warn(clippy::unnecessary_lazy_evaluations)] -#![allow(clippy::unnecessary_literal_unwrap)] +#![expect(clippy::unnecessary_literal_unwrap)] //@no-rustfix struct Deep(Option); diff --git a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.fixed b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.fixed index 05ffdeb1dcc59..96242b9a5ec2d 100644 --- a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.fixed @@ -1,10 +1,9 @@ #![warn(clippy::unnecessary_literal_unwrap)] -#![allow(unreachable_code)] #![allow( - clippy::unnecessary_lazy_evaluations, clippy::diverging_sub_expression, clippy::let_unit_value, - clippy::no_effect + clippy::no_effect, + clippy::unnecessary_lazy_evaluations )] fn unwrap_option_some() { diff --git a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.rs b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.rs index 5efefb24530b9..a901f82c03d64 100644 --- a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.rs +++ b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.rs @@ -1,10 +1,9 @@ #![warn(clippy::unnecessary_literal_unwrap)] -#![allow(unreachable_code)] #![allow( - clippy::unnecessary_lazy_evaluations, clippy::diverging_sub_expression, clippy::let_unit_value, - clippy::no_effect + clippy::no_effect, + clippy::unnecessary_lazy_evaluations )] fn unwrap_option_some() { diff --git a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.stderr b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.stderr index 9c93f5a09bb04..fdad1ee060b91 100644 --- a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap.stderr @@ -1,5 +1,5 @@ error: used `unwrap()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:11:16 + --> tests/ui/unnecessary_literal_unwrap.rs:10:16 | LL | let _val = Some(1).unwrap(); | ^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let _val = 1; | error: used `expect()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:13:16 + --> tests/ui/unnecessary_literal_unwrap.rs:12:16 | LL | let _val = Some(1).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + let _val = 1; | error: used `unwrap()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:16:5 + --> tests/ui/unnecessary_literal_unwrap.rs:15:5 | LL | Some(1).unwrap(); | ^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + 1; | error: used `expect()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:18:5 + --> tests/ui/unnecessary_literal_unwrap.rs:17:5 | LL | Some(1).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + 1; | error: used `unwrap()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:24:16 + --> tests/ui/unnecessary_literal_unwrap.rs:23:16 | LL | let _val = None::<()>.unwrap(); | ^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + let _val = panic!(); | error: used `expect()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:26:16 + --> tests/ui/unnecessary_literal_unwrap.rs:25:16 | LL | let _val = None::<()>.expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + let _val = panic!("this always happens"); | error: used `unwrap_or_default()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:28:24 + --> tests/ui/unnecessary_literal_unwrap.rs:27:24 | LL | let _val: String = None.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + let _val: String = String::default(); | error: used `unwrap_or()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:30:21 + --> tests/ui/unnecessary_literal_unwrap.rs:29:21 | LL | let _val: u16 = None.unwrap_or(234); | ^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL + let _val: u16 = 234; | error: used `unwrap_or_else()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:32:21 + --> tests/ui/unnecessary_literal_unwrap.rs:31:21 | LL | let _val: u16 = None.unwrap_or_else(|| 234); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -109,7 +109,7 @@ LL + let _val: u16 = 234; | error: used `unwrap_or_else()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:34:21 + --> tests/ui/unnecessary_literal_unwrap.rs:33:21 | LL | let _val: u16 = None.unwrap_or_else(|| { 234 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -121,7 +121,7 @@ LL + let _val: u16 = { 234 }; | error: used `unwrap_or_else()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:36:21 + --> tests/ui/unnecessary_literal_unwrap.rs:35:21 | LL | let _val: u16 = None.unwrap_or_else(|| -> u16 { 234 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -133,7 +133,7 @@ LL + let _val: u16 = { 234 }; | error: used `unwrap()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:39:5 + --> tests/ui/unnecessary_literal_unwrap.rs:38:5 | LL | None::<()>.unwrap(); | ^^^^^^^^^^^^^^^^^^^ @@ -145,7 +145,7 @@ LL + panic!(); | error: used `expect()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:41:5 + --> tests/ui/unnecessary_literal_unwrap.rs:40:5 | LL | None::<()>.expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -157,7 +157,7 @@ LL + panic!("this always happens"); | error: used `unwrap_or_default()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:43:5 + --> tests/ui/unnecessary_literal_unwrap.rs:42:5 | LL | None::.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -169,7 +169,7 @@ LL + String::default(); | error: used `unwrap_or()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:45:5 + --> tests/ui/unnecessary_literal_unwrap.rs:44:5 | LL | None::.unwrap_or(234); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -181,7 +181,7 @@ LL + 234; | error: used `unwrap_or_else()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:47:5 + --> tests/ui/unnecessary_literal_unwrap.rs:46:5 | LL | None::.unwrap_or_else(|| 234); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -193,7 +193,7 @@ LL + 234; | error: used `unwrap_or_else()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:49:5 + --> tests/ui/unnecessary_literal_unwrap.rs:48:5 | LL | None::.unwrap_or_else(|| { 234 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -205,7 +205,7 @@ LL + { 234 }; | error: used `unwrap_or_else()` on `None` value - --> tests/ui/unnecessary_literal_unwrap.rs:51:5 + --> tests/ui/unnecessary_literal_unwrap.rs:50:5 | LL | None::.unwrap_or_else(|| -> u16 { 234 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -217,7 +217,7 @@ LL + { 234 }; | error: used `unwrap()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:56:16 + --> tests/ui/unnecessary_literal_unwrap.rs:55:16 | LL | let _val = Ok::<_, ()>(1).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -229,7 +229,7 @@ LL + let _val = 1; | error: used `expect()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:58:16 + --> tests/ui/unnecessary_literal_unwrap.rs:57:16 | LL | let _val = Ok::<_, ()>(1).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -241,7 +241,7 @@ LL + let _val = 1; | error: used `unwrap_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:60:16 + --> tests/ui/unnecessary_literal_unwrap.rs:59:16 | LL | let _val = Ok::<_, ()>(1).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -253,7 +253,7 @@ LL + let _val = panic!("{:?}", 1); | error: used `expect_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:62:16 + --> tests/ui/unnecessary_literal_unwrap.rs:61:16 | LL | let _val = Ok::<_, ()>(1).expect_err("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -265,7 +265,7 @@ LL + let _val = panic!("{1}: {:?}", 1, "this always happens"); | error: used `unwrap()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:65:5 + --> tests/ui/unnecessary_literal_unwrap.rs:64:5 | LL | Ok::<_, ()>(1).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -277,7 +277,7 @@ LL + 1; | error: used `expect()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:67:5 + --> tests/ui/unnecessary_literal_unwrap.rs:66:5 | LL | Ok::<_, ()>(1).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -289,7 +289,7 @@ LL + 1; | error: used `unwrap_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:69:5 + --> tests/ui/unnecessary_literal_unwrap.rs:68:5 | LL | Ok::<_, ()>(1).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -301,7 +301,7 @@ LL + panic!("{:?}", 1); | error: used `expect_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:71:5 + --> tests/ui/unnecessary_literal_unwrap.rs:70:5 | LL | Ok::<_, ()>(1).expect_err("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -313,7 +313,7 @@ LL + panic!("{1}: {:?}", 1, "this always happens"); | error: used `unwrap_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:76:16 + --> tests/ui/unnecessary_literal_unwrap.rs:75:16 | LL | let _val = Err::<(), _>(1).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -325,7 +325,7 @@ LL + let _val = 1; | error: used `expect_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:78:16 + --> tests/ui/unnecessary_literal_unwrap.rs:77:16 | LL | let _val = Err::<(), _>(1).expect_err("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -337,7 +337,7 @@ LL + let _val = 1; | error: used `unwrap()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:80:16 + --> tests/ui/unnecessary_literal_unwrap.rs:79:16 | LL | let _val = Err::<(), _>(1).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -349,7 +349,7 @@ LL + let _val = panic!("{:?}", 1); | error: used `expect()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:82:16 + --> tests/ui/unnecessary_literal_unwrap.rs:81:16 | LL | let _val = Err::<(), _>(1).expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -361,7 +361,7 @@ LL + let _val = panic!("{1}: {:?}", 1, "this always happens"); | error: used `unwrap_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:85:5 + --> tests/ui/unnecessary_literal_unwrap.rs:84:5 | LL | Err::<(), _>(1).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -373,7 +373,7 @@ LL + 1; | error: used `expect_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:87:5 + --> tests/ui/unnecessary_literal_unwrap.rs:86:5 | LL | Err::<(), _>(1).expect_err("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -385,7 +385,7 @@ LL + 1; | error: used `unwrap()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:89:5 + --> tests/ui/unnecessary_literal_unwrap.rs:88:5 | LL | Err::<(), _>(1).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -397,7 +397,7 @@ LL + panic!("{:?}", 1); | error: used `expect()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:91:5 + --> tests/ui/unnecessary_literal_unwrap.rs:90:5 | LL | Err::<(), _>(1).expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -409,7 +409,7 @@ LL + panic!("{1}: {:?}", 1, "this always happens"); | error: used `unwrap_or()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:96:16 + --> tests/ui/unnecessary_literal_unwrap.rs:95:16 | LL | let _val = Some(1).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^ @@ -421,7 +421,7 @@ LL + let _val = 1; | error: used `unwrap_or_default()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:98:16 + --> tests/ui/unnecessary_literal_unwrap.rs:97:16 | LL | let _val = Some(1).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -433,7 +433,7 @@ LL + let _val = 1; | error: used `unwrap_or_else()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:100:16 + --> tests/ui/unnecessary_literal_unwrap.rs:99:16 | LL | let _val = Some(1).unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -445,7 +445,7 @@ LL + let _val = 1; | error: used `unwrap_or()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:103:5 + --> tests/ui/unnecessary_literal_unwrap.rs:102:5 | LL | Some(1).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^ @@ -457,7 +457,7 @@ LL + 1; | error: used `unwrap_or_default()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:105:5 + --> tests/ui/unnecessary_literal_unwrap.rs:104:5 | LL | Some(1).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -469,7 +469,7 @@ LL + 1; | error: used `unwrap_or_else()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:107:5 + --> tests/ui/unnecessary_literal_unwrap.rs:106:5 | LL | Some(1).unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -481,7 +481,7 @@ LL + 1; | error: used `unwrap_or()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:112:16 + --> tests/ui/unnecessary_literal_unwrap.rs:111:16 | LL | let _val = Ok::<_, ()>(1).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -493,7 +493,7 @@ LL + let _val = 1; | error: used `unwrap_or_default()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:114:16 + --> tests/ui/unnecessary_literal_unwrap.rs:113:16 | LL | let _val = Ok::<_, ()>(1).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -505,7 +505,7 @@ LL + let _val = 1; | error: used `unwrap_or_else()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:116:16 + --> tests/ui/unnecessary_literal_unwrap.rs:115:16 | LL | let _val = Ok::<_, ()>(1).unwrap_or_else(|_| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -517,7 +517,7 @@ LL + let _val = 1; | error: used `unwrap_or()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:119:5 + --> tests/ui/unnecessary_literal_unwrap.rs:118:5 | LL | Ok::<_, ()>(1).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -529,7 +529,7 @@ LL + 1; | error: used `unwrap_or_default()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:121:5 + --> tests/ui/unnecessary_literal_unwrap.rs:120:5 | LL | Ok::<_, ()>(1).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -541,7 +541,7 @@ LL + 1; | error: used `unwrap_or_else()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:123:5 + --> tests/ui/unnecessary_literal_unwrap.rs:122:5 | LL | Ok::<_, ()>(1).unwrap_or_else(|_| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -553,7 +553,7 @@ LL + 1; | error: used `unwrap_unchecked()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:138:22 + --> tests/ui/unnecessary_literal_unwrap.rs:137:22 | LL | let _ = unsafe { Some(1).unwrap_unchecked() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -565,7 +565,7 @@ LL + let _ = 1; | error: used `unwrap_unchecked()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:140:22 + --> tests/ui/unnecessary_literal_unwrap.rs:139:22 | LL | let _ = unsafe { Some(1).unwrap_unchecked() + *(&1 as *const i32) }; // needs to keep the unsafe block | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -577,7 +577,7 @@ LL + let _ = unsafe { 1 + *(&1 as *const i32) }; // needs to keep the unsafe | error: used `unwrap_unchecked()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap.rs:143:22 + --> tests/ui/unnecessary_literal_unwrap.rs:142:22 | LL | let _ = unsafe { Some(1).unwrap_unchecked() } + 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -589,7 +589,7 @@ LL + let _ = 1 + 1; | error: used `unwrap_unchecked()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:145:22 + --> tests/ui/unnecessary_literal_unwrap.rs:144:22 | LL | let _ = unsafe { Ok::<_, ()>(1).unwrap_unchecked() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -601,7 +601,7 @@ LL + let _ = 1; | error: used `unwrap_unchecked()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:147:22 + --> tests/ui/unnecessary_literal_unwrap.rs:146:22 | LL | let _ = unsafe { Ok::<_, ()>(1).unwrap_unchecked() + *(&1 as *const i32) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -613,7 +613,7 @@ LL + let _ = unsafe { 1 + *(&1 as *const i32) }; | error: used `unwrap_unchecked()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap.rs:149:22 + --> tests/ui/unnecessary_literal_unwrap.rs:148:22 | LL | let _ = unsafe { Ok::<_, ()>(1).unwrap_unchecked() } + 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -625,7 +625,7 @@ LL + let _ = 1 + 1; | error: used `unwrap_err_unchecked()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap.rs:151:22 + --> tests/ui/unnecessary_literal_unwrap.rs:150:22 | LL | let _ = unsafe { Err::<(), i32>(123).unwrap_err_unchecked() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.rs b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.rs index 2680d0a6697be..cd47d96f1c1e8 100644 --- a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.rs +++ b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.rs @@ -1,6 +1,5 @@ #![warn(clippy::unnecessary_literal_unwrap)] -#![allow(unreachable_code)] -#![allow(clippy::unnecessary_lazy_evaluations, clippy::let_unit_value)] +#![expect(clippy::let_unit_value, clippy::unnecessary_lazy_evaluations)] //@no-rustfix fn unwrap_option_some() { let val = Some(1); diff --git a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.stderr b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.stderr index 39418d0e3a969..278bbefd678dd 100644 --- a/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_literal_unwrap_unfixable.stderr @@ -1,11 +1,11 @@ error: used `unwrap()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:7:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:6:17 | LL | let _val2 = val.unwrap(); | ^^^^^^^^^^^^ | help: remove the `Some` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:6:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:5:15 | LL | let val = Some(1); | ^^^^^^^ @@ -13,91 +13,91 @@ LL | let val = Some(1); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_literal_unwrap)]` error: used `expect()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:10:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:9:17 | LL | let _val2 = val.expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:6:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:5:15 | LL | let val = Some(1); | ^^^^^^^ error: used `unwrap()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:15:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:14:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:15:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:14:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:18:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:17:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:18:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:17:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:22:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:21:17 | LL | let _val2 = val.unwrap(); | ^^^^^^^^^^^^ | help: remove the `Some` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:21:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:20:15 | LL | let val = Some::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:25:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:24:17 | LL | let _val2 = val.expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:21:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:20:15 | LL | let val = Some::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap()` on `None` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:31:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:30:17 | LL | let _val2 = val.unwrap(); | ^^^^^^^^^^^^ | help: remove the `None` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:30:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:29:15 | LL | let val = None::<()>; | ^^^^^^^^^^ error: used `expect()` on `None` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:34:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:33:17 | LL | let _val2 = val.expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `None` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:30:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:29:15 | LL | let val = None::<()>; | ^^^^^^^^^^ error: used `unwrap_or_default()` on `None` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:37:21 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:36:21 | LL | let _val3: u8 = None.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -109,7 +109,7 @@ LL + let _val3: u8 = Default::default(); | error: used `unwrap_or_default()` on `None` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:40:5 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:39:5 | LL | None::<()>.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -121,505 +121,505 @@ LL + Default::default(); | error: used `unwrap()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:46:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:45:17 | LL | let _val2 = val.unwrap(); | ^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:45:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:44:15 | LL | let val = Ok::<_, ()>(1); | ^^^^^^^^^^^^^^ error: used `expect()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:49:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:48:17 | LL | let _val2 = val.expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:45:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:44:15 | LL | let val = Ok::<_, ()>(1); | ^^^^^^^^^^^^^^ error: used `unwrap_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:52:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:51:17 | LL | let _val2 = val.unwrap_err(); | ^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:45:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:44:15 | LL | let val = Ok::<_, ()>(1); | ^^^^^^^^^^^^^^ error: used `expect_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:55:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:54:17 | LL | let _val2 = val.expect_err("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `expect_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:45:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:44:15 | LL | let val = Ok::<_, ()>(1); | ^^^^^^^^^^^^^^ error: used `unwrap()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:60:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:59:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:60:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:59:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:63:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:62:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:63:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:62:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:66:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:65:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:66:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:65:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:69:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:68:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).expect_err("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `expect_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:69:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:68:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).expect_err("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:73:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:72:17 | LL | let _val2 = val.unwrap(); | ^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:72:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:71:15 | LL | let val = Ok::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:76:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:75:17 | LL | let _val2 = val.expect("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:72:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:71:15 | LL | let val = Ok::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:79:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:78:17 | LL | let _val2 = val.unwrap_err(); | ^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:72:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:71:15 | LL | let val = Ok::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect_err()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:82:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:81:17 | LL | let _val2 = val.expect_err("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `expect_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:72:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:71:15 | LL | let val = Ok::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:88:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:87:17 | LL | let _val2 = val.unwrap_err(); | ^^^^^^^^^^^^^^^^ | help: remove the `Err` and `unwrap_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:87:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:86:15 | LL | let val = Err::<(), _>(1); | ^^^^^^^^^^^^^^^ error: used `expect_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:91:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:90:17 | LL | let _val2 = val.expect_err("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `expect_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:87:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:86:15 | LL | let val = Err::<(), _>(1); | ^^^^^^^^^^^^^^^ error: used `unwrap()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:94:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:93:17 | LL | let _val2 = val.unwrap(); | ^^^^^^^^^^^^ | help: remove the `Err` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:87:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:86:15 | LL | let val = Err::<(), _>(1); | ^^^^^^^^^^^^^^^ error: used `expect()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:97:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:96:17 | LL | let _val2 = val.expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:87:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:86:15 | LL | let val = Err::<(), _>(1); | ^^^^^^^^^^^^^^^ error: used `unwrap_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:102:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:101:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `unwrap_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:102:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:101:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).unwrap_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:105:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:104:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).expect_err("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `expect_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:105:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:104:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).expect_err("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:108:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:107:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:108:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:107:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:111:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:110:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:111:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:110:16 | LL | let _val = Err::<(), usize>([1, 2, 3].iter().sum()).expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:115:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:114:17 | LL | let _val2 = val.unwrap_err(); | ^^^^^^^^^^^^^^^^ | help: remove the `Err` and `unwrap_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:114:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:113:15 | LL | let val = Err::<(), usize>([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect_err()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:118:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:117:17 | LL | let _val2 = val.expect_err("this never happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `expect_err()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:114:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:113:15 | LL | let val = Err::<(), usize>([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:121:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:120:17 | LL | let _val2 = val.unwrap(); | ^^^^^^^^^^^^ | help: remove the `Err` and `unwrap()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:114:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:113:15 | LL | let val = Err::<(), usize>([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `expect()` on `Err` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:124:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:123:17 | LL | let _val2 = val.expect("this always happens"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Err` and `expect()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:114:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:113:15 | LL | let val = Err::<(), usize>([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:130:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:129:17 | LL | let _val2 = val.unwrap_or(2); | ^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:129:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:128:15 | LL | let val = Some(1); | ^^^^^^^ error: used `unwrap_or_default()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:133:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:132:17 | LL | let _val2 = val.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or_default()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:129:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:128:15 | LL | let val = Some(1); | ^^^^^^^ error: used `unwrap_or_else()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:136:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:135:17 | LL | let _val2 = val.unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or_else()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:129:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:128:15 | LL | let val = Some(1); | ^^^^^^^ error: used `unwrap_or()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:141:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:140:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:141:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:140:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_default()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:144:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:143:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or_default()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:144:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:143:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_else()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:147:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:146:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or_else()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:147:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:146:16 | LL | let _val = Some::([1, 2, 3].iter().sum()).unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:151:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:150:17 | LL | let _val2 = val.unwrap_or(2); | ^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:150:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:149:15 | LL | let val = Some::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_default()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:154:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:153:17 | LL | let _val2 = val.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or_default()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:150:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:149:15 | LL | let val = Some::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_else()` on `Some` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:157:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:156:17 | LL | let _val2 = val.unwrap_or_else(|| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Some` and `unwrap_or_else()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:150:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:149:15 | LL | let val = Some::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:163:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:162:17 | LL | let _val2 = val.unwrap_or(2); | ^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:162:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:161:15 | LL | let val = Ok::<_, ()>(1); | ^^^^^^^^^^^^^^ error: used `unwrap_or_default()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:166:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:165:17 | LL | let _val2 = val.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or_default()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:162:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:161:15 | LL | let val = Ok::<_, ()>(1); | ^^^^^^^^^^^^^^ error: used `unwrap_or_else()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:169:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:168:17 | LL | let _val2 = val.unwrap_or_else(|_| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or_else()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:162:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:161:15 | LL | let val = Ok::<_, ()>(1); | ^^^^^^^^^^^^^^ error: used `unwrap_or()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:174:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:173:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:174:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:173:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_or(2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_default()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:177:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:176:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or_default()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:177:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:176:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_else()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:180:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:179:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_or_else(|_| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or_else()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:180:16 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:179:16 | LL | let _val = Ok::([1, 2, 3].iter().sum()).unwrap_or_else(|_| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:184:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:183:17 | LL | let _val2 = val.unwrap_or(2); | ^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:183:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:182:15 | LL | let val = Ok::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_default()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:187:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:186:17 | LL | let _val2 = val.unwrap_or_default(); | ^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or_default()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:183:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:182:15 | LL | let val = Ok::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: used `unwrap_or_else()` on `Ok` value - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:190:17 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:189:17 | LL | let _val2 = val.unwrap_or_else(|_| 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | help: remove the `Ok` and `unwrap_or_else()` - --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:183:15 + --> tests/ui/unnecessary_literal_unwrap_unfixable.rs:182:15 | LL | let val = Ok::([1, 2, 3].iter().sum()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.fixed b/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.fixed index 4452fda38c406..9e6059808d3c8 100644 --- a/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.fixed @@ -1,4 +1,3 @@ -#![allow(unused)] #![warn(clippy::unnecessary_map_on_constructor)] use std::ffi::OsStr; diff --git a/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.rs b/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.rs index 0cd41f2b363ac..d731fc13e291c 100644 --- a/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.rs +++ b/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.rs @@ -1,4 +1,3 @@ -#![allow(unused)] #![warn(clippy::unnecessary_map_on_constructor)] use std::ffi::OsStr; diff --git a/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.stderr b/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.stderr index a191168208088..4e31d4f6bc8da 100644 --- a/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_map_on_constructor.stderr @@ -1,5 +1,5 @@ error: unnecessary `map` on constructor `Some(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:32:13 + --> tests/ui/unnecessary_map_on_constructor.rs:31:13 | LL | let a = Some(x).map(fun); | ^^^^^^^^^^^^^^^^ help: try: `Some(fun(x))` @@ -8,43 +8,43 @@ LL | let a = Some(x).map(fun); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_map_on_constructor)]` error: unnecessary `map` on constructor `Ok(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:34:27 + --> tests/ui/unnecessary_map_on_constructor.rs:33:27 | LL | let b: SimpleResult = Ok(x).map(fun); | ^^^^^^^^^^^^^^ help: try: `Ok(fun(x))` error: unnecessary `map_err` on constructor `Err(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:36:27 + --> tests/ui/unnecessary_map_on_constructor.rs:35:27 | LL | let c: SimpleResult = Err(err).map_err(notfun); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Err(notfun(err))` error: unnecessary `map` on constructor `Option::Some(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:39:13 + --> tests/ui/unnecessary_map_on_constructor.rs:38:13 | LL | let a = Option::Some(x).map(fun); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Option::Some(fun(x))` error: unnecessary `map` on constructor `SimpleResult::Ok(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:41:27 + --> tests/ui/unnecessary_map_on_constructor.rs:40:27 | LL | let b: SimpleResult = SimpleResult::Ok(x).map(fun); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `SimpleResult::Ok(fun(x))` error: unnecessary `map_err` on constructor `SimpleResult::Err(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:43:27 + --> tests/ui/unnecessary_map_on_constructor.rs:42:27 | LL | let c: SimpleResult = SimpleResult::Err(err).map_err(notfun); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `SimpleResult::Err(notfun(err))` error: unnecessary `map` on constructor `Ok(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:45:52 + --> tests/ui/unnecessary_map_on_constructor.rs:44:52 | LL | let b: std::result::Result = Ok(x).map(fun); | ^^^^^^^^^^^^^^ help: try: `Ok(fun(x))` error: unnecessary `map_err` on constructor `Err(_)` - --> tests/ui/unnecessary_map_on_constructor.rs:47:52 + --> tests/ui/unnecessary_map_on_constructor.rs:46:52 | LL | let c: std::result::Result = Err(err).map_err(notfun); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Err(notfun(err))` diff --git a/src/tools/clippy/tests/ui/unnecessary_map_or.fixed b/src/tools/clippy/tests/ui/unnecessary_map_or.fixed index b1f991b9b26c0..aa88ea8589aca 100644 --- a/src/tools/clippy/tests/ui/unnecessary_map_or.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_map_or.fixed @@ -1,12 +1,7 @@ //@aux-build:proc_macros.rs #![warn(clippy::unnecessary_map_or)] -#![allow( - clippy::no_effect, - clippy::eq_op, - clippy::unnecessary_lazy_evaluations, - clippy::nonminimal_bool, - clippy::manual_assert_eq -)] +#![expect(clippy::eq_op, clippy::unnecessary_lazy_evaluations)] + #[clippy::msrv = "1.70.0"] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unnecessary_map_or.rs b/src/tools/clippy/tests/ui/unnecessary_map_or.rs index edd5ea9d878fe..cab89bf805616 100644 --- a/src/tools/clippy/tests/ui/unnecessary_map_or.rs +++ b/src/tools/clippy/tests/ui/unnecessary_map_or.rs @@ -1,12 +1,7 @@ //@aux-build:proc_macros.rs #![warn(clippy::unnecessary_map_or)] -#![allow( - clippy::no_effect, - clippy::eq_op, - clippy::unnecessary_lazy_evaluations, - clippy::nonminimal_bool, - clippy::manual_assert_eq -)] +#![expect(clippy::eq_op, clippy::unnecessary_lazy_evaluations)] + #[clippy::msrv = "1.70.0"] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unnecessary_map_or.stderr b/src/tools/clippy/tests/ui/unnecessary_map_or.stderr index 12a973c84213d..6deaa88824752 100644 --- a/src/tools/clippy/tests/ui/unnecessary_map_or.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_map_or.stderr @@ -1,5 +1,5 @@ error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:16:13 + --> tests/ui/unnecessary_map_or.rs:11:13 | LL | let _ = Some(5).map_or(false, |n| n == 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let _ = Some(5) == Some(5); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:18:13 + --> tests/ui/unnecessary_map_or.rs:13:13 | LL | let _ = Some(5).map_or(true, |n| n != 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + let _ = Some(5) != Some(5); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:20:13 + --> tests/ui/unnecessary_map_or.rs:15:13 | LL | let _ = Some(5).map_or(false, |n| { | _____________^ @@ -46,7 +46,7 @@ LL + let _ = Some(5) == Some(5); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:25:13 + --> tests/ui/unnecessary_map_or.rs:20:13 | LL | let _ = Some(5).map_or(false, |n| { | _____________^ @@ -63,7 +63,7 @@ LL + let _ = Some(5).is_some_and(|n| { | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:30:13 + --> tests/ui/unnecessary_map_or.rs:25:13 | LL | let _ = Some(vec![5]).map_or(false, |n| n == [5]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -75,7 +75,7 @@ LL + let _ = Some(vec![5]).is_some_and(|n| n == [5]); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:32:13 + --> tests/ui/unnecessary_map_or.rs:27:13 | LL | let _ = Some(vec![1]).map_or(false, |n| vec![2] == n); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -87,7 +87,7 @@ LL + let _ = Some(vec![1]).is_some_and(|n| vec![2] == n); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:34:13 + --> tests/ui/unnecessary_map_or.rs:29:13 | LL | let _ = Some(5).map_or(false, |n| n == n); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -99,7 +99,7 @@ LL + let _ = Some(5).is_some_and(|n| n == n); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:36:13 + --> tests/ui/unnecessary_map_or.rs:31:13 | LL | let _ = Some(5).map_or(false, |n| n == if 2 > 1 { n } else { 0 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -111,7 +111,7 @@ LL + let _ = Some(5).is_some_and(|n| n == if 2 > 1 { n } else { 0 }); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:38:13 + --> tests/ui/unnecessary_map_or.rs:33:13 | LL | let _ = Ok::, i32>(vec![5]).map_or(false, |n| n == [5]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -123,7 +123,7 @@ LL + let _ = Ok::, i32>(vec![5]).is_ok_and(|n| n == [5]); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:40:13 + --> tests/ui/unnecessary_map_or.rs:35:13 | LL | let _ = Ok::(5).map_or(false, |n| n == 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -135,7 +135,7 @@ LL + let _ = Ok::(5) == Ok(5); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:42:13 + --> tests/ui/unnecessary_map_or.rs:37:13 | LL | let _ = Some(5).map_or(false, |n| n == 5).then(|| 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -147,7 +147,7 @@ LL + let _ = (Some(5) == Some(5)).then(|| 1); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:44:13 + --> tests/ui/unnecessary_map_or.rs:39:13 | LL | let _ = Some(5).map_or(true, |n| n == 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -159,7 +159,7 @@ LL + let _ = Some(5).is_none_or(|n| n == 5); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:46:13 + --> tests/ui/unnecessary_map_or.rs:41:13 | LL | let _ = Some(5).map_or(true, |n| 5 == n); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -171,7 +171,7 @@ LL + let _ = Some(5).is_none_or(|n| 5 == n); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:48:14 + --> tests/ui/unnecessary_map_or.rs:43:14 | LL | let _ = !Some(5).map_or(false, |n| n == 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -183,7 +183,7 @@ LL + let _ = !(Some(5) == Some(5)); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:50:13 + --> tests/ui/unnecessary_map_or.rs:45:13 | LL | let _ = Some(5).map_or(false, |n| n == 5) || false; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -195,7 +195,7 @@ LL + let _ = (Some(5) == Some(5)) || false; | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:52:13 + --> tests/ui/unnecessary_map_or.rs:47:13 | LL | let _ = Some(5).map_or(false, |n| n == 5) as usize; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -207,7 +207,7 @@ LL + let _ = (Some(5) == Some(5)) as usize; | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:77:13 + --> tests/ui/unnecessary_map_or.rs:72:13 | LL | let _ = r.map_or(false, |x| x == 7); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -219,7 +219,7 @@ LL + let _ = r.is_ok_and(|x| x == 7); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:83:13 + --> tests/ui/unnecessary_map_or.rs:78:13 | LL | let _ = r.map_or(false, func); | ^^^^^^^^^^^^^^^^^^^^^ @@ -231,7 +231,7 @@ LL + let _ = r.is_ok_and(func); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:85:13 + --> tests/ui/unnecessary_map_or.rs:80:13 | LL | let _ = Some(5).map_or(false, func); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -243,7 +243,7 @@ LL + let _ = Some(5).is_some_and(func); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:87:13 + --> tests/ui/unnecessary_map_or.rs:82:13 | LL | let _ = Some(5).map_or(true, func); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -255,7 +255,7 @@ LL + let _ = Some(5).is_none_or(func); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:93:13 + --> tests/ui/unnecessary_map_or.rs:88:13 | LL | let _ = r.map_or(false, |x| x == 8); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -267,7 +267,7 @@ LL + let _ = r == Ok(8); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:114:5 + --> tests/ui/unnecessary_map_or.rs:109:5 | LL | o.map_or(true, |n| n > 5) || (o as &Option).map_or(true, |n| n < 5) | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -279,7 +279,7 @@ LL + o.is_none_or(|n| n > 5) || (o as &Option).map_or(true, |n| n < 5) | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:114:34 + --> tests/ui/unnecessary_map_or.rs:109:34 | LL | o.map_or(true, |n| n > 5) || (o as &Option).map_or(true, |n| n < 5) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -291,7 +291,7 @@ LL + o.map_or(true, |n| n > 5) || (o as &Option).is_none_or(|n| n < 5) | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:129:5 + --> tests/ui/unnecessary_map_or.rs:124:5 | LL | o.map_or(true, |n| n > 5) | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -303,7 +303,7 @@ LL + o.is_none_or(|n| n > 5) | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:134:13 + --> tests/ui/unnecessary_map_or.rs:129:13 | LL | let x = a.map_or(false, |a| a == *s); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -315,7 +315,7 @@ LL + let x = a.is_some_and(|a| a == *s); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:136:13 + --> tests/ui/unnecessary_map_or.rs:131:13 | LL | let y = b.map_or(true, |b| b == *s); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -327,7 +327,7 @@ LL + let y = b.is_none_or(|b| b == *s); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:142:13 + --> tests/ui/unnecessary_map_or.rs:137:13 | LL | assert!(Some("test").map_or(false, |x| x == "test")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -339,7 +339,7 @@ LL + assert!(Some("test") == Some("test")); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:146:13 + --> tests/ui/unnecessary_map_or.rs:141:13 | LL | assert!(Some("test").map_or(false, |x| x == "test").then(|| 1).is_some()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -351,7 +351,7 @@ LL + assert!((Some("test") == Some("test")).then(|| 1).is_some()); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:163:9 + --> tests/ui/unnecessary_map_or.rs:158:9 | LL | _ = s.lock().unwrap().map_or(false, |s| s == "foo"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -363,7 +363,7 @@ LL + _ = s.lock().unwrap().is_some_and(|s| s == "foo"); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:167:9 + --> tests/ui/unnecessary_map_or.rs:162:9 | LL | _ = s.map_or(false, |s| s == "foo"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_min_or_max.fixed b/src/tools/clippy/tests/ui/unnecessary_min_or_max.fixed index e2e1700e28b99..fd6f136e99e51 100644 --- a/src/tools/clippy/tests/ui/unnecessary_min_or_max.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_min_or_max.fixed @@ -1,8 +1,7 @@ //@aux-build:external_consts.rs -#![allow(unused)] #![warn(clippy::unnecessary_min_or_max)] -#![allow(clippy::identity_op)] +#![expect(clippy::identity_op)] extern crate external_consts; diff --git a/src/tools/clippy/tests/ui/unnecessary_min_or_max.rs b/src/tools/clippy/tests/ui/unnecessary_min_or_max.rs index dd71ee2080305..a1aede84cd93b 100644 --- a/src/tools/clippy/tests/ui/unnecessary_min_or_max.rs +++ b/src/tools/clippy/tests/ui/unnecessary_min_or_max.rs @@ -1,8 +1,7 @@ //@aux-build:external_consts.rs -#![allow(unused)] #![warn(clippy::unnecessary_min_or_max)] -#![allow(clippy::identity_op)] +#![expect(clippy::identity_op)] extern crate external_consts; diff --git a/src/tools/clippy/tests/ui/unnecessary_min_or_max.stderr b/src/tools/clippy/tests/ui/unnecessary_min_or_max.stderr index b391d21d3bf43..e23450ec2a68f 100644 --- a/src/tools/clippy/tests/ui/unnecessary_min_or_max.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_min_or_max.stderr @@ -1,5 +1,5 @@ error: `(-6_i32)` is never greater than `9` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:13:13 + --> tests/ui/unnecessary_min_or_max.rs:12:13 | LL | let _ = (-6_i32).min(9); | ^^^^^^^^^^^^^^^ help: try: `(-6_i32)` @@ -8,145 +8,145 @@ LL | let _ = (-6_i32).min(9); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_min_or_max)]` error: `(-6_i32)` is never greater than `9` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:15:13 + --> tests/ui/unnecessary_min_or_max.rs:14:13 | LL | let _ = (-6_i32).max(9); | ^^^^^^^^^^^^^^^ help: try: `9` error: `9_u32` is never smaller than `6` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:17:13 + --> tests/ui/unnecessary_min_or_max.rs:16:13 | LL | let _ = 9_u32.min(6); | ^^^^^^^^^^^^ help: try: `6` error: `9_u32` is never smaller than `6` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:19:13 + --> tests/ui/unnecessary_min_or_max.rs:18:13 | LL | let _ = 9_u32.max(6); | ^^^^^^^^^^^^ help: try: `9_u32` error: `6` is never greater than `7_u8` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:21:13 + --> tests/ui/unnecessary_min_or_max.rs:20:13 | LL | let _ = 6.min(7_u8); | ^^^^^^^^^^^ help: try: `6` error: `6` is never greater than `7_u8` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:23:13 + --> tests/ui/unnecessary_min_or_max.rs:22:13 | LL | let _ = 6.max(7_u8); | ^^^^^^^^^^^ help: try: `7_u8` error: `0` is never greater than `x` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:28:13 + --> tests/ui/unnecessary_min_or_max.rs:27:13 | LL | let _ = 0.min(x); | ^^^^^^^^ help: try: `0` error: `0` is never greater than `x` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:30:13 + --> tests/ui/unnecessary_min_or_max.rs:29:13 | LL | let _ = 0.max(x); | ^^^^^^^^ help: try: `x` error: `x` is never smaller than `0_u32` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:32:13 + --> tests/ui/unnecessary_min_or_max.rs:31:13 | LL | let _ = x.min(0_u32); | ^^^^^^^^^^^^ help: try: `0_u32` error: `x` is never smaller than `0_u32` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:34:13 + --> tests/ui/unnecessary_min_or_max.rs:33:13 | LL | let _ = x.max(0_u32); | ^^^^^^^^^^^^ help: try: `x` error: `i32::MIN` is never greater than `x` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:39:13 + --> tests/ui/unnecessary_min_or_max.rs:38:13 | LL | let _ = i32::MIN.min(x); | ^^^^^^^^^^^^^^^ help: try: `i32::MIN` error: `i32::MIN` is never greater than `x` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:41:13 + --> tests/ui/unnecessary_min_or_max.rs:40:13 | LL | let _ = i32::MIN.max(x); | ^^^^^^^^^^^^^^^ help: try: `x` error: `x` is never smaller than `i32::MIN` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:43:13 + --> tests/ui/unnecessary_min_or_max.rs:42:13 | LL | let _ = x.min(i32::MIN); | ^^^^^^^^^^^^^^^ help: try: `i32::MIN` error: `x` is never smaller than `i32::MIN` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:45:13 + --> tests/ui/unnecessary_min_or_max.rs:44:13 | LL | let _ = x.max(i32::MIN); | ^^^^^^^^^^^^^^^ help: try: `x` error: `x` is never smaller than `i32::MIN - 0` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:48:13 + --> tests/ui/unnecessary_min_or_max.rs:47:13 | LL | let _ = x.min(i32::MIN - 0); | ^^^^^^^^^^^^^^^^^^^ help: try: `i32::MIN - 0` error: `x` is never smaller than `i32::MIN` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:50:13 + --> tests/ui/unnecessary_min_or_max.rs:49:13 | LL | let _ = x.max(i32::MIN); | ^^^^^^^^^^^^^^^ help: try: `x` error: `x` is never smaller than `i32::MIN - 0` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:53:13 + --> tests/ui/unnecessary_min_or_max.rs:52:13 | LL | let _ = x.min(i32::MIN - 0); | ^^^^^^^^^^^^^^^^^^^ help: try: `i32::MIN - 0` error: `n` is never smaller than `0` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:83:13 + --> tests/ui/unnecessary_min_or_max.rs:82:13 | LL | let _ = n.min(0); | ^^^^^^^^ help: try: `0` error: `n` is never smaller than `0usize` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:86:13 + --> tests/ui/unnecessary_min_or_max.rs:85:13 | LL | let _ = n.min(0usize); | ^^^^^^^^^^^^^ help: try: `0usize` error: `(0usize)` is never greater than `n` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:89:13 + --> tests/ui/unnecessary_min_or_max.rs:88:13 | LL | let _ = (0usize).min(n); | ^^^^^^^^^^^^^^^ help: try: `(0usize)` error: `n` is never smaller than `usize::MIN` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:92:13 + --> tests/ui/unnecessary_min_or_max.rs:91:13 | LL | let _ = n.min(usize::MIN); | ^^^^^^^^^^^^^^^^^ help: try: `usize::MIN` error: `n` is never greater than `usize::MAX` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:95:13 + --> tests/ui/unnecessary_min_or_max.rs:94:13 | LL | let _ = n.max(usize::MAX); | ^^^^^^^^^^^^^^^^^ help: try: `usize::MAX` error: `(usize::MAX)` is never smaller than `n` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:98:13 + --> tests/ui/unnecessary_min_or_max.rs:97:13 | LL | let _ = (usize::MAX).max(n); | ^^^^^^^^^^^^^^^^^^^ help: try: `(usize::MAX)` error: `n` is never greater than `!0usize` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:101:13 + --> tests/ui/unnecessary_min_or_max.rs:100:13 | LL | let _ = n.max(!0usize); | ^^^^^^^^^^^^^^ help: try: `!0usize` error: `n` is never smaller than `0` and has therefore no effect - --> tests/ui/unnecessary_min_or_max.rs:104:13 + --> tests/ui/unnecessary_min_or_max.rs:103:13 | LL | let _ = n.max(0); | ^^^^^^^^ help: try: `n` diff --git a/src/tools/clippy/tests/ui/unnecessary_mut_passed.fixed b/src/tools/clippy/tests/ui/unnecessary_mut_passed.fixed index 876b61d29519b..7fff62b9e9384 100644 --- a/src/tools/clippy/tests/ui/unnecessary_mut_passed.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_mut_passed.fixed @@ -1,4 +1,5 @@ -#![allow(clippy::mut_mut)] +#![warn(clippy::unnecessary_mut_passed)] +#![expect(clippy::mut_mut)] fn takes_ref(a: &i32) {} fn takes_refmut(a: &mut i32) {} diff --git a/src/tools/clippy/tests/ui/unnecessary_mut_passed.rs b/src/tools/clippy/tests/ui/unnecessary_mut_passed.rs index e92368bfffeb6..9beb4851db619 100644 --- a/src/tools/clippy/tests/ui/unnecessary_mut_passed.rs +++ b/src/tools/clippy/tests/ui/unnecessary_mut_passed.rs @@ -1,4 +1,5 @@ -#![allow(clippy::mut_mut)] +#![warn(clippy::unnecessary_mut_passed)] +#![expect(clippy::mut_mut)] fn takes_ref(a: &i32) {} fn takes_refmut(a: &mut i32) {} diff --git a/src/tools/clippy/tests/ui/unnecessary_mut_passed.stderr b/src/tools/clippy/tests/ui/unnecessary_mut_passed.stderr index ace11027e3e25..ff379d2132cf3 100644 --- a/src/tools/clippy/tests/ui/unnecessary_mut_passed.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_mut_passed.stderr @@ -1,5 +1,5 @@ error: the function `takes_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:57:15 + --> tests/ui/unnecessary_mut_passed.rs:58:15 | LL | takes_ref(&mut 42); | ^^^^^^^ @@ -13,7 +13,7 @@ LL + takes_ref(&42); | error: the function `takes_ref_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:59:19 + --> tests/ui/unnecessary_mut_passed.rs:60:19 | LL | takes_ref_ref(&mut &42); | ^^^^^^^^ @@ -25,7 +25,7 @@ LL + takes_ref_ref(&&42); | error: the function `takes_ref_refmut` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:61:22 + --> tests/ui/unnecessary_mut_passed.rs:62:22 | LL | takes_ref_refmut(&mut &mut 42); | ^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + takes_ref_refmut(&&mut 42); | error: the function `takes_raw_const` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:63:21 + --> tests/ui/unnecessary_mut_passed.rs:64:21 | LL | takes_raw_const(&mut 42); | ^^^^^^^ @@ -49,7 +49,7 @@ LL + takes_raw_const(&42); | error: the function `as_ptr` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:67:12 + --> tests/ui/unnecessary_mut_passed.rs:68:12 | LL | as_ptr(&mut 42); | ^^^^^^^ @@ -61,7 +61,7 @@ LL + as_ptr(&42); | error: the function `as_ptr` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:70:12 + --> tests/ui/unnecessary_mut_passed.rs:71:12 | LL | as_ptr(&mut &42); | ^^^^^^^^ @@ -73,7 +73,7 @@ LL + as_ptr(&&42); | error: the function `as_ptr` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:73:12 + --> tests/ui/unnecessary_mut_passed.rs:74:12 | LL | as_ptr(&mut &mut 42); | ^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + as_ptr(&&mut 42); | error: the function `as_ptr` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:76:12 + --> tests/ui/unnecessary_mut_passed.rs:77:12 | LL | as_ptr(&mut 42); | ^^^^^^^ @@ -97,7 +97,7 @@ LL + as_ptr(&42); | error: the method `takes_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:81:25 + --> tests/ui/unnecessary_mut_passed.rs:82:25 | LL | my_struct.takes_ref(&mut 42); | ^^^^^^^ @@ -109,7 +109,7 @@ LL + my_struct.takes_ref(&42); | error: the method `takes_ref_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:83:29 + --> tests/ui/unnecessary_mut_passed.rs:84:29 | LL | my_struct.takes_ref_ref(&mut &42); | ^^^^^^^^ @@ -121,7 +121,7 @@ LL + my_struct.takes_ref_ref(&&42); | error: the method `takes_ref_refmut` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:85:32 + --> tests/ui/unnecessary_mut_passed.rs:86:32 | LL | my_struct.takes_ref_refmut(&mut &mut 42); | ^^^^^^^^^^^^ @@ -133,7 +133,7 @@ LL + my_struct.takes_ref_refmut(&&mut 42); | error: the method `takes_raw_const` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:87:31 + --> tests/ui/unnecessary_mut_passed.rs:88:31 | LL | my_struct.takes_raw_const(&mut 42); | ^^^^^^^ @@ -145,7 +145,7 @@ LL + my_struct.takes_raw_const(&42); | error: the method `takes_nothing` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:175:5 + --> tests/ui/unnecessary_mut_passed.rs:176:5 | LL | (&mut my_struct).takes_nothing(); | ^^^^^^^^^^^^^^^^ @@ -157,7 +157,7 @@ LL + (&my_struct).takes_nothing(); | error: the method `takes_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:180:5 + --> tests/ui/unnecessary_mut_passed.rs:181:5 | LL | (&mut my_struct).takes_ref(&mut 42); | ^^^^^^^^^^^^^^^^ @@ -169,7 +169,7 @@ LL + (&my_struct).takes_ref(&mut 42); | error: the method `takes_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:180:32 + --> tests/ui/unnecessary_mut_passed.rs:181:32 | LL | (&mut my_struct).takes_ref(&mut 42); | ^^^^^^^ @@ -181,7 +181,7 @@ LL + (&mut my_struct).takes_ref(&42); | error: the method `takes_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:184:5 + --> tests/ui/unnecessary_mut_passed.rs:185:5 | LL | (&mut my_struct).takes_ref((&mut 42)); | ^^^^^^^^^^^^^^^^ @@ -193,7 +193,7 @@ LL + (&my_struct).takes_ref((&mut 42)); | error: the method `takes_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:184:32 + --> tests/ui/unnecessary_mut_passed.rs:185:32 | LL | (&mut my_struct).takes_ref((&mut 42)); | ^^^^^^^^^ @@ -205,7 +205,7 @@ LL + (&mut my_struct).takes_ref((&42)); | error: the method `takes_ref` doesn't need a mutable reference - --> tests/ui/unnecessary_mut_passed.rs:188:25 + --> tests/ui/unnecessary_mut_passed.rs:189:25 | LL | my_struct.takes_ref((&mut 42)); | ^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_operation.fixed b/src/tools/clippy/tests/ui/unnecessary_operation.fixed index 2b447e5c4a36d..092cc7c348909 100644 --- a/src/tools/clippy/tests/ui/unnecessary_operation.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_operation.fixed @@ -1,12 +1,5 @@ -#![allow( - clippy::deref_addrof, - clippy::no_effect, - clippy::uninlined_format_args, - clippy::unnecessary_struct_initialization, - dead_code, - unused -)] #![warn(clippy::unnecessary_operation)] +#![allow(clippy::deref_addrof, clippy::no_effect)] use std::fmt::Display; use std::ops::Shl; diff --git a/src/tools/clippy/tests/ui/unnecessary_operation.rs b/src/tools/clippy/tests/ui/unnecessary_operation.rs index def14469c9bdc..c298bd8c15fcb 100644 --- a/src/tools/clippy/tests/ui/unnecessary_operation.rs +++ b/src/tools/clippy/tests/ui/unnecessary_operation.rs @@ -1,12 +1,5 @@ -#![allow( - clippy::deref_addrof, - clippy::no_effect, - clippy::uninlined_format_args, - clippy::unnecessary_struct_initialization, - dead_code, - unused -)] #![warn(clippy::unnecessary_operation)] +#![allow(clippy::deref_addrof, clippy::no_effect)] use std::fmt::Display; use std::ops::Shl; diff --git a/src/tools/clippy/tests/ui/unnecessary_operation.stderr b/src/tools/clippy/tests/ui/unnecessary_operation.stderr index 55751cb08b136..92434be9d798e 100644 --- a/src/tools/clippy/tests/ui/unnecessary_operation.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_operation.stderr @@ -1,5 +1,5 @@ error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:71:5 + --> tests/ui/unnecessary_operation.rs:64:5 | LL | Tuple(get_number()); | ^^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` @@ -8,103 +8,103 @@ LL | Tuple(get_number()); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_operation)]` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:73:5 + --> tests/ui/unnecessary_operation.rs:66:5 | LL | Struct { field: get_number() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:75:5 + --> tests/ui/unnecessary_operation.rs:68:5 | LL | Struct { ..get_struct() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_struct();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:77:5 + --> tests/ui/unnecessary_operation.rs:70:5 | LL | Enum::Tuple(get_number()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:79:5 + --> tests/ui/unnecessary_operation.rs:72:5 | LL | Enum::Struct { field: get_number() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:81:5 + --> tests/ui/unnecessary_operation.rs:74:5 | LL | 5 + get_number(); | ^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `5; get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:83:5 + --> tests/ui/unnecessary_operation.rs:76:5 | LL | *&get_number(); | ^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:85:5 + --> tests/ui/unnecessary_operation.rs:78:5 | LL | &get_number(); | ^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:87:5 + --> tests/ui/unnecessary_operation.rs:80:5 | LL | (5, 6, get_number()); | ^^^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `5; 6; get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:89:5 + --> tests/ui/unnecessary_operation.rs:82:5 | LL | get_number()..; | ^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:91:5 + --> tests/ui/unnecessary_operation.rs:84:5 | LL | ..get_number(); | ^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:93:5 + --> tests/ui/unnecessary_operation.rs:86:5 | LL | 5..get_number(); | ^^^^^^^^^^^^^^^^ help: statement can be reduced to: `5; get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:95:5 + --> tests/ui/unnecessary_operation.rs:88:5 | LL | [42, get_number()]; | ^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `42; get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:97:5 + --> tests/ui/unnecessary_operation.rs:90:5 | LL | [42, 55][get_usize()]; | ^^^^^^^^^^^^^^^^^^^^^^ help: statement can be written as: `assert!([42, 55].len() > get_usize());` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:99:5 + --> tests/ui/unnecessary_operation.rs:92:5 | LL | (42, get_number()).1; | ^^^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `42; get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:101:5 + --> tests/ui/unnecessary_operation.rs:94:5 | LL | [get_number(); 55]; | ^^^^^^^^^^^^^^^^^^^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:103:5 + --> tests/ui/unnecessary_operation.rs:96:5 | LL | [42; 55][get_usize()]; | ^^^^^^^^^^^^^^^^^^^^^^ help: statement can be written as: `assert!([42; 55].len() > get_usize());` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:105:5 + --> tests/ui/unnecessary_operation.rs:98:5 | LL | / { LL | | @@ -113,7 +113,7 @@ LL | | }; | |______^ help: statement can be reduced to: `get_number();` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:109:5 + --> tests/ui/unnecessary_operation.rs:102:5 | LL | / FooString { LL | | @@ -122,13 +122,13 @@ LL | | }; | |______^ help: statement can be reduced to: `String::from("blah");` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:150:5 + --> tests/ui/unnecessary_operation.rs:143:5 | LL | [42, 55][get_usize()]; | ^^^^^^^^^^^^^^^^^^^^^^ help: statement can be written as: `assert!([42, 55].len() > get_usize());` error: unnecessary operation - --> tests/ui/unnecessary_operation.rs:181:9 + --> tests/ui/unnecessary_operation.rs:174:9 | LL | / { LL | | never() diff --git a/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.fixed b/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.fixed index 8d25efbeea001..867528dd7e44f 100644 --- a/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.fixed @@ -1,11 +1,11 @@ #![warn(clippy::unnecessary_option_map_or_else)] #![allow( - clippy::let_and_return, clippy::let_unit_value, + clippy::needless_return, clippy::unnecessary_lazy_evaluations, - clippy::unnecessary_literal_unwrap, - clippy::needless_return + clippy::unnecessary_literal_unwrap )] +#![expect(clippy::let_and_return)] const fn double_it(x: i32) -> i32 { x * 2 diff --git a/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.rs b/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.rs index 42d4ad6ac1f82..325e63879ba24 100644 --- a/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.rs +++ b/src/tools/clippy/tests/ui/unnecessary_option_map_or_else.rs @@ -1,11 +1,11 @@ #![warn(clippy::unnecessary_option_map_or_else)] #![allow( - clippy::let_and_return, clippy::let_unit_value, + clippy::needless_return, clippy::unnecessary_lazy_evaluations, - clippy::unnecessary_literal_unwrap, - clippy::needless_return + clippy::unnecessary_literal_unwrap )] +#![expect(clippy::let_and_return)] const fn double_it(x: i32) -> i32 { x * 2 diff --git a/src/tools/clippy/tests/ui/unnecessary_os_str_debug_formatting.rs b/src/tools/clippy/tests/ui/unnecessary_os_str_debug_formatting.rs index 66590be3d0543..c5b279ea2ae12 100644 --- a/src/tools/clippy/tests/ui/unnecessary_os_str_debug_formatting.rs +++ b/src/tools/clippy/tests/ui/unnecessary_os_str_debug_formatting.rs @@ -1,5 +1,5 @@ #![warn(clippy::unnecessary_debug_formatting)] -#![allow(clippy::uninlined_format_args)] +#![expect(clippy::uninlined_format_args)] use std::ffi::{OsStr, OsString}; diff --git a/src/tools/clippy/tests/ui/unnecessary_path_debug_formatting.rs b/src/tools/clippy/tests/ui/unnecessary_path_debug_formatting.rs index 215e0d5d7802e..303cded913071 100644 --- a/src/tools/clippy/tests/ui/unnecessary_path_debug_formatting.rs +++ b/src/tools/clippy/tests/ui/unnecessary_path_debug_formatting.rs @@ -1,5 +1,5 @@ #![warn(clippy::unnecessary_debug_formatting)] -#![allow(clippy::uninlined_format_args)] +#![expect(clippy::uninlined_format_args)] use std::ffi::{OsStr, OsString}; use std::ops::Deref; diff --git a/src/tools/clippy/tests/ui/unnecessary_rest_pattern.fixed b/src/tools/clippy/tests/ui/unnecessary_rest_pattern.fixed new file mode 100644 index 0000000000000..830f868226678 --- /dev/null +++ b/src/tools/clippy/tests/ui/unnecessary_rest_pattern.fixed @@ -0,0 +1,90 @@ +//@aux-build:proc_macros.rs +//@aux-build:non-exhaustive-struct.rs +#![warn(clippy::unnecessary_rest_pattern)] +#![allow(clippy::unneeded_wildcard_pattern)] + +use non_exhaustive_struct::{NonExhaustiveStruct, NonExhaustiveStructNoPrivateFields}; + +struct S { + a: u8, + b: u8, + c: u8, +} + +#[derive(Default)] +#[non_exhaustive] +struct LocalNonExhaustive { + field: i32, +} + +enum E { + A { a1: u8, a2: u8 }, + B { b1: u8, b2: u8 }, + C {}, +} + +mod m { + #[derive(Default)] + pub struct Sm { + pub a: u8, + pub(crate) b: u8, + c: u8, + } +} + +fn main() { + let s = S { a: 1, b: 2, c: 3 }; + + let S { a, b, c, } = s; + //~^ unnecessary_rest_pattern + + let e = E::A { a1: 1, a2: 2 }; + + match e { + E::A { a1, a2 } => (), + E::B { b1, b2, } => (), + //~^ unnecessary_rest_pattern + E::C { } => (), + //~^ unnecessary_rest_pattern + } + + proc_macros::external! { + let s1 = S { a: 1, b: 2, c: 3 }; + let S { a, b, c, .. } = s1; + } + + proc_macros::with_span! { + span + let s2 = S { a: 1, b: 2, c: 3 }; + let S { a, b, c, .. } = s2; + } + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { field1: _, .. } = ne; + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { + field1: _, field2: _, .. + } = ne; + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { .. } = ne; + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { field: _, .. } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _ } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _, } = ne; + //~^ unnecessary_rest_pattern + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { .. } = ne; + + use m::Sm; + + let Sm { .. } = Sm::default(); + let Sm { a: _, b: _, .. } = Sm::default(); +} diff --git a/src/tools/clippy/tests/ui/unnecessary_rest_pattern.rs b/src/tools/clippy/tests/ui/unnecessary_rest_pattern.rs new file mode 100644 index 0000000000000..51ed4b1e18042 --- /dev/null +++ b/src/tools/clippy/tests/ui/unnecessary_rest_pattern.rs @@ -0,0 +1,90 @@ +//@aux-build:proc_macros.rs +//@aux-build:non-exhaustive-struct.rs +#![warn(clippy::unnecessary_rest_pattern)] +#![allow(clippy::unneeded_wildcard_pattern)] + +use non_exhaustive_struct::{NonExhaustiveStruct, NonExhaustiveStructNoPrivateFields}; + +struct S { + a: u8, + b: u8, + c: u8, +} + +#[derive(Default)] +#[non_exhaustive] +struct LocalNonExhaustive { + field: i32, +} + +enum E { + A { a1: u8, a2: u8 }, + B { b1: u8, b2: u8 }, + C {}, +} + +mod m { + #[derive(Default)] + pub struct Sm { + pub a: u8, + pub(crate) b: u8, + c: u8, + } +} + +fn main() { + let s = S { a: 1, b: 2, c: 3 }; + + let S { a, b, c, .. } = s; + //~^ unnecessary_rest_pattern + + let e = E::A { a1: 1, a2: 2 }; + + match e { + E::A { a1, a2 } => (), + E::B { b1, b2, .. } => (), + //~^ unnecessary_rest_pattern + E::C { .. } => (), + //~^ unnecessary_rest_pattern + } + + proc_macros::external! { + let s1 = S { a: 1, b: 2, c: 3 }; + let S { a, b, c, .. } = s1; + } + + proc_macros::with_span! { + span + let s2 = S { a: 1, b: 2, c: 3 }; + let S { a, b, c, .. } = s2; + } + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { field1: _, .. } = ne; + + let ne = NonExhaustiveStruct::default(); + let NonExhaustiveStruct { + field1: _, field2: _, .. + } = ne; + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { .. } = ne; + + let ne = NonExhaustiveStructNoPrivateFields::default(); + let NonExhaustiveStructNoPrivateFields { field: _, .. } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _ } = ne; + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { field: _, .. } = ne; + //~^ unnecessary_rest_pattern + + let ne = LocalNonExhaustive::default(); + let LocalNonExhaustive { .. } = ne; + + use m::Sm; + + let Sm { .. } = Sm::default(); + let Sm { a: _, b: _, .. } = Sm::default(); +} diff --git a/src/tools/clippy/tests/ui/unnecessary_rest_pattern.stderr b/src/tools/clippy/tests/ui/unnecessary_rest_pattern.stderr new file mode 100644 index 0000000000000..2c8e66f9d1034 --- /dev/null +++ b/src/tools/clippy/tests/ui/unnecessary_rest_pattern.stderr @@ -0,0 +1,52 @@ +error: unnecessary rest pattern (`..`) + --> tests/ui/unnecessary_rest_pattern.rs:38:9 + | +LL | let S { a, b, c, .. } = s; + | ^^^^^^^^^^^^^^^^^ + | + = note: `-D clippy::unnecessary-rest-pattern` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::unnecessary_rest_pattern)]` +help: consider removing the unnecessary rest pattern (`..`) + | +LL - let S { a, b, c, .. } = s; +LL + let S { a, b, c, } = s; + | + +error: unnecessary rest pattern (`..`) + --> tests/ui/unnecessary_rest_pattern.rs:45:9 + | +LL | E::B { b1, b2, .. } => (), + | ^^^^^^^^^^^^^^^^^^^ + | +help: consider removing the unnecessary rest pattern (`..`) + | +LL - E::B { b1, b2, .. } => (), +LL + E::B { b1, b2, } => (), + | + +error: unnecessary rest pattern (`..`) + --> tests/ui/unnecessary_rest_pattern.rs:47:9 + | +LL | E::C { .. } => (), + | ^^^^^^^^^^^ + | +help: consider removing the unnecessary rest pattern (`..`) + | +LL - E::C { .. } => (), +LL + E::C { } => (), + | + +error: unnecessary rest pattern (`..`) + --> tests/ui/unnecessary_rest_pattern.rs:80:9 + | +LL | let LocalNonExhaustive { field: _, .. } = ne; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: consider removing the unnecessary rest pattern (`..`) + | +LL - let LocalNonExhaustive { field: _, .. } = ne; +LL + let LocalNonExhaustive { field: _, } = ne; + | + +error: aborting due to 4 previous errors + diff --git a/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.fixed b/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.fixed index 55542519bdb7e..2bb8e22a0bb90 100644 --- a/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.fixed @@ -1,10 +1,6 @@ #![warn(clippy::unnecessary_result_map_or_else)] -#![allow( - clippy::unnecessary_literal_unwrap, - clippy::let_and_return, - clippy::let_unit_value, - clippy::needless_return -)] +#![allow(clippy::needless_return, clippy::unnecessary_literal_unwrap)] +#![expect(clippy::let_and_return, clippy::let_unit_value)] fn main() { let x: Result<(), ()> = Ok(()); diff --git a/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.rs b/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.rs index 21a4826911e58..829dd035adc32 100644 --- a/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.rs +++ b/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.rs @@ -1,10 +1,6 @@ #![warn(clippy::unnecessary_result_map_or_else)] -#![allow( - clippy::unnecessary_literal_unwrap, - clippy::let_and_return, - clippy::let_unit_value, - clippy::needless_return -)] +#![allow(clippy::needless_return, clippy::unnecessary_literal_unwrap)] +#![expect(clippy::let_and_return, clippy::let_unit_value)] fn main() { let x: Result<(), ()> = Ok(()); diff --git a/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.stderr b/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.stderr index f76999127c647..2443083d4390c 100644 --- a/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_result_map_or_else.stderr @@ -1,5 +1,5 @@ error: unused "map closure" when calling `Result::map_or_else` value - --> tests/ui/unnecessary_result_map_or_else.rs:11:5 + --> tests/ui/unnecessary_result_map_or_else.rs:7:5 | LL | x.map_or_else(|err| err, |n| n); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + x.unwrap_or_else(|err| err); | error: unused "map closure" when calling `Result::map_or_else` value - --> tests/ui/unnecessary_result_map_or_else.rs:16:5 + --> tests/ui/unnecessary_result_map_or_else.rs:12:5 | LL | x.map_or_else(|err: ()| err, |n: ()| n); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + x.unwrap_or_else(|err: ()| err); | error: unused "map closure" when calling `Result::map_or_else` value - --> tests/ui/unnecessary_result_map_or_else.rs:27:5 + --> tests/ui/unnecessary_result_map_or_else.rs:23:5 | LL | / x.map_or_else( LL | | @@ -51,7 +51,7 @@ LL + x.unwrap_or_else(|err| err); | error: unused "map closure" when calling `Result::map_or_else` value - --> tests/ui/unnecessary_result_map_or_else.rs:39:5 + --> tests/ui/unnecessary_result_map_or_else.rs:35:5 | LL | / x.map_or_else( LL | | @@ -77,7 +77,7 @@ LL + x.unwrap_or_else(|err| err); | error: unused "map closure" when calling `Result::map_or_else` value - --> tests/ui/unnecessary_result_map_or_else.rs:91:5 + --> tests/ui/unnecessary_result_map_or_else.rs:87:5 | LL | x.map_or_else(|err| err, |(a, b)| (a, b)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -89,7 +89,7 @@ LL + x.unwrap_or_else(|err| err); | error: unused "map closure" when calling `Result::map_or_else` value - --> tests/ui/unnecessary_result_map_or_else.rs:96:5 + --> tests/ui/unnecessary_result_map_or_else.rs:92:5 | LL | / x.map_or_else( LL | | @@ -115,7 +115,7 @@ LL + x.unwrap_or_else(|err| err); | error: unused "map closure" when calling `Result::map_or_else` value - --> tests/ui/unnecessary_result_map_or_else.rs:108:5 + --> tests/ui/unnecessary_result_map_or_else.rs:104:5 | LL | / x.map_or_else( LL | | diff --git a/src/tools/clippy/tests/ui/unnecessary_safety_comment.rs b/src/tools/clippy/tests/ui/unnecessary_safety_comment.rs index 75e8315343d3d..0eab44a826a1f 100644 --- a/src/tools/clippy/tests/ui/unnecessary_safety_comment.rs +++ b/src/tools/clippy/tests/ui/unnecessary_safety_comment.rs @@ -1,5 +1,5 @@ #![warn(clippy::undocumented_unsafe_blocks, clippy::unnecessary_safety_comment)] -#![allow(clippy::let_unit_value, clippy::missing_safety_doc, clippy::needless_ifs)] +#![expect(clippy::needless_ifs)] mod unsafe_items_invalid_comment { // SAFETY: @@ -110,3 +110,12 @@ mod issue16553 { //! ``` mod blah {} } + +fn issue17039() { + let mut data = [1u8, 2, 3, 4]; + let mut slice = data.as_mut_slice(); + + let parent; + // SAFETY: length is within bounds + (parent, slice) = unsafe { slice.split_at_mut_unchecked(slice.len() / 2) }; +} diff --git a/src/tools/clippy/tests/ui/unnecessary_self_imports.fixed b/src/tools/clippy/tests/ui/unnecessary_self_imports.fixed index 0fd74705bde02..f3405f486b2d4 100644 --- a/src/tools/clippy/tests/ui/unnecessary_self_imports.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_self_imports.fixed @@ -1,5 +1,4 @@ #![warn(clippy::unnecessary_self_imports)] -#![allow(unused_imports, dead_code)] use std::collections::hash_map::{self, *}; use std::fs as alias; diff --git a/src/tools/clippy/tests/ui/unnecessary_self_imports.rs b/src/tools/clippy/tests/ui/unnecessary_self_imports.rs index d09c5fcb8caa6..c15efb274f46a 100644 --- a/src/tools/clippy/tests/ui/unnecessary_self_imports.rs +++ b/src/tools/clippy/tests/ui/unnecessary_self_imports.rs @@ -1,5 +1,4 @@ #![warn(clippy::unnecessary_self_imports)] -#![allow(unused_imports, dead_code)] use std::collections::hash_map::{self, *}; use std::fs::{self as alias}; diff --git a/src/tools/clippy/tests/ui/unnecessary_self_imports.stderr b/src/tools/clippy/tests/ui/unnecessary_self_imports.stderr index 1bb22c46a6c11..8e7add731cd60 100644 --- a/src/tools/clippy/tests/ui/unnecessary_self_imports.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_self_imports.stderr @@ -1,5 +1,5 @@ error: import ending with `::{self}` - --> tests/ui/unnecessary_self_imports.rs:5:1 + --> tests/ui/unnecessary_self_imports.rs:4:1 | LL | use std::fs::{self as alias}; | ^^^^^^^^^-------------------- @@ -11,7 +11,7 @@ LL | use std::fs::{self as alias}; = help: to override `-D warnings` add `#[allow(clippy::unnecessary_self_imports)]` error: import ending with `::{self}` - --> tests/ui/unnecessary_self_imports.rs:8:1 + --> tests/ui/unnecessary_self_imports.rs:7:1 | LL | use std::rc::{self}; | ^^^^^^^^^----------- diff --git a/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2021.fixed b/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2021.fixed index 797f1505f4992..624aefe087195 100644 --- a/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2021.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2021.fixed @@ -4,7 +4,7 @@ #![warn(clippy::unnecessary_semicolon)] #![feature(postfix_match)] -#![allow(clippy::single_match)] +#![expect(clippy::single_match)] fn no_lint(mut x: u32) -> Option { Some(())?; diff --git a/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2024.fixed b/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2024.fixed index d2609cea00027..87cda0f34ed91 100644 --- a/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2024.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_semicolon.edition2024.fixed @@ -4,7 +4,7 @@ #![warn(clippy::unnecessary_semicolon)] #![feature(postfix_match)] -#![allow(clippy::single_match)] +#![expect(clippy::single_match)] fn no_lint(mut x: u32) -> Option { Some(())?; diff --git a/src/tools/clippy/tests/ui/unnecessary_semicolon.rs b/src/tools/clippy/tests/ui/unnecessary_semicolon.rs index 55f1ec84cb0ea..d2badb556255a 100644 --- a/src/tools/clippy/tests/ui/unnecessary_semicolon.rs +++ b/src/tools/clippy/tests/ui/unnecessary_semicolon.rs @@ -4,7 +4,7 @@ #![warn(clippy::unnecessary_semicolon)] #![feature(postfix_match)] -#![allow(clippy::single_match)] +#![expect(clippy::single_match)] fn no_lint(mut x: u32) -> Option { Some(())?; diff --git a/src/tools/clippy/tests/ui/unnecessary_sort_by.fixed b/src/tools/clippy/tests/ui/unnecessary_sort_by.fixed index db31b339a08b0..f2753252bd5f0 100644 --- a/src/tools/clippy/tests/ui/unnecessary_sort_by.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_sort_by.fixed @@ -1,4 +1,5 @@ -#![allow(clippy::stable_sort_primitive, clippy::useless_vec)] +#![warn(clippy::unnecessary_sort_by)] +#![expect(clippy::useless_vec)] use std::cell::Ref; diff --git a/src/tools/clippy/tests/ui/unnecessary_sort_by.rs b/src/tools/clippy/tests/ui/unnecessary_sort_by.rs index a31cf29679993..bcf2e1ca694bc 100644 --- a/src/tools/clippy/tests/ui/unnecessary_sort_by.rs +++ b/src/tools/clippy/tests/ui/unnecessary_sort_by.rs @@ -1,4 +1,5 @@ -#![allow(clippy::stable_sort_primitive, clippy::useless_vec)] +#![warn(clippy::unnecessary_sort_by)] +#![expect(clippy::useless_vec)] use std::cell::Ref; diff --git a/src/tools/clippy/tests/ui/unnecessary_sort_by.stderr b/src/tools/clippy/tests/ui/unnecessary_sort_by.stderr index 868f7895fc069..afd2cd72e5db3 100644 --- a/src/tools/clippy/tests/ui/unnecessary_sort_by.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_sort_by.stderr @@ -1,5 +1,5 @@ error: consider using `sort` - --> tests/ui/unnecessary_sort_by.rs:12:5 + --> tests/ui/unnecessary_sort_by.rs:13:5 | LL | vec.sort_by(|a, b| a.cmp(b)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + vec.sort(); | error: consider using `sort_unstable` - --> tests/ui/unnecessary_sort_by.rs:14:5 + --> tests/ui/unnecessary_sort_by.rs:15:5 | LL | vec.sort_unstable_by(|a, b| a.cmp(b)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + vec.sort_unstable(); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:16:5 + --> tests/ui/unnecessary_sort_by.rs:17:5 | LL | vec.sort_by(|a, b| (a + 5).abs().cmp(&(b + 5).abs())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + vec.sort_by_key(|a| (a + 5).abs()); | error: consider using `sort_unstable_by_key` - --> tests/ui/unnecessary_sort_by.rs:18:5 + --> tests/ui/unnecessary_sort_by.rs:19:5 | LL | vec.sort_unstable_by(|a, b| id(-a).cmp(&id(-b))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + vec.sort_unstable_by_key(|a| id(-a)); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:22:5 + --> tests/ui/unnecessary_sort_by.rs:23:5 | LL | vec.sort_by(|a, b| (b + 5).abs().cmp(&(a + 5).abs())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + vec.sort_by_key(|a| std::cmp::Reverse((a + 5).abs())); | error: consider using `sort_unstable_by_key` - --> tests/ui/unnecessary_sort_by.rs:24:5 + --> tests/ui/unnecessary_sort_by.rs:25:5 | LL | vec.sort_unstable_by(|a, b| id(-b).cmp(&id(-a))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + vec.sort_unstable_by_key(|a| std::cmp::Reverse(id(-a))); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:35:5 + --> tests/ui/unnecessary_sort_by.rs:36:5 | LL | vec.sort_by(|a, b| (***a).abs().cmp(&(***b).abs())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + vec.sort_by_key(|a| (***a).abs()); | error: consider using `sort_unstable_by_key` - --> tests/ui/unnecessary_sort_by.rs:37:5 + --> tests/ui/unnecessary_sort_by.rs:38:5 | LL | vec.sort_unstable_by(|a, b| (***a).abs().cmp(&(***b).abs())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL + vec.sort_unstable_by_key(|a| (***a).abs()); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:97:9 + --> tests/ui/unnecessary_sort_by.rs:98:9 | LL | args.sort_by(|a, b| a.name().cmp(&b.name())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -109,7 +109,7 @@ LL + args.sort_by_key(|a| a.name()); | error: consider using `sort_unstable_by_key` - --> tests/ui/unnecessary_sort_by.rs:99:9 + --> tests/ui/unnecessary_sort_by.rs:100:9 | LL | args.sort_unstable_by(|a, b| a.name().cmp(&b.name())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -121,7 +121,7 @@ LL + args.sort_unstable_by_key(|a| a.name()); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:102:9 + --> tests/ui/unnecessary_sort_by.rs:103:9 | LL | args.sort_by(|a, b| b.name().cmp(&a.name())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -133,7 +133,7 @@ LL + args.sort_by_key(|a| std::cmp::Reverse(a.name())); | error: consider using `sort_unstable_by_key` - --> tests/ui/unnecessary_sort_by.rs:104:9 + --> tests/ui/unnecessary_sort_by.rs:105:9 | LL | args.sort_unstable_by(|a, b| b.name().cmp(&a.name())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -145,7 +145,7 @@ LL + args.sort_unstable_by_key(|a| std::cmp::Reverse(a.name())); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:114:5 + --> tests/ui/unnecessary_sort_by.rs:115:5 | LL | v.sort_by(|a, b| a.0.cmp(&b.0)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -157,7 +157,7 @@ LL + v.sort_by_key(|a| a.0); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:132:5 + --> tests/ui/unnecessary_sort_by.rs:133:5 | LL | items.sort_by(|item1, item2| item1.key.cmp(&item2.key)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -169,7 +169,7 @@ LL + items.sort_by_key(|item1| item1.key); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:137:5 + --> tests/ui/unnecessary_sort_by.rs:138:5 | LL | items.sort_by(|item1, item2| item1.value.clone().cmp(&item2.value.clone())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -181,7 +181,7 @@ LL + items.sort_by_key(|item1| item1.value.clone()); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:143:5 + --> tests/ui/unnecessary_sort_by.rs:144:5 | LL | v.sort_by(|(_, s1), (_, s2)| s1.cmp(s2)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -193,7 +193,7 @@ LL + v.sort_by_key(|(_, s1)| *s1); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:150:5 + --> tests/ui/unnecessary_sort_by.rs:151:5 | LL | v.sort_by(|Foo { bar: b1 }, Foo { bar: b2 }| b1.cmp(b2)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -205,7 +205,7 @@ LL + v.sort_by_key(|Foo { bar: b1 }| *b1); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:155:5 + --> tests/ui/unnecessary_sort_by.rs:156:5 | LL | v.sort_by(|Baz(b1), Baz(b2)| b1.cmp(b2)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -217,7 +217,7 @@ LL + v.sort_by_key(|Baz(b1)| *b1); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:158:5 + --> tests/ui/unnecessary_sort_by.rs:159:5 | LL | v.sort_by(|&Baz(b1), &Baz(b2)| b1.cmp(&b2)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -229,7 +229,7 @@ LL + v.sort_by_key(|&Baz(b1)| b1); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:162:5 + --> tests/ui/unnecessary_sort_by.rs:163:5 | LL | v.sort_by(|&&b1, &&b2| b1.cmp(&b2)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -241,7 +241,7 @@ LL + v.sort_by_key(|&&b1| b1); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:166:5 + --> tests/ui/unnecessary_sort_by.rs:167:5 | LL | v.sort_by(|[a1, b1], [a2, b2]| a1.cmp(a2)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -253,7 +253,7 @@ LL + v.sort_by_key(|[a1, b1]| *a1); | error: consider using `sort_by_key` - --> tests/ui/unnecessary_sort_by.rs:169:5 + --> tests/ui/unnecessary_sort_by.rs:170:5 | LL | v.sort_by(|[a1, b1], [a2, b2]| (a1 - b1).cmp(&(a2 - b2))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_struct_initialization.fixed b/src/tools/clippy/tests/ui/unnecessary_struct_initialization.fixed index 07dc90acfa308..c39a336674fd1 100644 --- a/src/tools/clippy/tests/ui/unnecessary_struct_initialization.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_struct_initialization.fixed @@ -1,5 +1,5 @@ -#![allow(clippy::non_canonical_clone_impl, unused)] #![warn(clippy::unnecessary_struct_initialization)] +#![allow(clippy::non_canonical_clone_impl)] struct S { f: String, diff --git a/src/tools/clippy/tests/ui/unnecessary_struct_initialization.rs b/src/tools/clippy/tests/ui/unnecessary_struct_initialization.rs index 12a444fc878b9..28bb450d219cb 100644 --- a/src/tools/clippy/tests/ui/unnecessary_struct_initialization.rs +++ b/src/tools/clippy/tests/ui/unnecessary_struct_initialization.rs @@ -1,5 +1,5 @@ -#![allow(clippy::non_canonical_clone_impl, unused)] #![warn(clippy::unnecessary_struct_initialization)] +#![allow(clippy::non_canonical_clone_impl)] struct S { f: String, diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed b/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed index 590359bc1ad2b..dbcb32bd4823e 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed @@ -1,13 +1,11 @@ -#![allow( +#![warn(clippy::redundant_clone, clippy::unnecessary_to_owned)] +#![expect( clippy::manual_async_fn, clippy::needless_borrow, clippy::needless_borrows_for_generic_args, - clippy::needless_lifetimes, clippy::owned_cow, - clippy::ptr_arg, - clippy::uninlined_format_args + clippy::ptr_arg )] -#![warn(clippy::unnecessary_to_owned, clippy::redundant_clone)] use std::borrow::Cow; use std::ffi::{CStr, CString, OsStr, OsString}; @@ -44,7 +42,6 @@ impl X { } } -#[allow(dead_code)] #[derive(Clone)] enum FileType { Account, @@ -312,7 +309,6 @@ fn require_string(_: &String) {} // https://github.com/rust-lang/rust-clippy/issues/8507 mod issue_8507 { - #![allow(dead_code)] struct Opaque

(P); @@ -362,7 +358,6 @@ mod issue_8507 { // https://github.com/rust-lang/rust-clippy/issues/8759 mod issue_8759 { - #![allow(dead_code)] #[derive(Default)] struct View {} @@ -393,7 +388,6 @@ mod issue_8759 { } mod issue_8759_variant { - #![allow(dead_code)] #[derive(Clone, Default)] struct View {} @@ -417,7 +411,6 @@ mod issue_8759_variant { } mod issue_9317 { - #![allow(dead_code)] struct Bytes {} @@ -446,7 +439,6 @@ mod issue_9317 { } mod issue_9351 { - #![allow(dead_code)] use std::ops::Deref; use std::path::{Path, PathBuf}; @@ -507,7 +499,6 @@ mod issue_9351 { } mod issue_9504 { - #![allow(dead_code)] async fn foo>(_: S) {} async fn bar() { @@ -516,7 +507,6 @@ mod issue_9504 { } mod issue_9771a { - #![allow(dead_code)] use std::marker::PhantomData; @@ -534,7 +524,6 @@ mod issue_9771a { } mod issue_9771b { - #![allow(dead_code)] pub struct Key>(K); @@ -548,7 +537,6 @@ mod issue_9771b { // The ICE is triggered by the call to `to_owned` on this line: // https://github.com/oxigraph/rio/blob/66635b9ff8e5423e58932353fa40d6e64e4820f7/testsuite/src/parser_evaluator.rs#L116 mod issue_10021 { - #![allow(unused)] pub struct Iri(T); @@ -565,7 +553,6 @@ mod issue_10021 { } mod issue_10033 { - #![allow(dead_code)] use std::fmt::Display; use std::ops::Deref; diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned.rs b/src/tools/clippy/tests/ui/unnecessary_to_owned.rs index d1e3e6497c0af..1f8cb7681a887 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned.rs +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned.rs @@ -1,13 +1,11 @@ -#![allow( +#![warn(clippy::redundant_clone, clippy::unnecessary_to_owned)] +#![expect( clippy::manual_async_fn, clippy::needless_borrow, clippy::needless_borrows_for_generic_args, - clippy::needless_lifetimes, clippy::owned_cow, - clippy::ptr_arg, - clippy::uninlined_format_args + clippy::ptr_arg )] -#![warn(clippy::unnecessary_to_owned, clippy::redundant_clone)] use std::borrow::Cow; use std::ffi::{CStr, CString, OsStr, OsString}; @@ -44,7 +42,6 @@ impl X { } } -#[allow(dead_code)] #[derive(Clone)] enum FileType { Account, @@ -312,7 +309,6 @@ fn require_string(_: &String) {} // https://github.com/rust-lang/rust-clippy/issues/8507 mod issue_8507 { - #![allow(dead_code)] struct Opaque

(P); @@ -362,7 +358,6 @@ mod issue_8507 { // https://github.com/rust-lang/rust-clippy/issues/8759 mod issue_8759 { - #![allow(dead_code)] #[derive(Default)] struct View {} @@ -393,7 +388,6 @@ mod issue_8759 { } mod issue_8759_variant { - #![allow(dead_code)] #[derive(Clone, Default)] struct View {} @@ -417,7 +411,6 @@ mod issue_8759_variant { } mod issue_9317 { - #![allow(dead_code)] struct Bytes {} @@ -446,7 +439,6 @@ mod issue_9317 { } mod issue_9351 { - #![allow(dead_code)] use std::ops::Deref; use std::path::{Path, PathBuf}; @@ -507,7 +499,6 @@ mod issue_9351 { } mod issue_9504 { - #![allow(dead_code)] async fn foo>(_: S) {} async fn bar() { @@ -516,7 +507,6 @@ mod issue_9504 { } mod issue_9771a { - #![allow(dead_code)] use std::marker::PhantomData; @@ -534,7 +524,6 @@ mod issue_9771a { } mod issue_9771b { - #![allow(dead_code)] pub struct Key>(K); @@ -548,7 +537,6 @@ mod issue_9771b { // The ICE is triggered by the call to `to_owned` on this line: // https://github.com/oxigraph/rio/blob/66635b9ff8e5423e58932353fa40d6e64e4820f7/testsuite/src/parser_evaluator.rs#L116 mod issue_10021 { - #![allow(unused)] pub struct Iri(T); @@ -565,7 +553,6 @@ mod issue_10021 { } mod issue_10033 { - #![allow(dead_code)] use std::fmt::Display; use std::ops::Deref; diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr b/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr index 50e3d5eb21950..158adffe0f7f8 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr @@ -1,11 +1,11 @@ error: redundant clone - --> tests/ui/unnecessary_to_owned.rs:218:64 + --> tests/ui/unnecessary_to_owned.rs:215:64 | LL | require_c_str(&CString::from_vec_with_nul(vec![0]).unwrap().to_owned()); | ^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> tests/ui/unnecessary_to_owned.rs:218:20 + --> tests/ui/unnecessary_to_owned.rs:215:20 | LL | require_c_str(&CString::from_vec_with_nul(vec![0]).unwrap().to_owned()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,55 +13,55 @@ LL | require_c_str(&CString::from_vec_with_nul(vec![0]).unwrap().to_owned()) = help: to override `-D warnings` add `#[allow(clippy::redundant_clone)]` error: redundant clone - --> tests/ui/unnecessary_to_owned.rs:220:40 + --> tests/ui/unnecessary_to_owned.rs:217:40 | LL | require_os_str(&OsString::from("x").to_os_string()); | ^^^^^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> tests/ui/unnecessary_to_owned.rs:220:21 + --> tests/ui/unnecessary_to_owned.rs:217:21 | LL | require_os_str(&OsString::from("x").to_os_string()); | ^^^^^^^^^^^^^^^^^^^ error: redundant clone - --> tests/ui/unnecessary_to_owned.rs:222:48 + --> tests/ui/unnecessary_to_owned.rs:219:48 | LL | require_path(&std::path::PathBuf::from("x").to_path_buf()); | ^^^^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> tests/ui/unnecessary_to_owned.rs:222:19 + --> tests/ui/unnecessary_to_owned.rs:219:19 | LL | require_path(&std::path::PathBuf::from("x").to_path_buf()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: redundant clone - --> tests/ui/unnecessary_to_owned.rs:224:35 + --> tests/ui/unnecessary_to_owned.rs:221:35 | LL | require_str(&String::from("x").to_string()); | ^^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> tests/ui/unnecessary_to_owned.rs:224:18 + --> tests/ui/unnecessary_to_owned.rs:221:18 | LL | require_str(&String::from("x").to_string()); | ^^^^^^^^^^^^^^^^^ error: redundant clone - --> tests/ui/unnecessary_to_owned.rs:226:39 + --> tests/ui/unnecessary_to_owned.rs:223:39 | LL | require_slice(&[String::from("x")].to_owned()); | ^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> tests/ui/unnecessary_to_owned.rs:226:20 + --> tests/ui/unnecessary_to_owned.rs:223:20 | LL | require_slice(&[String::from("x")].to_owned()); | ^^^^^^^^^^^^^^^^^^^ error: unnecessary use of `into_owned` - --> tests/ui/unnecessary_to_owned.rs:66:36 + --> tests/ui/unnecessary_to_owned.rs:63:36 | LL | require_c_str(&Cow::from(c_str).into_owned()); | ^^^^^^^^^^^^^ help: remove this @@ -70,391 +70,391 @@ LL | require_c_str(&Cow::from(c_str).into_owned()); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_to_owned)]` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:68:19 + --> tests/ui/unnecessary_to_owned.rs:65:19 | LL | require_c_str(&c_str.to_owned()); | ^^^^^^^^^^^^^^^^^ help: use: `c_str` error: unnecessary use of `to_os_string` - --> tests/ui/unnecessary_to_owned.rs:71:20 + --> tests/ui/unnecessary_to_owned.rs:68:20 | LL | require_os_str(&os_str.to_os_string()); | ^^^^^^^^^^^^^^^^^^^^^^ help: use: `os_str` error: unnecessary use of `into_owned` - --> tests/ui/unnecessary_to_owned.rs:73:38 + --> tests/ui/unnecessary_to_owned.rs:70:38 | LL | require_os_str(&Cow::from(os_str).into_owned()); | ^^^^^^^^^^^^^ help: remove this error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:75:20 + --> tests/ui/unnecessary_to_owned.rs:72:20 | LL | require_os_str(&os_str.to_owned()); | ^^^^^^^^^^^^^^^^^^ help: use: `os_str` error: unnecessary use of `to_path_buf` - --> tests/ui/unnecessary_to_owned.rs:78:18 + --> tests/ui/unnecessary_to_owned.rs:75:18 | LL | require_path(&path.to_path_buf()); | ^^^^^^^^^^^^^^^^^^^ help: use: `path` error: unnecessary use of `into_owned` - --> tests/ui/unnecessary_to_owned.rs:80:34 + --> tests/ui/unnecessary_to_owned.rs:77:34 | LL | require_path(&Cow::from(path).into_owned()); | ^^^^^^^^^^^^^ help: remove this error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:82:18 + --> tests/ui/unnecessary_to_owned.rs:79:18 | LL | require_path(&path.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `path` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned.rs:85:17 + --> tests/ui/unnecessary_to_owned.rs:82:17 | LL | require_str(&s.to_string()); | ^^^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `into_owned` - --> tests/ui/unnecessary_to_owned.rs:87:30 + --> tests/ui/unnecessary_to_owned.rs:84:30 | LL | require_str(&Cow::from(s).into_owned()); | ^^^^^^^^^^^^^ help: remove this error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:89:17 + --> tests/ui/unnecessary_to_owned.rs:86:17 | LL | require_str(&s.to_owned()); | ^^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned.rs:91:17 + --> tests/ui/unnecessary_to_owned.rs:88:17 | LL | require_str(&x_ref.to_string()); | ^^^^^^^^^^^^^^^^^^ help: use: `x_ref.as_ref()` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:94:19 + --> tests/ui/unnecessary_to_owned.rs:91:19 | LL | require_slice(&slice.to_vec()); | ^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `into_owned` - --> tests/ui/unnecessary_to_owned.rs:96:36 + --> tests/ui/unnecessary_to_owned.rs:93:36 | LL | require_slice(&Cow::from(slice).into_owned()); | ^^^^^^^^^^^^^ help: remove this error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:98:19 + --> tests/ui/unnecessary_to_owned.rs:95:19 | LL | require_slice(&array.to_owned()); | ^^^^^^^^^^^^^^^^^ help: use: `array.as_ref()` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:100:19 + --> tests/ui/unnecessary_to_owned.rs:97:19 | LL | require_slice(&array_ref.to_owned()); | ^^^^^^^^^^^^^^^^^^^^^ help: use: `array_ref.as_ref()` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:102:19 + --> tests/ui/unnecessary_to_owned.rs:99:19 | LL | require_slice(&slice.to_owned()); | ^^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `into_owned` - --> tests/ui/unnecessary_to_owned.rs:106:42 + --> tests/ui/unnecessary_to_owned.rs:103:42 | LL | require_x(&Cow::::Owned(x.clone()).into_owned()); | ^^^^^^^^^^^^^ help: remove this error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:110:25 + --> tests/ui/unnecessary_to_owned.rs:107:25 | LL | require_deref_c_str(c_str.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `c_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:112:26 + --> tests/ui/unnecessary_to_owned.rs:109:26 | LL | require_deref_os_str(os_str.to_owned()); | ^^^^^^^^^^^^^^^^^ help: use: `os_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:114:24 + --> tests/ui/unnecessary_to_owned.rs:111:24 | LL | require_deref_path(path.to_owned()); | ^^^^^^^^^^^^^^^ help: use: `path` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:116:23 + --> tests/ui/unnecessary_to_owned.rs:113:23 | LL | require_deref_str(s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:118:25 + --> tests/ui/unnecessary_to_owned.rs:115:25 | LL | require_deref_slice(slice.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:121:30 + --> tests/ui/unnecessary_to_owned.rs:118:30 | LL | require_impl_deref_c_str(c_str.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `c_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:123:31 + --> tests/ui/unnecessary_to_owned.rs:120:31 | LL | require_impl_deref_os_str(os_str.to_owned()); | ^^^^^^^^^^^^^^^^^ help: use: `os_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:125:29 + --> tests/ui/unnecessary_to_owned.rs:122:29 | LL | require_impl_deref_path(path.to_owned()); | ^^^^^^^^^^^^^^^ help: use: `path` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:127:28 + --> tests/ui/unnecessary_to_owned.rs:124:28 | LL | require_impl_deref_str(s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:129:30 + --> tests/ui/unnecessary_to_owned.rs:126:30 | LL | require_impl_deref_slice(slice.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:132:29 + --> tests/ui/unnecessary_to_owned.rs:129:29 | LL | require_deref_str_slice(s.to_owned(), slice.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:132:43 + --> tests/ui/unnecessary_to_owned.rs:129:43 | LL | require_deref_str_slice(s.to_owned(), slice.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:135:29 + --> tests/ui/unnecessary_to_owned.rs:132:29 | LL | require_deref_slice_str(slice.to_owned(), s.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:135:47 + --> tests/ui/unnecessary_to_owned.rs:132:47 | LL | require_deref_slice_str(slice.to_owned(), s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:139:26 + --> tests/ui/unnecessary_to_owned.rs:136:26 | LL | require_as_ref_c_str(c_str.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `c_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:141:27 + --> tests/ui/unnecessary_to_owned.rs:138:27 | LL | require_as_ref_os_str(os_str.to_owned()); | ^^^^^^^^^^^^^^^^^ help: use: `os_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:143:25 + --> tests/ui/unnecessary_to_owned.rs:140:25 | LL | require_as_ref_path(path.to_owned()); | ^^^^^^^^^^^^^^^ help: use: `path` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:145:24 + --> tests/ui/unnecessary_to_owned.rs:142:24 | LL | require_as_ref_str(s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:147:24 + --> tests/ui/unnecessary_to_owned.rs:144:24 | LL | require_as_ref_str(x.to_owned()); | ^^^^^^^^^^^^ help: use: `&x` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:149:26 + --> tests/ui/unnecessary_to_owned.rs:146:26 | LL | require_as_ref_slice(array.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `array` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:151:26 + --> tests/ui/unnecessary_to_owned.rs:148:26 | LL | require_as_ref_slice(array_ref.to_owned()); | ^^^^^^^^^^^^^^^^^^^^ help: use: `array_ref` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:153:26 + --> tests/ui/unnecessary_to_owned.rs:150:26 | LL | require_as_ref_slice(slice.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:156:31 + --> tests/ui/unnecessary_to_owned.rs:153:31 | LL | require_impl_as_ref_c_str(c_str.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `c_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:158:32 + --> tests/ui/unnecessary_to_owned.rs:155:32 | LL | require_impl_as_ref_os_str(os_str.to_owned()); | ^^^^^^^^^^^^^^^^^ help: use: `os_str` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:160:30 + --> tests/ui/unnecessary_to_owned.rs:157:30 | LL | require_impl_as_ref_path(path.to_owned()); | ^^^^^^^^^^^^^^^ help: use: `path` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:162:29 + --> tests/ui/unnecessary_to_owned.rs:159:29 | LL | require_impl_as_ref_str(s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:164:29 + --> tests/ui/unnecessary_to_owned.rs:161:29 | LL | require_impl_as_ref_str(x.to_owned()); | ^^^^^^^^^^^^ help: use: `&x` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:166:31 + --> tests/ui/unnecessary_to_owned.rs:163:31 | LL | require_impl_as_ref_slice(array.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `array` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:168:31 + --> tests/ui/unnecessary_to_owned.rs:165:31 | LL | require_impl_as_ref_slice(array_ref.to_owned()); | ^^^^^^^^^^^^^^^^^^^^ help: use: `array_ref` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:170:31 + --> tests/ui/unnecessary_to_owned.rs:167:31 | LL | require_impl_as_ref_slice(slice.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:173:30 + --> tests/ui/unnecessary_to_owned.rs:170:30 | LL | require_as_ref_str_slice(s.to_owned(), array.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:173:44 + --> tests/ui/unnecessary_to_owned.rs:170:44 | LL | require_as_ref_str_slice(s.to_owned(), array.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `array` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:176:30 + --> tests/ui/unnecessary_to_owned.rs:173:30 | LL | require_as_ref_str_slice(s.to_owned(), array_ref.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:176:44 + --> tests/ui/unnecessary_to_owned.rs:173:44 | LL | require_as_ref_str_slice(s.to_owned(), array_ref.to_owned()); | ^^^^^^^^^^^^^^^^^^^^ help: use: `array_ref` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:179:30 + --> tests/ui/unnecessary_to_owned.rs:176:30 | LL | require_as_ref_str_slice(s.to_owned(), slice.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:179:44 + --> tests/ui/unnecessary_to_owned.rs:176:44 | LL | require_as_ref_str_slice(s.to_owned(), slice.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:182:30 + --> tests/ui/unnecessary_to_owned.rs:179:30 | LL | require_as_ref_slice_str(array.to_owned(), s.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `array` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:182:48 + --> tests/ui/unnecessary_to_owned.rs:179:48 | LL | require_as_ref_slice_str(array.to_owned(), s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:185:30 + --> tests/ui/unnecessary_to_owned.rs:182:30 | LL | require_as_ref_slice_str(array_ref.to_owned(), s.to_owned()); | ^^^^^^^^^^^^^^^^^^^^ help: use: `array_ref` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:185:52 + --> tests/ui/unnecessary_to_owned.rs:182:52 | LL | require_as_ref_slice_str(array_ref.to_owned(), s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:188:30 + --> tests/ui/unnecessary_to_owned.rs:185:30 | LL | require_as_ref_slice_str(slice.to_owned(), s.to_owned()); | ^^^^^^^^^^^^^^^^ help: use: `slice` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:188:48 + --> tests/ui/unnecessary_to_owned.rs:185:48 | LL | require_as_ref_slice_str(slice.to_owned(), s.to_owned()); | ^^^^^^^^^^^^ help: use: `s` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned.rs:192:20 + --> tests/ui/unnecessary_to_owned.rs:189:20 | LL | let _ = x.join(&x_ref.to_string()); | ^^^^^^^^^^^^^^^^^^ help: use: `x_ref` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:195:13 + --> tests/ui/unnecessary_to_owned.rs:192:13 | LL | let _ = slice.to_vec().into_iter(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `slice.iter().copied()` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:197:13 + --> tests/ui/unnecessary_to_owned.rs:194:13 | LL | let _ = slice.to_owned().into_iter(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `slice.iter().copied()` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:200:13 + --> tests/ui/unnecessary_to_owned.rs:197:13 | LL | let _ = IntoIterator::into_iter(slice.to_vec()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `slice.iter().copied()` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:202:13 + --> tests/ui/unnecessary_to_owned.rs:199:13 | LL | let _ = IntoIterator::into_iter(slice.to_owned()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `slice.iter().copied()` error: allocating a new `String` only to create a temporary `&str` from it - --> tests/ui/unnecessary_to_owned.rs:230:26 + --> tests/ui/unnecessary_to_owned.rs:227:26 | LL | let _ref_str: &str = &String::from_utf8(slice.to_vec()).expect("not UTF-8"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -466,7 +466,7 @@ LL + let _ref_str: &str = core::str::from_utf8(&slice).expect("not UTF-8"); | error: allocating a new `String` only to create a temporary `&str` from it - --> tests/ui/unnecessary_to_owned.rs:232:26 + --> tests/ui/unnecessary_to_owned.rs:229:26 | LL | let _ref_str: &str = &String::from_utf8(b"foo".to_vec()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -478,7 +478,7 @@ LL + let _ref_str: &str = core::str::from_utf8(b"foo").unwrap(); | error: allocating a new `String` only to create a temporary `&str` from it - --> tests/ui/unnecessary_to_owned.rs:234:26 + --> tests/ui/unnecessary_to_owned.rs:231:26 | LL | let _ref_str: &str = &String::from_utf8(b"foo".as_slice().to_owned()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -490,7 +490,7 @@ LL + let _ref_str: &str = core::str::from_utf8(b"foo".as_slice()).unwrap(); | error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:292:14 + --> tests/ui/unnecessary_to_owned.rs:289:14 | LL | for t in file_types.to_vec() { | ^^^^^^^^^^^^^^^^^^^ @@ -503,55 +503,55 @@ LL ~ let path = match get_file_path(t) { | error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned.rs:358:24 + --> tests/ui/unnecessary_to_owned.rs:354:24 | LL | Box::new(build(y.to_string())) | ^^^^^^^^^^^^^ help: use: `y` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned.rs:468:12 + --> tests/ui/unnecessary_to_owned.rs:460:12 | LL | id("abc".to_string()) | ^^^^^^^^^^^^^^^^^ help: use: `"abc"` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:612:37 + --> tests/ui/unnecessary_to_owned.rs:599:37 | LL | IntoFuture::into_future(foo([].to_vec(), &0)); | ^^^^^^^^^^^ help: use: `[]` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:623:18 + --> tests/ui/unnecessary_to_owned.rs:610:18 | LL | s.remove(&a.to_vec()); | ^^^^^^^^^^^ help: replace it with: `a` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned.rs:628:14 + --> tests/ui/unnecessary_to_owned.rs:615:14 | LL | s.remove(&"b".to_owned()); | ^^^^^^^^^^^^^^^ help: replace it with: `"b"` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned.rs:630:14 + --> tests/ui/unnecessary_to_owned.rs:617:14 | LL | s.remove(&"b".to_string()); | ^^^^^^^^^^^^^^^^ help: replace it with: `"b"` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:636:14 + --> tests/ui/unnecessary_to_owned.rs:623:14 | LL | s.remove(&["b"].to_vec()); | ^^^^^^^^^^^^^^^ help: replace it with: `["b"].as_slice()` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned.rs:638:14 + --> tests/ui/unnecessary_to_owned.rs:625:14 | LL | s.remove(&(&["b"]).to_vec()); | ^^^^^^^^^^^^^^^^^^ help: replace it with: `(&["b"]).as_slice()` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned.rs:690:10 + --> tests/ui/unnecessary_to_owned.rs:677:10 | LL | take(format!("ouch{dot}").to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `&format!("ouch{dot}")` diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.fixed b/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.fixed index f43d92a2d9bab..7ee1f539c2048 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.fixed @@ -1,4 +1,5 @@ -#![allow(clippy::single_char_pattern)] +#![warn(clippy::unnecessary_to_owned)] +#![expect(clippy::single_char_pattern)] struct Issue12068; diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.rs b/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.rs index bdf5f98bf61e3..a716ac965175c 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.rs +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.rs @@ -1,4 +1,5 @@ -#![allow(clippy::single_char_pattern)] +#![warn(clippy::unnecessary_to_owned)] +#![expect(clippy::single_char_pattern)] struct Issue12068; diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.stderr b/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.stderr index 5e4fbb1035d69..a9e913de89b1e 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned_on_split.stderr @@ -1,5 +1,5 @@ error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned_on_split.rs:19:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:20:13 | LL | let _ = "a".to_string().split('a').next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `"a".split('a')` @@ -8,49 +8,49 @@ LL | let _ = "a".to_string().split('a').next().unwrap(); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_to_owned)]` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned_on_split.rs:22:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:23:13 | LL | let _ = "a".to_string().split("a").next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `"a".split("a")` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned_on_split.rs:25:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:26:13 | LL | let _ = "a".to_owned().split('a').next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `"a".split('a')` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned_on_split.rs:28:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:29:13 | LL | let _ = "a".to_owned().split("a").next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `"a".split("a")` error: unnecessary use of `to_string` - --> tests/ui/unnecessary_to_owned_on_split.rs:31:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:32:13 | LL | let _ = Issue12068.to_string().split('a').next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `Issue12068.as_ref().split('a')` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned_on_split.rs:34:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:35:13 | LL | let _ = [1].to_vec().split(|x| *x == 2).next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `[1].split(|x| *x == 2)` error: unnecessary use of `to_vec` - --> tests/ui/unnecessary_to_owned_on_split.rs:37:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:38:13 | LL | let _ = [1].to_vec().split(|x| *x == 2).next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `[1].split(|x| *x == 2)` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned_on_split.rs:40:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:41:13 | LL | let _ = [1].to_owned().split(|x| *x == 2).next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `[1].split(|x| *x == 2)` error: unnecessary use of `to_owned` - --> tests/ui/unnecessary_to_owned_on_split.rs:43:13 + --> tests/ui/unnecessary_to_owned_on_split.rs:44:13 | LL | let _ = [1].to_owned().split(|x| *x == 2).next().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `[1].split(|x| *x == 2)` diff --git a/src/tools/clippy/tests/ui/unnecessary_trailing_comma.fixed b/src/tools/clippy/tests/ui/unnecessary_trailing_comma.fixed index f418fe954d400..6e034c126fb07 100644 --- a/src/tools/clippy/tests/ui/unnecessary_trailing_comma.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_trailing_comma.fixed @@ -1,5 +1,6 @@ // run-rustfix #![warn(clippy::unnecessary_trailing_comma)] +#![allow(clippy::nonstandard_macro_braces)] fn main() {} diff --git a/src/tools/clippy/tests/ui/unnecessary_trailing_comma.rs b/src/tools/clippy/tests/ui/unnecessary_trailing_comma.rs index 26770ffaeee18..5616ac254f1ad 100644 --- a/src/tools/clippy/tests/ui/unnecessary_trailing_comma.rs +++ b/src/tools/clippy/tests/ui/unnecessary_trailing_comma.rs @@ -1,5 +1,6 @@ // run-rustfix #![warn(clippy::unnecessary_trailing_comma)] +#![allow(clippy::nonstandard_macro_braces)] fn main() {} diff --git a/src/tools/clippy/tests/ui/unnecessary_trailing_comma.stderr b/src/tools/clippy/tests/ui/unnecessary_trailing_comma.stderr index 8ff7195a147b0..78c6476f6ef42 100644 --- a/src/tools/clippy/tests/ui/unnecessary_trailing_comma.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_trailing_comma.stderr @@ -1,5 +1,5 @@ error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:10:19 + --> tests/ui/unnecessary_trailing_comma.rs:11:19 | LL | println!("Foo" , ); | ^^^ help: remove the trailing comma @@ -8,115 +8,115 @@ LL | println!("Foo" , ); = help: to override `-D warnings` add `#[allow(clippy::unnecessary_trailing_comma)]` error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:11:19 + --> tests/ui/unnecessary_trailing_comma.rs:12:19 | LL | println!{"Foo" , }; | ^^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:12:19 + --> tests/ui/unnecessary_trailing_comma.rs:13:19 | LL | println!["Foo" , ]; | ^^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:13:27 + --> tests/ui/unnecessary_trailing_comma.rs:14:27 | LL | println!("Foo={}", 1 , ); | ^^^^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:14:36 + --> tests/ui/unnecessary_trailing_comma.rs:15:36 | LL | println!(concat!("b", "o", "o") , ); | ^^^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:15:22 + --> tests/ui/unnecessary_trailing_comma.rs:16:22 | LL | println!("Foo(,)",); | ^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:16:22 + --> tests/ui/unnecessary_trailing_comma.rs:17:22 | LL | println!("Foo[,]" , ); | ^^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:17:22 + --> tests/ui/unnecessary_trailing_comma.rs:18:22 | LL | println!["Foo(,)", ]; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:18:22 + --> tests/ui/unnecessary_trailing_comma.rs:19:22 | LL | println!["Foo[,]", ]; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:19:24 + --> tests/ui/unnecessary_trailing_comma.rs:20:24 | LL | println!["Foo{{,}}", ]; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:20:24 + --> tests/ui/unnecessary_trailing_comma.rs:21:24 | LL | println!{"Foo{{,}}", }; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:21:22 + --> tests/ui/unnecessary_trailing_comma.rs:22:22 | LL | println!{"Foo(,)", }; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:22:22 + --> tests/ui/unnecessary_trailing_comma.rs:23:22 | LL | println!{"Foo[,]", }; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:23:21 + --> tests/ui/unnecessary_trailing_comma.rs:24:21 | LL | println!["Foo(,", ]; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:24:21 + --> tests/ui/unnecessary_trailing_comma.rs:25:21 | LL | println!["Foo[,", ]; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:25:24 + --> tests/ui/unnecessary_trailing_comma.rs:26:24 | LL | println!["Foo{{,}}", ]; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:26:24 + --> tests/ui/unnecessary_trailing_comma.rs:27:24 | LL | println!{"Foo{{,}}", }; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:27:21 + --> tests/ui/unnecessary_trailing_comma.rs:28:21 | LL | println!{"Foo(,", }; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:28:21 + --> tests/ui/unnecessary_trailing_comma.rs:29:21 | LL | println!{"Foo[,", }; | ^^ help: remove the trailing comma error: unnecessary trailing comma - --> tests/ui/unnecessary_trailing_comma.rs:29:42 + --> tests/ui/unnecessary_trailing_comma.rs:30:42 | LL | println!(concat!("Foo", "=", "{}"), 1,); | ^ help: remove the trailing comma diff --git a/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.rs b/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.rs index 7a847d2e3b501..1fcad44e83804 100644 --- a/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.rs +++ b/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.rs @@ -1,6 +1,5 @@ //@aux-build:proc_macros.rs -#![allow(clippy::let_unit_value, clippy::needless_pass_by_ref_mut)] #![warn(clippy::unnecessary_safety_doc)] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.stderr b/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.stderr index dd9d8b65f75e8..cb2fb3119e86e 100644 --- a/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_unsafety_doc.stderr @@ -1,5 +1,5 @@ error: safe function's docs have unnecessary `# Safety` section - --> tests/ui/unnecessary_unsafety_doc.rs:19:1 + --> tests/ui/unnecessary_unsafety_doc.rs:18:1 | LL | pub fn apocalypse(universe: &mut ()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,31 +8,31 @@ LL | pub fn apocalypse(universe: &mut ()) { = help: to override `-D warnings` add `#[allow(clippy::unnecessary_safety_doc)]` error: safe function's docs have unnecessary `# Safety` section - --> tests/ui/unnecessary_unsafety_doc.rs:46:5 + --> tests/ui/unnecessary_unsafety_doc.rs:45:5 | LL | pub fn republished() { | ^^^^^^^^^^^^^^^^^^^^ error: safe function's docs have unnecessary `# Safety` section - --> tests/ui/unnecessary_unsafety_doc.rs:60:5 + --> tests/ui/unnecessary_unsafety_doc.rs:59:5 | LL | fn documented(self); | ^^^^^^^^^^^^^^^^^^^^ error: docs for safe trait have unnecessary `# Safety` section - --> tests/ui/unnecessary_unsafety_doc.rs:71:1 + --> tests/ui/unnecessary_unsafety_doc.rs:70:1 | LL | pub trait DocumentedSafeTrait { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: safe function's docs have unnecessary `# Safety` section - --> tests/ui/unnecessary_unsafety_doc.rs:100:5 + --> tests/ui/unnecessary_unsafety_doc.rs:99:5 | LL | pub fn documented() -> Self { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: safe function's docs have unnecessary `# Safety` section - --> tests/ui/unnecessary_unsafety_doc.rs:128:9 + --> tests/ui/unnecessary_unsafety_doc.rs:127:9 | LL | pub fn drive() { | ^^^^^^^^^^^^^^ @@ -43,7 +43,7 @@ LL | very_safe!(); = note: this error originates in the macro `very_safe` (in Nightly builds, run with -Z macro-backtrace for more info) error: docs for safe trait have unnecessary `# Safety` section - --> tests/ui/unnecessary_unsafety_doc.rs:157:1 + --> tests/ui/unnecessary_unsafety_doc.rs:156:1 | LL | pub trait DocumentedSafeTraitWithImplementationHeader { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnecessary_wraps.rs b/src/tools/clippy/tests/ui/unnecessary_wraps.rs index 4770ef3b48300..5803eff6a4ff9 100644 --- a/src/tools/clippy/tests/ui/unnecessary_wraps.rs +++ b/src/tools/clippy/tests/ui/unnecessary_wraps.rs @@ -1,9 +1,7 @@ //@no-rustfix: overlapping suggestions #![warn(clippy::unnecessary_wraps)] -#![allow(clippy::no_effect)] +#![expect(clippy::if_same_then_else, clippy::no_effect)] #![allow(clippy::needless_return)] -#![allow(clippy::if_same_then_else)] -#![allow(dead_code)] // should be linted fn func1(a: bool, b: bool) -> Option { diff --git a/src/tools/clippy/tests/ui/unnecessary_wraps.stderr b/src/tools/clippy/tests/ui/unnecessary_wraps.stderr index 13d71271e211c..1fd421c201c96 100644 --- a/src/tools/clippy/tests/ui/unnecessary_wraps.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_wraps.stderr @@ -1,5 +1,5 @@ error: this function's return value is unnecessarily wrapped by `Option` - --> tests/ui/unnecessary_wraps.rs:9:1 + --> tests/ui/unnecessary_wraps.rs:7:1 | LL | fn func1(a: bool, b: bool) -> Option { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -23,7 +23,7 @@ LL ~ return 1337; | error: this function's return value is unnecessarily wrapped by `Option` - --> tests/ui/unnecessary_wraps.rs:24:1 + --> tests/ui/unnecessary_wraps.rs:22:1 | LL | fn func2(a: bool, b: bool) -> Option { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -41,7 +41,7 @@ LL ~ if a { 20 } else { 30 } | error: this function's return value is unnecessarily wrapped by `Option` - --> tests/ui/unnecessary_wraps.rs:44:1 + --> tests/ui/unnecessary_wraps.rs:42:1 | LL | fn func5() -> Option { | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -58,7 +58,7 @@ LL + 1 | error: this function's return value is unnecessarily wrapped by `Result` - --> tests/ui/unnecessary_wraps.rs:56:1 + --> tests/ui/unnecessary_wraps.rs:54:1 | LL | fn func7() -> Result { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -75,7 +75,7 @@ LL + 1 | error: this function's return value is unnecessarily wrapped by `Option` - --> tests/ui/unnecessary_wraps.rs:86:5 + --> tests/ui/unnecessary_wraps.rs:84:5 | LL | fn func12() -> Option { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -92,7 +92,7 @@ LL + 1 | error: this function's return value is unnecessary - --> tests/ui/unnecessary_wraps.rs:115:1 + --> tests/ui/unnecessary_wraps.rs:113:1 | LL | fn issue_6640_1(a: bool, b: bool) -> Option<()> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -114,7 +114,7 @@ LL ~ return ; | error: this function's return value is unnecessary - --> tests/ui/unnecessary_wraps.rs:130:1 + --> tests/ui/unnecessary_wraps.rs:128:1 | LL | fn issue_6640_2(a: bool, b: bool) -> Result<(), i32> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unneeded_field_pattern.rs b/src/tools/clippy/tests/ui/unneeded_field_pattern.rs index 327b64e7c4aab..b048789cf1aaf 100644 --- a/src/tools/clippy/tests/ui/unneeded_field_pattern.rs +++ b/src/tools/clippy/tests/ui/unneeded_field_pattern.rs @@ -1,6 +1,6 @@ //@aux-build:proc_macros.rs #![warn(clippy::unneeded_field_pattern)] -#![allow(dead_code, unused, clippy::single_match)] +#![expect(clippy::single_match)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unneeded_struct_pattern.fixed b/src/tools/clippy/tests/ui/unneeded_struct_pattern.fixed index 665ab98913be3..a51f6ad34fec0 100644 --- a/src/tools/clippy/tests/ui/unneeded_struct_pattern.fixed +++ b/src/tools/clippy/tests/ui/unneeded_struct_pattern.fixed @@ -1,10 +1,7 @@ //@aux-build:non-exhaustive-enum.rs -#![allow( - clippy::manual_unwrap_or_default, - clippy::manual_unwrap_or, - clippy::redundant_pattern_matching -)] #![warn(clippy::unneeded_struct_pattern)] +#![allow(clippy::redundant_pattern_matching)] +#![expect(clippy::manual_unwrap_or_default)] extern crate non_exhaustive_enum; use non_exhaustive_enum::*; diff --git a/src/tools/clippy/tests/ui/unneeded_struct_pattern.rs b/src/tools/clippy/tests/ui/unneeded_struct_pattern.rs index 7cadb6c7fbb54..4039f72c5316a 100644 --- a/src/tools/clippy/tests/ui/unneeded_struct_pattern.rs +++ b/src/tools/clippy/tests/ui/unneeded_struct_pattern.rs @@ -1,10 +1,7 @@ //@aux-build:non-exhaustive-enum.rs -#![allow( - clippy::manual_unwrap_or_default, - clippy::manual_unwrap_or, - clippy::redundant_pattern_matching -)] #![warn(clippy::unneeded_struct_pattern)] +#![allow(clippy::redundant_pattern_matching)] +#![expect(clippy::manual_unwrap_or_default)] extern crate non_exhaustive_enum; use non_exhaustive_enum::*; diff --git a/src/tools/clippy/tests/ui/unneeded_struct_pattern.stderr b/src/tools/clippy/tests/ui/unneeded_struct_pattern.stderr index 7c0c3c9e4462e..2e66fb40881ca 100644 --- a/src/tools/clippy/tests/ui/unneeded_struct_pattern.stderr +++ b/src/tools/clippy/tests/ui/unneeded_struct_pattern.stderr @@ -1,5 +1,5 @@ error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:17:13 + --> tests/ui/unneeded_struct_pattern.rs:14:13 | LL | None {} => 0, | ^^^ help: remove the struct pattern @@ -8,193 +8,193 @@ LL | None {} => 0, = help: to override `-D warnings` add `#[allow(clippy::unneeded_struct_pattern)]` error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:23:13 + --> tests/ui/unneeded_struct_pattern.rs:20:13 | LL | None { .. } => 0, | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:34:18 + --> tests/ui/unneeded_struct_pattern.rs:31:18 | LL | Some(None {}) => 0, | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:36:13 + --> tests/ui/unneeded_struct_pattern.rs:33:13 | LL | None {} => 0, | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:40:16 + --> tests/ui/unneeded_struct_pattern.rs:37:16 | LL | if let None {} = Some(0) {} | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:42:16 + --> tests/ui/unneeded_struct_pattern.rs:39:16 | LL | if let None { .. } = Some(0) {} | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:44:21 + --> tests/ui/unneeded_struct_pattern.rs:41:21 | LL | if let Some(None {}) = Some(Some(0)) {} | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:46:13 + --> tests/ui/unneeded_struct_pattern.rs:43:13 | LL | let None {} = Some(0) else { panic!() }; | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:48:13 + --> tests/ui/unneeded_struct_pattern.rs:45:13 | LL | let None { .. } = Some(0) else { panic!() }; | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:50:18 + --> tests/ui/unneeded_struct_pattern.rs:47:18 | LL | let Some(None {}) = Some(Some(0)) else { panic!() }; | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:67:27 + --> tests/ui/unneeded_struct_pattern.rs:64:27 | LL | Custom::NoBrackets {} => 0, | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:68:40 + --> tests/ui/unneeded_struct_pattern.rs:65:40 | LL | Custom::NoBracketsNonExhaustive {} => 0, | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:75:27 + --> tests/ui/unneeded_struct_pattern.rs:72:27 | LL | Custom::NoBrackets { .. } => 0, | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:76:40 + --> tests/ui/unneeded_struct_pattern.rs:73:40 | LL | Custom::NoBracketsNonExhaustive { .. } => 0, | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:81:27 + --> tests/ui/unneeded_struct_pattern.rs:78:27 | LL | Custom::NoBrackets {} if true => 0, | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:86:27 + --> tests/ui/unneeded_struct_pattern.rs:83:27 | LL | Custom::NoBrackets {} | Custom::NoBracketsNonExhaustive {} => 0, | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:86:64 + --> tests/ui/unneeded_struct_pattern.rs:83:64 | LL | Custom::NoBrackets {} | Custom::NoBracketsNonExhaustive {} => 0, | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:101:30 + --> tests/ui/unneeded_struct_pattern.rs:98:30 | LL | if let Custom::NoBrackets {} = Custom::Init { | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:105:30 + --> tests/ui/unneeded_struct_pattern.rs:102:30 | LL | if let Custom::NoBrackets { .. } = Custom::Init { | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:109:30 + --> tests/ui/unneeded_struct_pattern.rs:106:30 | LL | if let Custom::NoBrackets {} | Custom::NoBracketsNonExhaustive {} = Custom::Init { | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:109:67 + --> tests/ui/unneeded_struct_pattern.rs:106:67 | LL | if let Custom::NoBrackets {} | Custom::NoBracketsNonExhaustive {} = Custom::Init { | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:114:43 + --> tests/ui/unneeded_struct_pattern.rs:111:43 | LL | if let Custom::NoBracketsNonExhaustive {} = Custom::Init { | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:118:43 + --> tests/ui/unneeded_struct_pattern.rs:115:43 | LL | if let Custom::NoBracketsNonExhaustive { .. } = Custom::Init { | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:134:27 + --> tests/ui/unneeded_struct_pattern.rs:131:27 | LL | let Custom::NoBrackets {} = Custom::Init else { panic!() }; | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:136:27 + --> tests/ui/unneeded_struct_pattern.rs:133:27 | LL | let Custom::NoBrackets { .. } = Custom::Init else { | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:140:40 + --> tests/ui/unneeded_struct_pattern.rs:137:40 | LL | let Custom::NoBracketsNonExhaustive {} = Custom::Init else { | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:144:40 + --> tests/ui/unneeded_struct_pattern.rs:141:40 | LL | let Custom::NoBracketsNonExhaustive { .. } = Custom::Init else { | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:153:44 + --> tests/ui/unneeded_struct_pattern.rs:150:44 | LL | fn pat_in_fn_param_1(Refutable::Variant {}: Refutable) {} | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:154:44 + --> tests/ui/unneeded_struct_pattern.rs:151:44 | LL | fn pat_in_fn_param_2(Refutable::Variant { .. }: Refutable) {} | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:156:27 + --> tests/ui/unneeded_struct_pattern.rs:153:27 | LL | for Refutable::Variant {} in [] {} | ^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:157:27 + --> tests/ui/unneeded_struct_pattern.rs:154:27 | LL | for Refutable::Variant { .. } in [] {} | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:171:23 + --> tests/ui/unneeded_struct_pattern.rs:168:23 | LL | ExhaustiveUnit { .. } => 0, | ^^^^^^^ help: remove the struct pattern error: struct pattern is not needed for a unit variant - --> tests/ui/unneeded_struct_pattern.rs:177:23 + --> tests/ui/unneeded_struct_pattern.rs:174:23 | LL | ExhaustiveUnit {} => 0, | ^^^ help: remove the struct pattern diff --git a/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.fixed b/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.fixed index ff99e436c661f..1c987d0a9aec4 100644 --- a/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.fixed +++ b/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.fixed @@ -1,7 +1,6 @@ //@aux-build:proc_macros.rs #![feature(stmt_expr_attributes)] -#![deny(clippy::unneeded_wildcard_pattern)] -#![allow(clippy::needless_ifs)] +#![warn(clippy::unneeded_wildcard_pattern)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.rs b/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.rs index 5913735d3b4ba..30c11c2f5e7e5 100644 --- a/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.rs +++ b/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.rs @@ -1,7 +1,6 @@ //@aux-build:proc_macros.rs #![feature(stmt_expr_attributes)] -#![deny(clippy::unneeded_wildcard_pattern)] -#![allow(clippy::needless_ifs)] +#![warn(clippy::unneeded_wildcard_pattern)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.stderr b/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.stderr index bfdceb53f7d4a..6559aa42b36fc 100644 --- a/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.stderr +++ b/src/tools/clippy/tests/ui/unneeded_wildcard_pattern.stderr @@ -1,113 +1,110 @@ error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:12:18 + --> tests/ui/unneeded_wildcard_pattern.rs:11:18 | LL | if let (0, .., _) = t {}; | ^^^ help: remove it | -note: the lint level is defined here - --> tests/ui/unneeded_wildcard_pattern.rs:3:9 - | -LL | #![deny(clippy::unneeded_wildcard_pattern)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::unneeded-wildcard-pattern` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::unneeded_wildcard_pattern)]` error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:14:16 + --> tests/ui/unneeded_wildcard_pattern.rs:13:16 | LL | if let (0, _, ..) = t {}; | ^^^ help: remove it error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:16:13 + --> tests/ui/unneeded_wildcard_pattern.rs:15:13 | LL | if let (_, .., 0) = t {}; | ^^^ help: remove it error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:18:15 + --> tests/ui/unneeded_wildcard_pattern.rs:17:15 | LL | if let (.., _, 0) = t {}; | ^^^ help: remove it error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:20:16 + --> tests/ui/unneeded_wildcard_pattern.rs:19:16 | LL | if let (0, _, _, ..) = t {}; | ^^^^^^ help: remove them error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:22:18 + --> tests/ui/unneeded_wildcard_pattern.rs:21:18 | LL | if let (0, .., _, _) = t {}; | ^^^^^^ help: remove them error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:32:22 + --> tests/ui/unneeded_wildcard_pattern.rs:31:22 | LL | if let (0, .., _, _,) = t {}; | ^^^^^^ help: remove them error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:40:19 + --> tests/ui/unneeded_wildcard_pattern.rs:39:19 | LL | if let S(0, .., _) = s {}; | ^^^ help: remove it error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:42:17 + --> tests/ui/unneeded_wildcard_pattern.rs:41:17 | LL | if let S(0, _, ..) = s {}; | ^^^ help: remove it error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:44:14 + --> tests/ui/unneeded_wildcard_pattern.rs:43:14 | LL | if let S(_, .., 0) = s {}; | ^^^ help: remove it error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:46:16 + --> tests/ui/unneeded_wildcard_pattern.rs:45:16 | LL | if let S(.., _, 0) = s {}; | ^^^ help: remove it error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:48:17 + --> tests/ui/unneeded_wildcard_pattern.rs:47:17 | LL | if let S(0, _, _, ..) = s {}; | ^^^^^^ help: remove them error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:50:19 + --> tests/ui/unneeded_wildcard_pattern.rs:49:19 | LL | if let S(0, .., _, _) = s {}; | ^^^^^^ help: remove them error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:60:23 + --> tests/ui/unneeded_wildcard_pattern.rs:59:23 | LL | if let S(0, .., _, _,) = s {}; | ^^^^^^ help: remove them error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:83:33 + --> tests/ui/unneeded_wildcard_pattern.rs:82:33 | LL | let Struct4 { mut a, mut b, c: _, .. } = fourval; | ^^^^^^ help: remove it error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:85:26 + --> tests/ui/unneeded_wildcard_pattern.rs:84:26 | LL | let Struct4 { mut b, c: _, d: _, .. } = fourval; | ^^^^^^^^^^^^ help: remove them error: these patterns are unneeded as the `..` pattern can match those elements - --> tests/ui/unneeded_wildcard_pattern.rs:89:19 + --> tests/ui/unneeded_wildcard_pattern.rs:88:19 | LL | let Struct4 { b: _, c: _, .. } = fourval; | ^^^^^^^^^^^^ help: remove them error: this pattern is unneeded as the `..` pattern can match that element - --> tests/ui/unneeded_wildcard_pattern.rs:91:19 + --> tests/ui/unneeded_wildcard_pattern.rs:90:19 | LL | let Struct4 { c: _, .. } = fourval; | ^^^^^^ help: remove it diff --git a/src/tools/clippy/tests/ui/unnested_or_patterns.fixed b/src/tools/clippy/tests/ui/unnested_or_patterns.fixed index 0391fb19b1f6f..f96088bd39a6d 100644 --- a/src/tools/clippy/tests/ui/unnested_or_patterns.fixed +++ b/src/tools/clippy/tests/ui/unnested_or_patterns.fixed @@ -1,13 +1,7 @@ #![feature(box_patterns)] #![warn(clippy::unnested_or_patterns)] -#![allow( - clippy::cognitive_complexity, - clippy::match_ref_pats, - clippy::upper_case_acronyms, - clippy::needless_ifs, - clippy::manual_range_patterns -)] -#![allow(unreachable_patterns, irrefutable_let_patterns, unused)] +#![allow(clippy::manual_range_patterns)] +#![expect(irrefutable_let_patterns)] struct S { x: u8, diff --git a/src/tools/clippy/tests/ui/unnested_or_patterns.rs b/src/tools/clippy/tests/ui/unnested_or_patterns.rs index f0702668fa917..6f4ef615e9d16 100644 --- a/src/tools/clippy/tests/ui/unnested_or_patterns.rs +++ b/src/tools/clippy/tests/ui/unnested_or_patterns.rs @@ -1,13 +1,7 @@ #![feature(box_patterns)] #![warn(clippy::unnested_or_patterns)] -#![allow( - clippy::cognitive_complexity, - clippy::match_ref_pats, - clippy::upper_case_acronyms, - clippy::needless_ifs, - clippy::manual_range_patterns -)] -#![allow(unreachable_patterns, irrefutable_let_patterns, unused)] +#![allow(clippy::manual_range_patterns)] +#![expect(irrefutable_let_patterns)] struct S { x: u8, diff --git a/src/tools/clippy/tests/ui/unnested_or_patterns.stderr b/src/tools/clippy/tests/ui/unnested_or_patterns.stderr index d2b617c322c46..7298eabaa03e6 100644 --- a/src/tools/clippy/tests/ui/unnested_or_patterns.stderr +++ b/src/tools/clippy/tests/ui/unnested_or_patterns.stderr @@ -1,5 +1,5 @@ error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:21:12 + --> tests/ui/unnested_or_patterns.rs:15:12 | LL | if let box 0 | box 2 = Box::new(0) {} | ^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + if let box (0 | 2) = Box::new(0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:23:12 + --> tests/ui/unnested_or_patterns.rs:17:12 | LL | if let box ((0 | 1)) | box (2 | 3) | box 4 = Box::new(0) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + if let box (0 | 1 | 2 | 3 | 4) = Box::new(0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:26:12 + --> tests/ui/unnested_or_patterns.rs:20:12 | LL | if let Some(1) | C0 | Some(2) = None {} | ^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + if let Some(1 | 2) | C0 = None {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:28:12 + --> tests/ui/unnested_or_patterns.rs:22:12 | LL | if let &mut 0 | &mut 2 = &mut 0 {} | ^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + if let &mut (0 | 2) = &mut 0 {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:30:12 + --> tests/ui/unnested_or_patterns.rs:24:12 | LL | if let x @ 0 | x @ 2 = 0 {} | ^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + if let x @ (0 | 2) = 0 {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:32:12 + --> tests/ui/unnested_or_patterns.rs:26:12 | LL | if let (0, 1) | (0, 2) | (0, 3) = (0, 0) {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + if let (0, 1 | 2 | 3) = (0, 0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:34:12 + --> tests/ui/unnested_or_patterns.rs:28:12 | LL | if let (1, 0) | (2, 0) | (3, 0) = (0, 0) {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + if let (1 | 2 | 3, 0) = (0, 0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:36:12 + --> tests/ui/unnested_or_patterns.rs:30:12 | LL | if let (x, ..) | (x, 1) | (x, 2) = (0, 1) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL + if let (x, ..) | (x, 1 | 2) = (0, 1) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:38:12 + --> tests/ui/unnested_or_patterns.rs:32:12 | LL | if let [0] | [1] = [0] {} | ^^^^^^^^^ @@ -109,7 +109,7 @@ LL + if let [0 | 1] = [0] {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:40:12 + --> tests/ui/unnested_or_patterns.rs:34:12 | LL | if let [x, 0] | [x, 1] = [0, 1] {} | ^^^^^^^^^^^^^^^ @@ -121,7 +121,7 @@ LL + if let [x, 0 | 1] = [0, 1] {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:42:12 + --> tests/ui/unnested_or_patterns.rs:36:12 | LL | if let [x, 0] | [x, 1] | [x, 2] = [0, 1] {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -133,7 +133,7 @@ LL + if let [x, 0 | 1 | 2] = [0, 1] {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:44:12 + --> tests/ui/unnested_or_patterns.rs:38:12 | LL | if let [x, ..] | [x, 1] | [x, 2] = [0, 1] {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -145,7 +145,7 @@ LL + if let [x, ..] | [x, 1 | 2] = [0, 1] {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:47:12 + --> tests/ui/unnested_or_patterns.rs:41:12 | LL | if let TS(0, x) | TS(1, x) = TS(0, 0) {} | ^^^^^^^^^^^^^^^^^^^ @@ -157,7 +157,7 @@ LL + if let TS(0 | 1, x) = TS(0, 0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:49:12 + --> tests/ui/unnested_or_patterns.rs:43:12 | LL | if let TS(1, 0) | TS(2, 0) | TS(3, 0) = TS(0, 0) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -169,7 +169,7 @@ LL + if let TS(1 | 2 | 3, 0) = TS(0, 0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:51:12 + --> tests/ui/unnested_or_patterns.rs:45:12 | LL | if let TS(x, ..) | TS(x, 1) | TS(x, 2) = TS(0, 0) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -181,7 +181,7 @@ LL + if let TS(x, ..) | TS(x, 1 | 2) = TS(0, 0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:53:12 + --> tests/ui/unnested_or_patterns.rs:47:12 | LL | if let S { x: 0, y } | S { y, x: 1 } = (S { x: 0, y: 1 }) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -193,7 +193,7 @@ LL + if let S { x: 0 | 1, y } = (S { x: 0, y: 1 }) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:65:12 + --> tests/ui/unnested_or_patterns.rs:59:12 | LL | if let [1] | [53] = [0] {} | ^^^^^^^^^^ @@ -205,7 +205,7 @@ LL + if let [1 | 53] = [0] {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:71:13 + --> tests/ui/unnested_or_patterns.rs:65:13 | LL | let (0 | (1 | _)) = 0; | ^^^^^^^^^^^^^ @@ -217,7 +217,7 @@ LL + let (0 | 1 | _) = 0; | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:74:16 + --> tests/ui/unnested_or_patterns.rs:68:16 | LL | if let (0 | (1 | _)) = 0 {} | ^^^^^^^^^^^^^ @@ -229,7 +229,7 @@ LL + if let (0 | 1 | _) = 0 {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:78:20 + --> tests/ui/unnested_or_patterns.rs:72:20 | LL | fn or_in_param((x | (x | x)): i32) {} | ^^^^^^^^^^^^^ @@ -241,7 +241,7 @@ LL + fn or_in_param((x | x | x): i32) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns.rs:94:12 + --> tests/ui/unnested_or_patterns.rs:88:12 | LL | if let S { y, x: 0 } | S { y, x: 1 } = (S { x: 0, y: 1 }) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unnested_or_patterns2.fixed b/src/tools/clippy/tests/ui/unnested_or_patterns2.fixed index 852c4ddcfd712..d9625e78c246d 100644 --- a/src/tools/clippy/tests/ui/unnested_or_patterns2.fixed +++ b/src/tools/clippy/tests/ui/unnested_or_patterns2.fixed @@ -1,12 +1,6 @@ #![feature(box_patterns)] #![warn(clippy::unnested_or_patterns)] -#![allow( - clippy::cognitive_complexity, - clippy::match_ref_pats, - clippy::needless_ifs, - clippy::manual_range_patterns -)] -#![allow(unreachable_patterns, irrefutable_let_patterns, unused_variables)] +#![allow(clippy::manual_range_patterns)] fn main() { if let Some(Some(0 | 1)) = None {} diff --git a/src/tools/clippy/tests/ui/unnested_or_patterns2.rs b/src/tools/clippy/tests/ui/unnested_or_patterns2.rs index 12f3d3fca464e..d5215966fcb13 100644 --- a/src/tools/clippy/tests/ui/unnested_or_patterns2.rs +++ b/src/tools/clippy/tests/ui/unnested_or_patterns2.rs @@ -1,12 +1,6 @@ #![feature(box_patterns)] #![warn(clippy::unnested_or_patterns)] -#![allow( - clippy::cognitive_complexity, - clippy::match_ref_pats, - clippy::needless_ifs, - clippy::manual_range_patterns -)] -#![allow(unreachable_patterns, irrefutable_let_patterns, unused_variables)] +#![allow(clippy::manual_range_patterns)] fn main() { if let Some(Some(0)) | Some(Some(1)) = None {} diff --git a/src/tools/clippy/tests/ui/unnested_or_patterns2.stderr b/src/tools/clippy/tests/ui/unnested_or_patterns2.stderr index 3deef33cf258e..776589e294ba5 100644 --- a/src/tools/clippy/tests/ui/unnested_or_patterns2.stderr +++ b/src/tools/clippy/tests/ui/unnested_or_patterns2.stderr @@ -1,5 +1,5 @@ error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:12:12 + --> tests/ui/unnested_or_patterns2.rs:6:12 | LL | if let Some(Some(0)) | Some(Some(1)) = None {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + if let Some(Some(0 | 1)) = None {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:14:12 + --> tests/ui/unnested_or_patterns2.rs:8:12 | LL | if let Some(Some(0)) | Some(Some(1) | Some(2)) = None {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + if let Some(Some(0 | 1 | 2)) = None {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:16:12 + --> tests/ui/unnested_or_patterns2.rs:10:12 | LL | if let Some(Some(0 | 1) | Some(2)) | Some(Some(3) | Some(4)) = None {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + if let Some(Some(0 | 1 | 2 | 3 | 4)) = None {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:18:12 + --> tests/ui/unnested_or_patterns2.rs:12:12 | LL | if let Some(Some(0) | Some(1 | 2)) = None {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + if let Some(Some(0 | 1 | 2)) = None {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:20:12 + --> tests/ui/unnested_or_patterns2.rs:14:12 | LL | if let ((0,),) | ((1,) | (2,),) = ((0,),) {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + if let ((0 | 1 | 2,),) = ((0,),) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:22:12 + --> tests/ui/unnested_or_patterns2.rs:16:12 | LL | if let 0 | (1 | 2) = 0 {} | ^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + if let 0 | 1 | 2 = 0 {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:24:12 + --> tests/ui/unnested_or_patterns2.rs:18:12 | LL | if let box (0 | 1) | (box 2 | box (3 | 4)) = Box::new(0) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + if let box (0 | 1 | 2 | 3 | 4) = Box::new(0) {} | error: unnested or-patterns - --> tests/ui/unnested_or_patterns2.rs:26:12 + --> tests/ui/unnested_or_patterns2.rs:20:12 | LL | if let box box 0 | box (box 2 | box 4) = Box::new(Box::new(0)) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unsafe_derive_deserialize.rs b/src/tools/clippy/tests/ui/unsafe_derive_deserialize.rs index d0022f3b6d93d..2d3cddc2d6e13 100644 --- a/src/tools/clippy/tests/ui/unsafe_derive_deserialize.rs +++ b/src/tools/clippy/tests/ui/unsafe_derive_deserialize.rs @@ -1,5 +1,5 @@ #![warn(clippy::unsafe_derive_deserialize)] -#![allow(unused, clippy::missing_safety_doc)] +#![expect(clippy::missing_safety_doc)] extern crate serde; diff --git a/src/tools/clippy/tests/ui/unsafe_removed_from_name.rs b/src/tools/clippy/tests/ui/unsafe_removed_from_name.rs index f3d318815c101..fe2b495611cc3 100644 --- a/src/tools/clippy/tests/ui/unsafe_removed_from_name.rs +++ b/src/tools/clippy/tests/ui/unsafe_removed_from_name.rs @@ -1,5 +1,3 @@ -#![allow(unused_imports)] -#![allow(dead_code)] #![warn(clippy::unsafe_removed_from_name)] use std::cell::UnsafeCell as TotallySafeCell; diff --git a/src/tools/clippy/tests/ui/unsafe_removed_from_name.stderr b/src/tools/clippy/tests/ui/unsafe_removed_from_name.stderr index cd3c1f80a3002..0010ce5d6e5b9 100644 --- a/src/tools/clippy/tests/ui/unsafe_removed_from_name.stderr +++ b/src/tools/clippy/tests/ui/unsafe_removed_from_name.stderr @@ -1,5 +1,5 @@ error: removed `unsafe` from the name of `UnsafeCell` in use as `TotallySafeCell` - --> tests/ui/unsafe_removed_from_name.rs:5:1 + --> tests/ui/unsafe_removed_from_name.rs:3:1 | LL | use std::cell::UnsafeCell as TotallySafeCell; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,31 +8,31 @@ LL | use std::cell::UnsafeCell as TotallySafeCell; = help: to override `-D warnings` add `#[allow(clippy::unsafe_removed_from_name)]` error: removed `unsafe` from the name of `UnsafeCell` in use as `TotallySafeCellAgain` - --> tests/ui/unsafe_removed_from_name.rs:8:1 + --> tests/ui/unsafe_removed_from_name.rs:6:1 | LL | use std::cell::UnsafeCell as TotallySafeCellAgain; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: removed `unsafe` from the name of `Unsafe` in use as `LieAboutModSafety` - --> tests/ui/unsafe_removed_from_name.rs:28:1 + --> tests/ui/unsafe_removed_from_name.rs:26:1 | LL | use mod_with_some_unsafe_things::Unsafe as LieAboutModSafety; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: removed `unsafe` from the name of `Unsafe` in use as `A` - --> tests/ui/unsafe_removed_from_name.rs:32:1 + --> tests/ui/unsafe_removed_from_name.rs:30:1 | LL | use mod_with_some_unsafe_things::{Unsafe as A, Unsafe as B}; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: removed `unsafe` from the name of `Unsafe` in use as `B` - --> tests/ui/unsafe_removed_from_name.rs:32:1 + --> tests/ui/unsafe_removed_from_name.rs:30:1 | LL | use mod_with_some_unsafe_things::{Unsafe as A, Unsafe as B}; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: removed `unsafe` from the name of `UnsafeTrait` in use as `FakeSafeTrait` - --> tests/ui/unsafe_removed_from_name.rs:47:1 + --> tests/ui/unsafe_removed_from_name.rs:45:1 | LL | use mod_with_some_unsafe_things::UnsafeTrait as FakeSafeTrait; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unseparated_prefix_literals.fixed b/src/tools/clippy/tests/ui/unseparated_prefix_literals.fixed index e13dd561d627a..e90a7319263db 100644 --- a/src/tools/clippy/tests/ui/unseparated_prefix_literals.fixed +++ b/src/tools/clippy/tests/ui/unseparated_prefix_literals.fixed @@ -1,7 +1,6 @@ //@aux-build:proc_macro_derive.rs #![warn(clippy::unseparated_literal_suffix)] -#![allow(dead_code)] #[macro_use] extern crate proc_macro_derive; diff --git a/src/tools/clippy/tests/ui/unseparated_prefix_literals.rs b/src/tools/clippy/tests/ui/unseparated_prefix_literals.rs index 6f7b16ccba54c..8988ae7b879af 100644 --- a/src/tools/clippy/tests/ui/unseparated_prefix_literals.rs +++ b/src/tools/clippy/tests/ui/unseparated_prefix_literals.rs @@ -1,7 +1,6 @@ //@aux-build:proc_macro_derive.rs #![warn(clippy::unseparated_literal_suffix)] -#![allow(dead_code)] #[macro_use] extern crate proc_macro_derive; diff --git a/src/tools/clippy/tests/ui/unseparated_prefix_literals.stderr b/src/tools/clippy/tests/ui/unseparated_prefix_literals.stderr index 4cfbf5e4b74ea..67e47865108e1 100644 --- a/src/tools/clippy/tests/ui/unseparated_prefix_literals.stderr +++ b/src/tools/clippy/tests/ui/unseparated_prefix_literals.stderr @@ -1,5 +1,5 @@ error: integer type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:24:18 + --> tests/ui/unseparated_prefix_literals.rs:23:18 | LL | let _fail1 = 1234i32; | ^^^^^^^ help: add an underscore: `1234_i32` @@ -8,43 +8,43 @@ LL | let _fail1 = 1234i32; = help: to override `-D warnings` add `#[allow(clippy::unseparated_literal_suffix)]` error: integer type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:26:18 + --> tests/ui/unseparated_prefix_literals.rs:25:18 | LL | let _fail2 = 1234u32; | ^^^^^^^ help: add an underscore: `1234_u32` error: integer type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:28:18 + --> tests/ui/unseparated_prefix_literals.rs:27:18 | LL | let _fail3 = 1234isize; | ^^^^^^^^^ help: add an underscore: `1234_isize` error: integer type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:30:18 + --> tests/ui/unseparated_prefix_literals.rs:29:18 | LL | let _fail4 = 1234usize; | ^^^^^^^^^ help: add an underscore: `1234_usize` error: integer type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:32:18 + --> tests/ui/unseparated_prefix_literals.rs:31:18 | LL | let _fail5 = 0x123isize; | ^^^^^^^^^^ help: add an underscore: `0x123_isize` error: float type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:37:19 + --> tests/ui/unseparated_prefix_literals.rs:36:19 | LL | let _failf1 = 1.5f32; | ^^^^^^ help: add an underscore: `1.5_f32` error: float type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:39:19 + --> tests/ui/unseparated_prefix_literals.rs:38:19 | LL | let _failf2 = 1f32; | ^^^^ help: add an underscore: `1_f32` error: integer type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:15:9 + --> tests/ui/unseparated_prefix_literals.rs:14:9 | LL | 42usize | ^^^^^^^ help: add an underscore: `42_usize` @@ -55,7 +55,7 @@ LL | let _ = lit_from_macro!(); = note: this error originates in the macro `lit_from_macro` (in Nightly builds, run with -Z macro-backtrace for more info) error: integer type suffix should be separated by an underscore - --> tests/ui/unseparated_prefix_literals.rs:48:16 + --> tests/ui/unseparated_prefix_literals.rs:47:16 | LL | assert_eq!(4897u32, 32223); | ^^^^^^^ help: add an underscore: `4897_u32` diff --git a/src/tools/clippy/tests/ui/unused_async.rs b/src/tools/clippy/tests/ui/unused_async.rs index b6780d240b17c..6fcb55cb434f1 100644 --- a/src/tools/clippy/tests/ui/unused_async.rs +++ b/src/tools/clippy/tests/ui/unused_async.rs @@ -1,11 +1,10 @@ #![warn(clippy::unused_async)] -#![allow(incomplete_features)] use std::future::Future; use std::pin::Pin; mod issue10800 { - #![allow(dead_code, unused_must_use, clippy::no_effect)] + #![allow(clippy::no_effect)] use std::future::ready; diff --git a/src/tools/clippy/tests/ui/unused_async.stderr b/src/tools/clippy/tests/ui/unused_async.stderr index f95fdd8653001..513e0bb9b9ed4 100644 --- a/src/tools/clippy/tests/ui/unused_async.stderr +++ b/src/tools/clippy/tests/ui/unused_async.stderr @@ -1,5 +1,5 @@ error: unused `async` for function with no await statements - --> tests/ui/unused_async.rs:12:5 + --> tests/ui/unused_async.rs:11:5 | LL | / async fn async_block_await() { LL | | @@ -12,7 +12,7 @@ LL | | } | = help: consider removing the `async` from this function note: `await` used in an async block, which does not require the enclosing function to be `async` - --> tests/ui/unused_async.rs:16:23 + --> tests/ui/unused_async.rs:15:23 | LL | ready(()).await; | ^^^^^ @@ -20,7 +20,7 @@ LL | ready(()).await; = help: to override `-D warnings` add `#[allow(clippy::unused_async)]` error: unused `async` for function with no await statements - --> tests/ui/unused_async.rs:46:5 + --> tests/ui/unused_async.rs:45:5 | LL | async fn f3() {} | ^^^^^^^^^^^^^^^^ @@ -28,7 +28,7 @@ LL | async fn f3() {} = help: consider removing the `async` from this function error: unused `async` for function with no await statements - --> tests/ui/unused_async.rs:75:1 + --> tests/ui/unused_async.rs:74:1 | LL | / async fn foo() -> i32 { LL | | @@ -40,7 +40,7 @@ LL | | } = help: consider removing the `async` from this function error: unused `async` for function with no await statements - --> tests/ui/unused_async.rs:88:5 + --> tests/ui/unused_async.rs:87:5 | LL | / async fn unused(&self) -> i32 { LL | | diff --git a/src/tools/clippy/tests/ui/unused_enumerate_index.fixed b/src/tools/clippy/tests/ui/unused_enumerate_index.fixed index 258e52971ceab..4e7a50825a3e3 100644 --- a/src/tools/clippy/tests/ui/unused_enumerate_index.fixed +++ b/src/tools/clippy/tests/ui/unused_enumerate_index.fixed @@ -1,5 +1,5 @@ -#![allow(unused, clippy::map_identity)] #![warn(clippy::unused_enumerate_index)] +#![allow(clippy::map_identity)] use std::iter::Enumerate; diff --git a/src/tools/clippy/tests/ui/unused_enumerate_index.rs b/src/tools/clippy/tests/ui/unused_enumerate_index.rs index a17e3259a9b07..13115e6ab322f 100644 --- a/src/tools/clippy/tests/ui/unused_enumerate_index.rs +++ b/src/tools/clippy/tests/ui/unused_enumerate_index.rs @@ -1,5 +1,5 @@ -#![allow(unused, clippy::map_identity)] #![warn(clippy::unused_enumerate_index)] +#![allow(clippy::map_identity)] use std::iter::Enumerate; diff --git a/src/tools/clippy/tests/ui/unused_format_specs_width.rs b/src/tools/clippy/tests/ui/unused_format_specs_width.rs index 3f0bfc0963a87..ea9f62e1e95e1 100644 --- a/src/tools/clippy/tests/ui/unused_format_specs_width.rs +++ b/src/tools/clippy/tests/ui/unused_format_specs_width.rs @@ -2,7 +2,7 @@ // Format width has no effect for certain traits (issue #15039) #![warn(clippy::unused_format_specs)] -#![allow(clippy::zero_ptr, clippy::manual_dangling_ptr)] +#![expect(clippy::manual_dangling_ptr, clippy::zero_ptr)] fn main() { // Integer formats with # (alternate): 0x/0o/0b prefix makes min width 4 diff --git a/src/tools/clippy/tests/ui/unused_io_amount.rs b/src/tools/clippy/tests/ui/unused_io_amount.rs index 32a50375806a3..5859dc20f6428 100644 --- a/src/tools/clippy/tests/ui/unused_io_amount.rs +++ b/src/tools/clippy/tests/ui/unused_io_amount.rs @@ -1,6 +1,5 @@ -#![allow(dead_code, clippy::needless_pass_by_ref_mut)] -#![allow(clippy::redundant_pattern_matching)] #![warn(clippy::unused_io_amount)] +#![expect(clippy::redundant_pattern_matching)] extern crate futures; use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; diff --git a/src/tools/clippy/tests/ui/unused_io_amount.stderr b/src/tools/clippy/tests/ui/unused_io_amount.stderr index 71bb4c40de840..466487de894aa 100644 --- a/src/tools/clippy/tests/ui/unused_io_amount.stderr +++ b/src/tools/clippy/tests/ui/unused_io_amount.stderr @@ -1,5 +1,5 @@ error: written amount is not handled - --> tests/ui/unused_io_amount.rs:10:5 + --> tests/ui/unused_io_amount.rs:9:5 | LL | s.write(b"test")?; | ^^^^^^^^^^^^^^^^^ @@ -9,7 +9,7 @@ LL | s.write(b"test")?; = help: to override `-D warnings` add `#[allow(clippy::unused_io_amount)]` error: read amount is not handled - --> tests/ui/unused_io_amount.rs:13:5 + --> tests/ui/unused_io_amount.rs:12:5 | LL | s.read(&mut buf)?; | ^^^^^^^^^^^^^^^^^ @@ -17,7 +17,7 @@ LL | s.read(&mut buf)?; = help: use `Read::read_exact` instead, or handle partial reads error: written amount is not handled - --> tests/ui/unused_io_amount.rs:19:5 + --> tests/ui/unused_io_amount.rs:18:5 | LL | s.write(b"test").unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL | s.write(b"test").unwrap(); = help: use `Write::write_all` instead, or handle partial writes error: read amount is not handled - --> tests/ui/unused_io_amount.rs:22:5 + --> tests/ui/unused_io_amount.rs:21:5 | LL | s.read(&mut buf).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -33,19 +33,19 @@ LL | s.read(&mut buf).unwrap(); = help: use `Read::read_exact` instead, or handle partial reads error: read amount is not handled - --> tests/ui/unused_io_amount.rs:27:5 + --> tests/ui/unused_io_amount.rs:26:5 | LL | s.read_vectored(&mut [io::IoSliceMut::new(&mut [])])?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: written amount is not handled - --> tests/ui/unused_io_amount.rs:29:5 + --> tests/ui/unused_io_amount.rs:28:5 | LL | s.write_vectored(&[io::IoSlice::new(&[])])?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: read amount is not handled - --> tests/ui/unused_io_amount.rs:37:5 + --> tests/ui/unused_io_amount.rs:36:5 | LL | reader.read(&mut result).ok()?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -53,7 +53,7 @@ LL | reader.read(&mut result).ok()?; = help: use `Read::read_exact` instead, or handle partial reads error: read amount is not handled - --> tests/ui/unused_io_amount.rs:47:5 + --> tests/ui/unused_io_amount.rs:46:5 | LL | reader.read(&mut result).or_else(|err| Err(err))?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL | reader.read(&mut result).or_else(|err| Err(err))?; = help: use `Read::read_exact` instead, or handle partial reads error: read amount is not handled - --> tests/ui/unused_io_amount.rs:60:5 + --> tests/ui/unused_io_amount.rs:59:5 | LL | reader.read(&mut result).or(Err(Error::Kind))?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -69,7 +69,7 @@ LL | reader.read(&mut result).or(Err(Error::Kind))?; = help: use `Read::read_exact` instead, or handle partial reads error: read amount is not handled - --> tests/ui/unused_io_amount.rs:68:5 + --> tests/ui/unused_io_amount.rs:67:5 | LL | / reader LL | | @@ -82,7 +82,7 @@ LL | | .expect("error"); = help: use `Read::read_exact` instead, or handle partial reads error: written amount is not handled - --> tests/ui/unused_io_amount.rs:78:5 + --> tests/ui/unused_io_amount.rs:77:5 | LL | s.write(b"ok").is_ok(); | ^^^^^^^^^^^^^^^^^^^^^^ @@ -90,7 +90,7 @@ LL | s.write(b"ok").is_ok(); = help: use `Write::write_all` instead, or handle partial writes error: written amount is not handled - --> tests/ui/unused_io_amount.rs:80:5 + --> tests/ui/unused_io_amount.rs:79:5 | LL | s.write(b"err").is_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -98,7 +98,7 @@ LL | s.write(b"err").is_err(); = help: use `Write::write_all` instead, or handle partial writes error: read amount is not handled - --> tests/ui/unused_io_amount.rs:83:5 + --> tests/ui/unused_io_amount.rs:82:5 | LL | s.read(&mut buf).is_ok(); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -106,7 +106,7 @@ LL | s.read(&mut buf).is_ok(); = help: use `Read::read_exact` instead, or handle partial reads error: read amount is not handled - --> tests/ui/unused_io_amount.rs:85:5 + --> tests/ui/unused_io_amount.rs:84:5 | LL | s.read(&mut buf).is_err(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -114,7 +114,7 @@ LL | s.read(&mut buf).is_err(); = help: use `Read::read_exact` instead, or handle partial reads error: written amount is not handled - --> tests/ui/unused_io_amount.rs:90:5 + --> tests/ui/unused_io_amount.rs:89:5 | LL | w.write(b"hello world").await.unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -122,7 +122,7 @@ LL | w.write(b"hello world").await.unwrap(); = help: use `AsyncWriteExt::write_all` instead, or handle partial writes error: read amount is not handled - --> tests/ui/unused_io_amount.rs:96:5 + --> tests/ui/unused_io_amount.rs:95:5 | LL | r.read(&mut buf[..]).await.unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -130,7 +130,7 @@ LL | r.read(&mut buf[..]).await.unwrap(); = help: use `AsyncReadExt::read_exact` instead, or handle partial reads error: written amount is not handled - --> tests/ui/unused_io_amount.rs:104:5 + --> tests/ui/unused_io_amount.rs:103:5 | LL | w.write(b"hello world"); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -138,7 +138,7 @@ LL | w.write(b"hello world"); = help: use `AsyncWriteExt::write_all` instead, or handle partial writes error: written amount is not handled - --> tests/ui/unused_io_amount.rs:111:9 + --> tests/ui/unused_io_amount.rs:110:9 | LL | w.write(b"hello world").await?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -146,7 +146,7 @@ LL | w.write(b"hello world").await?; = help: use `AsyncWriteExt::write_all` instead, or handle partial writes error: read amount is not handled - --> tests/ui/unused_io_amount.rs:120:9 + --> tests/ui/unused_io_amount.rs:119:9 | LL | r.read(&mut buf[..]).await.or(Err(Error::Kind))?; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -154,7 +154,7 @@ LL | r.read(&mut buf[..]).await.or(Err(Error::Kind))?; = help: use `AsyncReadExt::read_exact` instead, or handle partial reads error: written amount is not handled - --> tests/ui/unused_io_amount.rs:129:5 + --> tests/ui/unused_io_amount.rs:128:5 | LL | w.write(b"hello world").await.unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -162,7 +162,7 @@ LL | w.write(b"hello world").await.unwrap(); = help: use `AsyncWriteExt::write_all` instead, or handle partial writes error: read amount is not handled - --> tests/ui/unused_io_amount.rs:135:5 + --> tests/ui/unused_io_amount.rs:134:5 | LL | r.read(&mut buf[..]).await.unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -170,92 +170,92 @@ LL | r.read(&mut buf[..]).await.unwrap(); = help: use `AsyncReadExt::read_exact` instead, or handle partial reads error: written amount is not handled - --> tests/ui/unused_io_amount.rs:148:11 + --> tests/ui/unused_io_amount.rs:147:11 | LL | match s.write(b"test") { | ^^^^^^^^^^^^^^^^ | = help: use `Write::write_all` instead, or handle partial writes note: the result is consumed here, but the amount of I/O bytes remains unhandled - --> tests/ui/unused_io_amount.rs:150:9 + --> tests/ui/unused_io_amount.rs:149:9 | LL | Ok(_) => todo!(), | ^^^^^ error: read amount is not handled - --> tests/ui/unused_io_amount.rs:155:11 + --> tests/ui/unused_io_amount.rs:154:11 | LL | match s.read(&mut buf) { | ^^^^^^^^^^^^^^^^ | = help: use `Read::read_exact` instead, or handle partial reads note: the result is consumed here, but the amount of I/O bytes remains unhandled - --> tests/ui/unused_io_amount.rs:157:9 + --> tests/ui/unused_io_amount.rs:156:9 | LL | Ok(_) => todo!(), | ^^^^^ error: read amount is not handled - --> tests/ui/unused_io_amount.rs:163:11 + --> tests/ui/unused_io_amount.rs:162:11 | LL | match s.read(&mut [0u8; 4]) { | ^^^^^^^^^^^^^^^^^^^^^ | = help: use `Read::read_exact` instead, or handle partial reads note: the result is consumed here, but the amount of I/O bytes remains unhandled - --> tests/ui/unused_io_amount.rs:165:9 + --> tests/ui/unused_io_amount.rs:164:9 | LL | Ok(_) => todo!(), | ^^^^^ error: written amount is not handled - --> tests/ui/unused_io_amount.rs:171:11 + --> tests/ui/unused_io_amount.rs:170:11 | LL | match s.write(b"test") { | ^^^^^^^^^^^^^^^^ | = help: use `Write::write_all` instead, or handle partial writes note: the result is consumed here, but the amount of I/O bytes remains unhandled - --> tests/ui/unused_io_amount.rs:173:9 + --> tests/ui/unused_io_amount.rs:172:9 | LL | Ok(_) => todo!(), | ^^^^^ error: read amount is not handled - --> tests/ui/unused_io_amount.rs:183:8 + --> tests/ui/unused_io_amount.rs:182:8 | LL | if let Ok(_) = s.read(&mut [0u8; 4]) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: use `Read::read_exact` instead, or handle partial reads note: the result is consumed here, but the amount of I/O bytes remains unhandled - --> tests/ui/unused_io_amount.rs:183:12 + --> tests/ui/unused_io_amount.rs:182:12 | LL | if let Ok(_) = s.read(&mut [0u8; 4]) { | ^^^^^ error: written amount is not handled - --> tests/ui/unused_io_amount.rs:190:8 + --> tests/ui/unused_io_amount.rs:189:8 | LL | if let Ok(_) = s.write(b"test") { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: use `Write::write_all` instead, or handle partial writes note: the result is consumed here, but the amount of I/O bytes remains unhandled - --> tests/ui/unused_io_amount.rs:190:12 + --> tests/ui/unused_io_amount.rs:189:12 | LL | if let Ok(_) = s.write(b"test") { | ^^^^^ error: written amount is not handled - --> tests/ui/unused_io_amount.rs:197:8 + --> tests/ui/unused_io_amount.rs:196:8 | LL | if let Ok(..) = s.write(b"test") { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: use `Write::write_all` instead, or handle partial writes note: the result is consumed here, but the amount of I/O bytes remains unhandled - --> tests/ui/unused_io_amount.rs:197:12 + --> tests/ui/unused_io_amount.rs:196:12 | LL | if let Ok(..) = s.write(b"test") { | ^^^^^^ diff --git a/src/tools/clippy/tests/ui/unused_peekable.rs b/src/tools/clippy/tests/ui/unused_peekable.rs index 29e830fefb87d..8c5a3c6fa9fa6 100644 --- a/src/tools/clippy/tests/ui/unused_peekable.rs +++ b/src/tools/clippy/tests/ui/unused_peekable.rs @@ -1,5 +1,5 @@ #![warn(clippy::unused_peekable)] -#![allow(clippy::no_effect)] +#![expect(clippy::no_effect)] use std::iter::{Empty, Peekable}; diff --git a/src/tools/clippy/tests/ui/unused_result_ok.fixed b/src/tools/clippy/tests/ui/unused_result_ok.fixed index faedd96216c2e..91db7574b0c31 100644 --- a/src/tools/clippy/tests/ui/unused_result_ok.fixed +++ b/src/tools/clippy/tests/ui/unused_result_ok.fixed @@ -1,6 +1,5 @@ //@aux-build:proc_macros.rs #![warn(clippy::unused_result_ok)] -#![allow(dead_code)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unused_result_ok.rs b/src/tools/clippy/tests/ui/unused_result_ok.rs index 6ab974861b636..b02252db416c7 100644 --- a/src/tools/clippy/tests/ui/unused_result_ok.rs +++ b/src/tools/clippy/tests/ui/unused_result_ok.rs @@ -1,6 +1,5 @@ //@aux-build:proc_macros.rs #![warn(clippy::unused_result_ok)] -#![allow(dead_code)] #[macro_use] extern crate proc_macros; diff --git a/src/tools/clippy/tests/ui/unused_result_ok.stderr b/src/tools/clippy/tests/ui/unused_result_ok.stderr index 0e134ba3ccba2..e4560aa84dea1 100644 --- a/src/tools/clippy/tests/ui/unused_result_ok.stderr +++ b/src/tools/clippy/tests/ui/unused_result_ok.stderr @@ -1,5 +1,5 @@ error: ignoring a result with `.ok()` is misleading - --> tests/ui/unused_result_ok.rs:9:5 + --> tests/ui/unused_result_ok.rs:8:5 | LL | x.parse::().ok(); | ^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let _ = x.parse::(); | error: ignoring a result with `.ok()` is misleading - --> tests/ui/unused_result_ok.rs:19:5 + --> tests/ui/unused_result_ok.rs:18:5 | LL | x . parse::() . ok (); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + let _ = x . parse::(); | error: ignoring a result with `.ok()` is misleading - --> tests/ui/unused_result_ok.rs:37:5 + --> tests/ui/unused_result_ok.rs:36:5 | LL | v!().ok(); | ^^^^^^^^^ @@ -37,7 +37,7 @@ LL + let _ = v!(); | error: ignoring a result with `.ok()` is misleading - --> tests/ui/unused_result_ok.rs:31:9 + --> tests/ui/unused_result_ok.rs:30:9 | LL | Ok::<(), ()>(()).ok(); | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unused_self.rs b/src/tools/clippy/tests/ui/unused_self.rs index cb80d946acedb..9e016af400534 100644 --- a/src/tools/clippy/tests/ui/unused_self.rs +++ b/src/tools/clippy/tests/ui/unused_self.rs @@ -1,5 +1,5 @@ #![warn(clippy::unused_self)] -#![allow(clippy::boxed_local, clippy::fn_params_excessive_bools)] +#![expect(clippy::boxed_local, clippy::fn_params_excessive_bools)] mod unused_self { use std::pin::Pin; diff --git a/src/tools/clippy/tests/ui/unused_trait_names.fixed b/src/tools/clippy/tests/ui/unused_trait_names.fixed index 6abbed01bb023..014e667d125d7 100644 --- a/src/tools/clippy/tests/ui/unused_trait_names.fixed +++ b/src/tools/clippy/tests/ui/unused_trait_names.fixed @@ -1,6 +1,5 @@ //@aux-build:proc_macros.rs -#![allow(unused)] #![warn(clippy::unused_trait_names)] #![feature(decl_macro)] diff --git a/src/tools/clippy/tests/ui/unused_trait_names.rs b/src/tools/clippy/tests/ui/unused_trait_names.rs index 4a06f062dc37e..38c0b775f84b7 100644 --- a/src/tools/clippy/tests/ui/unused_trait_names.rs +++ b/src/tools/clippy/tests/ui/unused_trait_names.rs @@ -1,6 +1,5 @@ //@aux-build:proc_macros.rs -#![allow(unused)] #![warn(clippy::unused_trait_names)] #![feature(decl_macro)] diff --git a/src/tools/clippy/tests/ui/unused_trait_names.stderr b/src/tools/clippy/tests/ui/unused_trait_names.stderr index 28067e17414f8..32c7151e9908c 100644 --- a/src/tools/clippy/tests/ui/unused_trait_names.stderr +++ b/src/tools/clippy/tests/ui/unused_trait_names.stderr @@ -1,5 +1,5 @@ error: unused import: `std::any::Any` - --> tests/ui/unused_trait_names.rs:254:9 + --> tests/ui/unused_trait_names.rs:253:9 | LL | use std::any::Any; | ^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | use std::any::Any; = help: to override `-D warnings` add `#[allow(unused_imports)]` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:12:19 + --> tests/ui/unused_trait_names.rs:11:19 | LL | use std::any::Any; | ^^^ help: use: `Any as _` @@ -17,43 +17,43 @@ LL | use std::any::Any; = help: to override `-D warnings` add `#[allow(clippy::unused_trait_names)]` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:32:26 + --> tests/ui/unused_trait_names.rs:31:26 | LL | use std::any::{self, Any, TypeId}; | ^^^ help: use: `Any as _` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:45:19 + --> tests/ui/unused_trait_names.rs:44:19 | LL | use std::any::Any as MyAny; | ^^^^^^^^^^^^ help: use: `Any as _` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:52:20 + --> tests/ui/unused_trait_names.rs:51:20 | LL | use std::any::{Any as MyAny, TypeId as MyTypeId}; | ^^^^^^^^^^^^ help: use: `Any as _` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:76:23 + --> tests/ui/unused_trait_names.rs:75:23 | LL | use std::any::Any; | ^^^ help: use: `Any as _` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:118:19 + --> tests/ui/unused_trait_names.rs:117:19 | LL | use std::any::Any; | ^^^ help: use: `Any as _` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:138:19 + --> tests/ui/unused_trait_names.rs:137:19 | LL | use std::any::Any; | ^^^ help: use: `Any as _` error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:198:34 + --> tests/ui/unused_trait_names.rs:197:34 | LL | use simple_trait::{MyStruct, MyTrait}; | ^^^^^^^ help: use: `MyTrait as _` diff --git a/src/tools/clippy/tests/ui/unused_unit.edition2021.fixed b/src/tools/clippy/tests/ui/unused_unit.edition2021.fixed index 8e12bd2c8c7b9..b6e3753d9ee4d 100644 --- a/src/tools/clippy/tests/ui/unused_unit.edition2021.fixed +++ b/src/tools/clippy/tests/ui/unused_unit.edition2021.fixed @@ -12,9 +12,8 @@ #![feature(closure_lifetime_binder)] #![rustfmt::skip] -#![deny(clippy::unused_unit)] -#![allow(dead_code)] -#![allow(clippy::from_over_into)] +#![warn(clippy::unused_unit)] +#![expect(clippy::from_over_into)] struct Unitter; impl Unitter { @@ -142,7 +141,6 @@ mod issue14577 { } mod pr14962 { - #[allow(unused_parens)] type UnusedParensButNoUnit = Box; } diff --git a/src/tools/clippy/tests/ui/unused_unit.edition2021.stderr b/src/tools/clippy/tests/ui/unused_unit.edition2021.stderr index 9ad3c2df915ec..a6b9fa70d6cf8 100644 --- a/src/tools/clippy/tests/ui/unused_unit.edition2021.stderr +++ b/src/tools/clippy/tests/ui/unused_unit.edition2021.stderr @@ -1,125 +1,122 @@ error: unneeded unit expression - --> tests/ui/unused_unit.rs:37:9 + --> tests/ui/unused_unit.rs:36:9 | LL | () | ^^ help: remove the final `()` | -note: the lint level is defined here - --> tests/ui/unused_unit.rs:15:9 - | -LL | #![deny(clippy::unused_unit)] - | ^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::unused-unit` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::unused_unit)]` error: unneeded unit expression - --> tests/ui/unused_unit.rs:62:26 + --> tests/ui/unused_unit.rs:61:26 | LL | fn return_unit() -> () { () } | ^^ help: remove the final `()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:22:28 + --> tests/ui/unused_unit.rs:21:28 | LL | pub fn get_unit (), G>(&self, f: F, _g: G) -> () | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:25:18 + --> tests/ui/unused_unit.rs:24:18 | LL | where G: Fn() -> () { | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:22:58 + --> tests/ui/unused_unit.rs:21:58 | LL | pub fn get_unit (), G>(&self, f: F, _g: G) -> () | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:27:26 + --> tests/ui/unused_unit.rs:26:26 | LL | let _y: &dyn Fn() -> () = &f; | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:35:18 + --> tests/ui/unused_unit.rs:34:18 | LL | fn into(self) -> () { | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:43:29 + --> tests/ui/unused_unit.rs:42:29 | LL | fn redundant (), G, H>(&self, _f: F, _g: G, _h: H) | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:46:19 + --> tests/ui/unused_unit.rs:45:19 | LL | G: FnMut() -> (), | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:48:16 + --> tests/ui/unused_unit.rs:47:16 | LL | H: Fn() -> (); | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:53:29 + --> tests/ui/unused_unit.rs:52:29 | LL | fn redundant (), G, H>(&self, _f: F, _g: G, _h: H) | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:56:19 + --> tests/ui/unused_unit.rs:55:19 | LL | G: FnMut() -> (), | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:58:16 + --> tests/ui/unused_unit.rs:57:16 | LL | H: Fn() -> () {} | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:62:17 + --> tests/ui/unused_unit.rs:61:17 | LL | fn return_unit() -> () { () } | ^^^^^^ help: remove the `-> ()` error: unneeded `()` - --> tests/ui/unused_unit.rs:74:14 + --> tests/ui/unused_unit.rs:73:14 | LL | break(); | ^^ help: remove the `()` error: unneeded `()` - --> tests/ui/unused_unit.rs:77:11 + --> tests/ui/unused_unit.rs:76:11 | LL | return(); | ^^ help: remove the `()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:95:10 + --> tests/ui/unused_unit.rs:94:10 | LL | fn test()->(){} | ^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:99:11 + --> tests/ui/unused_unit.rs:98:11 | LL | fn test2() ->(){} | ^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:103:11 + --> tests/ui/unused_unit.rs:102:11 | LL | fn test3()-> (){} | ^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:131:13 + --> tests/ui/unused_unit.rs:130:13 | LL | fn bar() -> () { | ^^^^^^ help: remove the `-> ()` diff --git a/src/tools/clippy/tests/ui/unused_unit.edition2024.fixed b/src/tools/clippy/tests/ui/unused_unit.edition2024.fixed index 688d2fe9afa28..f389b833310a1 100644 --- a/src/tools/clippy/tests/ui/unused_unit.edition2024.fixed +++ b/src/tools/clippy/tests/ui/unused_unit.edition2024.fixed @@ -12,9 +12,8 @@ #![feature(closure_lifetime_binder)] #![rustfmt::skip] -#![deny(clippy::unused_unit)] -#![allow(dead_code)] -#![allow(clippy::from_over_into)] +#![warn(clippy::unused_unit)] +#![expect(clippy::from_over_into)] struct Unitter; impl Unitter { @@ -142,7 +141,6 @@ mod issue14577 { } mod pr14962 { - #[allow(unused_parens)] type UnusedParensButNoUnit = Box; } diff --git a/src/tools/clippy/tests/ui/unused_unit.edition2024.stderr b/src/tools/clippy/tests/ui/unused_unit.edition2024.stderr index a79e70e066bd3..360dabbe145a4 100644 --- a/src/tools/clippy/tests/ui/unused_unit.edition2024.stderr +++ b/src/tools/clippy/tests/ui/unused_unit.edition2024.stderr @@ -1,119 +1,116 @@ error: unneeded unit expression - --> tests/ui/unused_unit.rs:37:9 + --> tests/ui/unused_unit.rs:36:9 | LL | () | ^^ help: remove the final `()` | -note: the lint level is defined here - --> tests/ui/unused_unit.rs:15:9 - | -LL | #![deny(clippy::unused_unit)] - | ^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::unused-unit` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::unused_unit)]` error: unneeded unit expression - --> tests/ui/unused_unit.rs:62:26 + --> tests/ui/unused_unit.rs:61:26 | LL | fn return_unit() -> () { () } | ^^ help: remove the final `()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:22:28 + --> tests/ui/unused_unit.rs:21:28 | LL | pub fn get_unit (), G>(&self, f: F, _g: G) -> () | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:25:18 + --> tests/ui/unused_unit.rs:24:18 | LL | where G: Fn() -> () { | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:22:58 + --> tests/ui/unused_unit.rs:21:58 | LL | pub fn get_unit (), G>(&self, f: F, _g: G) -> () | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:27:26 + --> tests/ui/unused_unit.rs:26:26 | LL | let _y: &dyn Fn() -> () = &f; | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:35:18 + --> tests/ui/unused_unit.rs:34:18 | LL | fn into(self) -> () { | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:43:29 + --> tests/ui/unused_unit.rs:42:29 | LL | fn redundant (), G, H>(&self, _f: F, _g: G, _h: H) | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:46:19 + --> tests/ui/unused_unit.rs:45:19 | LL | G: FnMut() -> (), | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:48:16 + --> tests/ui/unused_unit.rs:47:16 | LL | H: Fn() -> (); | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:53:29 + --> tests/ui/unused_unit.rs:52:29 | LL | fn redundant (), G, H>(&self, _f: F, _g: G, _h: H) | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:56:19 + --> tests/ui/unused_unit.rs:55:19 | LL | G: FnMut() -> (), | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:58:16 + --> tests/ui/unused_unit.rs:57:16 | LL | H: Fn() -> () {} | ^^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:62:17 + --> tests/ui/unused_unit.rs:61:17 | LL | fn return_unit() -> () { () } | ^^^^^^ help: remove the `-> ()` error: unneeded `()` - --> tests/ui/unused_unit.rs:74:14 + --> tests/ui/unused_unit.rs:73:14 | LL | break(); | ^^ help: remove the `()` error: unneeded `()` - --> tests/ui/unused_unit.rs:77:11 + --> tests/ui/unused_unit.rs:76:11 | LL | return(); | ^^ help: remove the `()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:95:10 + --> tests/ui/unused_unit.rs:94:10 | LL | fn test()->(){} | ^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:99:11 + --> tests/ui/unused_unit.rs:98:11 | LL | fn test2() ->(){} | ^^^^^ help: remove the `-> ()` error: unneeded unit return type - --> tests/ui/unused_unit.rs:103:11 + --> tests/ui/unused_unit.rs:102:11 | LL | fn test3()-> (){} | ^^^^^ help: remove the `-> ()` diff --git a/src/tools/clippy/tests/ui/unused_unit.rs b/src/tools/clippy/tests/ui/unused_unit.rs index 31e980f2655c6..b70d7bf18ac84 100644 --- a/src/tools/clippy/tests/ui/unused_unit.rs +++ b/src/tools/clippy/tests/ui/unused_unit.rs @@ -12,9 +12,8 @@ #![feature(closure_lifetime_binder)] #![rustfmt::skip] -#![deny(clippy::unused_unit)] -#![allow(dead_code)] -#![allow(clippy::from_over_into)] +#![warn(clippy::unused_unit)] +#![expect(clippy::from_over_into)] struct Unitter; impl Unitter { @@ -142,7 +141,6 @@ mod issue14577 { } mod pr14962 { - #[allow(unused_parens)] type UnusedParensButNoUnit = Box; } diff --git a/src/tools/clippy/tests/ui/unwrap_expect_used.rs b/src/tools/clippy/tests/ui/unwrap_expect_used.rs index 207d4dd815be3..ef638bf0e9c9a 100644 --- a/src/tools/clippy/tests/ui/unwrap_expect_used.rs +++ b/src/tools/clippy/tests/ui/unwrap_expect_used.rs @@ -1,5 +1,5 @@ -#![warn(clippy::unwrap_used, clippy::expect_used)] -#![allow(clippy::unnecessary_literal_unwrap)] +#![warn(clippy::expect_used, clippy::unwrap_used)] +#![expect(clippy::unnecessary_literal_unwrap)] #![feature(never_type)] use std::convert::Infallible; diff --git a/src/tools/clippy/tests/ui/unwrap_in_result.rs b/src/tools/clippy/tests/ui/unwrap_in_result.rs index 70c28fe54f37d..bcdbbd2ae7fe3 100644 --- a/src/tools/clippy/tests/ui/unwrap_in_result.rs +++ b/src/tools/clippy/tests/ui/unwrap_in_result.rs @@ -1,5 +1,5 @@ #![warn(clippy::unwrap_in_result)] -#![allow(clippy::ok_expect)] +#![expect(clippy::ok_expect)] struct A; diff --git a/src/tools/clippy/tests/ui/unwrap_or.fixed b/src/tools/clippy/tests/ui/unwrap_or.fixed index e550484b5d9f0..f27103e48dd36 100644 --- a/src/tools/clippy/tests/ui/unwrap_or.fixed +++ b/src/tools/clippy/tests/ui/unwrap_or.fixed @@ -1,5 +1,5 @@ #![warn(clippy::or_fun_call)] -#![allow(clippy::unnecessary_literal_unwrap)] +#![expect(clippy::unnecessary_literal_unwrap)] fn main() { let s = Some(String::from("test string")).unwrap_or_else(|| "Fail".to_string()).len(); diff --git a/src/tools/clippy/tests/ui/unwrap_or.rs b/src/tools/clippy/tests/ui/unwrap_or.rs index cdd61ac898e6d..456ca5c143e1f 100644 --- a/src/tools/clippy/tests/ui/unwrap_or.rs +++ b/src/tools/clippy/tests/ui/unwrap_or.rs @@ -1,5 +1,5 @@ #![warn(clippy::or_fun_call)] -#![allow(clippy::unnecessary_literal_unwrap)] +#![expect(clippy::unnecessary_literal_unwrap)] fn main() { let s = Some(String::from("test string")).unwrap_or("Fail".to_string()).len(); diff --git a/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed b/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed index 5cf529fe01433..b6ef0d7f264be 100644 --- a/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed +++ b/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed @@ -1,6 +1,5 @@ #![warn(clippy::unwrap_or_default)] -#![allow(dead_code)] -#![allow(clippy::unnecessary_wraps, clippy::unnecessary_literal_unwrap)] +#![expect(clippy::unnecessary_literal_unwrap)] /// Checks implementation of the `UNWRAP_OR_DEFAULT` lint. fn unwrap_or_else_default() { @@ -135,7 +134,6 @@ fn method_call_with_deref() { let mut outer_map = cell.borrow_mut(); - #[allow(unused_assignments)] let mut option = None; option = Some(0); diff --git a/src/tools/clippy/tests/ui/unwrap_or_else_default.rs b/src/tools/clippy/tests/ui/unwrap_or_else_default.rs index e49ff13e1f2f9..b2149a5dd0913 100644 --- a/src/tools/clippy/tests/ui/unwrap_or_else_default.rs +++ b/src/tools/clippy/tests/ui/unwrap_or_else_default.rs @@ -1,6 +1,5 @@ #![warn(clippy::unwrap_or_default)] -#![allow(dead_code)] -#![allow(clippy::unnecessary_wraps, clippy::unnecessary_literal_unwrap)] +#![expect(clippy::unnecessary_literal_unwrap)] /// Checks implementation of the `UNWRAP_OR_DEFAULT` lint. fn unwrap_or_else_default() { @@ -135,7 +134,6 @@ fn method_call_with_deref() { let mut outer_map = cell.borrow_mut(); - #[allow(unused_assignments)] let mut option = None; option = Some(0); diff --git a/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr b/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr index 610f20fa62b18..1d61a5e89e458 100644 --- a/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr +++ b/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr @@ -1,5 +1,5 @@ error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:60:23 + --> tests/ui/unwrap_or_else_default.rs:59:23 | LL | with_real_default.unwrap_or_else(::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` @@ -8,85 +8,85 @@ LL | with_real_default.unwrap_or_else(::d = help: to override `-D warnings` add `#[allow(clippy::unwrap_or_default)]` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:64:24 + --> tests/ui/unwrap_or_else_default.rs:63:24 | LL | with_default_trait.unwrap_or_else(Default::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:68:23 + --> tests/ui/unwrap_or_else_default.rs:67:23 | LL | with_default_type.unwrap_or_else(u64::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:72:23 + --> tests/ui/unwrap_or_else_default.rs:71:23 | LL | with_default_type.unwrap_or_else(Vec::new); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:76:18 + --> tests/ui/unwrap_or_else_default.rs:75:18 | LL | empty_string.unwrap_or_else(|| "".to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:81:12 + --> tests/ui/unwrap_or_else_default.rs:80:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:85:12 + --> tests/ui/unwrap_or_else_default.rs:84:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:89:12 + --> tests/ui/unwrap_or_else_default.rs:88:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:93:12 + --> tests/ui/unwrap_or_else_default.rs:92:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:97:12 + --> tests/ui/unwrap_or_else_default.rs:96:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:101:12 + --> tests/ui/unwrap_or_else_default.rs:100:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:105:12 + --> tests/ui/unwrap_or_else_default.rs:104:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:109:12 + --> tests/ui/unwrap_or_else_default.rs:108:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/unwrap_or_else_default.rs:126:12 + --> tests/ui/unwrap_or_else_default.rs:125:12 | LL | option.unwrap_or_else(Vec::new).push(1); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `or_insert_with` to construct default value - --> tests/ui/unwrap_or_else_default.rs:144:32 + --> tests/ui/unwrap_or_else_default.rs:142:32 | LL | let _ = inner_map.entry(0).or_insert_with(Default::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `or_default()` diff --git a/src/tools/clippy/tests/ui/use_self.fixed b/src/tools/clippy/tests/ui/use_self.fixed index 37559f9a23673..817676346dd22 100644 --- a/src/tools/clippy/tests/ui/use_self.fixed +++ b/src/tools/clippy/tests/ui/use_self.fixed @@ -1,16 +1,7 @@ //@aux-build:proc_macro_derive.rs #![warn(clippy::use_self)] -#![allow(dead_code, unreachable_code)] -#![allow( - clippy::should_implement_trait, - clippy::upper_case_acronyms, - clippy::from_over_into, - clippy::self_named_constructors, - clippy::needless_lifetimes, - clippy::missing_transmute_annotations -)] -#![allow(incomplete_features)] +#![expect(incomplete_features, clippy::from_over_into, clippy::self_named_constructors)] #![feature(adt_const_params)] #![feature(unsized_const_params)] @@ -160,7 +151,6 @@ mod nesting { struct Foo; impl Foo { fn foo() { - #[allow(unused_imports)] use self::Foo; // Can't use Self here struct Bar { foo: Foo, // Foo != Self @@ -195,7 +185,6 @@ mod nesting { } impl Enum { fn method() { - #[allow(unused_imports)] use self::Enum::*; // Issue 3425 static STATIC: Enum = Enum::A; // Can't use Self as type } diff --git a/src/tools/clippy/tests/ui/use_self.rs b/src/tools/clippy/tests/ui/use_self.rs index 74abd2f61bf92..b2eb869b3f4ba 100644 --- a/src/tools/clippy/tests/ui/use_self.rs +++ b/src/tools/clippy/tests/ui/use_self.rs @@ -1,16 +1,7 @@ //@aux-build:proc_macro_derive.rs #![warn(clippy::use_self)] -#![allow(dead_code, unreachable_code)] -#![allow( - clippy::should_implement_trait, - clippy::upper_case_acronyms, - clippy::from_over_into, - clippy::self_named_constructors, - clippy::needless_lifetimes, - clippy::missing_transmute_annotations -)] -#![allow(incomplete_features)] +#![expect(incomplete_features, clippy::from_over_into, clippy::self_named_constructors)] #![feature(adt_const_params)] #![feature(unsized_const_params)] @@ -160,7 +151,6 @@ mod nesting { struct Foo; impl Foo { fn foo() { - #[allow(unused_imports)] use self::Foo; // Can't use Self here struct Bar { foo: Foo, // Foo != Self @@ -195,7 +185,6 @@ mod nesting { } impl Enum { fn method() { - #[allow(unused_imports)] use self::Enum::*; // Issue 3425 static STATIC: Enum = Enum::A; // Can't use Self as type } diff --git a/src/tools/clippy/tests/ui/use_self.stderr b/src/tools/clippy/tests/ui/use_self.stderr index 8ce341d22d4f5..eedd11fe56176 100644 --- a/src/tools/clippy/tests/ui/use_self.stderr +++ b/src/tools/clippy/tests/ui/use_self.stderr @@ -1,5 +1,5 @@ error: unnecessary structure name repetition - --> tests/ui/use_self.rs:26:21 + --> tests/ui/use_self.rs:17:21 | LL | fn new() -> Foo { | ^^^ help: use the applicable keyword: `Self` @@ -8,247 +8,247 @@ LL | fn new() -> Foo { = help: to override `-D warnings` add `#[allow(clippy::use_self)]` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:28:13 + --> tests/ui/use_self.rs:19:13 | LL | Foo {} | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:31:22 + --> tests/ui/use_self.rs:22:22 | LL | fn test() -> Foo { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:33:13 + --> tests/ui/use_self.rs:24:13 | LL | Foo::new() | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:39:25 + --> tests/ui/use_self.rs:30:25 | LL | fn default() -> Foo { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:41:13 + --> tests/ui/use_self.rs:32:13 | LL | Foo::new() | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:83:28 + --> tests/ui/use_self.rs:74:28 | LL | fn clone(&self) -> Foo<'a> { | ^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:117:24 + --> tests/ui/use_self.rs:108:24 | LL | fn bad(foos: &[Foo]) -> impl Iterator { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:117:55 + --> tests/ui/use_self.rs:108:55 | LL | fn bad(foos: &[Foo]) -> impl Iterator { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:134:13 + --> tests/ui/use_self.rs:125:13 | LL | TS(0) | ^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:170:29 + --> tests/ui/use_self.rs:160:29 | LL | fn bar() -> Bar { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:172:21 + --> tests/ui/use_self.rs:162:21 | LL | Bar { foo: Foo {} } | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:184:21 + --> tests/ui/use_self.rs:174:21 | LL | fn baz() -> Foo { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:186:13 + --> tests/ui/use_self.rs:176:13 | LL | Foo {} | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:204:21 + --> tests/ui/use_self.rs:193:21 | LL | let _ = Enum::B(42); | ^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:206:21 + --> tests/ui/use_self.rs:195:21 | LL | let _ = Enum::C { field: true }; | ^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:208:21 + --> tests/ui/use_self.rs:197:21 | LL | let _ = Enum::A; | ^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:251:13 + --> tests/ui/use_self.rs:240:13 | LL | nested::A::fun_1(); | ^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:253:13 + --> tests/ui/use_self.rs:242:13 | LL | nested::A::A; | ^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:256:13 + --> tests/ui/use_self.rs:245:13 | LL | nested::A {}; | ^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:276:13 + --> tests/ui/use_self.rs:265:13 | LL | TestStruct::from_something() | ^^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:291:25 + --> tests/ui/use_self.rs:280:25 | LL | async fn g() -> S { | ^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:293:13 + --> tests/ui/use_self.rs:282:13 | LL | S {} | ^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:298:16 + --> tests/ui/use_self.rs:287:16 | LL | &p[S::A..S::B] | ^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:298:22 + --> tests/ui/use_self.rs:287:22 | LL | &p[S::A..S::B] | ^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:323:29 + --> tests/ui/use_self.rs:312:29 | LL | fn foo(value: T) -> Foo { | ^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:325:13 + --> tests/ui/use_self.rs:314:13 | LL | Foo:: { value } | ^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:498:13 + --> tests/ui/use_self.rs:487:13 | LL | A::new::(submod::B {}) | ^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:574:17 + --> tests/ui/use_self.rs:563:17 | LL | Foo::Bar => unimplemented!(), | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:576:17 + --> tests/ui/use_self.rs:565:17 | LL | Foo::Baz => unimplemented!(), | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:583:20 + --> tests/ui/use_self.rs:572:20 | LL | if let Foo::Bar = self { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:608:17 + --> tests/ui/use_self.rs:597:17 | LL | Something::Num(n) => *n, | ^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:610:17 + --> tests/ui/use_self.rs:599:17 | LL | Something::TupleNums(n, _m) => *n, | ^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:612:17 + --> tests/ui/use_self.rs:601:17 | LL | Something::StructNums { one, two: _ } => *one, | ^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:619:17 + --> tests/ui/use_self.rs:608:17 | LL | crate::issue8845::Something::Num(n) => *n, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:621:17 + --> tests/ui/use_self.rs:610:17 | LL | crate::issue8845::Something::TupleNums(n, _m) => *n, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:623:17 + --> tests/ui/use_self.rs:612:17 | LL | crate::issue8845::Something::StructNums { one, two: _ } => *one, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:640:17 + --> tests/ui/use_self.rs:629:17 | LL | let Foo(x) = self; | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:646:17 + --> tests/ui/use_self.rs:635:17 | LL | let crate::issue8845::Foo(x) = self; | ^^^^^^^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:654:17 + --> tests/ui/use_self.rs:643:17 | LL | let Bar { x, .. } = self; | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:660:17 + --> tests/ui/use_self.rs:649:17 | LL | let crate::issue8845::Bar { x, .. } = self; | ^^^^^^^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self.rs:700:17 + --> tests/ui/use_self.rs:689:17 | LL | E::A => {}, | ^ help: use the applicable keyword: `Self` diff --git a/src/tools/clippy/tests/ui/use_self_structs.fixed b/src/tools/clippy/tests/ui/use_self_structs.fixed index bd7bc3e0c1f69..bb3c8722de9fa 100644 --- a/src/tools/clippy/tests/ui/use_self_structs.fixed +++ b/src/tools/clippy/tests/ui/use_self_structs.fixed @@ -1,5 +1,5 @@ #![warn(clippy::use_self)] -#![allow(clippy::type_complexity)] +#![expect(clippy::type_complexity)] fn main() {} diff --git a/src/tools/clippy/tests/ui/use_self_structs.rs b/src/tools/clippy/tests/ui/use_self_structs.rs index 624f158164ab0..3dbf1337882ac 100644 --- a/src/tools/clippy/tests/ui/use_self_structs.rs +++ b/src/tools/clippy/tests/ui/use_self_structs.rs @@ -1,5 +1,5 @@ #![warn(clippy::use_self)] -#![allow(clippy::type_complexity)] +#![expect(clippy::type_complexity)] fn main() {} diff --git a/src/tools/clippy/tests/ui/use_self_trait.fixed b/src/tools/clippy/tests/ui/use_self_trait.fixed index c5d800dc94e18..77c47d304750e 100644 --- a/src/tools/clippy/tests/ui/use_self_trait.fixed +++ b/src/tools/clippy/tests/ui/use_self_trait.fixed @@ -1,6 +1,4 @@ #![warn(clippy::use_self)] -#![allow(dead_code)] -#![allow(clippy::should_implement_trait, clippy::boxed_local)] use std::ops::Mul; diff --git a/src/tools/clippy/tests/ui/use_self_trait.rs b/src/tools/clippy/tests/ui/use_self_trait.rs index dcf5820afc26a..e8a1a772ec267 100644 --- a/src/tools/clippy/tests/ui/use_self_trait.rs +++ b/src/tools/clippy/tests/ui/use_self_trait.rs @@ -1,6 +1,4 @@ #![warn(clippy::use_self)] -#![allow(dead_code)] -#![allow(clippy::should_implement_trait, clippy::boxed_local)] use std::ops::Mul; diff --git a/src/tools/clippy/tests/ui/use_self_trait.stderr b/src/tools/clippy/tests/ui/use_self_trait.stderr index 1b664b3b7a28f..f7eb8f21306b8 100644 --- a/src/tools/clippy/tests/ui/use_self_trait.stderr +++ b/src/tools/clippy/tests/ui/use_self_trait.stderr @@ -1,5 +1,5 @@ error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:19:18 + --> tests/ui/use_self_trait.rs:17:18 | LL | fn refs(p1: &Bad) -> &Bad { | ^^^ help: use the applicable keyword: `Self` @@ -8,91 +8,91 @@ LL | fn refs(p1: &Bad) -> &Bad { = help: to override `-D warnings` add `#[allow(clippy::use_self)]` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:19:27 + --> tests/ui/use_self_trait.rs:17:27 | LL | fn refs(p1: &Bad) -> &Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:25:33 + --> tests/ui/use_self_trait.rs:23:33 | LL | fn ref_refs<'a>(p1: &'a &'a Bad) -> &'a &'a Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:25:49 + --> tests/ui/use_self_trait.rs:23:49 | LL | fn ref_refs<'a>(p1: &'a &'a Bad) -> &'a &'a Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:31:26 + --> tests/ui/use_self_trait.rs:29:26 | LL | fn mut_refs(p1: &mut Bad) -> &mut Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:31:39 + --> tests/ui/use_self_trait.rs:29:39 | LL | fn mut_refs(p1: &mut Bad) -> &mut Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:37:24 + --> tests/ui/use_self_trait.rs:35:24 | LL | fn nested(_p1: Box, _p2: (&u8, &Bad)) {} | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:37:42 + --> tests/ui/use_self_trait.rs:35:42 | LL | fn nested(_p1: Box, _p2: (&u8, &Bad)) {} | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:41:16 + --> tests/ui/use_self_trait.rs:39:16 | LL | fn vals(_: Bad) -> Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:41:24 + --> tests/ui/use_self_trait.rs:39:24 | LL | fn vals(_: Bad) -> Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:44:9 + --> tests/ui/use_self_trait.rs:42:9 | LL | Bad | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:50:19 + --> tests/ui/use_self_trait.rs:48:19 | LL | type Output = Bad; | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:53:23 + --> tests/ui/use_self_trait.rs:51:23 | LL | fn mul(self, rhs: Bad) -> Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:53:31 + --> tests/ui/use_self_trait.rs:51:31 | LL | fn mul(self, rhs: Bad) -> Bad { | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:62:9 + --> tests/ui/use_self_trait.rs:60:9 | LL | Bad | ^^^ help: use the applicable keyword: `Self` error: unnecessary structure name repetition - --> tests/ui/use_self_trait.rs:160:13 + --> tests/ui/use_self_trait.rs:158:13 | LL | std::fmt::Error // Should lint | ^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` diff --git a/src/tools/clippy/tests/ui/used_underscore_binding.rs b/src/tools/clippy/tests/ui/used_underscore_binding.rs index 3b063fd16be1e..b2a8fdcc0ce77 100644 --- a/src/tools/clippy/tests/ui/used_underscore_binding.rs +++ b/src/tools/clippy/tests/ui/used_underscore_binding.rs @@ -1,7 +1,7 @@ //@aux-build:proc_macro_derive.rs #![feature(rustc_private)] #![warn(clippy::used_underscore_binding)] -#![allow(clippy::disallowed_names, clippy::eq_op, clippy::uninlined_format_args)] +#![expect(clippy::disallowed_names, clippy::eq_op, clippy::uninlined_format_args)] #[macro_use] extern crate proc_macro_derive; diff --git a/src/tools/clippy/tests/ui/used_underscore_items.rs b/src/tools/clippy/tests/ui/used_underscore_items.rs index aecdd32693c14..08660eefc3226 100644 --- a/src/tools/clippy/tests/ui/used_underscore_items.rs +++ b/src/tools/clippy/tests/ui/used_underscore_items.rs @@ -1,5 +1,4 @@ //@aux-build:external_item.rs -#![allow(unused)] #![warn(clippy::used_underscore_items)] extern crate external_item; diff --git a/src/tools/clippy/tests/ui/used_underscore_items.stderr b/src/tools/clippy/tests/ui/used_underscore_items.stderr index d6e23f1e726af..b2f9e2db0dfc4 100644 --- a/src/tools/clippy/tests/ui/used_underscore_items.stderr +++ b/src/tools/clippy/tests/ui/used_underscore_items.stderr @@ -1,11 +1,11 @@ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:43:5 + --> tests/ui/used_underscore_items.rs:42:5 | LL | _foo1(); | ^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:22:1 + --> tests/ui/used_underscore_items.rs:21:1 | LL | fn _foo1() {} | ^^^^^^^^^^ @@ -13,97 +13,97 @@ LL | fn _foo1() {} = help: to override `-D warnings` add `#[allow(clippy::used_underscore_items)]` error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:45:13 + --> tests/ui/used_underscore_items.rs:44:13 | LL | let _ = _foo2(); | ^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:24:1 + --> tests/ui/used_underscore_items.rs:23:1 | LL | fn _foo2() -> i32 { | ^^^^^^^^^^^^^^^^^ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:47:5 + --> tests/ui/used_underscore_items.rs:46:5 | LL | a::b::c::_foo3(); | ^^^^^^^^^^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:31:13 + --> tests/ui/used_underscore_items.rs:30:13 | LL | pub fn _foo3() {} | ^^^^^^^^^^^^^^ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:49:14 + --> tests/ui/used_underscore_items.rs:48:14 | LL | let _ = &_FooStruct {}; | ^^^^^^^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:16:1 + --> tests/ui/used_underscore_items.rs:15:1 | LL | struct _FooStruct {} | ^^^^^^^^^^^^^^^^^ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:51:13 + --> tests/ui/used_underscore_items.rs:50:13 | LL | let _ = _FooStruct {}; | ^^^^^^^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:16:1 + --> tests/ui/used_underscore_items.rs:15:1 | LL | struct _FooStruct {} | ^^^^^^^^^^^^^^^^^ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:54:22 + --> tests/ui/used_underscore_items.rs:53:22 | LL | let foo_struct = _FooStruct {}; | ^^^^^^^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:16:1 + --> tests/ui/used_underscore_items.rs:15:1 | LL | struct _FooStruct {} | ^^^^^^^^^^^^^^^^^ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:56:5 + --> tests/ui/used_underscore_items.rs:55:5 | LL | foo_struct._method_call(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:19:5 + --> tests/ui/used_underscore_items.rs:18:5 | LL | fn _method_call(self) {} | ^^^^^^^^^^^^^^^^^^^^^ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:59:23 + --> tests/ui/used_underscore_items.rs:58:23 | LL | let foo_struct2 = a::b::c::_FooStruct2 {}; | ^^^^^^^^^^^^^^^^^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:33:13 + --> tests/ui/used_underscore_items.rs:32:13 | LL | pub struct _FooStruct2 {} | ^^^^^^^^^^^^^^^^^^^^^^ error: used underscore-prefixed item - --> tests/ui/used_underscore_items.rs:61:5 + --> tests/ui/used_underscore_items.rs:60:5 | LL | foo_struct2._method_call(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: item is defined here - --> tests/ui/used_underscore_items.rs:36:17 + --> tests/ui/used_underscore_items.rs:35:17 | LL | pub fn _method_call(self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/useful_asref.rs b/src/tools/clippy/tests/ui/useful_asref.rs index a37c2785bde2a..12e2a5837bf8d 100644 --- a/src/tools/clippy/tests/ui/useful_asref.rs +++ b/src/tools/clippy/tests/ui/useful_asref.rs @@ -1,7 +1,7 @@ //@ check-pass -#![deny(clippy::useless_asref)] -#![allow(clippy::needless_lifetimes)] +#![warn(clippy::useless_asref)] +#![expect(clippy::needless_lifetimes)] trait Trait { fn as_ptr(&self); diff --git a/src/tools/clippy/tests/ui/useless_asref.fixed b/src/tools/clippy/tests/ui/useless_asref.fixed index 5131ae113d184..587f3cf6427bb 100644 --- a/src/tools/clippy/tests/ui/useless_asref.fixed +++ b/src/tools/clippy/tests/ui/useless_asref.fixed @@ -1,11 +1,5 @@ -#![deny(clippy::useless_asref)] -#![allow( - clippy::explicit_auto_deref, - clippy::uninlined_format_args, - clippy::map_clone, - clippy::needless_pass_by_ref_mut, - clippy::redundant_closure -)] +#![warn(clippy::useless_asref)] +#![expect(clippy::redundant_closure)] use std::fmt::Debug; use std::ops::Deref; @@ -83,7 +77,7 @@ fn not_ok() { //~^ useless_asref foo_rslice(mrrrrrslice); } - #[allow(unused_parens, clippy::double_parens, clippy::needless_borrow)] + #[allow(clippy::double_parens, clippy::needless_borrow)] foo_rrrrmr((&&&&MoreRef)); //~^ useless_asref diff --git a/src/tools/clippy/tests/ui/useless_asref.rs b/src/tools/clippy/tests/ui/useless_asref.rs index e1c2a1d81d04f..e203942bbaf55 100644 --- a/src/tools/clippy/tests/ui/useless_asref.rs +++ b/src/tools/clippy/tests/ui/useless_asref.rs @@ -1,11 +1,5 @@ -#![deny(clippy::useless_asref)] -#![allow( - clippy::explicit_auto_deref, - clippy::uninlined_format_args, - clippy::map_clone, - clippy::needless_pass_by_ref_mut, - clippy::redundant_closure -)] +#![warn(clippy::useless_asref)] +#![expect(clippy::redundant_closure)] use std::fmt::Debug; use std::ops::Deref; @@ -83,7 +77,7 @@ fn not_ok() { //~^ useless_asref foo_rslice(mrrrrrslice); } - #[allow(unused_parens, clippy::double_parens, clippy::needless_borrow)] + #[allow(clippy::double_parens, clippy::needless_borrow)] foo_rrrrmr((&&&&MoreRef).as_ref()); //~^ useless_asref diff --git a/src/tools/clippy/tests/ui/useless_asref.stderr b/src/tools/clippy/tests/ui/useless_asref.stderr index 861472b4419ed..cc7bf0e8ae36f 100644 --- a/src/tools/clippy/tests/ui/useless_asref.stderr +++ b/src/tools/clippy/tests/ui/useless_asref.stderr @@ -1,143 +1,140 @@ error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:51:18 + --> tests/ui/useless_asref.rs:45:18 | LL | foo_rstr(rstr.as_ref()); | ^^^^^^^^^^^^^ help: try: `rstr` | -note: the lint level is defined here - --> tests/ui/useless_asref.rs:1:9 - | -LL | #![deny(clippy::useless_asref)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::useless-asref` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::useless_asref)]` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:54:20 + --> tests/ui/useless_asref.rs:48:20 | LL | foo_rslice(rslice.as_ref()); | ^^^^^^^^^^^^^^^ help: try: `rslice` error: this call to `as_mut` does nothing - --> tests/ui/useless_asref.rs:59:21 + --> tests/ui/useless_asref.rs:53:21 | LL | foo_mrslice(mrslice.as_mut()); | ^^^^^^^^^^^^^^^^ help: try: `mrslice` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:62:20 + --> tests/ui/useless_asref.rs:56:20 | LL | foo_rslice(mrslice.as_ref()); | ^^^^^^^^^^^^^^^^ help: try: `mrslice` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:70:20 + --> tests/ui/useless_asref.rs:64:20 | LL | foo_rslice(rrrrrslice.as_ref()); | ^^^^^^^^^^^^^^^^^^^ help: try: `rrrrrslice` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:73:18 + --> tests/ui/useless_asref.rs:67:18 | LL | foo_rstr(rrrrrstr.as_ref()); | ^^^^^^^^^^^^^^^^^ help: try: `rrrrrstr` error: this call to `as_mut` does nothing - --> tests/ui/useless_asref.rs:79:21 + --> tests/ui/useless_asref.rs:73:21 | LL | foo_mrslice(mrrrrrslice.as_mut()); | ^^^^^^^^^^^^^^^^^^^^ help: try: `mrrrrrslice` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:82:20 + --> tests/ui/useless_asref.rs:76:20 | LL | foo_rslice(mrrrrrslice.as_ref()); | ^^^^^^^^^^^^^^^^^^^^ help: try: `mrrrrrslice` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:87:16 + --> tests/ui/useless_asref.rs:81:16 | LL | foo_rrrrmr((&&&&MoreRef).as_ref()); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `(&&&&MoreRef)` error: this call to `as_mut` does nothing - --> tests/ui/useless_asref.rs:138:13 + --> tests/ui/useless_asref.rs:132:13 | LL | foo_mrt(mrt.as_mut()); | ^^^^^^^^^^^^ help: try: `mrt` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:141:12 + --> tests/ui/useless_asref.rs:135:12 | LL | foo_rt(mrt.as_ref()); | ^^^^^^^^^^^^ help: try: `mrt` error: this call to `as_ref.map(...)` does nothing - --> tests/ui/useless_asref.rs:153:13 + --> tests/ui/useless_asref.rs:147:13 | LL | let z = x.as_ref().map(String::clone); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x.clone()` error: this call to `as_ref.map(...)` does nothing - --> tests/ui/useless_asref.rs:156:13 + --> tests/ui/useless_asref.rs:150:13 | LL | let z = x.as_ref().map(|z| z.clone()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x.clone()` error: this call to `as_ref.map(...)` does nothing - --> tests/ui/useless_asref.rs:159:13 + --> tests/ui/useless_asref.rs:153:13 | LL | let z = x.as_ref().map(|z| String::clone(z)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x.clone()` error: this call to `as_ref.map(...)` does nothing - --> tests/ui/useless_asref.rs:183:9 + --> tests/ui/useless_asref.rs:177:9 | LL | x.field.as_ref().map(|v| v.clone()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x.field.clone()` error: this call to `as_ref.map(...)` does nothing - --> tests/ui/useless_asref.rs:186:9 + --> tests/ui/useless_asref.rs:180:9 | LL | x.field.as_ref().map(Clone::clone); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x.field.clone()` error: this call to `as_ref.map(...)` does nothing - --> tests/ui/useless_asref.rs:189:9 + --> tests/ui/useless_asref.rs:183:9 | LL | x.field.as_ref().map(|v| Clone::clone(v)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x.field.clone()` error: this call to `as_ref.map(...)` does nothing - --> tests/ui/useless_asref.rs:194:9 + --> tests/ui/useless_asref.rs:188:9 | LL | Some(1).as_ref().map(|&x| x.clone()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Some(1).clone()` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:264:66 + --> tests/ui/useless_asref.rs:258:66 | LL | let v: Vec> = exts.iter().map(|s| Cow::Borrowed(s.as_ref())).collect(); | ^^^^^^^^^^ help: try: `*s` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:277:66 + --> tests/ui/useless_asref.rs:271:66 | LL | let v: Vec> = exts.iter().map(|s| Cow::Borrowed(s.id().as_ref())).collect(); | ^^^^^^^^^^^^^^^ help: try: `s.id()` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:282:32 + --> tests/ui/useless_asref.rs:276:32 | LL | .map(|s| Cow::Borrowed(std::convert::identity(s).as_ref())) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `*std::convert::identity(s)` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:288:72 + --> tests/ui/useless_asref.rs:282:72 | LL | let v: Vec> = exts_field.iter().map(|w| Cow::Borrowed(w.0.as_ref())).collect(); | ^^^^^^^^^^^^ help: try: `w.0` error: this call to `as_ref` does nothing - --> tests/ui/useless_asref.rs:292:74 + --> tests/ui/useless_asref.rs:286:74 | LL | let v: Vec> = exts_index.iter().map(|arr| Cow::Borrowed(arr[0].as_ref())).collect(); | ^^^^^^^^^^^^^^^ help: try: `arr[0]` diff --git a/src/tools/clippy/tests/ui/useless_attribute.fixed b/src/tools/clippy/tests/ui/useless_attribute.fixed index ff40f51c02054..7ca97f517f95d 100644 --- a/src/tools/clippy/tests/ui/useless_attribute.fixed +++ b/src/tools/clippy/tests/ui/useless_attribute.fixed @@ -1,8 +1,7 @@ //@aux-build:proc_macro_derive.rs - -#![allow(unused, clippy::duplicated_attributes)] #![warn(clippy::useless_attribute)] -#![warn(unreachable_pub)] +#![deny(unreachable_pub)] +#![expect(clippy::duplicated_attributes)] #![feature(rustc_private)] #![allow(dead_code)] diff --git a/src/tools/clippy/tests/ui/useless_attribute.rs b/src/tools/clippy/tests/ui/useless_attribute.rs index 426c720b4429e..effc1691edacb 100644 --- a/src/tools/clippy/tests/ui/useless_attribute.rs +++ b/src/tools/clippy/tests/ui/useless_attribute.rs @@ -1,8 +1,7 @@ //@aux-build:proc_macro_derive.rs - -#![allow(unused, clippy::duplicated_attributes)] #![warn(clippy::useless_attribute)] -#![warn(unreachable_pub)] +#![deny(unreachable_pub)] +#![expect(clippy::duplicated_attributes)] #![feature(rustc_private)] #[allow(dead_code)] diff --git a/src/tools/clippy/tests/ui/useless_attribute.stderr b/src/tools/clippy/tests/ui/useless_attribute.stderr index 91383adf994bf..9efc7ee0bbc62 100644 --- a/src/tools/clippy/tests/ui/useless_attribute.stderr +++ b/src/tools/clippy/tests/ui/useless_attribute.stderr @@ -1,5 +1,5 @@ error: useless lint attribute - --> tests/ui/useless_attribute.rs:8:1 + --> tests/ui/useless_attribute.rs:7:1 | LL | #[allow(dead_code)] | ^^^^^^^^^^^^^^^^^^^ help: if you just forgot a `!`, use: `#![allow(dead_code)]` @@ -8,13 +8,13 @@ LL | #[allow(dead_code)] = help: to override `-D warnings` add `#[allow(clippy::useless_attribute)]` error: useless lint attribute - --> tests/ui/useless_attribute.rs:10:1 + --> tests/ui/useless_attribute.rs:9:1 | LL | #[cfg_attr(clippy, allow(dead_code))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: if you just forgot a `!`, use: `#![cfg_attr(clippy, allow(dead_code)` error: useless lint attribute - --> tests/ui/useless_attribute.rs:22:5 + --> tests/ui/useless_attribute.rs:21:5 | LL | #[allow(clippy::almost_swapped)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: if you just forgot a `!`, use: `#![allow(clippy::almost_swapped)]` diff --git a/src/tools/clippy/tests/ui/useless_borrows_in_formatting.fixed b/src/tools/clippy/tests/ui/useless_borrows_in_formatting.fixed index f1a4635ee7268..675303d978198 100644 --- a/src/tools/clippy/tests/ui/useless_borrows_in_formatting.fixed +++ b/src/tools/clippy/tests/ui/useless_borrows_in_formatting.fixed @@ -2,7 +2,6 @@ // TESTNAME=useless_borrows_in_formatting cargo uitest // TESTNAME=useless_borrows_in_formatting cargo uibless #![warn(clippy::useless_borrows_in_formatting)] -#![allow(unused, clippy::useless_format)] fn main() { let mut s: &str = "hello"; diff --git a/src/tools/clippy/tests/ui/useless_borrows_in_formatting.rs b/src/tools/clippy/tests/ui/useless_borrows_in_formatting.rs index 12ad80cc8dd52..dc67d38fa6d5d 100644 --- a/src/tools/clippy/tests/ui/useless_borrows_in_formatting.rs +++ b/src/tools/clippy/tests/ui/useless_borrows_in_formatting.rs @@ -2,7 +2,6 @@ // TESTNAME=useless_borrows_in_formatting cargo uitest // TESTNAME=useless_borrows_in_formatting cargo uibless #![warn(clippy::useless_borrows_in_formatting)] -#![allow(unused, clippy::useless_format)] fn main() { let mut s: &str = "hello"; diff --git a/src/tools/clippy/tests/ui/useless_borrows_in_formatting.stderr b/src/tools/clippy/tests/ui/useless_borrows_in_formatting.stderr index 683d9dfdf946e..13c014df0cc7c 100644 --- a/src/tools/clippy/tests/ui/useless_borrows_in_formatting.stderr +++ b/src/tools/clippy/tests/ui/useless_borrows_in_formatting.stderr @@ -1,5 +1,5 @@ error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:9:20 + --> tests/ui/useless_borrows_in_formatting.rs:8:20 | LL | println!("{}", &s); | ^^ help: remove the redundant `&`: `s` @@ -8,103 +8,103 @@ LL | println!("{}", &s); = help: to override `-D warnings` add `#[allow(clippy::useless_borrows_in_formatting)]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:10:22 + --> tests/ui/useless_borrows_in_formatting.rs:9:22 | LL | println!("{:?}", &s); | ^^ help: remove the redundant `&`: `s` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:11:20 + --> tests/ui/useless_borrows_in_formatting.rs:10:20 | LL | println!("{}", &&s); | ^^^ help: remove the redundant `&`: `s` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:12:20 + --> tests/ui/useless_borrows_in_formatting.rs:11:20 | LL | println!("{}", &&mut s); | ^^^^^^^ help: remove the redundant `&`/`&mut`: `s` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:13:20 + --> tests/ui/useless_borrows_in_formatting.rs:12:20 | LL | println!("{}", &mut &s); | ^^^^^^^ help: remove the redundant `&`/`&mut`: `s` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:14:20 + --> tests/ui/useless_borrows_in_formatting.rs:13:20 | LL | println!("{}", &mut s); | ^^^^^^ help: remove the redundant `&mut`: `s` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:17:20 + --> tests/ui/useless_borrows_in_formatting.rs:16:20 | LL | println!("{}", &string); | ^^^^^^^ help: remove the redundant `&`: `string` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:18:22 + --> tests/ui/useless_borrows_in_formatting.rs:17:22 | LL | println!("{:?}", &string); | ^^^^^^^ help: remove the redundant `&`: `string` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:19:20 + --> tests/ui/useless_borrows_in_formatting.rs:18:20 | LL | println!("{}", &&string); | ^^^^^^^^ help: remove the redundant `&`: `string` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:20:20 + --> tests/ui/useless_borrows_in_formatting.rs:19:20 | LL | println!("{}", &&string[..2]); | ^^^^^^^^^^^^^ help: remove the redundant `&`: `&string[..2]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:21:22 + --> tests/ui/useless_borrows_in_formatting.rs:20:22 | LL | println!("{:?}", &&string[..2]); | ^^^^^^^^^^^^^ help: remove the redundant `&`: `&string[..2]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:27:20 + --> tests/ui/useless_borrows_in_formatting.rs:26:20 | LL | println!("{}", &n); | ^^ help: remove the redundant `&`: `n` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:28:22 + --> tests/ui/useless_borrows_in_formatting.rs:27:22 | LL | println!("{:?}", &n); | ^^ help: remove the redundant `&`: `n` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:29:20 + --> tests/ui/useless_borrows_in_formatting.rs:28:20 | LL | println!("{}", &&n); | ^^^ help: remove the redundant `&`: `n` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:33:20 + --> tests/ui/useless_borrows_in_formatting.rs:32:20 | LL | println!("{}", &slice[0]); | ^^^^^^^^^ help: remove the redundant `&`: `slice[0]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:34:22 + --> tests/ui/useless_borrows_in_formatting.rs:33:22 | LL | println!("{:?}", &slice[0]); | ^^^^^^^^^ help: remove the redundant `&`: `slice[0]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:35:20 + --> tests/ui/useless_borrows_in_formatting.rs:34:20 | LL | println!("{}", &&slice[0]); | ^^^^^^^^^^ help: remove the redundant `&`: `slice[0]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:40:9 + --> tests/ui/useless_borrows_in_formatting.rs:39:9 | LL | / &[ LL | | @@ -125,157 +125,157 @@ LL + ] | error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:48:22 + --> tests/ui/useless_borrows_in_formatting.rs:47:22 | LL | println!("{:?}", &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove the redundant `&`: `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:52:26 + --> tests/ui/useless_borrows_in_formatting.rs:51:26 | LL | println!("{:016x?}", &[a[0], a[1], a[0], a[1]]); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove the redundant `&`: `[a[0], a[1], a[0], a[1]]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:56:22 + --> tests/ui/useless_borrows_in_formatting.rs:55:22 | LL | println!("{:?}", &&slice[0..1]); | ^^^^^^^^^^^^^ help: remove the redundant `&`: `&slice[0..1]` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:65:20 + --> tests/ui/useless_borrows_in_formatting.rs:64:20 | LL | println!("{}", &w.0); | ^^^^ help: remove the redundant `&`: `w.0` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:66:22 + --> tests/ui/useless_borrows_in_formatting.rs:65:22 | LL | println!("{:?}", &w.0); | ^^^^ help: remove the redundant `&`: `w.0` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:67:20 + --> tests/ui/useless_borrows_in_formatting.rs:66:20 | LL | println!("{}", &&w.0); | ^^^^^ help: remove the redundant `&`: `w.0` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:72:20 + --> tests/ui/useless_borrows_in_formatting.rs:71:20 | LL | println!("{}", &w.0); | ^^^^ help: remove the redundant `&`: `w.0` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:73:22 + --> tests/ui/useless_borrows_in_formatting.rs:72:22 | LL | println!("{:?}", &w.0); | ^^^^ help: remove the redundant `&`: `w.0` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:74:20 + --> tests/ui/useless_borrows_in_formatting.rs:73:20 | LL | println!("{}", &&w.0); | ^^^^^ help: remove the redundant `&`: `w.0` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:77:20 + --> tests/ui/useless_borrows_in_formatting.rs:76:20 | LL | println!("{}", &*a); | ^^^ help: remove the redundant `&`: `*a` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:78:22 + --> tests/ui/useless_borrows_in_formatting.rs:77:22 | LL | println!("{:?}", &*a); | ^^^ help: remove the redundant `&`: `*a` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:82:20 + --> tests/ui/useless_borrows_in_formatting.rs:81:20 | LL | println!("{}", &(n)); | ^^^^ help: remove the redundant `&`: `(n)` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:83:22 + --> tests/ui/useless_borrows_in_formatting.rs:82:22 | LL | println!("{:?}", &(n + 1)); | ^^^^^^^^ help: remove the redundant `&`: `(n + 1)` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:84:20 + --> tests/ui/useless_borrows_in_formatting.rs:83:20 | LL | println!("{}", &(String::from("paren"))); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: remove the redundant `&`: `(String::from("paren"))` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:87:20 + --> tests/ui/useless_borrows_in_formatting.rs:86:20 | LL | println!("{}", &{ n }); | ^^^^^^ help: remove the redundant `&`: `{ n }` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:88:22 + --> tests/ui/useless_borrows_in_formatting.rs:87:22 | LL | println!("{:?}", &{ n + 1 }); | ^^^^^^^^^^ help: remove the redundant `&`: `{ n + 1 }` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:89:20 + --> tests/ui/useless_borrows_in_formatting.rs:88:20 | LL | println!("{}", &{ String::from("block") }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove the redundant `&`: `{ String::from("block") }` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:94:27 + --> tests/ui/useless_borrows_in_formatting.rs:93:27 | LL | println!("{0:1$.2$}", &v1, &v2, &v3); | ^^^ help: remove the redundant `&`: `v1` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:94:32 + --> tests/ui/useless_borrows_in_formatting.rs:93:32 | LL | println!("{0:1$.2$}", &v1, &v2, &v3); | ^^^ help: remove the redundant `&`: `v2` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:94:37 + --> tests/ui/useless_borrows_in_formatting.rs:93:37 | LL | println!("{0:1$.2$}", &v1, &v2, &v3); | ^^^ help: remove the redundant `&`: `v3` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:98:28 + --> tests/ui/useless_borrows_in_formatting.rs:97:28 | LL | println!("{0:1$.2$?}", &v1, &v2, &v3); | ^^^ help: remove the redundant `&`: `v1` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:98:33 + --> tests/ui/useless_borrows_in_formatting.rs:97:33 | LL | println!("{0:1$.2$?}", &v1, &v2, &v3); | ^^^ help: remove the redundant `&`: `v2` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:98:38 + --> tests/ui/useless_borrows_in_formatting.rs:97:38 | LL | println!("{0:1$.2$?}", &v1, &v2, &v3); | ^^^ help: remove the redundant `&`: `v3` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:102:27 + --> tests/ui/useless_borrows_in_formatting.rs:101:27 | LL | println!("{0:1$.2$}", &v1, v2, v3); | ^^^ help: remove the redundant `&`: `v1` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:103:31 + --> tests/ui/useless_borrows_in_formatting.rs:102:31 | LL | println!("{0:1$.2$}", v1, &v2, v3); | ^^^ help: remove the redundant `&`: `v2` error: redundant reference in `println!` argument - --> tests/ui/useless_borrows_in_formatting.rs:104:35 + --> tests/ui/useless_borrows_in_formatting.rs:103:35 | LL | println!("{0:1$.2$}", v1, v2, &v3); | ^^^ help: remove the redundant `&`: `v3` diff --git a/src/tools/clippy/tests/ui/useless_conversion.fixed b/src/tools/clippy/tests/ui/useless_conversion.fixed index d74ea54354fdd..a0759f9b0efeb 100644 --- a/src/tools/clippy/tests/ui/useless_conversion.fixed +++ b/src/tools/clippy/tests/ui/useless_conversion.fixed @@ -1,8 +1,7 @@ -#![deny(clippy::useless_conversion)] -#![allow(clippy::into_iter_on_ref)] -#![allow(clippy::needless_ifs, clippy::unnecessary_wraps, unused)] +#![warn(clippy::useless_conversion)] // FIXME(static_mut_refs): use raw pointers instead of references -#![allow(static_mut_refs)] +#![expect(static_mut_refs)] +#![allow(clippy::into_iter_on_ref)] use std::ops::ControlFlow; @@ -173,7 +172,6 @@ fn main() { issue11300::bar(); } -#[allow(dead_code)] fn issue11065_fp() { use std::option::IntoIter; fn takes_into_iter(_: impl IntoIterator) {} @@ -187,7 +185,6 @@ fn issue11065_fp() { x!(Some(5).into_iter()); } -#[allow(dead_code)] fn explicit_into_iter_fn_arg() { fn a(_: T) {} fn b>(_: T) {} diff --git a/src/tools/clippy/tests/ui/useless_conversion.rs b/src/tools/clippy/tests/ui/useless_conversion.rs index 5d7d180635771..b070dfca32414 100644 --- a/src/tools/clippy/tests/ui/useless_conversion.rs +++ b/src/tools/clippy/tests/ui/useless_conversion.rs @@ -1,8 +1,7 @@ -#![deny(clippy::useless_conversion)] -#![allow(clippy::into_iter_on_ref)] -#![allow(clippy::needless_ifs, clippy::unnecessary_wraps, unused)] +#![warn(clippy::useless_conversion)] // FIXME(static_mut_refs): use raw pointers instead of references -#![allow(static_mut_refs)] +#![expect(static_mut_refs)] +#![allow(clippy::into_iter_on_ref)] use std::ops::ControlFlow; @@ -173,7 +172,6 @@ fn main() { issue11300::bar(); } -#[allow(dead_code)] fn issue11065_fp() { use std::option::IntoIter; fn takes_into_iter(_: impl IntoIterator) {} @@ -187,7 +185,6 @@ fn issue11065_fp() { x!(Some(5).into_iter()); } -#[allow(dead_code)] fn explicit_into_iter_fn_arg() { fn a(_: T) {} fn b>(_: T) {} diff --git a/src/tools/clippy/tests/ui/useless_conversion.stderr b/src/tools/clippy/tests/ui/useless_conversion.stderr index 7042e18a2cad8..e8174427de825 100644 --- a/src/tools/clippy/tests/ui/useless_conversion.stderr +++ b/src/tools/clippy/tests/ui/useless_conversion.stderr @@ -1,65 +1,62 @@ error: useless conversion to the same type: `T` - --> tests/ui/useless_conversion.rs:10:13 + --> tests/ui/useless_conversion.rs:9:13 | LL | let _ = T::from(val); | ^^^^^^^^^^^^ help: consider removing `T::from()`: `val` | -note: the lint level is defined here - --> tests/ui/useless_conversion.rs:1:9 - | -LL | #![deny(clippy::useless_conversion)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::useless-conversion` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::useless_conversion)]` error: useless conversion to the same type: `T` - --> tests/ui/useless_conversion.rs:12:5 + --> tests/ui/useless_conversion.rs:11:5 | LL | val.into() | ^^^^^^^^^^ help: consider removing `.into()`: `val` error: useless conversion to the same type: `i32` - --> tests/ui/useless_conversion.rs:25:22 + --> tests/ui/useless_conversion.rs:24:22 | LL | let _: i32 = 0i32.into(); | ^^^^^^^^^^^ help: consider removing `.into()`: `0i32` error: useless conversion to the same type: `std::str::Lines<'_>` - --> tests/ui/useless_conversion.rs:56:22 + --> tests/ui/useless_conversion.rs:55:22 | LL | if Some("ok") == lines.into_iter().next() {} | ^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `lines` error: useless conversion to the same type: `std::str::Lines<'_>` - --> tests/ui/useless_conversion.rs:62:21 + --> tests/ui/useless_conversion.rs:61:21 | LL | let mut lines = text.lines().into_iter(); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `text.lines()` error: useless conversion to the same type: `std::str::Lines<'_>` - --> tests/ui/useless_conversion.rs:69:22 + --> tests/ui/useless_conversion.rs:68:22 | LL | if Some("ok") == text.lines().into_iter().next() {} | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `text.lines()` error: useless conversion to the same type: `std::iter::Empty` - --> tests/ui/useless_conversion.rs:76:13 + --> tests/ui/useless_conversion.rs:75:13 | LL | let _ = NUMBERS.into_iter().next(); | ^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `NUMBERS` error: useless conversion to the same type: `std::iter::Empty` - --> tests/ui/useless_conversion.rs:82:17 + --> tests/ui/useless_conversion.rs:81:17 | LL | let mut n = NUMBERS.into_iter(); | ^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `NUMBERS` error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:126:17 + --> tests/ui/useless_conversion.rs:125:17 | LL | consume(items.into_iter()); | ^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:122:28 + --> tests/ui/useless_conversion.rs:121:28 | LL | fn consume(_: impl IntoIterator) {} | ^^^^^^^^^^^^ @@ -70,79 +67,79 @@ LL + consume(*items); | error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion.rs:139:21 + --> tests/ui/useless_conversion.rs:138:21 | LL | let _: String = "foo".to_string().into(); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into()`: `"foo".to_string()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion.rs:141:21 + --> tests/ui/useless_conversion.rs:140:21 | LL | let _: String = From::from("foo".to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `From::from()`: `"foo".to_string()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion.rs:143:13 + --> tests/ui/useless_conversion.rs:142:13 | LL | let _ = String::from("foo".to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `String::from()`: `"foo".to_string()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion.rs:145:13 + --> tests/ui/useless_conversion.rs:144:13 | LL | let _ = String::from(format!("A: {:04}", 123)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `String::from()`: `format!("A: {:04}", 123)` error: useless conversion to the same type: `std::str::Lines<'_>` - --> tests/ui/useless_conversion.rs:147:13 + --> tests/ui/useless_conversion.rs:146:13 | LL | let _ = "".lines().into_iter(); | ^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `"".lines()` error: useless conversion to the same type: `std::vec::IntoIter` - --> tests/ui/useless_conversion.rs:149:13 + --> tests/ui/useless_conversion.rs:148:13 | LL | let _ = vec![1, 2, 3].into_iter().into_iter(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `vec![1, 2, 3].into_iter()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion.rs:151:21 + --> tests/ui/useless_conversion.rs:150:21 | LL | let _: String = format!("Hello {}", "world").into(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into()`: `format!("Hello {}", "world")` error: useless conversion to the same type: `i32` - --> tests/ui/useless_conversion.rs:157:13 + --> tests/ui/useless_conversion.rs:156:13 | LL | let _ = i32::from(a + b) * 3; | ^^^^^^^^^^^^^^^^ help: consider removing `i32::from()`: `(a + b)` error: useless conversion to the same type: `Foo<'a'>` - --> tests/ui/useless_conversion.rs:164:23 + --> tests/ui/useless_conversion.rs:163:23 | LL | let _: Foo<'a'> = s2.into(); | ^^^^^^^^^ help: consider removing `.into()`: `s2` error: useless conversion to the same type: `Foo<'a'>` - --> tests/ui/useless_conversion.rs:167:13 + --> tests/ui/useless_conversion.rs:166:13 | LL | let _ = Foo::<'a'>::from(s3); | ^^^^^^^^^^^^^^^^^^^^ help: consider removing `Foo::<'a'>::from()`: `s3` error: useless conversion to the same type: `std::vec::IntoIter>` - --> tests/ui/useless_conversion.rs:170:13 + --> tests/ui/useless_conversion.rs:169:13 | LL | let _ = vec![s4, s4, s4].into_iter().into_iter(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `vec![s4, s4, s4].into_iter()` error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:203:7 + --> tests/ui/useless_conversion.rs:200:7 | LL | b(vec![1, 2].into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:193:13 + --> tests/ui/useless_conversion.rs:190:13 | LL | fn b>(_: T) {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -153,13 +150,13 @@ LL + b(vec![1, 2]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:205:7 + --> tests/ui/useless_conversion.rs:202:7 | LL | c(vec![1, 2].into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:194:18 + --> tests/ui/useless_conversion.rs:191:18 | LL | fn c(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -170,13 +167,13 @@ LL + c(vec![1, 2]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:207:7 + --> tests/ui/useless_conversion.rs:204:7 | LL | d(vec![1, 2].into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:197:12 + --> tests/ui/useless_conversion.rs:194:12 | LL | T: IntoIterator, | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -187,13 +184,13 @@ LL + d(vec![1, 2]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:211:7 + --> tests/ui/useless_conversion.rs:208:7 | LL | b(vec![1, 2].into_iter().into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:193:13 + --> tests/ui/useless_conversion.rs:190:13 | LL | fn b>(_: T) {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -204,13 +201,13 @@ LL + b(vec![1, 2]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:213:7 + --> tests/ui/useless_conversion.rs:210:7 | LL | b(vec![1, 2].into_iter().into_iter().into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:193:13 + --> tests/ui/useless_conversion.rs:190:13 | LL | fn b>(_: T) {} | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -221,13 +218,13 @@ LL + b(vec![1, 2]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:260:24 + --> tests/ui/useless_conversion.rs:257:24 | LL | foo2::([1, 2, 3].into_iter()); | ^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:239:12 + --> tests/ui/useless_conversion.rs:236:12 | LL | I: IntoIterator + Helper, | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -238,13 +235,13 @@ LL + foo2::([1, 2, 3]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:269:14 + --> tests/ui/useless_conversion.rs:266:14 | LL | foo3([1, 2, 3].into_iter()); | ^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:248:12 + --> tests/ui/useless_conversion.rs:245:12 | LL | I: IntoIterator, | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -255,13 +252,13 @@ LL + foo3([1, 2, 3]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:279:16 + --> tests/ui/useless_conversion.rs:276:16 | LL | S1.foo([1, 2].into_iter()); | ^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:276:27 + --> tests/ui/useless_conversion.rs:273:27 | LL | pub fn foo(&self, _: I) {} | ^^^^^^^^^^^^ @@ -272,13 +269,13 @@ LL + S1.foo([1, 2]); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:299:44 + --> tests/ui/useless_conversion.rs:296:44 | LL | v0.into_iter().interleave_shortest(v1.into_iter()); | ^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:286:20 + --> tests/ui/useless_conversion.rs:283:20 | LL | J: IntoIterator, | ^^^^^^^^^^^^ @@ -289,61 +286,61 @@ LL + v0.into_iter().interleave_shortest(v1); | error: useless conversion to the same type: `()` - --> tests/ui/useless_conversion.rs:327:58 + --> tests/ui/useless_conversion.rs:324:58 | LL | let _: Result<(), std::io::Error> = test_issue_3913().map(Into::into); | ^^^^^^^^^^^^^^^^ help: consider removing error: useless conversion to the same type: `std::io::Error` - --> tests/ui/useless_conversion.rs:330:58 + --> tests/ui/useless_conversion.rs:327:58 | LL | let _: Result<(), std::io::Error> = test_issue_3913().map_err(Into::into); | ^^^^^^^^^^^^^^^^^^^^ help: consider removing error: useless conversion to the same type: `()` - --> tests/ui/useless_conversion.rs:333:58 + --> tests/ui/useless_conversion.rs:330:58 | LL | let _: Result<(), std::io::Error> = test_issue_3913().map(From::from); | ^^^^^^^^^^^^^^^^ help: consider removing error: useless conversion to the same type: `std::io::Error` - --> tests/ui/useless_conversion.rs:336:58 + --> tests/ui/useless_conversion.rs:333:58 | LL | let _: Result<(), std::io::Error> = test_issue_3913().map_err(From::from); | ^^^^^^^^^^^^^^^^^^^^ help: consider removing error: useless conversion to the same type: `()` - --> tests/ui/useless_conversion.rs:340:31 + --> tests/ui/useless_conversion.rs:337:31 | LL | let _: ControlFlow<()> = c.map_break(Into::into); | ^^^^^^^^^^^^^^^^^^^^^^ help: consider removing error: useless conversion to the same type: `()` - --> tests/ui/useless_conversion.rs:344:31 + --> tests/ui/useless_conversion.rs:341:31 | LL | let _: ControlFlow<()> = c.map_continue(Into::into); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing error: useless conversion to the same type: `u32` - --> tests/ui/useless_conversion.rs:358:41 + --> tests/ui/useless_conversion.rs:355:41 | LL | let _: Vec = [1u32].into_iter().map(Into::into).collect(); | ^^^^^^^^^^^^^^^^ help: consider removing error: useless conversion to the same type: `T` - --> tests/ui/useless_conversion.rs:369:18 + --> tests/ui/useless_conversion.rs:366:18 | LL | x.into_iter().map(Into::into).collect() | ^^^^^^^^^^^^^^^^ help: consider removing error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:385:29 + --> tests/ui/useless_conversion.rs:382:29 | LL | takes_into_iter(self.my_field.into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:374:32 + --> tests/ui/useless_conversion.rs:371:32 | LL | fn takes_into_iter(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -354,13 +351,13 @@ LL + takes_into_iter(&self.my_field); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:393:29 + --> tests/ui/useless_conversion.rs:390:29 | LL | takes_into_iter(self.my_field.into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:374:32 + --> tests/ui/useless_conversion.rs:371:32 | LL | fn takes_into_iter(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -371,13 +368,13 @@ LL + takes_into_iter(&mut self.my_field); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:402:29 + --> tests/ui/useless_conversion.rs:399:29 | LL | takes_into_iter(self.my_field.into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:374:32 + --> tests/ui/useless_conversion.rs:371:32 | LL | fn takes_into_iter(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -388,13 +385,13 @@ LL + takes_into_iter(*self.my_field); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:411:29 + --> tests/ui/useless_conversion.rs:408:29 | LL | takes_into_iter(self.my_field.into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:374:32 + --> tests/ui/useless_conversion.rs:371:32 | LL | fn takes_into_iter(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -405,13 +402,13 @@ LL + takes_into_iter(&*self.my_field); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:420:29 + --> tests/ui/useless_conversion.rs:417:29 | LL | takes_into_iter(self.my_field.into_iter()); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:374:32 + --> tests/ui/useless_conversion.rs:371:32 | LL | fn takes_into_iter(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -422,49 +419,49 @@ LL + takes_into_iter(&mut *self.my_field); | error: useless conversion to the same type: `std::iter::Empty` - --> tests/ui/useless_conversion.rs:433:5 + --> tests/ui/useless_conversion.rs:430:5 | LL | R.into_iter().for_each(|_x| {}); | ^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `R` error: useless conversion to the same type: `std::iter::Empty` - --> tests/ui/useless_conversion.rs:435:13 + --> tests/ui/useless_conversion.rs:432:13 | LL | let _ = R.into_iter().map(|_x| 0); | ^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `R` error: useless conversion to the same type: `std::ops::Range` - --> tests/ui/useless_conversion.rs:458:14 + --> tests/ui/useless_conversion.rs:455:14 | LL | for _ in (0..10).into_iter() {} | ^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `(0..10)` error: useless conversion to the same type: `std::ops::RangeInclusive` - --> tests/ui/useless_conversion.rs:459:14 + --> tests/ui/useless_conversion.rs:456:14 | LL | for _ in (0..=10).into_iter() {} | ^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `(0..=10)` error: useless conversion to the same type: `std::ops::RangeFrom` - --> tests/ui/useless_conversion.rs:460:14 + --> tests/ui/useless_conversion.rs:457:14 | LL | for _ in (0..).into_iter() { | ^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `(0..)` error: useless conversion to the same type: `std::slice::Iter<'_, i32>` - --> tests/ui/useless_conversion.rs:473:14 + --> tests/ui/useless_conversion.rs:470:14 | LL | for _ in mac!(iter [1, 2]).into_iter() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `mac!(iter [1, 2])` error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:486:27 + --> tests/ui/useless_conversion.rs:483:27 | LL | takes_into_iter_usize(b.into_iter()); | ^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:477:34 + --> tests/ui/useless_conversion.rs:474:34 | LL | fn takes_into_iter_usize(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -475,13 +472,13 @@ LL + takes_into_iter_usize(b); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:495:31 + --> tests/ui/useless_conversion.rs:492:31 | LL | takes_into_iter_usize(b.clone().into_iter()); | ^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:477:34 + --> tests/ui/useless_conversion.rs:474:34 | LL | fn takes_into_iter_usize(_: impl IntoIterator) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -492,13 +489,13 @@ LL + takes_into_iter_usize(b.clone()); | error: explicit call to `.into_iter()` in function argument accepting `IntoIterator` - --> tests/ui/useless_conversion.rs:503:34 + --> tests/ui/useless_conversion.rs:500:34 | LL | takes_into_iter_usize_result(b.clone().into_iter())?; | ^^^^^^^^^^^^^^^^^^^^^ | note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()` - --> tests/ui/useless_conversion.rs:478:41 + --> tests/ui/useless_conversion.rs:475:41 | LL | fn takes_into_iter_usize_result(_: impl IntoIterator) -> Result<(), ()> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/useless_conversion_try.rs b/src/tools/clippy/tests/ui/useless_conversion_try.rs index 157c236a214cd..69445c74f31ea 100644 --- a/src/tools/clippy/tests/ui/useless_conversion_try.rs +++ b/src/tools/clippy/tests/ui/useless_conversion_try.rs @@ -1,9 +1,5 @@ -#![deny(clippy::useless_conversion)] -#![allow( - clippy::needless_ifs, - clippy::unnecessary_fallible_conversions, - clippy::manual_unwrap_or_default -)] +#![warn(clippy::useless_conversion)] +#![expect(clippy::manual_unwrap_or_default, clippy::unnecessary_fallible_conversions)] fn test_generic(val: T) -> T { let _ = T::try_from(val).unwrap(); diff --git a/src/tools/clippy/tests/ui/useless_conversion_try.stderr b/src/tools/clippy/tests/ui/useless_conversion_try.stderr index 1c62426c89526..fd15efc7ba657 100644 --- a/src/tools/clippy/tests/ui/useless_conversion_try.stderr +++ b/src/tools/clippy/tests/ui/useless_conversion_try.stderr @@ -1,18 +1,15 @@ error: useless conversion to the same type: `T` - --> tests/ui/useless_conversion_try.rs:9:13 + --> tests/ui/useless_conversion_try.rs:5:13 | LL | let _ = T::try_from(val).unwrap(); | ^^^^^^^^^^^^^^^^ | = help: consider removing `T::try_from()` -note: the lint level is defined here - --> tests/ui/useless_conversion_try.rs:1:9 - | -LL | #![deny(clippy::useless_conversion)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::useless-conversion` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::useless_conversion)]` error: useless conversion to the same type: `T` - --> tests/ui/useless_conversion_try.rs:12:5 + --> tests/ui/useless_conversion_try.rs:8:5 | LL | val.try_into().unwrap() | ^^^^^^^^^^^^^^ @@ -20,7 +17,7 @@ LL | val.try_into().unwrap() = help: consider removing `.try_into()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion_try.rs:35:21 + --> tests/ui/useless_conversion_try.rs:31:21 | LL | let _: String = "foo".to_string().try_into().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -28,7 +25,7 @@ LL | let _: String = "foo".to_string().try_into().unwrap(); = help: consider removing `.try_into()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion_try.rs:38:21 + --> tests/ui/useless_conversion_try.rs:34:21 | LL | let _: String = TryFrom::try_from("foo".to_string()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -36,7 +33,7 @@ LL | let _: String = TryFrom::try_from("foo".to_string()).unwrap(); = help: consider removing `TryFrom::try_from()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion_try.rs:41:13 + --> tests/ui/useless_conversion_try.rs:37:13 | LL | let _ = String::try_from("foo".to_string()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -44,7 +41,7 @@ LL | let _ = String::try_from("foo".to_string()).unwrap(); = help: consider removing `String::try_from()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion_try.rs:44:13 + --> tests/ui/useless_conversion_try.rs:40:13 | LL | let _ = String::try_from(format!("A: {:04}", 123)).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -52,7 +49,7 @@ LL | let _ = String::try_from(format!("A: {:04}", 123)).unwrap(); = help: consider removing `String::try_from()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion_try.rs:47:21 + --> tests/ui/useless_conversion_try.rs:43:21 | LL | let _: String = format!("Hello {}", "world").try_into().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -60,7 +57,7 @@ LL | let _: String = format!("Hello {}", "world").try_into().unwrap(); = help: consider removing `.try_into()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion_try.rs:50:21 + --> tests/ui/useless_conversion_try.rs:46:21 | LL | let _: String = String::new().try_into().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -68,7 +65,7 @@ LL | let _: String = String::new().try_into().unwrap(); = help: consider removing `.try_into()` error: useless conversion to the same type: `std::string::String` - --> tests/ui/useless_conversion_try.rs:53:27 + --> tests/ui/useless_conversion_try.rs:49:27 | LL | let _: String = match String::from("_").try_into() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/vec_box_sized.rs b/src/tools/clippy/tests/ui/vec_box_sized.rs index 897add423b6d4..5cc140953cecc 100644 --- a/src/tools/clippy/tests/ui/vec_box_sized.rs +++ b/src/tools/clippy/tests/ui/vec_box_sized.rs @@ -1,6 +1,6 @@ //@no-rustfix -#![allow(dead_code)] +#![warn(clippy::vec_box)] #![feature(allocator_api)] use std::alloc::{AllocError, Allocator, Layout}; diff --git a/src/tools/clippy/tests/ui/vec_init_then_push.rs b/src/tools/clippy/tests/ui/vec_init_then_push.rs index f5b9dae47c759..a747b669d3944 100644 --- a/src/tools/clippy/tests/ui/vec_init_then_push.rs +++ b/src/tools/clippy/tests/ui/vec_init_then_push.rs @@ -1,4 +1,3 @@ -#![allow(unused_variables)] #![warn(clippy::vec_init_then_push)] //@no-rustfix fn main() { diff --git a/src/tools/clippy/tests/ui/vec_init_then_push.stderr b/src/tools/clippy/tests/ui/vec_init_then_push.stderr index 1900ad7bd6a0e..2561439accef4 100644 --- a/src/tools/clippy/tests/ui/vec_init_then_push.stderr +++ b/src/tools/clippy/tests/ui/vec_init_then_push.stderr @@ -1,5 +1,5 @@ error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:5:5 + --> tests/ui/vec_init_then_push.rs:4:5 | LL | / let mut def_err: Vec = Default::default(); ... | @@ -10,7 +10,7 @@ LL | | def_err.push(0); = help: to override `-D warnings` add `#[allow(clippy::vec_init_then_push)]` error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:10:5 + --> tests/ui/vec_init_then_push.rs:9:5 | LL | / let mut new_err = Vec::::new(); ... | @@ -18,7 +18,7 @@ LL | | new_err.push(1); | |____________________^ help: consider using the `vec![]` macro: `let mut new_err = vec![..];` error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:15:5 + --> tests/ui/vec_init_then_push.rs:14:5 | LL | / let mut cap_err = Vec::with_capacity(2); LL | | @@ -29,7 +29,7 @@ LL | | cap_err.push(2); | |____________________^ help: consider using the `vec![]` macro: `let mut cap_err = vec![..];` error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:29:5 + --> tests/ui/vec_init_then_push.rs:28:5 | LL | / new_err = Vec::new(); ... | @@ -37,7 +37,7 @@ LL | | new_err.push(0); | |____________________^ help: consider using the `vec![]` macro: `new_err = vec![..];` error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:81:5 + --> tests/ui/vec_init_then_push.rs:80:5 | LL | / let mut v = Vec::new(); LL | | @@ -47,7 +47,7 @@ LL | | v.push(1); | |______________^ help: consider using the `vec![]` macro: `let mut v = vec![..];` error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:91:5 + --> tests/ui/vec_init_then_push.rs:90:5 | LL | / let mut v = Vec::new(); LL | | @@ -59,7 +59,7 @@ LL | | v.push(0); | |______________^ help: consider using the `vec![]` macro: `let mut v = vec![..];` error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:106:5 + --> tests/ui/vec_init_then_push.rs:105:5 | LL | / let mut v2 = Vec::new(); LL | | @@ -71,7 +71,7 @@ LL | | v2.push(0); | |_______________^ help: consider using the `vec![]` macro: `let mut v2 = vec![..];` error: calls to `push` immediately after creation - --> tests/ui/vec_init_then_push.rs:123:5 + --> tests/ui/vec_init_then_push.rs:122:5 | LL | / let mut v = Vec::new(); ... | diff --git a/src/tools/clippy/tests/ui/while_let_loop.rs b/src/tools/clippy/tests/ui/while_let_loop.rs index b5a362669ce2b..0100be4ec137b 100644 --- a/src/tools/clippy/tests/ui/while_let_loop.rs +++ b/src/tools/clippy/tests/ui/while_let_loop.rs @@ -1,5 +1,5 @@ #![warn(clippy::while_let_loop)] -#![allow(clippy::uninlined_format_args)] +#![expect(clippy::uninlined_format_args)] //@no-rustfix fn main() { let y = Some(true); diff --git a/src/tools/clippy/tests/ui/while_let_on_iterator.fixed b/src/tools/clippy/tests/ui/while_let_on_iterator.fixed index 0d3b446af43fa..a06c57250aba2 100644 --- a/src/tools/clippy/tests/ui/while_let_on_iterator.fixed +++ b/src/tools/clippy/tests/ui/while_let_on_iterator.fixed @@ -1,12 +1,7 @@ #![warn(clippy::while_let_on_iterator)] -#![allow(dead_code, unreachable_code, unused_mut)] -#![allow( - clippy::equatable_if_let, - clippy::manual_find, - clippy::never_loop, +#![expect( clippy::redundant_closure_call, clippy::single_range_in_vec_init, - clippy::uninlined_format_args, clippy::useless_vec )] diff --git a/src/tools/clippy/tests/ui/while_let_on_iterator.rs b/src/tools/clippy/tests/ui/while_let_on_iterator.rs index e1d9e9081e452..3d3ba3d07f1f7 100644 --- a/src/tools/clippy/tests/ui/while_let_on_iterator.rs +++ b/src/tools/clippy/tests/ui/while_let_on_iterator.rs @@ -1,12 +1,7 @@ #![warn(clippy::while_let_on_iterator)] -#![allow(dead_code, unreachable_code, unused_mut)] -#![allow( - clippy::equatable_if_let, - clippy::manual_find, - clippy::never_loop, +#![expect( clippy::redundant_closure_call, clippy::single_range_in_vec_init, - clippy::uninlined_format_args, clippy::useless_vec )] diff --git a/src/tools/clippy/tests/ui/while_let_on_iterator.stderr b/src/tools/clippy/tests/ui/while_let_on_iterator.stderr index cd43d3c17800e..5e7e74d7ae8d7 100644 --- a/src/tools/clippy/tests/ui/while_let_on_iterator.stderr +++ b/src/tools/clippy/tests/ui/while_let_on_iterator.stderr @@ -1,5 +1,5 @@ error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:15:5 + --> tests/ui/while_let_on_iterator.rs:10:5 | LL | while let Option::Some(x) = iter.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in iter` @@ -8,193 +8,193 @@ LL | while let Option::Some(x) = iter.next() { = help: to override `-D warnings` add `#[allow(clippy::while_let_on_iterator)]` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:21:5 + --> tests/ui/while_let_on_iterator.rs:16:5 | LL | while let Some(x) = iter.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in iter` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:27:5 + --> tests/ui/while_let_on_iterator.rs:22:5 | LL | while let Some(_) = iter.next() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for _ in iter` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:104:9 + --> tests/ui/while_let_on_iterator.rs:99:9 | LL | while let Some([..]) = it.next() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for [..] in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:112:9 + --> tests/ui/while_let_on_iterator.rs:107:9 | LL | while let Some([_x]) = it.next() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for [_x] in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:126:9 + --> tests/ui/while_let_on_iterator.rs:121:9 | LL | while let Some(x @ [_]) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x @ [_] in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:147:9 + --> tests/ui/while_let_on_iterator.rs:142:9 | LL | while let Some(_) = y.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for _ in y` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:205:9 + --> tests/ui/while_let_on_iterator.rs:200:9 | LL | while let Some(m) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for m in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:217:5 + --> tests/ui/while_let_on_iterator.rs:212:5 | LL | while let Some(n) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for n in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:220:9 + --> tests/ui/while_let_on_iterator.rs:215:9 | LL | while let Some(m) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for m in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:230:9 + --> tests/ui/while_let_on_iterator.rs:225:9 | LL | while let Some(m) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for m in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:240:9 + --> tests/ui/while_let_on_iterator.rs:235:9 | LL | while let Some(m) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for m in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:258:9 + --> tests/ui/while_let_on_iterator.rs:253:9 | LL | while let Some(m) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for m in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:274:13 + --> tests/ui/while_let_on_iterator.rs:269:13 | LL | while let Some(i) = self.0.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for i in self.0.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:307:13 + --> tests/ui/while_let_on_iterator.rs:302:13 | LL | while let Some(i) = self.0.0.0.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for i in self.0.0.0.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:337:5 + --> tests/ui/while_let_on_iterator.rs:332:5 | LL | while let Some(n) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for n in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:350:9 + --> tests/ui/while_let_on_iterator.rs:345:9 | LL | while let Some(x) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:365:5 + --> tests/ui/while_let_on_iterator.rs:360:5 | LL | while let Some(x) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:377:5 + --> tests/ui/while_let_on_iterator.rs:372:5 | LL | while let Some(x) = it.0.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it.0.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:413:5 + --> tests/ui/while_let_on_iterator.rs:408:5 | LL | while let Some(x) = s.x.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in s.x.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:421:5 + --> tests/ui/while_let_on_iterator.rs:416:5 | LL | while let Some(x) = x[0].next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in x[0].by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:430:9 + --> tests/ui/while_let_on_iterator.rs:425:9 | LL | while let Some(x) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:441:9 + --> tests/ui/while_let_on_iterator.rs:436:9 | LL | while let Some(x) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:452:9 + --> tests/ui/while_let_on_iterator.rs:447:9 | LL | while let Some(x) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:463:9 + --> tests/ui/while_let_on_iterator.rs:458:9 | LL | while let Some(x) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:476:9 + --> tests/ui/while_let_on_iterator.rs:471:9 | LL | while let Some(x) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:487:5 + --> tests/ui/while_let_on_iterator.rs:482:5 | LL | 'label: while let Some(n) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `'label: for n in it` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:499:13 + --> tests/ui/while_let_on_iterator.rs:494:13 | LL | while let Some(r) = self.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for r in &mut *self` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:515:13 + --> tests/ui/while_let_on_iterator.rs:510:13 | LL | while let Some(r) = self.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for r in self.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:541:9 + --> tests/ui/while_let_on_iterator.rs:536:9 | LL | while let Some(_) = x.next() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for _ in &mut ***x` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:563:9 + --> tests/ui/while_let_on_iterator.rs:558:9 | LL | while let Some(_) = x.next() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for _ in &mut **x` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:594:9 + --> tests/ui/while_let_on_iterator.rs:589:9 | LL | while let Some(_) = x.next() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for _ in x.by_ref()` error: this loop could be written as a `for` loop - --> tests/ui/while_let_on_iterator.rs:601:5 + --> tests/ui/while_let_on_iterator.rs:596:5 | LL | while let Some(..) = it.next() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for _ in it` diff --git a/src/tools/clippy/tests/ui/wildcard_enum_match_arm.fixed b/src/tools/clippy/tests/ui/wildcard_enum_match_arm.fixed index 5f738a254dcdd..e51236e444fca 100644 --- a/src/tools/clippy/tests/ui/wildcard_enum_match_arm.fixed +++ b/src/tools/clippy/tests/ui/wildcard_enum_match_arm.fixed @@ -1,13 +1,6 @@ //@aux-build:non-exhaustive-enum.rs -#![deny(clippy::wildcard_enum_match_arm)] -#![allow(dead_code, unreachable_code, unused_variables)] -#![allow( - clippy::diverging_sub_expression, - clippy::single_match, - clippy::uninlined_format_args, - clippy::unnested_or_patterns, - clippy::wildcard_in_or_patterns -)] +#![warn(clippy::wildcard_enum_match_arm)] +#![expect(clippy::diverging_sub_expression, clippy::single_match)] extern crate non_exhaustive_enum; diff --git a/src/tools/clippy/tests/ui/wildcard_enum_match_arm.rs b/src/tools/clippy/tests/ui/wildcard_enum_match_arm.rs index 4bc4bfdcb7945..729fca0ce6372 100644 --- a/src/tools/clippy/tests/ui/wildcard_enum_match_arm.rs +++ b/src/tools/clippy/tests/ui/wildcard_enum_match_arm.rs @@ -1,13 +1,6 @@ //@aux-build:non-exhaustive-enum.rs -#![deny(clippy::wildcard_enum_match_arm)] -#![allow(dead_code, unreachable_code, unused_variables)] -#![allow( - clippy::diverging_sub_expression, - clippy::single_match, - clippy::uninlined_format_args, - clippy::unnested_or_patterns, - clippy::wildcard_in_or_patterns -)] +#![warn(clippy::wildcard_enum_match_arm)] +#![expect(clippy::diverging_sub_expression, clippy::single_match)] extern crate non_exhaustive_enum; diff --git a/src/tools/clippy/tests/ui/wildcard_enum_match_arm.stderr b/src/tools/clippy/tests/ui/wildcard_enum_match_arm.stderr index d0929989494a4..34d3efc136eeb 100644 --- a/src/tools/clippy/tests/ui/wildcard_enum_match_arm.stderr +++ b/src/tools/clippy/tests/ui/wildcard_enum_match_arm.stderr @@ -1,53 +1,50 @@ error: wildcard match will also match any future added variants - --> tests/ui/wildcard_enum_match_arm.rs:39:9 + --> tests/ui/wildcard_enum_match_arm.rs:32:9 | LL | _ => eprintln!("Not red"), | ^ help: try: `Color::Green | Color::Blue | Color::Rgb(..) | Color::Cyan` | -note: the lint level is defined here - --> tests/ui/wildcard_enum_match_arm.rs:2:9 - | -LL | #![deny(clippy::wildcard_enum_match_arm)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::wildcard-enum-match-arm` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::wildcard_enum_match_arm)]` error: wildcard match will also match any future added variants - --> tests/ui/wildcard_enum_match_arm.rs:44:9 + --> tests/ui/wildcard_enum_match_arm.rs:37:9 | LL | _not_red => eprintln!("Not red"), | ^^^^^^^^ help: try: `_not_red @ Color::Green | _not_red @ Color::Blue | _not_red @ Color::Rgb(..) | _not_red @ Color::Cyan` error: wildcard match will also match any future added variants - --> tests/ui/wildcard_enum_match_arm.rs:49:9 + --> tests/ui/wildcard_enum_match_arm.rs:42:9 | LL | not_red => format!("{:?}", not_red), | ^^^^^^^ help: try: `not_red @ Color::Green | not_red @ Color::Blue | not_red @ Color::Rgb(..) | not_red @ Color::Cyan` error: wildcard match will also match any future added variants - --> tests/ui/wildcard_enum_match_arm.rs:66:9 + --> tests/ui/wildcard_enum_match_arm.rs:59:9 | LL | _ => "No red", | ^ help: try: `Color::Red | Color::Green | Color::Blue | Color::Rgb(..) | Color::Cyan` error: wildcard matches known variants and will also match future added variants - --> tests/ui/wildcard_enum_match_arm.rs:84:9 + --> tests/ui/wildcard_enum_match_arm.rs:77:9 | LL | _ => {}, | ^ help: try: `ErrorKind::PermissionDenied | _` error: wildcard match will also match any future added variants - --> tests/ui/wildcard_enum_match_arm.rs:103:13 + --> tests/ui/wildcard_enum_match_arm.rs:96:13 | LL | _ => (), | ^ help: try: `Enum::B | Enum::C(_) | Enum::D(..) | Enum::E { .. }` error: wildcard match will also match any future added variants - --> tests/ui/wildcard_enum_match_arm.rs:118:13 + --> tests/ui/wildcard_enum_match_arm.rs:111:13 | LL | _ => (), | ^ help: try: `Enum::B | Enum::__Private` error: wildcard match will also match any future added variants - --> tests/ui/wildcard_enum_match_arm.rs:133:9 + --> tests/ui/wildcard_enum_match_arm.rs:126:9 | LL | r#type => {}, | ^^^^^^ help: try: `r#type @ Foo::B | r#type @ Foo::C` diff --git a/src/tools/clippy/tests/ui/wildcard_imports.fixed b/src/tools/clippy/tests/ui/wildcard_imports.fixed index 17510683f03e4..27d01e6573b85 100644 --- a/src/tools/clippy/tests/ui/wildcard_imports.fixed +++ b/src/tools/clippy/tests/ui/wildcard_imports.fixed @@ -7,8 +7,8 @@ // no longer detects some of the cases starting with Rust 2018. #![warn(clippy::wildcard_imports)] -#![allow(unused, clippy::unnecessary_wraps, clippy::let_unit_value)] -#![warn(unused_imports)] +#![deny(unused_imports)] +#![expect(clippy::let_unit_value)] extern crate wildcard_imports_helper; diff --git a/src/tools/clippy/tests/ui/wildcard_imports.rs b/src/tools/clippy/tests/ui/wildcard_imports.rs index 2168f0a8918dd..226f26412cc1b 100644 --- a/src/tools/clippy/tests/ui/wildcard_imports.rs +++ b/src/tools/clippy/tests/ui/wildcard_imports.rs @@ -7,8 +7,8 @@ // no longer detects some of the cases starting with Rust 2018. #![warn(clippy::wildcard_imports)] -#![allow(unused, clippy::unnecessary_wraps, clippy::let_unit_value)] -#![warn(unused_imports)] +#![deny(unused_imports)] +#![expect(clippy::let_unit_value)] extern crate wildcard_imports_helper; diff --git a/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2018.fixed b/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2018.fixed index f97b883ea231f..46abaa91a1c2f 100644 --- a/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2018.fixed +++ b/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2018.fixed @@ -5,8 +5,8 @@ //@aux-build:wildcard_imports_helper.rs #![warn(clippy::wildcard_imports)] -#![allow(unused, clippy::unnecessary_wraps, clippy::let_unit_value)] -#![warn(unused_imports)] +#![deny(unused_imports)] +#![expect(clippy::let_unit_value)] extern crate wildcard_imports_helper; diff --git a/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2021.fixed b/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2021.fixed index f97b883ea231f..46abaa91a1c2f 100644 --- a/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2021.fixed +++ b/src/tools/clippy/tests/ui/wildcard_imports_2021.edition2021.fixed @@ -5,8 +5,8 @@ //@aux-build:wildcard_imports_helper.rs #![warn(clippy::wildcard_imports)] -#![allow(unused, clippy::unnecessary_wraps, clippy::let_unit_value)] -#![warn(unused_imports)] +#![deny(unused_imports)] +#![expect(clippy::let_unit_value)] extern crate wildcard_imports_helper; diff --git a/src/tools/clippy/tests/ui/wildcard_imports_2021.rs b/src/tools/clippy/tests/ui/wildcard_imports_2021.rs index 8075c15bc14f1..3e71d83ef4596 100644 --- a/src/tools/clippy/tests/ui/wildcard_imports_2021.rs +++ b/src/tools/clippy/tests/ui/wildcard_imports_2021.rs @@ -5,8 +5,8 @@ //@aux-build:wildcard_imports_helper.rs #![warn(clippy::wildcard_imports)] -#![allow(unused, clippy::unnecessary_wraps, clippy::let_unit_value)] -#![warn(unused_imports)] +#![deny(unused_imports)] +#![expect(clippy::let_unit_value)] extern crate wildcard_imports_helper; diff --git a/src/tools/clippy/tests/ui/wildcard_imports_cfgtest.rs b/src/tools/clippy/tests/ui/wildcard_imports_cfgtest.rs index c41458d5bb0a7..5a35c0f74f21b 100644 --- a/src/tools/clippy/tests/ui/wildcard_imports_cfgtest.rs +++ b/src/tools/clippy/tests/ui/wildcard_imports_cfgtest.rs @@ -2,7 +2,7 @@ //@compile-flags: --test #![warn(clippy::wildcard_imports)] -#![allow(unused, clippy::unnecessary_wraps, clippy::let_unit_value)] +#![expect(clippy::let_unit_value)] // Test for #10580, the lint should ignore it because of the crate's cfg test flag. diff --git a/src/tools/clippy/tests/ui/with_capacity_zero.fixed b/src/tools/clippy/tests/ui/with_capacity_zero.fixed index 6da614d000248..3e9e12ac57918 100644 --- a/src/tools/clippy/tests/ui/with_capacity_zero.fixed +++ b/src/tools/clippy/tests/ui/with_capacity_zero.fixed @@ -1,5 +1,4 @@ #![warn(clippy::with_capacity_zero)] -#![allow(unused)] #![allow(clippy::eq_op)] use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque}; diff --git a/src/tools/clippy/tests/ui/with_capacity_zero.rs b/src/tools/clippy/tests/ui/with_capacity_zero.rs index 0f8bfb12c34f5..6fb6a11b61d11 100644 --- a/src/tools/clippy/tests/ui/with_capacity_zero.rs +++ b/src/tools/clippy/tests/ui/with_capacity_zero.rs @@ -1,5 +1,4 @@ #![warn(clippy::with_capacity_zero)] -#![allow(unused)] #![allow(clippy::eq_op)] use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque}; diff --git a/src/tools/clippy/tests/ui/with_capacity_zero.stderr b/src/tools/clippy/tests/ui/with_capacity_zero.stderr index 5fce9d90e0360..6033845d59fc3 100644 --- a/src/tools/clippy/tests/ui/with_capacity_zero.stderr +++ b/src/tools/clippy/tests/ui/with_capacity_zero.stderr @@ -1,5 +1,5 @@ error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:19:23 + --> tests/ui/with_capacity_zero.rs:18:23 | LL | let v: Vec = Vec::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let v: Vec = Vec::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:21:13 + --> tests/ui/with_capacity_zero.rs:20:13 | LL | let s = String::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + let s = String::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:23:14 + --> tests/ui/with_capacity_zero.rs:22:14 | LL | let v2 = std::vec::Vec::::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + let v2 = std::vec::Vec::::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:25:15 + --> tests/ui/with_capacity_zero.rs:24:15 | LL | let map = HashMap::::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + let map = HashMap::::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:27:15 + --> tests/ui/with_capacity_zero.rs:26:15 | LL | let set = HashSet::::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + let set = HashSet::::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:29:17 + --> tests/ui/with_capacity_zero.rs:28:17 | LL | let deque = VecDeque::::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + let deque = VecDeque::::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:31:16 + --> tests/ui/with_capacity_zero.rs:30:16 | LL | let heap = BinaryHeap::::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + let heap = BinaryHeap::::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:33:16 + --> tests/ui/with_capacity_zero.rs:32:16 | LL | let path = PathBuf::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -97,7 +97,7 @@ LL + let path = PathBuf::new(); | error: calling `with_capacity(0)` is equivalent to `new()` - --> tests/ui/with_capacity_zero.rs:35:18 + --> tests/ui/with_capacity_zero.rs:34:18 | LL | let os_str = OsString::with_capacity(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/write_literal.fixed b/src/tools/clippy/tests/ui/write_literal.fixed index ae29f3a574625..95bbdca4d10c3 100644 --- a/src/tools/clippy/tests/ui/write_literal.fixed +++ b/src/tools/clippy/tests/ui/write_literal.fixed @@ -1,5 +1,5 @@ #![warn(clippy::write_literal)] -#![allow(clippy::uninlined_format_args, unused_must_use)] +#![expect(clippy::uninlined_format_args)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/write_literal.rs b/src/tools/clippy/tests/ui/write_literal.rs index d930339e106cf..6b190d9c5c10c 100644 --- a/src/tools/clippy/tests/ui/write_literal.rs +++ b/src/tools/clippy/tests/ui/write_literal.rs @@ -1,5 +1,5 @@ #![warn(clippy::write_literal)] -#![allow(clippy::uninlined_format_args, unused_must_use)] +#![expect(clippy::uninlined_format_args)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/write_literal_unfixable.rs b/src/tools/clippy/tests/ui/write_literal_unfixable.rs index 3a5660180779d..80b80d05d9b1d 100644 --- a/src/tools/clippy/tests/ui/write_literal_unfixable.rs +++ b/src/tools/clippy/tests/ui/write_literal_unfixable.rs @@ -1,5 +1,4 @@ //@no-rustfix -#![allow(unused_must_use)] #![warn(clippy::write_literal)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/write_literal_unfixable.stderr b/src/tools/clippy/tests/ui/write_literal_unfixable.stderr index 0dd40e891893d..a18b84964a7d3 100644 --- a/src/tools/clippy/tests/ui/write_literal_unfixable.stderr +++ b/src/tools/clippy/tests/ui/write_literal_unfixable.stderr @@ -1,5 +1,5 @@ error: literal with an empty format string - --> tests/ui/write_literal_unfixable.rs:10:24 + --> tests/ui/write_literal_unfixable.rs:9:24 | LL | writeln!(v, r"{}", '"'); | ^^^ @@ -8,7 +8,7 @@ LL | writeln!(v, r"{}", '"'); = help: to override `-D warnings` add `#[allow(clippy::write_literal)]` error: literal with an empty format string - --> tests/ui/write_literal_unfixable.rs:14:28 + --> tests/ui/write_literal_unfixable.rs:13:28 | LL | writeln!(v, r#"{}{}"#, '#', '"'); | ^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/write_with_newline.fixed b/src/tools/clippy/tests/ui/write_with_newline.fixed index 40742bbbb4275..319f981d95ad3 100644 --- a/src/tools/clippy/tests/ui/write_with_newline.fixed +++ b/src/tools/clippy/tests/ui/write_with_newline.fixed @@ -1,7 +1,5 @@ -// FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934 - -#![allow(clippy::write_literal)] #![warn(clippy::write_with_newline)] +#![expect(clippy::write_literal)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/write_with_newline.rs b/src/tools/clippy/tests/ui/write_with_newline.rs index ad6af69e78137..91ca88dde672b 100644 --- a/src/tools/clippy/tests/ui/write_with_newline.rs +++ b/src/tools/clippy/tests/ui/write_with_newline.rs @@ -1,7 +1,5 @@ -// FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934 - -#![allow(clippy::write_literal)] #![warn(clippy::write_with_newline)] +#![expect(clippy::write_literal)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/write_with_newline.stderr b/src/tools/clippy/tests/ui/write_with_newline.stderr index 7243b7943df00..b7a5c3f3c5ab7 100644 --- a/src/tools/clippy/tests/ui/write_with_newline.stderr +++ b/src/tools/clippy/tests/ui/write_with_newline.stderr @@ -1,5 +1,5 @@ error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:12:5 + --> tests/ui/write_with_newline.rs:10:5 | LL | write!(v, "Hello\n"); | ^^^^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + writeln!(v, "Hello"); | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:15:5 + --> tests/ui/write_with_newline.rs:13:5 | LL | write!(v, "Hello {}\n", "world"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL + writeln!(v, "Hello {}", "world"); | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:18:5 + --> tests/ui/write_with_newline.rs:16:5 | LL | write!(v, "Hello {} {}\n", "world", "#2"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + writeln!(v, "Hello {} {}", "world", "#2"); | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:21:5 + --> tests/ui/write_with_newline.rs:19:5 | LL | write!(v, "{}\n", 1265); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL + writeln!(v, "{}", 1265); | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:24:5 + --> tests/ui/write_with_newline.rs:22:5 | LL | write!(v, "\n"); | ^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + writeln!(v); | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:47:5 + --> tests/ui/write_with_newline.rs:45:5 | LL | write!(v, "\\\n"); | ^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + writeln!(v, "\\"); | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:57:5 + --> tests/ui/write_with_newline.rs:55:5 | LL | / write!( LL | | @@ -91,7 +91,7 @@ LL ~ v | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:63:5 + --> tests/ui/write_with_newline.rs:61:5 | LL | / write!( LL | | @@ -109,7 +109,7 @@ LL ~ v | error: using `write!()` with a format string that ends in a single newline - --> tests/ui/write_with_newline.rs:73:5 + --> tests/ui/write_with_newline.rs:71:5 | LL | write!(v, "\\r\n"); | ^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/writeln_empty_string.fixed b/src/tools/clippy/tests/ui/writeln_empty_string.fixed index 5cb702b10f2d5..e6195846c4396 100644 --- a/src/tools/clippy/tests/ui/writeln_empty_string.fixed +++ b/src/tools/clippy/tests/ui/writeln_empty_string.fixed @@ -1,4 +1,3 @@ -#![allow(unused_must_use)] #![warn(clippy::writeln_empty_string)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/writeln_empty_string.rs b/src/tools/clippy/tests/ui/writeln_empty_string.rs index e6478264a578d..c20eef8c813ad 100644 --- a/src/tools/clippy/tests/ui/writeln_empty_string.rs +++ b/src/tools/clippy/tests/ui/writeln_empty_string.rs @@ -1,4 +1,3 @@ -#![allow(unused_must_use)] #![warn(clippy::writeln_empty_string)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/writeln_empty_string.stderr b/src/tools/clippy/tests/ui/writeln_empty_string.stderr index 43e76309ba64c..899c82a47e143 100644 --- a/src/tools/clippy/tests/ui/writeln_empty_string.stderr +++ b/src/tools/clippy/tests/ui/writeln_empty_string.stderr @@ -1,5 +1,5 @@ error: empty string literal in `writeln!` - --> tests/ui/writeln_empty_string.rs:9:5 + --> tests/ui/writeln_empty_string.rs:8:5 | LL | writeln!(v, ""); | ^^^^^^^^^^----^ @@ -10,7 +10,7 @@ LL | writeln!(v, ""); = help: to override `-D warnings` add `#[allow(clippy::writeln_empty_string)]` error: empty string literal in `writeln!` - --> tests/ui/writeln_empty_string.rs:13:5 + --> tests/ui/writeln_empty_string.rs:12:5 | LL | writeln!(suggestion, ""); | ^^^^^^^^^^^^^^^^^^^----^ diff --git a/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.rs b/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.rs index ca570fd1fc7bf..f4b16bfed0a25 100644 --- a/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.rs +++ b/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.rs @@ -1,4 +1,3 @@ -#![allow(unused_must_use)] #![warn(clippy::writeln_empty_string)] use std::io::Write; diff --git a/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.stderr b/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.stderr index 0ed802ba84ba5..d2aa50f057277 100644 --- a/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.stderr +++ b/src/tools/clippy/tests/ui/writeln_empty_string_unfixable.stderr @@ -1,11 +1,11 @@ error: empty string literal in `writeln!` - --> tests/ui/writeln_empty_string_unfixable.rs:11:5 + --> tests/ui/writeln_empty_string_unfixable.rs:10:5 | LL | writeln!(v, /* comment */ ""); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: remove the empty string - --> tests/ui/writeln_empty_string_unfixable.rs:11:31 + --> tests/ui/writeln_empty_string_unfixable.rs:10:31 | LL | writeln!(v, /* comment */ ""); | ^^ @@ -13,19 +13,19 @@ LL | writeln!(v, /* comment */ ""); = help: to override `-D warnings` add `#[allow(clippy::writeln_empty_string)]` error: empty string literal in `writeln!` - --> tests/ui/writeln_empty_string_unfixable.rs:14:5 + --> tests/ui/writeln_empty_string_unfixable.rs:13:5 | LL | writeln!(v, "" /* comment */); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: remove the empty string - --> tests/ui/writeln_empty_string_unfixable.rs:14:17 + --> tests/ui/writeln_empty_string_unfixable.rs:13:17 | LL | writeln!(v, "" /* comment */); | ^^ error: empty string literal in `writeln!` - --> tests/ui/writeln_empty_string_unfixable.rs:18:5 + --> tests/ui/writeln_empty_string_unfixable.rs:17:5 | LL | / writeln!(v, LL | | "\ @@ -36,7 +36,7 @@ LL | | ); | |_____^ | note: remove the empty string - --> tests/ui/writeln_empty_string_unfixable.rs:19:9 + --> tests/ui/writeln_empty_string_unfixable.rs:18:9 | LL | / "\ LL | | \ diff --git a/src/tools/clippy/tests/ui/wrong_self_convention.rs b/src/tools/clippy/tests/ui/wrong_self_convention.rs index 840dfe7c6524e..802cc38af4f38 100644 --- a/src/tools/clippy/tests/ui/wrong_self_convention.rs +++ b/src/tools/clippy/tests/ui/wrong_self_convention.rs @@ -1,5 +1,4 @@ #![warn(clippy::wrong_self_convention)] -#![allow(dead_code)] fn main() {} diff --git a/src/tools/clippy/tests/ui/wrong_self_convention.stderr b/src/tools/clippy/tests/ui/wrong_self_convention.stderr index e720ddf3fae17..2f2ab956c639e 100644 --- a/src/tools/clippy/tests/ui/wrong_self_convention.stderr +++ b/src/tools/clippy/tests/ui/wrong_self_convention.stderr @@ -1,5 +1,5 @@ error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention.rs:16:17 + --> tests/ui/wrong_self_convention.rs:15:17 | LL | fn from_i32(self) {} | ^^^^ @@ -9,7 +9,7 @@ LL | fn from_i32(self) {} = help: to override `-D warnings` add `#[allow(clippy::wrong_self_convention)]` error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention.rs:23:21 + --> tests/ui/wrong_self_convention.rs:22:21 | LL | pub fn from_i64(self) {} | ^^^^ @@ -17,7 +17,7 @@ LL | pub fn from_i64(self) {} = help: consider choosing a less ambiguous name error: methods called `as_*` usually take `self` by reference or `self` by mutable reference - --> tests/ui/wrong_self_convention.rs:37:15 + --> tests/ui/wrong_self_convention.rs:36:15 | LL | fn as_i32(self) {} | ^^^^ @@ -25,7 +25,7 @@ LL | fn as_i32(self) {} = help: consider choosing a less ambiguous name error: methods called `into_*` usually take `self` by value - --> tests/ui/wrong_self_convention.rs:41:17 + --> tests/ui/wrong_self_convention.rs:40:17 | LL | fn into_i32(&self) {} | ^^^^^ @@ -33,7 +33,7 @@ LL | fn into_i32(&self) {} = help: consider choosing a less ambiguous name error: methods called `is_*` usually take `self` by mutable reference or `self` by reference or no `self` - --> tests/ui/wrong_self_convention.rs:45:15 + --> tests/ui/wrong_self_convention.rs:44:15 | LL | fn is_i32(self) {} | ^^^^ @@ -41,7 +41,7 @@ LL | fn is_i32(self) {} = help: consider choosing a less ambiguous name error: methods with the following characteristics: (`to_*` and `self` type is not `Copy`) usually take `self` by reference - --> tests/ui/wrong_self_convention.rs:49:15 + --> tests/ui/wrong_self_convention.rs:48:15 | LL | fn to_i32(self) {} | ^^^^ @@ -49,7 +49,7 @@ LL | fn to_i32(self) {} = help: consider choosing a less ambiguous name error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention.rs:53:17 + --> tests/ui/wrong_self_convention.rs:52:17 | LL | fn from_i32(self) {} | ^^^^ @@ -57,7 +57,7 @@ LL | fn from_i32(self) {} = help: consider choosing a less ambiguous name error: methods called `as_*` usually take `self` by reference or `self` by mutable reference - --> tests/ui/wrong_self_convention.rs:56:19 + --> tests/ui/wrong_self_convention.rs:55:19 | LL | pub fn as_i64(self) {} | ^^^^ @@ -65,7 +65,7 @@ LL | pub fn as_i64(self) {} = help: consider choosing a less ambiguous name error: methods called `into_*` usually take `self` by value - --> tests/ui/wrong_self_convention.rs:59:21 + --> tests/ui/wrong_self_convention.rs:58:21 | LL | pub fn into_i64(&self) {} | ^^^^^ @@ -73,7 +73,7 @@ LL | pub fn into_i64(&self) {} = help: consider choosing a less ambiguous name error: methods called `is_*` usually take `self` by mutable reference or `self` by reference or no `self` - --> tests/ui/wrong_self_convention.rs:62:19 + --> tests/ui/wrong_self_convention.rs:61:19 | LL | pub fn is_i64(self) {} | ^^^^ @@ -81,7 +81,7 @@ LL | pub fn is_i64(self) {} = help: consider choosing a less ambiguous name error: methods with the following characteristics: (`to_*` and `self` type is not `Copy`) usually take `self` by reference - --> tests/ui/wrong_self_convention.rs:65:19 + --> tests/ui/wrong_self_convention.rs:64:19 | LL | pub fn to_i64(self) {} | ^^^^ @@ -89,7 +89,7 @@ LL | pub fn to_i64(self) {} = help: consider choosing a less ambiguous name error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention.rs:68:21 + --> tests/ui/wrong_self_convention.rs:67:21 | LL | pub fn from_i64(self) {} | ^^^^ @@ -97,7 +97,7 @@ LL | pub fn from_i64(self) {} = help: consider choosing a less ambiguous name error: methods called `as_*` usually take `self` by reference or `self` by mutable reference - --> tests/ui/wrong_self_convention.rs:114:19 + --> tests/ui/wrong_self_convention.rs:113:19 | LL | fn as_i32(self) {} | ^^^^ @@ -105,7 +105,7 @@ LL | fn as_i32(self) {} = help: consider choosing a less ambiguous name error: methods called `into_*` usually take `self` by value - --> tests/ui/wrong_self_convention.rs:119:25 + --> tests/ui/wrong_self_convention.rs:118:25 | LL | fn into_i32_ref(&self) {} | ^^^^^ @@ -113,7 +113,7 @@ LL | fn into_i32_ref(&self) {} = help: consider choosing a less ambiguous name error: methods called `is_*` usually take `self` by mutable reference or `self` by reference or no `self` - --> tests/ui/wrong_self_convention.rs:123:19 + --> tests/ui/wrong_self_convention.rs:122:19 | LL | fn is_i32(self) {} | ^^^^ @@ -121,7 +121,7 @@ LL | fn is_i32(self) {} = help: consider choosing a less ambiguous name error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention.rs:129:21 + --> tests/ui/wrong_self_convention.rs:128:21 | LL | fn from_i32(self) {} | ^^^^ @@ -129,7 +129,7 @@ LL | fn from_i32(self) {} = help: consider choosing a less ambiguous name error: methods called `as_*` usually take `self` by reference or `self` by mutable reference - --> tests/ui/wrong_self_convention.rs:146:19 + --> tests/ui/wrong_self_convention.rs:145:19 | LL | fn as_i32(self); | ^^^^ @@ -137,7 +137,7 @@ LL | fn as_i32(self); = help: consider choosing a less ambiguous name error: methods called `into_*` usually take `self` by value - --> tests/ui/wrong_self_convention.rs:151:25 + --> tests/ui/wrong_self_convention.rs:150:25 | LL | fn into_i32_ref(&self); | ^^^^^ @@ -145,7 +145,7 @@ LL | fn into_i32_ref(&self); = help: consider choosing a less ambiguous name error: methods called `is_*` usually take `self` by mutable reference or `self` by reference or no `self` - --> tests/ui/wrong_self_convention.rs:155:19 + --> tests/ui/wrong_self_convention.rs:154:19 | LL | fn is_i32(self); | ^^^^ @@ -153,7 +153,7 @@ LL | fn is_i32(self); = help: consider choosing a less ambiguous name error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention.rs:161:21 + --> tests/ui/wrong_self_convention.rs:160:21 | LL | fn from_i32(self); | ^^^^ @@ -161,7 +161,7 @@ LL | fn from_i32(self); = help: consider choosing a less ambiguous name error: methods called `into_*` usually take `self` by value - --> tests/ui/wrong_self_convention.rs:181:25 + --> tests/ui/wrong_self_convention.rs:180:25 | LL | fn into_i32_ref(&self); | ^^^^^ @@ -169,7 +169,7 @@ LL | fn into_i32_ref(&self); = help: consider choosing a less ambiguous name error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention.rs:189:21 + --> tests/ui/wrong_self_convention.rs:188:21 | LL | fn from_i32(self); | ^^^^ @@ -177,7 +177,7 @@ LL | fn from_i32(self); = help: consider choosing a less ambiguous name error: methods with the following characteristics: (`to_*` and `self` type is `Copy`) usually take `self` by value - --> tests/ui/wrong_self_convention.rs:215:22 + --> tests/ui/wrong_self_convention.rs:214:22 | LL | fn to_u64_v2(&self) -> u64 { | ^^^^^ @@ -185,7 +185,7 @@ LL | fn to_u64_v2(&self) -> u64 { = help: consider choosing a less ambiguous name error: methods with the following characteristics: (`to_*` and `self` type is not `Copy`) usually take `self` by reference - --> tests/ui/wrong_self_convention.rs:226:19 + --> tests/ui/wrong_self_convention.rs:225:19 | LL | fn to_u64(self) -> u64 { | ^^^^ diff --git a/src/tools/clippy/tests/ui/wrong_self_convention2.rs b/src/tools/clippy/tests/ui/wrong_self_convention2.rs index 0a3e4982a49ac..1f40a0229d308 100644 --- a/src/tools/clippy/tests/ui/wrong_self_convention2.rs +++ b/src/tools/clippy/tests/ui/wrong_self_convention2.rs @@ -1,5 +1,4 @@ #![warn(clippy::wrong_self_convention)] -#![allow(dead_code)] fn main() {} diff --git a/src/tools/clippy/tests/ui/wrong_self_convention2.stderr b/src/tools/clippy/tests/ui/wrong_self_convention2.stderr index 2eafb95d9bbe5..31ed291c7d658 100644 --- a/src/tools/clippy/tests/ui/wrong_self_convention2.stderr +++ b/src/tools/clippy/tests/ui/wrong_self_convention2.stderr @@ -1,5 +1,5 @@ error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention2.rs:54:29 + --> tests/ui/wrong_self_convention2.rs:53:29 | LL | pub fn from_be_self(self) -> Self { | ^^^^ @@ -9,7 +9,7 @@ LL | pub fn from_be_self(self) -> Self { = help: to override `-D warnings` add `#[allow(clippy::wrong_self_convention)]` error: methods called `from_*` usually take no `self` - --> tests/ui/wrong_self_convention2.rs:65:25 + --> tests/ui/wrong_self_convention2.rs:64:25 | LL | fn from_be_self(self) -> Self; | ^^^^ diff --git a/src/tools/clippy/tests/ui/wrong_self_conventions_mut.rs b/src/tools/clippy/tests/ui/wrong_self_conventions_mut.rs index eb6f08fff4245..ab25d760183b2 100644 --- a/src/tools/clippy/tests/ui/wrong_self_conventions_mut.rs +++ b/src/tools/clippy/tests/ui/wrong_self_conventions_mut.rs @@ -1,5 +1,4 @@ #![warn(clippy::wrong_self_convention)] -#![allow(dead_code)] fn main() {} diff --git a/src/tools/clippy/tests/ui/wrong_self_conventions_mut.stderr b/src/tools/clippy/tests/ui/wrong_self_conventions_mut.stderr index 5ea2e8192efee..f82ce70e6390e 100644 --- a/src/tools/clippy/tests/ui/wrong_self_conventions_mut.stderr +++ b/src/tools/clippy/tests/ui/wrong_self_conventions_mut.stderr @@ -1,5 +1,5 @@ error: methods with the following characteristics: (`to_*` and `self` type is not `Copy`) usually take `self` by reference - --> tests/ui/wrong_self_conventions_mut.rs:14:24 + --> tests/ui/wrong_self_conventions_mut.rs:13:24 | LL | pub fn to_many(&mut self) -> Option<&mut [T]> { | ^^^^^^^^^ @@ -9,7 +9,7 @@ LL | pub fn to_many(&mut self) -> Option<&mut [T]> { = help: to override `-D warnings` add `#[allow(clippy::wrong_self_convention)]` error: methods with the following characteristics: (`to_*` and `*_mut`) usually take `self` by mutable reference - --> tests/ui/wrong_self_conventions_mut.rs:24:28 + --> tests/ui/wrong_self_conventions_mut.rs:23:28 | LL | pub fn to_many_mut(&self) -> Option<&[T]> { | ^^^^^ diff --git a/src/tools/clippy/tests/ui/zero_repeat_side_effects.fixed b/src/tools/clippy/tests/ui/zero_repeat_side_effects.fixed index 4bdff6fd0f6c5..27adfadcf19a0 100644 --- a/src/tools/clippy/tests/ui/zero_repeat_side_effects.fixed +++ b/src/tools/clippy/tests/ui/zero_repeat_side_effects.fixed @@ -1,9 +1,11 @@ #![warn(clippy::zero_repeat_side_effects)] -#![allow( - clippy::unnecessary_operation, - clippy::useless_vec, +#![expect( clippy::needless_late_init, clippy::single_match, + clippy::unnecessary_operation, + clippy::useless_vec +)] +#![allow( clippy::no_effect // only fires _after_ the fix )] diff --git a/src/tools/clippy/tests/ui/zero_repeat_side_effects.rs b/src/tools/clippy/tests/ui/zero_repeat_side_effects.rs index a1454d724c870..292387bb36e88 100644 --- a/src/tools/clippy/tests/ui/zero_repeat_side_effects.rs +++ b/src/tools/clippy/tests/ui/zero_repeat_side_effects.rs @@ -1,9 +1,11 @@ #![warn(clippy::zero_repeat_side_effects)] -#![allow( - clippy::unnecessary_operation, - clippy::useless_vec, +#![expect( clippy::needless_late_init, clippy::single_match, + clippy::unnecessary_operation, + clippy::useless_vec +)] +#![allow( clippy::no_effect // only fires _after_ the fix )] diff --git a/src/tools/clippy/tests/ui/zero_repeat_side_effects.stderr b/src/tools/clippy/tests/ui/zero_repeat_side_effects.stderr index f376a1501b001..5560f4855c75c 100644 --- a/src/tools/clippy/tests/ui/zero_repeat_side_effects.stderr +++ b/src/tools/clippy/tests/ui/zero_repeat_side_effects.stderr @@ -1,5 +1,5 @@ error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:22:5 + --> tests/ui/zero_repeat_side_effects.rs:24:5 | LL | let a = [f(); 0]; | ^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + let a: [i32; 0] = []; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:25:5 + --> tests/ui/zero_repeat_side_effects.rs:27:5 | LL | b = [f(); 0]; | ^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL ~ b = [] as [i32; 0]; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:30:5 + --> tests/ui/zero_repeat_side_effects.rs:32:5 | LL | let c = vec![f(); 0]; | ^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL + let c: std::vec::Vec = vec![]; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:33:5 + --> tests/ui/zero_repeat_side_effects.rs:35:5 | LL | d = vec![f(); 0]; | ^^^^^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL ~ d = vec![] as std::vec::Vec; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:37:5 + --> tests/ui/zero_repeat_side_effects.rs:39:5 | LL | let e = [println!("side effect"); 0]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +61,7 @@ LL + let e: [(); 0] = []; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:41:5 + --> tests/ui/zero_repeat_side_effects.rs:43:5 | LL | let g = [{ f() }; 0]; | ^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +73,7 @@ LL + let g: [i32; 0] = []; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:45:10 + --> tests/ui/zero_repeat_side_effects.rs:47:10 | LL | drop(vec![f(); 0]); | ^^^^^^^^^^^^ @@ -87,7 +87,7 @@ LL ~ }); | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:49:5 + --> tests/ui/zero_repeat_side_effects.rs:51:5 | LL | vec![f(); 0]; | ^^^^^^^^^^^^ @@ -99,7 +99,7 @@ LL ~ vec![] as std::vec::Vec; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:51:5 + --> tests/ui/zero_repeat_side_effects.rs:53:5 | LL | [f(); 0]; | ^^^^^^^^ @@ -111,7 +111,7 @@ LL ~ [] as [i32; 0]; | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:105:10 + --> tests/ui/zero_repeat_side_effects.rs:107:10 | LL | foo(&[Some(f()); 0]); | ^^^^^^^^^^^^^^ @@ -125,7 +125,7 @@ LL ~ }); | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:107:10 + --> tests/ui/zero_repeat_side_effects.rs:109:10 | LL | foo(&[Some(Some(S::new())); 0]); | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -139,7 +139,7 @@ LL ~ }); | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:115:14 + --> tests/ui/zero_repeat_side_effects.rs:117:14 | LL | 0 => _ = [f(); 0], | ^^^^^^^^^^^^ @@ -153,7 +153,7 @@ LL ~ }, | error: expression with side effects as the initial value in a zero-sized array initializer - --> tests/ui/zero_repeat_side_effects.rs:122:14 + --> tests/ui/zero_repeat_side_effects.rs:124:14 | LL | 0 => a = [f(); 0], | ^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/zombie_processes.rs b/src/tools/clippy/tests/ui/zombie_processes.rs index e81b5fd4f3e24..39acc7d92da55 100644 --- a/src/tools/clippy/tests/ui/zombie_processes.rs +++ b/src/tools/clippy/tests/ui/zombie_processes.rs @@ -1,5 +1,5 @@ #![warn(clippy::zombie_processes)] -#![allow(clippy::if_same_then_else, clippy::ifs_same_cond, clippy::needless_return)] +#![expect(clippy::if_same_then_else, clippy::ifs_same_cond, clippy::needless_return)] use std::process::{Child, Command, ExitStatus}; diff --git a/src/tools/clippy/tests/ui/zombie_processes_fixable.fixed b/src/tools/clippy/tests/ui/zombie_processes_fixable.fixed index 220abbfcfd7b9..69638b0a706de 100644 --- a/src/tools/clippy/tests/ui/zombie_processes_fixable.fixed +++ b/src/tools/clippy/tests/ui/zombie_processes_fixable.fixed @@ -1,5 +1,5 @@ #![warn(clippy::zombie_processes)] -#![allow(clippy::needless_return)] +#![expect(clippy::needless_return)] use std::process::{Child, Command}; diff --git a/src/tools/clippy/tests/ui/zombie_processes_fixable.rs b/src/tools/clippy/tests/ui/zombie_processes_fixable.rs index 820a839cd4619..bae7680064115 100644 --- a/src/tools/clippy/tests/ui/zombie_processes_fixable.rs +++ b/src/tools/clippy/tests/ui/zombie_processes_fixable.rs @@ -1,5 +1,5 @@ #![warn(clippy::zombie_processes)] -#![allow(clippy::needless_return)] +#![expect(clippy::needless_return)] use std::process::{Child, Command}; diff --git a/src/tools/clippy/tests/ui/{literal_string_with_formatting_args}.rs b/src/tools/clippy/tests/ui/{literal_string_with_formatting_args}.rs index 3096558a516a6..af69d9ebf2e89 100644 --- a/src/tools/clippy/tests/ui/{literal_string_with_formatting_args}.rs +++ b/src/tools/clippy/tests/ui/{literal_string_with_formatting_args}.rs @@ -37,7 +37,6 @@ // ``` #![crate_name = "foo"] -#![allow(unused)] #![warn(clippy::literal_string_with_formatting_args)] fn another_bad() { diff --git a/src/tools/clippy/triagebot.toml b/src/tools/clippy/triagebot.toml index f98831b42bfc2..55f9ca05999d8 100644 --- a/src/tools/clippy/triagebot.toml +++ b/src/tools/clippy/triagebot.toml @@ -66,7 +66,7 @@ threshold = 20 type = "merge-queue" [notify-zulip."lint-nominated"] -zulip_stream = 577190 # #clippy/fcp +zulip_stream = 577190 # #t-clippy/fcp topic = "FCP rust-clippy#{number}: {title}" github_comment = """\ This lint has been nominated for inclusion. @@ -95,12 +95,11 @@ message_on_reopen = "PR rust-clippy#{number} has been reopened." contributing_url = "https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md" users_on_vacation = [ "matthiaskrgr", - "Manishearth", "Alexendoo", "y21", "blyxyas", "ada4a", - "dswij" + "samueltardieu" ] [assign.owners] @@ -117,3 +116,9 @@ users_on_vacation = [ "@samueltardieu", "@ada4a", ] + +# Require community reviews before automatic assignment +# Documentation at: https://forge.rust-lang.org/triagebot/pr-assignment.html#community-reviews +[assign.community_reviews] +minimum_approvals = 2 +label = "S-waiting-on-community-reviews" diff --git a/src/tools/clippy/util/gh-pages/index_template.html b/src/tools/clippy/util/gh-pages/index_template.html index 26ca901fcd226..d92ad879f7956 100644 --- a/src/tools/clippy/util/gh-pages/index_template.html +++ b/src/tools/clippy/util/gh-pages/index_template.html @@ -31,7 +31,7 @@