From 3142ee3f7a2169ee9aa591ebd6414d8952c5a412 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Wed, 1 Apr 2020 19:42:15 +0200 Subject: [PATCH 01/58] Rustup to rust-lang/rust#70627 --- clippy_lints/src/redundant_clone.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index 6bb11c8d9d76..dc1ff86c0bdc 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -437,7 +437,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive { _block: mir::BasicBlock, _func: &mir::Operand<'tcx>, _args: &[mir::Operand<'tcx>], - _return_place: &mir::Place<'tcx>, + _return_place: mir::Place<'tcx>, ) { // Nothing to do when a call returns successfully } From 63987aafba617fcd07a617e36727365430d97e76 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Wed, 1 Apr 2020 20:12:36 +0200 Subject: [PATCH 02/58] Rustup to rust-lang/rust#70081 --- tests/ui/unit_arg.fixed | 2 +- tests/ui/unit_arg.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ui/unit_arg.fixed b/tests/ui/unit_arg.fixed index cf146c91f6d0..a739cf7ad814 100644 --- a/tests/ui/unit_arg.fixed +++ b/tests/ui/unit_arg.fixed @@ -1,6 +1,6 @@ // run-rustfix #![warn(clippy::unit_arg)] -#![allow(clippy::no_effect, unused_must_use)] +#![allow(unused_braces, clippy::no_effect, unused_must_use)] use std::fmt::Debug; diff --git a/tests/ui/unit_arg.rs b/tests/ui/unit_arg.rs index c15b0a500455..d90c49f79de6 100644 --- a/tests/ui/unit_arg.rs +++ b/tests/ui/unit_arg.rs @@ -1,6 +1,6 @@ // run-rustfix #![warn(clippy::unit_arg)] -#![allow(clippy::no_effect, unused_must_use)] +#![allow(unused_braces, clippy::no_effect, unused_must_use)] use std::fmt::Debug; From 7d58ba20b436422a46a1a94c97d0ace199e853ec Mon Sep 17 00:00:00 2001 From: flip1995 Date: Wed, 1 Apr 2020 20:14:05 +0200 Subject: [PATCH 03/58] Rustup to rust-lang/rust#70632 --- clippy_lints/src/utils/higher.rs | 3 +++ clippy_lints/src/utils/paths.rs | 1 + tests/ui/or_fun_call.fixed | 4 +--- tests/ui/or_fun_call.rs | 2 -- tests/ui/or_fun_call.stderr | 16 ++++++++-------- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/clippy_lints/src/utils/higher.rs b/clippy_lints/src/utils/higher.rs index 7dfe666b18ed..33fba7df8d33 100644 --- a/clippy_lints/src/utils/higher.rs +++ b/clippy_lints/src/utils/higher.rs @@ -280,6 +280,9 @@ pub fn vec_macro<'e>(cx: &LateContext<'_, '_>, expr: &'e hir::Expr<'_>) -> Optio None } + else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() { + Some(VecArgs::Vec(&[])) + } else { None }; diff --git a/clippy_lints/src/utils/paths.rs b/clippy_lints/src/utils/paths.rs index 4a4ee5baf002..d443d63cc186 100644 --- a/clippy_lints/src/utils/paths.rs +++ b/clippy_lints/src/utils/paths.rs @@ -131,5 +131,6 @@ pub const VEC_AS_MUT_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_mut_slice"]; pub const VEC_AS_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_slice"]; pub const VEC_DEQUE: [&str; 4] = ["alloc", "collections", "vec_deque", "VecDeque"]; pub const VEC_FROM_ELEM: [&str; 3] = ["alloc", "vec", "from_elem"]; +pub const VEC_NEW: [&str; 4] = ["alloc", "vec", "Vec", "new"]; pub const WEAK_ARC: [&str; 3] = ["alloc", "sync", "Weak"]; pub const WEAK_RC: [&str; 3] = ["alloc", "rc", "Weak"]; diff --git a/tests/ui/or_fun_call.fixed b/tests/ui/or_fun_call.fixed index cf2a42fa485d..8ea03fe42616 100644 --- a/tests/ui/or_fun_call.fixed +++ b/tests/ui/or_fun_call.fixed @@ -53,9 +53,7 @@ fn or_fun_call() { with_default_type.unwrap_or_default(); let with_vec = Some(vec![1]); - with_vec.unwrap_or_else(|| vec![]); - - // FIXME #944: ~|SUGGESTION with_vec.unwrap_or_else(|| vec![]); + with_vec.unwrap_or_default(); let without_default = Some(Foo); without_default.unwrap_or_else(Foo::new); diff --git a/tests/ui/or_fun_call.rs b/tests/ui/or_fun_call.rs index 35fd0a30f6ce..7599b945a913 100644 --- a/tests/ui/or_fun_call.rs +++ b/tests/ui/or_fun_call.rs @@ -55,8 +55,6 @@ fn or_fun_call() { let with_vec = Some(vec![1]); with_vec.unwrap_or(vec![]); - // FIXME #944: ~|SUGGESTION with_vec.unwrap_or_else(|| vec![]); - let without_default = Some(Foo); without_default.unwrap_or(Foo::new()); diff --git a/tests/ui/or_fun_call.stderr b/tests/ui/or_fun_call.stderr index cb92892b8e10..96d55771e6ce 100644 --- a/tests/ui/or_fun_call.stderr +++ b/tests/ui/or_fun_call.stderr @@ -42,38 +42,38 @@ error: use of `unwrap_or` followed by a call to `default` LL | with_default_type.unwrap_or(u64::default()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `with_default_type.unwrap_or_default()` -error: use of `unwrap_or` followed by a function call - --> $DIR/or_fun_call.rs:56:14 +error: use of `unwrap_or` followed by a call to `new` + --> $DIR/or_fun_call.rs:56:5 | LL | with_vec.unwrap_or(vec![]); - | ^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| vec![])` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `with_vec.unwrap_or_default()` error: use of `unwrap_or` followed by a function call - --> $DIR/or_fun_call.rs:61:21 + --> $DIR/or_fun_call.rs:59:21 | LL | without_default.unwrap_or(Foo::new()); | ^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(Foo::new)` error: use of `or_insert` followed by a function call - --> $DIR/or_fun_call.rs:64:19 + --> $DIR/or_fun_call.rs:62:19 | LL | map.entry(42).or_insert(String::new()); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(String::new)` error: use of `or_insert` followed by a function call - --> $DIR/or_fun_call.rs:67:21 + --> $DIR/or_fun_call.rs:65:21 | LL | btree.entry(42).or_insert(String::new()); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(String::new)` error: use of `unwrap_or` followed by a function call - --> $DIR/or_fun_call.rs:70:21 + --> $DIR/or_fun_call.rs:68:21 | LL | let _ = stringy.unwrap_or("".to_owned()); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| "".to_owned())` error: use of `or` followed by a function call - --> $DIR/or_fun_call.rs:95:35 + --> $DIR/or_fun_call.rs:93:35 | LL | let _ = Some("a".to_string()).or(Some("b".to_string())); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_else(|| Some("b".to_string()))` From fcc56fcd1b539ece92a645d664b71b9bf366fb41 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Wed, 1 Apr 2020 20:24:46 +0200 Subject: [PATCH 04/58] Fix dogfood fallout --- clippy_lints/src/loops.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/loops.rs b/clippy_lints/src/loops.rs index 43217b6cc64e..2c0a274e969f 100644 --- a/clippy_lints/src/loops.rs +++ b/clippy_lints/src/loops.rs @@ -922,7 +922,7 @@ fn get_indexed_assignments<'a, 'tcx>( .chain(expr.as_ref().into_iter().map(|e| Some(get_assignment(cx, &*e, var)))) .filter_map(|op| op) .collect::>>() - .unwrap_or_else(|| vec![]) + .unwrap_or_default() } else { get_assignment(cx, body, var).into_iter().collect() } From 86b0dd419752788c8e63313c9c3ae19d27b3e8e4 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Wed, 1 Apr 2020 12:00:49 -0700 Subject: [PATCH 05/58] Downgrade option_option to pedantic --- clippy_lints/src/lib.rs | 3 +-- clippy_lints/src/types.rs | 2 +- src/lintlist/mod.rs | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 5d5b5d9a6da5..4235cd40a22e 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1125,6 +1125,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::CAST_SIGN_LOSS), LintId::of(&types::INVALID_UPCAST_COMPARISONS), LintId::of(&types::LINKEDLIST), + LintId::of(&types::OPTION_OPTION), LintId::of(&unicode::NON_ASCII_LITERAL), LintId::of(&unicode::UNICODE_NOT_NFC), LintId::of(&unused_self::UNUSED_SELF), @@ -1375,7 +1376,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(&types::IMPLICIT_HASHER), LintId::of(&types::LET_UNIT_VALUE), - LintId::of(&types::OPTION_OPTION), LintId::of(&types::TYPE_COMPLEXITY), LintId::of(&types::UNIT_ARG), LintId::of(&types::UNIT_CMP), @@ -1565,7 +1565,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&transmute::TRANSMUTE_PTR_TO_REF), LintId::of(&types::BORROWED_BOX), LintId::of(&types::CHAR_LIT_AS_U8), - LintId::of(&types::OPTION_OPTION), LintId::of(&types::TYPE_COMPLEXITY), LintId::of(&types::UNIT_ARG), LintId::of(&types::UNNECESSARY_CAST), diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 4ff2947378f8..7fae477b8327 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -108,7 +108,7 @@ declare_clippy_lint! { /// } /// ``` pub OPTION_OPTION, - complexity, + pedantic, "usage of `Option>`" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 3b89f5d19477..9d135beae4f3 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -1566,7 +1566,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "option_option", - group: "complexity", + group: "pedantic", desc: "usage of `Option>`", deprecation: None, module: "types", From 97acabe56aa89d24627f5a6ae29b57a3ff89a937 Mon Sep 17 00:00:00 2001 From: pmk21 Date: Thu, 2 Apr 2020 00:44:09 +0530 Subject: [PATCH 06/58] Test for ignoring let_underscore_must_use --- tests/ui/let_underscore_must_use.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/ui/let_underscore_must_use.rs b/tests/ui/let_underscore_must_use.rs index 7f481542fa73..27dda606067a 100644 --- a/tests/ui/let_underscore_must_use.rs +++ b/tests/ui/let_underscore_must_use.rs @@ -88,4 +88,7 @@ fn main() { let _ = a.map(|_| ()); let _ = a; + + #[allow(clippy::let_underscore_must_use)] + let _ = a; } From f6e8da81f184efb4036db16940ef3bfc84a29984 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Wed, 1 Apr 2020 12:15:21 -0700 Subject: [PATCH 07/58] Update option_option ui test --- tests/ui/option_option.rs | 2 ++ tests/ui/option_option.stderr | 24 ++++++++++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/tests/ui/option_option.rs b/tests/ui/option_option.rs index e2e649a81087..904c50e14039 100644 --- a/tests/ui/option_option.rs +++ b/tests/ui/option_option.rs @@ -1,3 +1,5 @@ +#![deny(clippy::option_option)] + fn input(_: Option>) {} fn output() -> Option> { diff --git a/tests/ui/option_option.stderr b/tests/ui/option_option.stderr index 9e9425cf9540..79db186d7ea7 100644 --- a/tests/ui/option_option.stderr +++ b/tests/ui/option_option.stderr @@ -1,55 +1,59 @@ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:1:13 + --> $DIR/option_option.rs:3:13 | LL | fn input(_: Option>) {} | ^^^^^^^^^^^^^^^^^^ | - = note: `-D clippy::option-option` implied by `-D warnings` +note: the lint level is defined here + --> $DIR/option_option.rs:1:9 + | +LL | #![deny(clippy::option_option)] + | ^^^^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:3:16 + --> $DIR/option_option.rs:5:16 | LL | fn output() -> Option> { | ^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:7:27 + --> $DIR/option_option.rs:9:27 | LL | fn output_nested() -> Vec>> { | ^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:12:30 + --> $DIR/option_option.rs:14:30 | LL | fn output_nested_nested() -> Option>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:17:8 + --> $DIR/option_option.rs:19:8 | LL | x: Option>, | ^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:21:23 + --> $DIR/option_option.rs:23:23 | LL | fn struct_fn() -> Option> { | ^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:27:22 + --> $DIR/option_option.rs:29:22 | LL | fn trait_fn() -> Option>; | ^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:31:11 + --> $DIR/option_option.rs:33:11 | LL | Tuple(Option>), | ^^^^^^^^^^^^^^^^^^ error: consider using `Option` instead of `Option>` or a custom enum if you need to distinguish all 3 cases - --> $DIR/option_option.rs:32:17 + --> $DIR/option_option.rs:34:17 | LL | Struct { x: Option> }, | ^^^^^^^^^^^^^^^^^^ From c9978b69bdd169777ec0befeeb75d2c7bd560526 Mon Sep 17 00:00:00 2001 From: pmk21 Date: Thu, 2 Apr 2020 00:48:16 +0530 Subject: [PATCH 08/58] Allow let_underscore --- clippy_lints/src/let_underscore.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/clippy_lints/src/let_underscore.rs b/clippy_lints/src/let_underscore.rs index 1f5a6b77ed31..a68f7edd8370 100644 --- a/clippy_lints/src/let_underscore.rs +++ b/clippy_lints/src/let_underscore.rs @@ -1,5 +1,5 @@ use if_chain::if_chain; -use rustc_hir::{PatKind, Stmt, StmtKind}; +use rustc_hir::{Local, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -66,13 +66,12 @@ const SYNC_GUARD_PATHS: [&[&str]; 3] = [ ]; impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { - fn check_stmt(&mut self, cx: &LateContext<'_, '_>, stmt: &Stmt<'_>) { - if in_external_macro(cx.tcx.sess, stmt.span) { + fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local<'_>) { + if in_external_macro(cx.tcx.sess, local.span) { return; } if_chain! { - if let StmtKind::Local(ref local) = stmt.kind; if let PatKind::Wild = local.pat.kind; if let Some(ref init) = local.init; then { @@ -81,7 +80,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_LOCK, - stmt.span, + local.span, "non-binding let on a synchronization lock", "consider using an underscore-prefixed named \ binding or dropping explicitly with `std::mem::drop`" @@ -90,7 +89,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_MUST_USE, - stmt.span, + local.span, "non-binding let on an expression with `#[must_use]` type", "consider explicitly using expression value" ) @@ -98,7 +97,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { span_lint_and_help( cx, LET_UNDERSCORE_MUST_USE, - stmt.span, + local.span, "non-binding let on a result of a `#[must_use]` function", "consider explicitly using function result" ) From f8e892db5ecdc3bd684bddb109470987e422535a Mon Sep 17 00:00:00 2001 From: Jacek Pospychala Date: Thu, 12 Mar 2020 21:41:13 +0100 Subject: [PATCH 09/58] useless Rc>, Rc>, Rc<&T>, Box<&T> --- CHANGELOG.md | 1 + clippy_lints/src/lib.rs | 3 + clippy_lints/src/types.rs | 103 +++++++++++++++++++++++++-- clippy_lints/src/utils/paths.rs | 1 + src/lintlist/mod.rs | 7 ++ tests/ui/must_use_candidates.fixed | 2 +- tests/ui/must_use_candidates.rs | 2 +- tests/ui/redundant_allocation.fixed | 48 +++++++++++++ tests/ui/redundant_allocation.rs | 48 +++++++++++++ tests/ui/redundant_allocation.stderr | 52 ++++++++++++++ 10 files changed, 259 insertions(+), 8 deletions(-) create mode 100644 tests/ui/redundant_allocation.fixed create mode 100644 tests/ui/redundant_allocation.rs create mode 100644 tests/ui/redundant_allocation.stderr diff --git a/CHANGELOG.md b/CHANGELOG.md index f3b1073988b0..894aab21fb37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1433,6 +1433,7 @@ Released 2018-09-13 [`range_plus_one`]: https://rust-lang.github.io/rust-clippy/master/index.html#range_plus_one [`range_step_by_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#range_step_by_zero [`range_zip_with_len`]: https://rust-lang.github.io/rust-clippy/master/index.html#range_zip_with_len +[`redundant_allocation`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation [`redundant_clone`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone [`redundant_closure`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure [`redundant_closure_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure_call diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 4235cd40a22e..dfc2a26b06b2 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -811,6 +811,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &types::LET_UNIT_VALUE, &types::LINKEDLIST, &types::OPTION_OPTION, + &types::REDUNDANT_ALLOCATION, &types::TYPE_COMPLEXITY, &types::UNIT_ARG, &types::UNIT_CMP, @@ -1376,6 +1377,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(&types::IMPLICIT_HASHER), LintId::of(&types::LET_UNIT_VALUE), + LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&types::TYPE_COMPLEXITY), LintId::of(&types::UNIT_ARG), LintId::of(&types::UNIT_CMP), @@ -1660,6 +1662,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&slow_vector_initialization::SLOW_VECTOR_INITIALIZATION), LintId::of(&trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF), LintId::of(&types::BOX_VEC), + LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&vec::USELESS_VEC), ]); diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 7fae477b8327..b21c37392659 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -171,11 +171,35 @@ declare_clippy_lint! { "a borrow of a boxed type" } +declare_clippy_lint! { + /// **What it does:** Checks for use of redundant allocations anywhere in the code. + /// + /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc>`, `Rc>`, `Box<&T>` + /// add an unnecessary level of indirection. + /// + /// **Known problems:** None. + /// + /// **Example:** + /// ```rust + /// # use std::rc::Rc; + /// fn foo(bar: Rc<&usize>) {} + /// ``` + /// + /// Better: + /// + /// ```rust + /// fn foo(bar: &usize) {} + /// ``` + pub REDUNDANT_ALLOCATION, + perf, + "redundant allocation" +} + pub struct Types { vec_box_size_threshold: u64, } -impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX]); +impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types { fn check_fn( @@ -217,7 +241,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types { } /// Checks if `qpath` has last segment with type parameter matching `path` -fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&str]) -> bool { +fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&str]) -> Option { let last = last_path_segment(qpath); if_chain! { if let Some(ref params) = last.args; @@ -230,10 +254,27 @@ fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&st if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id(); if match_def_path(cx, did, path); then { - return true; + return Some(ty.span); } } - false + None +} + +fn match_borrows_parameter(_cx: &LateContext<'_, '_>, qpath: &QPath<'_>) -> Option { + let last = last_path_segment(qpath); + if_chain! { + if let Some(ref params) = last.args; + if !params.parenthesized; + if let Some(ty) = params.args.iter().find_map(|arg| match arg { + GenericArg::Type(ty) => Some(ty), + _ => None, + }); + if let TyKind::Rptr(..) = ty.kind; + then { + return Some(ty.span); + } + } + None } impl Types { @@ -257,6 +298,7 @@ impl Types { /// The parameter `is_local` distinguishes the context of the type; types from /// local bindings should only be checked for the `BORROWED_BOX` lint. #[allow(clippy::too_many_lines)] + #[allow(clippy::cognitive_complexity)] fn check_ty(&mut self, cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool) { if hir_ty.span.from_expansion() { return; @@ -267,7 +309,19 @@ impl Types { let res = qpath_res(cx, qpath, hir_id); if let Some(def_id) = res.opt_def_id() { if Some(def_id) == cx.tcx.lang_items().owned_box() { - if match_type_parameter(cx, qpath, &paths::VEC) { + if let Some(span) = match_borrows_parameter(cx, qpath) { + span_lint_and_sugg( + cx, + REDUNDANT_ALLOCATION, + hir_ty.span, + "usage of `Box<&T>`", + "try", + snippet(cx, span, "..").to_string(), + Applicability::MachineApplicable, + ); + return; // don't recurse into the type + } + if match_type_parameter(cx, qpath, &paths::VEC).is_some() { span_lint_and_help( cx, BOX_VEC, @@ -277,6 +331,43 @@ impl Types { ); return; // don't recurse into the type } + } else if Some(def_id) == cx.tcx.lang_items().rc() { + if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) { + span_lint_and_sugg( + cx, + REDUNDANT_ALLOCATION, + hir_ty.span, + "usage of `Rc>`", + "try", + snippet(cx, span, "..").to_string(), + Applicability::MachineApplicable, + ); + return; // don't recurse into the type + } + if let Some(span) = match_type_parameter(cx, qpath, &paths::BOX) { + span_lint_and_sugg( + cx, + REDUNDANT_ALLOCATION, + hir_ty.span, + "usage of `Rc>`", + "try", + snippet(cx, span, "..").to_string(), + Applicability::MachineApplicable, + ); + return; // don't recurse into the type + } + if let Some(span) = match_borrows_parameter(cx, qpath) { + span_lint_and_sugg( + cx, + REDUNDANT_ALLOCATION, + hir_ty.span, + "usage of `Rc<&T>`", + "try", + snippet(cx, span, "..").to_string(), + Applicability::MachineApplicable, + ); + return; // don't recurse into the type + } } else if cx.tcx.is_diagnostic_item(Symbol::intern("vec_type"), def_id) { if_chain! { // Get the _ part of Vec<_> @@ -314,7 +405,7 @@ impl Types { } } } else if match_def_path(cx, def_id, &paths::OPTION) { - if match_type_parameter(cx, qpath, &paths::OPTION) { + if match_type_parameter(cx, qpath, &paths::OPTION).is_some() { span_lint( cx, OPTION_OPTION, diff --git a/clippy_lints/src/utils/paths.rs b/clippy_lints/src/utils/paths.rs index d443d63cc186..b79ba345df4f 100644 --- a/clippy_lints/src/utils/paths.rs +++ b/clippy_lints/src/utils/paths.rs @@ -10,6 +10,7 @@ pub const BEGIN_PANIC: [&str; 3] = ["std", "panicking", "begin_panic"]; pub const BEGIN_PANIC_FMT: [&str; 3] = ["std", "panicking", "begin_panic_fmt"]; pub const BINARY_HEAP: [&str; 4] = ["alloc", "collections", "binary_heap", "BinaryHeap"]; pub const BORROW_TRAIT: [&str; 3] = ["core", "borrow", "Borrow"]; +pub const BOX: [&str; 3] = ["alloc", "boxed", "Box"]; pub const BTREEMAP: [&str; 5] = ["alloc", "collections", "btree", "map", "BTreeMap"]; pub const BTREEMAP_ENTRY: [&str; 5] = ["alloc", "collections", "btree", "map", "Entry"]; pub const BTREESET: [&str; 5] = ["alloc", "collections", "btree", "set", "BTreeSet"]; diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 9d135beae4f3..8a6d0af5f8a7 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -1725,6 +1725,13 @@ pub static ref ALL_LINTS: Vec = vec![ deprecation: None, module: "ranges", }, + Lint { + name: "redundant_allocation", + group: "perf", + desc: "redundant allocation", + deprecation: None, + module: "types", + }, Lint { name: "redundant_clone", group: "perf", diff --git a/tests/ui/must_use_candidates.fixed b/tests/ui/must_use_candidates.fixed index e2ceb8baded2..9556f6f82cc6 100644 --- a/tests/ui/must_use_candidates.fixed +++ b/tests/ui/must_use_candidates.fixed @@ -1,6 +1,6 @@ // run-rustfix #![feature(never_type)] -#![allow(unused_mut)] +#![allow(unused_mut, clippy::redundant_allocation)] #![warn(clippy::must_use_candidate)] use std::rc::Rc; use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/tests/ui/must_use_candidates.rs b/tests/ui/must_use_candidates.rs index 29ef8d1ed9c2..373242201710 100644 --- a/tests/ui/must_use_candidates.rs +++ b/tests/ui/must_use_candidates.rs @@ -1,6 +1,6 @@ // run-rustfix #![feature(never_type)] -#![allow(unused_mut)] +#![allow(unused_mut, clippy::redundant_allocation)] #![warn(clippy::must_use_candidate)] use std::rc::Rc; use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/tests/ui/redundant_allocation.fixed b/tests/ui/redundant_allocation.fixed new file mode 100644 index 000000000000..266358334587 --- /dev/null +++ b/tests/ui/redundant_allocation.fixed @@ -0,0 +1,48 @@ +// run-rustfix +#![warn(clippy::all)] +#![allow(clippy::boxed_local, clippy::needless_pass_by_value)] +#![allow(clippy::blacklisted_name, unused_variables, dead_code)] + +use std::boxed::Box; +use std::rc::Rc; + +pub struct MyStruct {} + +pub struct SubT { + foo: T, +} + +pub enum MyEnum { + One, + Two, +} + +// Rc<&T> + +pub fn test1(foo: &T) {} + +pub fn test2(foo: &MyStruct) {} + +pub fn test3(foo: &MyEnum) {} + +pub fn test4_neg(foo: Rc>) {} + +// Rc> + +pub fn test5(a: Rc) {} + +// Rc> + +pub fn test6(a: Box) {} + +// Box<&T> + +pub fn test7(foo: &T) {} + +pub fn test8(foo: &MyStruct) {} + +pub fn test9(foo: &MyEnum) {} + +pub fn test10_neg(foo: Box>) {} + +fn main() {} diff --git a/tests/ui/redundant_allocation.rs b/tests/ui/redundant_allocation.rs new file mode 100644 index 000000000000..677b3e56d4dc --- /dev/null +++ b/tests/ui/redundant_allocation.rs @@ -0,0 +1,48 @@ +// run-rustfix +#![warn(clippy::all)] +#![allow(clippy::boxed_local, clippy::needless_pass_by_value)] +#![allow(clippy::blacklisted_name, unused_variables, dead_code)] + +use std::boxed::Box; +use std::rc::Rc; + +pub struct MyStruct {} + +pub struct SubT { + foo: T, +} + +pub enum MyEnum { + One, + Two, +} + +// Rc<&T> + +pub fn test1(foo: Rc<&T>) {} + +pub fn test2(foo: Rc<&MyStruct>) {} + +pub fn test3(foo: Rc<&MyEnum>) {} + +pub fn test4_neg(foo: Rc>) {} + +// Rc> + +pub fn test5(a: Rc>) {} + +// Rc> + +pub fn test6(a: Rc>) {} + +// Box<&T> + +pub fn test7(foo: Box<&T>) {} + +pub fn test8(foo: Box<&MyStruct>) {} + +pub fn test9(foo: Box<&MyEnum>) {} + +pub fn test10_neg(foo: Box>) {} + +fn main() {} diff --git a/tests/ui/redundant_allocation.stderr b/tests/ui/redundant_allocation.stderr new file mode 100644 index 000000000000..eaa57ce3024b --- /dev/null +++ b/tests/ui/redundant_allocation.stderr @@ -0,0 +1,52 @@ +error: usage of `Rc<&T>` + --> $DIR/redundant_allocation.rs:22:22 + | +LL | pub fn test1(foo: Rc<&T>) {} + | ^^^^^^ help: try: `&T` + | + = note: `-D clippy::redundant-allocation` implied by `-D warnings` + +error: usage of `Rc<&T>` + --> $DIR/redundant_allocation.rs:24:19 + | +LL | pub fn test2(foo: Rc<&MyStruct>) {} + | ^^^^^^^^^^^^^ help: try: `&MyStruct` + +error: usage of `Rc<&T>` + --> $DIR/redundant_allocation.rs:26:19 + | +LL | pub fn test3(foo: Rc<&MyEnum>) {} + | ^^^^^^^^^^^ help: try: `&MyEnum` + +error: usage of `Rc>` + --> $DIR/redundant_allocation.rs:32:17 + | +LL | pub fn test5(a: Rc>) {} + | ^^^^^^^^^^^^ help: try: `Rc` + +error: usage of `Rc>` + --> $DIR/redundant_allocation.rs:36:17 + | +LL | pub fn test6(a: Rc>) {} + | ^^^^^^^^^^^^^ help: try: `Box` + +error: usage of `Box<&T>` + --> $DIR/redundant_allocation.rs:40:22 + | +LL | pub fn test7(foo: Box<&T>) {} + | ^^^^^^^ help: try: `&T` + +error: usage of `Box<&T>` + --> $DIR/redundant_allocation.rs:42:19 + | +LL | pub fn test8(foo: Box<&MyStruct>) {} + | ^^^^^^^^^^^^^^ help: try: `&MyStruct` + +error: usage of `Box<&T>` + --> $DIR/redundant_allocation.rs:44:19 + | +LL | pub fn test9(foo: Box<&MyEnum>) {} + | ^^^^^^^^^^^^ help: try: `&MyEnum` + +error: aborting due to 8 previous errors + From db3423f46a4e54f0f5aef16da2e263fee29770b5 Mon Sep 17 00:00:00 2001 From: Simon Farnsworth Date: Thu, 2 Apr 2020 10:03:15 +0100 Subject: [PATCH 10/58] Improve docs for option_option Hint about using tri-state enums to replace legitimate uses of `Option>` --- clippy_lints/src/types.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index b21c37392659..6b63f2b1f0a2 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -99,14 +99,32 @@ declare_clippy_lint! { /// represents an optional optional value which is logically the same thing as an optional /// value but has an unneeded extra level of wrapping. /// + /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases, + /// consider a custom `enum` instead, with clear names for each case. + /// /// **Known problems:** None. /// /// **Example** - /// ```rust - /// fn x() -> Option> { + /// ```rust,ignore + /// fn get_node_data(n: Node) -> Option> { /// None /// } /// ``` + /// + /// Better: + /// + /// ```rust,ignore + /// pub enum Contents { + /// Data(Vec), // Was Some(Some(Vec)) + /// NotYetFetched, // Was Some(None) + /// None, // Was None + /// } + /// + /// fn get_node_data(n: Node) -> Contents { + /// Contents::None + /// } + /// ``` + /// pub OPTION_OPTION, pedantic, "usage of `Option>`" From f3f1babc1b226bc0083f5941468025f5008f428b Mon Sep 17 00:00:00 2001 From: Simon Farnsworth Date: Thu, 2 Apr 2020 14:28:25 +0100 Subject: [PATCH 11/58] Update types.rs --- clippy_lints/src/types.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 6b63f2b1f0a2..2ec58c04cd62 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -106,7 +106,7 @@ declare_clippy_lint! { /// /// **Example** /// ```rust,ignore - /// fn get_node_data(n: Node) -> Option> { + /// fn get_data() -> Option> { /// None /// } /// ``` @@ -120,7 +120,7 @@ declare_clippy_lint! { /// None, // Was None /// } /// - /// fn get_node_data(n: Node) -> Contents { + /// fn get_data() -> Contents { /// Contents::None /// } /// ``` From 50ecc1254130d0d69a968f99c1aa8b150bf1662e Mon Sep 17 00:00:00 2001 From: Simon Farnsworth Date: Thu, 2 Apr 2020 14:29:08 +0100 Subject: [PATCH 12/58] Update types.rs --- clippy_lints/src/types.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 2ec58c04cd62..50a64516e4bd 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -105,7 +105,7 @@ declare_clippy_lint! { /// **Known problems:** None. /// /// **Example** - /// ```rust,ignore + /// ```rust /// fn get_data() -> Option> { /// None /// } @@ -113,7 +113,7 @@ declare_clippy_lint! { /// /// Better: /// - /// ```rust,ignore + /// ```rust /// pub enum Contents { /// Data(Vec), // Was Some(Some(Vec)) /// NotYetFetched, // Was Some(None) From 5f8b696e2e76374fe600ee0f0e444e94215239b6 Mon Sep 17 00:00:00 2001 From: Simon Farnsworth Date: Thu, 2 Apr 2020 14:30:13 +0100 Subject: [PATCH 13/58] Update clippy_lints/src/types.rs Co-Authored-By: Philipp Krones --- clippy_lints/src/types.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 50a64516e4bd..8c151f2277c1 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -124,7 +124,6 @@ declare_clippy_lint! { /// Contents::None /// } /// ``` - /// pub OPTION_OPTION, pedantic, "usage of `Option>`" From 98aa5938c434617109e2bf7bfeb21a2f44f61572 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Thu, 2 Apr 2020 22:29:41 +0200 Subject: [PATCH 14/58] Rustup to rust-lang/rust#70634 --- clippy_lints/src/escape.rs | 2 +- clippy_lints/src/large_enum_variant.rs | 2 +- clippy_lints/src/types.rs | 2 +- clippy_lints/src/utils/mod.rs | 16 ++++------------ 4 files changed, 7 insertions(+), 15 deletions(-) diff --git a/clippy_lints/src/escape.rs b/clippy_lints/src/escape.rs index 94c458cc6a66..1ec60a0e6e67 100644 --- a/clippy_lints/src/escape.rs +++ b/clippy_lints/src/escape.rs @@ -2,10 +2,10 @@ use rustc_hir::intravisit; use rustc_hir::{self, Body, FnDecl, HirId, HirIdSet, ItemKind, Node}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::source_map::Span; +use rustc_target::abi::LayoutOf; use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Place, PlaceBase}; use crate::utils::span_lint; diff --git a/clippy_lints/src/large_enum_variant.rs b/clippy_lints/src/large_enum_variant.rs index 429f7440510b..961a645a62e9 100644 --- a/clippy_lints/src/large_enum_variant.rs +++ b/clippy_lints/src/large_enum_variant.rs @@ -4,8 +4,8 @@ use crate::utils::{snippet_opt, span_lint_and_then}; use rustc_errors::Applicability; use rustc_hir::{Item, ItemKind, VariantData}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::layout::LayoutOf; use rustc_session::{declare_tool_lint, impl_lint_pass}; +use rustc_target::abi::LayoutOf; declare_clippy_lint! { /// **What it does:** Checks for large size differences between variants on diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 8c151f2277c1..271459bd1e94 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -17,12 +17,12 @@ use rustc_hir::{ use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TypeckTables}; use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass}; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::Span; use rustc_span::symbol::{sym, Symbol}; +use rustc_target::abi::LayoutOf; use rustc_target::spec::abi::Abi; use rustc_typeck::hir_ty_to_ty; diff --git a/clippy_lints/src/utils/mod.rs b/clippy_lints/src/utils/mod.rs index a2c6e0bbd249..315869e2aea3 100644 --- a/clippy_lints/src/utils/mod.rs +++ b/clippy_lints/src/utils/mod.rs @@ -41,16 +41,12 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, Level, Lint, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::traits; -use rustc_middle::ty::{ - self, - layout::{self, IntegerExt}, - subst::GenericArg, - Binder, Ty, TyCtxt, TypeFoldable, -}; +use rustc_middle::ty::{self, layout::IntegerExt, subst::GenericArg, Binder, Ty, TyCtxt, TypeFoldable}; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::original_sp; use rustc_span::symbol::{self, kw, Symbol}; use rustc_span::{BytePos, Pos, Span, DUMMY_SP}; +use rustc_target::abi::Integer; use rustc_trait_selection::traits::predicate_for_trait_def; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::query::normalize::AtExt; @@ -1080,9 +1076,7 @@ pub fn get_arg_name(pat: &Pat<'_>) -> Option { } pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 { - layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity)) - .size() - .bits() + Integer::from_attr(&tcx, attr::IntType::SignedInt(ity)).size().bits() } #[allow(clippy::cast_possible_wrap)] @@ -1101,9 +1095,7 @@ pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 { /// clip unused bytes pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 { - let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity)) - .size() - .bits(); + let bits = Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity)).size().bits(); let amt = 128 - bits; (u << amt) >> amt } From adcaa1b86ddbf51659d5f7e4e7471427682649ba Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 2 Apr 2020 18:22:18 -0700 Subject: [PATCH 15/58] Downgrade let_unit_value to pedantic --- clippy_lints/src/lib.rs | 3 +-- clippy_lints/src/types.rs | 2 +- src/lintlist/mod.rs | 2 +- tests/ui/doc_unsafe.rs | 1 - tests/ui/redundant_pattern_matching.fixed | 2 +- tests/ui/redundant_pattern_matching.rs | 2 +- tests/ui/uninit.rs | 1 - tests/ui/uninit.stderr | 4 ++-- 8 files changed, 7 insertions(+), 10 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfc2a26b06b2..84b89311fa0b 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1125,6 +1125,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::CAST_PRECISION_LOSS), LintId::of(&types::CAST_SIGN_LOSS), LintId::of(&types::INVALID_UPCAST_COMPARISONS), + LintId::of(&types::LET_UNIT_VALUE), LintId::of(&types::LINKEDLIST), LintId::of(&types::OPTION_OPTION), LintId::of(&unicode::NON_ASCII_LITERAL), @@ -1376,7 +1377,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::FN_TO_NUMERIC_CAST), LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(&types::IMPLICIT_HASHER), - LintId::of(&types::LET_UNIT_VALUE), LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&types::TYPE_COMPLEXITY), LintId::of(&types::UNIT_ARG), @@ -1489,7 +1489,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::FN_TO_NUMERIC_CAST), LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(&types::IMPLICIT_HASHER), - LintId::of(&types::LET_UNIT_VALUE), LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME), LintId::of(&write::PRINTLN_EMPTY_STRING), LintId::of(&write::PRINT_LITERAL), diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 8c151f2277c1..171852d41e36 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -593,7 +593,7 @@ declare_clippy_lint! { /// }; /// ``` pub LET_UNIT_VALUE, - style, + pedantic, "creating a `let` binding to a value of unit type, which usually can't be used afterwards" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 8a6d0af5f8a7..79e337f55307 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -999,7 +999,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "let_unit_value", - group: "style", + group: "pedantic", desc: "creating a `let` binding to a value of unit type, which usually can\'t be used afterwards", deprecation: None, module: "types", diff --git a/tests/ui/doc_unsafe.rs b/tests/ui/doc_unsafe.rs index c44f3c62a98e..484aa72d59a2 100644 --- a/tests/ui/doc_unsafe.rs +++ b/tests/ui/doc_unsafe.rs @@ -88,7 +88,6 @@ very_unsafe!(); // we don't lint code from external macros undocd_unsafe!(); -#[allow(clippy::let_unit_value)] fn main() { unsafe { you_dont_see_me(); diff --git a/tests/ui/redundant_pattern_matching.fixed b/tests/ui/redundant_pattern_matching.fixed index 776c9444566b..538fa1ed9cb0 100644 --- a/tests/ui/redundant_pattern_matching.fixed +++ b/tests/ui/redundant_pattern_matching.fixed @@ -2,7 +2,7 @@ #![warn(clippy::all)] #![warn(clippy::redundant_pattern_matching)] -#![allow(clippy::unit_arg, clippy::let_unit_value, unused_must_use)] +#![allow(clippy::unit_arg, unused_must_use)] fn main() { Ok::(42).is_ok(); diff --git a/tests/ui/redundant_pattern_matching.rs b/tests/ui/redundant_pattern_matching.rs index 2b2d5b1c1ec6..34d2cd62e54e 100644 --- a/tests/ui/redundant_pattern_matching.rs +++ b/tests/ui/redundant_pattern_matching.rs @@ -2,7 +2,7 @@ #![warn(clippy::all)] #![warn(clippy::redundant_pattern_matching)] -#![allow(clippy::unit_arg, clippy::let_unit_value, unused_must_use)] +#![allow(clippy::unit_arg, unused_must_use)] fn main() { if let Ok(_) = Ok::(42) {} diff --git a/tests/ui/uninit.rs b/tests/ui/uninit.rs index a4424c490e70..f42b884e0f0e 100644 --- a/tests/ui/uninit.rs +++ b/tests/ui/uninit.rs @@ -2,7 +2,6 @@ use std::mem::MaybeUninit; -#[allow(clippy::let_unit_value)] fn main() { let _: usize = unsafe { MaybeUninit::uninit().assume_init() }; diff --git a/tests/ui/uninit.stderr b/tests/ui/uninit.stderr index f4c45354aefe..a37233ecddae 100644 --- a/tests/ui/uninit.stderr +++ b/tests/ui/uninit.stderr @@ -1,5 +1,5 @@ error: this call for this type may be undefined behavior - --> $DIR/uninit.rs:7:29 + --> $DIR/uninit.rs:6:29 | LL | let _: usize = unsafe { MaybeUninit::uninit().assume_init() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,7 +7,7 @@ LL | let _: usize = unsafe { MaybeUninit::uninit().assume_init() }; = note: `#[deny(clippy::uninit_assumed_init)]` on by default error: this call for this type may be undefined behavior - --> $DIR/uninit.rs:10:31 + --> $DIR/uninit.rs:9:31 | LL | let _: [u8; 0] = unsafe { MaybeUninit::uninit().assume_init() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From 94154cad20d4687461fcbb4901a1252576329d13 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 2 Apr 2020 18:46:01 -0700 Subject: [PATCH 16/58] Downgrade trivially_copy_pass_by_ref to pedantic --- clippy_lints/src/lib.rs | 3 +- .../src/trivially_copy_pass_by_ref.rs | 2 +- src/lintlist/mod.rs | 2 +- tests/ui-toml/toml_trivially_copy/test.rs | 1 + tests/ui-toml/toml_trivially_copy/test.stderr | 10 ++++-- tests/ui/clone_on_copy_mut.rs | 1 - tests/ui/debug_assert_with_mut_call.rs | 2 +- tests/ui/eta.fixed | 3 +- tests/ui/eta.rs | 3 +- tests/ui/eta.stderr | 24 ++++++------- tests/ui/extra_unused_lifetimes.rs | 3 +- tests/ui/extra_unused_lifetimes.stderr | 8 ++--- tests/ui/float_arithmetic.rs | 3 +- tests/ui/float_arithmetic.stderr | 34 +++++++++--------- tests/ui/infinite_iter.rs | 1 - tests/ui/infinite_iter.stderr | 32 ++++++++--------- tests/ui/infinite_loop.rs | 2 -- tests/ui/infinite_loop.stderr | 22 ++++++------ tests/ui/integer_arithmetic.rs | 3 +- tests/ui/integer_arithmetic.stderr | 34 +++++++++--------- tests/ui/mut_from_ref.rs | 2 +- tests/ui/mut_reference.rs | 2 +- tests/ui/needless_borrow.fixed | 1 - tests/ui/needless_borrow.rs | 1 - tests/ui/needless_borrow.stderr | 8 ++--- tests/ui/needless_lifetimes.rs | 2 +- tests/ui/new_ret_no_self.rs | 2 +- tests/ui/trivially_copy_pass_by_ref.rs | 1 + tests/ui/trivially_copy_pass_by_ref.stderr | 36 ++++++++++--------- tests/ui/useless_asref.fixed | 1 - tests/ui/useless_asref.rs | 1 - tests/ui/useless_asref.stderr | 22 ++++++------ tests/ui/wrong_self_convention.rs | 2 +- 33 files changed, 135 insertions(+), 139 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfc2a26b06b2..ece9efded461 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1119,6 +1119,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&shadow::SHADOW_UNRELATED), LintId::of(&strings::STRING_ADD_ASSIGN), LintId::of(&trait_bounds::TYPE_REPETITION_IN_BOUNDS), + LintId::of(&trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF), LintId::of(&types::CAST_LOSSLESS), LintId::of(&types::CAST_POSSIBLE_TRUNCATION), LintId::of(&types::CAST_POSSIBLE_WRAP), @@ -1365,7 +1366,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&transmute::UNSOUND_COLLECTION_TRANSMUTE), LintId::of(&transmute::WRONG_TRANSMUTE), LintId::of(&transmuting_null::TRANSMUTING_NULL), - LintId::of(&trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF), LintId::of(&try_err::TRY_ERR), LintId::of(&types::ABSURD_EXTREME_COMPARISONS), LintId::of(&types::BORROWED_BOX), @@ -1660,7 +1660,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&mutex_atomic::MUTEX_ATOMIC), LintId::of(&redundant_clone::REDUNDANT_CLONE), LintId::of(&slow_vector_initialization::SLOW_VECTOR_INITIALIZATION), - LintId::of(&trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF), LintId::of(&types::BOX_VEC), LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&vec::USELESS_VEC), diff --git a/clippy_lints/src/trivially_copy_pass_by_ref.rs b/clippy_lints/src/trivially_copy_pass_by_ref.rs index 52b07fb34017..2c101220c5d6 100644 --- a/clippy_lints/src/trivially_copy_pass_by_ref.rs +++ b/clippy_lints/src/trivially_copy_pass_by_ref.rs @@ -49,7 +49,7 @@ declare_clippy_lint! { /// fn foo(v: u32) {} /// ``` pub TRIVIALLY_COPY_PASS_BY_REF, - perf, + pedantic, "functions taking small copyable arguments by reference" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 8a6d0af5f8a7..62e7fe42110f 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -2161,7 +2161,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "trivially_copy_pass_by_ref", - group: "perf", + group: "pedantic", desc: "functions taking small copyable arguments by reference", deprecation: None, module: "trivially_copy_pass_by_ref", diff --git a/tests/ui-toml/toml_trivially_copy/test.rs b/tests/ui-toml/toml_trivially_copy/test.rs index 6dcbae040750..19019a254163 100644 --- a/tests/ui-toml/toml_trivially_copy/test.rs +++ b/tests/ui-toml/toml_trivially_copy/test.rs @@ -1,6 +1,7 @@ // 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::many_single_char_names)] #[derive(Copy, Clone)] diff --git a/tests/ui-toml/toml_trivially_copy/test.stderr b/tests/ui-toml/toml_trivially_copy/test.stderr index d2b55eff16db..912761a8f009 100644 --- a/tests/ui-toml/toml_trivially_copy/test.stderr +++ b/tests/ui-toml/toml_trivially_copy/test.stderr @@ -1,13 +1,17 @@ error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> $DIR/test.rs:14:11 + --> $DIR/test.rs:15:11 | LL | fn bad(x: &u16, y: &Foo) {} | ^^^^ help: consider passing by value instead: `u16` | - = note: `-D clippy::trivially-copy-pass-by-ref` implied by `-D warnings` +note: the lint level is defined here + --> $DIR/test.rs:4:9 + | +LL | #![deny(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) - --> $DIR/test.rs:14:20 + --> $DIR/test.rs:15:20 | LL | fn bad(x: &u16, y: &Foo) {} | ^^^^ help: consider passing by value instead: `Foo` diff --git a/tests/ui/clone_on_copy_mut.rs b/tests/ui/clone_on_copy_mut.rs index 3cbbcb7c0830..5bfa256623b6 100644 --- a/tests/ui/clone_on_copy_mut.rs +++ b/tests/ui/clone_on_copy_mut.rs @@ -5,7 +5,6 @@ pub fn dec_read_dec(i: &mut i32) -> i32 { ret } -#[allow(clippy::trivially_copy_pass_by_ref)] pub fn minus_1(i: &i32) -> i32 { dec_read_dec(&mut i.clone()) } diff --git a/tests/ui/debug_assert_with_mut_call.rs b/tests/ui/debug_assert_with_mut_call.rs index 3db7e0164fa4..b061fff6b9e9 100644 --- a/tests/ui/debug_assert_with_mut_call.rs +++ b/tests/ui/debug_assert_with_mut_call.rs @@ -2,7 +2,7 @@ #![feature(custom_inner_attributes)] #![rustfmt::skip] #![warn(clippy::debug_assert_with_mut_call)] -#![allow(clippy::trivially_copy_pass_by_ref, clippy::cognitive_complexity, clippy::redundant_closure_call)] +#![allow(clippy::cognitive_complexity, clippy::redundant_closure_call)] struct S; diff --git a/tests/ui/eta.fixed b/tests/ui/eta.fixed index 5d62a6d9b01e..1b34c2f74eba 100644 --- a/tests/ui/eta.fixed +++ b/tests/ui/eta.fixed @@ -6,8 +6,7 @@ clippy::redundant_closure_call, clippy::many_single_char_names, clippy::needless_pass_by_value, - clippy::option_map_unit_fn, - clippy::trivially_copy_pass_by_ref + clippy::option_map_unit_fn )] #![warn( clippy::redundant_closure, diff --git a/tests/ui/eta.rs b/tests/ui/eta.rs index a9c4b209960c..4f050bd8479a 100644 --- a/tests/ui/eta.rs +++ b/tests/ui/eta.rs @@ -6,8 +6,7 @@ clippy::redundant_closure_call, clippy::many_single_char_names, clippy::needless_pass_by_value, - clippy::option_map_unit_fn, - clippy::trivially_copy_pass_by_ref + clippy::option_map_unit_fn )] #![warn( clippy::redundant_closure, diff --git a/tests/ui/eta.stderr b/tests/ui/eta.stderr index d19d21eec0db..c4713ca8083d 100644 --- a/tests/ui/eta.stderr +++ b/tests/ui/eta.stderr @@ -1,5 +1,5 @@ error: redundant closure found - --> $DIR/eta.rs:21:27 + --> $DIR/eta.rs:20:27 | LL | let a = Some(1u8).map(|a| foo(a)); | ^^^^^^^^^^ help: remove closure as shown: `foo` @@ -7,13 +7,13 @@ LL | let a = Some(1u8).map(|a| foo(a)); = note: `-D clippy::redundant-closure` implied by `-D warnings` error: redundant closure found - --> $DIR/eta.rs:22:10 + --> $DIR/eta.rs:21:10 | LL | meta(|a| foo(a)); | ^^^^^^^^^^ help: remove closure as shown: `foo` error: this expression borrows a reference that is immediately dereferenced by the compiler - --> $DIR/eta.rs:25:21 + --> $DIR/eta.rs:24:21 | LL | all(&[1, 2, 3], &&2, |x, y| below(x, y)); //is adjusted | ^^^ help: change this to: `&2` @@ -21,13 +21,13 @@ LL | all(&[1, 2, 3], &&2, |x, y| below(x, y)); //is adjusted = note: `-D clippy::needless-borrow` implied by `-D warnings` error: redundant closure found - --> $DIR/eta.rs:32:27 + --> $DIR/eta.rs:31:27 | LL | let e = Some(1u8).map(|a| generic(a)); | ^^^^^^^^^^^^^^ help: remove closure as shown: `generic` error: redundant closure found - --> $DIR/eta.rs:75:51 + --> $DIR/eta.rs:74:51 | LL | let e = Some(TestStruct { some_ref: &i }).map(|a| a.foo()); | ^^^^^^^^^^^ help: remove closure as shown: `TestStruct::foo` @@ -35,43 +35,43 @@ LL | let e = Some(TestStruct { some_ref: &i }).map(|a| a.foo()); = note: `-D clippy::redundant-closure-for-method-calls` implied by `-D warnings` error: redundant closure found - --> $DIR/eta.rs:77:51 + --> $DIR/eta.rs:76:51 | LL | let e = Some(TestStruct { some_ref: &i }).map(|a| a.trait_foo()); | ^^^^^^^^^^^^^^^^^ help: remove closure as shown: `TestTrait::trait_foo` error: redundant closure found - --> $DIR/eta.rs:80:42 + --> $DIR/eta.rs:79:42 | LL | let e = Some(&mut vec![1, 2, 3]).map(|v| v.clear()); | ^^^^^^^^^^^^^ help: remove closure as shown: `std::vec::Vec::clear` error: redundant closure found - --> $DIR/eta.rs:85:29 + --> $DIR/eta.rs:84:29 | LL | let e = Some("str").map(|s| s.to_string()); | ^^^^^^^^^^^^^^^^^ help: remove closure as shown: `std::string::ToString::to_string` error: redundant closure found - --> $DIR/eta.rs:87:27 + --> $DIR/eta.rs:86:27 | LL | let e = Some('a').map(|s| s.to_uppercase()); | ^^^^^^^^^^^^^^^^^^^^ help: remove closure as shown: `char::to_uppercase` error: redundant closure found - --> $DIR/eta.rs:90:65 + --> $DIR/eta.rs:89:65 | LL | let e: std::vec::Vec = vec!['a', 'b', 'c'].iter().map(|c| c.to_ascii_uppercase()).collect(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove closure as shown: `char::to_ascii_uppercase` error: redundant closure found - --> $DIR/eta.rs:173:27 + --> $DIR/eta.rs:172:27 | LL | let a = Some(1u8).map(|a| foo_ptr(a)); | ^^^^^^^^^^^^^^ help: remove closure as shown: `foo_ptr` error: redundant closure found - --> $DIR/eta.rs:178:27 + --> $DIR/eta.rs:177:27 | LL | let a = Some(1u8).map(|a| closure(a)); | ^^^^^^^^^^^^^^ help: remove closure as shown: `closure` diff --git a/tests/ui/extra_unused_lifetimes.rs b/tests/ui/extra_unused_lifetimes.rs index ba95fd63bf9a..26df71ddcb0f 100644 --- a/tests/ui/extra_unused_lifetimes.rs +++ b/tests/ui/extra_unused_lifetimes.rs @@ -2,8 +2,7 @@ unused, dead_code, clippy::needless_lifetimes, - clippy::needless_pass_by_value, - clippy::trivially_copy_pass_by_ref + clippy::needless_pass_by_value )] #![warn(clippy::extra_unused_lifetimes)] diff --git a/tests/ui/extra_unused_lifetimes.stderr b/tests/ui/extra_unused_lifetimes.stderr index ebdb8e749520..e997951346f7 100644 --- a/tests/ui/extra_unused_lifetimes.stderr +++ b/tests/ui/extra_unused_lifetimes.stderr @@ -1,5 +1,5 @@ error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:14:14 + --> $DIR/extra_unused_lifetimes.rs:13:14 | LL | fn unused_lt<'a>(x: u8) {} | ^^ @@ -7,19 +7,19 @@ LL | fn unused_lt<'a>(x: u8) {} = note: `-D clippy::extra-unused-lifetimes` implied by `-D warnings` error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:16:25 + --> $DIR/extra_unused_lifetimes.rs:15:25 | LL | fn unused_lt_transitive<'a, 'b: 'a>(x: &'b u8) { | ^^ error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:41:10 + --> $DIR/extra_unused_lifetimes.rs:40:10 | LL | fn x<'a>(&self) {} | ^^ error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:67:22 + --> $DIR/extra_unused_lifetimes.rs:66:22 | LL | fn unused_lt<'a>(x: u8) {} | ^^ diff --git a/tests/ui/float_arithmetic.rs b/tests/ui/float_arithmetic.rs index 5ad320c62095..60fa7569eb9d 100644 --- a/tests/ui/float_arithmetic.rs +++ b/tests/ui/float_arithmetic.rs @@ -5,8 +5,7 @@ clippy::shadow_unrelated, clippy::no_effect, clippy::unnecessary_operation, - clippy::op_ref, - clippy::trivially_copy_pass_by_ref + clippy::op_ref )] #[rustfmt::skip] diff --git a/tests/ui/float_arithmetic.stderr b/tests/ui/float_arithmetic.stderr index 809392529fd9..1ceffb35beed 100644 --- a/tests/ui/float_arithmetic.stderr +++ b/tests/ui/float_arithmetic.stderr @@ -1,5 +1,5 @@ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:16:5 + --> $DIR/float_arithmetic.rs:15:5 | LL | f * 2.0; | ^^^^^^^ @@ -7,97 +7,97 @@ LL | f * 2.0; = note: `-D clippy::float-arithmetic` implied by `-D warnings` error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:18:5 + --> $DIR/float_arithmetic.rs:17:5 | LL | 1.0 + f; | ^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:19:5 + --> $DIR/float_arithmetic.rs:18:5 | LL | f * 2.0; | ^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:20:5 + --> $DIR/float_arithmetic.rs:19:5 | LL | f / 2.0; | ^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:21:5 + --> $DIR/float_arithmetic.rs:20:5 | LL | f - 2.0 * 4.2; | ^^^^^^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:22:5 + --> $DIR/float_arithmetic.rs:21:5 | LL | -f; | ^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:24:5 + --> $DIR/float_arithmetic.rs:23:5 | LL | f += 1.0; | ^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:25:5 + --> $DIR/float_arithmetic.rs:24:5 | LL | f -= 1.0; | ^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:26:5 + --> $DIR/float_arithmetic.rs:25:5 | LL | f *= 2.0; | ^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:27:5 + --> $DIR/float_arithmetic.rs:26:5 | LL | f /= 2.0; | ^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:33:5 + --> $DIR/float_arithmetic.rs:32:5 | LL | 3.1_f32 + &1.2_f32; | ^^^^^^^^^^^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:34:5 + --> $DIR/float_arithmetic.rs:33:5 | LL | &3.4_f32 + 1.5_f32; | ^^^^^^^^^^^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:35:5 + --> $DIR/float_arithmetic.rs:34:5 | LL | &3.5_f32 + &1.3_f32; | ^^^^^^^^^^^^^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:40:5 + --> $DIR/float_arithmetic.rs:39:5 | LL | a + f | ^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:44:5 + --> $DIR/float_arithmetic.rs:43:5 | LL | f1 + f2 | ^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:48:5 + --> $DIR/float_arithmetic.rs:47:5 | LL | f1 + f2 | ^^^^^^^ error: floating-point arithmetic detected - --> $DIR/float_arithmetic.rs:52:5 + --> $DIR/float_arithmetic.rs:51:5 | LL | (&f1 + &f2) | ^^^^^^^^^^^ diff --git a/tests/ui/infinite_iter.rs b/tests/ui/infinite_iter.rs index c324eb957776..1fe688977659 100644 --- a/tests/ui/infinite_iter.rs +++ b/tests/ui/infinite_iter.rs @@ -1,5 +1,4 @@ use std::iter::repeat; -#[allow(clippy::trivially_copy_pass_by_ref)] fn square_is_lower_64(x: &u32) -> bool { x * x < 64 } diff --git a/tests/ui/infinite_iter.stderr b/tests/ui/infinite_iter.stderr index 4750316d3f4e..5f5e7ac9f253 100644 --- a/tests/ui/infinite_iter.stderr +++ b/tests/ui/infinite_iter.stderr @@ -1,29 +1,29 @@ error: infinite iteration detected - --> $DIR/infinite_iter.rs:10:5 + --> $DIR/infinite_iter.rs:9:5 | LL | repeat(0_u8).collect::>(); // infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: the lint level is defined here - --> $DIR/infinite_iter.rs:8:8 + --> $DIR/infinite_iter.rs:7:8 | LL | #[deny(clippy::infinite_iter)] | ^^^^^^^^^^^^^^^^^^^^^ error: infinite iteration detected - --> $DIR/infinite_iter.rs:11:5 + --> $DIR/infinite_iter.rs:10:5 | LL | (0..8_u32).take_while(square_is_lower_64).cycle().count(); // infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: infinite iteration detected - --> $DIR/infinite_iter.rs:12:5 + --> $DIR/infinite_iter.rs:11:5 | LL | (0..8_u64).chain(0..).max(); // infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: infinite iteration detected - --> $DIR/infinite_iter.rs:17:5 + --> $DIR/infinite_iter.rs:16:5 | LL | / (0..8_u32) LL | | .rev() @@ -33,37 +33,37 @@ LL | | .for_each(|x| println!("{}", x)); // infinite iter | |________________________________________^ error: infinite iteration detected - --> $DIR/infinite_iter.rs:23:5 + --> $DIR/infinite_iter.rs:22:5 | LL | (0_usize..).flat_map(|x| 0..x).product::(); // infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: infinite iteration detected - --> $DIR/infinite_iter.rs:24:5 + --> $DIR/infinite_iter.rs:23:5 | LL | (0_u64..).filter(|x| x % 2 == 0).last(); // infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: possible infinite iteration detected - --> $DIR/infinite_iter.rs:31:5 + --> $DIR/infinite_iter.rs:30:5 | LL | (0..).zip((0..).take_while(square_is_lower_64)).count(); // maybe infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: the lint level is defined here - --> $DIR/infinite_iter.rs:29:8 + --> $DIR/infinite_iter.rs:28:8 | LL | #[deny(clippy::maybe_infinite_iter)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: possible infinite iteration detected - --> $DIR/infinite_iter.rs:32:5 + --> $DIR/infinite_iter.rs:31:5 | LL | repeat(42).take_while(|x| *x == 42).chain(0..42).max(); // maybe infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: possible infinite iteration detected - --> $DIR/infinite_iter.rs:33:5 + --> $DIR/infinite_iter.rs:32:5 | LL | / (1..) LL | | .scan(0, |state, x| { @@ -74,31 +74,31 @@ LL | | .min(); // maybe infinite iter | |______________^ error: possible infinite iteration detected - --> $DIR/infinite_iter.rs:39:5 + --> $DIR/infinite_iter.rs:38:5 | LL | (0..).find(|x| *x == 24); // maybe infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^ error: possible infinite iteration detected - --> $DIR/infinite_iter.rs:40:5 + --> $DIR/infinite_iter.rs:39:5 | LL | (0..).position(|x| x == 24); // maybe infinite iter | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: possible infinite iteration detected - --> $DIR/infinite_iter.rs:41:5 + --> $DIR/infinite_iter.rs:40:5 | LL | (0..).any(|x| x == 24); // maybe infinite iter | ^^^^^^^^^^^^^^^^^^^^^^ error: possible infinite iteration detected - --> $DIR/infinite_iter.rs:42:5 + --> $DIR/infinite_iter.rs:41:5 | LL | (0..).all(|x| x == 24); // maybe infinite iter | ^^^^^^^^^^^^^^^^^^^^^^ error: infinite iteration detected - --> $DIR/infinite_iter.rs:65:31 + --> $DIR/infinite_iter.rs:64:31 | LL | let _: HashSet = (0..).collect(); // Infinite iter | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/infinite_loop.rs b/tests/ui/infinite_loop.rs index 09f47adc46e6..72591f12baf8 100644 --- a/tests/ui/infinite_loop.rs +++ b/tests/ui/infinite_loop.rs @@ -1,5 +1,3 @@ -#![allow(clippy::trivially_copy_pass_by_ref)] - fn fn_val(i: i32) -> i32 { unimplemented!() } diff --git a/tests/ui/infinite_loop.stderr b/tests/ui/infinite_loop.stderr index 2736753c14b6..1fcb29eff18e 100644 --- a/tests/ui/infinite_loop.stderr +++ b/tests/ui/infinite_loop.stderr @@ -1,5 +1,5 @@ error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:23:11 + --> $DIR/infinite_loop.rs:21:11 | LL | while y < 10 { | ^^^^^^ @@ -8,7 +8,7 @@ LL | while y < 10 { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:28:11 + --> $DIR/infinite_loop.rs:26:11 | LL | while y < 10 && x < 3 { | ^^^^^^^^^^^^^^^ @@ -16,7 +16,7 @@ LL | while y < 10 && x < 3 { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:35:11 + --> $DIR/infinite_loop.rs:33:11 | LL | while !cond { | ^^^^^ @@ -24,7 +24,7 @@ LL | while !cond { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:79:11 + --> $DIR/infinite_loop.rs:77:11 | LL | while i < 3 { | ^^^^^ @@ -32,7 +32,7 @@ LL | while i < 3 { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:84:11 + --> $DIR/infinite_loop.rs:82:11 | LL | while i < 3 && j > 0 { | ^^^^^^^^^^^^^^ @@ -40,7 +40,7 @@ LL | while i < 3 && j > 0 { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:88:11 + --> $DIR/infinite_loop.rs:86:11 | LL | while i < 3 { | ^^^^^ @@ -48,7 +48,7 @@ LL | while i < 3 { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:103:11 + --> $DIR/infinite_loop.rs:101:11 | LL | while i < 3 { | ^^^^^ @@ -56,7 +56,7 @@ LL | while i < 3 { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:108:11 + --> $DIR/infinite_loop.rs:106:11 | LL | while i < 3 { | ^^^^^ @@ -64,7 +64,7 @@ LL | while i < 3 { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:174:15 + --> $DIR/infinite_loop.rs:172:15 | LL | while self.count < n { | ^^^^^^^^^^^^^^ @@ -72,7 +72,7 @@ LL | while self.count < n { = note: this may lead to an infinite or to a never running loop error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:182:11 + --> $DIR/infinite_loop.rs:180:11 | LL | while y < 10 { | ^^^^^^ @@ -82,7 +82,7 @@ LL | while y < 10 { = help: rewrite it as `if cond { loop { } }` error: variables in the condition are not mutated in the loop body - --> $DIR/infinite_loop.rs:189:11 + --> $DIR/infinite_loop.rs:187:11 | LL | while y < 10 { | ^^^^^^ diff --git a/tests/ui/integer_arithmetic.rs b/tests/ui/integer_arithmetic.rs index 31a07e7c35b0..2fe32c6ace87 100644 --- a/tests/ui/integer_arithmetic.rs +++ b/tests/ui/integer_arithmetic.rs @@ -5,8 +5,7 @@ clippy::shadow_unrelated, clippy::no_effect, clippy::unnecessary_operation, - clippy::op_ref, - clippy::trivially_copy_pass_by_ref + clippy::op_ref )] #[rustfmt::skip] diff --git a/tests/ui/integer_arithmetic.stderr b/tests/ui/integer_arithmetic.stderr index 0b8d0b767bf8..64c44d7ecc7b 100644 --- a/tests/ui/integer_arithmetic.stderr +++ b/tests/ui/integer_arithmetic.stderr @@ -1,5 +1,5 @@ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:15:5 + --> $DIR/integer_arithmetic.rs:14:5 | LL | 1 + i; | ^^^^^ @@ -7,98 +7,98 @@ LL | 1 + i; = note: `-D clippy::integer-arithmetic` implied by `-D warnings` error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:16:5 + --> $DIR/integer_arithmetic.rs:15:5 | LL | i * 2; | ^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:17:5 + --> $DIR/integer_arithmetic.rs:16:5 | LL | / 1 % LL | | i / 2; // no error, this is part of the expression in the preceding line | |_________^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:19:5 + --> $DIR/integer_arithmetic.rs:18:5 | LL | i - 2 + 2 - i; | ^^^^^^^^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:20:5 + --> $DIR/integer_arithmetic.rs:19:5 | LL | -i; | ^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:32:5 + --> $DIR/integer_arithmetic.rs:31:5 | LL | i += 1; | ^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:33:5 + --> $DIR/integer_arithmetic.rs:32:5 | LL | i -= 1; | ^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:34:5 + --> $DIR/integer_arithmetic.rs:33:5 | LL | i *= 2; | ^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:35:5 + --> $DIR/integer_arithmetic.rs:34:5 | LL | i /= 2; | ^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:36:5 + --> $DIR/integer_arithmetic.rs:35:5 | LL | i %= 2; | ^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:82:5 + --> $DIR/integer_arithmetic.rs:81:5 | LL | 3 + &1; | ^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:83:5 + --> $DIR/integer_arithmetic.rs:82:5 | LL | &3 + 1; | ^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:84:5 + --> $DIR/integer_arithmetic.rs:83:5 | LL | &3 + &1; | ^^^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:89:5 + --> $DIR/integer_arithmetic.rs:88:5 | LL | a + x | ^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:93:5 + --> $DIR/integer_arithmetic.rs:92:5 | LL | x + y | ^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:97:5 + --> $DIR/integer_arithmetic.rs:96:5 | LL | x + y | ^^^^^ error: integer arithmetic detected - --> $DIR/integer_arithmetic.rs:101:5 + --> $DIR/integer_arithmetic.rs:100:5 | LL | (&x + &y) | ^^^^^^^^^ diff --git a/tests/ui/mut_from_ref.rs b/tests/ui/mut_from_ref.rs index 8f9ed7ed6374..a9a04c8f56b9 100644 --- a/tests/ui/mut_from_ref.rs +++ b/tests/ui/mut_from_ref.rs @@ -1,4 +1,4 @@ -#![allow(unused, clippy::trivially_copy_pass_by_ref)] +#![allow(unused)] #![warn(clippy::mut_from_ref)] struct Foo; diff --git a/tests/ui/mut_reference.rs b/tests/ui/mut_reference.rs index c4379e0ea1c4..73906121c402 100644 --- a/tests/ui/mut_reference.rs +++ b/tests/ui/mut_reference.rs @@ -1,4 +1,4 @@ -#![allow(unused_variables, clippy::trivially_copy_pass_by_ref)] +#![allow(unused_variables)] fn takes_an_immutable_reference(a: &i32) {} fn takes_a_mutable_reference(a: &mut i32) {} diff --git a/tests/ui/needless_borrow.fixed b/tests/ui/needless_borrow.fixed index 50f9b7c7ba63..5ae4a0e79b99 100644 --- a/tests/ui/needless_borrow.fixed +++ b/tests/ui/needless_borrow.fixed @@ -2,7 +2,6 @@ #![allow(clippy::needless_borrowed_reference)] -#[allow(clippy::trivially_copy_pass_by_ref)] fn x(y: &i32) -> i32 { *y } diff --git a/tests/ui/needless_borrow.rs b/tests/ui/needless_borrow.rs index 8677b957e4c3..1e281316c8a3 100644 --- a/tests/ui/needless_borrow.rs +++ b/tests/ui/needless_borrow.rs @@ -2,7 +2,6 @@ #![allow(clippy::needless_borrowed_reference)] -#[allow(clippy::trivially_copy_pass_by_ref)] fn x(y: &i32) -> i32 { *y } diff --git a/tests/ui/needless_borrow.stderr b/tests/ui/needless_borrow.stderr index 49df9cd072b3..0bfeda7914db 100644 --- a/tests/ui/needless_borrow.stderr +++ b/tests/ui/needless_borrow.stderr @@ -1,5 +1,5 @@ error: this expression borrows a reference that is immediately dereferenced by the compiler - --> $DIR/needless_borrow.rs:15:15 + --> $DIR/needless_borrow.rs:14:15 | LL | let c = x(&&a); | ^^^ help: change this to: `&a` @@ -7,19 +7,19 @@ LL | let c = x(&&a); = note: `-D clippy::needless-borrow` implied by `-D warnings` error: this pattern creates a reference to a reference - --> $DIR/needless_borrow.rs:22:17 + --> $DIR/needless_borrow.rs:21:17 | LL | if let Some(ref cake) = Some(&5) {} | ^^^^^^^^ help: change this to: `cake` error: this expression borrows a reference that is immediately dereferenced by the compiler - --> $DIR/needless_borrow.rs:29:15 + --> $DIR/needless_borrow.rs:28:15 | LL | 46 => &&a, | ^^^ help: change this to: `&a` error: this pattern creates a reference to a reference - --> $DIR/needless_borrow.rs:52:31 + --> $DIR/needless_borrow.rs:51:31 | LL | let _ = v.iter().filter(|&ref a| a.is_empty()); | ^^^^^ help: change this to: `a` diff --git a/tests/ui/needless_lifetimes.rs b/tests/ui/needless_lifetimes.rs index f3fdd48633f8..913cd004f19f 100644 --- a/tests/ui/needless_lifetimes.rs +++ b/tests/ui/needless_lifetimes.rs @@ -1,5 +1,5 @@ #![warn(clippy::needless_lifetimes)] -#![allow(dead_code, clippy::needless_pass_by_value, clippy::trivially_copy_pass_by_ref)] +#![allow(dead_code, clippy::needless_pass_by_value)] fn distinct_lifetimes<'a, 'b>(_x: &'a u8, _y: &'b u8, _z: u8) {} diff --git a/tests/ui/new_ret_no_self.rs b/tests/ui/new_ret_no_self.rs index a31f046c0841..35aaecc9ac42 100644 --- a/tests/ui/new_ret_no_self.rs +++ b/tests/ui/new_ret_no_self.rs @@ -1,5 +1,5 @@ #![warn(clippy::new_ret_no_self)] -#![allow(dead_code, clippy::trivially_copy_pass_by_ref)] +#![allow(dead_code)] fn main() {} diff --git a/tests/ui/trivially_copy_pass_by_ref.rs b/tests/ui/trivially_copy_pass_by_ref.rs index bd23aa99ceb0..316426f1cf18 100644 --- a/tests/ui/trivially_copy_pass_by_ref.rs +++ b/tests/ui/trivially_copy_pass_by_ref.rs @@ -1,6 +1,7 @@ // 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::many_single_char_names, clippy::blacklisted_name, diff --git a/tests/ui/trivially_copy_pass_by_ref.stderr b/tests/ui/trivially_copy_pass_by_ref.stderr index 1addc3d7195d..be0914e4a794 100644 --- a/tests/ui/trivially_copy_pass_by_ref.stderr +++ b/tests/ui/trivially_copy_pass_by_ref.stderr @@ -1,91 +1,95 @@ error: this argument (N byte) is passed by reference, but would be more efficient if passed by value (limit: N byte) - --> $DIR/trivially_copy_pass_by_ref.rs:50:11 + --> $DIR/trivially_copy_pass_by_ref.rs:51:11 | LL | fn bad(x: &u32, y: &Foo, z: &Baz) {} | ^^^^ help: consider passing by value instead: `u32` | - = note: `-D clippy::trivially-copy-pass-by-ref` implied by `-D warnings` +note: the lint level is defined here + --> $DIR/trivially_copy_pass_by_ref.rs:4:9 + | +LL | #![deny(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) - --> $DIR/trivially_copy_pass_by_ref.rs:50:20 + --> $DIR/trivially_copy_pass_by_ref.rs:51: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) - --> $DIR/trivially_copy_pass_by_ref.rs:50:29 + --> $DIR/trivially_copy_pass_by_ref.rs:51: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) - --> $DIR/trivially_copy_pass_by_ref.rs:57:12 + --> $DIR/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) - --> $DIR/trivially_copy_pass_by_ref.rs:57:22 + --> $DIR/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) - --> $DIR/trivially_copy_pass_by_ref.rs:57:31 + --> $DIR/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) - --> $DIR/trivially_copy_pass_by_ref.rs:57:40 + --> $DIR/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) - --> $DIR/trivially_copy_pass_by_ref.rs:59:16 + --> $DIR/trivially_copy_pass_by_ref.rs:60: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) - --> $DIR/trivially_copy_pass_by_ref.rs:59:25 + --> $DIR/trivially_copy_pass_by_ref.rs:60: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) - --> $DIR/trivially_copy_pass_by_ref.rs:59:34 + --> $DIR/trivially_copy_pass_by_ref.rs:60: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) - --> $DIR/trivially_copy_pass_by_ref.rs:71:16 + --> $DIR/trivially_copy_pass_by_ref.rs:72: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) - --> $DIR/trivially_copy_pass_by_ref.rs:71:25 + --> $DIR/trivially_copy_pass_by_ref.rs:72: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) - --> $DIR/trivially_copy_pass_by_ref.rs:71:34 + --> $DIR/trivially_copy_pass_by_ref.rs:72: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) - --> $DIR/trivially_copy_pass_by_ref.rs:75:34 + --> $DIR/trivially_copy_pass_by_ref.rs:76:34 | 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) - --> $DIR/trivially_copy_pass_by_ref.rs:79:37 + --> $DIR/trivially_copy_pass_by_ref.rs:80:37 | LL | fn trait_method2(&self, _color: &Color); | ^^^^^^ help: consider passing by value instead: `Color` diff --git a/tests/ui/useless_asref.fixed b/tests/ui/useless_asref.fixed index c6fce5df210d..e356f13d087b 100644 --- a/tests/ui/useless_asref.fixed +++ b/tests/ui/useless_asref.fixed @@ -1,7 +1,6 @@ // run-rustfix #![deny(clippy::useless_asref)] -#![allow(clippy::trivially_copy_pass_by_ref)] use std::fmt::Debug; diff --git a/tests/ui/useless_asref.rs b/tests/ui/useless_asref.rs index 1d23760bd148..2a80291f5d83 100644 --- a/tests/ui/useless_asref.rs +++ b/tests/ui/useless_asref.rs @@ -1,7 +1,6 @@ // run-rustfix #![deny(clippy::useless_asref)] -#![allow(clippy::trivially_copy_pass_by_ref)] use std::fmt::Debug; diff --git a/tests/ui/useless_asref.stderr b/tests/ui/useless_asref.stderr index b21c67bb3645..5876b54aca8f 100644 --- a/tests/ui/useless_asref.stderr +++ b/tests/ui/useless_asref.stderr @@ -1,5 +1,5 @@ error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:44:18 + --> $DIR/useless_asref.rs:43:18 | LL | foo_rstr(rstr.as_ref()); | ^^^^^^^^^^^^^ help: try this: `rstr` @@ -11,61 +11,61 @@ LL | #![deny(clippy::useless_asref)] | ^^^^^^^^^^^^^^^^^^^^^ error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:46:20 + --> $DIR/useless_asref.rs:45:20 | LL | foo_rslice(rslice.as_ref()); | ^^^^^^^^^^^^^^^ help: try this: `rslice` error: this call to `as_mut` does nothing - --> $DIR/useless_asref.rs:50:21 + --> $DIR/useless_asref.rs:49:21 | LL | foo_mrslice(mrslice.as_mut()); | ^^^^^^^^^^^^^^^^ help: try this: `mrslice` error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:52:20 + --> $DIR/useless_asref.rs:51:20 | LL | foo_rslice(mrslice.as_ref()); | ^^^^^^^^^^^^^^^^ help: try this: `mrslice` error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:59:20 + --> $DIR/useless_asref.rs:58:20 | LL | foo_rslice(rrrrrslice.as_ref()); | ^^^^^^^^^^^^^^^^^^^ help: try this: `rrrrrslice` error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:61:18 + --> $DIR/useless_asref.rs:60:18 | LL | foo_rstr(rrrrrstr.as_ref()); | ^^^^^^^^^^^^^^^^^ help: try this: `rrrrrstr` error: this call to `as_mut` does nothing - --> $DIR/useless_asref.rs:66:21 + --> $DIR/useless_asref.rs:65:21 | LL | foo_mrslice(mrrrrrslice.as_mut()); | ^^^^^^^^^^^^^^^^^^^^ help: try this: `mrrrrrslice` error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:68:20 + --> $DIR/useless_asref.rs:67:20 | LL | foo_rslice(mrrrrrslice.as_ref()); | ^^^^^^^^^^^^^^^^^^^^ help: try this: `mrrrrrslice` error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:72:16 + --> $DIR/useless_asref.rs:71:16 | LL | foo_rrrrmr((&&&&MoreRef).as_ref()); | ^^^^^^^^^^^^^^^^^^^^^^ help: try this: `(&&&&MoreRef)` error: this call to `as_mut` does nothing - --> $DIR/useless_asref.rs:122:13 + --> $DIR/useless_asref.rs:121:13 | LL | foo_mrt(mrt.as_mut()); | ^^^^^^^^^^^^ help: try this: `mrt` error: this call to `as_ref` does nothing - --> $DIR/useless_asref.rs:124:12 + --> $DIR/useless_asref.rs:123:12 | LL | foo_rt(mrt.as_ref()); | ^^^^^^^^^^^^ help: try this: `mrt` diff --git a/tests/ui/wrong_self_convention.rs b/tests/ui/wrong_self_convention.rs index 7567fa7158cb..99652ca4470c 100644 --- a/tests/ui/wrong_self_convention.rs +++ b/tests/ui/wrong_self_convention.rs @@ -1,6 +1,6 @@ #![warn(clippy::wrong_self_convention)] #![warn(clippy::wrong_pub_self_convention)] -#![allow(dead_code, clippy::trivially_copy_pass_by_ref)] +#![allow(dead_code)] fn main() {} From e26ae7a0ff54cbb229790011df1031df68d258bb Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 2 Apr 2020 20:00:12 -0700 Subject: [PATCH 17/58] Downgrade inefficient_to_string to pedantic --- clippy_lints/src/lib.rs | 3 +-- clippy_lints/src/methods/mod.rs | 2 +- src/lintlist/mod.rs | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfc2a26b06b2..7648225f9c65 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1105,6 +1105,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::FILTER_MAP), LintId::of(&methods::FILTER_MAP_NEXT), LintId::of(&methods::FIND_MAP), + LintId::of(&methods::INEFFICIENT_TO_STRING), LintId::of(&methods::MAP_FLATTEN), LintId::of(&methods::OPTION_MAP_UNWRAP_OR), LintId::of(&methods::OPTION_MAP_UNWRAP_OR_ELSE), @@ -1259,7 +1260,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::EXPECT_FUN_CALL), LintId::of(&methods::FILTER_NEXT), LintId::of(&methods::FLAT_MAP_IDENTITY), - LintId::of(&methods::INEFFICIENT_TO_STRING), LintId::of(&methods::INTO_ITER_ON_REF), LintId::of(&methods::ITERATOR_STEP_BY_ZERO), LintId::of(&methods::ITER_CLONED_COLLECT), @@ -1652,7 +1652,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&loops::MANUAL_MEMCPY), LintId::of(&loops::NEEDLESS_COLLECT), LintId::of(&methods::EXPECT_FUN_CALL), - LintId::of(&methods::INEFFICIENT_TO_STRING), LintId::of(&methods::ITER_NTH), LintId::of(&methods::OR_FUN_CALL), LintId::of(&methods::SINGLE_CHAR_PATTERN), diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 527508af8a31..9064d2a41b5b 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -698,7 +698,7 @@ declare_clippy_lint! { /// ["foo", "bar"].iter().map(|&s| s.to_string()); /// ``` pub INEFFICIENT_TO_STRING, - perf, + pedantic, "using `to_string` on `&&T` where `T: ToString`" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 8a6d0af5f8a7..4ea974ec6e83 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -789,7 +789,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "inefficient_to_string", - group: "perf", + group: "pedantic", desc: "using `to_string` on `&&T` where `T: ToString`", deprecation: None, module: "methods", From ffb2e4123458e50202c02e63b9e044583c0fe79a Mon Sep 17 00:00:00 2001 From: flip1995 Date: Thu, 2 Apr 2020 18:20:23 +0200 Subject: [PATCH 18/58] Clean up update_lints --- clippy_dev/src/lib.rs | 19 +++++++++---------- clippy_dev/src/update_lints.rs | 10 +++++----- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index 83f60f15906f..b01112539bef 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -85,7 +85,7 @@ impl Lint { /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`. #[must_use] -pub fn gen_lint_group_list(lints: Vec) -> Vec { +pub fn gen_lint_group_list(lints: &[Lint]) -> Vec { lints .into_iter() .filter_map(|l| { @@ -101,14 +101,14 @@ pub fn gen_lint_group_list(lints: Vec) -> Vec { /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`. #[must_use] -pub fn gen_modules_list(lints: Vec) -> Vec { +pub fn gen_modules_list(lints: &[Lint]) -> Vec { lints .into_iter() .filter_map(|l| { if l.is_internal() || l.deprecation.is_some() { None } else { - Some(l.module) + Some(l.module.clone()) } }) .unique() @@ -119,11 +119,10 @@ pub fn gen_modules_list(lints: Vec) -> Vec { /// Generates the list of lint links at the bottom of the README #[must_use] -pub fn gen_changelog_lint_list(lints: Vec) -> Vec { - let mut lint_list_sorted: Vec = lints; - lint_list_sorted.sort_by_key(|l| l.name.clone()); - lint_list_sorted +pub fn gen_changelog_lint_list(lints: &[Lint]) -> Vec { + lints .iter() + .sorted_by_key(|l| l.name.clone()) .filter_map(|l| { if l.is_internal() { None @@ -475,7 +474,7 @@ fn test_gen_changelog_lint_list() { format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()), format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()), ]; - assert_eq!(expected, gen_changelog_lint_list(lints)); + assert_eq!(expected, gen_changelog_lint_list(&lints)); } #[test] @@ -525,7 +524,7 @@ fn test_gen_modules_list() { "pub mod another_module;".to_string(), "pub mod module_name;".to_string(), ]; - assert_eq!(expected, gen_modules_list(lints)); + assert_eq!(expected, gen_modules_list(&lints)); } #[test] @@ -541,5 +540,5 @@ fn test_gen_lint_group_list() { " LintId::of(&module_name::INTERNAL),".to_string(), " LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(), ]; - assert_eq!(expected, gen_lint_group_list(lints)); + assert_eq!(expected, gen_lint_group_list(&lints)); } diff --git a/clippy_dev/src/update_lints.rs b/clippy_dev/src/update_lints.rs index d30d6f97a2f7..d709e4892fe2 100644 --- a/clippy_dev/src/update_lints.rs +++ b/clippy_dev/src/update_lints.rs @@ -61,7 +61,7 @@ pub fn run(update_mode: UpdateMode) { "", false, update_mode == UpdateMode::Change, - || gen_changelog_lint_list(lint_list.clone()), + || gen_changelog_lint_list(&lint_list), ) .changed; @@ -91,7 +91,7 @@ pub fn run(update_mode: UpdateMode) { "end lints modules", false, update_mode == UpdateMode::Change, - || gen_modules_list(lint_list.clone()), + || gen_modules_list(&lint_list), ) .changed; @@ -110,9 +110,9 @@ pub fn run(update_mode: UpdateMode) { .filter(|l| { l.group == "correctness" || l.group == "style" || l.group == "complexity" || l.group == "perf" }) - .collect(); + .collect::>(); - gen_lint_group_list(all_group_lints) + gen_lint_group_list(&all_group_lints) }, ) .changed; @@ -125,7 +125,7 @@ pub fn run(update_mode: UpdateMode) { r#"\]\);"#, false, update_mode == UpdateMode::Change, - || gen_lint_group_list(lints.clone()), + || gen_lint_group_list(&lints), ) .changed; } From da679825e0d3b1dda22044b3ec9ec1612a4e26f0 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Thu, 2 Apr 2020 18:31:32 +0200 Subject: [PATCH 19/58] Get rid of Lint::is_internal method --- clippy_dev/src/lib.rs | 27 +++++---------------------- clippy_dev/src/update_lints.rs | 4 ++-- 2 files changed, 7 insertions(+), 24 deletions(-) diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index b01112539bef..4531d9b39c0e 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -63,7 +63,7 @@ impl Lint { /// Returns all non-deprecated lints and non-internal lints pub fn usable_lints(lints: impl Iterator) -> impl Iterator { - lints.filter(|l| l.deprecation.is_none() && !l.is_internal()) + lints.filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal")) } /// Returns all internal lints (not `internal_warn` lints) @@ -76,11 +76,6 @@ impl Lint { pub fn by_lint_group(lints: impl Iterator) -> HashMap> { lints.map(|lint| (lint.group.to_string(), lint)).into_group_map() } - - #[must_use] - pub fn is_internal(&self) -> bool { - self.group.starts_with("internal") - } } /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`. @@ -103,14 +98,8 @@ pub fn gen_lint_group_list(lints: &[Lint]) -> Vec { #[must_use] pub fn gen_modules_list(lints: &[Lint]) -> Vec { lints - .into_iter() - .filter_map(|l| { - if l.is_internal() || l.deprecation.is_some() { - None - } else { - Some(l.module.clone()) - } - }) + .iter() + .map(|l| &l.module) .unique() .map(|module| format!("pub mod {};", module)) .sorted() @@ -124,7 +113,7 @@ pub fn gen_changelog_lint_list(lints: &[Lint]) -> Vec { .iter() .sorted_by_key(|l| l.name.clone()) .filter_map(|l| { - if l.is_internal() { + if l.group.starts_with("internal") { None } else { Some(format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name)) @@ -158,13 +147,7 @@ pub fn gen_register_lint_list(lints: &[Lint]) -> Vec { let post = " ]);".to_string(); let mut inner = lints .iter() - .filter_map(|l| { - if !l.is_internal() && l.deprecation.is_none() { - Some(format!(" &{}::{},", l.module, l.name.to_uppercase())) - } else { - None - } - }) + .map(|l| format!(" &{}::{},", l.module, l.name.to_uppercase())) .sorted() .collect::>(); inner.insert(0, pre); diff --git a/clippy_dev/src/update_lints.rs b/clippy_dev/src/update_lints.rs index d709e4892fe2..be565700b012 100644 --- a/clippy_dev/src/update_lints.rs +++ b/clippy_dev/src/update_lints.rs @@ -81,7 +81,7 @@ pub fn run(update_mode: UpdateMode) { "end register lints", false, update_mode == UpdateMode::Change, - || gen_register_lint_list(&lint_list), + || gen_register_lint_list(&usable_lints), ) .changed; @@ -91,7 +91,7 @@ pub fn run(update_mode: UpdateMode) { "end lints modules", false, update_mode == UpdateMode::Change, - || gen_modules_list(&lint_list), + || gen_modules_list(&usable_lints), ) .changed; From 98c30fea8c8bac46f79a70e0ef0d7be0c76ae4e1 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Thu, 2 Apr 2020 22:04:54 +0200 Subject: [PATCH 20/58] Build lint lists once and the reuse them to update files --- clippy_dev/src/lib.rs | 45 ++++++++++++++++++++-------------- clippy_dev/src/update_lints.rs | 38 +++++++++++++--------------- 2 files changed, 43 insertions(+), 40 deletions(-) diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index 4531d9b39c0e..bec415aae94c 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -62,13 +62,25 @@ impl Lint { } /// Returns all non-deprecated lints and non-internal lints - pub fn usable_lints(lints: impl Iterator) -> impl Iterator { - lints.filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal")) + #[must_use] + pub fn usable_lints(lints: &[Self]) -> Vec { + lints + .iter() + .filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal")) + .cloned() + .collect() } /// Returns all internal lints (not `internal_warn` lints) - pub fn internal_lints(lints: impl Iterator) -> impl Iterator { - lints.filter(|l| l.group == "internal") + #[must_use] + pub fn internal_lints(lints: &[Self]) -> Vec { + lints.iter().filter(|l| l.group == "internal").cloned().collect() + } + + /// Returns all deprecated lints + #[must_use] + pub fn deprecated_lints(lints: &[Self]) -> Vec { + lints.iter().filter(|l| l.deprecation.is_some()).cloned().collect() } /// Returns the lints in a `HashMap`, grouped by the different lint groups @@ -80,9 +92,8 @@ impl Lint { /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`. #[must_use] -pub fn gen_lint_group_list(lints: &[Lint]) -> Vec { +pub fn gen_lint_group_list<'a>(lints: impl Iterator) -> Vec { lints - .into_iter() .filter_map(|l| { if l.deprecation.is_some() { None @@ -96,9 +107,8 @@ pub fn gen_lint_group_list(lints: &[Lint]) -> Vec { /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`. #[must_use] -pub fn gen_modules_list(lints: &[Lint]) -> Vec { +pub fn gen_modules_list<'a>(lints: impl Iterator) -> Vec { lints - .iter() .map(|l| &l.module) .unique() .map(|module| format!("pub mod {};", module)) @@ -108,9 +118,8 @@ pub fn gen_modules_list(lints: &[Lint]) -> Vec { /// Generates the list of lint links at the bottom of the README #[must_use] -pub fn gen_changelog_lint_list(lints: &[Lint]) -> Vec { +pub fn gen_changelog_lint_list<'a>(lints: impl Iterator) -> Vec { lints - .iter() .sorted_by_key(|l| l.name.clone()) .filter_map(|l| { if l.group.starts_with("internal") { @@ -124,9 +133,8 @@ pub fn gen_changelog_lint_list(lints: &[Lint]) -> Vec { /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`. #[must_use] -pub fn gen_deprecated(lints: &[Lint]) -> Vec { +pub fn gen_deprecated<'a>(lints: impl Iterator) -> Vec { lints - .iter() .filter_map(|l| { l.clone().deprecation.map(|depr_text| { vec![ @@ -142,11 +150,10 @@ pub fn gen_deprecated(lints: &[Lint]) -> Vec { } #[must_use] -pub fn gen_register_lint_list(lints: &[Lint]) -> Vec { +pub fn gen_register_lint_list<'a>(lints: impl Iterator) -> Vec { let pre = " store.register_lints(&[".to_string(); let post = " ]);".to_string(); let mut inner = lints - .iter() .map(|l| format!(" &{}::{},", l.module, l.name.to_uppercase())) .sorted() .collect::>(); @@ -421,7 +428,7 @@ fn test_usable_lints() { None, "module_name", )]; - assert_eq!(expected, Lint::usable_lints(lints.into_iter()).collect::>()); + assert_eq!(expected, Lint::usable_lints(&lints)); } #[test] @@ -457,7 +464,7 @@ fn test_gen_changelog_lint_list() { format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()), format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()), ]; - assert_eq!(expected, gen_changelog_lint_list(&lints)); + assert_eq!(expected, gen_changelog_lint_list(lints.iter())); } #[test] @@ -492,7 +499,7 @@ fn test_gen_deprecated() { .into_iter() .map(String::from) .collect(); - assert_eq!(expected, gen_deprecated(&lints)); + assert_eq!(expected, gen_deprecated(lints.iter())); } #[test] @@ -507,7 +514,7 @@ fn test_gen_modules_list() { "pub mod another_module;".to_string(), "pub mod module_name;".to_string(), ]; - assert_eq!(expected, gen_modules_list(&lints)); + assert_eq!(expected, gen_modules_list(lints.iter())); } #[test] @@ -523,5 +530,5 @@ fn test_gen_lint_group_list() { " LintId::of(&module_name::INTERNAL),".to_string(), " LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(), ]; - assert_eq!(expected, gen_lint_group_list(&lints)); + assert_eq!(expected, gen_lint_group_list(lints.iter())); } diff --git a/clippy_dev/src/update_lints.rs b/clippy_dev/src/update_lints.rs index be565700b012..a9a709299426 100644 --- a/clippy_dev/src/update_lints.rs +++ b/clippy_dev/src/update_lints.rs @@ -14,14 +14,14 @@ pub enum UpdateMode { pub fn run(update_mode: UpdateMode) { let lint_list: Vec = gather_all().collect(); - let internal_lints = Lint::internal_lints(lint_list.clone().into_iter()); - - let usable_lints: Vec = Lint::usable_lints(lint_list.clone().into_iter()).collect(); - let usable_lint_count = round_to_fifty(usable_lints.len()); - + let internal_lints = Lint::internal_lints(&lint_list); + let deprecated_lints = Lint::deprecated_lints(&lint_list); + let usable_lints = Lint::usable_lints(&lint_list); let mut sorted_usable_lints = usable_lints.clone(); sorted_usable_lints.sort_by_key(|lint| lint.name.clone()); + let usable_lint_count = round_to_fifty(usable_lints.len()); + let mut file_change = replace_region_in_file( Path::new("src/lintlist/mod.rs"), "begin lint list", @@ -61,7 +61,7 @@ pub fn run(update_mode: UpdateMode) { "", false, update_mode == UpdateMode::Change, - || gen_changelog_lint_list(&lint_list), + || gen_changelog_lint_list(usable_lints.iter().chain(deprecated_lints.iter())), ) .changed; @@ -71,7 +71,7 @@ pub fn run(update_mode: UpdateMode) { "end deprecated lints", false, update_mode == UpdateMode::Change, - || gen_deprecated(&lint_list), + || gen_deprecated(deprecated_lints.iter()), ) .changed; @@ -81,7 +81,7 @@ pub fn run(update_mode: UpdateMode) { "end register lints", false, update_mode == UpdateMode::Change, - || gen_register_lint_list(&usable_lints), + || gen_register_lint_list(usable_lints.iter().chain(internal_lints.iter())), ) .changed; @@ -91,7 +91,7 @@ pub fn run(update_mode: UpdateMode) { "end lints modules", false, update_mode == UpdateMode::Change, - || gen_modules_list(&usable_lints), + || gen_modules_list(usable_lints.iter()), ) .changed; @@ -104,15 +104,11 @@ pub fn run(update_mode: UpdateMode) { update_mode == UpdateMode::Change, || { // clippy::all should only include the following lint groups: - let all_group_lints = usable_lints - .clone() - .into_iter() - .filter(|l| { - l.group == "correctness" || l.group == "style" || l.group == "complexity" || l.group == "perf" - }) - .collect::>(); - - gen_lint_group_list(&all_group_lints) + let all_group_lints = usable_lints.iter().filter(|l| { + l.group == "correctness" || l.group == "style" || l.group == "complexity" || l.group == "perf" + }); + + gen_lint_group_list(all_group_lints) }, ) .changed; @@ -125,7 +121,7 @@ pub fn run(update_mode: UpdateMode) { r#"\]\);"#, false, update_mode == UpdateMode::Change, - || gen_lint_group_list(&lints), + || gen_lint_group_list(lints.iter()), ) .changed; } @@ -140,8 +136,8 @@ pub fn run(update_mode: UpdateMode) { } pub fn print_lints() { - let lint_list = gather_all(); - let usable_lints: Vec = Lint::usable_lints(lint_list).collect(); + let lint_list: Vec = gather_all().collect(); + let usable_lints = Lint::usable_lints(&lint_list); let usable_lint_count = usable_lints.len(); let grouped_by_lint_group = Lint::by_lint_group(usable_lints.into_iter()); From a186d9fafd7424feab7b5bde044219a0e8e58c9f Mon Sep 17 00:00:00 2001 From: flip1995 Date: Thu, 2 Apr 2020 22:07:33 +0200 Subject: [PATCH 21/58] Don't filter lints in code generation functions --- clippy_dev/src/lib.rs | 52 ++++++++++++++++++------------------------- 1 file changed, 22 insertions(+), 30 deletions(-) diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index bec415aae94c..10056e8f03e0 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -94,13 +94,7 @@ impl Lint { #[must_use] pub fn gen_lint_group_list<'a>(lints: impl Iterator) -> Vec { lints - .filter_map(|l| { - if l.deprecation.is_some() { - None - } else { - Some(format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase())) - } - }) + .map(|l| format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase())) .sorted() .collect::>() } @@ -120,14 +114,8 @@ pub fn gen_modules_list<'a>(lints: impl Iterator) -> Vec(lints: impl Iterator) -> Vec { lints - .sorted_by_key(|l| l.name.clone()) - .filter_map(|l| { - if l.group.starts_with("internal") { - None - } else { - Some(format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name)) - } - }) + .sorted_by_key(|l| &l.name) + .map(|l| format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name)) .collect() } @@ -135,17 +123,19 @@ pub fn gen_changelog_lint_list<'a>(lints: impl Iterator) -> Vec #[must_use] pub fn gen_deprecated<'a>(lints: impl Iterator) -> Vec { lints - .filter_map(|l| { - l.clone().deprecation.map(|depr_text| { - vec![ - " store.register_removed(".to_string(), - format!(" \"clippy::{}\",", l.name), - format!(" \"{}\",", depr_text), - " );".to_string(), - ] - }) + .flat_map(|l| { + l.deprecation + .clone() + .map(|depr_text| { + vec![ + " store.register_removed(".to_string(), + format!(" \"clippy::{}\",", l.name), + format!(" \"{}\",", depr_text), + " );".to_string(), + ] + }) + .expect("only deprecated lints should be passed") }) - .flatten() .collect::>() } @@ -458,7 +448,6 @@ fn test_gen_changelog_lint_list() { let lints = vec![ Lint::new("should_assert_eq", "group1", "abc", None, "module_name"), Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"), - Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"), ]; let expected = vec![ format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()), @@ -484,7 +473,6 @@ fn test_gen_deprecated() { Some("will be removed"), "module_name", ), - Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"), ]; let expected: Vec = vec![ " store.register_removed(", @@ -502,13 +490,18 @@ fn test_gen_deprecated() { assert_eq!(expected, gen_deprecated(lints.iter())); } +#[test] +#[should_panic] +fn test_gen_deprecated_fail() { + let lints = vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")]; + let _ = gen_deprecated(lints.iter()); +} + #[test] fn test_gen_modules_list() { let lints = vec![ Lint::new("should_assert_eq", "group1", "abc", None, "module_name"), - Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"), Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"), - Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"), ]; let expected = vec![ "pub mod another_module;".to_string(), @@ -522,7 +515,6 @@ fn test_gen_lint_group_list() { let lints = vec![ Lint::new("abc", "group1", "abc", None, "module_name"), Lint::new("should_assert_eq", "group1", "abc", None, "module_name"), - Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"), Lint::new("internal", "internal_style", "abc", None, "module_name"), ]; let expected = vec![ From d89bb50f72e1db538d6ae18023c0edb746b119f9 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Thu, 2 Apr 2020 22:08:10 +0200 Subject: [PATCH 22/58] Make lint modules private --- clippy_dev/src/lib.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index 10056e8f03e0..1f8510f43a61 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -105,7 +105,7 @@ pub fn gen_modules_list<'a>(lints: impl Iterator) -> Vec>() } @@ -503,10 +503,7 @@ fn test_gen_modules_list() { Lint::new("should_assert_eq", "group1", "abc", None, "module_name"), Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"), ]; - let expected = vec![ - "pub mod another_module;".to_string(), - "pub mod module_name;".to_string(), - ]; + let expected = vec!["mod another_module;".to_string(), "mod module_name;".to_string()]; assert_eq!(expected, gen_modules_list(lints.iter())); } From 045722a17ea05cb11ae933578ee01a3d5d831352 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Thu, 2 Apr 2020 22:08:25 +0200 Subject: [PATCH 23/58] Run update_lints --- clippy_lints/src/lib.rs | 308 ++++++++++++++++++++-------------------- 1 file changed, 157 insertions(+), 151 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfc2a26b06b2..b24110fc1844 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -170,157 +170,157 @@ mod consts; mod utils; // begin lints modules, do not remove this comment, it’s used in `update_lints` -pub mod approx_const; -pub mod arithmetic; -pub mod as_conversions; -pub mod assertions_on_constants; -pub mod assign_ops; -pub mod atomic_ordering; -pub mod attrs; -pub mod bit_mask; -pub mod blacklisted_name; -pub mod block_in_if_condition; -pub mod booleans; -pub mod bytecount; -pub mod cargo_common_metadata; -pub mod checked_conversions; -pub mod cognitive_complexity; -pub mod collapsible_if; -pub mod comparison_chain; -pub mod copies; -pub mod copy_iterator; -pub mod dbg_macro; -pub mod default_trait_access; -pub mod derive; -pub mod doc; -pub mod double_comparison; -pub mod double_parens; -pub mod drop_bounds; -pub mod drop_forget_ref; -pub mod duration_subsec; -pub mod else_if_without_else; -pub mod empty_enum; -pub mod entry; -pub mod enum_clike; -pub mod enum_variants; -pub mod eq_op; -pub mod erasing_op; -pub mod escape; -pub mod eta_reduction; -pub mod eval_order_dependence; -pub mod excessive_bools; -pub mod exit; -pub mod explicit_write; -pub mod fallible_impl_from; -pub mod float_literal; -pub mod floating_point_arithmetic; -pub mod format; -pub mod formatting; -pub mod functions; -pub mod get_last_with_len; -pub mod identity_conversion; -pub mod identity_op; -pub mod if_let_some_result; -pub mod if_not_else; -pub mod implicit_return; -pub mod indexing_slicing; -pub mod infinite_iter; -pub mod inherent_impl; -pub mod inherent_to_string; -pub mod inline_fn_without_body; -pub mod int_plus_one; -pub mod integer_division; -pub mod items_after_statements; -pub mod large_enum_variant; -pub mod large_stack_arrays; -pub mod len_zero; -pub mod let_if_seq; -pub mod let_underscore; -pub mod lifetimes; -pub mod literal_representation; -pub mod loops; -pub mod macro_use; -pub mod main_recursion; -pub mod map_clone; -pub mod map_unit_fn; -pub mod matches; -pub mod mem_discriminant; -pub mod mem_forget; -pub mod mem_replace; -pub mod methods; -pub mod minmax; -pub mod misc; -pub mod misc_early; -pub mod missing_const_for_fn; -pub mod missing_doc; -pub mod missing_inline; -pub mod modulo_arithmetic; -pub mod multiple_crate_versions; -pub mod mut_key; -pub mod mut_mut; -pub mod mut_reference; -pub mod mutable_debug_assertion; -pub mod mutex_atomic; -pub mod needless_bool; -pub mod needless_borrow; -pub mod needless_borrowed_ref; -pub mod needless_continue; -pub mod needless_pass_by_value; -pub mod needless_update; -pub mod neg_cmp_op_on_partial_ord; -pub mod neg_multiply; -pub mod new_without_default; -pub mod no_effect; -pub mod non_copy_const; -pub mod non_expressive_names; -pub mod open_options; -pub mod option_env_unwrap; -pub mod overflow_check_conditional; -pub mod panic_unimplemented; -pub mod partialeq_ne_impl; -pub mod path_buf_push_overwrite; -pub mod precedence; -pub mod ptr; -pub mod ptr_offset_with_cast; -pub mod question_mark; -pub mod ranges; -pub mod redundant_clone; -pub mod redundant_field_names; -pub mod redundant_pattern_matching; -pub mod redundant_pub_crate; -pub mod redundant_static_lifetimes; -pub mod reference; -pub mod regex; -pub mod returns; -pub mod serde_api; -pub mod shadow; -pub mod single_component_path_imports; -pub mod slow_vector_initialization; -pub mod strings; -pub mod suspicious_trait_impl; -pub mod swap; -pub mod tabs_in_doc_comments; -pub mod temporary_assignment; -pub mod to_digit_is_some; -pub mod trait_bounds; -pub mod transmute; -pub mod transmuting_null; -pub mod trivially_copy_pass_by_ref; -pub mod try_err; -pub mod types; -pub mod unicode; -pub mod unnamed_address; -pub mod unsafe_removed_from_name; -pub mod unused_io_amount; -pub mod unused_self; -pub mod unwrap; -pub mod use_self; -pub mod vec; -pub mod verbose_file_reads; -pub mod wildcard_dependencies; -pub mod wildcard_imports; -pub mod write; -pub mod zero_div_zero; +mod approx_const; +mod arithmetic; +mod as_conversions; +mod assertions_on_constants; +mod assign_ops; +mod atomic_ordering; +mod attrs; +mod bit_mask; +mod blacklisted_name; +mod block_in_if_condition; +mod booleans; +mod bytecount; +mod cargo_common_metadata; +mod checked_conversions; +mod cognitive_complexity; +mod collapsible_if; +mod comparison_chain; +mod copies; +mod copy_iterator; +mod dbg_macro; +mod default_trait_access; +mod derive; +mod doc; +mod double_comparison; +mod double_parens; +mod drop_bounds; +mod drop_forget_ref; +mod duration_subsec; +mod else_if_without_else; +mod empty_enum; +mod entry; +mod enum_clike; +mod enum_variants; +mod eq_op; +mod erasing_op; +mod escape; +mod eta_reduction; +mod eval_order_dependence; +mod excessive_bools; +mod exit; +mod explicit_write; +mod fallible_impl_from; +mod float_literal; +mod floating_point_arithmetic; +mod format; +mod formatting; +mod functions; +mod get_last_with_len; +mod identity_conversion; +mod identity_op; +mod if_let_some_result; +mod if_not_else; +mod implicit_return; +mod indexing_slicing; +mod infinite_iter; +mod inherent_impl; +mod inherent_to_string; +mod inline_fn_without_body; +mod int_plus_one; +mod integer_division; +mod items_after_statements; +mod large_enum_variant; +mod large_stack_arrays; +mod len_zero; +mod let_if_seq; +mod let_underscore; +mod lifetimes; +mod literal_representation; +mod loops; +mod macro_use; +mod main_recursion; +mod map_clone; +mod map_unit_fn; +mod matches; +mod mem_discriminant; +mod mem_forget; +mod mem_replace; +mod methods; +mod minmax; +mod misc; +mod misc_early; +mod missing_const_for_fn; +mod missing_doc; +mod missing_inline; +mod modulo_arithmetic; +mod multiple_crate_versions; +mod mut_key; +mod mut_mut; +mod mut_reference; +mod mutable_debug_assertion; +mod mutex_atomic; +mod needless_bool; +mod needless_borrow; +mod needless_borrowed_ref; +mod needless_continue; +mod needless_pass_by_value; +mod needless_update; +mod neg_cmp_op_on_partial_ord; +mod neg_multiply; +mod new_without_default; +mod no_effect; +mod non_copy_const; +mod non_expressive_names; +mod open_options; +mod option_env_unwrap; +mod overflow_check_conditional; +mod panic_unimplemented; +mod partialeq_ne_impl; +mod path_buf_push_overwrite; +mod precedence; +mod ptr; +mod ptr_offset_with_cast; +mod question_mark; +mod ranges; +mod redundant_clone; +mod redundant_field_names; +mod redundant_pattern_matching; +mod redundant_pub_crate; +mod redundant_static_lifetimes; +mod reference; +mod regex; +mod returns; +mod serde_api; +mod shadow; +mod single_component_path_imports; +mod slow_vector_initialization; +mod strings; +mod suspicious_trait_impl; +mod swap; +mod tabs_in_doc_comments; +mod temporary_assignment; +mod to_digit_is_some; +mod trait_bounds; +mod transmute; +mod transmuting_null; +mod trivially_copy_pass_by_ref; +mod try_err; +mod types; +mod unicode; +mod unnamed_address; +mod unsafe_removed_from_name; +mod unused_io_amount; +mod unused_self; +mod unwrap; +mod use_self; +mod vec; +mod verbose_file_reads; +mod wildcard_dependencies; +mod wildcard_imports; +mod write; +mod zero_div_zero; // end lints modules, do not remove this comment, it’s used in `update_lints` pub use crate::utils::conf::Conf; @@ -828,6 +828,12 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &unwrap::PANICKING_UNWRAP, &unwrap::UNNECESSARY_UNWRAP, &use_self::USE_SELF, + &utils::internal_lints::CLIPPY_LINTS_INTERNAL, + &utils::internal_lints::COMPILER_LINT_FUNCTIONS, + &utils::internal_lints::DEFAULT_LINT, + &utils::internal_lints::LINT_WITHOUT_LINT_PASS, + &utils::internal_lints::OUTER_EXPN_EXPN_DATA, + &utils::internal_lints::PRODUCE_ICE, &vec::USELESS_VEC, &verbose_file_reads::VERBOSE_FILE_READS, &wildcard_dependencies::WILDCARD_DEPENDENCIES, From 30503a91d2cd19239d0aed802cd740ec6f2a7e06 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Fri, 3 Apr 2020 21:31:47 +0200 Subject: [PATCH 24/58] Move matches test in matches module --- clippy_lints/src/matches.rs | 37 ++++++++++++++++++++++++++++++++ tests/matches.rs | 42 ------------------------------------- 2 files changed, 37 insertions(+), 42 deletions(-) delete mode 100644 tests/matches.rs diff --git a/clippy_lints/src/matches.rs b/clippy_lints/src/matches.rs index 20b793f95ded..4298e62b8037 100644 --- a/clippy_lints/src/matches.rs +++ b/clippy_lints/src/matches.rs @@ -1197,3 +1197,40 @@ where None } + +#[test] +fn test_overlapping() { + use rustc_span::source_map::DUMMY_SP; + + let sp = |s, e| SpannedRange { + span: DUMMY_SP, + node: (s, e), + }; + + assert_eq!(None, overlapping::(&[])); + assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))])); + assert_eq!( + None, + overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))]) + ); + assert_eq!( + None, + overlapping(&[ + sp(1, Bound::Included(4)), + sp(5, Bound::Included(6)), + sp(10, Bound::Included(11)) + ],) + ); + assert_eq!( + Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))), + overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))]) + ); + assert_eq!( + Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))), + overlapping(&[ + sp(1, Bound::Included(4)), + sp(5, Bound::Included(6)), + sp(6, Bound::Included(11)) + ],) + ); +} diff --git a/tests/matches.rs b/tests/matches.rs deleted file mode 100644 index 6691c074caf9..000000000000 --- a/tests/matches.rs +++ /dev/null @@ -1,42 +0,0 @@ -#![feature(rustc_private)] - -extern crate rustc_span; -use std::collections::Bound; - -#[test] -fn test_overlapping() { - use clippy_lints::matches::overlapping; - use rustc_span::source_map::DUMMY_SP; - - let sp = |s, e| clippy_lints::matches::SpannedRange { - span: DUMMY_SP, - node: (s, e), - }; - - assert_eq!(None, overlapping::(&[])); - assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))])); - assert_eq!( - None, - overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))]) - ); - assert_eq!( - None, - overlapping(&[ - sp(1, Bound::Included(4)), - sp(5, Bound::Included(6)), - sp(10, Bound::Included(11)) - ],) - ); - assert_eq!( - Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))), - overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))]) - ); - assert_eq!( - Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))), - overlapping(&[ - sp(1, Bound::Included(4)), - sp(5, Bound::Included(6)), - sp(6, Bound::Included(11)) - ],) - ); -} From 91d8a804d34b44a414b02ea5eba5305573748fff Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Fri, 3 Apr 2020 23:59:52 -0700 Subject: [PATCH 25/58] result_map_or_into_option: add lint to catch manually adpating Result -> Option Result has an `ok()` method that adapts a Result into an Option. It's possible to get around this adapter by writing Result.map_or(None, Some). This lint is implemented as a new variant of the existing [`option_map_none` lint](https://github.com/rust-lang/rust-clippy/pull/2128) --- CHANGELOG.md | 1 + clippy_lints/src/lib.rs | 3 + clippy_lints/src/methods/mod.rs | 105 ++++++++++++++++------ src/lintlist/mod.rs | 7 ++ tests/ui/result_map_or_into_option.fixed | 16 ++++ tests/ui/result_map_or_into_option.rs | 14 +++ tests/ui/result_map_or_into_option.stderr | 10 +++ 7 files changed, 131 insertions(+), 25 deletions(-) create mode 100644 tests/ui/result_map_or_into_option.fixed create mode 100644 tests/ui/result_map_or_into_option.rs create mode 100644 tests/ui/result_map_or_into_option.stderr diff --git a/CHANGELOG.md b/CHANGELOG.md index 894aab21fb37..b7ac3cace204 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1448,6 +1448,7 @@ Released 2018-09-13 [`replace_consts`]: https://rust-lang.github.io/rust-clippy/master/index.html#replace_consts [`rest_pat_in_fully_bound_structs`]: https://rust-lang.github.io/rust-clippy/master/index.html#rest_pat_in_fully_bound_structs [`result_expect_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_expect_used +[`result_map_or_into_option`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_or_into_option [`result_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_unit_fn [`result_map_unwrap_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_unwrap_or_else [`result_unwrap_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_unwrap_used diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfc2a26b06b2..83dcb350e185 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -666,6 +666,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &methods::OPTION_UNWRAP_USED, &methods::OR_FUN_CALL, &methods::RESULT_EXPECT_USED, + &methods::RESULT_MAP_OR_INTO_OPTION, &methods::RESULT_MAP_UNWRAP_OR_ELSE, &methods::RESULT_UNWRAP_USED, &methods::SEARCH_IS_SOME, @@ -1273,6 +1274,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::OPTION_AS_REF_DEREF), LintId::of(&methods::OPTION_MAP_OR_NONE), LintId::of(&methods::OR_FUN_CALL), + LintId::of(&methods::RESULT_MAP_OR_INTO_OPTION), LintId::of(&methods::SEARCH_IS_SOME), LintId::of(&methods::SHOULD_IMPLEMENT_TRAIT), LintId::of(&methods::SINGLE_CHAR_PATTERN), @@ -1453,6 +1455,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OK_EXPECT), LintId::of(&methods::OPTION_MAP_OR_NONE), + LintId::of(&methods::RESULT_MAP_OR_INTO_OPTION), LintId::of(&methods::SHOULD_IMPLEMENT_TRAIT), LintId::of(&methods::STRING_EXTEND_CHARS), LintId::of(&methods::UNNECESSARY_FOLD), diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 527508af8a31..e8d642ed71e0 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -330,6 +330,24 @@ declare_clippy_lint! { "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`" } +declare_clippy_lint! { + /// **What it does:** Checks for usage of `_.map_or(None, Some)`. + /// + /// **Why is this bad?** Readability, this can be written more concisely as + /// `_.ok()`. + /// + /// **Known problems:** + /// + /// **Example:** + /// ```rust + /// # let opt = Some(1); + /// # let r = opt.map_or(None, Some); + /// ``` + pub RESULT_MAP_OR_INTO_OPTION, + style, + "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`" +} + declare_clippy_lint! { /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`. /// @@ -1248,6 +1266,7 @@ declare_lint_pass!(Methods => [ OPTION_MAP_UNWRAP_OR, OPTION_MAP_UNWRAP_OR_ELSE, RESULT_MAP_UNWRAP_OR_ELSE, + RESULT_MAP_OR_INTO_OPTION, OPTION_MAP_OR_NONE, OPTION_AND_THEN_SOME, OR_FUN_CALL, @@ -2517,37 +2536,73 @@ fn lint_map_unwrap_or_else<'a, 'tcx>( } } -/// lint use of `_.map_or(None, _)` for `Option`s +/// lint use of `_.map_or(None, _)` for `Option`s and `Result`s fn lint_map_or_none<'a, 'tcx>( cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>], ) { - if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) { - // check if the first non-self argument to map_or() is None - let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind { - match_qpath(qpath, &paths::OPTION_NONE) - } else { - false - }; + let is_option = match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION); + let is_result = match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::RESULT); + + // There are two variants of this `map_or` lint: + // (1) using `map_or` as an adapter from `Result` to `Option` + // (2) using `map_or` as a combinator instead of `and_then` + // + // (For this lint) we don't care if any other type calls `map_or` + if !is_option && !is_result { + return; + } - if map_or_arg_is_none { - // lint message - let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \ - `and_then(f)` instead"; - let map_or_self_snippet = snippet(cx, map_or_args[0].span, ".."); - let map_or_func_snippet = snippet(cx, map_or_args[2].span, ".."); - let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet); - span_lint_and_sugg( - cx, - OPTION_MAP_OR_NONE, - expr.span, - msg, - "try using `and_then` instead", - hint, - Applicability::MachineApplicable, - ); - } + let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind { + match_qpath(qpath, &paths::OPTION_NONE) + } else { + false + }; + + // This is really only needed if `is_result` holds. Computing it here + // makes `mess`'s assignment a bit easier, so just compute it here. + let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind { + match_qpath(qpath, &paths::OPTION_SOME) + } else { + false + }; + + let mess = if is_option && default_arg_is_none { + let self_snippet = snippet(cx, map_or_args[0].span, ".."); + let func_snippet = snippet(cx, map_or_args[2].span, ".."); + let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \ + `and_then(f)` instead"; + Some(( + OPTION_MAP_OR_NONE, + msg, + "try using `and_then` instead", + format!("{0}.and_then({1})", self_snippet, func_snippet), + )) + } else if is_result && f_arg_is_some { + let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \ + `ok()` instead"; + let self_snippet = snippet(cx, map_or_args[0].span, ".."); + Some(( + RESULT_MAP_OR_INTO_OPTION, + msg, + "try using `ok` instead", + format!("{0}.ok()", self_snippet), + )) + } else { + None + }; + + if let Some((lint, msg, instead, hint)) = mess { + span_lint_and_sugg( + cx, + lint, + expr.span, + msg, + instead, + hint, + Applicability::MachineApplicable, + ); } } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 8a6d0af5f8a7..01d1d1a06723 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -1823,6 +1823,13 @@ pub static ref ALL_LINTS: Vec = vec![ deprecation: None, module: "methods", }, + Lint { + name: "result_map_or_into_option", + group: "style", + desc: "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`", + deprecation: None, + module: "methods", + }, Lint { name: "result_map_unit_fn", group: "complexity", diff --git a/tests/ui/result_map_or_into_option.fixed b/tests/ui/result_map_or_into_option.fixed new file mode 100644 index 000000000000..948eb6a3aca1 --- /dev/null +++ b/tests/ui/result_map_or_into_option.fixed @@ -0,0 +1,16 @@ +// run-rustfix + +#![warn(clippy::result_map_or_into_option)] + +fn main() { + let opt: Result = Ok(1); + let _ = opt.ok(); + + let rewrap = |s: u32| -> Option { + Some(s) + }; + + // A non-Some `f` arg should not emit the lint + let opt: Result = Ok(1); + let _ = opt.map_or(None, rewrap); +} diff --git a/tests/ui/result_map_or_into_option.rs b/tests/ui/result_map_or_into_option.rs new file mode 100644 index 000000000000..d097c19e44b9 --- /dev/null +++ b/tests/ui/result_map_or_into_option.rs @@ -0,0 +1,14 @@ +// run-rustfix + +#![warn(clippy::result_map_or_into_option)] + +fn main() { + let opt: Result = Ok(1); + let _ = opt.map_or(None, Some); + + let rewrap = |s: u32| -> Option { Some(s) }; + + // A non-Some `f` arg should not emit the lint + let opt: Result = Ok(1); + let _ = opt.map_or(None, rewrap); +} diff --git a/tests/ui/result_map_or_into_option.stderr b/tests/ui/result_map_or_into_option.stderr new file mode 100644 index 000000000000..febf32147d13 --- /dev/null +++ b/tests/ui/result_map_or_into_option.stderr @@ -0,0 +1,10 @@ +error: called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling `ok()` instead + --> $DIR/result_map_or_into_option.rs:7:13 + | +LL | let _ = opt.map_or(None, Some); + | ^^^^^^^^^^^^^^^^^^^^^^ help: try using `ok` instead: `opt.ok()` + | + = note: `-D clippy::result-map-or-into-option` implied by `-D warnings` + +error: aborting due to previous error + From 2481d3c74a0b89767d9b78db55d967f083bda0d7 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Sat, 4 Apr 2020 17:01:42 +0200 Subject: [PATCH 26/58] Rename rustc -> rustc_middle in doc links --- CONTRIBUTING.md | 2 +- doc/adding_lints.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b1f9be44b73d..466478c81509 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -70,7 +70,7 @@ an AST expression). `match_def_path()` in Clippy's `utils` module can also be us [`T-AST`]: https://github.com/rust-lang/rust-clippy/labels/T-AST [`T-middle`]: https://github.com/rust-lang/rust-clippy/labels/T-middle [`E-medium`]: https://github.com/rust-lang/rust-clippy/labels/E-medium -[`ty`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty +[`ty`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty [nodes in the AST docs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ast/ [deep-nesting]: https://github.com/rust-lang/rust-clippy/blob/557f6848bd5b7183f55c1e1522a326e9e1df6030/clippy_lints/src/mem_forget.rs#L29-L43 [if_chain]: https://docs.rs/if_chain/*/if_chain diff --git a/doc/adding_lints.md b/doc/adding_lints.md index 1d78a27820a6..a66d4e66add2 100644 --- a/doc/adding_lints.md +++ b/doc/adding_lints.md @@ -463,11 +463,11 @@ don't hesitate to ask on [Discord] or in the issue/PR. [utils]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/mod.rs [if_chain]: https://docs.rs/if_chain/*/if_chain/ [from_expansion]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html#method.from_expansion -[in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/fn.in_external_macro.html +[in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/lint/fn.in_external_macro.html [span]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html [applicability]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/enum.Applicability.html [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/ -[nightly_docs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ +[nightly_docs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ [ast]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ast/index.html -[ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/sty/index.html +[ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/sty/index.html [Discord]: https://discord.gg/rust-lang From fac5a41ca5ba3adb55ba76936c505c99b3f7c7c7 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Sat, 4 Apr 2020 17:02:05 +0200 Subject: [PATCH 27/58] Update CONTRIBUTING.md --- CONTRIBUTING.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 466478c81509..12b066b83fce 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,8 @@ High level approach: ### Finding something to fix/improve -All issues on Clippy are mentored, if you want help with a bug just ask @Manishearth, @llogiq, @mcarton or @oli-obk. +All issues on Clippy are mentored, if you want help with a bug just ask +@Manishearth, @flip1995, @phansch or @yaahc. Some issues are easier than others. The [`good first issue`] label can be used to find the easy issues. If you want to work on an issue, please leave a comment so that we can assign it to you! @@ -78,8 +79,7 @@ an AST expression). `match_def_path()` in Clippy's `utils` module can also be us ## Writing code -Have a look at the [docs for writing lints][adding_lints] for more details. [Llogiq's blog post on lints] -is also a nice primer to lint-writing, though it does get into advanced stuff and may be a bit outdated. +Have a look at the [docs for writing lints][adding_lints] for more details. If you want to add a new lint or change existing ones apart from bugfixing, it's also a good idea to give the [stability guarantees][rfc_stability] and @@ -87,7 +87,6 @@ also a good idea to give the [stability guarantees][rfc_stability] and quick read. [adding_lints]: https://github.com/rust-lang/rust-clippy/blob/master/doc/adding_lints.md -[Llogiq's blog post on lints]: https://llogiq.github.io/2015/06/04/workflows.html [clippy_rfc]: https://github.com/rust-lang/rfcs/blob/master/text/2476-clippy-uno.md [rfc_stability]: https://github.com/rust-lang/rfcs/blob/master/text/2476-clippy-uno.md#stability-guarantees [rfc_lint_cats]: https://github.com/rust-lang/rfcs/blob/master/text/2476-clippy-uno.md#lint-audit-and-categories From be34bc46ed7699c598e4525b07e04067e19e49aa Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 4 Apr 2020 12:47:16 -0700 Subject: [PATCH 28/58] Downgrade unreadable_literal to pedantic --- clippy_lints/src/lib.rs | 3 +-- clippy_lints/src/literal_representation.rs | 2 +- src/lintlist/mod.rs | 2 +- tests/ui/approx_const.rs | 2 +- tests/ui/inconsistent_digit_grouping.fixed | 1 + tests/ui/inconsistent_digit_grouping.rs | 1 + tests/ui/inconsistent_digit_grouping.stderr | 26 ++++++++++++--------- 7 files changed, 21 insertions(+), 16 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfc2a26b06b2..2e0a77068acd 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1098,6 +1098,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&items_after_statements::ITEMS_AFTER_STATEMENTS), LintId::of(&large_stack_arrays::LARGE_STACK_ARRAYS), LintId::of(&literal_representation::LARGE_DIGIT_GROUPS), + LintId::of(&literal_representation::UNREADABLE_LITERAL), LintId::of(&loops::EXPLICIT_INTO_ITER_LOOP), LintId::of(&loops::EXPLICIT_ITER_LOOP), LintId::of(¯o_use::MACRO_USE_IMPORTS), @@ -1219,7 +1220,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&lifetimes::NEEDLESS_LIFETIMES), LintId::of(&literal_representation::INCONSISTENT_DIGIT_GROUPING), LintId::of(&literal_representation::MISTYPED_LITERAL_SUFFIXES), - LintId::of(&literal_representation::UNREADABLE_LITERAL), LintId::of(&loops::EMPTY_LOOP), LintId::of(&loops::EXPLICIT_COUNTER_LOOP), LintId::of(&loops::FOR_KV_MAP), @@ -1428,7 +1428,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&len_zero::LEN_ZERO), LintId::of(&let_if_seq::USELESS_LET_IF_SEQ), LintId::of(&literal_representation::INCONSISTENT_DIGIT_GROUPING), - LintId::of(&literal_representation::UNREADABLE_LITERAL), LintId::of(&loops::EMPTY_LOOP), LintId::of(&loops::FOR_KV_MAP), LintId::of(&loops::NEEDLESS_RANGE_LOOP), diff --git a/clippy_lints/src/literal_representation.rs b/clippy_lints/src/literal_representation.rs index 1b0b111bcfed..0a6ffc1130a3 100644 --- a/clippy_lints/src/literal_representation.rs +++ b/clippy_lints/src/literal_representation.rs @@ -27,7 +27,7 @@ declare_clippy_lint! { /// let x: u64 = 61864918973511; /// ``` pub UNREADABLE_LITERAL, - style, + pedantic, "long integer literal without underscores" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 8a6d0af5f8a7..e24169bd3506 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -2294,7 +2294,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "unreadable_literal", - group: "style", + group: "pedantic", desc: "long integer literal without underscores", deprecation: None, module: "literal_representation", diff --git a/tests/ui/approx_const.rs b/tests/ui/approx_const.rs index e1c150fdefd4..fb57a0becbb2 100644 --- a/tests/ui/approx_const.rs +++ b/tests/ui/approx_const.rs @@ -1,5 +1,5 @@ #[warn(clippy::approx_constant)] -#[allow(unused, clippy::shadow_unrelated, clippy::similar_names, clippy::unreadable_literal)] +#[allow(unused, clippy::shadow_unrelated, clippy::similar_names)] fn main() { let my_e = 2.7182; let almost_e = 2.718; diff --git a/tests/ui/inconsistent_digit_grouping.fixed b/tests/ui/inconsistent_digit_grouping.fixed index f10673adfb2d..ae4d1806af49 100644 --- a/tests/ui/inconsistent_digit_grouping.fixed +++ b/tests/ui/inconsistent_digit_grouping.fixed @@ -1,5 +1,6 @@ // run-rustfix #[warn(clippy::inconsistent_digit_grouping)] +#[deny(clippy::unreadable_literal)] #[allow(unused_variables, clippy::excessive_precision)] fn main() { macro_rules! mac1 { diff --git a/tests/ui/inconsistent_digit_grouping.rs b/tests/ui/inconsistent_digit_grouping.rs index b97df0865ee8..a1ac21746f64 100644 --- a/tests/ui/inconsistent_digit_grouping.rs +++ b/tests/ui/inconsistent_digit_grouping.rs @@ -1,5 +1,6 @@ // run-rustfix #[warn(clippy::inconsistent_digit_grouping)] +#[deny(clippy::unreadable_literal)] #[allow(unused_variables, clippy::excessive_precision)] fn main() { macro_rules! mac1 { diff --git a/tests/ui/inconsistent_digit_grouping.stderr b/tests/ui/inconsistent_digit_grouping.stderr index 37211efcab5f..b8ac91554620 100644 --- a/tests/ui/inconsistent_digit_grouping.stderr +++ b/tests/ui/inconsistent_digit_grouping.stderr @@ -1,5 +1,5 @@ error: digits grouped inconsistently by underscores - --> $DIR/inconsistent_digit_grouping.rs:25:16 + --> $DIR/inconsistent_digit_grouping.rs:26:16 | LL | let bad = (1_23_456, 1_234_5678, 1234_567, 1_234.5678_f32, 1.234_5678_f32); | ^^^^^^^^ help: consider: `123_456` @@ -7,57 +7,61 @@ LL | let bad = (1_23_456, 1_234_5678, 1234_567, 1_234.5678_f32, 1.234_5678_f = note: `-D clippy::inconsistent-digit-grouping` implied by `-D warnings` error: digits grouped inconsistently by underscores - --> $DIR/inconsistent_digit_grouping.rs:25:26 + --> $DIR/inconsistent_digit_grouping.rs:26:26 | LL | let bad = (1_23_456, 1_234_5678, 1234_567, 1_234.5678_f32, 1.234_5678_f32); | ^^^^^^^^^^ help: consider: `12_345_678` error: digits grouped inconsistently by underscores - --> $DIR/inconsistent_digit_grouping.rs:25:38 + --> $DIR/inconsistent_digit_grouping.rs:26:38 | LL | let bad = (1_23_456, 1_234_5678, 1234_567, 1_234.5678_f32, 1.234_5678_f32); | ^^^^^^^^ help: consider: `1_234_567` error: digits grouped inconsistently by underscores - --> $DIR/inconsistent_digit_grouping.rs:25:48 + --> $DIR/inconsistent_digit_grouping.rs:26:48 | LL | let bad = (1_23_456, 1_234_5678, 1234_567, 1_234.5678_f32, 1.234_5678_f32); | ^^^^^^^^^^^^^^ help: consider: `1_234.567_8_f32` error: digits grouped inconsistently by underscores - --> $DIR/inconsistent_digit_grouping.rs:25:64 + --> $DIR/inconsistent_digit_grouping.rs:26:64 | LL | let bad = (1_23_456, 1_234_5678, 1234_567, 1_234.5678_f32, 1.234_5678_f32); | ^^^^^^^^^^^^^^ help: consider: `1.234_567_8_f32` error: long literal lacking separators - --> $DIR/inconsistent_digit_grouping.rs:28:13 + --> $DIR/inconsistent_digit_grouping.rs:29:13 | LL | let _ = 0x100000; | ^^^^^^^^ help: consider: `0x0010_0000` | - = note: `-D clippy::unreadable-literal` implied by `-D warnings` +note: the lint level is defined here + --> $DIR/inconsistent_digit_grouping.rs:3:8 + | +LL | #[deny(clippy::unreadable_literal)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: long literal lacking separators - --> $DIR/inconsistent_digit_grouping.rs:29:13 + --> $DIR/inconsistent_digit_grouping.rs:30:13 | LL | let _ = 0x1000000; | ^^^^^^^^^ help: consider: `0x0100_0000` error: long literal lacking separators - --> $DIR/inconsistent_digit_grouping.rs:30:13 + --> $DIR/inconsistent_digit_grouping.rs:31:13 | LL | let _ = 0x10000000; | ^^^^^^^^^^ help: consider: `0x1000_0000` error: long literal lacking separators - --> $DIR/inconsistent_digit_grouping.rs:31:13 + --> $DIR/inconsistent_digit_grouping.rs:32:13 | LL | let _ = 0x100000000_u64; | ^^^^^^^^^^^^^^^ help: consider: `0x0001_0000_0000_u64` error: digits grouped inconsistently by underscores - --> $DIR/inconsistent_digit_grouping.rs:34:18 + --> $DIR/inconsistent_digit_grouping.rs:35:18 | LL | let _: f32 = 1_23_456.; | ^^^^^^^^^ help: consider: `123_456.` From 560c8c9c701c0f84cdc725e00562c560b48dd0c2 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 4 Apr 2020 12:58:18 -0700 Subject: [PATCH 29/58] Downgrade new_ret_no_self to pedantic --- clippy_lints/src/lib.rs | 3 +-- clippy_lints/src/methods/mod.rs | 2 +- src/lintlist/mod.rs | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfc2a26b06b2..f6942f18476c 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1106,6 +1106,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::FILTER_MAP_NEXT), LintId::of(&methods::FIND_MAP), LintId::of(&methods::MAP_FLATTEN), + LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OPTION_MAP_UNWRAP_OR), LintId::of(&methods::OPTION_MAP_UNWRAP_OR_ELSE), LintId::of(&methods::RESULT_MAP_UNWRAP_OR_ELSE), @@ -1267,7 +1268,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::ITER_NTH_ZERO), LintId::of(&methods::ITER_SKIP_NEXT), LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC), - LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OK_EXPECT), LintId::of(&methods::OPTION_AND_THEN_SOME), LintId::of(&methods::OPTION_AS_REF_DEREF), @@ -1450,7 +1450,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::ITER_NTH_ZERO), LintId::of(&methods::ITER_SKIP_NEXT), LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC), - LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OK_EXPECT), LintId::of(&methods::OPTION_MAP_OR_NONE), LintId::of(&methods::SHOULD_IMPLEMENT_TRAIT), diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 527508af8a31..7d7a375ddac3 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -721,7 +721,7 @@ declare_clippy_lint! { /// } /// ``` pub NEW_RET_NO_SELF, - style, + pedantic, "not returning `Self` in a `new` method" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 8a6d0af5f8a7..0a565f4466fe 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -1447,7 +1447,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "new_ret_no_self", - group: "style", + group: "pedantic", desc: "not returning `Self` in a `new` method", deprecation: None, module: "methods", From 91759a7582a292c3f85204b1d61e7185c8543959 Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 13:42:24 -0700 Subject: [PATCH 30/58] result_map_or_into_option: explicitly note absence of known problems --- clippy_lints/src/methods/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index e8d642ed71e0..37bb3710fabc 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -336,7 +336,7 @@ declare_clippy_lint! { /// **Why is this bad?** Readability, this can be written more concisely as /// `_.ok()`. /// - /// **Known problems:** + /// **Known problems:** None. /// /// **Example:** /// ```rust From 3a29aedf8db3af19ee0f64dee6f00489812e6cb0 Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 13:44:11 -0700 Subject: [PATCH 31/58] result_map_or_into_option: add good and bad examples --- clippy_lints/src/methods/mod.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 37bb3710fabc..7c818232a553 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -340,8 +340,13 @@ declare_clippy_lint! { /// /// **Example:** /// ```rust - /// # let opt = Some(1); - /// # let r = opt.map_or(None, Some); + /// # Bad + /// let r: Result = Ok(1); + /// assert_eq!(Some(1), r.map_or(None, Some)); + /// + /// # Good + /// let r: Result = Ok(1); + /// assert_eq!(Some(1), r.ok()); /// ``` pub RESULT_MAP_OR_INTO_OPTION, style, From d0738bd673fe8e2b42d26b6d116f197f4aecea82 Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 13:53:08 -0700 Subject: [PATCH 32/58] result_map_or_into_option: destructure lint tuple or return early --- clippy_lints/src/methods/mod.rs | 74 +++++++++++++----------- tests/ui/result_map_or_into_option.fixed | 4 +- 2 files changed, 41 insertions(+), 37 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 7c818232a553..62fcd801bc30 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -2573,42 +2573,48 @@ fn lint_map_or_none<'a, 'tcx>( false }; - let mess = if is_option && default_arg_is_none { - let self_snippet = snippet(cx, map_or_args[0].span, ".."); - let func_snippet = snippet(cx, map_or_args[2].span, ".."); - let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \ - `and_then(f)` instead"; - Some(( - OPTION_MAP_OR_NONE, - msg, - "try using `and_then` instead", - format!("{0}.and_then({1})", self_snippet, func_snippet), - )) - } else if is_result && f_arg_is_some { - let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \ - `ok()` instead"; - let self_snippet = snippet(cx, map_or_args[0].span, ".."); - Some(( - RESULT_MAP_OR_INTO_OPTION, - msg, - "try using `ok` instead", - format!("{0}.ok()", self_snippet), - )) - } else { - None + let (lint, msg, instead, hint) = { + if !default_arg_is_none { + // nothing to lint! + return; + } + + if is_option { + let self_snippet = snippet(cx, map_or_args[0].span, ".."); + let func_snippet = snippet(cx, map_or_args[2].span, ".."); + let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \ + `and_then(f)` instead"; + ( + OPTION_MAP_OR_NONE, + msg, + "try using `and_then` instead", + format!("{0}.and_then({1})", self_snippet, func_snippet), + ) + } else if f_arg_is_some { + let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \ + `ok()` instead"; + let self_snippet = snippet(cx, map_or_args[0].span, ".."); + ( + RESULT_MAP_OR_INTO_OPTION, + msg, + "try using `ok` instead", + format!("{0}.ok()", self_snippet), + ) + } else { + // nothing to lint! + return; + } }; - if let Some((lint, msg, instead, hint)) = mess { - span_lint_and_sugg( - cx, - lint, - expr.span, - msg, - instead, - hint, - Applicability::MachineApplicable, - ); - } + span_lint_and_sugg( + cx, + lint, + expr.span, + msg, + instead, + hint, + Applicability::MachineApplicable, + ); } /// Lint use of `_.and_then(|x| Some(y))` for `Option`s diff --git a/tests/ui/result_map_or_into_option.fixed b/tests/ui/result_map_or_into_option.fixed index 948eb6a3aca1..07daf19fa250 100644 --- a/tests/ui/result_map_or_into_option.fixed +++ b/tests/ui/result_map_or_into_option.fixed @@ -6,9 +6,7 @@ fn main() { let opt: Result = Ok(1); let _ = opt.ok(); - let rewrap = |s: u32| -> Option { - Some(s) - }; + let rewrap = |s: u32| -> Option { Some(s) }; // A non-Some `f` arg should not emit the lint let opt: Result = Ok(1); From fb276dc3fa1d644ce6de1849ff3b78d3e54f5d9e Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 14:02:45 -0700 Subject: [PATCH 33/58] result_map_or_into_option: add `opt.map_or(None, |_| Some(y))` test --- tests/ui/result_map_or_into_option.fixed | 5 +++++ tests/ui/result_map_or_into_option.rs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/tests/ui/result_map_or_into_option.fixed b/tests/ui/result_map_or_into_option.fixed index 07daf19fa250..331531b5165f 100644 --- a/tests/ui/result_map_or_into_option.fixed +++ b/tests/ui/result_map_or_into_option.fixed @@ -11,4 +11,9 @@ fn main() { // A non-Some `f` arg should not emit the lint let opt: Result = Ok(1); let _ = opt.map_or(None, rewrap); + + // A non-Some `f` closure where the argument is not used as the + // return should not emit the lint + let opt: Result = Ok(1); + opt.map_or(None, |_x| Some(1)); } diff --git a/tests/ui/result_map_or_into_option.rs b/tests/ui/result_map_or_into_option.rs index d097c19e44b9..3058480e2ad3 100644 --- a/tests/ui/result_map_or_into_option.rs +++ b/tests/ui/result_map_or_into_option.rs @@ -11,4 +11,9 @@ fn main() { // A non-Some `f` arg should not emit the lint let opt: Result = Ok(1); let _ = opt.map_or(None, rewrap); + + // A non-Some `f` closure where the argument is not used as the + // return should not emit the lint + let opt: Result = Ok(1); + opt.map_or(None, |_x| Some(1)); } From acc3bc1ba27129f6fc5bda6d943046e9e2ad2d45 Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 14:24:22 -0700 Subject: [PATCH 34/58] result_map_or_into_option: move arg checks into tuple assignment --- clippy_lints/src/methods/mod.rs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 62fcd801bc30..d57cce47ff9b 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -2559,26 +2559,27 @@ fn lint_map_or_none<'a, 'tcx>( return; } - let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind { - match_qpath(qpath, &paths::OPTION_NONE) - } else { - false - }; - // This is really only needed if `is_result` holds. Computing it here - // makes `mess`'s assignment a bit easier, so just compute it here. - let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind { - match_qpath(qpath, &paths::OPTION_SOME) - } else { - false - }; let (lint, msg, instead, hint) = { + + let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind { + match_qpath(qpath, &paths::OPTION_NONE) + } else { + return; + }; + if !default_arg_is_none { // nothing to lint! return; } + let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind { + match_qpath(qpath, &paths::OPTION_SOME) + } else { + false + }; + if is_option { let self_snippet = snippet(cx, map_or_args[0].span, ".."); let func_snippet = snippet(cx, map_or_args[2].span, ".."); From 2533f56a0eaa4ebbeb607b6596d12e303f97e008 Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 14:33:43 -0700 Subject: [PATCH 35/58] result_map_or_into_option: fix `cargo dev fmt --check` errors --- clippy_lints/src/methods/mod.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index d57cce47ff9b..9ff669515cf8 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -2559,10 +2559,7 @@ fn lint_map_or_none<'a, 'tcx>( return; } - - let (lint, msg, instead, hint) = { - let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind { match_qpath(qpath, &paths::OPTION_NONE) } else { From fecdb72b14031617f1245db279ddffb6840e1dac Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 14:39:24 -0700 Subject: [PATCH 36/58] CONTRIBUTING.md: fix broken triage link --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b1f9be44b73d..614caf9cd27d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -223,7 +223,7 @@ You can find the Clippy bors queue [here][homu_queue]. If you have @bors permissions, you can find an overview of the available commands [here][homu_instructions]. -[triage]: https://forge.rust-lang.org/triage-procedure.html +[triage]: https://forge.rust-lang.org/release/triage-procedure.html [l-crash]: https://github.com/rust-lang/rust-clippy/labels/L-crash%20%3Aboom%3A [l-bug]: https://github.com/rust-lang/rust-clippy/labels/L-bug%20%3Abeetle%3A [homu]: https://github.com/rust-lang/homu From 325d0b69d2dffccecf48c5d7975ccd100141e1f5 Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 15:02:38 -0700 Subject: [PATCH 37/58] result_map_or_into: fix dogfood_clippy error => {h,l}int --- clippy_lints/src/methods/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 9ff669515cf8..7f4964da72e7 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -2559,7 +2559,7 @@ fn lint_map_or_none<'a, 'tcx>( return; } - let (lint, msg, instead, hint) = { + let (lint_name, msg, instead, hint) = { let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind { match_qpath(qpath, &paths::OPTION_NONE) } else { @@ -2606,7 +2606,7 @@ fn lint_map_or_none<'a, 'tcx>( span_lint_and_sugg( cx, - lint, + lint_name, expr.span, msg, instead, From 5d54fbb7914cc1ea5b3bd8cdfd6f24dbacd8f649 Mon Sep 17 00:00:00 2001 From: Nick Torres Date: Sat, 4 Apr 2020 17:20:23 -0700 Subject: [PATCH 38/58] result_map_or_into_option: fix syntax error in example --- clippy_lints/src/methods/mod.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 7f4964da72e7..98d9426bd8a5 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -339,13 +339,16 @@ declare_clippy_lint! { /// **Known problems:** None. /// /// **Example:** + /// + /// Bad: /// ```rust - /// # Bad - /// let r: Result = Ok(1); + /// # let r: Result = Ok(1); /// assert_eq!(Some(1), r.map_or(None, Some)); + /// ``` /// - /// # Good - /// let r: Result = Ok(1); + /// Good: + /// ```rust + /// # let r: Result = Ok(1); /// assert_eq!(Some(1), r.ok()); /// ``` pub RESULT_MAP_OR_INTO_OPTION, From 9c9af1d88525de5649375e08abf16437426349b8 Mon Sep 17 00:00:00 2001 From: Jacek Pospychala Date: Sun, 5 Apr 2020 20:40:51 +0200 Subject: [PATCH 39/58] Include OpAssign in suspicious_op_assign_impl --- clippy_lints/src/suspicious_trait_impl.rs | 10 ++++++---- tests/ui/suspicious_arithmetic_impl.rs | 21 ++++++++++++++++++++- tests/ui/suspicious_arithmetic_impl.stderr | 8 +++++++- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/clippy_lints/src/suspicious_trait_impl.rs b/clippy_lints/src/suspicious_trait_impl.rs index 89b57ed1a8de..f1e223d9a48c 100644 --- a/clippy_lints/src/suspicious_trait_impl.rs +++ b/clippy_lints/src/suspicious_trait_impl.rs @@ -54,7 +54,7 @@ declare_lint_pass!(SuspiciousImpl => [SUSPICIOUS_ARITHMETIC_IMPL, SUSPICIOUS_OP_ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for SuspiciousImpl { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) { - if let hir::ExprKind::Binary(binop, _, _) = expr.kind { + if let hir::ExprKind::Binary(binop, _, _) | hir::ExprKind::AssignOp(binop, ..) = expr.kind { match binop.node { hir::BinOpKind::Eq | hir::BinOpKind::Lt @@ -65,14 +65,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for SuspiciousImpl { _ => {}, } // Check if the binary expression is part of another bi/unary expression - // as a child node + // or operator assignment as a child node let mut parent_expr = cx.tcx.hir().get_parent_node(expr.hir_id); while parent_expr != hir::CRATE_HIR_ID { if let hir::Node::Expr(e) = cx.tcx.hir().get(parent_expr) { match e.kind { hir::ExprKind::Binary(..) | hir::ExprKind::Unary(hir::UnOp::UnNot, _) - | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => return, + | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) + | hir::ExprKind::AssignOp(..) => return, _ => {}, } } @@ -191,7 +192,8 @@ impl<'a, 'tcx> Visitor<'tcx> for BinaryExprVisitor { match expr.kind { hir::ExprKind::Binary(..) | hir::ExprKind::Unary(hir::UnOp::UnNot, _) - | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => self.in_binary_expr = true, + | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) + | hir::ExprKind::AssignOp(..) => self.in_binary_expr = true, _ => {}, } diff --git a/tests/ui/suspicious_arithmetic_impl.rs b/tests/ui/suspicious_arithmetic_impl.rs index 6ee924d3b2ed..1f5b98118870 100644 --- a/tests/ui/suspicious_arithmetic_impl.rs +++ b/tests/ui/suspicious_arithmetic_impl.rs @@ -1,5 +1,5 @@ #![warn(clippy::suspicious_arithmetic_impl)] -use std::ops::{Add, AddAssign, Div, Mul, Sub}; +use std::ops::{Add, AddAssign, BitOrAssign, Div, DivAssign, Mul, MulAssign, Sub}; #[derive(Copy, Clone)] struct Foo(u32); @@ -18,6 +18,25 @@ impl AddAssign for Foo { } } +impl BitOrAssign for Foo { + fn bitor_assign(&mut self, other: Foo) { + let idx = other.0; + self.0 |= 1 << idx; // OK: BinOpKind::Shl part of AssignOp as child node + } +} + +impl MulAssign for Foo { + fn mul_assign(&mut self, other: Foo) { + self.0 /= other.0; + } +} + +impl DivAssign for Foo { + fn div_assign(&mut self, other: Foo) { + self.0 /= other.0; // OK: BinOpKind::Div == DivAssign + } +} + impl Mul for Foo { type Output = Foo; diff --git a/tests/ui/suspicious_arithmetic_impl.stderr b/tests/ui/suspicious_arithmetic_impl.stderr index e8a6efc4c4d2..7e42d72c30b2 100644 --- a/tests/ui/suspicious_arithmetic_impl.stderr +++ b/tests/ui/suspicious_arithmetic_impl.stderr @@ -14,5 +14,11 @@ LL | *self = *self - other; | = note: `#[deny(clippy::suspicious_op_assign_impl)]` on by default -error: aborting due to 2 previous errors +error: Suspicious use of binary operator in `MulAssign` impl + --> $DIR/suspicious_arithmetic_impl.rs:30:16 + | +LL | self.0 /= other.0; + | ^^ + +error: aborting due to 3 previous errors From 4f14826e091e08f1ee4ff06d3ca6d5015045cfb5 Mon Sep 17 00:00:00 2001 From: xiongmao86 Date: Mon, 6 Apr 2020 21:48:38 +0800 Subject: [PATCH 40/58] Lint on opt.as_ref().map(|x| &**x). --- clippy_lints/src/loops.rs | 4 +-- clippy_lints/src/methods/mod.rs | 49 ++++++++++++++++++++--------- tests/ui/option_as_ref_deref.fixed | 3 ++ tests/ui/option_as_ref_deref.rs | 3 ++ tests/ui/option_as_ref_deref.stderr | 14 ++++++++- 5 files changed, 55 insertions(+), 18 deletions(-) diff --git a/clippy_lints/src/loops.rs b/clippy_lints/src/loops.rs index 43217b6cc64e..7cc21e4bdd23 100644 --- a/clippy_lints/src/loops.rs +++ b/clippy_lints/src/loops.rs @@ -654,7 +654,7 @@ fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult { let stmts = block.stmts.iter().map(stmt_to_expr); - let expr = once(block.expr.as_ref().map(|p| &**p)); + let expr = once(block.expr.as_deref()); let mut iter = stmts.chain(expr).filter_map(|e| e); never_loop_expr_seq(&mut iter, main_loop_id) } @@ -662,7 +662,7 @@ fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult { fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> { match stmt.kind { StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e), - StmtKind::Local(ref local) => local.init.as_ref().map(|p| &**p), + StmtKind::Local(ref local) => local.init.as_deref(), _ => None, } } diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 527508af8a31..6f85d1d69596 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -3159,6 +3159,8 @@ fn lint_option_as_ref_deref<'a, 'tcx>( map_args: &[hir::Expr<'_>], is_mut: bool, ) { + let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not); + let option_ty = cx.tables.expr_ty(&as_ref_args[0]); if !match_type(cx, option_ty, &paths::OPTION) { return; @@ -3181,23 +3183,40 @@ fn lint_option_as_ref_deref<'a, 'tcx>( hir::ExprKind::Closure(_, _, body_id, _, _) => { let closure_body = cx.tcx.hir().body(body_id); let closure_expr = remove_blocks(&closure_body.value); - if_chain! { - if let hir::ExprKind::MethodCall(_, _, args) = &closure_expr.kind; - if args.len() == 1; - if let hir::ExprKind::Path(qpath) = &args[0].kind; - if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id); - if closure_body.params[0].pat.hir_id == local_id; - let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::>(); - if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj; - then { - let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap(); - deref_aliases.iter().any(|path| match_def_path(cx, method_did, path)) - } else { - false - } + + match &closure_expr.kind { + hir::ExprKind::MethodCall(_, _, args) => { + if_chain! { + if args.len() == 1; + if let hir::ExprKind::Path(qpath) = &args[0].kind; + if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id); + if closure_body.params[0].pat.hir_id == local_id; + let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::>(); + if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj; + then { + let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap(); + deref_aliases.iter().any(|path| match_def_path(cx, method_did, path)) + } else { + false + } + } + }, + hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => { + if_chain! { + if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind; + if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind; + if let hir::ExprKind::Path(ref qpath) = inner2.kind; + if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, inner2.hir_id); + then { + closure_body.params[0].pat.hir_id == local_id + } else { + false + } + } + }, + _ => false, } }, - _ => false, }; diff --git a/tests/ui/option_as_ref_deref.fixed b/tests/ui/option_as_ref_deref.fixed index 973e5b308a2c..076692e64451 100644 --- a/tests/ui/option_as_ref_deref.fixed +++ b/tests/ui/option_as_ref_deref.fixed @@ -35,4 +35,7 @@ fn main() { let _ = Some(1_usize).as_ref().map(|x| vc[*x].as_str()); // should not be linted let _: Option<&str> = Some(&String::new()).as_ref().map(|x| x.as_str()); // should not be linted + + let _ = opt.as_deref(); + let _ = opt.as_deref_mut(); } diff --git a/tests/ui/option_as_ref_deref.rs b/tests/ui/option_as_ref_deref.rs index baad85ab9083..3bf5f715f833 100644 --- a/tests/ui/option_as_ref_deref.rs +++ b/tests/ui/option_as_ref_deref.rs @@ -38,4 +38,7 @@ fn main() { let _ = Some(1_usize).as_ref().map(|x| vc[*x].as_str()); // should not be linted let _: Option<&str> = Some(&String::new()).as_ref().map(|x| x.as_str()); // should not be linted + + let _ = opt.as_ref().map(|x| &**x); + let _ = opt.as_mut().map(|x| &mut **x); } diff --git a/tests/ui/option_as_ref_deref.stderr b/tests/ui/option_as_ref_deref.stderr index 09a0fa058e62..6c2bf8517060 100644 --- a/tests/ui/option_as_ref_deref.stderr +++ b/tests/ui/option_as_ref_deref.stderr @@ -88,5 +88,17 @@ error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases LL | let _ = opt.clone().as_mut().map(|x| x.deref_mut()).map(|x| x.len()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref_mut instead: `opt.clone().as_deref_mut()` -error: aborting due to 14 previous errors +error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref()` instead + --> $DIR/option_as_ref_deref.rs:42:13 + | +LL | let _ = opt.as_ref().map(|x| &**x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `opt.as_deref()` + +error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead + --> $DIR/option_as_ref_deref.rs:43:13 + | +LL | let _ = opt.as_mut().map(|x| &mut **x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref_mut instead: `opt.as_deref_mut()` + +error: aborting due to 16 previous errors From d7056f8ffba7ad87622b7fdcc429f33abc5c62a7 Mon Sep 17 00:00:00 2001 From: xiongmao86 Date: Tue, 7 Apr 2020 21:25:07 +0800 Subject: [PATCH 41/58] Refine lint message. --- clippy_lints/src/methods/mod.rs | 8 ++++---- tests/ui/option_as_ref_deref.stderr | 32 ++++++++++++++--------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 6f85d1d69596..0f331aad0682 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -3222,17 +3222,17 @@ fn lint_option_as_ref_deref<'a, 'tcx>( if is_deref { let current_method = if is_mut { - ".as_mut().map(DerefMut::deref_mut)" + format!(".as_mut().map({})", snippet(cx, map_args[1].span, "..")) } else { - ".as_ref().map(Deref::deref)" + format!(".as_ref().map({})", snippet(cx, map_args[1].span, "..")) }; let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" }; let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint); let suggestion = format!("try using {} instead", method_hint); let msg = format!( - "called `{0}` (or with one of deref aliases) on an Option value. \ - This can be done more directly by calling `{1}` instead", + "called `{0}` on an Option value. This can be done more directly \ + by calling `{1}` instead", current_method, hint ); span_lint_and_sugg( diff --git a/tests/ui/option_as_ref_deref.stderr b/tests/ui/option_as_ref_deref.stderr index 6c2bf8517060..a106582a6332 100644 --- a/tests/ui/option_as_ref_deref.stderr +++ b/tests/ui/option_as_ref_deref.stderr @@ -1,4 +1,4 @@ -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.clone().as_deref()` instead +error: called `.as_ref().map(Deref::deref)` on an Option value. This can be done more directly by calling `opt.clone().as_deref()` instead --> $DIR/option_as_ref_deref.rs:13:13 | LL | let _ = opt.clone().as_ref().map(Deref::deref).map(str::len); @@ -6,7 +6,7 @@ LL | let _ = opt.clone().as_ref().map(Deref::deref).map(str::len); | = note: `-D clippy::option-as-ref-deref` implied by `-D warnings` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.clone().as_deref()` instead +error: called `.as_ref().map(Deref::deref)` on an Option value. This can be done more directly by calling `opt.clone().as_deref()` instead --> $DIR/option_as_ref_deref.rs:16:13 | LL | let _ = opt.clone() @@ -16,85 +16,85 @@ LL | | Deref::deref LL | | ) | |_________^ help: try using as_deref instead: `opt.clone().as_deref()` -error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead +error: called `.as_mut().map(DerefMut::deref_mut)` on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead --> $DIR/option_as_ref_deref.rs:22:13 | LL | let _ = opt.as_mut().map(DerefMut::deref_mut); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref_mut instead: `opt.as_deref_mut()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref()` instead +error: called `.as_ref().map(String::as_str)` on an Option value. This can be done more directly by calling `opt.as_deref()` instead --> $DIR/option_as_ref_deref.rs:24:13 | LL | let _ = opt.as_ref().map(String::as_str); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `opt.as_deref()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref()` instead +error: called `.as_ref().map(|x| x.as_str())` on an Option value. This can be done more directly by calling `opt.as_deref()` instead --> $DIR/option_as_ref_deref.rs:25:13 | LL | let _ = opt.as_ref().map(|x| x.as_str()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `opt.as_deref()` -error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead +error: called `.as_mut().map(String::as_mut_str)` on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead --> $DIR/option_as_ref_deref.rs:26:13 | LL | let _ = opt.as_mut().map(String::as_mut_str); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref_mut instead: `opt.as_deref_mut()` -error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead +error: called `.as_mut().map(|x| x.as_mut_str())` on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead --> $DIR/option_as_ref_deref.rs:27:13 | LL | let _ = opt.as_mut().map(|x| x.as_mut_str()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref_mut instead: `opt.as_deref_mut()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `Some(CString::new(vec![]).unwrap()).as_deref()` instead +error: called `.as_ref().map(CString::as_c_str)` on an Option value. This can be done more directly by calling `Some(CString::new(vec![]).unwrap()).as_deref()` instead --> $DIR/option_as_ref_deref.rs:28:13 | LL | let _ = Some(CString::new(vec![]).unwrap()).as_ref().map(CString::as_c_str); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `Some(CString::new(vec![]).unwrap()).as_deref()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `Some(OsString::new()).as_deref()` instead +error: called `.as_ref().map(OsString::as_os_str)` on an Option value. This can be done more directly by calling `Some(OsString::new()).as_deref()` instead --> $DIR/option_as_ref_deref.rs:29:13 | LL | let _ = Some(OsString::new()).as_ref().map(OsString::as_os_str); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `Some(OsString::new()).as_deref()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `Some(PathBuf::new()).as_deref()` instead +error: called `.as_ref().map(PathBuf::as_path)` on an Option value. This can be done more directly by calling `Some(PathBuf::new()).as_deref()` instead --> $DIR/option_as_ref_deref.rs:30:13 | LL | let _ = Some(PathBuf::new()).as_ref().map(PathBuf::as_path); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `Some(PathBuf::new()).as_deref()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `Some(Vec::<()>::new()).as_deref()` instead +error: called `.as_ref().map(Vec::as_slice)` on an Option value. This can be done more directly by calling `Some(Vec::<()>::new()).as_deref()` instead --> $DIR/option_as_ref_deref.rs:31:13 | LL | let _ = Some(Vec::<()>::new()).as_ref().map(Vec::as_slice); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `Some(Vec::<()>::new()).as_deref()` -error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `Some(Vec::<()>::new()).as_deref_mut()` instead +error: called `.as_mut().map(Vec::as_mut_slice)` on an Option value. This can be done more directly by calling `Some(Vec::<()>::new()).as_deref_mut()` instead --> $DIR/option_as_ref_deref.rs:32:13 | LL | let _ = Some(Vec::<()>::new()).as_mut().map(Vec::as_mut_slice); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref_mut instead: `Some(Vec::<()>::new()).as_deref_mut()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref()` instead +error: called `.as_ref().map(|x| x.deref())` on an Option value. This can be done more directly by calling `opt.as_deref()` instead --> $DIR/option_as_ref_deref.rs:34:13 | LL | let _ = opt.as_ref().map(|x| x.deref()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `opt.as_deref()` -error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.clone().as_deref_mut()` instead +error: called `.as_mut().map(|x| x.deref_mut())` on an Option value. This can be done more directly by calling `opt.clone().as_deref_mut()` instead --> $DIR/option_as_ref_deref.rs:35:13 | LL | let _ = opt.clone().as_mut().map(|x| x.deref_mut()).map(|x| x.len()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref_mut instead: `opt.clone().as_deref_mut()` -error: called `.as_ref().map(Deref::deref)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref()` instead +error: called `.as_ref().map(|x| &**x)` on an Option value. This can be done more directly by calling `opt.as_deref()` instead --> $DIR/option_as_ref_deref.rs:42:13 | LL | let _ = opt.as_ref().map(|x| &**x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using as_deref instead: `opt.as_deref()` -error: called `.as_mut().map(DerefMut::deref_mut)` (or with one of deref aliases) on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead +error: called `.as_mut().map(|x| &mut **x)` on an Option value. This can be done more directly by calling `opt.as_deref_mut()` instead --> $DIR/option_as_ref_deref.rs:43:13 | LL | let _ = opt.as_mut().map(|x| &mut **x); From 18520aa8b2e2aa200c5f1756bfd9ab4d3294c995 Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Tue, 7 Apr 2020 19:51:59 +0000 Subject: [PATCH 42/58] Only /usr/bin/env is portable in shebangs. --- setup-toolchain.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup-toolchain.sh b/setup-toolchain.sh index 469cba1874d6..6038ed697f91 100755 --- a/setup-toolchain.sh +++ b/setup-toolchain.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # Set up the appropriate rustc toolchain set -e From 89e14d201db8c8dc49fab4c1d17d6546b00817ae Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Tue, 7 Apr 2020 19:53:02 +0000 Subject: [PATCH 43/58] use_self: switch to hir_ty_to_ty. --- clippy_lints/src/use_self.rs | 91 ++++++++++++++++-------------------- 1 file changed, 41 insertions(+), 50 deletions(-) diff --git a/clippy_lints/src/use_self.rs b/clippy_lints/src/use_self.rs index 4fcaf3cdb96e..412bebb9bc6e 100644 --- a/clippy_lints/src/use_self.rs +++ b/clippy_lints/src/use_self.rs @@ -14,6 +14,7 @@ use rustc_middle::ty; use rustc_middle::ty::{DefIdTree, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::kw; +use rustc_typeck::hir_ty_to_ty; use crate::utils::{differing_macro_contexts, span_lint_and_sugg}; @@ -80,37 +81,28 @@ fn span_use_self_lint(cx: &LateContext<'_, '_>, path: &Path<'_>, last_segment: O ); } -struct TraitImplTyVisitor<'a, 'tcx> { - item_type: Ty<'tcx>, +// FIXME: always use this (more correct) visitor, not just in method signatures. +struct SemanticUseSelfVisitor<'a, 'tcx> { cx: &'a LateContext<'a, 'tcx>, - trait_type_walker: ty::walk::TypeWalker<'tcx>, - impl_type_walker: ty::walk::TypeWalker<'tcx>, + self_ty: Ty<'tcx>, } -impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> { +impl<'a, 'tcx> Visitor<'tcx> for SemanticUseSelfVisitor<'a, 'tcx> { type Map = Map<'tcx>; - fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) { - let trait_ty = self.trait_type_walker.next(); - let impl_ty = self.impl_type_walker.next(); - - if_chain! { - if let TyKind::Path(QPath::Resolved(_, path)) = &t.kind; - - // The implementation and trait types don't match which means that - // the concrete type was specified by the implementation - if impl_ty != trait_ty; - if let Some(impl_ty) = impl_ty; - if self.item_type == impl_ty; - then { - match path.res { - def::Res::SelfTy(..) => {}, - _ => span_use_self_lint(self.cx, path, None) - } + fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'_>) { + if let TyKind::Path(QPath::Resolved(_, path)) = &hir_ty.kind { + match path.res { + def::Res::SelfTy(..) => {}, + _ => { + if hir_ty_to_ty(self.cx.tcx, hir_ty) == self.self_ty { + span_use_self_lint(self.cx, path, None); + } + }, } } - walk_ty(self, t) + walk_ty(self, hir_ty) } fn nested_visit_map(&mut self) -> NestedVisitorMap { @@ -120,10 +112,9 @@ impl<'a, 'tcx> Visitor<'tcx> for TraitImplTyVisitor<'a, 'tcx> { fn check_trait_method_impl_decl<'a, 'tcx>( cx: &'a LateContext<'a, 'tcx>, - item_type: Ty<'tcx>, impl_item: &ImplItem<'_>, impl_decl: &'tcx FnDecl<'_>, - impl_trait_ref: &ty::TraitRef<'_>, + impl_trait_ref: ty::TraitRef<'tcx>, ) { let trait_method = cx .tcx @@ -134,34 +125,35 @@ fn check_trait_method_impl_decl<'a, 'tcx>( let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id); let trait_method_sig = cx.tcx.erase_late_bound_regions(&trait_method_sig); - let impl_method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id); - let impl_method_sig = cx.tcx.fn_sig(impl_method_def_id); - let impl_method_sig = cx.tcx.erase_late_bound_regions(&impl_method_sig); - - let output_ty = if let FnRetTy::Return(ty) = &impl_decl.output { + let output_hir_ty = if let FnRetTy::Return(ty) = &impl_decl.output { Some(&**ty) } else { None }; - // `impl_decl_ty` (of type `hir::Ty`) represents the type declared in the signature. - // `impl_ty` (of type `ty:TyS`) is the concrete type that the compiler has determined for - // that declaration. We use `impl_decl_ty` to see if the type was declared as `Self` - // and use `impl_ty` to check its concrete type. - for (impl_decl_ty, (impl_ty, trait_ty)) in impl_decl.inputs.iter().chain(output_ty).zip( - impl_method_sig - .inputs_and_output - .iter() - .zip(trait_method_sig.inputs_and_output), - ) { - let mut visitor = TraitImplTyVisitor { - cx, - item_type, - trait_type_walker: trait_ty.walk(), - impl_type_walker: impl_ty.walk(), - }; - - visitor.visit_ty(&impl_decl_ty); + // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature. + // `trait_ty` (of type `ty::Ty`) is the semantic type for the signature in the trait. + // We use `impl_hir_ty` to see if the type was written as `Self`, + // `hir_ty_to_ty(...)` to check semantic types of paths, and + // `trait_ty` to determine which parts of the signature in the trait, mention + // the type being implemented verbatim (as opposed to `Self`). + for (impl_hir_ty, trait_ty) in impl_decl + .inputs + .iter() + .chain(output_hir_ty) + .zip(trait_method_sig.inputs_and_output) + { + // Check if the input/output type in the trait method specifies the implemented + // type verbatim, and only suggest `Self` if that isn't the case. + // This avoids suggestions to e.g. replace `Vec` with `Vec`, + // in an `impl Trait for u8`, when the trait always uses `Vec`. + // See also https://github.com/rust-lang/rust-clippy/issues/2894. + let self_ty = impl_trait_ref.self_ty(); + if !trait_ty.walk().any(|inner| inner == self_ty.into()) { + let mut visitor = SemanticUseSelfVisitor { cx, self_ty }; + + visitor.visit_ty(&impl_hir_ty); + } } } @@ -197,8 +189,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UseSelf { let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id); if let ImplItemKind::Fn(FnSig{ decl: impl_decl, .. }, impl_body_id) = &impl_item.kind { - let item_type = cx.tcx.type_of(impl_def_id); - check_trait_method_impl_decl(cx, item_type, impl_item, impl_decl, &impl_trait_ref); + check_trait_method_impl_decl(cx, impl_item, impl_decl, impl_trait_ref); let body = cx.tcx.hir().body(*impl_body_id); visitor.visit_body(body); From 2ad4d6a057e17c727ab007faed346d83fc1f33d3 Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Tue, 7 Apr 2020 19:53:56 +0000 Subject: [PATCH 44/58] rustup: update for the new Ty::walk interface. --- clippy_lints/src/let_underscore.rs | 10 ++++++++-- clippy_lints/src/methods/mod.rs | 25 ++++++++++++++++--------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/clippy_lints/src/let_underscore.rs b/clippy_lints/src/let_underscore.rs index a68f7edd8370..da83b1f3ce66 100644 --- a/clippy_lints/src/let_underscore.rs +++ b/clippy_lints/src/let_underscore.rs @@ -2,6 +2,7 @@ use if_chain::if_chain; use rustc_hir::{Local, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; +use rustc_middle::ty::subst::GenericArgKind; use rustc_session::{declare_lint_pass, declare_tool_lint}; use crate::utils::{is_must_use_func_call, is_must_use_ty, match_type, paths, span_lint_and_help}; @@ -75,8 +76,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { if let PatKind::Wild = local.pat.kind; if let Some(ref init) = local.init; then { - let check_ty = |ty| SYNC_GUARD_PATHS.iter().any(|path| match_type(cx, ty, path)); - if cx.tables.expr_ty(init).walk().any(check_ty) { + let init_ty = cx.tables.expr_ty(init); + let contains_sync_guard = init_ty.walk().any(|inner| match inner.unpack() { + GenericArgKind::Type(inner_ty) => SYNC_GUARD_PATHS.iter().any(|path| match_type(cx, inner_ty, path)), + + GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false, + }); + if contains_sync_guard { span_lint_and_help( cx, LET_UNDERSCORE_LOCK, diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 527508af8a31..124fc1d9878e 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -15,6 +15,7 @@ use rustc_hir::intravisit::{self, Visitor}; use rustc_lint::{LateContext, LateLintPass, Lint, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; +use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, Predicate, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; @@ -1407,7 +1408,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id); let item = cx.tcx.hir().expect_item(parent); let def_id = cx.tcx.hir().local_def_id(item.hir_id); - let ty = cx.tcx.type_of(def_id); + let self_ty = cx.tcx.type_of(def_id); if_chain! { if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind; if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next(); @@ -1429,7 +1430,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { if name == method_name && sig.decl.inputs.len() == n_args && out_type.matches(cx, &sig.decl.output) && - self_kind.matches(cx, ty, first_arg_ty) { + self_kind.matches(cx, self_ty, first_arg_ty) { span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!( "defining a method called `{}` on this type; consider implementing \ the `{}` trait or choosing a less ambiguous name", name, trait_name)); @@ -1441,7 +1442,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { .iter() .find(|(ref conv, _)| conv.check(&name)) { - if !self_kinds.iter().any(|k| k.matches(cx, ty, first_arg_ty)) { + if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) { let lint = if item.vis.node.is_pub() { WRONG_PUB_SELF_CONVENTION } else { @@ -1471,8 +1472,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { if let hir::ImplItemKind::Fn(_, _) = impl_item.kind { let ret_ty = return_ty(cx, impl_item.hir_id); + let contains_self_ty = |ty: Ty<'tcx>| { + ty.walk().any(|inner| match inner.unpack() { + GenericArgKind::Type(inner_ty) => same_tys(cx, self_ty, inner_ty), + + GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false, + }) + }; + // walk the return type and check for Self (this does not check associated types) - if ret_ty.walk().any(|inner_type| same_tys(cx, ty, inner_type)) { + if contains_self_ty(ret_ty) { return; } @@ -1486,10 +1495,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { let associated_type = binder.skip_binder(); // walk the associated type and check for Self - for inner_type in associated_type.walk() { - if same_tys(cx, ty, inner_type) { - return; - } + if contains_self_ty(associated_type) { + return; } }, (_, _) => {}, @@ -1497,7 +1504,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { } } - if name == "new" && !same_tys(cx, ret_ty, ty) { + if name == "new" && !same_tys(cx, ret_ty, self_ty) { span_lint( cx, NEW_RET_NO_SELF, From f5b6a0c54da3c9f94ccd53fae77dbf58fa16e680 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Tue, 7 Apr 2020 22:19:20 +0200 Subject: [PATCH 45/58] Format clippy_lints/src/let_underscore.rs --- clippy_lints/src/let_underscore.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/clippy_lints/src/let_underscore.rs b/clippy_lints/src/let_underscore.rs index da83b1f3ce66..f8f84f3d42d0 100644 --- a/clippy_lints/src/let_underscore.rs +++ b/clippy_lints/src/let_underscore.rs @@ -78,7 +78,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { then { let init_ty = cx.tables.expr_ty(init); let contains_sync_guard = init_ty.walk().any(|inner| match inner.unpack() { - GenericArgKind::Type(inner_ty) => SYNC_GUARD_PATHS.iter().any(|path| match_type(cx, inner_ty, path)), + GenericArgKind::Type(inner_ty) => { + SYNC_GUARD_PATHS.iter().any(|path| match_type(cx, inner_ty, path)) + }, GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false, }); From 0b4ee9a649318e78e1b3d1ade63669d5701c71b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Mon, 6 Apr 2020 23:53:11 +0200 Subject: [PATCH 46/58] Fix NAN comparison lint to use assoc NAN --- clippy_lints/src/misc.rs | 5 +-- tests/ui/cmp_nan.rs | 28 ++++++------ tests/ui/cmp_nan.stderr | 96 ++++++++++++++++++++-------------------- 3 files changed, 64 insertions(+), 65 deletions(-) diff --git a/clippy_lints/src/misc.rs b/clippy_lints/src/misc.rs index 0dc55b7f7beb..35f78dd22bd2 100644 --- a/clippy_lints/src/misc.rs +++ b/clippy_lints/src/misc.rs @@ -57,10 +57,9 @@ declare_clippy_lint! { /// /// **Example:** /// ```rust - /// # use core::f32::NAN; /// # let x = 1.0; /// - /// if x == NAN { } + /// if x == f32::NAN { } /// ``` pub CMP_NAN, correctness, @@ -457,7 +456,7 @@ fn check_nan(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) { cx, CMP_NAN, cmp_expr.span, - "doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead", + "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead", ); } } diff --git a/tests/ui/cmp_nan.rs b/tests/ui/cmp_nan.rs index f89ccddbfa44..64ca52b010a7 100644 --- a/tests/ui/cmp_nan.rs +++ b/tests/ui/cmp_nan.rs @@ -1,16 +1,16 @@ -const NAN_F32: f32 = std::f32::NAN; -const NAN_F64: f64 = std::f64::NAN; +const NAN_F32: f32 = f32::NAN; +const NAN_F64: f64 = f64::NAN; #[warn(clippy::cmp_nan)] #[allow(clippy::float_cmp, clippy::no_effect, clippy::unnecessary_operation)] fn main() { let x = 5f32; - x == std::f32::NAN; - x != std::f32::NAN; - x < std::f32::NAN; - x > std::f32::NAN; - x <= std::f32::NAN; - x >= std::f32::NAN; + x == f32::NAN; + x != f32::NAN; + x < f32::NAN; + x > f32::NAN; + x <= f32::NAN; + x >= f32::NAN; x == NAN_F32; x != NAN_F32; x < NAN_F32; @@ -19,12 +19,12 @@ fn main() { x >= NAN_F32; let y = 0f64; - y == std::f64::NAN; - y != std::f64::NAN; - y < std::f64::NAN; - y > std::f64::NAN; - y <= std::f64::NAN; - y >= std::f64::NAN; + y == f64::NAN; + y != f64::NAN; + y < f64::NAN; + y > f64::NAN; + y <= f64::NAN; + y >= f64::NAN; y == NAN_F64; y != NAN_F64; y < NAN_F64; diff --git a/tests/ui/cmp_nan.stderr b/tests/ui/cmp_nan.stderr index 7aceeeaf78fc..867516661a53 100644 --- a/tests/ui/cmp_nan.stderr +++ b/tests/ui/cmp_nan.stderr @@ -1,144 +1,144 @@ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:8:5 | -LL | x == std::f32::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | x == f32::NAN; + | ^^^^^^^^^^^^^ | = note: `-D clippy::cmp-nan` implied by `-D warnings` -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:9:5 | -LL | x != std::f32::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | x != f32::NAN; + | ^^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:10:5 | -LL | x < std::f32::NAN; - | ^^^^^^^^^^^^^^^^^ +LL | x < f32::NAN; + | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:11:5 | -LL | x > std::f32::NAN; - | ^^^^^^^^^^^^^^^^^ +LL | x > f32::NAN; + | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:12:5 | -LL | x <= std::f32::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | x <= f32::NAN; + | ^^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:13:5 | -LL | x >= std::f32::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | x >= f32::NAN; + | ^^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:14:5 | LL | x == NAN_F32; | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:15:5 | LL | x != NAN_F32; | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:16:5 | LL | x < NAN_F32; | ^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:17:5 | LL | x > NAN_F32; | ^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:18:5 | LL | x <= NAN_F32; | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:19:5 | LL | x >= NAN_F32; | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:22:5 | -LL | y == std::f64::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | y == f64::NAN; + | ^^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:23:5 | -LL | y != std::f64::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | y != f64::NAN; + | ^^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:24:5 | -LL | y < std::f64::NAN; - | ^^^^^^^^^^^^^^^^^ +LL | y < f64::NAN; + | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:25:5 | -LL | y > std::f64::NAN; - | ^^^^^^^^^^^^^^^^^ +LL | y > f64::NAN; + | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:26:5 | -LL | y <= std::f64::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | y <= f64::NAN; + | ^^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:27:5 | -LL | y >= std::f64::NAN; - | ^^^^^^^^^^^^^^^^^^ +LL | y >= f64::NAN; + | ^^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:28:5 | LL | y == NAN_F64; | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:29:5 | LL | y != NAN_F64; | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:30:5 | LL | y < NAN_F64; | ^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:31:5 | LL | y > NAN_F64; | ^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:32:5 | LL | y <= NAN_F64; | ^^^^^^^^^^^^ -error: doomed comparison with `NAN`, use `std::{f32,f64}::is_nan()` instead +error: doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead --> $DIR/cmp_nan.rs:33:5 | LL | y >= NAN_F64; From 645b62e436fb5beb2cb03b646ae5d92fd13baecd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Mon, 6 Apr 2020 23:57:57 +0200 Subject: [PATCH 47/58] Fix float cmp to use assoc fxx::EPSILON --- clippy_lints/src/misc.rs | 2 +- tests/ui/float_cmp.stderr | 6 +++--- tests/ui/float_cmp_const.stderr | 14 +++++++------- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/clippy_lints/src/misc.rs b/clippy_lints/src/misc.rs index 35f78dd22bd2..cedd15e8daf6 100644 --- a/clippy_lints/src/misc.rs +++ b/clippy_lints/src/misc.rs @@ -388,7 +388,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { ), Applicability::HasPlaceholders, // snippet ); - db.span_note(expr.span, "`std::f32::EPSILON` and `std::f64::EPSILON` are available."); + db.span_note(expr.span, "`f32::EPSILON` and `f64::EPSILON` are available."); }); } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) { span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0"); diff --git a/tests/ui/float_cmp.stderr b/tests/ui/float_cmp.stderr index 68f5b23bdc73..90c25a6db37d 100644 --- a/tests/ui/float_cmp.stderr +++ b/tests/ui/float_cmp.stderr @@ -5,7 +5,7 @@ LL | ONE as f64 != 2.0; | ^^^^^^^^^^^^^^^^^ help: consider comparing them within some error: `(ONE as f64 - 2.0).abs() > error` | = note: `-D clippy::float-cmp` implied by `-D warnings` -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp.rs:59:5 | LL | ONE as f64 != 2.0; @@ -17,7 +17,7 @@ error: strict comparison of `f32` or `f64` LL | x == 1.0; | ^^^^^^^^ help: consider comparing them within some error: `(x - 1.0).abs() < error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp.rs:64:5 | LL | x == 1.0; @@ -29,7 +29,7 @@ error: strict comparison of `f32` or `f64` LL | twice(x) != twice(ONE as f64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider comparing them within some error: `(twice(x) - twice(ONE as f64)).abs() > error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp.rs:67:5 | LL | twice(x) != twice(ONE as f64); diff --git a/tests/ui/float_cmp_const.stderr b/tests/ui/float_cmp_const.stderr index c13c555cd119..2dc43cf4e5fb 100644 --- a/tests/ui/float_cmp_const.stderr +++ b/tests/ui/float_cmp_const.stderr @@ -5,7 +5,7 @@ LL | 1f32 == ONE; | ^^^^^^^^^^^ help: consider comparing them within some error: `(1f32 - ONE).abs() < error` | = note: `-D clippy::float-cmp-const` implied by `-D warnings` -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp_const.rs:20:5 | LL | 1f32 == ONE; @@ -17,7 +17,7 @@ error: strict comparison of `f32` or `f64` constant LL | TWO == ONE; | ^^^^^^^^^^ help: consider comparing them within some error: `(TWO - ONE).abs() < error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp_const.rs:21:5 | LL | TWO == ONE; @@ -29,7 +29,7 @@ error: strict comparison of `f32` or `f64` constant LL | TWO != ONE; | ^^^^^^^^^^ help: consider comparing them within some error: `(TWO - ONE).abs() > error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp_const.rs:22:5 | LL | TWO != ONE; @@ -41,7 +41,7 @@ error: strict comparison of `f32` or `f64` constant LL | ONE + ONE == TWO; | ^^^^^^^^^^^^^^^^ help: consider comparing them within some error: `(ONE + ONE - TWO).abs() < error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp_const.rs:23:5 | LL | ONE + ONE == TWO; @@ -53,7 +53,7 @@ error: strict comparison of `f32` or `f64` constant LL | x as f32 == ONE; | ^^^^^^^^^^^^^^^ help: consider comparing them within some error: `(x as f32 - ONE).abs() < error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp_const.rs:25:5 | LL | x as f32 == ONE; @@ -65,7 +65,7 @@ error: strict comparison of `f32` or `f64` constant LL | v == ONE; | ^^^^^^^^ help: consider comparing them within some error: `(v - ONE).abs() < error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp_const.rs:28:5 | LL | v == ONE; @@ -77,7 +77,7 @@ error: strict comparison of `f32` or `f64` constant LL | v != ONE; | ^^^^^^^^ help: consider comparing them within some error: `(v - ONE).abs() > error` | -note: `std::f32::EPSILON` and `std::f64::EPSILON` are available. +note: `f32::EPSILON` and `f64::EPSILON` are available. --> $DIR/float_cmp_const.rs:29:5 | LL | v != ONE; From 51bb1d28c510b6833066561a2b5709e21b172c5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Tue, 7 Apr 2020 23:41:00 +0200 Subject: [PATCH 48/58] Use assoc const NAN for zero_div_zero lint --- clippy_lints/src/utils/diagnostics.rs | 2 +- clippy_lints/src/zero_div_zero.rs | 9 ++++----- src/lintlist/mod.rs | 2 +- tests/ui/zero_div_zero.stderr | 8 ++++---- 4 files changed, 10 insertions(+), 11 deletions(-) diff --git a/clippy_lints/src/utils/diagnostics.rs b/clippy_lints/src/utils/diagnostics.rs index cc519d525521..409bb2043d4b 100644 --- a/clippy_lints/src/utils/diagnostics.rs +++ b/clippy_lints/src/utils/diagnostics.rs @@ -60,7 +60,7 @@ pub fn span_lint(cx: &T, lint: &'static Lint, sp: impl Into(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str) { cx.struct_span_lint(lint, span, |ldb| { diff --git a/clippy_lints/src/zero_div_zero.rs b/clippy_lints/src/zero_div_zero.rs index 42cb9a77db02..afd10d9ed53f 100644 --- a/clippy_lints/src/zero_div_zero.rs +++ b/clippy_lints/src/zero_div_zero.rs @@ -8,8 +8,7 @@ use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// **What it does:** Checks for `0.0 / 0.0`. /// - /// **Why is this bad?** It's less readable than `std::f32::NAN` or - /// `std::f64::NAN`. + /// **Why is this bad?** It's less readable than `f32::NAN` or `f64::NAN`. /// /// **Known problems:** None. /// @@ -19,7 +18,7 @@ declare_clippy_lint! { /// ``` pub ZERO_DIVIDED_BY_ZERO, complexity, - "usage of `0.0 / 0.0` to obtain NaN instead of `std::f32::NAN` or `std::f64::NAN`" + "usage of `0.0 / 0.0` to obtain NaN instead of `f32::NAN` or `f64::NAN`" } declare_lint_pass!(ZeroDiv => [ZERO_DIVIDED_BY_ZERO]); @@ -38,7 +37,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ZeroDiv { if Constant::F32(0.0) == lhs_value || Constant::F64(0.0) == lhs_value; if Constant::F32(0.0) == rhs_value || Constant::F64(0.0) == rhs_value; then { - // since we're about to suggest a use of std::f32::NaN or std::f64::NaN, + // since we're about to suggest a use of f32::NAN or f64::NAN, // match the precision of the literals that are given. let float_type = match (lhs_value, rhs_value) { (Constant::F64(_), _) @@ -51,7 +50,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ZeroDiv { expr.span, "constant division of `0.0` with `0.0` will always result in NaN", &format!( - "Consider using `std::{}::NAN` if you would like a constant representing NaN", + "Consider using `{}::NAN` if you would like a constant representing NaN", float_type, ), ); diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 8a6d0af5f8a7..0e5757fe588c 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -2526,7 +2526,7 @@ pub static ref ALL_LINTS: Vec = vec![ Lint { name: "zero_divided_by_zero", group: "complexity", - desc: "usage of `0.0 / 0.0` to obtain NaN instead of `std::f32::NAN` or `std::f64::NAN`", + desc: "usage of `0.0 / 0.0` to obtain NaN instead of `f32::NAN` or `f64::NAN`", deprecation: None, module: "zero_div_zero", }, diff --git a/tests/ui/zero_div_zero.stderr b/tests/ui/zero_div_zero.stderr index e4d6f168038b..d0e88f3c5a54 100644 --- a/tests/ui/zero_div_zero.stderr +++ b/tests/ui/zero_div_zero.stderr @@ -13,7 +13,7 @@ LL | let nan = 0.0 / 0.0; | ^^^^^^^^^ | = note: `-D clippy::zero-divided-by-zero` implied by `-D warnings` - = help: Consider using `std::f64::NAN` if you would like a constant representing NaN + = help: Consider using `f64::NAN` if you would like a constant representing NaN error: equal expressions as operands to `/` --> $DIR/zero_div_zero.rs:5:19 @@ -27,7 +27,7 @@ error: constant division of `0.0` with `0.0` will always result in NaN LL | let f64_nan = 0.0 / 0.0f64; | ^^^^^^^^^^^^ | - = help: Consider using `std::f64::NAN` if you would like a constant representing NaN + = help: Consider using `f64::NAN` if you would like a constant representing NaN error: equal expressions as operands to `/` --> $DIR/zero_div_zero.rs:6:25 @@ -41,7 +41,7 @@ error: constant division of `0.0` with `0.0` will always result in NaN LL | let other_f64_nan = 0.0f64 / 0.0; | ^^^^^^^^^^^^ | - = help: Consider using `std::f64::NAN` if you would like a constant representing NaN + = help: Consider using `f64::NAN` if you would like a constant representing NaN error: equal expressions as operands to `/` --> $DIR/zero_div_zero.rs:7:28 @@ -55,7 +55,7 @@ error: constant division of `0.0` with `0.0` will always result in NaN LL | let one_more_f64_nan = 0.0f64 / 0.0f64; | ^^^^^^^^^^^^^^^ | - = help: Consider using `std::f64::NAN` if you would like a constant representing NaN + = help: Consider using `f64::NAN` if you would like a constant representing NaN error: aborting due to 8 previous errors From 518568ae0a1a88d3861a78609534ee05d4c86ffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Tue, 7 Apr 2020 23:44:24 +0200 Subject: [PATCH 49/58] Don't import primitive type modules --- clippy_lints/src/float_literal.rs | 2 +- clippy_lints/src/types.rs | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/clippy_lints/src/float_literal.rs b/clippy_lints/src/float_literal.rs index 79040ebf86d6..3a52b1d3fc20 100644 --- a/clippy_lints/src/float_literal.rs +++ b/clippy_lints/src/float_literal.rs @@ -6,7 +6,7 @@ use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use std::{f32, f64, fmt}; +use std::fmt; declare_clippy_lint! { /// **What it does:** Checks for float literals with a precision greater diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 271459bd1e94..3c8affb367c0 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -1973,8 +1973,6 @@ impl Ord for FullInt { } fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> { - use std::{i128, i16, i32, i64, i8, isize, u128, u16, u32, u64, u8, usize}; - if let ExprKind::Cast(ref cast_exp, _) = expr.kind { let pre_cast_ty = cx.tables.expr_ty(cast_exp); let cast_ty = cx.tables.expr_ty(expr); From c2f67e1e19ba63b96b1b6f7b0fe33d1ea907396e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Wed, 8 Apr 2020 00:01:27 +0200 Subject: [PATCH 50/58] Use integer assoc consts in more lint example code --- clippy_lints/src/neg_cmp_op_on_partial_ord.rs | 4 ++-- clippy_lints/src/types.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/clippy_lints/src/neg_cmp_op_on_partial_ord.rs b/clippy_lints/src/neg_cmp_op_on_partial_ord.rs index 339c460bbd5c..54536ed57d3e 100644 --- a/clippy_lints/src/neg_cmp_op_on_partial_ord.rs +++ b/clippy_lints/src/neg_cmp_op_on_partial_ord.rs @@ -25,13 +25,13 @@ declare_clippy_lint! { /// /// // Bad /// let a = 1.0; - /// let b = std::f64::NAN; + /// let b = f64::NAN; /// /// let _not_less_or_equal = !(a <= b); /// /// // Good /// let a = 1.0; - /// let b = std::f64::NAN; + /// let b = f64::NAN; /// /// let _not_less_or_equal = match a.partial_cmp(&b) { /// None | Some(Ordering::Greater) => true, diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 3c8affb367c0..732725e17944 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -837,7 +837,7 @@ declare_clippy_lint! { /// /// **Example:** /// ```rust - /// let x = std::u64::MAX; + /// let x = u64::MAX; /// x as f64; /// ``` pub CAST_PRECISION_LOSS, @@ -904,7 +904,7 @@ declare_clippy_lint! { /// /// **Example:** /// ```rust - /// std::u32::MAX as i32; // will yield a value of `-1` + /// u32::MAX as i32; // will yield a value of `-1` /// ``` pub CAST_POSSIBLE_WRAP, pedantic, @@ -1752,7 +1752,7 @@ declare_clippy_lint! { /// ```rust /// let vec: Vec = Vec::new(); /// if vec.len() <= 0 {} - /// if 100 > std::i32::MAX {} + /// if 100 > i32::MAX {} /// ``` pub ABSURD_EXTREME_COMPARISONS, correctness, From b192f2cd1592fc882b29bfad5baf3bfaa7acde2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Wed, 8 Apr 2020 00:04:33 +0200 Subject: [PATCH 51/58] Use primitive type assoc consts in more tests --- tests/ui/absurd-extreme-comparisons.rs | 16 ++++----- tests/ui/absurd-extreme-comparisons.stderr | 36 +++++++++---------- tests/ui/crashes/mut_mut_macro.rs | 4 +-- tests/ui/enum_clike_unportable_variant.rs | 4 +-- tests/ui/enum_clike_unportable_variant.stderr | 4 +-- tests/ui/float_cmp.rs | 4 +-- tests/ui/float_cmp_const.rs | 4 +-- tests/ui/if_same_then_else.rs | 2 +- tests/ui/if_same_then_else2.rs | 4 +-- tests/ui/if_same_then_else2.stderr | 4 +-- 10 files changed, 41 insertions(+), 41 deletions(-) diff --git a/tests/ui/absurd-extreme-comparisons.rs b/tests/ui/absurd-extreme-comparisons.rs index ae0727fe2ba3..d205b383d1ff 100644 --- a/tests/ui/absurd-extreme-comparisons.rs +++ b/tests/ui/absurd-extreme-comparisons.rs @@ -16,17 +16,17 @@ fn main() { u < Z; Z >= u; Z > u; - u > std::u32::MAX; - u >= std::u32::MAX; - std::u32::MAX < u; - std::u32::MAX <= u; + u > u32::MAX; + u >= u32::MAX; + u32::MAX < u; + u32::MAX <= u; 1-1 > u; u >= !0; u <= 12 - 2*6; let i: i8 = 0; i < -127 - 1; - std::i8::MAX >= i; - 3-7 < std::i32::MIN; + i8::MAX >= i; + 3-7 < i32::MIN; let b = false; b >= true; false > b; @@ -52,10 +52,10 @@ impl PartialOrd for U { } pub fn foo(val: U) -> bool { - val > std::u32::MAX + val > u32::MAX } pub fn bar(len: u64) -> bool { // This is OK as we are casting from target sized to fixed size - len >= std::usize::MAX as u64 + len >= usize::MAX as u64 } diff --git a/tests/ui/absurd-extreme-comparisons.stderr b/tests/ui/absurd-extreme-comparisons.stderr index 4ef364148cda..6de554378aaa 100644 --- a/tests/ui/absurd-extreme-comparisons.stderr +++ b/tests/ui/absurd-extreme-comparisons.stderr @@ -42,34 +42,34 @@ LL | Z > u; error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:19:5 | -LL | u > std::u32::MAX; - | ^^^^^^^^^^^^^^^^^ +LL | u > u32::MAX; + | ^^^^^^^^^^^^ | - = help: because `std::u32::MAX` is the maximum value for this type, this comparison is always false + = help: because `u32::MAX` is the maximum value for this type, this comparison is always false error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:20:5 | -LL | u >= std::u32::MAX; - | ^^^^^^^^^^^^^^^^^^ +LL | u >= u32::MAX; + | ^^^^^^^^^^^^^ | - = help: because `std::u32::MAX` is the maximum value for this type, the case where the two sides are not equal never occurs, consider using `u == std::u32::MAX` instead + = help: because `u32::MAX` is the maximum value for this type, the case where the two sides are not equal never occurs, consider using `u == u32::MAX` instead error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:21:5 | -LL | std::u32::MAX < u; - | ^^^^^^^^^^^^^^^^^ +LL | u32::MAX < u; + | ^^^^^^^^^^^^ | - = help: because `std::u32::MAX` is the maximum value for this type, this comparison is always false + = help: because `u32::MAX` is the maximum value for this type, this comparison is always false error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:22:5 | -LL | std::u32::MAX <= u; - | ^^^^^^^^^^^^^^^^^^ +LL | u32::MAX <= u; + | ^^^^^^^^^^^^^ | - = help: because `std::u32::MAX` is the maximum value for this type, the case where the two sides are not equal never occurs, consider using `std::u32::MAX == u` instead + = help: because `u32::MAX` is the maximum value for this type, the case where the two sides are not equal never occurs, consider using `u32::MAX == u` instead error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:23:5 @@ -106,18 +106,18 @@ LL | i < -127 - 1; error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:28:5 | -LL | std::i8::MAX >= i; - | ^^^^^^^^^^^^^^^^^ +LL | i8::MAX >= i; + | ^^^^^^^^^^^^ | - = help: because `std::i8::MAX` is the maximum value for this type, this comparison is always true + = help: because `i8::MAX` is the maximum value for this type, this comparison is always true error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:29:5 | -LL | 3-7 < std::i32::MIN; - | ^^^^^^^^^^^^^^^^^^^ +LL | 3-7 < i32::MIN; + | ^^^^^^^^^^^^^^ | - = help: because `std::i32::MIN` is the minimum value for this type, this comparison is always false + = help: because `i32::MIN` is the minimum value for this type, this comparison is always false error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false --> $DIR/absurd-extreme-comparisons.rs:31:5 diff --git a/tests/ui/crashes/mut_mut_macro.rs b/tests/ui/crashes/mut_mut_macro.rs index 14219f574c59..d8fbaa541466 100644 --- a/tests/ui/crashes/mut_mut_macro.rs +++ b/tests/ui/crashes/mut_mut_macro.rs @@ -16,7 +16,7 @@ const BAA: *const i32 = 0 as *const i32; static mut BAR: *const i32 = BAA; static mut FOO: *const i32 = 0 as *const i32; -static mut BUH: bool = 42.0 < std::f32::NAN; +static mut BUH: bool = 42.0 < f32::NAN; #[allow(unused_variables, unused_mut)] fn main() { @@ -32,5 +32,5 @@ fn main() { assert_eq!(*MUT_COUNT, 1); */ // FIXME: don't lint in array length, requires `check_body` - //let _ = [""; (42.0 < std::f32::NAN) as usize]; + //let _ = [""; (42.0 < f32::NAN) as usize]; } diff --git a/tests/ui/enum_clike_unportable_variant.rs b/tests/ui/enum_clike_unportable_variant.rs index 7379ad99f4af..7d6842f5b542 100644 --- a/tests/ui/enum_clike_unportable_variant.rs +++ b/tests/ui/enum_clike_unportable_variant.rs @@ -24,8 +24,8 @@ enum NonPortableSigned { Y = 0x7FFF_FFFF, Z = 0xFFFF_FFFF, A = 0x1_0000_0000, - B = std::i32::MIN as isize, - C = (std::i32::MIN as isize) - 1, + B = i32::MIN as isize, + C = (i32::MIN as isize) - 1, } enum NonPortableSignedNoHint { diff --git a/tests/ui/enum_clike_unportable_variant.stderr b/tests/ui/enum_clike_unportable_variant.stderr index bd729683e4ce..71f3f5e083e0 100644 --- a/tests/ui/enum_clike_unportable_variant.stderr +++ b/tests/ui/enum_clike_unportable_variant.stderr @@ -33,8 +33,8 @@ LL | A = 0x1_0000_0000, error: Clike enum variant discriminant is not portable to 32-bit targets --> $DIR/enum_clike_unportable_variant.rs:28:5 | -LL | C = (std::i32::MIN as isize) - 1, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | C = (i32::MIN as isize) - 1, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: Clike enum variant discriminant is not portable to 32-bit targets --> $DIR/enum_clike_unportable_variant.rs:34:5 diff --git a/tests/ui/float_cmp.rs b/tests/ui/float_cmp.rs index 207c1bcbbc67..c8248723bc9d 100644 --- a/tests/ui/float_cmp.rs +++ b/tests/ui/float_cmp.rs @@ -45,8 +45,8 @@ impl PartialEq for X { fn main() { ZERO == 0f32; //no error, comparison with zero is ok - 1.0f32 != ::std::f32::INFINITY; // also comparison with infinity - 1.0f32 != ::std::f32::NEG_INFINITY; // and negative infinity + 1.0f32 != f32::INFINITY; // also comparison with infinity + 1.0f32 != f32::NEG_INFINITY; // and negative infinity ZERO == 0.0; //no error, comparison with zero is ok ZERO + ZERO != 1.0; //no error, comparison with zero is ok diff --git a/tests/ui/float_cmp_const.rs b/tests/ui/float_cmp_const.rs index 8f4ad15720b0..a338040e19be 100644 --- a/tests/ui/float_cmp_const.rs +++ b/tests/ui/float_cmp_const.rs @@ -37,8 +37,8 @@ fn main() { // no errors, zero and infinity values ONE != 0f32; TWO == 0f32; - ONE != ::std::f32::INFINITY; - ONE == ::std::f32::NEG_INFINITY; + ONE != f32::INFINITY; + ONE == f32::NEG_INFINITY; // no errors, but will warn clippy::float_cmp if '#![allow(float_cmp)]' above is removed let w = 1.1; diff --git a/tests/ui/if_same_then_else.rs b/tests/ui/if_same_then_else.rs index 67b4c311085e..6bbf79edfcf7 100644 --- a/tests/ui/if_same_then_else.rs +++ b/tests/ui/if_same_then_else.rs @@ -78,7 +78,7 @@ fn if_same_then_else() { let _ = if true { 0.0 } else { -0.0 }; // Different NaNs - let _ = if true { 0.0 / 0.0 } else { std::f32::NAN }; + let _ = if true { 0.0 / 0.0 } else { f32::NAN }; if true { foo(); diff --git a/tests/ui/if_same_then_else2.rs b/tests/ui/if_same_then_else2.rs index 8e61bf3830be..cbec56324dca 100644 --- a/tests/ui/if_same_then_else2.rs +++ b/tests/ui/if_same_then_else2.rs @@ -87,10 +87,10 @@ fn if_same_then_else2() -> Result<&'static str, ()> { // Same NaNs let _ = if true { - std::f32::NAN + f32::NAN } else { //~ ERROR same body as `if` block - std::f32::NAN + f32::NAN }; if true { diff --git a/tests/ui/if_same_then_else2.stderr b/tests/ui/if_same_then_else2.stderr index c6da3c6be645..da2be6c8aa5a 100644 --- a/tests/ui/if_same_then_else2.stderr +++ b/tests/ui/if_same_then_else2.stderr @@ -69,7 +69,7 @@ error: this `if` has identical blocks LL | } else { | ____________^ LL | | //~ ERROR same body as `if` block -LL | | std::f32::NAN +LL | | f32::NAN LL | | }; | |_____^ | @@ -78,7 +78,7 @@ note: same as this | LL | let _ = if true { | _____________________^ -LL | | std::f32::NAN +LL | | f32::NAN LL | | } else { | |_____^ From 4726daad5253a1347b568100d4cfc53e5698d8de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Wed, 8 Apr 2020 00:22:42 +0200 Subject: [PATCH 52/58] Use int assoc consts in checked_conversions lint --- clippy_lints/src/checked_conversions.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/checked_conversions.rs b/clippy_lints/src/checked_conversions.rs index 88baaea9e562..d9776dd50a83 100644 --- a/clippy_lints/src/checked_conversions.rs +++ b/clippy_lints/src/checked_conversions.rs @@ -21,7 +21,7 @@ declare_clippy_lint! { /// ```rust /// # let foo: u32 = 5; /// # let _ = - /// foo <= i32::max_value() as u32 + /// foo <= i32::MAX as u32 /// # ; /// ``` /// @@ -179,7 +179,7 @@ impl ConversionType { } } -/// Check for `expr <= (to_type::max_value() as from_type)` +/// Check for `expr <= (to_type::MAX as from_type)` fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option> { if_chain! { if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind; @@ -194,7 +194,7 @@ fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option> { } } -/// Check for `expr >= 0|(to_type::min_value() as from_type)` +/// Check for `expr >= 0|(to_type::MIN as from_type)` fn check_lower_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option> { fn check_function<'a>(candidate: &'a Expr<'a>, check: &'a Expr<'a>) -> Option> { (check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check))) @@ -222,7 +222,7 @@ fn check_lower_bound_zero<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> O } } -/// Check for `expr >= (to_type::min_value() as from_type)` +/// Check for `expr >= (to_type::MIN as from_type)` fn check_lower_bound_min<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option> { if let Some((from, to)) = get_types_from_cast(check, MIN_VALUE, SINTS) { Conversion::try_new(candidate, from, to) From 1647f53fb3064e7bf86d396b401bca0f90a9d51d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Wed, 8 Apr 2020 00:24:18 +0200 Subject: [PATCH 53/58] Use int assoc consts in MANUAL_SATURATING_ARITHMETIC --- clippy_lints/src/methods/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 124fc1d9878e..31dbf6b2b385 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -1138,8 +1138,8 @@ declare_clippy_lint! { /// ```rust /// # let y: u32 = 0; /// # let x: u32 = 100; - /// let add = x.checked_add(y).unwrap_or(u32::max_value()); - /// let sub = x.checked_sub(y).unwrap_or(u32::min_value()); + /// let add = x.checked_add(y).unwrap_or(u32::MAX); + /// let sub = x.checked_sub(y).unwrap_or(u32::MIN); /// ``` /// /// can be written using dedicated methods for saturating addition/subtraction as: From 381f9cb34e499501f73b99f086f3ef85ab15d401 Mon Sep 17 00:00:00 2001 From: flip1995 Date: Wed, 8 Apr 2020 16:00:03 +0200 Subject: [PATCH 54/58] Run fmt and update test --- tests/ui/extra_unused_lifetimes.rs | 7 +------ tests/ui/extra_unused_lifetimes.stderr | 8 ++++---- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/tests/ui/extra_unused_lifetimes.rs b/tests/ui/extra_unused_lifetimes.rs index 26df71ddcb0f..ddbf4e98c51a 100644 --- a/tests/ui/extra_unused_lifetimes.rs +++ b/tests/ui/extra_unused_lifetimes.rs @@ -1,9 +1,4 @@ -#![allow( - unused, - dead_code, - clippy::needless_lifetimes, - clippy::needless_pass_by_value -)] +#![allow(unused, dead_code, clippy::needless_lifetimes, clippy::needless_pass_by_value)] #![warn(clippy::extra_unused_lifetimes)] fn empty() {} diff --git a/tests/ui/extra_unused_lifetimes.stderr b/tests/ui/extra_unused_lifetimes.stderr index e997951346f7..16bbb1c037d8 100644 --- a/tests/ui/extra_unused_lifetimes.stderr +++ b/tests/ui/extra_unused_lifetimes.stderr @@ -1,5 +1,5 @@ error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:13:14 + --> $DIR/extra_unused_lifetimes.rs:8:14 | LL | fn unused_lt<'a>(x: u8) {} | ^^ @@ -7,19 +7,19 @@ LL | fn unused_lt<'a>(x: u8) {} = note: `-D clippy::extra-unused-lifetimes` implied by `-D warnings` error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:15:25 + --> $DIR/extra_unused_lifetimes.rs:10:25 | LL | fn unused_lt_transitive<'a, 'b: 'a>(x: &'b u8) { | ^^ error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:40:10 + --> $DIR/extra_unused_lifetimes.rs:35:10 | LL | fn x<'a>(&self) {} | ^^ error: this lifetime isn't used in the function definition - --> $DIR/extra_unused_lifetimes.rs:66:22 + --> $DIR/extra_unused_lifetimes.rs:61:22 | LL | fn unused_lt<'a>(x: u8) {} | ^^ From 899a1b559805fa46c18b8165e2f59f77eb843585 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Mon, 6 Apr 2020 15:46:40 -0700 Subject: [PATCH 55/58] Move cognitive_complexity to nursery --- clippy_lints/src/assign_ops.rs | 1 - clippy_lints/src/cognitive_complexity.rs | 2 +- clippy_lints/src/lib.rs | 3 +- clippy_lints/src/methods/mod.rs | 2 +- clippy_lints/src/mutable_debug_assertion.rs | 1 - clippy_lints/src/types.rs | 1 - src/lintlist/mod.rs | 2 +- tests/ui/collapsible_else_if.fixed | 2 +- tests/ui/collapsible_else_if.rs | 2 +- tests/ui/collapsible_if.fixed | 2 +- tests/ui/collapsible_if.rs | 2 +- tests/ui/debug_assert_with_mut_call.rs | 2 +- tests/ui/for_loop_fixable.fixed | 1 - tests/ui/for_loop_fixable.rs | 1 - tests/ui/for_loop_fixable.stderr | 40 ++++++++++----------- tests/ui/for_loop_unfixable.rs | 1 - tests/ui/for_loop_unfixable.stderr | 2 +- tests/ui/if_same_then_else2.rs | 1 - tests/ui/if_same_then_else2.stderr | 24 ++++++------- tests/ui/rename.fixed | 1 - tests/ui/rename.rs | 1 - tests/ui/rename.stderr | 10 +++--- tests/ui/while_let_on_iterator.rs | 2 +- 23 files changed, 48 insertions(+), 58 deletions(-) diff --git a/clippy_lints/src/assign_ops.rs b/clippy_lints/src/assign_ops.rs index b66e87467075..c60577e8b2da 100644 --- a/clippy_lints/src/assign_ops.rs +++ b/clippy_lints/src/assign_ops.rs @@ -77,7 +77,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps { }, hir::ExprKind::Assign(assignee, e, _) => { if let hir::ExprKind::Binary(op, l, r) = &e.kind { - #[allow(clippy::cognitive_complexity)] let lint = |assignee: &hir::Expr<'_>, rhs: &hir::Expr<'_>| { let ty = cx.tables.expr_ty(assignee); let rty = cx.tables.expr_ty(rhs); diff --git a/clippy_lints/src/cognitive_complexity.rs b/clippy_lints/src/cognitive_complexity.rs index b90dd28642b7..98abc801302e 100644 --- a/clippy_lints/src/cognitive_complexity.rs +++ b/clippy_lints/src/cognitive_complexity.rs @@ -22,7 +22,7 @@ declare_clippy_lint! { /// /// **Example:** No. You'll see it when you get the warning. pub COGNITIVE_COMPLEXITY, - complexity, + nursery, "functions that should be split up into multiple functions" } diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 2cd22633bc87..3e8ce4006f6f 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1174,7 +1174,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&booleans::LOGIC_BUG), LintId::of(&booleans::NONMINIMAL_BOOL), LintId::of(&bytecount::NAIVE_BYTECOUNT), - LintId::of(&cognitive_complexity::COGNITIVE_COMPLEXITY), LintId::of(&collapsible_if::COLLAPSIBLE_IF), LintId::of(&comparison_chain::COMPARISON_CHAIN), LintId::of(&copies::IFS_SAME_COND), @@ -1509,7 +1508,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&assign_ops::MISREFACTORED_ASSIGN_OP), LintId::of(&attrs::DEPRECATED_CFG_ATTR), LintId::of(&booleans::NONMINIMAL_BOOL), - LintId::of(&cognitive_complexity::COGNITIVE_COMPLEXITY), LintId::of(&double_comparison::DOUBLE_COMPARISONS), LintId::of(&double_parens::DOUBLE_PARENS), LintId::of(&duration_subsec::DURATION_SUBSEC), @@ -1678,6 +1676,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_group(true, "clippy::nursery", Some("clippy_nursery"), vec![ LintId::of(&attrs::EMPTY_LINE_AFTER_OUTER_ATTR), + LintId::of(&cognitive_complexity::COGNITIVE_COMPLEXITY), LintId::of(&fallible_impl_from::FALLIBLE_IMPL_FROM), LintId::of(&floating_point_arithmetic::IMPRECISE_FLOPS), LintId::of(&floating_point_arithmetic::SUBOPTIMAL_FLOPS), diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 3b2f96e4d09f..3f49849ba323 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -1317,7 +1317,7 @@ declare_lint_pass!(Methods => [ ]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { - #[allow(clippy::cognitive_complexity, clippy::too_many_lines)] + #[allow(clippy::too_many_lines)] fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) { if in_macro(expr.span) { return; diff --git a/clippy_lints/src/mutable_debug_assertion.rs b/clippy_lints/src/mutable_debug_assertion.rs index 80609d5cb1d1..119e0905ff44 100644 --- a/clippy_lints/src/mutable_debug_assertion.rs +++ b/clippy_lints/src/mutable_debug_assertion.rs @@ -53,7 +53,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DebugAssertWithMutCall { } //HACK(hellow554): remove this when #4694 is implemented -#[allow(clippy::cognitive_complexity)] fn extract_call<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) -> Option { if_chain! { if let ExprKind::Block(ref block, _) = e.kind; diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index e2b16079f8f5..13e275b3291d 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -315,7 +315,6 @@ impl Types { /// The parameter `is_local` distinguishes the context of the type; types from /// local bindings should only be checked for the `BORROWED_BOX` lint. #[allow(clippy::too_many_lines)] - #[allow(clippy::cognitive_complexity)] fn check_ty(&mut self, cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool) { if hir_ty.span.from_expansion() { return; diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 00add20b7ae8..3b275f43e170 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -250,7 +250,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "cognitive_complexity", - group: "complexity", + group: "nursery", desc: "functions that should be split up into multiple functions", deprecation: None, module: "cognitive_complexity", diff --git a/tests/ui/collapsible_else_if.fixed b/tests/ui/collapsible_else_if.fixed index c4149ad19c1e..ce2a1c28c8a8 100644 --- a/tests/ui/collapsible_else_if.fixed +++ b/tests/ui/collapsible_else_if.fixed @@ -1,5 +1,5 @@ // run-rustfix -#![allow(clippy::cognitive_complexity, clippy::assertions_on_constants)] +#![allow(clippy::assertions_on_constants)] #[rustfmt::skip] #[warn(clippy::collapsible_if)] diff --git a/tests/ui/collapsible_else_if.rs b/tests/ui/collapsible_else_if.rs index 79a27aafc4d9..99c40b8d38eb 100644 --- a/tests/ui/collapsible_else_if.rs +++ b/tests/ui/collapsible_else_if.rs @@ -1,5 +1,5 @@ // run-rustfix -#![allow(clippy::cognitive_complexity, clippy::assertions_on_constants)] +#![allow(clippy::assertions_on_constants)] #[rustfmt::skip] #[warn(clippy::collapsible_if)] diff --git a/tests/ui/collapsible_if.fixed b/tests/ui/collapsible_if.fixed index 076771f5c57e..561283fc8e73 100644 --- a/tests/ui/collapsible_if.fixed +++ b/tests/ui/collapsible_if.fixed @@ -1,5 +1,5 @@ // run-rustfix -#![allow(clippy::cognitive_complexity, clippy::assertions_on_constants)] +#![allow(clippy::assertions_on_constants)] #[rustfmt::skip] #[warn(clippy::collapsible_if)] diff --git a/tests/ui/collapsible_if.rs b/tests/ui/collapsible_if.rs index 503cb35f8588..dc9d9b451c0f 100644 --- a/tests/ui/collapsible_if.rs +++ b/tests/ui/collapsible_if.rs @@ -1,5 +1,5 @@ // run-rustfix -#![allow(clippy::cognitive_complexity, clippy::assertions_on_constants)] +#![allow(clippy::assertions_on_constants)] #[rustfmt::skip] #[warn(clippy::collapsible_if)] diff --git a/tests/ui/debug_assert_with_mut_call.rs b/tests/ui/debug_assert_with_mut_call.rs index b061fff6b9e9..477a47118d41 100644 --- a/tests/ui/debug_assert_with_mut_call.rs +++ b/tests/ui/debug_assert_with_mut_call.rs @@ -2,7 +2,7 @@ #![feature(custom_inner_attributes)] #![rustfmt::skip] #![warn(clippy::debug_assert_with_mut_call)] -#![allow(clippy::cognitive_complexity, clippy::redundant_closure_call)] +#![allow(clippy::redundant_closure_call)] struct S; diff --git a/tests/ui/for_loop_fixable.fixed b/tests/ui/for_loop_fixable.fixed index 6717899ed090..5fc84ada9efd 100644 --- a/tests/ui/for_loop_fixable.fixed +++ b/tests/ui/for_loop_fixable.fixed @@ -28,7 +28,6 @@ impl Unrelated { clippy::linkedlist, clippy::shadow_unrelated, clippy::unnecessary_mut_passed, - clippy::cognitive_complexity, clippy::similar_names )] #[allow(clippy::many_single_char_names, unused_variables)] diff --git a/tests/ui/for_loop_fixable.rs b/tests/ui/for_loop_fixable.rs index 7c08d383420b..4165b0dc0049 100644 --- a/tests/ui/for_loop_fixable.rs +++ b/tests/ui/for_loop_fixable.rs @@ -28,7 +28,6 @@ impl Unrelated { clippy::linkedlist, clippy::shadow_unrelated, clippy::unnecessary_mut_passed, - clippy::cognitive_complexity, clippy::similar_names )] #[allow(clippy::many_single_char_names, unused_variables)] diff --git a/tests/ui/for_loop_fixable.stderr b/tests/ui/for_loop_fixable.stderr index f84b7a660ff4..cffb4b9f0a9c 100644 --- a/tests/ui/for_loop_fixable.stderr +++ b/tests/ui/for_loop_fixable.stderr @@ -1,5 +1,5 @@ error: this range is empty so this for loop will never run - --> $DIR/for_loop_fixable.rs:39:14 + --> $DIR/for_loop_fixable.rs:38:14 | LL | for i in 10..0 { | ^^^^^ @@ -11,7 +11,7 @@ LL | for i in (0..10).rev() { | ^^^^^^^^^^^^^ error: this range is empty so this for loop will never run - --> $DIR/for_loop_fixable.rs:43:14 + --> $DIR/for_loop_fixable.rs:42:14 | LL | for i in 10..=0 { | ^^^^^^ @@ -22,7 +22,7 @@ LL | for i in (0..=10).rev() { | ^^^^^^^^^^^^^^ error: this range is empty so this for loop will never run - --> $DIR/for_loop_fixable.rs:47:14 + --> $DIR/for_loop_fixable.rs:46:14 | LL | for i in MAX_LEN..0 { | ^^^^^^^^^^ @@ -33,7 +33,7 @@ LL | for i in (0..MAX_LEN).rev() { | ^^^^^^^^^^^^^^^^^^ error: this range is empty so this for loop will never run - --> $DIR/for_loop_fixable.rs:72:14 + --> $DIR/for_loop_fixable.rs:71:14 | LL | for i in 10..5 + 4 { | ^^^^^^^^^ @@ -44,7 +44,7 @@ LL | for i in (5 + 4..10).rev() { | ^^^^^^^^^^^^^^^^^ error: this range is empty so this for loop will never run - --> $DIR/for_loop_fixable.rs:76:14 + --> $DIR/for_loop_fixable.rs:75:14 | LL | for i in (5 + 2)..(3 - 1) { | ^^^^^^^^^^^^^^^^ @@ -55,7 +55,7 @@ LL | for i in ((3 - 1)..(5 + 2)).rev() { | ^^^^^^^^^^^^^^^^^^^^^^^^ error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:98:15 + --> $DIR/for_loop_fixable.rs:97:15 | LL | for _v in vec.iter() {} | ^^^^^^^^^^ help: to write this more concisely, try: `&vec` @@ -63,13 +63,13 @@ LL | for _v in vec.iter() {} = note: `-D clippy::explicit-iter-loop` implied by `-D warnings` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:100:15 + --> $DIR/for_loop_fixable.rs:99:15 | LL | for _v in vec.iter_mut() {} | ^^^^^^^^^^^^^^ help: to write this more concisely, try: `&mut vec` error: it is more concise to loop over containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:103:15 + --> $DIR/for_loop_fixable.rs:102:15 | LL | for _v in out_vec.into_iter() {} | ^^^^^^^^^^^^^^^^^^^ help: to write this more concisely, try: `out_vec` @@ -77,73 +77,73 @@ LL | for _v in out_vec.into_iter() {} = note: `-D clippy::explicit-into-iter-loop` implied by `-D warnings` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:108:15 + --> $DIR/for_loop_fixable.rs:107:15 | LL | for _v in [1, 2, 3].iter() {} | ^^^^^^^^^^^^^^^^ help: to write this more concisely, try: `&[1, 2, 3]` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:112:15 + --> $DIR/for_loop_fixable.rs:111:15 | LL | for _v in [0; 32].iter() {} | ^^^^^^^^^^^^^^ help: to write this more concisely, try: `&[0; 32]` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:117:15 + --> $DIR/for_loop_fixable.rs:116:15 | LL | for _v in ll.iter() {} | ^^^^^^^^^ help: to write this more concisely, try: `&ll` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:120:15 + --> $DIR/for_loop_fixable.rs:119:15 | LL | for _v in vd.iter() {} | ^^^^^^^^^ help: to write this more concisely, try: `&vd` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:123:15 + --> $DIR/for_loop_fixable.rs:122:15 | LL | for _v in bh.iter() {} | ^^^^^^^^^ help: to write this more concisely, try: `&bh` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:126:15 + --> $DIR/for_loop_fixable.rs:125:15 | LL | for _v in hm.iter() {} | ^^^^^^^^^ help: to write this more concisely, try: `&hm` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:129:15 + --> $DIR/for_loop_fixable.rs:128:15 | LL | for _v in bt.iter() {} | ^^^^^^^^^ help: to write this more concisely, try: `&bt` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:132:15 + --> $DIR/for_loop_fixable.rs:131:15 | LL | for _v in hs.iter() {} | ^^^^^^^^^ help: to write this more concisely, try: `&hs` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:135:15 + --> $DIR/for_loop_fixable.rs:134:15 | LL | for _v in bs.iter() {} | ^^^^^^^^^ help: to write this more concisely, try: `&bs` error: it is more concise to loop over containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:310:18 + --> $DIR/for_loop_fixable.rs:309:18 | LL | for i in iterator.into_iter() { | ^^^^^^^^^^^^^^^^^^^^ help: to write this more concisely, try: `iterator` error: it is more concise to loop over references to containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:330:18 + --> $DIR/for_loop_fixable.rs:329:18 | LL | for _ in t.into_iter() {} | ^^^^^^^^^^^^^ help: to write this more concisely, try: `&t` error: it is more concise to loop over containers instead of using explicit iteration methods - --> $DIR/for_loop_fixable.rs:332:18 + --> $DIR/for_loop_fixable.rs:331:18 | LL | for _ in r.into_iter() {} | ^^^^^^^^^^^^^ help: to write this more concisely, try: `r` diff --git a/tests/ui/for_loop_unfixable.rs b/tests/ui/for_loop_unfixable.rs index 20a93a222829..179b255e08ca 100644 --- a/tests/ui/for_loop_unfixable.rs +++ b/tests/ui/for_loop_unfixable.rs @@ -12,7 +12,6 @@ clippy::linkedlist, clippy::shadow_unrelated, clippy::unnecessary_mut_passed, - clippy::cognitive_complexity, clippy::similar_names, unused, dead_code diff --git a/tests/ui/for_loop_unfixable.stderr b/tests/ui/for_loop_unfixable.stderr index e88bfffaae6e..1da8e0f3588d 100644 --- a/tests/ui/for_loop_unfixable.stderr +++ b/tests/ui/for_loop_unfixable.stderr @@ -1,5 +1,5 @@ error[E0425]: cannot find function `f` in this scope - --> $DIR/for_loop_unfixable.rs:37:12 + --> $DIR/for_loop_unfixable.rs:36:12 | LL | if f(&vec[i], &vec[i]) { | ^ help: a local variable with a similar name exists: `i` diff --git a/tests/ui/if_same_then_else2.rs b/tests/ui/if_same_then_else2.rs index cbec56324dca..3cc21809264f 100644 --- a/tests/ui/if_same_then_else2.rs +++ b/tests/ui/if_same_then_else2.rs @@ -1,7 +1,6 @@ #![warn(clippy::if_same_then_else)] #![allow( clippy::blacklisted_name, - clippy::cognitive_complexity, clippy::collapsible_if, clippy::ifs_same_cond, clippy::needless_return diff --git a/tests/ui/if_same_then_else2.stderr b/tests/ui/if_same_then_else2.stderr index da2be6c8aa5a..f5d087fe1283 100644 --- a/tests/ui/if_same_then_else2.stderr +++ b/tests/ui/if_same_then_else2.stderr @@ -1,5 +1,5 @@ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:20:12 + --> $DIR/if_same_then_else2.rs:19:12 | LL | } else { | ____________^ @@ -13,7 +13,7 @@ LL | | } | = note: `-D clippy::if-same-then-else` implied by `-D warnings` note: same as this - --> $DIR/if_same_then_else2.rs:11:13 + --> $DIR/if_same_then_else2.rs:10:13 | LL | if true { | _____________^ @@ -26,7 +26,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:34:12 + --> $DIR/if_same_then_else2.rs:33:12 | LL | } else { | ____________^ @@ -36,7 +36,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:32:13 + --> $DIR/if_same_then_else2.rs:31:13 | LL | if true { | _____________^ @@ -45,7 +45,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:41:12 + --> $DIR/if_same_then_else2.rs:40:12 | LL | } else { | ____________^ @@ -55,7 +55,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:39:13 + --> $DIR/if_same_then_else2.rs:38:13 | LL | if true { | _____________^ @@ -64,7 +64,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:91:12 + --> $DIR/if_same_then_else2.rs:90:12 | LL | } else { | ____________^ @@ -74,7 +74,7 @@ LL | | }; | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:89:21 + --> $DIR/if_same_then_else2.rs:88:21 | LL | let _ = if true { | _____________________^ @@ -83,7 +83,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:98:12 + --> $DIR/if_same_then_else2.rs:97:12 | LL | } else { | ____________^ @@ -93,7 +93,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:96:13 + --> $DIR/if_same_then_else2.rs:95:13 | LL | if true { | _____________^ @@ -102,7 +102,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:123:12 + --> $DIR/if_same_then_else2.rs:122:12 | LL | } else { | ____________^ @@ -112,7 +112,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:120:20 + --> $DIR/if_same_then_else2.rs:119:20 | LL | } else if true { | ____________________^ diff --git a/tests/ui/rename.fixed b/tests/ui/rename.fixed index 947914aa123f..13fbb6e2a6ee 100644 --- a/tests/ui/rename.fixed +++ b/tests/ui/rename.fixed @@ -5,7 +5,6 @@ // allow the new lint name here, to test if the new name works #![allow(clippy::module_name_repetitions)] #![allow(clippy::new_without_default)] -#![allow(clippy::cognitive_complexity)] #![allow(clippy::redundant_static_lifetimes)] // warn for the old lint name here, to test if the renaming worked #![warn(clippy::cognitive_complexity)] diff --git a/tests/ui/rename.rs b/tests/ui/rename.rs index e2c8c223fc77..cbd3b1e91666 100644 --- a/tests/ui/rename.rs +++ b/tests/ui/rename.rs @@ -5,7 +5,6 @@ // allow the new lint name here, to test if the new name works #![allow(clippy::module_name_repetitions)] #![allow(clippy::new_without_default)] -#![allow(clippy::cognitive_complexity)] #![allow(clippy::redundant_static_lifetimes)] // warn for the old lint name here, to test if the renaming worked #![warn(clippy::cyclomatic_complexity)] diff --git a/tests/ui/rename.stderr b/tests/ui/rename.stderr index 83c7f26ba5fa..a9e803946041 100644 --- a/tests/ui/rename.stderr +++ b/tests/ui/rename.stderr @@ -1,5 +1,5 @@ error: lint `clippy::cyclomatic_complexity` has been renamed to `clippy::cognitive_complexity` - --> $DIR/rename.rs:11:9 + --> $DIR/rename.rs:10:9 | LL | #![warn(clippy::cyclomatic_complexity)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::cognitive_complexity` @@ -7,25 +7,25 @@ LL | #![warn(clippy::cyclomatic_complexity)] = note: `-D renamed-and-removed-lints` implied by `-D warnings` error: lint `clippy::stutter` has been renamed to `clippy::module_name_repetitions` - --> $DIR/rename.rs:13:8 + --> $DIR/rename.rs:12:8 | LL | #[warn(clippy::stutter)] | ^^^^^^^^^^^^^^^ help: use the new name: `clippy::module_name_repetitions` error: lint `clippy::new_without_default_derive` has been renamed to `clippy::new_without_default` - --> $DIR/rename.rs:16:8 + --> $DIR/rename.rs:15:8 | LL | #[warn(clippy::new_without_default_derive)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::new_without_default` error: lint `clippy::const_static_lifetime` has been renamed to `clippy::redundant_static_lifetimes` - --> $DIR/rename.rs:19:8 + --> $DIR/rename.rs:18:8 | LL | #[warn(clippy::const_static_lifetime)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::redundant_static_lifetimes` error: lint `clippy::cyclomatic_complexity` has been renamed to `clippy::cognitive_complexity` - --> $DIR/rename.rs:11:9 + --> $DIR/rename.rs:10:9 | LL | #![warn(clippy::cyclomatic_complexity)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::cognitive_complexity` diff --git a/tests/ui/while_let_on_iterator.rs b/tests/ui/while_let_on_iterator.rs index 01838ee202ec..84dfc34db150 100644 --- a/tests/ui/while_let_on_iterator.rs +++ b/tests/ui/while_let_on_iterator.rs @@ -1,5 +1,5 @@ #![warn(clippy::while_let_on_iterator)] -#![allow(clippy::never_loop, clippy::cognitive_complexity)] +#![allow(clippy::never_loop)] fn main() { let mut iter = 1..20; From 5f92faec6d0cbaac6c6afa93efc7298de6765afc Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 2 Apr 2020 19:09:30 -0700 Subject: [PATCH 56/58] Downgrade implicit_hasher to pedantic --- clippy_lints/src/lib.rs | 3 +-- clippy_lints/src/types.rs | 2 +- src/lintlist/mod.rs | 2 +- tests/ui/crashes/ice-3717.rs | 2 ++ tests/ui/crashes/ice-3717.stderr | 8 ++++++-- tests/ui/implicit_hasher.rs | 1 + tests/ui/implicit_hasher.stderr | 26 +++++++++++++++----------- tests/ui/mut_key.rs | 2 -- tests/ui/mut_key.stderr | 8 ++++---- 9 files changed, 31 insertions(+), 23 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 2cd22633bc87..e21d619119f0 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1135,6 +1135,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::CAST_POSSIBLE_WRAP), LintId::of(&types::CAST_PRECISION_LOSS), LintId::of(&types::CAST_SIGN_LOSS), + LintId::of(&types::IMPLICIT_HASHER), LintId::of(&types::INVALID_UPCAST_COMPARISONS), LintId::of(&types::LET_UNIT_VALUE), LintId::of(&types::LINKEDLIST), @@ -1384,7 +1385,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::CHAR_LIT_AS_U8), LintId::of(&types::FN_TO_NUMERIC_CAST), LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), - LintId::of(&types::IMPLICIT_HASHER), LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&types::TYPE_COMPLEXITY), LintId::of(&types::UNIT_ARG), @@ -1495,7 +1495,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&try_err::TRY_ERR), LintId::of(&types::FN_TO_NUMERIC_CAST), LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), - LintId::of(&types::IMPLICIT_HASHER), LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME), LintId::of(&write::PRINTLN_EMPTY_STRING), LintId::of(&write::PRINT_LITERAL), diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index e2b16079f8f5..455f71656fb1 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -2170,7 +2170,7 @@ declare_clippy_lint! { /// pub fn foo(map: &mut HashMap) { } /// ``` pub IMPLICIT_HASHER, - style, + pedantic, "missing generalization over different hashers" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index 00add20b7ae8..9af2c76323ef 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -747,7 +747,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "implicit_hasher", - group: "style", + group: "pedantic", desc: "missing generalization over different hashers", deprecation: None, module: "types", diff --git a/tests/ui/crashes/ice-3717.rs b/tests/ui/crashes/ice-3717.rs index 21c48f4749cc..f50714643fd2 100644 --- a/tests/ui/crashes/ice-3717.rs +++ b/tests/ui/crashes/ice-3717.rs @@ -1,3 +1,5 @@ +#![deny(clippy::implicit_hasher)] + use std::collections::HashSet; fn main() {} diff --git a/tests/ui/crashes/ice-3717.stderr b/tests/ui/crashes/ice-3717.stderr index 08c53c399c26..296c95abb96d 100644 --- a/tests/ui/crashes/ice-3717.stderr +++ b/tests/ui/crashes/ice-3717.stderr @@ -1,10 +1,14 @@ error: parameter of type `HashSet` should be generalized over different hashers - --> $DIR/ice-3717.rs:5:21 + --> $DIR/ice-3717.rs:7:21 | LL | pub fn ice_3717(_: &HashSet) { | ^^^^^^^^^^^^^^ | - = note: `-D clippy::implicit-hasher` implied by `-D warnings` +note: the lint level is defined here + --> $DIR/ice-3717.rs:1:9 + | +LL | #![deny(clippy::implicit_hasher)] + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider adding a type parameter | LL | pub fn ice_3717(_: &HashSet) { diff --git a/tests/ui/implicit_hasher.rs b/tests/ui/implicit_hasher.rs index c0ffa6879ce4..fdcc9a33f55f 100644 --- a/tests/ui/implicit_hasher.rs +++ b/tests/ui/implicit_hasher.rs @@ -1,4 +1,5 @@ // aux-build:implicit_hasher_macros.rs +#![deny(clippy::implicit_hasher)] #![allow(unused)] #[macro_use] diff --git a/tests/ui/implicit_hasher.stderr b/tests/ui/implicit_hasher.stderr index 252e9eb5dd8c..2b06d661772d 100644 --- a/tests/ui/implicit_hasher.stderr +++ b/tests/ui/implicit_hasher.stderr @@ -1,10 +1,14 @@ error: impl for `HashMap` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:15:35 + --> $DIR/implicit_hasher.rs:16:35 | LL | impl Foo for HashMap { | ^^^^^^^^^^^^^ | - = note: `-D clippy::implicit-hasher` implied by `-D warnings` +note: the lint level is defined here + --> $DIR/implicit_hasher.rs:2:9 + | +LL | #![deny(clippy::implicit_hasher)] + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider adding a type parameter | LL | impl Foo for HashMap { @@ -15,7 +19,7 @@ LL | (HashMap::default(), HashMap::with_capacity_and_hasher(10, Default: | ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: impl for `HashMap` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:24:36 + --> $DIR/implicit_hasher.rs:25:36 | LL | impl Foo for (HashMap,) { | ^^^^^^^^^^^^^ @@ -30,7 +34,7 @@ LL | ((HashMap::default(),), (HashMap::with_capacity_and_hasher(10, Defa | ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: impl for `HashMap` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:29:19 + --> $DIR/implicit_hasher.rs:30:19 | LL | impl Foo for HashMap { | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -45,7 +49,7 @@ LL | (HashMap::default(), HashMap::with_capacity_and_hasher(10, Default: | ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: impl for `HashSet` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:46:32 + --> $DIR/implicit_hasher.rs:47:32 | LL | impl Foo for HashSet { | ^^^^^^^^^^ @@ -60,7 +64,7 @@ LL | (HashSet::default(), HashSet::with_capacity_and_hasher(10, Default: | ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: impl for `HashSet` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:51:19 + --> $DIR/implicit_hasher.rs:52:19 | LL | impl Foo for HashSet { | ^^^^^^^^^^^^^^^ @@ -75,7 +79,7 @@ LL | (HashSet::default(), HashSet::with_capacity_and_hasher(10, Default: | ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: parameter of type `HashMap` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:68:23 + --> $DIR/implicit_hasher.rs:69:23 | LL | pub fn foo(_map: &mut HashMap, _set: &mut HashSet) {} | ^^^^^^^^^^^^^^^^^ @@ -86,7 +90,7 @@ LL | pub fn foo(_map: &mut HashMap, _s | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^ error: parameter of type `HashSet` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:68:53 + --> $DIR/implicit_hasher.rs:69:53 | LL | pub fn foo(_map: &mut HashMap, _set: &mut HashSet) {} | ^^^^^^^^^^^^ @@ -97,7 +101,7 @@ LL | pub fn foo(_map: &mut HashMap, _set: | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ error: impl for `HashMap` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:72:43 + --> $DIR/implicit_hasher.rs:73:43 | LL | impl Foo for HashMap { | ^^^^^^^^^^^^^ @@ -116,7 +120,7 @@ LL | (HashMap::default(), HashMap::with_capacity_and_hasher(10, | ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: parameter of type `HashMap` should be generalized over different hashers - --> $DIR/implicit_hasher.rs:80:33 + --> $DIR/implicit_hasher.rs:81:33 | LL | pub fn $name(_map: &mut HashMap, _set: &mut HashSet) {} | ^^^^^^^^^^^^^^^^^ @@ -131,7 +135,7 @@ LL | pub fn $name(_map: &mut HashMap $DIR/implicit_hasher.rs:80:63 + --> $DIR/implicit_hasher.rs:81:63 | LL | pub fn $name(_map: &mut HashMap, _set: &mut HashSet) {} | ^^^^^^^^^^^^ diff --git a/tests/ui/mut_key.rs b/tests/ui/mut_key.rs index d45cf8278a80..2d227e6654c3 100644 --- a/tests/ui/mut_key.rs +++ b/tests/ui/mut_key.rs @@ -1,5 +1,3 @@ -#![allow(clippy::implicit_hasher)] - use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; diff --git a/tests/ui/mut_key.stderr b/tests/ui/mut_key.stderr index 5af28f18d3d7..8d6a259c7e38 100644 --- a/tests/ui/mut_key.stderr +++ b/tests/ui/mut_key.stderr @@ -1,5 +1,5 @@ error: mutable key type - --> $DIR/mut_key.rs:29:32 + --> $DIR/mut_key.rs:27:32 | LL | fn should_not_take_this_arg(m: &mut HashMap, _n: usize) -> HashSet { | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,19 +7,19 @@ LL | fn should_not_take_this_arg(m: &mut HashMap, _n: usize) -> Hash = note: `#[deny(clippy::mutable_key_type)]` on by default error: mutable key type - --> $DIR/mut_key.rs:29:72 + --> $DIR/mut_key.rs:27:72 | LL | fn should_not_take_this_arg(m: &mut HashMap, _n: usize) -> HashSet { | ^^^^^^^^^^^^ error: mutable key type - --> $DIR/mut_key.rs:30:5 + --> $DIR/mut_key.rs:28:5 | LL | let _other: HashMap = HashMap::new(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: mutable key type - --> $DIR/mut_key.rs:49:22 + --> $DIR/mut_key.rs:47:22 | LL | fn tuples_bad(_m: &mut HashMap<(Key, U), bool>) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From c2e55341578ae7b8da9a91eb7ae02f805d5b992e Mon Sep 17 00:00:00 2001 From: Rabi Guha Date: Wed, 8 Apr 2020 16:27:58 +0530 Subject: [PATCH 57/58] Check fn header along with decl when suggesting to implement trait When checking for functions that are potential candidates for trait implementations check the function header to make sure modifiers like asyncness, constness and safety match before triggering the lint. Fixes #5413, #4290 --- clippy_lints/src/methods/mod.rs | 84 +++++++++++++++++++-------------- tests/ui/methods.rs | 15 ++++++ tests/ui/methods.stderr | 26 +++++----- 3 files changed, 77 insertions(+), 48 deletions(-) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 124fc1d9878e..3972af1913f1 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -1426,11 +1426,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { then { if cx.access_levels.is_exported(impl_item.hir_id) { // check missing trait implementations - for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS { + for &(method_name, n_args, fn_header, self_kind, out_type, trait_name) in &TRAIT_METHODS { if name == method_name && - sig.decl.inputs.len() == n_args && - out_type.matches(cx, &sig.decl.output) && - self_kind.matches(cx, self_ty, first_arg_ty) { + sig.decl.inputs.len() == n_args && + out_type.matches(cx, &sig.decl.output) && + self_kind.matches(cx, self_ty, first_arg_ty) && + fn_header_equals(*fn_header, sig.header) { span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!( "defining a method called `{}` on this type; consider implementing \ the `{}` trait or choosing a less ambiguous name", name, trait_name)); @@ -3266,38 +3267,45 @@ const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [ (Convention::StartsWith("to_"), &[SelfKind::Ref]), ]; +const FN_HEADER: hir::FnHeader = hir::FnHeader { + unsafety: hir::Unsafety::Normal, + constness: hir::Constness::NotConst, + asyncness: hir::IsAsync::NotAsync, + abi: rustc_target::spec::abi::Abi::Rust, +}; + #[rustfmt::skip] -const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [ - ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"), - ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"), - ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"), - ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"), - ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"), - ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"), - ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"), - ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"), - ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"), - ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"), - ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"), - ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"), - ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"), - ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"), - ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"), - ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"), - ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"), - ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"), - ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"), - ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"), - ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"), - ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"), - ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"), - ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"), - ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"), - ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"), - ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"), - ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"), - ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"), - ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"), +const TRAIT_METHODS: [(&str, usize, &hir::FnHeader, SelfKind, OutType, &str); 30] = [ + ("add", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Add"), + ("as_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"), + ("as_ref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"), + ("bitand", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitAnd"), + ("bitor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitOr"), + ("bitxor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitXor"), + ("borrow", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"), + ("borrow_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"), + ("clone", 1, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::clone::Clone"), + ("cmp", 2, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::cmp::Ord"), + ("default", 0, &FN_HEADER, SelfKind::No, OutType::Any, "std::default::Default"), + ("deref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Deref"), + ("deref_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"), + ("div", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Div"), + ("drop", 1, &FN_HEADER, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"), + ("eq", 2, &FN_HEADER, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"), + ("from_iter", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::iter::FromIterator"), + ("from_str", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::str::FromStr"), + ("hash", 2, &FN_HEADER, SelfKind::Ref, OutType::Unit, "std::hash::Hash"), + ("index", 2, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Index"), + ("index_mut", 2, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"), + ("into_iter", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"), + ("mul", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Mul"), + ("neg", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Neg"), + ("next", 1, &FN_HEADER, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"), + ("not", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Not"), + ("rem", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Rem"), + ("shl", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shl"), + ("shr", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shr"), + ("sub", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Sub"), ]; #[rustfmt::skip] @@ -3510,3 +3518,9 @@ fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: & let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary); span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, &help_msg); } + +fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool { + expected.constness == actual.constness + && expected.unsafety == actual.unsafety + && expected.asyncness == actual.asyncness +} diff --git a/tests/ui/methods.rs b/tests/ui/methods.rs index 2af33b263405..7880cf36415f 100644 --- a/tests/ui/methods.rs +++ b/tests/ui/methods.rs @@ -6,6 +6,7 @@ clippy::blacklisted_name, clippy::default_trait_access, clippy::missing_docs_in_private_items, + clippy::missing_safety_doc, clippy::non_ascii_literal, clippy::new_without_default, clippy::needless_pass_by_value, @@ -83,6 +84,20 @@ impl T { } } +pub struct T1; + +impl T1 { + // Shouldn't trigger lint as it is unsafe. + pub unsafe fn add(self, rhs: T1) -> T1 { + self + } + + // Should not trigger lint since this is an async function. + pub async fn next(&mut self) -> Option { + None + } +} + struct Lt<'a> { foo: &'a u32, } diff --git a/tests/ui/methods.stderr b/tests/ui/methods.stderr index 878e78fdcc5e..01cf487ac148 100644 --- a/tests/ui/methods.stderr +++ b/tests/ui/methods.stderr @@ -1,5 +1,5 @@ error: defining a method called `add` on this type; consider implementing the `std::ops::Add` trait or choosing a less ambiguous name - --> $DIR/methods.rs:38:5 + --> $DIR/methods.rs:39:5 | LL | / pub fn add(self, other: T) -> T { LL | | self @@ -9,7 +9,7 @@ LL | | } = note: `-D clippy::should-implement-trait` implied by `-D warnings` error: methods called `new` usually return `Self` - --> $DIR/methods.rs:154:5 + --> $DIR/methods.rs:169:5 | LL | / fn new() -> i32 { LL | | 0 @@ -19,7 +19,7 @@ LL | | } = note: `-D clippy::new-ret-no-self` implied by `-D warnings` error: called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling `.find(p)` instead. - --> $DIR/methods.rs:173:13 + --> $DIR/methods.rs:188:13 | LL | let _ = v.iter().filter(|&x| *x < 0).next(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -28,7 +28,7 @@ LL | let _ = v.iter().filter(|&x| *x < 0).next(); = note: replace `filter(|&x| *x < 0).next()` with `find(|&x| *x < 0)` error: called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling `.find(p)` instead. - --> $DIR/methods.rs:176:13 + --> $DIR/methods.rs:191:13 | LL | let _ = v.iter().filter(|&x| { | _____________^ @@ -38,7 +38,7 @@ LL | | ).next(); | |___________________________^ error: called `is_some()` after searching an `Iterator` with find. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:193:22 + --> $DIR/methods.rs:208:22 | LL | let _ = v.iter().find(|&x| *x < 0).is_some(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `any(|x| *x < 0)` @@ -46,25 +46,25 @@ LL | let _ = v.iter().find(|&x| *x < 0).is_some(); = note: `-D clippy::search-is-some` implied by `-D warnings` error: called `is_some()` after searching an `Iterator` with find. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:194:20 + --> $DIR/methods.rs:209:20 | LL | let _ = (0..1).find(|x| **y == *x).is_some(); // one dereference less | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `any(|x| **y == x)` error: called `is_some()` after searching an `Iterator` with find. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:195:20 + --> $DIR/methods.rs:210:20 | LL | let _ = (0..1).find(|x| *x == 0).is_some(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `any(|x| x == 0)` error: called `is_some()` after searching an `Iterator` with find. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:196:22 + --> $DIR/methods.rs:211:22 | LL | let _ = v.iter().find(|x| **x == 0).is_some(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `any(|x| *x == 0)` error: called `is_some()` after searching an `Iterator` with find. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:199:13 + --> $DIR/methods.rs:214:13 | LL | let _ = v.iter().find(|&x| { | _____________^ @@ -74,13 +74,13 @@ LL | | ).is_some(); | |______________________________^ error: called `is_some()` after searching an `Iterator` with position. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:205:22 + --> $DIR/methods.rs:220:22 | LL | let _ = v.iter().position(|&x| x < 0).is_some(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `any(|&x| x < 0)` error: called `is_some()` after searching an `Iterator` with position. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:208:13 + --> $DIR/methods.rs:223:13 | LL | let _ = v.iter().position(|&x| { | _____________^ @@ -90,13 +90,13 @@ LL | | ).is_some(); | |______________________________^ error: called `is_some()` after searching an `Iterator` with rposition. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:214:22 + --> $DIR/methods.rs:229:22 | LL | let _ = v.iter().rposition(|&x| x < 0).is_some(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `any(|&x| x < 0)` error: called `is_some()` after searching an `Iterator` with rposition. This is more succinctly expressed by calling `any()`. - --> $DIR/methods.rs:217:13 + --> $DIR/methods.rs:232:13 | LL | let _ = v.iter().rposition(|&x| { | _____________^ From 90fb50fabfcc03f3ee6fd0f7b614638791899c87 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Thu, 9 Apr 2020 19:38:20 +0200 Subject: [PATCH 58/58] Revert "Downgrade new_ret_no_self to pedantic" --- clippy_lints/src/lib.rs | 3 ++- clippy_lints/src/methods/mod.rs | 2 +- src/lintlist/mod.rs | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index b106113c2a98..cb9fcfca8a1c 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1115,7 +1115,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::FIND_MAP), LintId::of(&methods::INEFFICIENT_TO_STRING), LintId::of(&methods::MAP_FLATTEN), - LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OPTION_MAP_UNWRAP_OR), LintId::of(&methods::OPTION_MAP_UNWRAP_OR_ELSE), LintId::of(&methods::RESULT_MAP_UNWRAP_OR_ELSE), @@ -1277,6 +1276,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::ITER_NTH_ZERO), LintId::of(&methods::ITER_SKIP_NEXT), LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC), + LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OK_EXPECT), LintId::of(&methods::OPTION_AND_THEN_SOME), LintId::of(&methods::OPTION_AS_REF_DEREF), @@ -1456,6 +1456,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&methods::ITER_NTH_ZERO), LintId::of(&methods::ITER_SKIP_NEXT), LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC), + LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OK_EXPECT), LintId::of(&methods::OPTION_MAP_OR_NONE), LintId::of(&methods::RESULT_MAP_OR_INTO_OPTION), diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index c539e0360fb2..be9b369112af 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -748,7 +748,7 @@ declare_clippy_lint! { /// } /// ``` pub NEW_RET_NO_SELF, - pedantic, + style, "not returning `Self` in a `new` method" } diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs index b3c77f3f4814..edebaff9f142 100644 --- a/src/lintlist/mod.rs +++ b/src/lintlist/mod.rs @@ -1447,7 +1447,7 @@ pub static ref ALL_LINTS: Vec = vec![ }, Lint { name: "new_ret_no_self", - group: "pedantic", + group: "style", desc: "not returning `Self` in a `new` method", deprecation: None, module: "methods",