From 0893322e5412f78e8214c3ebc8b5b79a8c976f38 Mon Sep 17 00:00:00 2001 From: Jason Newcomb Date: Mon, 28 Nov 2022 23:56:02 -0500 Subject: [PATCH] Don't lint `unnecessary_operation` in mixed macro contexts --- clippy_lints/src/no_effect.rs | 8 ++++++-- tests/ui/unnecessary_operation.fixed | 9 +++++++++ tests/ui/unnecessary_operation.rs | 9 +++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/no_effect.rs b/clippy_lints/src/no_effect.rs index 819646bb678..79c1ae4861e 100644 --- a/clippy_lints/src/no_effect.rs +++ b/clippy_lints/src/no_effect.rs @@ -6,7 +6,8 @@ use clippy_utils::ty::has_drop; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{is_range_literal, BinOpKind, BlockCheckMode, Expr, ExprKind, PatKind, Stmt, StmtKind, UnsafeSource}; -use rustc_lint::{LateContext, LateLintPass}; +use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; use std::ops::Deref; @@ -159,8 +160,11 @@ fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { fn check_unnecessary_operation(cx: &LateContext<'_>, stmt: &Stmt<'_>) { if_chain! { if let StmtKind::Semi(expr) = stmt.kind; + let ctxt = stmt.span.ctxt(); + if expr.span.ctxt() == ctxt; if let Some(reduced) = reduce_expression(cx, expr); - if !&reduced.iter().any(|e| e.span.from_expansion()); + if !in_external_macro(cx.sess(), stmt.span); + if reduced.iter().all(|e| e.span.ctxt() == ctxt); then { if let ExprKind::Index(..) = &expr.kind { let snippet = if let (Some(arr), Some(func)) = diff --git a/tests/ui/unnecessary_operation.fixed b/tests/ui/unnecessary_operation.fixed index bf0ec8deb34..d37163570ab 100644 --- a/tests/ui/unnecessary_operation.fixed +++ b/tests/ui/unnecessary_operation.fixed @@ -76,4 +76,13 @@ fn main() { DropStruct { ..get_drop_struct() }; DropEnum::Tuple(get_number()); DropEnum::Struct { field: get_number() }; + + // Issue #9954 + fn one() -> i8 { + 1 + } + macro_rules! use_expr { + ($($e:expr),*) => {{ $($e;)* }} + } + use_expr!(isize::MIN / -(one() as isize), i8::MIN / -one()); } diff --git a/tests/ui/unnecessary_operation.rs b/tests/ui/unnecessary_operation.rs index 08cb9ab522e..a14fd4bca0e 100644 --- a/tests/ui/unnecessary_operation.rs +++ b/tests/ui/unnecessary_operation.rs @@ -80,4 +80,13 @@ fn main() { DropStruct { ..get_drop_struct() }; DropEnum::Tuple(get_number()); DropEnum::Struct { field: get_number() }; + + // Issue #9954 + fn one() -> i8 { + 1 + } + macro_rules! use_expr { + ($($e:expr),*) => {{ $($e;)* }} + } + use_expr!(isize::MIN / -(one() as isize), i8::MIN / -one()); }