]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/absurd_extreme_comparisons.rs
Remove clippy_utils::consts re-export
[rust.git] / clippy_lints / src / absurd_extreme_comparisons.rs
1 use rustc_hir::{BinOpKind, Expr, ExprKind};
2 use rustc_lint::{LateContext, LateLintPass};
3 use rustc_middle::ty;
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5
6 use clippy_utils::comparisons::{normalize_comparison, Rel};
7 use clippy_utils::consts::{constant, Constant};
8 use clippy_utils::diagnostics::span_lint_and_help;
9 use clippy_utils::source::snippet;
10 use clippy_utils::ty::is_isize_or_usize;
11 use clippy_utils::{clip, int_bits, unsext};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for comparisons where one side of the relation is
15     /// either the minimum or maximum value for its type and warns if it involves a
16     /// case that is always true or always false. Only integer and boolean types are
17     /// checked.
18     ///
19     /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
20     /// that it is possible for `x` to be less than the minimum. Expressions like
21     /// `max < x` are probably mistakes.
22     ///
23     /// **Known problems:** For `usize` the size of the current compile target will
24     /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
25     /// a comparison to detect target pointer width will trigger this lint. One can
26     /// use `mem::sizeof` and compare its value or conditional compilation
27     /// attributes
28     /// like `#[cfg(target_pointer_width = "64")] ..` instead.
29     ///
30     /// **Example:**
31     ///
32     /// ```rust
33     /// let vec: Vec<isize> = Vec::new();
34     /// if vec.len() <= 0 {}
35     /// if 100 > i32::MAX {}
36     /// ```
37     pub ABSURD_EXTREME_COMPARISONS,
38     correctness,
39     "a comparison with a maximum or minimum value that is always true or false"
40 }
41
42 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
43
44 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
45     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
46         if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
47             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
48                 if !expr.span.from_expansion() {
49                     let msg = "this comparison involving the minimum or maximum element for this \
50                                type contains a case that is always true or always false";
51
52                     let conclusion = match result {
53                         AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(),
54                         AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(),
55                         AbsurdComparisonResult::InequalityImpossible => format!(
56                             "the case where the two sides are not equal never occurs, consider using `{} == {}` \
57                              instead",
58                             snippet(cx, lhs.span, "lhs"),
59                             snippet(cx, rhs.span, "rhs")
60                         ),
61                     };
62
63                     let help = format!(
64                         "because `{}` is the {} value for this type, {}",
65                         snippet(cx, culprit.expr.span, "x"),
66                         match culprit.which {
67                             ExtremeType::Minimum => "minimum",
68                             ExtremeType::Maximum => "maximum",
69                         },
70                         conclusion
71                     );
72
73                     span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
74                 }
75             }
76         }
77     }
78 }
79
80 enum ExtremeType {
81     Minimum,
82     Maximum,
83 }
84
85 struct ExtremeExpr<'a> {
86     which: ExtremeType,
87     expr: &'a Expr<'a>,
88 }
89
90 enum AbsurdComparisonResult {
91     AlwaysFalse,
92     AlwaysTrue,
93     InequalityImpossible,
94 }
95
96 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
97     if let ExprKind::Cast(cast_exp, _) = expr.kind {
98         let precast_ty = cx.typeck_results().expr_ty(cast_exp);
99         let cast_ty = cx.typeck_results().expr_ty(expr);
100
101         return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
102     }
103
104     false
105 }
106
107 fn detect_absurd_comparison<'tcx>(
108     cx: &LateContext<'tcx>,
109     op: BinOpKind,
110     lhs: &'tcx Expr<'_>,
111     rhs: &'tcx Expr<'_>,
112 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
113     use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
114     use ExtremeType::{Maximum, Minimum};
115     // absurd comparison only makes sense on primitive types
116     // primitive types don't implement comparison operators with each other
117     if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
118         return None;
119     }
120
121     // comparisons between fix sized types and target sized types are considered unanalyzable
122     if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
123         return None;
124     }
125
126     let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
127
128     let lx = detect_extreme_expr(cx, normalized_lhs);
129     let rx = detect_extreme_expr(cx, normalized_rhs);
130
131     Some(match rel {
132         Rel::Lt => {
133             match (lx, rx) {
134                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
135                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
136                 _ => return None,
137             }
138         },
139         Rel::Le => {
140             match (lx, rx) {
141                 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
142                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
143                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
144                 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
145                 _ => return None,
146             }
147         },
148         Rel::Ne | Rel::Eq => return None,
149     })
150 }
151
152 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
153     let ty = cx.typeck_results().expr_ty(expr);
154
155     let cv = constant(cx, cx.typeck_results(), expr)?.0;
156
157     let which = match (ty.kind(), cv) {
158         (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum,
159         (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
160             ExtremeType::Minimum
161         },
162
163         (&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum,
164         (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
165             ExtremeType::Maximum
166         },
167         (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum,
168
169         _ => return None,
170     };
171     Some(ExtremeExpr { which, expr })
172 }