Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Identical arguments on assert macro family #6167

Merged
merged 6 commits into from
Oct 19, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions clippy_lints/src/eq_op.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::utils::{
eq_expr_value, implements_trait, in_macro, is_copy, multispan_sugg, snippet, span_lint, span_lint_and_then,
eq_expr_value, higher, implements_trait, in_macro, is_copy, is_expn_of, multispan_sugg, snippet, span_lint,
span_lint_and_then,
};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::{BinOp, BinOpKind, BorrowKind, Expr, ExprKind};
use rustc_hir::{BinOp, BinOpKind, BorrowKind, Expr, ExprKind, StmtKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};

Expand All @@ -23,6 +25,12 @@ declare_clippy_lint! {
/// # let x = 1;
/// if x + 1 == x + 1 {}
/// ```
/// or
/// ```rust
/// # let a = 3;
/// # let b = 4;
/// assert_eq!(a, a);
/// ```
pub EQ_OP,
correctness,
"equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
Expand Down Expand Up @@ -52,9 +60,34 @@ declare_clippy_lint! {

declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);

const ASSERT_MACRO_NAMES: [&str; 4] = ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne"];

impl<'tcx> LateLintPass<'tcx> for EqOp {
#[allow(clippy::similar_names, clippy::too_many_lines)]
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
if let ExprKind::Block(ref block, _) = e.kind {
for stmt in block.stmts {
for amn in &ASSERT_MACRO_NAMES {
if_chain! {
if is_expn_of(stmt.span, amn).is_some();
if let StmtKind::Semi(ref matchexpr) = stmt.kind;
ebroto marked this conversation as resolved.
Show resolved Hide resolved
if let Some(macro_args) = higher::extract_assert_macro_args(matchexpr);
if macro_args.len() == 2;
let (lhs, rhs) = (macro_args[0], macro_args[1]);
if eq_expr_value(cx, lhs, rhs);

then {
span_lint(
cx,
EQ_OP,
lhs.span.to(rhs.span),
&format!("identical args used in this `{}!` macro call", amn),
);
}
}
}
}
}
if let ExprKind::Binary(op, ref left, ref right) = e.kind {
if e.span.from_expansion() {
return;
Expand Down
66 changes: 11 additions & 55 deletions clippy_lints/src/mutable_debug_assertion.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::utils::{is_direct_expn_of, span_lint};
use if_chain::if_chain;
use crate::utils::{higher, is_direct_expn_of, span_lint};
use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc_hir::{BorrowKind, Expr, ExprKind, MatchSource, Mutability, StmtKind, UnOp};
use rustc_hir::{BorrowKind, Expr, ExprKind, MatchSource, Mutability};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_middle::ty;
Expand Down Expand Up @@ -39,66 +38,23 @@ impl<'tcx> LateLintPass<'tcx> for DebugAssertWithMutCall {
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
for dmn in &DEBUG_MACRO_NAMES {
if is_direct_expn_of(e.span, dmn).is_some() {
if let Some(span) = extract_call(cx, e) {
span_lint(
cx,
DEBUG_ASSERT_WITH_MUT_CALL,
span,
&format!("do not call a function with mutable arguments inside of `{}!`", dmn),
);
}
}
}
}
}

//HACK(hellow554): remove this when #4694 is implemented
fn extract_call<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<Span> {
if_chain! {
if let ExprKind::Block(ref block, _) = e.kind;
if block.stmts.len() == 1;
if let StmtKind::Semi(ref matchexpr) = block.stmts[0].kind;
then {
// debug_assert
if_chain! {
if let ExprKind::Match(ref ifclause, _, _) = matchexpr.kind;
if let ExprKind::DropTemps(ref droptmp) = ifclause.kind;
if let ExprKind::Unary(UnOp::UnNot, ref condition) = droptmp.kind;
then {
let mut visitor = MutArgVisitor::new(cx);
visitor.visit_expr(condition);
return visitor.expr_span();
}
}

// debug_assert_{eq,ne}
if_chain! {
if let ExprKind::Block(ref matchblock, _) = matchexpr.kind;
if let Some(ref matchheader) = matchblock.expr;
if let ExprKind::Match(ref headerexpr, _, _) = matchheader.kind;
if let ExprKind::Tup(ref conditions) = headerexpr.kind;
if conditions.len() == 2;
then {
if let ExprKind::AddrOf(BorrowKind::Ref, _, ref lhs) = conditions[0].kind {
if let Some(macro_args) = higher::extract_assert_macro_args(e) {
for arg in macro_args {
let mut visitor = MutArgVisitor::new(cx);
visitor.visit_expr(lhs);
visitor.visit_expr(arg);
if let Some(span) = visitor.expr_span() {
return Some(span);
}
}
if let ExprKind::AddrOf(BorrowKind::Ref, _, ref rhs) = conditions[1].kind {
let mut visitor = MutArgVisitor::new(cx);
visitor.visit_expr(rhs);
if let Some(span) = visitor.expr_span() {
return Some(span);
span_lint(
cx,
DEBUG_ASSERT_WITH_MUT_CALL,
span,
&format!("do not call a function with mutable arguments inside of `{}!`", dmn),
);
}
}
}
}
}
}

None
}

struct MutArgVisitor<'a, 'tcx> {
Expand Down
54 changes: 54 additions & 0 deletions clippy_lints/src/utils/higher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::utils::{is_expn_of, match_def_path, paths};
use if_chain::if_chain;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_hir::{BorrowKind, Expr, ExprKind, StmtKind, UnOp};
use rustc_lint::LateContext;

/// Converts a hir binary operator to the corresponding `ast` type.
Expand Down Expand Up @@ -241,3 +242,56 @@ pub fn vec_macro<'e>(cx: &LateContext<'_>, expr: &'e hir::Expr<'_>) -> Option<Ve

None
}

/// Extract args from an assert-like macro.
/// Currently working with:
/// - `assert!`, `assert_eq!` and `assert_ne!`
/// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
/// For example:
/// `assert!(expr)` will return Some([expr])
/// `debug_assert_eq!(a, b)` will return Some([a, b])
pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
/// Try to match the AST for a pattern that contains a match, for example when two args are
/// compared
fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
if_chain! {
if let ExprKind::Match(ref headerexpr, _, _) = &matchblock_expr.kind;
if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
then {
return Some(vec![lhs, rhs]);
}
}
None
}

if let ExprKind::Block(ref block, _) = e.kind {
if block.stmts.len() == 1 {
if let StmtKind::Semi(ref matchexpr) = block.stmts[0].kind {
// macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
if_chain! {
if let ExprKind::Match(ref ifclause, _, _) = matchexpr.kind;
if let ExprKind::DropTemps(ref droptmp) = ifclause.kind;
if let ExprKind::Unary(UnOp::UnNot, condition) = droptmp.kind;
then {
return Some(vec![condition]);
}
}

// debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
if_chain! {
if let ExprKind::Block(ref matchblock,_) = matchexpr.kind;
if let Some(ref matchblock_expr) = matchblock.expr;
then {
return ast_matchblock(matchblock_expr);
}
}
}
} else if let Some(matchblock_expr) = block.expr {
// macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
return ast_matchblock(&matchblock_expr);
}
}
None
}
1 change: 1 addition & 0 deletions tests/ui/auxiliary/proc_macro_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#![crate_type = "proc-macro"]
#![feature(repr128, proc_macro_quote)]
#![allow(clippy::eq_op)]

extern crate proc_macro;

Expand Down
2 changes: 1 addition & 1 deletion tests/ui/double_parens.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![warn(clippy::double_parens)]
#![allow(dead_code)]
#![allow(dead_code, clippy::eq_op)]
#![feature(custom_inner_attributes)]
#![rustfmt::skip]

Expand Down
57 changes: 57 additions & 0 deletions tests/ui/eq_op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ fn main() {
const B: u32 = 10;
const C: u32 = A / B; // ok, different named constants
const D: u32 = A / A;

check_assert_identical_args();
}

#[rustfmt::skip]
Expand All @@ -85,3 +87,58 @@ fn check_ignore_macro() {
// checks if the lint ignores macros with `!` operator
!bool_macro!(1) && !bool_macro!("");
}

macro_rules! assert_in_macro_def {
() => {
let a = 42;
assert_eq!(a, a);
assert_ne!(a, a);
debug_assert_eq!(a, a);
debug_assert_ne!(a, a);
};
}

// lint identical args in assert-like macro invocations (see #3574)
fn check_assert_identical_args() {
// lint also in macro definition
assert_in_macro_def!();

let a = 1;
let b = 2;

// lint identical args in `assert_eq!`
assert_eq!(a, a);
assert_eq!(a + 1, a + 1);
// ok
assert_eq!(a, b);
assert_eq!(a, a + 1);
assert_eq!(a + 1, b + 1);

// lint identical args in `assert_ne!`
assert_ne!(a, a);
assert_ne!(a + 1, a + 1);
// ok
assert_ne!(a, b);
assert_ne!(a, a + 1);
assert_ne!(a + 1, b + 1);

// lint identical args in `debug_assert_eq!`
debug_assert_eq!(a, a);
debug_assert_eq!(a + 1, a + 1);
// ok
debug_assert_eq!(a, b);
debug_assert_eq!(a, a + 1);
debug_assert_eq!(a + 1, b + 1);

// lint identical args in `debug_assert_ne!`
debug_assert_ne!(a, a);
debug_assert_ne!(a + 1, a + 1);
// ok
debug_assert_ne!(a, b);
debug_assert_ne!(a, a + 1);
debug_assert_ne!(a + 1, b + 1);

let my_vec = vec![1; 5];
let mut my_iter = my_vec.iter();
assert_ne!(my_iter.next(), my_iter.next());
}
95 changes: 94 additions & 1 deletion tests/ui/eq_op.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,98 @@ error: equal expressions as operands to `/`
LL | const D: u32 = A / A;
| ^^^^^

error: aborting due to 27 previous errors
error: identical args used in this `assert_eq!` macro call
--> $DIR/eq_op.rs:94:20
|
LL | assert_eq!(a, a);
| ^^^^
...
LL | assert_in_macro_def!();
| ----------------------- in this macro invocation
|
= note: `#[deny(clippy::eq_op)]` on by default
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: identical args used in this `assert_ne!` macro call
--> $DIR/eq_op.rs:95:20
|
LL | assert_ne!(a, a);
| ^^^^
...
LL | assert_in_macro_def!();
| ----------------------- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: identical args used in this `assert_eq!` macro call
--> $DIR/eq_op.rs:110:16
|
LL | assert_eq!(a, a);
| ^^^^

error: identical args used in this `assert_eq!` macro call
--> $DIR/eq_op.rs:111:16
|
LL | assert_eq!(a + 1, a + 1);
| ^^^^^^^^^^^^

error: identical args used in this `assert_ne!` macro call
--> $DIR/eq_op.rs:118:16
|
LL | assert_ne!(a, a);
| ^^^^

error: identical args used in this `assert_ne!` macro call
--> $DIR/eq_op.rs:119:16
|
LL | assert_ne!(a + 1, a + 1);
| ^^^^^^^^^^^^

error: identical args used in this `debug_assert_eq!` macro call
--> $DIR/eq_op.rs:96:26
|
LL | debug_assert_eq!(a, a);
| ^^^^
...
LL | assert_in_macro_def!();
| ----------------------- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: identical args used in this `debug_assert_ne!` macro call
--> $DIR/eq_op.rs:97:26
|
LL | debug_assert_ne!(a, a);
| ^^^^
...
LL | assert_in_macro_def!();
| ----------------------- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: identical args used in this `debug_assert_eq!` macro call
--> $DIR/eq_op.rs:126:22
|
LL | debug_assert_eq!(a, a);
| ^^^^

error: identical args used in this `debug_assert_eq!` macro call
--> $DIR/eq_op.rs:127:22
|
LL | debug_assert_eq!(a + 1, a + 1);
| ^^^^^^^^^^^^

error: identical args used in this `debug_assert_ne!` macro call
--> $DIR/eq_op.rs:134:22
|
LL | debug_assert_ne!(a, a);
| ^^^^

error: identical args used in this `debug_assert_ne!` macro call
--> $DIR/eq_op.rs:135:22
|
LL | debug_assert_ne!(a + 1, a + 1);
| ^^^^^^^^^^^^

error: aborting due to 39 previous errors

Loading