|
1 | 1 | use crate::rustc::hir::{Expr, ExprKind, MutMutable, QPath};
|
2 | 2 | use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
|
3 | 3 | use crate::rustc::{declare_tool_lint, lint_array};
|
4 |
| -use crate::utils::{match_def_path, match_qpath, match_type, opt_def_id, paths, snippet, span_lint_and_sugg}; |
| 4 | +use crate::utils::{match_def_path, match_qpath, opt_def_id, paths, snippet, span_lint_and_sugg}; |
5 | 5 | use if_chain::if_chain;
|
6 | 6 |
|
7 | 7 | /// **What it does:** Checks for `mem::replace()` on an `Option` with
|
@@ -40,25 +40,42 @@ impl LintPass for MemReplace {
|
40 | 40 | impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
|
41 | 41 | fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
|
42 | 42 | if_chain! {
|
| 43 | + // Check that `expr` is a call to `mem::replace()` |
43 | 44 | if let ExprKind::Call(ref func, ref func_args) = expr.node;
|
44 | 45 | if func_args.len() == 2;
|
45 | 46 | if let ExprKind::Path(ref func_qpath) = func.node;
|
46 | 47 | if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
|
47 | 48 | if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE);
|
48 |
| - if let ExprKind::AddrOf(MutMutable, ref replaced) = func_args[0].node; |
49 |
| - if match_type(cx, cx.tables.expr_ty(replaced), &paths::OPTION); |
| 49 | + |
| 50 | + // Check that second argument is `Option::None` |
50 | 51 | if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
|
51 | 52 | if match_qpath(replacement_qpath, &paths::OPTION_NONE);
|
52 |
| - if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node; |
| 53 | + |
53 | 54 | then {
|
54 |
| - let sugg = format!("{}.take()", snippet(cx, replaced_path.span, "")); |
| 55 | + // Since this is a late pass (already type-checked), |
| 56 | + // and we already know that the second argument is an |
| 57 | + // `Option`, we do not need to check if the first |
| 58 | + // argument's type. All that's left is to get |
| 59 | + // replacee's path. |
| 60 | + let replaced_path = match func_args[0].node { |
| 61 | + ExprKind::AddrOf(MutMutable, ref replaced) => { |
| 62 | + if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node { |
| 63 | + replaced_path |
| 64 | + } else { |
| 65 | + return |
| 66 | + } |
| 67 | + }, |
| 68 | + ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path, |
| 69 | + _ => return, |
| 70 | + }; |
| 71 | + |
55 | 72 | span_lint_and_sugg(
|
56 | 73 | cx,
|
57 | 74 | MEM_REPLACE_OPTION_WITH_NONE,
|
58 | 75 | expr.span,
|
59 | 76 | "replacing an `Option` with `None`",
|
60 | 77 | "consider `Option::take()` instead",
|
61 |
| - sugg |
| 78 | + format!("{}.take()", snippet(cx, replaced_path.span, "")) |
62 | 79 | );
|
63 | 80 | }
|
64 | 81 | }
|
|
0 commit comments