Skip to content

Commit

Permalink
Better handle method/function calls
Browse files Browse the repository at this point in the history
  • Loading branch information
Serial-ATA committed Aug 16, 2022
1 parent 5986708 commit 7b62d1f
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 39 deletions.
2 changes: 1 addition & 1 deletion clippy_lints/src/lib.register_suspicious.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec!
LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF),
LintId::of(write::POSITIONAL_NAMED_FORMAT_PARAMETERS),
LintId::of(unused_peekable::UNUSED_PEEKABLE),
LintId::of(write::POSITIONAL_NAMED_FORMAT_PARAMETERS),
])
94 changes: 58 additions & 36 deletions clippy_lints/src/unused_peekable.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::ty::{match_type, peel_mid_ty_refs_is_mutable};
use clippy_utils::{fn_def_id, path_to_local_id, paths, peel_ref_operators};
use clippy_utils::{fn_def_id, is_trait_method, path_to_local_id, paths, peel_ref_operators};
use rustc_ast::Mutability;
use rustc_hir::intravisit::{walk_expr, Visitor};
use rustc_hir::lang_items::LangItem;
use rustc_hir::{Block, Expr, ExprKind, HirId, Local, Node, PatKind, PathSegment, StmtKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::Ty;
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::sym;

declare_clippy_lint! {
/// ### What it does
Expand Down Expand Up @@ -70,7 +70,9 @@ impl<'tcx> LateLintPass<'tcx> for UnusedPeekable {
&& let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
&& match_type(cx, ty, &paths::PEEKABLE)
{
let mut vis = PeekableVisitor::new(cx, local.pat.hir_id);
self.visited.push(local.pat.hir_id);

let mut vis = PeekableVisitor::new(cx, local.pat.hir_id, &mut self.visited);

if idx + 1 == block.stmts.len() && block.expr.is_none() {
return;
Expand Down Expand Up @@ -103,20 +105,26 @@ struct PeekableVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
expected_hir_id: HirId,
found_peek_call: bool,
visited: &'a mut Vec<HirId>,
}

impl<'a, 'tcx> PeekableVisitor<'a, 'tcx> {
fn new(cx: &'a LateContext<'tcx>, expected_hir_id: HirId) -> Self {
fn new(cx: &'a LateContext<'tcx>, expected_hir_id: HirId, visited: &'a mut Vec<HirId>) -> Self {
Self {
cx,
expected_hir_id,
found_peek_call: false,
visited,
}
}
}

impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> {
fn visit_expr(&mut self, ex: &'_ Expr<'_>) {
if self.found_peek_call {
return;
}

if path_to_local_id(ex, self.expected_hir_id) {
for (_, node) in self.cx.tcx.hir().parent_iter(ex.hir_id) {
match node {
Expand All @@ -138,54 +146,57 @@ impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> {
return;
}

for arg in args.iter().map(|arg| peel_ref_operators(self.cx, arg)) {
if let ExprKind::Path(_) = arg.kind
&& let Some(ty) = self
.cx
.typeck_results()
.expr_ty_opt(arg)
.map(Ty::peel_refs)
&& match_type(self.cx, ty, &paths::PEEKABLE)
{
self.found_peek_call = true;
return;
}
if args.iter().any(|arg| {
matches!(arg.kind, ExprKind::Path(_)) && arg_is_mut_peekable(self.cx, arg)
}) {
self.found_peek_call = true;
return;
}
},
// Peekable::peek()
ExprKind::MethodCall(PathSegment { ident: method_name, .. }, [arg, ..], _) => {
let arg = peel_ref_operators(self.cx, arg);
let method_name = method_name.name.as_str();

if (method_name == "peek"
|| method_name == "peek_mut"
|| method_name == "next_if"
|| method_name == "next_if_eq")
&& let ExprKind::Path(_) = arg.kind
&& let Some(ty) = self.cx.typeck_results().expr_ty_opt(arg).map(Ty::peel_refs)
&& match_type(self.cx, ty, &paths::PEEKABLE)
// Catch anything taking a Peekable mutably
ExprKind::MethodCall(
PathSegment { ident: method_name, .. },
[self_arg, remaining_args @ ..],
_,
) => {
// `Peekable` methods
if matches!(
method_name.name.as_str(),
"peek" | "peek_mut" | "next_if" | "next_if_eq"
) && arg_is_mut_peekable(self.cx, self_arg)
{
self.found_peek_call = true;
return;
}

// foo.some_method() excluding Iterator methods
if remaining_args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg))
&& !is_trait_method(self.cx, expr, sym::Iterator)
{
self.found_peek_call = true;
return;
}

return;
},
// Don't bother if moved into a struct
ExprKind::Struct(..) => {
ExprKind::AddrOf(_, Mutability::Mut, _) | ExprKind::Unary(..) | ExprKind::DropTemps(_) => {
},
ExprKind::AddrOf(_, Mutability::Not, _) => return,
_ => {
self.found_peek_call = true;
return;
},
_ => {},
}
},
Node::Local(Local { init: Some(init), .. }) => {
if let Some(ty) = self.cx.typeck_results().expr_ty_opt(init)
&& let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
&& match_type(self.cx, ty, &paths::PEEKABLE)
{
Node::Local(Local {
init: Some(init), pat, ..
}) => {
if arg_is_mut_peekable(self.cx, init) {
self.found_peek_call = true;
return;
}

self.visited.push(pat.hir_id);
break;
},
Node::Stmt(stmt) => match stmt.kind {
Expand All @@ -206,3 +217,14 @@ impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> {
walk_expr(self, ex);
}
}

fn arg_is_mut_peekable(cx: &LateContext<'_>, arg: &Expr<'_>) -> bool {
if let Some(ty) = cx.typeck_results().expr_ty_opt(arg)
&& let (ty, _, Mutability::Mut) = peel_mid_ty_refs_is_mutable(ty)
&& match_type(cx, ty, &paths::PEEKABLE)
{
true
} else {
false
}
}
17 changes: 17 additions & 0 deletions tests/ui/unused_peekable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ fn invalid() {
let mut peekable_using_iterator_method = std::iter::empty::<u32>().peekable();
peekable_using_iterator_method.next();

// Passed by ref to another function
fn takes_ref(_peek: &Peekable<Empty<u32>>) {}
let passed_along_ref = std::iter::empty::<u32>().peekable();
takes_ref(&passed_along_ref);

let mut peekable_in_for_loop = std::iter::empty::<u32>().peekable();
for x in peekable_in_for_loop {}
}
Expand All @@ -43,6 +48,18 @@ fn valid() {
let passed_along = std::iter::empty::<u32>().peekable();
takes_peekable(passed_along);

// Passed to another method
struct PeekableConsumer;
impl PeekableConsumer {
fn consume(&self, _: Peekable<Empty<u32>>) {}
fn consume_mut_ref(&self, _: &mut Peekable<Empty<u32>>) {}
}

let peekable_consumer = PeekableConsumer;
let mut passed_along_to_method = std::iter::empty::<u32>().peekable();
peekable_consumer.consume_mut_ref(&mut passed_along_to_method);
peekable_consumer.consume(passed_along_to_method);

// `peek` called in another block
let mut peekable_in_block = std::iter::empty::<u32>().peekable();
{
Expand Down
12 changes: 10 additions & 2 deletions tests/ui/unused_peekable.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,20 @@ LL | let mut peekable_using_iterator_method = std::iter::empty::<u32>().peek
= help: consider removing the call to `peekable`

error: `peek` never called on `Peekable` iterator
--> $DIR/unused_peekable.rs:35:13
--> $DIR/unused_peekable.rs:37:9
|
LL | let passed_along_ref = std::iter::empty::<u32>().peekable();
| ^^^^^^^^^^^^^^^^
|
= help: consider removing the call to `peekable`

error: `peek` never called on `Peekable` iterator
--> $DIR/unused_peekable.rs:40:13
|
LL | let mut peekable_in_for_loop = std::iter::empty::<u32>().peekable();
| ^^^^^^^^^^^^^^^^^^^^
|
= help: consider removing the call to `peekable`

error: aborting due to 6 previous errors
error: aborting due to 7 previous errors

0 comments on commit 7b62d1f

Please sign in to comment.