Skip to content

Commit

Permalink
Fix suspicious_map false positives
Browse files Browse the repository at this point in the history
  • Loading branch information
mathstuf authored and camsteffen committed Mar 7, 2021
1 parent e451d6e commit 3f11be7
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 20 deletions.
46 changes: 30 additions & 16 deletions clippy_lints/src/methods/mod.rs
Expand Up @@ -33,12 +33,12 @@ use crate::consts::{constant, Constant};
use crate::utils::eager_or_lazy::is_lazyness_candidate;
use crate::utils::usage::mutated_variables;
use crate::utils::{
contains_return, contains_ty, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment, match_def_path,
match_qpath, match_trait_method, match_type, meets_msrv, method_calls, method_chain_args, path_to_local_id, paths,
remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite,
span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, strip_pat_refs, sugg, walk_ptrs_ty_depth,
SpanlessEq,
contains_return, contains_ty, expr_or_init, get_parent_expr, get_trait_def_id, has_iter_method, higher,
implements_trait, in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
match_def_path, match_qpath, match_trait_method, match_type, meets_msrv, method_calls, method_chain_args,
path_to_local_id, paths, remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability,
snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, strip_pat_refs,
sugg, walk_ptrs_ty_depth, SpanlessEq,
};

declare_clippy_lint! {
Expand Down Expand Up @@ -1709,7 +1709,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
unnecessary_filter_map::lint(cx, expr, arg_lists[0]);
filter_map_identity::check(cx, expr, arg_lists[0], method_spans[0]);
},
["count", "map"] => lint_suspicious_map(cx, expr),
["count", "map"] => lint_suspicious_map(cx, expr, &arg_lists[1][1]),
["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
Expand Down Expand Up @@ -3758,15 +3758,29 @@ fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
}
}

fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
span_lint_and_help(
cx,
SUSPICIOUS_MAP,
expr.span,
"this call to `map()` won't have an effect on the call to `count()`",
None,
"make sure you did not confuse `map` with `filter` or `for_each`",
);
fn lint_suspicious_map<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, map_arg: &'tcx hir::Expr<'tcx>) {
let closure = expr_or_init(cx, map_arg);
if_chain! {
if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(closure.hir_id);
let closure_body = cx.tcx.hir().body(body_id);
if !cx.typeck_results().expr_ty(&closure_body.value).is_unit();
then {
if let Some(map_mutated_vars) = mutated_variables(&closure_body.value, cx) {
// A variable is used mutably inside of the closure. Suppress the lint.
if !map_mutated_vars.is_empty() {
return;
}
}
span_lint_and_help(
cx,
SUSPICIOUS_MAP,
expr.span,
"this call to `map()` won't have an effect on the call to `count()`",
None,
"make sure you did not confuse `map` with `filter` or `for_each`",
);
}
}
}

const OPTION_AS_REF_DEREF_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
Expand Down
62 changes: 59 additions & 3 deletions clippy_utils/src/lib.rs
Expand Up @@ -63,9 +63,9 @@ use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::Node;
use rustc_hir::{
def, Arm, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, GenericArgs, HirId, Impl, ImplItem, ImplItemKind,
Item, ItemKind, MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem, TraitItemKind, TraitRef,
TyKind, Unsafety,
def, Arm, BindingAnnotation, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, GenericArgs, HirId, Impl,
ImplItem, ImplItemKind, Item, ItemKind, MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem,
TraitItemKind, TraitRef, TyKind, Unsafety,
};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::{LateContext, Level, Lint, LintContext};
Expand Down Expand Up @@ -137,6 +137,62 @@ pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
rhs.ctxt() != lhs.ctxt()
}

/// If the given expression is a local binding, find the initializer expression.
/// If that initializer expression is another local binding, find its initializer again.
/// This process repeats as long as possible (but usually no more than once). Initializer
/// expressions with adjustments are ignored. If this is not desired, use [`find_binding_init`]
/// instead.
///
/// Examples:
/// ```ignore
/// let abc = 1;
/// // ^ output
/// let def = abc;
/// dbg!(def)
/// // ^^^ input
///
/// // or...
/// let abc = 1;
/// let def = abc + 2;
/// // ^^^^^^^ output
/// dbg!(def)
/// // ^^^ input
/// ```
pub fn expr_or_init<'tcx>(cx: &LateContext<'tcx>, mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
while let Some(init) = path_to_local(expr)
.and_then(|id| find_binding_init(cx, id))
.filter(|init| cx.typeck_results().expr_adjustments(init).is_empty())
{
expr = init;
}
expr
}

/// Finds the initializer expression for a local binding. Returns `None` if the binding is mutable.
/// By only considering immutable bindings, we guarantee that the returned expression represents the
/// value of the binding wherever it is referenced.
///
/// Example:
/// ```ignore
/// let abc = 1;
/// // ^ output
/// dbg!(abc)
/// // ^^^ input
/// ```
pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
let hir = cx.tcx.hir();
if_chain! {
if let Some(Node::Binding(pat)) = hir.find(hir_id);
if matches!(pat.kind, PatKind::Binding(BindingAnnotation::Unannotated, ..));
let parent = hir.get_parent_node(hir_id);
if let Some(Node::Local(local)) = hir.find(parent);
then {
return local.init;
}
}
None
}

/// Returns `true` if the given `NodeId` is inside a constant context
///
/// # Example
Expand Down
27 changes: 27 additions & 0 deletions tests/ui/suspicious_map.rs
Expand Up @@ -2,4 +2,31 @@

fn main() {
let _ = (0..3).map(|x| x + 2).count();

let f = |x| x + 1;
let _ = (0..3).map(f).count();
}

fn negative() {
// closure with side effects
let mut sum = 0;
let _ = (0..3).map(|x| sum += x).count();

// closure variable with side effects
let ext_closure = |x| sum += x;
let _ = (0..3).map(ext_closure).count();

// closure that returns unit
let _ = (0..3)
.map(|x| {
// do nothing
})
.count();

// external function
let _ = (0..3).map(do_something).count();
}

fn do_something<T>(t: T) -> String {
unimplemented!()
}
10 changes: 9 additions & 1 deletion tests/ui/suspicious_map.stderr
Expand Up @@ -7,5 +7,13 @@ LL | let _ = (0..3).map(|x| x + 2).count();
= note: `-D clippy::suspicious-map` implied by `-D warnings`
= help: make sure you did not confuse `map` with `filter` or `for_each`

error: aborting due to previous error
error: this call to `map()` won't have an effect on the call to `count()`
--> $DIR/suspicious_map.rs:7:13
|
LL | let _ = (0..3).map(f).count();
| ^^^^^^^^^^^^^^^^^^^^^
|
= help: make sure you did not confuse `map` with `filter` or `for_each`

error: aborting due to 2 previous errors

0 comments on commit 3f11be7

Please sign in to comment.