]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unit_types/unit_cmp.rs
Rollup merge of #102720 - lyming2007:issue-102397-fix, r=compiler-errors
[rust.git] / src / tools / clippy / clippy_lints / src / unit_types / unit_cmp.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::macros::{find_assert_eq_args, root_macro_call_first_node};
3 use rustc_hir::{BinOpKind, Expr, ExprKind};
4 use rustc_lint::LateContext;
5
6 use super::UNIT_CMP;
7
8 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) {
9     if expr.span.from_expansion() {
10         if let Some(macro_call) = root_macro_call_first_node(cx, expr) {
11             let macro_name = cx.tcx.item_name(macro_call.def_id);
12             let result = match macro_name.as_str() {
13                 "assert_eq" | "debug_assert_eq" => "succeed",
14                 "assert_ne" | "debug_assert_ne" => "fail",
15                 _ => return,
16             };
17             let Some ((left, _, _)) = find_assert_eq_args(cx, expr, macro_call.expn) else { return };
18             if !cx.typeck_results().expr_ty(left).is_unit() {
19                 return;
20             }
21             span_lint(
22                 cx,
23                 UNIT_CMP,
24                 macro_call.span,
25                 &format!("`{macro_name}` of unit values detected. This will always {result}"),
26             );
27         }
28         return;
29     }
30
31     if let ExprKind::Binary(ref cmp, left, _) = expr.kind {
32         let op = cmp.node;
33         if op.is_comparison() && cx.typeck_results().expr_ty(left).is_unit() {
34             let result = match op {
35                 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
36                 _ => "false",
37             };
38             span_lint(
39                 cx,
40                 UNIT_CMP,
41                 expr.span,
42                 &format!(
43                     "{}-comparison of unit values detected. This will always be {result}",
44                     op.as_str()
45                 ),
46             );
47         }
48     }
49 }