From 598df08d88efc816ec97dee9410ebd5a591e5850 Mon Sep 17 00:00:00 2001 From: Jay Kickliter Date: Sun, 16 Sep 2018 16:25:33 -0700 Subject: [PATCH 1/5] Add lint for `mem::replace(.., None)`. Suggest `Option::take()` as an alternative. --- clippy_lints/src/lib.rs | 3 ++ clippy_lints/src/mem_replace.rs | 66 +++++++++++++++++++++++++++++++++ clippy_lints/src/utils/paths.rs | 1 + tests/ui/mem_replace.rs | 9 +++++ tests/ui/mem_replace.stderr | 10 +++++ 5 files changed, 89 insertions(+) create mode 100644 clippy_lints/src/mem_replace.rs create mode 100644 tests/ui/mem_replace.rs create mode 100644 tests/ui/mem_replace.stderr diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index ec00a13c0c6..63204d1c387 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -133,6 +133,7 @@ pub mod map_clone; pub mod map_unit_fn; pub mod matches; pub mod mem_forget; +pub mod mem_replace; pub mod methods; pub mod minmax; pub mod misc; @@ -380,6 +381,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) { reg.register_late_lint_pass(box neg_multiply::NegMultiply); reg.register_early_lint_pass(box unsafe_removed_from_name::UnsafeNameRemoval); reg.register_late_lint_pass(box mem_forget::MemForget); + reg.register_late_lint_pass(box mem_replace::MemReplace); reg.register_late_lint_pass(box arithmetic::Arithmetic::default()); reg.register_late_lint_pass(box assign_ops::AssignOps); reg.register_late_lint_pass(box let_if_seq::LetIfSeq); @@ -748,6 +750,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) { matches::MATCH_REF_PATS, matches::MATCH_WILD_ERR_ARM, matches::SINGLE_MATCH, + mem_replace::MEM_REPLACE_OPTION_WITH_NONE, methods::CHARS_LAST_CMP, methods::GET_UNWRAP, methods::ITER_CLONED_COLLECT, diff --git a/clippy_lints/src/mem_replace.rs b/clippy_lints/src/mem_replace.rs new file mode 100644 index 00000000000..41658cca3c7 --- /dev/null +++ b/clippy_lints/src/mem_replace.rs @@ -0,0 +1,66 @@ +use crate::rustc::hir::{Expr, ExprKind, MutMutable, QPath}; +use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; +use crate::rustc::{declare_tool_lint, lint_array}; +use crate::utils::{match_def_path, match_qpath, match_type, opt_def_id, paths, snippet, span_lint_and_sugg}; +use if_chain::if_chain; + +/// **What it does:** Checks for `mem::replace()` on an `Option` with +/// `None`. +/// +/// **Why is this bad?** `Option` already has the method `take()` for +/// taking its current value (Some(..) or None) and replacing it with +/// `None`. +/// +/// **Known problems:** None. +/// +/// **Example:** +/// ```rust +/// let an_option = Some(0); +/// let replaced = mem::replace(&mut an_option, None); +/// ``` +/// Is better expressed with: +/// ```rust +/// let an_option = Some(0); +/// let taken = an_option.take(); +/// ``` +declare_clippy_lint! { + pub MEM_REPLACE_OPTION_WITH_NONE, + style, + "replacing an `Option` with `None` instead of `take()`" +} + +pub struct MemReplace; + +impl LintPass for MemReplace { + fn get_lints(&self) -> LintArray { + lint_array![MEM_REPLACE_OPTION_WITH_NONE] + } +} + +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace { + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { + if_chain! { + if let ExprKind::Call(ref func, ref func_args) = expr.node; + if func_args.len() == 2; + if let ExprKind::Path(ref func_qpath) = func.node; + if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id)); + if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE); + if let ExprKind::AddrOf(MutMutable, ref replaced) = func_args[0].node; + if match_type(cx, cx.tables.expr_ty(replaced), &paths::OPTION); + if let ExprKind::Path(ref replacement_qpath) = func_args[1].node; + if match_qpath(replacement_qpath, &paths::OPTION_NONE); + if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node; + then { + let sugg = format!("{}.take()", snippet(cx, replaced_path.span, "")); + span_lint_and_sugg( + cx, + MEM_REPLACE_OPTION_WITH_NONE, + expr.span, + "replacing an `Option` with `None`", + "consider `Option::take()` instead", + sugg + ); + } + } + } +} diff --git a/clippy_lints/src/utils/paths.rs b/clippy_lints/src/utils/paths.rs index 30475da7023..eb28cc7e179 100644 --- a/clippy_lints/src/utils/paths.rs +++ b/clippy_lints/src/utils/paths.rs @@ -47,6 +47,7 @@ pub const LINKED_LIST: [&str; 4] = ["alloc", "collections", "linked_list", "Link pub const LINT: [&str; 3] = ["rustc", "lint", "Lint"]; pub const LINT_ARRAY: [&str; 3] = ["rustc", "lint", "LintArray"]; pub const MEM_FORGET: [&str; 3] = ["core", "mem", "forget"]; +pub const MEM_REPLACE: [&str; 3] = ["core", "mem", "replace"]; pub const MEM_UNINIT: [&str; 3] = ["core", "mem", "uninitialized"]; pub const MEM_ZEROED: [&str; 3] = ["core", "mem", "zeroed"]; pub const MUTEX: [&str; 4] = ["std", "sync", "mutex", "Mutex"]; diff --git a/tests/ui/mem_replace.rs b/tests/ui/mem_replace.rs new file mode 100644 index 00000000000..14f586e71bf --- /dev/null +++ b/tests/ui/mem_replace.rs @@ -0,0 +1,9 @@ +#![feature(tool_lints)] +#![warn(clippy::all, clippy::style, clippy::mem_replace_option_with_none)] + +use std::mem; + +fn main() { + let mut an_option = Some(1); + let _ = mem::replace(&mut an_option, None); +} diff --git a/tests/ui/mem_replace.stderr b/tests/ui/mem_replace.stderr new file mode 100644 index 00000000000..1ce9fc38093 --- /dev/null +++ b/tests/ui/mem_replace.stderr @@ -0,0 +1,10 @@ +error: replacing an `Option` with `None` + --> $DIR/mem_replace.rs:8:13 + | +8 | let _ = mem::replace(&mut an_option, None); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider `Option::take()` instead: `an_option.take()` + | + = note: `-D clippy::mem-replace-option-with-none` implied by `-D warnings` + +error: aborting due to previous error + From 1b6d739ce3826b4990c6899b89a362ee0faf676d Mon Sep 17 00:00:00 2001 From: Jay Kickliter Date: Tue, 18 Sep 2018 10:21:49 -0700 Subject: [PATCH 2/5] mem_replace: make examples compilable. --- clippy_lints/src/mem_replace.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/mem_replace.rs b/clippy_lints/src/mem_replace.rs index 41658cca3c7..f516fc5085c 100644 --- a/clippy_lints/src/mem_replace.rs +++ b/clippy_lints/src/mem_replace.rs @@ -15,12 +15,12 @@ use if_chain::if_chain; /// /// **Example:** /// ```rust -/// let an_option = Some(0); +/// let mut an_option = Some(0); /// let replaced = mem::replace(&mut an_option, None); /// ``` /// Is better expressed with: /// ```rust -/// let an_option = Some(0); +/// let mut an_option = Some(0); /// let taken = an_option.take(); /// ``` declare_clippy_lint! { From 12c7bc1e585d0be7f9fd191dc084cd30ee344385 Mon Sep 17 00:00:00 2001 From: Jay Kickliter Date: Tue, 18 Sep 2018 10:28:58 -0700 Subject: [PATCH 3/5] mem_replace: apply update_lints tool. --- CHANGELOG.md | 1 + README.md | 2 +- clippy_lints/src/lib.rs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82596edf30e..a7b4c5921e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -744,6 +744,7 @@ All notable changes to this project will be documented in this file. [`match_wild_err_arm`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#match_wild_err_arm [`maybe_infinite_iter`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#maybe_infinite_iter [`mem_forget`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#mem_forget +[`mem_replace_option_with_none`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#mem_replace_option_with_none [`min_max`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#min_max [`misaligned_transmute`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#misaligned_transmute [`misrefactored_assign_op`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#misrefactored_assign_op diff --git a/README.md b/README.md index 3d994b4ef85..0d18dcf6cb2 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ We are currently in the process of discussing Clippy 1.0 via the RFC process in A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code. -[There are 276 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html) +[There are 277 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html) We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you: diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 63204d1c387..90094429a36 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -593,6 +593,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) { matches::MATCH_REF_PATS, matches::MATCH_WILD_ERR_ARM, matches::SINGLE_MATCH, + mem_replace::MEM_REPLACE_OPTION_WITH_NONE, methods::CHARS_LAST_CMP, methods::CHARS_NEXT_CMP, methods::CLONE_DOUBLE_REF, From 2f53aaa5bd663fb572f349ca31ad56c32e222977 Mon Sep 17 00:00:00 2001 From: Jay Kickliter Date: Tue, 18 Sep 2018 16:54:01 -0700 Subject: [PATCH 4/5] mem_replace: match on path. --- clippy_lints/src/mem_replace.rs | 29 +++++++++++++++++++++++------ tests/ui/mem_replace.rs | 2 ++ tests/ui/mem_replace.stderr | 8 +++++++- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/clippy_lints/src/mem_replace.rs b/clippy_lints/src/mem_replace.rs index f516fc5085c..22460ccb5ea 100644 --- a/clippy_lints/src/mem_replace.rs +++ b/clippy_lints/src/mem_replace.rs @@ -1,7 +1,7 @@ use crate::rustc::hir::{Expr, ExprKind, MutMutable, QPath}; use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; use crate::rustc::{declare_tool_lint, lint_array}; -use crate::utils::{match_def_path, match_qpath, match_type, opt_def_id, paths, snippet, span_lint_and_sugg}; +use crate::utils::{match_def_path, match_qpath, opt_def_id, paths, snippet, span_lint_and_sugg}; use if_chain::if_chain; /// **What it does:** Checks for `mem::replace()` on an `Option` with @@ -40,25 +40,42 @@ impl LintPass for MemReplace { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { if_chain! { + // Check that `expr` is a call to `mem::replace()` if let ExprKind::Call(ref func, ref func_args) = expr.node; if func_args.len() == 2; if let ExprKind::Path(ref func_qpath) = func.node; if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id)); if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE); - if let ExprKind::AddrOf(MutMutable, ref replaced) = func_args[0].node; - if match_type(cx, cx.tables.expr_ty(replaced), &paths::OPTION); + + // Check that second argument is `Option::None` if let ExprKind::Path(ref replacement_qpath) = func_args[1].node; if match_qpath(replacement_qpath, &paths::OPTION_NONE); - if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node; + then { - let sugg = format!("{}.take()", snippet(cx, replaced_path.span, "")); + // Since this is a late pass (already type-checked), + // and we already know that the second argument is an + // `Option`, we do not need to check if the first + // argument's type. All that's left is to get + // replacee's path. + let replaced_path = match func_args[0].node { + ExprKind::AddrOf(MutMutable, ref replaced) => { + if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node { + replaced_path + } else { + return + } + }, + ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path, + _ => return, + }; + span_lint_and_sugg( cx, MEM_REPLACE_OPTION_WITH_NONE, expr.span, "replacing an `Option` with `None`", "consider `Option::take()` instead", - sugg + format!("{}.take()", snippet(cx, replaced_path.span, "")) ); } } diff --git a/tests/ui/mem_replace.rs b/tests/ui/mem_replace.rs index 14f586e71bf..62df42ef2d2 100644 --- a/tests/ui/mem_replace.rs +++ b/tests/ui/mem_replace.rs @@ -6,4 +6,6 @@ use std::mem; fn main() { let mut an_option = Some(1); let _ = mem::replace(&mut an_option, None); + let an_option = &mut Some(1); + let _ = mem::replace(an_option, None); } diff --git a/tests/ui/mem_replace.stderr b/tests/ui/mem_replace.stderr index 1ce9fc38093..8385fa3cb3c 100644 --- a/tests/ui/mem_replace.stderr +++ b/tests/ui/mem_replace.stderr @@ -6,5 +6,11 @@ error: replacing an `Option` with `None` | = note: `-D clippy::mem-replace-option-with-none` implied by `-D warnings` -error: aborting due to previous error +error: replacing an `Option` with `None` + --> $DIR/mem_replace.rs:10:13 + | +10 | let _ = mem::replace(an_option, None); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider `Option::take()` instead: `an_option.take()` + +error: aborting due to 2 previous errors From 79cda3bb1ef7f4261bf0fb18bbb141127d31c5a5 Mon Sep 17 00:00:00 2001 From: Jay Kickliter Date: Wed, 19 Sep 2018 14:54:38 -0700 Subject: [PATCH 5/5] mem_replace: fix grammar. --- clippy_lints/src/mem_replace.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/mem_replace.rs b/clippy_lints/src/mem_replace.rs index 22460ccb5ea..fd22e3afe80 100644 --- a/clippy_lints/src/mem_replace.rs +++ b/clippy_lints/src/mem_replace.rs @@ -54,7 +54,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace { then { // Since this is a late pass (already type-checked), // and we already know that the second argument is an - // `Option`, we do not need to check if the first + // `Option`, we do not need to check the first // argument's type. All that's left is to get // replacee's path. let replaced_path = match func_args[0].node {